��c��RDUCK3 �����=�23�-���f&01���T2`�Z���5T���<d����#EYl�����%pwz����)jq�E��S�I�3Y���  3 L s z �  Z _ j � � �  e � : S z � �   - d y � +BZ|����:Q���-Ui����EMr���?R����8���-p���MW����[n����� 0�M`���7}��o���(��� <a���'ay���� 3Xm����� + E c z � � � !!X!�!�!�!,"g"�"�"#9#�#�#�# $V$e$y$�$�$�$�$�$%D%o%�%�%�%3&C&T&�&�&�& '*'<'w'�'�' (B(y(�(�(�(�(�(�(X)o)�)�)�)*(*J*b*�*�*�*�*$+F+R+a+k+y+�+�+�+�+�+�+�+�+ ,,),N,�,�,�,�,�,A-i-u-�-�-�- .3.G.i.k.�.�.�.�. /D/t/�/�/�/�/�/�/�/ 0$070@0R0Z0�0�0�0�0�0 1"1R1�1�1�1�1�1�1�12282`2d2}22�2�2�2�2(3g3�3�3�3�3�3�3494Y4�4�4 5.5H5q5}5�5�5�5�56<6Z6�6�6$747W7f7�7�7�7888U8a8n8�8�8�899F9u9�9�9�9�9�9+:N:X:�:�:�:�:�:�: ;;-;9;Q;V;s;�;�;�;�;�;�; <A<s<�<�<=!=:=Z=p=�=�=�=�=>Z>l>�>�>�>�>�>�>?4?v?�?�?@@@:@J@n@�@�@�@�@ACAnA�A�A�A�A�AFB�B�BC6C�C�C[D�DE*E7E?ETExE�E�E FJF�F:GIGPG^G�G�G�G�GHMHZHoH�H�H I!IPI}I�I�IJ=JKJTJtJ�J�J�JK)K4K�L�e�}�����V��������G����������.�R�������:�~����������-�P��������9�@�O�\�k��������I�^����7�`�������;��������B�g�����������������������>�a��������e���������R�c�s����� �_�}�����4�O�������'�I�Z�l�r�x�����b�f���� �!�*�=����K�g��������T�q�������-x�'Bq���-=M� Ri�����$;g����"Do��� ����\~���;X��� ! < _ � � �  1 a � � � * 4 T q � � � ) [ � � � �   @ H g p � � � � R�����;[z���"4E~���)H}�������Nl����2m���+r���-h{���Tfz����5`��,N_v���)R|���!Ku���Gq���Ak��� /Sw���+Om�����2O{�� 3 T r � � � �  !-!Z!�!�!�! "8"d"�"�"�"#K#M#_#�#�#�#$5$W$j$�$�$�$%N%�%�%�% &&E&�&�&2'W'�'�'�'�'((H(b(k(�(�(�(�()-)d)�)*-*y*�*�*�*'+8+O+n+�+�+�+�+�+, ,5,�,�,�,�,�, .�.�.�.7/�/�/ 0E0a0�0�0�0"151B1]1v1�1�1�12T2t2�2�2�23K3c3�3�3�3�3�3&484V4{4�4�45.5G5t5�5�5�56/6J6�6�6�6�6757s7�7�7�7�78.8_8�8�8�8�8 9949N9h9z9�9�9�9�9::7:K:a:�:�:8;~;�;�;</<z<�<�<�<N=i=�=�=>*>E>�>�>?R?~?�?�?�?2@c@�@�@�@5AgA�A�ABBdB�B�B�B(CS`S�S�S�ST,TUTwT�T�T�T�T$UHUrU�U�U�UV%V]V�V�V�V WLW�W�W�W�W�WX9XVX�X�X�X�X�X3YAYCYKY`YzY�Y�Y�Y�Y�YZZ%Z8ZaZnZ{Z�Z�Z�Z�Z�Z�Z[2[:[M[W[f[�[�[�[�[�[�[\\*\:\R\�\�\�\�\�\�\]]"]/]?]_]j]v]�]�]�]�]�]�]�]�]�]�]�]^H^P^[^i^s^�^�^�^�^�^__/_7_S_�_�_�_`=`�`�`�`�`0aDasa�a�a�a.bQb�b�b�b�bc6cMcqc�c�c�c d:dGdUd|d�d�d�d�d0e8ede�e�e�e,fLf�f�f�f�f�f�fg gOgyg�g�g�gh.hTh�h�j�j�j�j&k.k6kJkhk�k�k�k�kDl�l�l�l�l�l�l�lmm5mqm�mn/n`n�n�n�no o,o@oyo�o�opSplp�p�p�p�pqq,q�q�qrr&r�r�rs&sEst�t6uLucu�u�u�u�u�u%vAvy$y=yMyay�y�y�ymz�z{�{�{�{7|�|�|�|�|}#}r}�}�}~!~w~�~�~�~�~C��*�U�d�|�Ā`���I�z�ʂނ�A�L���ۃ�� �}�������g�x�ʅ�P�`����� �����m����3�u��������q���,�d���e���ލŽ��5�u����$�2�S�p���� �H�������,�U���� �!�M����Γ �7�U�����ݔ�G�j�n�����/�f�������ۖ�^�������ڗ�5�_���������šs���6�ۣ'�6�D�U�h�v���������ݤ�U���0�U�r���Ҧ�l�§ �Z����<���۩�C�k�������ë��F�|�������ˬ��)�W�~���˭��0�K�x��������#�A�k���̯��.�^�����ذ�J���Ʊ�P���̲ �R���ɳ��� � �2�F�W�\�h�Ӵ�g���ص%�C�a������ �X�������$�C�e���Ƹ� �,�;�]�s�����Թ�� �=�W�r�������ʺغ��)�T�������<�k�ɼ���@�i�����ս���9�c�����Ӿ��%�H�g�������+�K�s�������W�e����������G�`�w�������"�;�v����������������� ���:�[������*�U�������;�^�i�s�������,�h�y������*�y�����?��������F�t�������)�R���������,�U�r��������C�j�������)�B�n��� �Y�z��������y��������.��� ��%�?�o���������3�Q�e����������H�`�������4�_�|����=�����������&�8�I�k����������A�f����������;�c������� �?�u������5�i��� ��9�V�u��������C����������6�e������� ��L��������������S����� �V���������� �=�R�����%�T�x������F����,�v�����������������P�����%�X�|�����������:�I�R����/�`�m��������=�r��������3�C����������d�{����������*�T���%�2�]�������Q�q����6�\�x�������a������r�z����������������V�}��������� �+�`������#�?�Y�u����R���������������1����� �E��������2�T������3������T�����5�����'3N���[���-Dk��^��+AS���'\��� N����<f�� ( C � � � � B t  � � � �   y � � �  ? e � � � & d ~ � � � � :^���7Vg���+q����!Iz����8j����-d���U�1c���[n�>L^m����I��M|��$Sg~��(8E����,I^z����<h���H������. X i z � � �  !%!;!s!�!�!�!""A"`"|"�"�"�"�"##8#O#u#�#�#�#$.$_$�$�$�$�$�$%3%V%�%�%�%�%&^&u&�&�&�&'N'�'�'�'�'(5(R(~(�(�(�(�(�()%)C)p)�)�)�)�)**\*�*�*�*�*�*�*+E+�+�+�+�+,&,n,�,�,-%-I-�-./.D.\.j.�.�.�.//:/U/x/�/040X0o0�0�0�0�01=1u1�1�12C2o2�2�23/3V3t3�3�3�3�34&4G4|4�4�4555f5v5�5�5�5�5�5 6_6k6}6�6�6�6�67$7J7k7r7�7�7�7�78868K8e8z8�8�8J9p9�9�9�9:':;:h:�:�:�:^;�;�;2<K<�<�< ==5=j=�=�=�=>:>�>�>�>�> ?.?U?}?�?�? @3@W@x@�@�@A�A�A�ABB*BFBdB�B�B�B5CKCbC�C�C'DhDyD�D�D�D/E?EoE�E�E3FgF�F�F�F�F�FaG|G�G�G�G�G�GHLH�H�HI=I�I-JNJ�JK�K�K�KL^L�L�LMPMyM�M�M�M�MdN�N�N�N'OhO�OPXPpP�P�P�PQ0QGQ_QtQ�Q�Q�Q�QBRORjRSGS�STT6TVTuT�T�T�T U:U_U�U�U�U(VBV[VtV�V#WBWgW�W�WX3XYX�X�X�X�X�X�X Y$YmY�Y�Y�Y�YZ;ZXZ�Z�Z�Z�Z�Z[/[@[O[�[�[�[�[�[\�\�\ ]]]�]^E^^^�^�^�^_B_|_�_`R`�`aa4ama�a�a$b(b\babvb�b�b�b�b!c�c�c�cd-ddd�d�d�de$e7e�e�e�e�eff2fRfrf�f�f�f�f�f g;g�g�g�g�g h#hDhVh�h�h�h�h=i�i�i�i�ij[jpj�j�j�j�j'kJk�k�kl7lNlkl�l�l�l+m�m�m�mnen�n�no�o�o.pEpep�p�p�p q>qWq�q�q�q�q$rSrer�rs[sos�s�s�s�s t9thtvt�t�t�t0ufu�u�u�u�uCvuv�v�v4w�w�w�w xAx�x�x�x�x�xy:yay�y�y�yz0z_z�z�z�z{{D{U{r{�{�{�{�{|B|c|�|�|4}M}�}�}�}\~�~�����l��������� �<�u�������2�L�`���т �.�=�~�`�6�����0�I��������Ј�������։�:�Z�z�������B�e���������?�R�������Č!�=�_�u�Ս$�^��I�n���ҏ���� ��?�`�u���������4�V�������ґ�,�_�u�����ݒ ��+�G�v���Г���5�[�ߔ �D�r����=�b�����ɖ3���—З?�_�u���٘Y�k�����ݙ�L�u���� �(�F��������͜ ��1�S�~�������5�B����v���ɟ� �{�ɠ`������L�\���Ԣ��!�?����!�x����2�{�� �G����$�E����;�����W����/�������6����&�)�i���j������$�Z����������z�c�ֲ6���г �q�δO�׵>�U�k���˶�� �R���·!�G�k������.�O�������/�z���պ��f�����I�W�f����$���������H�k����>�z�������]���������&�t�����3�s��������F��������4�E������6�h������8�������������������6�a�e����������<�k�������(�;��������+�P�r�������!�N�w����������t����������(�D�f�������������,�D���h�w�������6�B�������y���������(����?�v�������%�C�_�������)�^�������3�h������.�L�x����������������i����� �d�����P�����������D�_�������b��������6�U�|�����.�g�9�u����3����������<�����'�R�v�����x����� �)�E�������<�j������#�x���=�^���#�������I�����R������@�x����� ��N�������3�c��������$��������I�x���������:�L�a���������� �E�k���� �K�W�l�|����������� �/�d����� ��~��=�H��Cf"U��Lm���� 2H[v����� / Y } � � � �  u � � 7 � �   Y � � � 6 u � � � $7JXs�����>[v�2S��[z�����a{���'=\���:u����J��F�?!g��m�:u�CM]k���q���h���'����7 � � � � /!>!Q!`!�!�!)"D"R"�"�"�"6#W#p#�#�#�#$R$p$�$�$%'%e%q%�%&9&A&H&�&/'x'�'�'(*(�(�(�( ))1)P)�)�)�)*!*=*�*U+�+,6,m,�,�,�,�,�,�,-A-�-�-/.�.�.�.I/�/�/ 0<0K0c0�0�0�0�0�01�1�1�122h2s2�2�2�2=3�34R4n4�4�4�45Q5�5�5�56(6S6�6�6�6 717�7�7�718m8�899/9l9�9�9�9:e:�:�:�:�:,;x;�;�;!<�<�<=^=�=�=�=>A>t>�>�>�>�>�>?0?y?�?�?�?�?�?@O@�@�@�@�@4AqA~A�A�A�A B$B>BpB�B�B�BCOC�C�CD;DXDlD�D�D�D�DEDEfE�EF6FeF�F�F,G\G�GiHmI�IJK*KLLQLcL�L�L�L%MxM�M�M:N�N?O�ONP�PGQ�QCR�R�R[L[m[�[�[�[/\P\\�\�\�\]]7]�]�]�]�]�]^]^n^�^�^�^#_=_i_�_�_�_`2`O`k`p`�`�`�` a>aXa�a�a�ab5b�b�b�b>cyc�cd)dNdWd{d�d�d�deSeceoe�e�e�e�e�eYf�f�f�fzg�g�g�ghrh�h�h;i\ii�i�i�i�iIj�j�j�jk"kJk�k�k�k l=lbl�l�lmDmkm�m�m�mnn:nInpn�n�n�no4oso�o�oIpvp�p�pqXq�q+rar�r�r�r�r,sXsms�s�s�s�s tWtnt�t�t�t�tu>u_u{u�u�u�uvQvqv�vw.wlw�w�w�w�wxx xIxjx�x�x�x8y�y�y�y�yz2zoz�z�z�z{[{r{�{�{�{=|W|}|�|�|}W}�}�}~E~{~�~�~O��1���%�R���3�����˃4�����Ƅ�'�Z���ԅ�H�o����K�3�Z������X�����މ�+��������n���ۋ�g�|�����׌�;�K�Y�n�������ύ��*�F�U�f�������ݎ�(�T���ɏ׏��C�����%�������C�z���������#�-�F�a�w���͓���T�x�����Д#�>�M�e�~�ϕ��_���ז�)�L�x�����ŗ��� �+�A�s������;�K�`�h�~�™ՙ��!�B�[�e�z�����ؚ����?�O�m�����Û؛�:�n������6�Z�s�����ɝݝ��9�X�������͞���?�k��������8�p�����ߠ�� �(�<�U�����ޡ�5�m�֢$�G�������ߣ�� ��0�E�t����� �E�M�Z�j�|�����ҥ.�I�n�����Ϧ��/�>�R���������'�L�T�`�|���������٨��K�{�������թ�9�X�g�t����ͪ� ��0�9�L�[�t�����������ʫԫ߫��4�c�s���������� �,�t�|��������Q�Z�amesetNothing()Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))if missing value ≠ v thenset v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:kset ca to current applicationon lookUpDict(k, dct)end keys(allKeys() of its (NSDictionary's dictionaryWithDictionary:rec)) as liston keys(rec)end insertDictit as recordits setValue:v forKey:(k as string)tell dictionaryWithDictionary_(rec) of its NSMutableDictionaryon insertDict(k, v, rec)end identityon identity(x)end dictFromListforKeys:(my map(go, item 1 of tpl)))) as record(its (NSDictionary's dictionaryWithObjects:(item 2 of tpl) ¬tell current applicationx as stringon |λ|(x)script goset tpl to unzip(kvs)on dictFromList(kvs)end enumFromTolstset end of lst to irepeat with i from m to nif m ≤ n thenon enumFromTo(m, n)end elems(allObjects() of x) as listelse -- Setof its NSDictionary as listof dictionaryWithDictionary_(x) ¬tell current application to allValues() ¬if record is class of x then -- Dicton elems(x)end deleteKeynsDct as recordremoveObjectForKey_(k) of nsDctdictionaryWithDictionary_(rec) of its NSMutableDictionarytell current application to set nsDct to ¬on deleteKey(k, rec)end assocs(allValues() of dict) as list)allKeys() of dict) as list, ¬zip((sortedArrayUsingSelector_("compare:") of ¬dictionaryWithDictionary_(m) of its NSDictionarytell current application to set dict to ¬else if record is c thenzip(enumFromTo(1, length of m), m)if list is c thenset c to class of mon assocs(m)end Nothing{type:"Maybe", Nothing:true}on Nothing()end Just{type:"Maybe", Nothing:false, Just:x}on Just(x)end getFilenamefilenameset text item delimiters to TIDset filename to last item of pathArrayset pathArray to text items of pathset {TID, text item delimiters} to {AppleScript's text item delimiters, "/"}on getFilename(path)end loadMappingdictFromList(Ly)set AppleScript's text item delimiters to TIDset end of Ly to {rfilename, rdate}set rdate to (item 2 of ritems)set rfilename to getFilename(rpath)set rpath to (item 1 of ritems)set ritems to every text item of arowrepeat with arow in csvListset {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, DELIM}set csvList to read acsv using delimiter linefeedset acsv to (choose file)set Ly to {}set DELIM to {","}on loadMapping()end parseDatedateDateset the text item delimiters to spaceset dateDate to date ("" & dateObj)set dateObj to {item 2 of dateArray, item 3 of dateArray, item 1 of dateArray}set dateArray to items 1 through 3 of text items of dateStrset the text item delimiters to {"-", ":", " "}on parseDate(dateStr)end getDateFromDictparseDate(dateStr)missing valueif missing value = dateStr thenset dateStr to getFromDict(k, dct)on getDateFromDict(k, dct)log ("Done")log ("Skipping File " & (img_key) & " -> " & (img_date) & " -> " & img_date_fix)set the date of img to img_date_fixlog ("Fixing File " & (img_key) & " -> " & (img_date) & " -> " & img_date_fix)if ((missing value ≠ img_date_fix) and ((missing value is img_date) or (img_date_fix < img_date))) thenset img_date_fix to my getDateFromDict(img_key, mapping)set img_key to (the filename of img) as stringset img_date to (the date of img) as dateset img to item i of imageSelrepeat with i from 1 to length of imageSelset imageSel to (get selection) # Media Item class = PHAsset classtell application "Photos"log ("Loading done")set mapping to loadMapping()log ("Loading mapping")end dbNameOfWindowNametell application "htcLib" to dbNameOfWindowName(prefs)on dbNameOfWindowName(prefs)end fmGUI_ALL_Utilities_Closetell application "htcLib" to fmGUI_ALL_Utilities_Close()on fmGUI_ALL_Utilities_Close()end fmGUI_Database_DbNameOfFrontWindowerror "Couldn't get fmGUI_Database_DbNameOfFrontWindow - " & errMsg number errNumreturn dbNameOfWindowName("")fmGUI_ALL_Utilities_Close()on fmGUI_Database_DbNameOfFrontWindow(prefs)fmGUI_Database_DbNameOfFrontWindow({})end richTextToMarkdownreturn markdownTextset markdownText to rowText as textif inItalic thenif inBold thenset end of rowText to runTextset end of rowText to "[" & runText & "](" & runText & ")"else if my isLink(runText) thenset end of rowText to "[" & runText & "](mailto:" & runText & ")"if my isEmail(runText) thenset inItalic to trueif not inItalic and runIsItalic thenset inBold to trueif not inBold and runIsBold thenset end of rowText to "*"if inItalic and not runIsItalic thenset end of rowText to "**"if inBold and not runIsBold then{contents of anAttribute, my isBoldFont(font of anAttribute), my isItalicFont(font of anAttribute)}set {runText, runIsBold, runIsItalic} to ¬repeat with anAttribute in attribute runs of cellRefusing terms from application "TextEdit"set rowText to {} -- use an array because its a bit fasterset inItalic to falseset inBold to falseset markdownText to ""local markdownText, inBold, inItalic, rowTexton richTextToMarkdown(cellRef)end isItalicFontreturn fontName contains "Italic"on isItalicFont(fontName)end isBoldFontreturn fontName contains "Bold"on isBoldFont(fontName)end isEmailreturn emailText contains "@" and emailText ends with ".com"on isEmail(emailText)end isLinklinkText ends with ".com"linkText begins with "ftp:" or ¬linkText begins with "https:" or ¬return linkText begins with "http:" or ¬on isLink(linkText)set returned to process_text(testFirstPaneStuff, testThirdPaneStuff)end get argument countreturn 2on get argument countend process textdisplay dialog a with title "error with your QS action script"on error a number btell application "Quicksilver" to set selection to returnedset returned to process_text(firstPaneStuff, thirdPaneStuff)on process text firstPaneStuff with thirdPaneStuffend get indirect typesreturn {"NSFilenamesPboardType"}on get indirect typesend get direct typesreturn {"NSStringPboardType"}on get direct typesusing terms from application "Quicksilver"end process_textreturn firstPaneStuff & " " & thirdPaneStuffdisplay notification thirdPaneStuffdisplay notification firstPaneStuffon process_text(firstPaneStuff, thirdPaneStuff)property testThirdPaneStuff : "This is from the third pane."property testFirstPaneStuff : "This is from the first pane."set result_string to "Current Coinbase Bitcoin price " & price & " USD."set price to amount of result as numberset result to read JSON from jsonset json to (do shell script "curl https://coinbase.com/api/v1/prices/spot_rate")set selection to the_fileselect window of desktopreveal the_fileif is_desktop is false thenset the_file to make new file at folder this_folder with properties {name:new_file}set new_file to file_name & " " & x & file_extif new_file is in file_list thenset x to 1set new_file to file_name & file_extset file_list to get the name of every disk item of this_folderset is_desktop to trueset this_folder to path to desktop folder as aliasset this_folder to (folder of the front Finder window) as aliasset is_desktop to falseset file_ext to ".txt"set file_name to "untitled"tell application "MacVim"delay 0.02write text "" & argvtell _terminalset _terminal to current terminalset _terminal to (make new terminal)if (count of terminals) = 0 thenset destFolder to destFolder & "/"set destFolder to do shell script "dirname " & pathFileset pathFile to quoted form of POSIX path of pathFileset pathFile to selection as aliasset «class tnam» of newToDo to "from email"set «class dued» of newToDo to (current date) + 7 * daysset newToDo to make new «class tstk» with properties {name:taskName, «class note»:taskNotes}tell application "Things.app"set taskNotes to content of eachMessageset taskName to subject of eachMessagedisplay alert "No Messages Selected" message "Select the messages you want to add to Things before running this script."if (count of selectedMessages) is equal to 0 thenend tell_timedisplay dialog (time string of (current date))on tell_time()end removeItemAtIndexset newList to items 1 thru (theIndex - 1) of lst & items (theIndex + 1) thru (theLength) of lstset newList to items 2 thru theLength of lstelse if theIndex = 1 thenset newList to items 1 thru (theLength - 1) of lstelse if theLength = theIndex thenif theLength = 1 thenset theLength to length of lston removeItemAtIndex(lst, theIndex)end findLeastItemreturn theIndexset iterater to iterater + 1set theIndex to iteraterset theLeast to start date of iif start date of i ≤ theLeast thenrepeat with i in lstset iterater to 1set theIndex to 1set theLeast to start date of item 1 of lston findLeastItem(lst)end sortEventsreturn myNewListset myList to removeItemAtIndex(myList, leastIndex)set end of myNewList to item leastIndex of myListset leastIndex to findLeastItem(myList)repeat until length of myList = 0set myNewList to {}on sortEvents(myList)display dialog "The new DNS server(s):" & return & newDNS buttons {"OK"}set newDNS to do shell script "networksetup -getdnsservers Ethernet"do shell script "networksetup -setdnsservers Ethernet 1.1.1.1 1.0.0.1"if answer is equal to "Cloudflare" thendo shell script "networksetup -setdnsservers Ethernet 208.67.222.222 208.67.220.220"if answer is equal to "OpenDNS" thendo shell script "networksetup -setdnsservers Ethernet 8.8.8.8 8.8.4.4"if answer is equal to "Google DNS" thenset question to display dialog "Please select" buttons {"Google DNS", "OpenDNS", "Cloudflare"}if answer is equal to "Set DNS" thendo shell script "dscacheutil -flushcache"do shell script "networksetup -setdnsservers Ethernet Empty"if answer is equal to "DHCP" thenset answer to button returned of questionset question to display dialog "The current DNS server(s):" & return & DNSinUse buttons {"Set DNS", "DHCP", "Cancel"}set DNSinUse to do shell script "networksetup -getdnsservers Ethernet"end coerceToStringtell codeCoerce to coerceToString(incomingObject)set codeCoerce to run script codeCoercetell application "htcLib" to set codeCoerce to "script codeCoerce " & return & getTextBetween({sourceText:codeCoerce, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeCoerce"set codeCoerce to read file coercePath as texttell application "Finder" to set coercePath to (container of (container of (path to me)) as text) & "text parsing:coerceToString.applescript"on coerceToString(incomingObject)end fmGUI_ManageSecurity_PrivSet_Selecttell application "htcLib" to fmGUI_ManageSecurity_PrivSet_Select(prefs)on fmGUI_ManageSecurity_PrivSet_Select(prefs)end fmGUI_ManageSecurity_PrivSet_OpenSelectedtell application "htcLib" to fmGUI_ManageSecurity_PrivSet_OpenSelected(prefs)on fmGUI_ManageSecurity_PrivSet_OpenSelected(prefs)end clickObjectByCoordstell application "htcLib" to clickObjectByCoords(my coerceToString(prefs))on clickObjectByCoords(prefs)end fmGUI_ManageSecurity_PrivSet_Renameerror "Couldn't fmGUI_ManageSecurity_PrivSet_Rename - " & errMsg number errNumreturn windowWaitUntil({windowName:"Manage Security", whichWindow:"front", windowNameTest:"starts with"})clickObjectByCoords(okButton)set okButton to button "OK" of window 1set value of text field "Privilege Set Name" of window 1 to privSet_newName of prefsfmGUI_ManageSecurity_PrivSet_OpenSelected({})if not fmGUI_ManageSecurity_PrivSet_Select({privSetName:privSet_oldName of prefs, fullAccessAccountName:fullAccessAccountName of prefs, fullAccessPassword:fullAccessPassword of prefs}) then error "unable to select by old name" number -1024if fmGUI_ManageSecurity_PrivSet_Select({privSetName:privSet_newName of prefs, fullAccessAccountName:fullAccessAccountName of prefs, fullAccessPassword:fullAccessPassword of prefs}) then return trueon fmGUI_ManageSecurity_PrivSet_Rename(prefs)fmGUI_ManageSecurity_PrivSet_Rename({privSet_oldName:"Developer", privSet_newName:"Developer_1", fullAccessAccountName:"admin", fullAccessPassword:""})display dialog errMsg & return & return & errNum buttons {"Cancel", "OK"} default button "OK"if errNum = 1000 then set errMsg to "Script timeout, " & errMsg & " not found"click (first button of group 1 of group 1 of window 1 whose name contains "Hazel")if failsafe = 100 then error "Start/Stop Hazel button" number 1000repeat until exists of (first button of group 1 of group 1 of window 1 whose name contains "Hazel")click radio button 3 of radio group 1 of window 1if value of radio button 3 of radio group 1 of window 1 = 0 thenif failsafe = 100 then error "info button" number 1000repeat until exists of radio button 3 of radio group 1 of window 1set current pane to pane "com.noodlesoft.Hazel"set q color of eachCue to newColorset newColor to choose from list theColors with title "Pick a color" default items {"none"}set theColors to {"none", "red", "orange", "green", "blue", "purple"}tell application "System Events" to keystroke space using {option down, control down}keystroke "c" using command downkeystroke "l" using command downtell application "Firefox" to activateon run {input, parameters}/Applications/Emacs.app/Contents/MacOS/" & emacs_bin & " -l ${MYEMACSDIR}/_emacs.mac"export MYEMACSDIR=" & emacs_d & ";do shell script "export PATH=/usr/local/git/bin:${PATH};else echo 'Emacs-10.7'; fi)"then echo 'Emacs-10.4';set emacs_bin to do shell script "echo $(if [[ `sw_vers -productVersion` == 10.6* ]];ln -s " & emacs_d & " ~/.emacs.d"mv ~/.emacs.d ~/.emacs.d-$dtime;do shell script "export dtime=`date +%Y-%m-%d_%H-%M-%S`;if not target_d = emacs_d thenset target_d to do shell script "echo $(readlink ~/.emacs.d)"do shell script "ln -s " & emacs_d & " ~/.emacs.d"if fileexists = "nop" thenelse echo 'nop'; fi)"then echo 'yep';set fileexists to do shell script "echo $(if [ -e ~/.emacs.d ];set emacs_d to do shell script "echo $(dirname " & scptpath & ")/_emacs.d"set scptpath to POSIX path of (path to me) as Unicode texttell application "Finder" to get the name of the second Finder windowend runItset the name of theFile to theDate & " " & the name of theFile as textset theSelection to get selectionset theDate to do shell script "date +%F"on runIt()runIt()return POSIX path of (choose file)return POSIX path of (choose folder)open location linkset link to the clipboarddo shell script "qlmanage -p \"" & pathFile & "\""set pathFile to POSIX file "/Users/zhangyongkang/Desktop/Code"quit application closeallrepeat with closeall in quitappstell application "System Events" to set quitapps to name of every application process whose visible is true and name is not "Finder"key code 40 using {command down}make new tab with properties {URL:"https://www.zhihu.com"}tell application "Opera" to key code 45 using {command down}if windows of application "Opera" is {} thentell application "Opera"activate application "Opera"POSIX file filePath as aliasset filePath to ("${folderPath}")if windows of application "Finder" is {} thenreturn allCollapseset allCollapse to (collapsed of (_window)) and allCollapseset allCollapse to truereturn "Not running"if application "Finder" is not running thenreturn finderWindowPathset the end of finderWindowPath to POSIX path of (folder of _window as alias)repeat with _window in windowListset finderWindowPath to {}set windowList to windowsset _size to size of front windowset _location to position of back windowtell process "Finder"set activeApp to name of current applicationif exists file (folderPath & fileName as text) thenset fileName to ("filename with extension")set folderPath to insertion location as aliasset visible of theApp to falserepeat with theApp in visibleAppsset visibleApps to every process whose visible is truetell app "Finder" to set the clipboard to (POSIX file "/Users/zhangyongkang/Desktop/Markdown.md")tell application "System Events" to do shell script "defaults write com.apple.finder AppleShowAllFiles -bool true"set theString to theString & theNewString & eachPart as stringrepeat with eachPart in items 2 thru -1 of theStringPartsset theString to text item 1 of theStringParts as stringif (count of theStringParts) is greater than 1 thenset theStringParts to text items of theStringset {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, theOriginalString}on replaceString(theString, theOriginalString, theNewString)set (HTML content of item 1 of theNote) to editHTMLset editHTML to my replaceString(noteHTML, "", addString)set addString to "" & add_to_topset noteHTML to (HTML content of item 1 of theNote)set theNotes to selectionproperty noteHTML : ""property add_to_top : "





"tell application "Spotify" to playpauseclose this_filesave this_file without iconflip this_file with verticalset this_file to open file this_imagewith timeout of 30 secondsset this_image to the image of this_itemif the type of this_item is equal to picture thenrepeat with this_item in this_selectionif this_selection is {} then error "Please select some images."set this_selection to the selectionset the clipboard to resub(URL_list, "chrome-extension://[a-z]+/suspended.html#uri=", "")click button 1 -- click the back buttontell group 1 of group 1 of toolbar 1repeat until exists group 1 of group 1 of toolbar 1tell window "ASUS PB278 (1)"click radio button "Default for display"tell tab group 1 of group 1 of window "ASUS PB278 (1)"repeat until exists tab group 1 of group 1 of window "ASUS PB278 (1)"select row 2 of table 1 of scroll area 1click radio button "Scaled"click radio button "Display"tell tab group 1 of window "ASUS PB278 (1)"repeat until exists tab group 1 of window "ASUS PB278 (1)"set the current pane to pane "com.apple.preference.displays"display notification "This is a notification" with title "Title" subtitle "Subtitle"open theFilerepeat with theFile in theSelectiontell application "Emacs"set theSelection to get selection as alias listtell application "Finder" to launchtell application "Finder" to quitdo shell script "defaults write com.apple.finder CreateDesktop -bool FALSE"do shell script "defaults delete com.apple.finder CreateDesktop"do shell script "defaults read com.apple.finder CreateDesktop"do shell script "/usr/local/bin/pandoc -f html " & path_file & " -t pdf -o " & dest_file & baseName & ".pdf"set baseName to result(characters 1 through (-2 - (count of nameExt)) of dispName) as textdispNameif isHidden or nameExt is equal to "" thentell application "Finder" to set {dispName, nameExt, isHidden} to the {displayed name, name extension, extension hidden} of source_fileset dest_file to POSIX path of dest_fileset dest_file to choose folder with prompt "Where to save the PDF file?"set path_file to POSIX path of source_fileset source_file to choose file with prompt "Where is the HTML or HTM file?" of type {"htm", "html"}greetingset greeting to linefeed & greeting & linefeedset greeting to "Hello, world!"playSong(theLetter)set theLetter to item 1 of argvend playSongplay randomTrackset randomTrack to item (random number from 1 to (count of theTracks)) of theTracksset theTracks to tracks of library playlist 1 whose name starts with songLettertell application "Music"on playSong(songLetter)end padreturn text -2 thru -1 of ("00" & n)on pad(n)end perform mail action with messagessave theAttachment in file (savePath)set savePath to attachmentsFolder & ":" & timeStamp & " - " & businesspartner & " " & originalNameset originalName to name of theAttachmentrepeat with theAttachment in eachMessage's mail attachmentsset timeStamp to ("" & y & "-" & my pad(m as integer) & "-" & my pad(d))set {year:y, month:m, day:d, hours:h, minutes:min} to eachMessage's date sentrepeat with eachMessage in theMessagesset attachmentsFolder to ((path to home folder as text) & "Downloads") as textset businesspartner to name of theRuleon perform mail action with messages theMessages for rule theRuleusing terms from application "Mail"set position to {600, 450}tell application "System Events" to tell process "Photos"set position to {240, 320}tell application "System Events" to tell process "TV"set size to {1000, 650}set position to {800, 600}tell application "System Events" to tell process "Music"tell application "ScreenSaverEngine" to activatepauseset volume with output mutedrelaunchApplication("Finder")setValueForKey(targetKey, newValue)set newValue to not prevValueset prevValue to first item of coerceObjToAS(getValueForKey(targetKey)) as booleanset targetKey to "CreateDesktop"end relaunchApplicationtell application applicationName to activateset counter to counter + 1if applicationName is not in (name of application processes) then exit repeatrepeat while counter < 10tell application applicationName to quitto relaunchApplication(applicationName)end coerceObjToASreturn item 1 of (current application's NSArray's arrayWithObject:obj) as listto coerceObjToAS(obj)end getSuiteValuesreturn (NSUserDefaults's alloc's persistentDomainForName:suiteID)to getSuiteValues()end setSuiteValuesNSUserDefaults's alloc's setPersistentDomain:keyValueRecord forName:suiteIDto setSuiteValues(keyValueRecord)end getValueForKeyreturn defaultsSuite's objectForKey:keyNameto getValueForKey(keyName)end setValueForKeydefaultsSuite's setObject:value forKey:keyNameif defaultsSuite = missing value then my init()to setValueForKey(keyName, value)set defaultsSuite to NSUserDefaults's alloc's initWithSuiteName:suiteIDproperty suiteID : "com.apple.finder"property defaultsSuite : missing valueproperty NSUserDefaults : class "NSUserDefaults"property ca : current applicationzoomMuteState"return returnValue & "| size=18set returnValue to "MUTED"set returnValue to "LIVE MIC"if exists (menu item btnTitle of menu 1 of menu bar item "Meeting" of menu bar 1) thenif exists (menu bar item "Meeting" of menu bar 1) thentell application process "zoom.us"if application "zoom.us" is running thenproperty btnTitle : "Mute audio"system attribute "USER_HOME"repeat with name in otherAccountselse if accountType as rich text is "other" thenrepeat with name in privateelse if accountType as rich text is "private" thenset enabled of account name to myBoolrepeat with name in workif accountType as rich text is "work" thenrepeat with accountType in accountTypesset myBool to falseelse if myBool as rich text is "disable" thenset myBool to trueelse if myBool as rich text is "enable" thenif myBool is false thenset myBool to result(choose from list {"enable", "disable"} default items "enable" OK button name "Ok" with prompt "Enable or disable" with title "Create Reminder from E-Mail")if accountTypes is false then returnset accountTypes to result(choose from list {"work", "private", "other"} default items "work" OK button name "Ok" with prompt "Choose account type" with title "Enable disable account group" with multiple selections allowed)set otherAccounts to ["OtherAccount1", "OtherAccount2", "OtherAccount3"]set private to ["PrivateAccount1", "PrivateAccount2", "PrivateAccount3"]set work to ["WorkAccount1", "WorkAccount2"]display dialog tab & tab & tab & "MacOS " & MacOSVers & " (" & MacOSBuild & ")" & return & return & "Component " & tab & tab & "Version " & tab & tab & "Updated " & return & return & "XProtect " & tab & tab & XProtectVers & tab & tab & XProtectDate & return & "Gatekeeper " & tab & tab & GatekeeperVers & tab & tab & tab & GatekeeperDate & return & "SIP" & tab & tab & tab & tab & SIPVer & tab & tab & tab & SIPDateShort & return & "MRT " & tab & tab & tab & MRTVer & tab & tab & tab & MRTDate & return & return & SIPStatus & return & "Gatekeeper Status:" & GatekeeperStatus & return buttons {"Close"} default button 1set GatekeeperStatus to do shell script "spctl --status | sed -e s/'assessments'//g"set SIPStatus to do shell script "/usr/bin/csrutil status"set MRTDate to do shell script "GetFileInfo -d /System/Library/CoreServices/MRT.app/Contents/version.plist"set MRTVer to do shell script "defaults read /System/Library/CoreServices/MRT.app/Contents/version.plist CFBundleShortVersionString"set SIPDateShort to do shell script "GetFileInfo -d /System/Library/Sandbox/Compatibility.bundle/Contents/version.plist"set SIPVer to do shell script "defaults read /System/Library/Sandbox/Compatibility.bundle/Contents/version.plist CFBundleShortVersionString"set GatekeeperDate to do shell script "GetFileInfo -d /private/var/db/gkopaque.bundle/Contents/version.plist"set GatekeeperVers to do shell script "defaults read /private/var/db/gkopaque.bundle/Contents/version.plist CFBundleShortVersionString"set XProtectDate to do shell script "GetFileInfo -d /System/Library/CoreServices/XProtect.bundle/Contents/Resources/XProtect.meta.plist"set XProtectVers to do shell script "defaults read /System/Library/CoreServices/XProtect.bundle/Contents/Resources/XProtect.meta.plist Version"set MacOSBuild to do shell script "defaults read /System/Library/CoreServices/SystemVersion.plist ProductBuildVersion"set MacOSVers to do shell script "defaults read /System/Library/CoreServices/SystemVersion.plist ProductVersion"end cleanupdo shell script "echo " & quoted form of clipboardContent & " | pbcopy"if (exists file tmpAttachmentB64FilePath) then delete file tmpAttachmentB64FilePathif (exists file tmpAttachmentFilePath) then delete file tmpAttachmentFilePathif (exists file tmpNoteContentPath) then delete file tmpNoteContentPathon cleanup()end getNoteContentFromEvernoteNotereturn noteContentset noteContent to my readFile(tmpNoteContentPath)display dialog dialogTextset dialogText to "The note (" & title of evernoteNote & ") has unhandled attachment mime-type: " & attachmentMime & ". Attachment will NOT be imported. Set property showAttachmentError to false to ignore such messages."if showAttachmentError is true thendo shell script "cat " & (quoted form of POSIX path of tmpNoteContentPath) & " | perl -pe 's|" & searchPattern & "|`cat " & quoted form of POSIX path of tmpAttachmentB64FilePath & "`|gme' | pbcopy && pbpaste > " & (quoted form of POSIX path of tmpNoteContentPath)set searchPattern to "]*" & attachmentHash & ".*?>"do shell script "echo '\"/>' >> " & quoted form of POSIX path of tmpAttachmentB64FilePathdo shell script "cat " & quoted form of POSIX path of tmpAttachmentB64FilePath & " | pbcopy && echo '" & prependReplace & "' > " & quoted form of POSIX path of tmpAttachmentB64FilePath & " && pbpaste >> " & quoted form of POSIX path of tmpAttachmentB64FilePathset prependReplace to " " & quoted form of POSIX path of tmpAttachmentB64FilePathcurrentAttachment write to tmpAttachmentFilePathtell application "System Events" to if (exists file tmpAttachmentFilePath) then delete file tmpAttachmentFilePathif attachmentMime contains "image" thenset attachmentMime to mime of currentAttachmentset attachmentHash to hash of currentAttachmentrepeat with currentAttachment in allAttachmentsmy writeToFile(noteContent, tmpNoteContentPath, false)tell application "System Events" to if (exists file tmpNoteContentPath) then delete file tmpNoteContentPathif (allAttachments is not {}) thenset allAttachments to every attachment in evernoteNoteset noteContent to HTML content of evernoteNoteon getNoteContentFromEvernoteNote(evernoteNote)end readFilereturn read file theFileset theFile to theFile as stringon readFile(theFile)close access file target_filelog "ERROR" & errStr & errorNumberwrite this_data to the open_target_file starting at eofif append_data is false then set eof of the open_target_file to 0set the open_target_file to open for access file target_file with write permissionset the target_file to the target_file as stringon writeToFile(this_data, target_file, append_data) -- (string, file path as string, boolean)end zero_padreturn padded_valueset padded_value to string_zeroes & value as stringset string_zeroes to string_zeroes & "0" as stringrepeat digits_to_pad timesif digits_to_pad > 0 thenset digits_to_pad to string_length - (length of (value as string))set string_zeroes to ""on zero_pad(value, string_length)end nowYYYYMMDDMMSSreturn resultset result to result & zero_pad(seconds of now as integer, 2)set result to result & zero_pad(minutes of now as integer, 2)set result to result & ":"set result to result & zero_pad(hours of now as integer, 2)set result to result & "T"set result to result & zero_pad(day of now as integer, 2)set result to result & zero_pad(month of now as integer, 2)set result to result & "-"set result to (year of now as integer) as stringset now to (current date)on nowYYYYMMDDMMSS()end extractStackNamereturn stackNameset stackName to text ((length of stackTagPrefix) + 1) thru -1 of tagNameset tagName to name of noteTagif name of noteTag starts with stackTagPrefix thenrepeat with noteTag in noteTagson extractStackName(noteTags)end getNotesSubFolderreturn nullreturn subfolderif name of subfolder is equal to subfolderName thenrepeat with subfolder in folders in notesFolderon getNotesSubFolder(notesFolder, subfolderName)my cleanup()log "Stopping at notes #" & importedNotesCountif maxNotesToImport ≥ 0 and importedNotesCount ≥ maxNotesToImport thenlog "Notes #" & importedNotesCount & "/" & allNotesCount & " imported"set importedNotesCount to importedNotesCount + 1set notebookNotesCounter to notebookNotesCounter + 1make new note at notebookFolder with properties {name:"", body:noteContent, creation date:noteCreationDate, modification date:noteModificationDate}set notebookFolder to make new folder at parentImportFolder with properties {name:notebookName}log "Create notebook folder " & notebookNameif notebookFolder is null thenset notebookFolder to my getNotesSubFolder(parentImportFolder, notebookName)set notebookName to the name of the notebook of currentNoteset parentImportFolder to importRootFolderset parentImportFolder to stackFolderif stackFolder is not null thenset parentImportFolder to nullset stackFolder to make new folder at importRootFolder with properties {name:stackName}log "Create stack folder " & stackNameif stackFolder is null thenset stackFolder to my getNotesSubFolder(importRootFolder, stackName)if stackName is not null thenset stackName to my extractStackName(the tags of currentNote)set stackFolder to nullset noteTitle to ""set noteContent to "

" & noteTitle & "


" & noteContentset noteContent to my getNoteContentFromEvernoteNote(currentNote)set noteModificationDate to modification date of currentNoteset noteCreationDate to creation date of currentNoteset noteContent to HTML content of currentNoteset noteTitle to (the title of currentNote)log "Importing Note " & notebookNotesCounter & "/" & notebookNotesCount & " from Evernote notebook " & notebookNamerepeat with currentNote in notebookNotesset notebookNotesCounter to 1set notebookNotesCount to count of notebookNotesset notebookNotes to every note in notebook notebookNameset notebookName to (the name of currentNoteBook)repeat with currentNoteBook in allNotebooksset allNotebooks to every notebookset allNotesCount to count of allNotesset allNotes to find notestell application "Evernote Legacy"set importRootFolder to make new folder with properties {name:importRootFolderName}log "Create import root folder " & importRootFolderNametell application "Notes" to launchtell application "Evernote Legacy" to launchset importedNotesCount to 0set importRootFolderName to "_ImportedNotes" & my nowYYYYMMDDMMSS()set importRootFolder to nullproperty clipboardContent : do shell script "pbpaste"property tmpAttachmentB64FilePath : (((path to desktop folder) as string) & "evernote2AppleNotesAttachmentB64.tmp")property tmpAttachmentFilePath : (((path to desktop folder) as string) & "evernote2AppleNotesAttachment.tmp")property tmpNoteContentPath : (((path to desktop folder) as string) & "evernote2AppleNotesContent.tmp")property stackTagPrefix : "stack:"property showAttachmentError : trueproperty maxNotesToImport : -1system infodo shell script ("networksetup -setairportpower " & device & " " & power)set power to "on"set power to "off"if power is equal to "on" thenset power to do shell script "networksetup -getairportpower " & device & " | awk '{print $4}'"set device to do shell script "networksetup -listallhardwareports | awk '$3==\"Wi-Fi\" {getline;print}' | awk '{print $2}'"on rotate(theImage, degrees)end rotatationtheImage's (rotate by degrees)on rotatation of theImage by degreesend imageFromData:return my (createImage from theData)on imageFromData:theDataend createImageerror "Could not convert data to base 64 string."if theImage is missing value thenset theImage to current application's NSImage's alloc()'s initWithData:theDataset imageObj's base64data to (theData's base64EncodedStringWithOptions:0) as stringset theImage to current application's NSImage's alloc()'s initWithContentsOfFile:theTempFilewrite theData to fileRefset fileRef to open for access theTempFile with write permissionset theTempFile to POSIX path of (current application's NSTemporaryDirectory() as string) & "tmp.data"if (class of theData as text) contains "picture" thenset theImage to current application's NSImage's alloc()'s initWithData:base64dataset base64data to current application's NSData's alloc()'s initWithBase64EncodedString:theData options:0set imageObj's base64data to theDataif class of theData is text thenerror "Data is missing value"if theData is missing value thenon createImage from theDataend Symbolreturn imageObjset imageObj's modified to trueset imageObj's height to theImage's |size|()'s height()set imageObj's width to theImage's |size|()'s width()set imageObj's base64data to (theImage's TIFFRepresentation()'s base64EncodedStringWithOptions:0) as stringset theImage to theImage's imageWithSymbolConfiguration:theConfigset theImage to current application's NSImage's imageWithSystemSymbolName:symbolName accessibilityDescription:(missing value)set theConfig to current application's NSImageSymbolConfiguration's configurationWithPointSize:pointSize weight:(current application's NSFontWeightRegular)set imageObj to Image("---")on Symbol(symbolName, pointSize)return theImage's extractPayloads()on extractPayloads from theImagereturn theImage's (classifications above confidenceLevel)on classifications for theImage above confidenceLevelreturn theImage's extractText()on extractText from theImageend Imagereturn ILImageset ILImage's height to theImage's |size|()'s height()set ILImage's width to theImage's |size|()'s width()set ILImage's base64data to (theImage's TIFFRepresentation()'s base64EncodedStringWithOptions:0) as stringif theImage is not missing value thenset theImage to ILImage's _getNSImage()theWorkspace's openURL:theURLset theWorkspace to current application's NSWorkspace's sharedWorkspace()set theURL to current application's |NSURL|'s fileURLWithPath:theTempFileset theTempFile to POSIX path of (current application's NSTemporaryDirectory() as string) & "Image.png"set theData to theBitmap's representationUsingType:(current application's NSBitmapImageFileTypePNG) |properties|:(missing value)on openend savetheData's writeToURL:theURL atomically:trueset theURL to current application's |NSURL|'s fileURLWithPath:filePathset theData to theBitmap's representationUsingType:theType |properties|:(missing value)end ignoringset theType to current application's NSBitmapImageFileTypeTIFFelse if fileType is "tiff" thenset theType to current application's NSBitmapImageFileTypeBMPelse if fileType is "bmp" thenset theType to current application's NSBitmapImageFileTypeGIFelse if fileType is "gif" thenset theType to current application's NSBitmapImageFileTypeJPEGif fileType is "jpg" or fileType is "jpeg" thenignoring caseset theType to current application's NSBitmapImageFileTypePNGerror "Must provide an output destination."set filePath to my targetif filePath is missing value thenset theBitmap to current application's NSBitmapImageRep's imageRepWithData:theImageDataset theImageData to theImage's TIFFRepresentation()set theImageData to missing valueon save in filePath : (missing value) as fileType : "png"end countFacesreturn count of faceResultsset faceResults to faceRequest's results()requestHandler's performRequests:{faceRequest} |error|:(missing value)set faceRequest to current application's VNDetectFaceRectanglesRequest's alloc()'s init()on countFaces()end extractPayloadsreturn payloadscopy (observation's payloadStringValue() as text) to end of payloadsrepeat with observation in barcodeResultsset payloads to {}set barcodeResults to barcodeRequest's results()requestHandler's performRequests:{barcodeRequest} |error|:(missing value)set barcodeRequest to current application's VNDetectBarcodesRequest's alloc()'s init()on extractPayloads()end classificationsreturn classificationscopy {identifier:observation's identifier() as text, confidence:observation's confidence() as real} to end of classificationsif observation's confidence() > confidenceThreshold thenrepeat with observation in classificationResultsset classifications to {}set classificationResults to classificationRequest's results()requestHandler's performRequests:{classificationRequest} |error|:(missing value)set classificationRequest to current application's VNClassifyImageRequest's alloc()'s init()on classifications above confidenceThresholdend extractTextreturn textItemscopy (first item in (observation's topCandidates:1))'s |string|() as text to end of textItemsrepeat with observation in textResultsset textItems to {}set textResults to textRequest's results()requestHandler's performRequests:{textRequest} |error|:(missing value)set textRequest to current application's VNRecognizeTextRequest's alloc()'s init()set requestHandler to current application's VNImageRequestHandler's alloc()'s initWithData:(theImage's TIFFRepresentation()) options:(current application's NSDictionary's alloc()'s init())on extractText()end rotateset my height to current application's NSHeight(rotatedBounds)set my width to current application's NSWidth(rotatedBounds)set my base64data to (rotatedImageData's base64EncodedStringWithOptions:0) as stringset rotatedImageData to rotatedImage's TIFFRepresentation()rotatedImage's unlockFocus()theImage's drawInRect:imageBounds fromRect:(current application's CGRectZero) operation:(current application's NSCompositingOperationCopy) fraction:1.0rotatedImage's lockFocus()transform's translateXBy:((item 1 of item 2 of rotatedBounds) / -2) yBy:((item 2 of item 2 of rotatedBounds) / -2)transform's rotateByDegrees:-degreestransform's translateXBy:((item 1 of item 2 of rotatedBounds) / 2) yBy:((item 2 of item 2 of rotatedBounds) / 2)set transform to current application's NSAffineTransform's transform()set item 1 of imageBounds to {(current application's NSMidX(rotatedBounds)) - (current application's NSWidth(imageBounds)) / 2, (current application's NSMidY(rotatedBounds)) - (current application's NSHeight(imageBounds)) / 2}set rotatedImage to current application's NSImage's alloc()'s initWithSize:(item 2 of rotatedBounds)set rotatedBounds to current application's NSMakeRect(0, 0, item 1 of item 2 of pathBounds's |bounds|(), item 2 of item 2 of pathBounds's |bounds|())pathBounds's transformUsingAffineTransform:theTransformtheTransform's rotateByDegrees:-degreesset theTransform to current application's NSAffineTransform's transform()set pathBounds to current application's NSBezierPath's bezierPathWithRect:imageBoundsset imageBounds to current application's NSMakeRect(0, 0, my width, my height)on rotate by degreesend flipset my modified to trueset my base64data to (flippedImageData's base64EncodedStringWithOptions:0) as stringset flippedImageData to flippedImage's TIFFRepresentation()flippedImage's unlockFocus()theImage's drawInRect:theRectset theRect to current application's NSMakeRect(0, 0, my width, my height)transform's concat()error "Invalid axis."(transform's translateXBy:0 yBy:(0 - (my height)))(transform's scaleXBy:1 yBy:-1)else if axis is 1 then(transform's translateXBy:(0 - (my width)) yBy:0)(transform's scaleXBy:-1 yBy:1)if axis is 0 thenset transform to current application's NSAffineTransform's alloc()'s init()flippedImage's lockFocus()set flippedImage to (current application's NSImage's alloc()'s initWithSize:(theImage's |size|()))set theImage to my _getNSImage()on flip over axisend _getNSImageerror "Cannot create image from " & (my target)return (missing value)else if my target is "---" thenreturn current application's NSImage's alloc()'s initWithContentsOfURL:theURLset theURL to current application's NSURL's URLWithString:(my target)else if my target contains ":" thenreturn current application's NSImage's alloc()'s initWithContentsOfFile:(my target)if my target starts with "/" thenreturn current application's NSImage's alloc()'s initWithData:theImageDataset theImageData to current application's NSData's alloc()'s initWithBase64EncodedString:(my base64data) options:0if my modified is true thenset theImage to missing valueset _NSImage to current application's NSClassFromString("NSImage")on _getNSImage()property modified : falseproperty base64data : missing valueproperty height : missing valueproperty width : missing valueproperty target : theTargetscript ILImageon Image(theTarget)property Y_AXIS : 0property X_AXIS : 1property NSImage : class "NSImage"use framework "Quartz"doCompleteReminderFromID(aReminderList, aReminder)doCreateNewReminder(aReminderList, theNewReminder)copy its item 12 to the end of theNewReminder -- remind me datecopy its item 11 to the end of theNewReminder -- prioritycopy its item 10 to the end of theNewReminder -- namecopy its item 7 to the end of theNewReminder -- flaggedcopy its item 6 to the end of theNewReminder -- due datecopy its item 1 to the end of theNewReminder -- alldayduedatetell theFullReminderset theFullReminder to myRemindersLib's getReminderFromID(aReminderList, aReminder)if item 1 of theReminderBody contains "Hour" thenset theReminderBody to MarksLib's split(item 1 of theReminderBodyFromID, "~")if item 1 of theReminderBodyFromID is not missing value thenset theReminderBodyFromID to myRemindersLib's getReminderBodyFromID(aReminderList, aReminder)repeat with aReminder in theRemindersByIDset theRemindersByID to myRemindersLib's getRemindersID(aReminderList, today, today, "not completed")repeat with aReminderList in theRemindersListset time of today to 0set theRemindersList to {"HPE"}set theNewReminder to {}set theFullReminder to {}set theReminderBody to missing valueset theReminderBodyFromID to missing valueset aReminderList to missing valueset theReminders to missing valueset aReminder to missing valueset theRemindersByID to {}local theNewReminderlocal theFullReminderlocal theReminderBodylocal theReminderBodyFromIDlocal aReminderListlocal theRemindersListlocal theReminderslocal aReminderlocal theRemindersByIDuse MarksLib : script "MarksLib"use myRemindersLib : script "StephensRemindersLib"use AppleScript version "2.7"set desiredSize to {0.666, 1.0}set desiredPosition to {0.0, 0.0}* NSOrderedSet, NSString, NSPropertyListSerialization* whereFroms - a set of handlers in an example that adds or removes the file whereFrom attribute.* NSData, NSJSONSerialization, NSError* JSON - conversion of a list/record to/from a JSON string.* NSDictionary, NSData, NSPropertyListSerialization* FinderTags - gets all of the Finder's tags and their label colors. Works with old and new plist locations (uses the `sqlite3` shell utility to read the database in current OS versions).* NSOrderedSet, NSURL, NSDictionary* tags - a set of handlers in an example that adds or removes file tags.* NSData, NSImage, NSBitmapImageRep* OverlayImage - overlay one image over another. The example puts an image or application icon onto a copy of the system's generic folder icon.These are also examples using AppleScriptObjC, but use other Cocoa classes that can be run directly from the **Script Editor** or **Script Debugger** without any main thread issues.* NSWindow, NSButton, NSTextField, NSView,NSViewController, NSPopover, NSFont, NSColor* *Popover - shows a popover at a button when it is clicked.* NSAlert, NSTextField, NSSecureTextField, NSComboBox, NSButton, NSTimer, NSBox, NSMutableDictionary, NSImage.* *AlertLib - an NSAlert library. Performs an NSAlert with optional TextField, ComboBox, CheckBox, or RadioButton accessory views. Can be used as a script library.* NSWindow, NSStatusBar, NSMenu, NSTimer, NSTextField, NSMutableAttributedString, NSDictionary, NSFont, NSColor.* *TimerDisplay - similar to StatusbarTimer, but displays a general-purpose timer in a floating window and / or a status bar menu item.* NSStatusBar, NSMenu, NSWorkspace notifications, NSTimer, NSMutableAttributedString, NSDictionary, NSFont, NSColor.* *StatusBarTimer - a status bar menu item showing the time that a specified application is active.* NSWindow, NSAlert, NSButton* *Sheets - shows an alert sheet (with a help sheet) over the main window. ASObjC does not support blocks, so you are limited to the (somewhat buggy) deprecated method. There are some third-party Objective-C categories supporting completionHandler blocks available for use in an Xcode project.* NSApplication, NSOpenPanel, NSMenu, NSBox, NSButton, NSDictionary* *OpenPanel - an NSOpenPanel with an accessory view.A few simple ASObjC scripts demonstrating the usage of various Cocoa classes. These should be saved and run as stay-open applications, since GUI elements need to be run on the main thread, although many* can be run from the **Script Editor** or **Script Debugger** (and adjusted for **Xcode**, of course). Care should be taken when running from an editor though, as programmatically created objects such as windows and menu items can be added to the current editor instance, in which case they will be kept until they are explicitly removed or the editor is quit.keystroke "w" using {command down}end revealDocumentreveal theFileset theFile to file of theDocumentset theDocument to document 1tell application "OmniOutliner"on revealDocument()revealDocument()if found is true thenfound = truedisplay notification button_action with title "Google Hangouts"say button_actionexecute the_tab javascript "var el = document.querySelector('div[role=\"button\"][data-tooltip*=\"camera\"]'); el.dispatchEvent(new MouseEvent('mousedown')); el.dispatchEvent(new MouseEvent('mouseup')); el.dispatchEvent(new MouseEvent('mouseout'));"set button_action to execute the_tab javascript "document.querySelector('div[role=\"button\"][data-tooltip*=\"camera\"]').getAttribute(\"aria-label\")"if the_title is "Google Hangouts" thenset the_title to the title of the_tabset index_tab to index_tab + 1repeat with the_tab in tab_listset index_tab to 0set tab_list to every tab in the_windowset index_window to index_window + 1repeat with the_window in window_listset index_window to 0set found to falseset window_list to every window(Next I'll look into AppleScriptObjC -Shane Stanley's- and what else can be tweaked with that.)but I'm slowly getting a "feeling" for applescript ...triggered quite different behaviours in the scripts. I admit to not yet quite understanding the "whys" ...I was really astonished how "tell application" or "tell process" or even "tell application process" eachset position of window "Recent downloads" to {rightEdge, 61}end repeat -- wait for "dialog window" !repeat while not (exists window "Recent downloads")tell application "System Events" to tell process "Finder"set rightEdge to (item 3 of screenRgt) - 425set screenRgt to bounds of the window of desktopHere's the 2nd "folder action script" to "Folder1" that moves your "dialog" to the right/top:end opening folderbuttons {"Close"} default button 1tell application "Finder" to display dialog DL_display as string ¬DL_item & returntext item 1 of DL_item & ":]" & return & text item 2 of ¬set DL_display to DL_display & return & "[" & ¬list item i of property list item 1 of plist_file) as string))property list item "DownloadEntryPath" of property ¬set DL_item to (get text items -2 thru -1 of ((value of ¬repeat with i from 1 to number of items in downloadItemsset AppleScript's text item delimiters to {"/"}set DL_display to """DownloadHistory" of plist_fileset downloadItems to property list items of property list item ¬set the plist_file to property list file plist_pathset the plist_path to "~/Library/Safari/Downloads.plist"tell application "Finder" to close front windowon opening folder this_folderLet's get started - these two applescripts are needed to run the show:- (Waiting for "dialog window":) #-2 script immediately on pop-up moves it to the top-right.- These paths are shortened to name plus parent-folder and collected into a "dialog alert".- ... next ordering "System Events" to get all of Safari's "DownloadEntryPath" items.- Thus BOTH attached scripts are launched, #-1 closing the bookmarked "Folder2" window...- The clicked-on toolbar link will open "Folder1" because the called upon "Folder2" is inside.Now, what happens:file:///Path/to/first/Folder1/Folder2 [place link in your favorites bar!]To activate them, you will address a (meaningless) dummy "Folder2" inside "Folder1" thru this bookmark:(context menu: configure folder actions) to a new "Folder1" somewhere deep down on your Mac.First you save these scripts into "~/Library/Scripts/Folder action scripts/" folder, next you attach thema link in Safari's favorites bar:file names, e.g. *.otrkey files) uses applescript to directly ACCESS "Downloads.plist", and placesMy workaround solution for a wider "downloads window" (naturally hiding vital information in longerdisplay alert "Could not make selection (" & errNum & "):" message errMsg as criticalselect every item of selectablesif visible of fileinfo then set end of selectables to posixmatchset fileinfo to info for posixmatch without sizeset posixmatch to matchpath as POSIX filerepeat with matchpath in paragraphs of matchestell me to set matches to do shell script ("/usr/bin/grep -liE " & quoted form of query & " " & quoted form of pwd & "*")if query = "" then returnset query to text returned of drif selection as alias is equal to pwdAlias then set selectables to {}set selectables to selectionselect {}if selection as alias is not equal to pwdAlias then select {}else if button returned of dr is equal to "Select Matches" thenif button returned of dr is equal to "" thenset dr to display dialog "Grep pattern:" default answer "" buttons {"Cancel", "Add Matches", "Select Matches"} default button 3 cancel button 1 with title pwd giving up after 60set pwd to POSIX path of pwdAliasset pwdAlias to (container of pwdAlias) as aliasif not (exists folder pwdAlias) thenset pwdAlias to insertion location as aliasif the button returned of the result is "Single File" thendisplay dialog "Sign all files or one only?" buttons {"Single File", "All Files"} default button 2set fileList to paragraphs of (do shell script "ls " & folderPathNoHD & "*ipa")set folderPathNoHD to temp as textset temp to text items of folderPathNoHDset folderPathNoHD to folderPathEncset folderPath to temp as textset temp to text items of folderPathset {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "/"}set folderPath to folderPathEncset folderPathEnc to text returned of pathChalset pathChal to display dialog "Set IPA Path:" default answer folderPathEnc buttons {"Continue"} default button 1else if the button returned of the result is "Continue" thendisplay dialog "AppleScript IPA Signer written by Leon M'laiel (@Cynostial) 2017 - Licensed via MIT, do not remove Copyright Notice" & return & "All Rights Reserved" buttons {"That's awesome!"} default button 1else if the button returned of the result is "About" thenif the button returned of the result is "Quit" thendisplay dialog "AppleScript IPA Signer" buttons {"Quit", "About", "Continue"} default button 3set folderPathEnc to temp as textset temp to text items of folderPathEncset folderPathEnc to folderPathset folderPath to ((path to desktop folder)) as stringset provPathEnc to temp as textset temp to text items of provPathEncset provPathEnc to provPathset provPath to ("~/Desktop/profile.mobileprovision") as stringset {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "Macintosh HD"}set userPathEnc to temp as textset temp to text items of userPathEncset {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}set userPathEnc to userPathset userPath to ("Macintosh HD:") as stringopen frepeat with f in libfilesset libfiles to used script library filesname of processesclick allowJavaScriptMenuif value of attribute "AXMenuItemMarkChar" of allowJavaScriptMenu is missing value thenset allowJavaScriptMenu to menu item "Allow JavaScript from Apple Events" of menu 1 of menu bar item "Develop" of menu bar 1tell application "System Events" to tell process "Safari"set _path to (path of temporary items folder) as stringevery file of entire contents of folder "Documents" of home whose size > (10 * 1000 * 1000)tell application "Finder"my GrowlNotify("Failed to create image file.")my GrowlNotify((text item 1 of movieItems) & " (" & (text item 2 of movieItems) & ")")tell application "System Events" to set picture of desktop 1 to (finalImg as alias)if exists finalImg thenset name of file jpg to (movieName & ".jpg")my Download(imageFile, jpg)set imageFile to do shell script cmdStringset cmdString to "grep -oE '", "")set movieName to my replaceString(movieName, "<", "")set movieName to my replaceString(movieName, "\"", "")set movieName to my replaceString(movieName, "*", "")set movieName to my replaceString(movieName, "%", "")set movieName to my replaceString(movieName, "?", "")set movieName to my replaceString(movieName, "|", "")set movieName to my replaceString(movieName, ":", "")set movieName to my replaceString(movieName, "\\", "")set movieName to text item 1 of movieItemsset jpg to basePath & ".jpg"set html to basePath & ".html"set basePath to myFolder & "movie-data" & idxset movieItems to every text item of movieInfoset AppleScript's text item delimiters to "|"set movieInfo to item idx of movieItemsset idx to random number from 1 to length of movieItemsset movieItems to paragraphs of cmdResultset cmdResult to do shell script cmdStringset cmdString to "grep -oE '(http:\\/\\/moviebarcode.tumblr.com[^\\\"]*)\\\">([^<]*)' \"" & (POSIX path of f) & "\" | sed -nE \"s/&/\\&/g;s/([^\\\"]+)\\\">(.*) \\(([0-9]+)\\)/\\2|\\3|\\1/p\""my Download("http://moviebarcode.tumblr.com/movie-index", f)if not (exists f) thendelete fif (current date) - (modification date of file f) > 48 * 60 * 60 thenif exists f thenmake new folder at (path to library folder from user domain as string) & "Application Support:" with properties {name:"Movie Barcoder"}if not (exists myFolder) thenset f to myFolder & "moviebarcode-index"set myFolder to (path to library folder from user domain as string) & "Application Support:Movie Barcoder:"end Downloaddo shell script "curl -s -L " & thisUrl & " -o '" & POSIX path of localFile & "'"on Download(thisUrl, localFile)set theText to the tempList as stringset tempList to every text item of theTextend GrowlNotifynotify with name "Desktop Change" title "Desktop Change" description message application name "Movie Barcode Random Desktop"register as application "Movie Barcode Random Desktop" all notifications {"Desktop Change"} default notifications {"Desktop Change"} icon of application "Script Editor"tell application "Growl"on GrowlNotify(message)write text "cd " & thePath & " && clear"tell the last sessionlaunch sessioncreate tab with default profiletell current windowif not createdWindow thenset createdWindow to truecreate window with default profileif (count windows) is 0 thenif it is running thenset createdWindow to falseset thePath to quoted form of POSIX path of (thePath as alias)display dialog "The location of the Finder window \"" & theName & "\" is not a real location (e.g. smart folder, search, network, trash, etc) and cannot opened in iTerm." with icon caution buttons {"OK"} with title "Open iTerm Here..."tell application "Finder" to set theName to name of front windowif not (exists thePath) thendisplay dialog "There are no open Finder windows." with icon caution buttons {"OK"} with title "Open iTerm Here..."set thePath to target of front windowif (count of windows) > 0 thenend makeListreturn theListset AppleScript's text item delimiters to tmpset theList to every text item of theTextset tmp to AppleScript's text item delimiterson makeList(theText, theDelimiter)end openMapsdo shell script "open 'http://maps.apple.com/?saddr=" & saddrText & "&daddr=" & daddrText & "'"set daddrText to item 2 of theListset saddrText to item 1 of theListset theList to makeList(theText, " ")on openMaps(theText)on handle_string(theText) --for LaunchBaropenMaps(theText)set theText to text returned of resultdisplay dialog "出発地と目的地をスペースで区切って入力" default answer "" buttons {"OK"} default button 1on run --for Dialogkeystroke "m" using {command down} -- Minimize windowkeystroke "v" using {command down} -- Past Text from clipboarddo shell script "open -a 'TaskPaper' " & TaskPtell application "TaskPaper"set TaskP to quoted form of POSIX path of TaskPset TaskP to selection as textkey code 15 using shift down & command downclose every windowdisplay dialog "Done"move alias image_path to folder (doc_container as string)set doc_container to (container of (doc_path))beepset image_name to name of image 1 as stringset image_path to file path of image 1 as stringtell picture box irepeat with i from 1 to count of picture boxesset doc_path to file path of document 1end buttonAction:display dialog "The button '" & ((sender's title) as text) & "' was pressed." buttons {"OK"} default button 1 giving up after 2on buttonAction:senderend makeButtonits setAction:(action as text) -- see the following action handlerits setTarget:targetif target is missing value then set target to me -- 'me' can't be used as an optional defaultif action is not missing value thenif tag is not missing value then its setTag:tagif alternate is not missing value then its setAlternateTitle:alternateif transparent is not false then its setTransparent:trueif bordered is not true then its setBordered:falseits setButtonType:buttonType -- NSButtonType enumits setTitle:(title as text)tell (current application's NSButton's alloc's initWithFrame:{origin, dimensions}) -- old styleto makeButton at origin given dimensions:dimensions : {80, 24}, title:title : "Button", buttonType:buttonType : 7, bezelStyle:bezelStyle : 1, bordered:bordered : true, transparent:transparent : false, alternate:alternate : missing value, tag:tag : missing value, action:action : "buttonAction:", target:target : missing valueend makeTextFieldits setDrawsBackground:drawsBackgroundits setSelectable:selectableits setEditable:editableif placeholder is not missing value then its setPlaceholderString:placeholderif stringValue is not missing value then its setStringValue:stringValueif bordered is not false then its setBordered:trueits setBezelStyle:bezelStyleits setBezeled:bezeledif bezeled is not false thenif backgroundColor is not missing value then its setBackgroundColor:backgroundColorif textColor is not missing value then its setTexColor:textColorif textFont is not missing value then its setFont:textFontits setLineBreakMode:lineBreakMode -- 5 = NSLineBreakByTruncatingMiddletell (theClass's alloc()'s initWithFrame:{origin, dimensions})if secure is true then set theClass to current application's NSSecureTextFieldset theClass to current application's NSTextFieldto makeTextField at origin given dimensions:dimensions : {100, 22}, secure:secure : false, editable:editable : true, selectable:selectable : true, bordered:bordered : false, bezeled:bezeled : false, bezelStyle:bezelStyle : missing value, stringValue:stringValue : missing value, placeholder:placeholder : missing value, lineBreakMode:lineBreakMode : 5, textFont:textFont : missing value, textColor:textColor : missing value, backgroundColor:backgroundColor : missing value, drawsBackground:drawsBackground : trueend makeViewControllerreturn viewControllerviewController's view's setFrameSize:{maxWidth + (first item of padding), maxHeight + (last item of padding)}if class of padding is not list then set padding to {padding, padding} -- common width & height padding(viewController's view's addSubview:anItem)set maxHeight to maxHeight + heightif width > maxWidth then set maxWidth to widthset {width, height} to last item of anItem's frame() as listrepeat with anItem in (controls as list)viewController's setView:(current application's NSView's alloc's initWithFrame:{{0, 0}, {0, 0}})set viewController to current application's NSViewController's alloc's initset {maxWidth, maxHeight} to {0, 0}to makeViewController for controls given padding:padding : {20, 20}end makePopoverreturn itits setContentSize:(second item of viewController's view's frame())its setContentViewController:viewControllerif behavior is not 0 then its setBehavior:behavior -- 0 = needs to be closed, 1 = transientif animates is not true then its setAnimates:falsetell current application's NSPopover's alloc's init()to makePopover for viewController given animates:animates : true, behavior:behavior : 1end showPopoverreturn popoverpopover's showRelativeToRect:rect ofView:targetView preferredEdge:edge -- show popoverset popover to makePopover for popoverView given animates:animates, behavior:behavior -- create popoverset popoverView to makeViewController for controls given padding:padding -- create viewController for the controlsto showPopover for targetView given controls:controls : {}, rect:rect : {{0, 0}, {0, 0}}, edge:edge : 0, padding:padding : {20, 20}, animates:animates : true, behavior:behavior : 1use AppleScript version "2.5" -- Sierra (10.12) or later for new enumerationsopen target_folderset target of front Finder window to target_folderif front Finder window exists thenset target_folder to (POSIX file "/Users/IceHe/Pictures")set selectedItem to quoted form of (posix path of (the selection as alias))tell app "Finder"tell application "iTunes" to play playlist "Developing"tell application "AppleScript Editor" to activatetell application "CodeRunner" to activateif closeapps is not in keepapp then quit application closeappsrepeat with closeapps in openappsset keepapp to {""}tell application "System Events" to set openapps to name of every application process whose visible is true and name is not "Finder"return subjectset subject to subject as textset subject to text items of subjecton replaceText(find, replace, subject)set the bounds of the first window to {xAxis, yAxis, windowWidth + xAxis, windowHeight + yAxis}set xAxis to (screenWidth - windowWidth) / 2 as integerset yAxis to (screenHeight - windowHeight) / 2 as integerset properties of current tab to ({URL:"https://song.link/" & trackUrl})make new documentset screenHeight to item 4 of screenResolutionset screenWidth to item 3 of screenResolutionset screenResolution to bounds of window of desktopset windowWidth to 300set windowHeight to 535set trackUrl to theKeyValuePairTrimmedEnd --Yay! we go the link. (sigh.. all that to get this one URL.)set theKeyValuePairTrimmedEnd to ((characters 1 thru -2 of theKeyValuePairTrimmedStart) as string) --@yuuiko trim last 2? characters outset theKeyValuePairTrimmedStart to ((characters 23 thru -1 of theKeyValuePair) as string) --@yuuiko trim first 24? characters outset theKeyValuePair to item thiskeyValuePair of keyValueList --@yuuiko extract the right inforepeat with thiskeyValuePair from 1 to 13 --@yuuiko this seems to control which property it extractsset keyValueList to (every text item in searchResult) as listset AppleScript's text item delimiters to {","}set searchResult to do shell script curlTask --@yuuiko do the shell script itunes websearch and return JSONset curlTask to "curl " & fixedURL --@yuuiko construct shell script command for itunes websearchset fixedURL to replaceText(" ", "%20", theURL) --@yuuiko emove spaces from itunes websearch and replace with "%20"set theURL to "https://itunes.apple.com/search?term=" & name of theCurrentTrackProperties & " " & artist of theCurrentTrackProperties & "&limit=1" --@yuuiko build link of the itunes website search, which only returns the first resultset theCurrentTrackProperties to get properties of current track --@yuuiko Get currently playing song information from iTunesend openDataFolderwrite text "cd " & the quoted form of thePathtell current session of theWindowtell theWindowset theWindow to (create window with default profile)else if exists (processes where name is "iTerm2") thenelse if exists (processes where name is "kitty") thendo script "cd " & quoted form of thePath in theWindowset theWindow to do script ""if exists (processes where name is "Terminal") thenset thePath to do shell script "lsof -p " & theProcess & " | grep -oE \"/.*Library/Developer/CoreSimulator/Devices/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}/\" | grep -v grep | awk '{ print $1 }' | head -n 1"if thePath is equal to "" thenset thePath to do shell script "lsof -p " & theProcess & " | grep -oE \"/.*Library/Developer/CoreSimulator/Devices/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}/data/Containers/Data/Application/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\" | grep -v grep | awk '{ print $1 }' | head -n 1"set theProcess to do shell script "ps ax | grep -E \"/.*Library/Developer/CoreSimulator/Devices/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}/.*/[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\" | grep -v grep | awk '{ print $1 }'"on openDataFolder()openDataFolder()Controller's control(187)set Controller to run script ("script s" & return & (read alias (POSIX file (theFolder & "/lib/controller.scpt")) as «class utf8») & return & "end script " & return & "return s")set theFolder to POSIX path of ((the path to me as text) & "::")display notification "Todos los archivos han sido movidos" with title "Proceso completado"do shell script comandoMoverset comandoMover to "mv " & folderOrigenPOSIXPath & "* " & folderDestinoPOSIXPathset folderDestinoPOSIXPath to (the POSIX path of folderDestino)set folderOrigenPOSIXPath to (the POSIX path of folderOrigen)set folderDestino to (choose folder with prompt "Selecciona la carpeta de destino") as aliasset folderOrigen to (choose folder with prompt "Selecciona la carpeta de origen") as aliasset value of slider 1 of group 1 of tab group 1 of window 1 of process "System Preferences" to 1set value of slider 1 of group 1 of tab group 1 of window 1 of process "System Preferences" to 0.5tell process "System Preferences" to set visible to falsereveal anchor "displaysDisplayTab" of pane id "com.apple.preference.displays"do shell script "sort -o " & quoted form of POSIX path of saveFile & " " & quoted form of POSIX path of saveFileclose access the open_target_filewrite (output as text) to the open_target_file starting at 0set the open_target_file to open for access saveFile with write permissionset saveFile to choose file name with prompt "Save timesheet as:" default name fileNameset AppleScript's text item delimiters to {ASCII character 10}set end of output to outputLine as textset outputLine to (outputDate) & " " & outputTime & "," & outputDuration & ",\"" & (summaryText) & "\""set summaryText to my replace_chars(the summary of myEvent, "\"", "\"\"")set outputDuration to the resulttell (1000000 + (days * 10000 + hours * 100 + minutes)) as string to text 2 thru 3 & ":" & text 4 thru 5 & ":" & text 6 thru 7set outputTime to the resulttell (10000 + (h * 100 + min)) as string to text 2 thru 3 & ":" & text 4 thru 5 & ":00"set outputDate to the resulttell (100000000 + (d * 1000000 + m * 10000 + y)) as string to text 2 thru 3 & "/" & text 4 thru 5 & "/" & text 6 thru 9set {year:y, month:m, day:d, hours:h, minutes:min} to the start date of myEventset minutes to duration mod 60set hours to hours mod 24set days to hours div 24set hours to duration div 60set duration to (((end date of myEvent) - (start date of myEvent)) / 60) as integerrepeat with myEvent in selectedEventsset output to {}set selectedEvents to every event of cal whose start date ≥ startDate and end date < endDateset cal to first calendar whose name is calendar_nameset calendar_name to the first item of calendar_nameif calendar_name is false then returnset calendar_name to choose from list calendarNames with prompt "Select the timesheet calendar: " OK button name "Continue" cancel button name "Cancel"tell application "Calendar" to set calendarNames to the name of every calendarset fileName to (the year of startDate & "-" & (the month of startDate as integer) & "_timesheet.csv") as texttell endDate to set {day, day} to {32, day}copy startDate to endDateset startDate to date ("1 " & selected_month)if selected_month is false then returnset selected_month to choose from list monthList with prompt "Select the month to export: " OK button name "Continue" cancel button name "Cancel"set monthList to {monthsAgo(0), monthsAgo(1), monthsAgo(2), monthsAgo(3), monthsAgo(4), monthsAgo(5)}on replace_chars(this_text, search_string, replacement_string)end monthsAgoreturn (the month of newDate & " " & the year of newDate) as textif m is not 0 then tell newDate to set {day, day} to {32, day}repeat m timesset newDate's year to (newDate's year) + yif m < 0 then set {y, m} to {y - 1, m + 12}set {y, m} to {m div 12, m mod 12}set newDate to current dateset m to -mon monthsAgo(m) -- returns a date formatted for the select boxend fmGUI_ManageDataSources_SavewindowWaitUntil({windowName:manageWindowName, windowNameTest:"does not contain", whichWindow:"any", waitCycleDelaySeconds:waitCycleDelaySeconds, waitCycleMax:waitCycleMax})error "Manage Data Source window wasn't open, so nothing to close." number 1024if notInManageWindowIsError of prefs thenerror "Couldn't save Manage Data Sources - " & errMsg number errNumdelay 1 -- let click register.click (button "OK" of window 1)set manageWindowName to name of window 1if name of window 1 starts with manageWindowNamePrefix thenset waitSaveTotalSeconds to 5 * minutes --secondsset waitCycleDelaySeconds to 5 -- secondsset manageWindowNamePrefix to "Manage External Data Sources"set defaultPrefs to {notInManageWindowIsError:true}on fmGUI_ManageDataSources_Save(prefs)fmGUI_ManageDataSources_Save({})tell application "Script Editor" to activatedelay " & delayOnedo shell script \"eval $(/usr/libexec/path_helper -s); cliclick c:\" & " & coordinateName & "X & \",\" & " & coordinateName & "Yset " & coordinateName & "Y to " & yCoordinate & "set " & coordinateName & "X to " & xCoordinate & "set the clipboard to "set xCoordinate to the clipboarddo shell script "eval $(/usr/libexec/path_helper -s); cliclick p:. | cut -d ',' -f1 | tr -d \"\\n\" | pbcopy"delay delayOneset yCoordinate to the clipboarddo shell script "eval $(/usr/libexec/path_helper -s); cliclick p:. | cut -d ',' -f2 | tr -d \"\\n\" | pbcopy"set coordinateName to the text returned of (display dialog "Name of Coordinate Marker?" default answer "")set pageDelay to 2set delayOne to 0.2move oldMessage to mailbox theMailbox of mailbox theAccountArchiverepeat with oldMessage in oldMessagesmake new mailbox with properties {name:(theAccountArchive & "/" & theMailbox)}if not (exists mailbox theMailbox of mailbox theAccountArchive) thenmake new mailbox with properties {name:theAccountArchive}if not (exists mailbox theAccountArchive) thenset theAccountArchive to ("Archiver" & "-" & theAccount)if (count oldMessages) is greater than 0 thenset oldMessages to ((every message of mailbox theMailbox of account theAccount) whose (date sent < (current date) - theDays * days))repeat with theMailbox in theMailboxesrepeat with theAccount in theAccountsset theDays to 363set theMailboxes to {"INBOX", "Sent Messages"}set theAccounts to {"PledgeMusic"}set the clipboard to simple_sort(the textToSort) as textset the textToSort to splitText(theText, space)set theText to the clipboardend splitTextreturn theTextItemsset theTextItems to every text item of theTextset AppleScript's text item delimiters to theDelimiteron splitText(theText, theDelimiter)end simple_sortreturn the sorted_listset the end of the index_list to the low_item_indexset the end of sorted_list to the low_itemelse if this_item comes before the low_item thenset the low_item_index to iset the low_item to this_itemif the low_item is "" thenset this_item to item i of my_list as textif i is not in the index_list thenrepeat with i from 1 to (number of items in my_list)set the low_item to ""repeat (the number of items in my_list) timesset the sorted_list to {}set the index_list to {}on simple_sort(my_list)addWatermark(anImage)addComment(anImage, textResponse)repeat with anImage in theImagesif hasPS is false thenend addWatermarkon addWatermark(theImage)end addCommentset comment of theFile to textResponseset theFile to (theImagesFolder & theImage) as string as aliason addComment(theImage, textResponse)set textResponse to text returned of resultdisplay dialog "Fill in copyright to add to images" default answer "Copyright (c) 2015 All Rights Reserved" with title "Copyright text" with icon note buttons {"Ok", "Cancel"} default button 1set theImages to the name of every file of theImagesFolderset theImagesFolder to ((path to desktop folder) & "Images" as string as alias)set hasPS to get exists folder ((path to applications folder as string) & "Adobe Photoshop CS6")global theImagesFolderset values_list to values_list & vset d to cell j of selectionrepeat with j from (count of columns of selection as integer + 1) to count large of selectionlog vset v to value of dset d to cell j of row 1 of selectionrepeat with j from 1 to count of columns of selectionlog "-------------"log ("" & (count of columns of selection as integer) & " columns")log ("" & (count of rows of selection as integer) & " rows")tell application "Microsoft Excel"set values_list to {}set alignment of even footer to rightset alignment of odd footer to leftset even footer to "(c) Apple Inc., 2010"set odd footer to "http://www.apple.com/iwork/pages/"set even header to "Pages Features"set odd header to "iWork '09"set different left and right pages to trueset different first page to truetell every section of document 1tell application "Pages"tell application "System Events" to keystroke return using {command down}tell application "Typinator" to quick search "last"else if buttonName = "Show" thendisplay notification "No unique id found" with title "Edit Snippet" subtitle "Error:" sound name "Basso"if errNum = -1719 thenset plain expansion to snipset description to descripset abbreviation to abbrevetell rset r to first rule whose unique id is uidtell cset c to first rule set whose unique id is containeridif buttonName = "OK" thenset {unused, descrip, unused, snip, unused, abbreve} to controlResultsset {buttonName, suppressedState, controlResults} to display enhanced alert "Edit Last Typinator Rule" message "Use this window to edit directly, or click Show to see the snippet in Typinator" as informational alert buttons {"Cancel", "Show", "OK"} giving up after 120 acc view width 400 acc view height theTop acc view controls allControls without suppressionset allControls to {theRule, descripField, descripLabel, snipField, snipLabel, abbreveField, abbreveLabel}set {abbreveField, abbreveLabel, theTop, fieldLeft} to create side labeled field (abbreve) placeholder text abbreve left inset 0 bottom (theTop + 8) total width 400 label text (item 1 of theLabelStrings) field left controlLeftset {snipField, snipLabel, theTop, fieldLeft} to create side labeled field (snip) placeholder text snip left inset 0 bottom (theTop + 8) total width 400 label text (item 2 of theLabelStrings) field left controlLeftset {descripField, descripLabel, theTop, fieldLeft} to create side labeled field (descrip) placeholder text descrip left inset 0 bottom (theTop + 8) total width 400 label text (item 3 of theLabelStrings) field left controlLeftset {theRule, theTop} to create rule (theTop + 12) rule width 400set theTop to 0set controlLeft to maxLabelWidth + 8set maxLabelWidth to max width for labels theLabelStringsset theLabelStrings to {"Abbreviation", "Snippet:", "Description:"}set containerid to unique id of containing setset uid to unique idset descrip to descriptionset abbreve to abbreviationset snip to plain expansiontell lastruleset lastrule to first rule of rule set theSet whose abbreviation is lastexpset theSet to value of variable "Typinator_set"set lastexp to value of variable "Typinator_abbreviation"tell application "Typinator"use script "Dialog Toolkit Plus" --version "1.1.0"delay 3set sound volume to (sound volume + 10)if sound volume is less than 50 thenrepeat 10 timesdelay FIRSTTRACKDURATIONINSECONDSplay track "spotify:track:TRACKURI" in context "spotify:user:USERNAME:playlist:PLAYLISTURI"set the sound volume to 0end ensureObjectReftell codeEnsureObj to ensureObjectRef(someObjectRef)set codeEnsureObj to run script codeEnsureObjtell application "htcLib" to set codeEnsureObj to "script codeEnsureObj " & return & getTextBetween({sourceText:codeEnsureObj, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeEnsureObj"set codeEnsureObj to read file ensureObjPath as texttell application "Finder" to set ensureObjPath to (container of (container of (path to me)) as text) & "text parsing:ensureObjectRef.applescript"on ensureObjectRef(someObjectRef)end fmGUI_MenuItemAvailableerror "Couldn't fmGUI_MenuItemAvailable - " & errMsg number errNumreturn exists menuItemRefif menuItemRef is null then error "menuItemRef not specified" number -1024set menuItemRef to ensureObjectRef(menuItemRef of prefs)set defaultPrefs to {menuItemRef:null, maxTimeoutSec:60, checkFrequencySec:0.5}on fmGUI_MenuItemAvailable(prefs)fmGUI_MenuItemAvailable({menuItemRef:copyMenuItem})set copyMenuItem to menu item "Copy" of menu 1 of menu bar item "Edit" of menu bar 1return aVarset aVar to aVar + 1set aVar to 0if aVar is missing value thenproperty aVar : missing valueend replaceStringerror "Can't replaceString: " & eMsg number eNumreturn theTextset theText to lst as stringset AppleScript's text item delimiters to newStringset lst to every text item of theTextset AppleScript's text item delimiters to oldStringlocal ASTID, theText, oldString, newString, lston replaceString(theText, oldString, newString)end remove_extensionreturn this_nameset this_name to (the reverse of every character of this_name) as stringset this_name to (text (x + 1) thru -1 of this_name)set x to the offset of "." in this_name(the reverse of every character of this_name) as stringset this_name to ¬if this_name contains "." thenon remove_extension(this_name)end encode_textreturn the encoded_textset the encoded_text to (the encoded_text & encode_char(this_char)) as stringset the encoded_text to (the encoded_text & this_char)if this_char is in the acceptable_characters thenrepeat with this_char in this_textset the encoded_text to ""if encode_URL_B is false then set the acceptable_characters to the acceptable_characters & the URL_B_charsif encode_URL_A is false then set the acceptable_characters to the acceptable_characters & the URL_A_charsset the acceptable_characters to the standard_charactersset the URL_B_chars to ".-_:"set the URL_A_chars to "$+!'/?;&@=#%><{}[]"~`^\|*"set the standard_characters to "abcdefghijklmnopqrstuvwxyz0123456789"on encode_text(this_text, encode_URL_A, encode_URL_B)end encode_charreturn ("%" & x & y) as stringset y to item ((ASCII_num mod 16) + 1) of the hex_listset x to item ((ASCII_num div 16) + 1) of the hex_listset the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}set the ASCII_num to (the ASCII number this_char)on encode_char(this_char)end basenamereturn thePathset AppleScript's text item delimiters to ASTIDset thePath to text item nameIndex of thePathset ASTID to AppleScript's text item delimitersset nameIndex to -1set nameIndex to -2if thePath ends with "/" thenon basename(thePath) -- Requires POSIX pathend hazelProcessFilemake new inbox task with properties {name:taskName, note:taskNote}set taskNote to "Created from nvALT: nvalt://find/" & my encode_text(my remove_extension(my basename(p)), true, false)set taskName to (do shell script "n="" & v & ""; echo ${n:6}")repeat with v in ltell application "OmniFocus" to tell document 1set l to paragraphs of (do shell script "grep '\[ x \]' " & quoted form of p)set p to POSIX path of theFileon hazelProcessFile(theFile)end windowWaitUntiltell application "htcLib" to windowWaitUntil(prefs)on windowWaitUntil(prefs)end fmGUI_ObjectClick_OkButtontell application "htcLib" to fmGUI_ObjectClick_OkButton(prefs)on fmGUI_ObjectClick_OkButton(prefs)end fmGUI_NameOfFrontmostWindowtell application "htcLib" to fmGUI_NameOfFrontmostWindow()on fmGUI_NameOfFrontmostWindow()end fmGUI_ManageDb_Saveerror "unable to fmGUI_ManageDB_Save - " & errMsg number errNumdelay 1 -- let normal window come to front.windowWaitUntil({windowName:frontmostWindowName, windowNameTest:"does not contain", whichWindow:"any", waitCycleDelaySeconds:waitCycleDelaySeconds, waitCycleMax:waitCycleMax})error "Manage Database window wasn't open, so nothing to close." number 1024if notInManageDbIsError of prefs thenerror "Couldn't save Manage Database - " & errMsg number errNumdelay 1 -- let click register. will continue below to wait for window to closefmGUI_ObjectClick_OkButton({})if frontmostWindowName starts with manageDbWindowNamePrefix thenset frontmostWindowName to fmGUI_NameOfFrontmostWindow()set waitCycleMax to round (waitSaveTotalSeconds / waitCycleDelaySeconds) rounding downset waitSaveTotalSeconds to 60 * minutes --secondsset waitCycleDelaySeconds to 10 -- secondsset manageDbWindowNamePrefix to "Manage Database for"set defaultPrefs to {notInManageDbIsError:true}on fmGUI_ManageDb_Save(prefs)fmGUI_ManageDb_Save({})set the clipboard to theURLset theURL to the URL of the active tab of window 1say "Hello, world!" -- an audio message using a synthesized computer voicetell application "Spotify" to artist of current track & " - " & name of current trackif state is equal to "playing" thentell application "Spotify" to set state to player state as textend capitalizeStringerror "Can't capitalizeString: " & eMsg number eNumreturn firstChar & otherCharsset otherChars to ""on error number -1728set otherChars to my lowerString(characters 2 thru -1 of theText)set firstChar to my upperString(first character of theText)if theText = "" then return ""local theText, firstChar, otherCharson capitalizeString(theText)make new note with properties {name:mailTitle, body:(the clipboard)}set body of note 1 to {"
" & originalText & "
" & (the clipboard)}set originalText to body of note 1set Today to date string of (current date)set CDate to date string of CreationDateset CreationDate to creation date of note 1if counts > 0 thenset counts to count of every notetell folder "DailyNote"tell default accounttell application "Notes"set mailTitle to dataText & "-DailyNote"set dataText to the result as texttell (current date) to get (its year as integer) & "-" & (its month as integer) & "-" & dayset end of calendarURLs to {calendarName, theURL}set theURL to valuetell text area 1tell scroll area 1set calendarName to value of text field 1keystroke "i" using command downrepeat with i from 1 to 35key code 126 using {option down}keystroke "f" using command downtell process "Calendar"set calendarURLs to {}tell application "Calendar"load_libraries()end load_librariesset TestLib to load script alias (scripts_folder_path & "TestLib.scpt")set scripts_folder_path to path to scripts folder from user domain as texton load_libraries()property TestLib : missing valuereturn selectedTextset selectedText to (do JavaScript jsCode in current tab of window 1)set jsCode to "document.getSelection(); "set the clipboard to urlTextset urlText to "message://" & "%3c" & messageid & "%3e"set messageid to message id of theMessageset theMessage to item 1 of selectedMessagesset selectedMessages to selectiondo shell script strCMDset strCMD to "echo " & quoted form of strLinkHTML & " | textutil -format html -convert rtf -stdin -stdout | pbcopy -Prefer rtf"set strLinkHTML to "" & lstNameTab & ""if length of lstNameTab > 1 thenset lstNameTab to nameset strNameTabUrl to URLtell current tabset strLinkHTML to ""pastemake new document with properties {color space:CMYK}copyset selected of every page item of document 1 to true tell application id "com.adobe.illustrator"set ConnectAnyway to button "Connect Anyway" of window 0 of process "vpndownloader"repeat until (window 1 of process "vpndownloader" exists)keystroke ("521198" as string)click ConnectAnywayset ConnectAnyway to button 2 of window 1 of process "Cisco AnyConnect Secure Mobility Client"repeat until (window 2 of process "Cisco AnyConnect Secure Mobility Client" exists)tell process "Cisco AnyConnect Secure Mobility Client"repeat until (window 1 of process "Cisco AnyConnect Secure Mobility Client" exists)repeat until application "Cisco AnyConnect Secure Mobility Client" is runningtell application "Cisco AnyConnect Secure Mobility Client"delay 0.01 -- Time Between Volume Up Stepsrepeat with i from newVolume to startVolume by 2 -- Fade-In Loopreturn "iTunes is Not Playing"return "iTunes Volume is Less then " & newVolumedelay 0.01 -- Time Between Volume Down Stepsset the sound volume to irepeat with i from currentVolume to newVolume by -2 -- Fade-Out Loopif currentVolume > newVolume then -- is the Volume is Grater Then X ()set currentVolume to the startVolume -- Save the Initial Volume to set startVolume to the sound volume -- Get the Initial Volumeif (player state is playing) then -- Chack if iTunes is Playingtell application "iTunes" -- Set Volume if iTunes is On and Playingtell application "System Events" to if (name of processes) does not contain "iTunes" then return "iTunes is Off" -- Kill Script if iTunes is Offset newVolume to "40"end getThePathreturn theFolderPathset theFolderPath to "~"set theFolderPath to POSIX path of theFolderAliasset theFolderAlias to target of front window as alias as stringon getThePath()end copyFilePathstell application "kitty" to open thePathset thePath to my getThePath()on copyFilePaths()copyFilePaths()key code 51key code 9 using command downdo shell script "pbpaste | sed -e 's/^/[[/' | sed -e 's/$/]]/' | pbcopy"key code 7 using command downtell application "Notational Velocity"end removeDuplicateLinesreturn newListset text item delimiters to oTidset newList to newList as stringset {oTid, text item delimiters} to {text item delimiters, return}if (item j of l) is not in newList then set end of newList to item j of lrepeat with j from 1 to tcset newList to {}if tc = 1 then return tset tc to count lset l to paragraphs of ton removeDuplicateLines(t)end deleteLinesFromTextset AppleScript's text item delimiters to astidset newText to textList's text as textset astid to AppleScript's text item delimitersif (item i of textList contains deletePhrase) then set item i of textList to missing valuerepeat with i from 1 to (count textList)set deletePhrase to "Group"set textList to paragraphs of theTexton deleteLinesFromText(theText)if thisNote is not missing value then set note of i to my removeDuplicateLines(thisNote)if thisNote is not missing value then set note of i to my deleteLinesFromText(thisNote)set thisNote to note of iset fileText to note of irepeat with i in thePeopleelse if the button returned of o is "Remove" thensaveset note of aPerson to "Groups: " & (text items of theGroups as string)set note of aPerson to oldNotes & return & "Groups: " & (theGroups as string)if oldNotes is not missing value thenset AppleScript's text item delimiters to ", "if theGroups is not {} thenset theGroups to theGroups & (name of aGroup)repeat with aGroup in (groups whose people contains aPerson)set theGroups to {}set oldNotes to note of aPersonrepeat with aPerson in thePeopleset thePeople to peopleset thePeople to selectionif the button returned of c is "Selected" thenset c to display dialog "Do you want to change all Contacts or just the selected Contact?" buttons {"All", "Selected"} default button "Selected"if the button returned of o is "Add" thenset o to display dialog "Do you want to add Group(s), remove Group(s) or remove duplicate records from Contacts Notes?" buttons {"Add", "Remove", "Duplicates"} default button "Add"tell application "Contacts"end moveRightset size of iWindow to {primaryScreenRight * 0.58, primaryScreenBottom}set position of iWindow to {primaryScreenRight * 0.42, 0}set {winWidth, winHeight} to sizeset {winLeft, winTop} to positiontell iWindowon moveRight(iWindow)moveRight(iWindow) of meset iWindow to window irepeat with i from 1 to (count of windows)tell application "System Events" to tell application process "Google Chrome"global primaryScreenBottomglobal primaryScreenTopglobal primaryScreenRightglobal primaryScreenLeftset primaryScreenBottom to (primaryScreenTop) + (item 2 of item 2 of primaryScreenFrame)set primaryScreenTop to (item 2 of item 1 of primaryScreenFrame)set primaryScreenRight to (primaryScreenLeft) + (item 1 of item 2 of primaryScreenFrame)set primaryScreenLeft to (item 1 of item 1 of primaryScreenFrame)set primaryScreenFrame to current application's NSScreen's screens()'s firstObject()'s frame()use framework "AppKit"tell application "htcLib" to fmGUI_AppFrontMost()end fmGUI_ScriptDebugger_Closeclick (first button of (first window whose name is "Script Debugger") whose name is not "Copy Script Text")tell process "FileMaker Pro Advanced"on fmGUI_ScriptDebugger_Close()fmGUI_ScriptDebugger_Close()end set_decimal_delimiter_to_dotset this_text to the text_items as stringset the text_items to every text item of this_texton set_decimal_delimiter_to_dot(this_text)make new keyword with properties {name:item k of address_components_list, parents:parents_list as string}set AppleScript's text item delimiters to " "copy item (k - l) of address_components_list to end of parents_listrepeat with l from 1 to (k - 1)set parents_list to {}repeat with k from 1 to count of address_components_listcopy long_name of item j of address_components to beginning of address_components_list --adding them at the beginning, sorts locations from general to specificif item 1 of |types| of item j of address_components is in {"route", "sublocality", "locality", "administrative_area_level_1", "country"} thenrepeat with j from 1 to count of address_componentsset address_components_list to {}set address_components to get address_components of item 1 of results of reverse_geocode_requestset reverse_geocode_request to fetch JSON from ("http://maps.googleapis.com/maps/api/geocode/json?latlng=" & lat & "," & long & "&sensor=false")tell application "JSON Helper"set long to my set_decimal_delimiter_to_dot(long as string)set lat to my set_decimal_delimiter_to_dot(lat as string)display dialog "Please select a geotagged image" with title "GPS data missing" buttons {"Okay"}if (long is missing value) or (lat is missing value) thenset long to get longitudeset lat to get latitudetell item i of imageSeltell library 1repeat with i from 1 to count of imageSelset imageSel to selectiontell application "Aperture"make new folder at folder "Desktop" of folder "smerth" of folder "Users" of folder "Macintosh HD" with properties {name:"My_Super_Folder"}end newLogManagerreturn LogManagerinitWithPath(aLogFilePath)tell LogManagererror errorMessage number errorNumberset errorMessage to "writeToFile(): " & errorMessageerror "Error while writing to file: " & errorMessage number errorNumberclose access file logFilePathwrite (content & (ASCII character 10)) to file logFilePath starting at fileEnd as «class utf8»set fileEnd to (get eof of file logFilePath) + 1set fileEnd to 0error "Could not open file with write permission: " & errorMessage number errorNumberopen for access file logFilePath with write permissionon writeToFile(content)end hfsPathForParentreturn parentPathset parentPath to (text items 1 thru -3 of anyPath as text) & ":"if anyPath does not end with ":" then set anyPath to anyPath & ":"if anyPath does not contain ":" then set anyPath to (POSIX file anyPath) as textset anyPath to userPath & text 2 thru -1 of anyPathset anyPath to userPathif anyPath is "~" thenif userPath ends with "/" then set userPath to text 1 thru -2 of userPath as textif anyPath starts with "~" thenset anyPath to text 2 thru -2 of anyPathif anyPath starts with "'" and anyPath ends with "'" thenset anyPath to anyPath as texton hfsPathForParent(anyPath)end hfsPathreturn aPathset aPath to (POSIX file aPath) as textif aPath does not contain ":" thenset aPath to parentDirectoryPath & item -1 of pathComponentsset parentDirectoryPath to (items 1 thru ((count of items of myPathComponents) - parentDirectoryCount) of myPathComponents) & "" as textset myPathComponents to text items of myPathset parentDirectoryCount to (count of pathComponents) - 1set pathComponents to text items of aPathset text item delimiters to "../"else if aPath starts with "../" thenset aPath to parentDirectoryPath & aPathset text item delimiters to prvDlmtset parentDirectoryPath to (text items 1 thru -2 of myPath) & "" as textset prvDlmt to text item delimitersset myPath to POSIX path of (path to me)set myPath to POSIX path of kScriptPathset aPath to text 3 thru -1 of aPathelse if aPath starts with "./" thenset aPath to userPath & (text 2 thru -1 of aPath)set aPath to userPathif aPath is "~" thenif userPath ends with "/" then set userPath to (text 1 thru -2 of userPath) as textset userPath to POSIX path of (path to home folder)if aPath starts with "~" thenset aPath to "./" & aPathif aPath does not contain "/" and aPath does not contain ":" thenset aPath to text 2 thru -2 of anyPathif aPath starts with "'" and aPath ends with "'" thenset aPath to aPath as texton hfsPath(aPath)end timestamperror "timestamp(): Unknown time format: " & (aFormat as text) number 1return text 1 thru 4 & text 6 thru 7 & text 9 thru 10 & text 12 thru 13 & text 15 thru 16 & text 18 thru 19else if aFormat is 5 thenreturn text 1 thru 4 & text 6 thru 7 & text 9 thru 13 & text 15 thru 16 & text 18 thru 19else if aFormat is 4 thenreturn item (month of aDate) of shortMonths & " " & (day of aDate as text) & " " & text 12 thru -1set shortMonths to {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}else if aFormat is 3 thenreturn text 1 thru 10 & "_" & text 12 thru 13 & "-" & text 15 thru 16 & "-" & text 18 thru 19else if aFormat is 2 thenreturn text 1 thru 10 & " " & text 12 thru -1if aFormat is 1 thentell contentstell aDate as «class isot» as stringon timestamp(aDate as date, aFormat)end archivedo shell script "gzip --suffix '.0.gz' " & quoted form of (POSIX path of logFilePath)set previousArchivePath to archivePathdo shell script "mv " & quoted form of (POSIX path of archivePath) & " " & quoted form of (POSIX path of previousArchivePath)do shell script "rm -f " & quoted form of (POSIX path of archivePath)if i is 9 thenif archiveExists thenset archiveExists to falseon error errorMessageset archiveExists to trueget info for file archivePathset archivePath to parentFolderPath & logFileName & ".log." & (i as text) & ".gz"if i < 0 then exit repeatset i to 9on archive()end _logToFilelog msgif writeToFile(msg) is false thenif fileSize ≥ maxSize then archive()set fileSize to 0on error eMsg number eNumset fileSize to size of (info for file logFilePath)on _logToFile(msg)end logWarningset fullMessage to ts & " Warning! " & msgon logWarning(msg)end logErrorset fullMessage to ts & " [Error] " & fnc & ": " & msg & " (" & (num as text) & ")"on logError(fnc, msg, num)end logMessage_logToFile(fullMessage)set fullMessage to ts & " " & msgset ts to timestamp(current date, 1)on logMessage(msg)end initWithPathset AppleScript's text item delimiters to prvDlmtset logFileName to text item 1 of logFileNameset AppleScript's text item delimiters to "."set logFileName to text item -1 of logFilePathset prvDlmt to AppleScript's text item delimitersset parentFolderPath to hfsPathForParent(logFilePath)set logFilePath to hfsPath(aPath)on initWithPath(aPath)property maxSize : 1048576property logFileName : missing valueproperty parentFolderPath : missing valueproperty logFilePath : missing valuescript LogManageron newLogManager(aLogFilePath)logWarning("This is an urgent message")logError("on run", "Some error message", 1234)logMessage("Hello World " & (random number from 1000 to 9999))tell Loggerset Logger to newLogManager("~/Desktop/AppleScript Log Manager Demo.log")set value of cell j of emailsTarget to emailif usernameSource is equal to usernameTarget thenset usernameTarget to value of cell j of usernamesTargetrepeat with j from 2 to count of cells of usernamesTargetset email to value of cell i of emailsSourceset usernameSource to value of cell i of usernamesSourcerepeat with i from 2 to count of cells of usernamesSourceset usernamesTarget to column "H"set emailsTarget to column "I"tell document targetDocset usernamesSource to column "D"set emailsSource to column "C"tell document sourceDocset targetDoc to item 1 of targetDocset sourceDoc to item 1 of sourceDocset targetDoc to choose from list listOfDocs with prompt "Choose Target Doc"set sourceDoc to choose from list listOfDocs with prompt "Choose Source Doc"set listOfDocs to name of documents"Hello, AppleScript World!"tell front window to set target to thePathopen thePathif (count of windows) = 0 thenset t to ((path to application support from user domain) as string)open thefileset thefile to path of document 1 of window 1end throwErrorerror errMsg number 1000on throwError(errMsg)end getKeychainItemif result is not "SecKeychainSearchCopyNext:" then return (text 2 thru -2 of result)do shell script "security 2>&1 >/dev/null find-generic-password -gl " & quoted form of keychainItemName & " | awk '{print $2}'"on getKeychainItem(keychainItemName)end readPlistAt:return theDict as recordset theDict to current application's NSDictionary's dictionaryWithContentsOfFile:thePathset thePath to thePath's stringByExpandingTildeInPath()set thePath to current application's NSString's stringWithString:thePathon readPlistAt:thePatherror errMessage number errNumon error errMessage number errNumwrite theData to fileReference as «class utf8»set eof fileReference to 0set fileReference to open for access theFile with write permissionset theFile to makeFileReference(theFile)on writeToFile(theFile, theData)end pathExistsPOSIX file thePath as aliaselse if thePath contains "/" thenalias thePathif thePath contains ":" thenif class of thePath is alias then return trueif thePath is missing value or my isEmpty(thePath) then return falselog "checking for path"on pathExists(thePath)end folderExistsreturn (class of (disk item theFolder) is folder)if my pathExists(theFolder) thenon folderExists(theFolder)return (class of (disk item theFile) is file)if my pathExists(theFile) thenlog "checking for file"on fileExists(theFile)end readFromFileAsreturn missing valueclose access file theFilereturn theDataset theData to read fileReference as theClassset fileReference to open for access theFilelocal fileReference, fileSpecon readFromFileAs(theFile, theClass)end makeFileReferencereturn theFileset theFile to alias theFileelse if class of theFile is string thenset theFile to POSIX file ((POSIX path of (path to home folder)) & text 2 thru -1 of theFile)else if class of theFile is string and character 1 of theFile is "~" thenset theFile to POSIX file theFileif class of theFile is string and character 1 of theFile is "/" thenon makeFileReference(theFile)end sortAList:return theArray as listset theArray to theArray's sortedArrayUsingSelector:"localizedStandardCompare:"set theArray to current application's NSArray's arrayWithArray:theListon sortAList:theListend ls__makeParasFromListreturn textListset textList to textList & return & item n of this_listset textList to item n of this_listif textList = "" thenrepeat with n from 1 to count of this_listset textList to ""on ls__makeParasFromList(this_list)end ls__countMatchesInListreturn the match_counterset the match_counter to the match_counter + 1if item i of this_list contains this_item then ¬set the match_counter to 0on ls__countMatchesInList(this_list, this_item)end list_positionif item i of this_list is this_item then return irepeat with i from 1 to the count of this_liston list_position(this_item, this_list)end checkForExistingTabset thetab to current tabif URLfound is false thenif URLfound then exit repeatset thetab to tab nset URLfound to trueif item n of URLs is theURL thenrepeat with n from 1 to (count of URLs)if URLs contains theURL thenset theURL to item q of theURLsrepeat with q from 1 to count of theURLsset URLfound to falseset URLs to URL of every tabif class of theURLs is text then set theURLs to theURLs as liston checkForExistingTab(theURLs)end waitForSafariToLoaderror "Script timed out, Safari didn't load" number -100if failsafe = 300 thenset failsafe to failsafe + 1set tabText to text of thetabrepeat until tabText contains SearchTextif thetab is missing value then set thetab to current tabtell front windowset failsafe to 0set tabText to ""on waitForSafariToLoad(SearchText, thetab)end doJava:onType:withIdentifier:withElementNum:withSetValue:inTab:do JavaScript theJavareturn inputset input to do JavaScript theJavaif theAction = "get" thentell thetabif thetab is missing value then set thetab to front documentset theJava to "document." & getBy & "('" & theID & "')" & theJavaEndelse if theAction = "force" thenelse if theAction = "submit" thenset theJavaEnd to theJavaEnd & ".value ='" & theValue & "';"else if theAction = "set" thenset theJavaEnd to theJavaEnd & ".innerHTML;"else if theAction = "get" thenset theJavaEnd to theJavaEnd & ".click();"if theAction = "click" thenset theJavaEnd to "[" & num & "]"set getBy to "getElementsBy" & theTypeset theType to "TagName"else if theType = "tag" thenset theType to "Name"else if theType = "name" thenset theType to "ClassName"if theType = "class" thenset theJavaEnd to ""set getBy to "getElementById"if theType = "id" thenon doJava:theAction onType:theType withIdentifier:theID withElementNum:num withSetValue:theValue inTab:thetabend escBshPthreturn theStringset theString to SearchandReplace(theString, "(", "\\( ")set theString to SearchandReplace(theString, ")", "\\) ")set theString to SearchandReplace(theString, " ", "\\ ")on escBshPth(theString)end encodeHFStoPosixreturn my SearchandReplace(theString, ":", "/")if theString contains "~/" then set theString to my SearchandReplace(theString, (path to home folder as string), "~/")on encodeHFStoPosix(theString)end encodePosixtoHFSreturn my SearchandReplace(theString, "/", ":")if theString contains "\"" then set theString to my SearchandReplace(theString, "\"", "")if theString contains "\\" then set theString to my SearchandReplace(theString, "\\", "")if theString starts with "/Users" then set theString to "Macintosh HD" & theStringif theString contains "~" then set theString to my SearchandReplace(theString, "~", path to home folder as string)on encodePosixtoHFS(theString)end isEmptyreturn length of str is 0if str is missing value then return trueon isEmpty(str)end TrimWhitespacereturn aStringset aString to ((NSString's stringWithString:sourceString)'s stringByTrimmingCharactersInSet:(current application's NSCharacterSet's whitespaceAndNewlineCharacterSet())) as texton TrimWhitespace(sourceString)end SearchWithRegExset end of theResult to (theNSString's substringWithRange:theRange) as stringset theRange to (oneFind's rangeAtIndex:n)set end of theResult to missing valueif (oneFind's numberOfRanges()) as integer < (n + 1) thenset oneFind to (item i of theFinds)repeat with i from 1 to count of items of theFindsset theResult to {} -- we will add to thisset theFinds to theRegEx's matchesInString:theNSString options:0 range:{location:0, |length|:theNSString's |length|()}set theRegEx to current application's NSRegularExpression's regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value)set theOptions to ((current application's NSRegularExpressionDotMatchesLineSeparators) as integer) + ((current application's NSRegularExpressionAnchorsMatchLines) as integer)set theNSString to NSString's stringWithString:theStringon SearchWithRegEx(thePattern, theString, n)end SearchandReplacereturn theString as textset theString to theString's stringByReplacingOccurrencesOfString:replaceThis withString:withThatset theString to NSString's stringWithString:sourceTexton SearchandReplace(sourceText, replaceThis, withThat)end extractBetweenreturn beginningToEndset beginningToEnd to text of text item 1 of endItemsset AppleScript's text item delimiters to endTextset endItems to text of text item -1 of SearchTextset AppleScript's text item delimiters to startTexton extractBetween(SearchText, startText, endText)end joinset theResult to theString as texton join(theString, theSeparator)return theResultset AppleScript's text item delimiters to saveTIDset theResult to text items of theStringset AppleScript's text item delimiters to theSeparatorset saveTID to AppleScript's text item delimiterslocal saveTID, theResulton split(theString, theSeparator)end capFirstWordset newText to (char1 & (characters 2 thru end of inString)) as stringif char1 is in comparisonString then set char1 to transformText(char1, "upper")set comparisonString to "abcdefghijklmnopqrstuvwxyz"set char1 to first character of inStringon capFirstWord(inString)end transformTextreturn (adjustedString as text)set the adjustedString to sourceString's capitalizedString()set the adjustedString to sourceString's lowercaseString()else if the caseIndicator is "lower" thenset the adjustedString to sourceString's uppercaseString()if the caseIndicator is "upper" thenset the sourceString to NSString's stringWithString:inStringon transformText(inString, caseIndicator)property vt : character id 11property lf : character id 10property cr : character id 13property version : "1.0.0"property id : "com.kfunderburg.library.kevinsScriptingLibrary"property name : "Kevin's Scripting Library"property NSString : a reference to current application's NSStringset kb to std's import("keyboard")'s new()set cp to std's import("clipboard")'s new()set textUtil to std's import("string")set uni to std's import("unicodes")set syseve to std's import("system-events")set fileUtil to std's import("file")set retry to std's import("retry")set logger to std's import("logger")'s new("atom")set RESERVED_DOC_NAMES to {"Settings", "Project", "Project Find Results", "Welcome Guide"}end _extractDocPathByHotkeydocPathset docPath to cp's extract(GetFromClipboard)kb's pressControlShiftKey("c")script GetFromClipboardon _extractDocPathByHotkey()end cleanUprepeat while running of application "Atom" is trueif running of application "Atom" is true then tell application "Atom" to quitif not running of application "Atom" then returnon cleanUp()end closeAllTabsperform action "AXPress" of menu item "Close All Tabs" of menu 1 of menu bar item "File" of menu bar 1activate application "Atom"on closeAllTabs()end getCurrentResourcePathtextUtil's replace(docPath, expandedFolderPath & "/", "")set expandedFolderPath to textUtil's replace(folderPath, "~", "/Users/" & std's getUsername())set folderPath to last item of titleTokensif docPath is missing value then return missing valueset docPath to getCurrentFilePath()on getCurrentResourcePath()end getCurrentBaseFilenamefirstTokenif firstToken is "" or RESERVED_DOC_NAMES contains firstToken then return missing valueset firstToken to first item of filenameTokenson getCurrentBaseFilename()end getCurrentFileExtensionlast item of filenameTokensif the (count of filenameTokens) is 1 then return missing valueset filenameTokens to textUtil's split(docName, ".")if docName is missing value then return missing valueset docName to getCurrentDocumentName()on getCurrentFileExtension()end closeFrontTabclick menu item "Close Tab" of menu 1 of menu bar item "File" of menu bar 1if running of application "Atom" is false then returnon closeFrontTab()end getCurrentFilePathtextUtil's decodeUrl(textUtil's stringAfter(filePath, "file://"))set filePath to get value of attribute "AXDocument" of front windowif RESERVED_DOC_NAMES contains firstItemInTitle then return missing valueif firstItemInTitle is "Project" then return _extractDocPathByHotkey()set firstItemInTitle to first item of titleTokensif the number of titleTokens is 1 then return missing valueset titleTokens to textUtil's split(windowTitle, uni's SEPARATOR)set windowTitle to name of front windowon getCurrentFilePath()end getCurrentDocumentNamefileUtil's getBaseFilename(docPath)set docPath to _extractDocPathByHotkey()if docNameFromTitle is not "Project" then return docNameFromTitleset docNameFromTitle to first item of tokensset tokens to textUtil's split(windowTitle, uni's SEPARATOR)set windowTitle to name of window 1if (count of windows) is 0 then return missing valuetell application "System Events" to tell process "Atom"if running of application "Atom" is false then return missing valueon getCurrentDocumentName()end openFileopen location "atom://core/open/file?filename=" & textUtil's encodeUrl(pathUrl)set pathUrl to posixPathon openFile(posixPath)script AtomInstancesut's closeFrontTab()logger's infof("Current Base Filename: [{}]", sut's getCurrentBaseFilename())logger's infof("Current Resource Path: [{}]", sut's getCurrentResourcePath())logger's infof("Current File Extension: [{}]", sut's getCurrentFileExtension())logger's infof("Current File Path: [{}]", sut's getCurrentFilePath())logger's infof("Current Document Name: [{}]", sut's getCurrentDocumentName())sut's openFile(sampleNoteFilePath)logger's infof("Note Path: [{}]", sampleNoteFilePath)set sampleNoteFilePath to configSystem's getValue("AppleScript Core Project Path") & "/apps/3rd-party/Atom/1.60.0/sample.txt"Manual: Close Front TabManual: Document Info (sample.txt, no file, search result, nav bar focused, Settings)Manual: Load File (App Open, Not Running, Already Loaded)set configSystem to std's import("config")'s new("system")set thisCaseId to "atom-spotCheck"global RESERVED_DOC_NAMESglobal std, retry, fileUtil, textUtil, cp, kb, uniend handle_stringdisplay in large type theMessage with title theTitleset theTitle to (fromAmount of parsedData & " " & fromCurrency of parsedData & " = ") as textset theMessage to toAmount & " " & toCurrency of parsedDatatell application "LaunchBar"if areCurrenciesGiven of parsedData thenset toAmount to my currency_convert(fromAmount of parsedData, fromCurrency of parsedData, toCurrency of parsedData, areCurrenciesGiven of parsedData)set parsedData to my parse_input_string(theString)on handle_string(theString)end currency_convertopen location theURLreturn text item 1 of (do shell script theShellScript)set theShellScript to "curl " & quoted form of theURL & " 2> /dev/null | xmllint --html --xpath \"//div[@id='currency_converter_result']/span/text()\" - 2> /dev/null"if currenciesGiven thenset theURL to "http://www.google.com/finance/converter?a=" & fromAmount & "&from=" & fromCurrency & "&to=" & toCurrencyon currency_convert(fromAmount, fromCurrency, toCurrency, currenciesGiven)end parse_input_stringreturn {fromAmount:theFromAmount, fromCurrency:theFromCurrency, toCurrency:theToCurrency, areCurrenciesGiven:currenciesGiven}set currenciesGiven to falseset theToCurrency to "EUR"set theFromCurrency to "USD"set currenciesGiven to trueset theToCurrency to text item -1 of theString as textset theFromCurrency to text item 2 of theString as textif length of text items of theString is greater than 1 thenset theFromAmount to text item 1 of theString as texton parse_input_string(theString)set dthole_folders to getHomeFolders()set all_disks to getAllDisks()end getHomeFoldersdthole_folderslog "Dthole (Object): " & toString(dthole)set dthole_folders to folders of dtholeset dthole to folder "dthole" of folder "Users" of disk "Macintosh HD"on getHomeFolders()end getAllDisksdlog "Alias: " & aaslog "Disks: " & toString(d)set aas to disk "Macintosh HD"set d to get every diskon getAllDisks()end dlogdo shell script "printf '%s\\n' " & quoted form of (prefixDateTime & txtCombined) & " >> \"" & fpath & "\""if fpath starts with "~/" then set fpath to "$HOME/" & text 3 thru -1 of fpathset fpath to contents of logTargetelse # assumed to be a POSIX file path to *append* to.do shell script "logger -t " & quoted form of ("AS: " & (name of me)) & " " & quoted form of txtCombinedelse if contents of logTarget is "syslog" thendisplay alert prefixTime & txtCombinedelse if contents of logTarget is "alert" thenlog prefixTime & txtCombinedif contents of logTarget is "log" thenrepeat with logTarget in DLOG_TARGETSset prefixDateTime to "[" & short date string of (current date) & " " & text 2 thru -1 of prefixTimeset prefixTime to "[" & time string of (current date) & "] "set txtCombined to lst as stringset {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {" "}} # 'set lst to lst & txtset txt to prefix & txtset {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} # 'repeat with anyObj in anyObjOrListOfObjectsset lst to {}local lst, i, txt, errMsg, orgTids, oName, oId, prefix, logTarget, txtCombined, prefixTime, prefixDateTimeif class of anyObjOrListOfObjects is not list then set anyObjOrListOfObjects to {anyObjOrListOfObjects}if length of DLOG_TARGETS is 0 then returnglobal DLOG_TARGETSon dlog(anyObjOrListOfObjects)end toStringreturn prefix & txtset prefix to prefix & "] "if oId is not missing value then set prefix to prefix & " id=" & oIdset oId to id of anyObjif oName is not missing value then set prefix to prefix & " name=\"" & oName & "\""set oName to name of anyObjset oId to ""set oName to ""set prefix to "[" & class of anyObjif class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value thenset prefix to ""if txt is not "" then exit repeatset txt to do shell script "egrep -o '\\{.*\\}' <<< " & quoted form of errMsgon error errMsgset txt to properties of anyObj as stringset txt to anyObj as stringset AppleScript's text item delimiters to orgTids # 'set txt to ("{" & anyObj as string) & "}"set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}}if class of anyObj is list thenif i is 1 thenrepeat with i from 1 to 2set txt to ""local i, txt, errMsg, orgTids, oName, oId, prefixon toString(anyObj)display dialog "Battery is " & batteryPercent & " charged." buttons {"OK"} default button "OK"set batteryPercent to do shell script "pmset -g batt | awk '/InternalBattery/ { sub(/;/, \"\"); print $2 }'"end resubahz3Yaazah2see"puts raw_text.gsub(%r{" & regex & "},%Q{" & substitute & "})voh2veemeecaoZ" & theText & "raw_text = < '" & logFilepath & "'"set partFilepath to (characters 1 thru -5 of origFilepath as string) & " " & partDuplicate & ".hb"set partDuplicate to partDuplicate + 1repeat while fileExists(POSIX file partFilepath)set partFilepath to (characters 1 thru -5 of origFilepath as string) & ".hb"set partDuplicate to 1set logFilepath to (characters 1 thru -5 of origFilepath as string) & ".log"tell application "Finder" to set origFilepath to POSIX path of (currentFile as alias)tell application "Finder" to set label index of currentFile to 7if label index of currentFile is not 0 then exit repeatset currentFile to (item i of allFiles)repeat with i from 1 to number of items in allFilesset allFiles to every file of entire contents of (POSIX file torrentsLocation as alias) whose ((name extension is "avi" or name extension is "mkv") and label index is 0)if isRunning = false thenset isRunning to segmentedActivityLog contains "HandBrakeCLI"set segmentedActivityLog to (every word of activityLog)set activityLog to do shell script "/bin/ps -ax"end replaceTextset text item delimiters of AppleScript to prevTIDsset someText to "" & someTextset text item delimiters of AppleScript to replaceset someText to text items of someTextset text item delimiters of AppleScript to findset prevTIDs to text item delimiters of AppleScripton replaceText(find, replace, someText)end fileExistsif not (exists posixFile as alias) then return falseon fileExists(posixFile)set handbrakeLocation to "/Applications/Utilities/HandBrakeCLI"set torrentsLocation to "/Users/Jelly/Torrents"make new inbox task with properties {name:theTitle, note:theUrl}tell default documentset theTitle to the title of theNoteset theUrl to the note link of theNoterepeat with theNote in theNotesset theNotes to the selectionrepeat until isSynchronizing is falselog "ok"assert_eq(json's encode(dict2), "{\"a\": 13, \"b\": [2, \"other\", {\"foo\": \"bar\"}]}")set dict2 to json's createDictWith({{"a", 13}, {"b", {2, "other", dict}}})assert_eq(json's encode(dict), "{\"foo\": \"bar\"}")set dict to json's createDictWith({{"foo", "bar"}})assert_eq(json's encode(json's createDict()), "{}")assert_eq(json's encode({1, 2, 3}), "[1, 2, 3]")assert_eq(json's encode("\\"), "\"\\\\\"")assert_eq(json's encode("\"bar\""), "\"\\\"bar\\\"\"")assert_eq(json's encode("u" & "̈"), "\"u\\u0308\"")assert_eq(json's encode("ș"), "\"\\u0219\"")assert_eq(json's encode("\n"), "\"\\u000a\"")assert_eq(json's encode(""), "\"\"")assert_eq(json's encode("foo"), "\"foo\"")assert_eq(json's encode(false), "false")assert_eq(json's encode(true), "true")assert_eq(json's encode(0), "0")assert_eq(json's encode(1), "1")assert_eq(json's hex4(65537), "0001")assert_eq(json's hex4(65536), "0000")assert_eq(json's hex4(65535), "ffff")assert_eq(json's hex4(65534), "fffe")assert_eq(json's hex4(2*16), "0020")assert_eq(json's hex4(11), "000b")assert_eq(json's hex4(1), "0001")assert_eq(json's hex4(0), "0000")error "values not equal:" & aq & " != " & bqset bq to quoted form of b as textset aq to quoted form of a as textif not a = b thenon assert_eq(a, b)set json to load script (json_path as alias)set json_path to file "json.scpt" of folder of (path to me)log {1, 2} ends with 2 -- truelog "XXXXXXX"log 2 is in {1, 2}log {name:"Matt", age:"51"} contains {age:"51", name:"Matt"} -- truelog {name:"Matt", age:"51"} contains {name:"Matt"} -- truelog {1, 2, 3} contains {1, 3} -- false -- lists are orderd, and items must be compared in sequencelog {1, 2, 3} contains {2, 3} -- truelog {1, 2} contains 2 -- truetell application "Sublime Text" to activatetell process "Sublime Text" to click menu item "New Window" in menu "File" of menu bar 1if appIsRunning("Sublime Text") thenend appIsRunningtell application "System Events" to (name of processes) contains appNameon appIsRunning(appName)return getCurrentFrameSA(winPosX, winPosY)set winPosY to item 2 of winPosset winPosX to item 1 of winPosset winPos to position of topWindowset topWindow to window 1set topWindow to item 1 of (every window whose focused is true)tell process appNameset appName to item 1 of pListset pList to name of every process whose frontmost is trueend getCurrentFrameSAreturn getCurrentFrame(x, y, vframes)set vframes to gf's getAllVisibleFrames()set gf to load script file getFrameScptset getFrameScpt to scriptPath & "getFrame.scpt"on getCurrentFrameSA(x, y)end getCurrentFramereturn 0return {pos, i, vframes}if x ≥ gf's getFrameOriginX(f) and x ≤ (gf's getFrameOriginX(f)) + (gf's getFrameWidth(f)) and y ≥ gf's getFrameOriginY(f) and y ≤ (gf's getFrameOriginY(f)) + (gf's getFrameHeight(f)) thenset f to item i of framesrepeat with i from 1 to frames's lengthset frames to rb's getKeyValue(vframes, pos)set pos to item i of positionsrepeat with i from 1 to length of positionsset positions to {"main_frames", "left_frames", "right_frames", "top_frames", "bottom_frames"}set gf to load script file getframeset getframe to scriptPath & "getFrame.scpt"set rb to load script file recordlibset recordlib to scriptPath & "recordlib.scpt"on getCurrentFrame(x, y, vframes)make new document with properties {name:"Word Frequencies", text:the_report}set the_report to the_report_list as textset end of the_report_list to quote & the_word of word_info & quote & " appears " & the_count of word_info & " times."repeat with word_info in word_frequency_listset the_report_list to {}set the_count of word_info to (the_count of word_info) + 1set end of word_frequency_list to word_infoset word_info to {the_word:the_current_word, the_count:1}if word_info = missing value thenset word_info to contents of record_refif the_word of record_ref = the_current_word thenrepeat with record_ref in word_frequency_listset word_info to missing valueset the_current_word to contents of the_word_refrepeat with the_word_ref in word_listset word_frequency_list to {}set word_list to every word of document 1tell application "TextEdit"end getActiveAppreturn name of activeApptell application "System Events" to set activeApp to first process where it is frontmoston getActiveApp()return "{\"text\":\"🖥\",\"font_size\": 15}"else if handoffDevice contains "Mac" thenreturn "{\"text\":\"⌚️\",\"font_size\": 15}"else if handoffDevice contains "watch" thenreturn "{\"text\":\"⬛️\",\"font_size\": 15}"else if handoffDevice contains "iPad" thenreturn "{\"text\":\"📱\",\"font_size\": 15}"if handoffDevice contains "iPhone" thenelse if handoffDevice is not missing value thenreturn "{\"text\":\"" & badgeNumber & "\",\"font_size\": 15}"if application "WhatsApp" is running thenif badgeNumber is not missing value and handoffDevice is missing value thenset handoffDevice to get_dock_badge_for ExactNameOfYourApp & "-handoff" update_interval 3set badgeNumber to get_dock_badge_for ExactNameOfYourApp update_interval 3tell application ExactNameOfYourAppif LCL_DNDStatus is "OFF" and activeApp is not equal to ExactNameOfYourApp thenset activeApp to my getActiveApp()tell application "BetterTouchTool" to set LCL_DNDStatus to get_string_variable "DNDStatus"set ExactNameOfYourApp to "The App Name"editMacro uidset uid to m's idset m to first macro whose enabled is true and name is mnameset mname to text 3 thru length of (item 2 of kl's split(p, "‚"))set p to paragraph -i of theLogrepeat until p contains "Execute macro"set theLog to kl's readFromFileAs(logpath, text)set i to 0set p to ""tell application "Keyboard Maestro"set logpath to POSIX file "/Users/kevinfunderburg/Library/Logs/Keyboard Maestro/Engine.log"display dialog "not found"if findRes's found is false thenset findRes to find (text returned of res) options searchOpt with selecting matchset oldSearchString to text returned of resset searchOpt's starting at top to trueset searchOpt to get current search optionsif button returned of res is "OK" thenset res to display dialog "search current document for?" default answer oldSearchStringproperty oldSearchString : "fish"display dialog "ONE STAR!!!"repeat 5 timesrun sset s to theClosure()end theClosurereturn inner of outerset x to x + 1script innerproperty x : 0script outeron theClosure()set position to {100, 100}tell application "System Events" to tell process "Terminal"set position to {100, 80}tell application "System Events" to tell process "Sublime Text"set size to {960, 600}set position to {400, 200}tell application "System Events" to tell process "KeePassXC"set size to {1200, 800}set position to {160, 60}tell application "System Events" to tell process "Brave Browser"set size to {960, 900}set position to {0, 0}tell window 1tell application "System Events" to tell process "iTerm2"keystroke "7" using {command down, control down}repeat 2 timesdisplay notification "It's a funky reggae party!!!" with title "Rogue Program Says" subtitle "What's that noise nearby?" sound name "blow"end replaceCharson replaceChars(this_text, search_string, replacement_string)end addToListif itemName does not start with "~" thencopy itemName to end of listNameif itemName is not equal to sinNamespace thenif listName does not contain itemName and itemName is not equal to sinNamespace thenset itemName to itemName & " "copy namespaceItem to end of listNamecopy fixedName to end of definecopy namespaceItem to end of defineif define does not contain itemName thenelse if defineGroup contains itemName thencopy fixedName to end of repeatercopy namespaceItem to end of repeaterif repeater does not contain itemName thenelse if repeatGroup contains itemName thencopy fixedName to end of condcopy namespaceItem to end of condif cond does not contain itemName thenelse if condGroup contains itemName thencopy fixedName to end of specialcopy namespaceItem to end of specialif special does not contain itemName thenif specialGroup contains itemName thenset fixedName to itemName & " "if namespaceItem is not equal to dblNamespace thenif listName does not contain namespaceItem and namespaceItem is not equal to sinNamespace thenset namespaceItem to namespace & itemName & " "if badStuff does not contain itemName thenif itemName does not start with "^" thenset dblNamespace to namespace & namespace & " " as textset sinNamespace to namespace & " " as textset namespace to my replaceChars(namespace, " ", "")set itemName to my replaceChars(itemName, "if itemName is not "" thenon addToList(itemName, listName, namespace)end parseSynreturn newCollcopy spaced to end of newCollset spaced to l & " "repeat with l in collset newColl to {}copy nameTar to end of collcopy target to end of collif (count of alert) is 0 thenif (count of found) is 0 thencopy target to end of foundif target is ex thenset ex to text item k of excludesrepeat with k from 1 to excludeCountif type is in manyTypes thencopy 1 to end of alertif target contains namespaces thenset alert to {}set nameTar to namespaces & targetset target to text item j of oneItemrepeat with j from 2 to theCountset theCount to count of text items in oneItemset excludeCount to count of text items in excludesset oneItem to text item i of wootrepeat with i from 1 to counterset manyTypes to {"clojureConstant", "clojureBoolean", "clojureSpecial", "clojureException"} as textset type to word 3 of startingset namespaces to "clojure.core"set counter to count of text items in wootset woot to text 1 thru ((offset of "syntax keyword " in stuff) - 1) of stuffset stuff to text item 2 of infoset AppleScript's text item delimiters to startingon parseSyn(info, coll, starting)tell application "Finder" to display dialog "all done!"close access the fileReferencewrite theText to fileReferenceset the fileReference to open for access file buildFile with write permissionset buildFile to buildFile as textset buildFile to make new file at buildFolder with properties {name:outputName}set buildFolder to (choose folder with prompt "Please select a location for the scan output") as aliasset outputName to text returned of outputQueryset outputQuery to display dialog "Enter the name of the output file here: " default answer "" & "cljs.vim"" & funcText" & "" & macroText & "" & reservedText & "" & defineText & "" & repeaterText & "" & condText & "" & exceptionText & "set theText to specialText & "set funcText to "syntax keyword cljsFunc " & funcs as textset macroText to "syntax keyword cljsMacro " & macros as textset reservedText to "syntax keyword cljsReserved " & jsReserved as textset defineText to "syntax keyword cljsDefine " & define as textset repeaterText to "syntax keyword cljsRepeat " & repeater as textset condText to "syntax keyword cljsCond " & cond as textset exceptionText to "syntax keyword cljsException " & exception as textset specialText to "syntax keyword cljsSpecial " & special as textset boolText to "syntax keyword cljsBoolean " & bool as textset constText to "syntax keyword cljsConstants " & const as textset addition to my addToList(newTag, macros, namespaces)set addition to my addToList(newMacro, macros, namespaces)if text of defs = "(defmacro " thenif namespaces does not contain newTag thenset inputReference to open for access cljCoreset AppleScript's text item delimiters to oldTIDset addition to my addToList(newTag, funcs, namespaces)else if newTag does not start with "*" thenset addition to my addToList(newMacro, funcs, namespaces)if newMacro does not start with "*" thenset newMacro to second text item of anitemif newTag starts with "^" thencopy newTag to end of namespacesset newTag to newTag & "/"", "")set newTag to my replaceChars(newTag, "if text of defs = "(ns " thenset newTag to first text item of anitemset AppleScript's text item delimiters to " "repeat with anitem in foundcopy oneText to end of foundset oneText to text item i of fileContentsrepeat with i from 2 to counterset counter to count of text items in fileContentsclose access inputReferenceset fileContents to read inputReferenceset inputReference to open for access cljsCoreset AppleScript's text item delimiters to defsset oldTID to AppleScript's text item delimitersset found to {}repeat with defs in cljsDefineset tags to {}set namespaces to {}set cljsCore to file ("core.cljs") in cljsFol as aliasif (exists file ("core.cljs") in cljsFol) thenset cljFol to folder ("cljs") in inputFolif (exists folder ("cljs") in inputFol) thendisplay dialog "Make sure you're selecting the correct clojurescript folder!" & return & return & "(from: https://github.com/clojure/clojurescript/tree/master/src)"set cljCore to file ("core.clj") in cljsFol as aliasif (exists file ("core.clj") in cljsFol) thenset cljsFol to folder ("cljs") in cljFolif (exists folder ("cljs") in cljFol) thenset cljFol to folder ("clj") in inputFolif (exists folder ("clj") in inputFol) thenset inputFol to choose folder with prompt "clojurescript/src"display dialog "Please select the clojurescript/src folder"set cljsDefine to {"(ns ", "(defn- ", "(defn ", "(def ", "(:refer-clojure :exclude [", "(defmacro "}set funcs to my parseSyn(synContent, funcs, "syntax keyword clojureFunc")set macros to my parseSyn(synContent, macros, "syntax keyword clojureMacro")set define to my parseSyn(synContent, define, "syntax keyword clojureDefine")set repeater to my parseSyn(synContent, repeater, "syntax keyword clojureRepeat")set cond to my parseSyn(synContent, cond, "syntax keyword clojureCond")set exception to my parseSyn(synContent, exception, "syntax keyword clojureException")set special to my parseSyn(synContent, special, "syntax keyword clojureSpecial")set bool to my parseSyn(synContent, bool, "syntax keyword clojureBoolean")set const to my parseSyn(synContent, const, "syntax keyword clojureConstant")close access synRefset synContent to read synRefset synRef to open for access synFiledisplay dialog "Make sure you're using the correct vim-clojure-static/syntax/clojure.vim" & return & return & "https://github.com/guns/vim-clojure-static/tree/master/syntax"if name of synFile is not ("clojure.vim") thenset synFile to choose file with prompt "syntax/clojure.vim"display dialog "Select vim-clojure-static/syntax/clojure.vim"global special, cond, repeater, defineset funcs to {}set macros to {}set define to {}set repeater to {}set cond to {}set exception to {}set special to {}set bool to {}set const to {}global badStuff, excludes, specialGroup, condGroup, repeatGroup, defineGroupset defineGroup to {"definline", "definterface", "defmacro", "defmethod", "defmulti", "defn", "defn-", "defonce", "defprotocol", "defrecord", "defstruct", "deftype"}set repeatGroup to {"doall", "dorun", "doseq", "dotimes", "while"}set condGroup to {"case", "cond", "cond->", "cond->>", "condp", "if-let", "if-not", "when", "when-first", "when-let", "when-not"}set specialGroup to {".", "catch", "def", "do", "finally", "fn", "if", "let", "loop", "monitor-enter", "monitor-exit", "new", "quote", "recur", "set!", "throw", "try", "var"}set excludes to {"-> ", "->> ", ".. ", "amap ", "and ", "areduce ", "alength ", "aclone ", "assert ", "binding ", "bound-fn ", "case ", "comment ", "cond ", "condp ", "declare ", "definline ", "definterface ", "defmethod ", "defmulti ", "defn ", "defn- ", "defonce ", "defprotocol ", "defrecord ", "defstruct ", "deftype ", "delay ", "destructure ", "doseq ", "dosync ", "dotimes ", "doto ", "extend-protocol ", "extend-type ", "fn ", "for ", "future ", "gen-class ", "gen-interface ", "if-let ", "if-not ", "import ", "io! ", "lazy-cat ", "lazy-seq ", "let ", "letfn ", "locking ", "loop ", "memfn ", "ns ", "or ", "proxy ", "proxy-super ", "pvalues ", "refer-clojure ", "reify ", "sync ", "time ", "when ", "when-first ", "when-let ", "when-not ", "while ", "with-bindings ", "with-in-str ", "with-loading-context ", "with-local-vars ", "with-open ", "with-out-str ", "with-precision ", "with-redefs ", "satisfies? ", "identical? ", "true? ", "false? ", "nil? ", "str ", "get ", "aget ", "aset ", "+ ", "- ", "* ", "/ ", "< ", "<= ", "> ", ">= ", "== ", "zero? ", "pos? ", "neg? ", "inc ", "dec ", "max ", "min ", "mod ", "bit-and ", "bit-and-not ", "bit-clear ", "bit-flip ", "bit-not ", "bit-or ", "bit-set ", "bit-test ", "bit-shift-left ", "bit-shift-right ", "bit-xor "} as textset jsReserved to {"^:abstract ", "^:boolean ", "^:break ", "^:byte ", "^:case ", "^:catch ", "^:char ", "^:class ", "^:const ", "^:continue ", "^:debugger ", "^:default ", "^:delete ", "^:do ", "^:double ", "^:else ", "^:enum ", "^:export ", "^:extends ", "^:final ", "^:finally ", "^:float ", "^:for ", "^:function ", "^:goto ", "^:if ", "^:implements ", "^:import ", "^:in ", "^:instanceof ", "^:int ", "^:interface ", "^:let ", "^:long ", "^:native ", "^:new ", "^:package ", "^:private ", "^:protected ", "^:public ", "^:return ", "^:short ", "^:static ", "^:super ", "^:switch ", "^:synchronized ", "^:this ", "^:throw ", "^:throws ", "^:transient ", "^:try ", "^:typeof ", "^:var ", "^:void ", "^:volatile ", "^:while ", "^:with ", "^:yield ", "^:methods "} as textset badStuff to {"{", "#", "~", "a", "b", "str*", "gensym", "gensym_counter", "truth_", "type_satisfies_", "fixture1", "fixture2", "~(with-meta", "~psym", "#^:private", "~'apply-to"} as textset finalSizeY to (item 2 of desiredSize) * (screenHeight - dockHeight - 32)set finalPositionY to (item 2 of desiredPosition) * (screenHeight - dockHeight) + 8set dockHeight to item 2 of dockDimensionsset dockDimensions to size in list 1tell application "System Events" to tell process "Dock"set desiredSize to {0.5, 0.5}set desiredPosition to {0.5, 0.5}end dodisplay notification theResult with title "Archive File"set theResult to do shell script "~/.bin/backup_file " & the quoted form of the theUnixPathset theUnixPath to POSIX path of theFileset theFile to file of document 1tell application "iA Writer"on do()" Error Message: " & errMsg & " Number " & errNumdisplay dialog "AppleScript encountered an error." & ¬activate -- This prevents a beep when scripts are run from LaunchBar but it also makes the script run slower from the Script Menuif errNum is not equal to -128 thenon error errMsg number errNumdo()set the clipboard to content_stringset content_string to content_string & returnset content_string to content_string & bookmark_desc & returnif bookmark_desc is not "" thenset bookmark_desc to desc of current_bookmarkset content_string to content_string & bookmark_url & returnif bookmark_url is not "" thenset bookmark_url to url of current_bookmarkset content_string to content_string & bookmark_title & returnif bookmark_title is not "" thenset bookmark_title to title of current_bookmarkrepeat with current_bookmark in selected_bookmarksset selected_bookmarks to selected bookmarksset content_string to ""tell application "Spillo"tell front window of (first application process whose frontmost is true) to set {position, size} to theBoundsset theBounds to {finalPosition} & {finalSize}set finalSize to {finalSizeX, finalSizeY}set finalSizeY to (item 2 of desiredSize) * screenHeightset finalSizeX to (item 1 of desiredSize) * screenWidthset finalPosition to {finalPositionX, finalPositionY}set finalPositionY to (item 2 of desiredPosition) * screenHeightset finalPositionX to (item 1 of desiredPosition) * screenWidthset screenHeight to item 4 of screenSizeset screenWidth to item 3 of screenSizetell application "Finder" to set screenSize to bounds of window of desktopset desiredSize to {0.8, 1.0}set desiredPosition to {0.2, 0.0}getConnected()set userToken to KeyChainer("get")checkConnection()legalWarning()set autoOk to do shell script "defaults read " & quoted form of prefName & " " & quoted form of autoOkPropNameelse if button returned of dialogResult is "Reset Password" thendo shell script "defaults delete com.cisco." & prefsNameif button returned of dialogResult is "Clear Settings" thenset dialogResult to display dialog "Yubikey OTP device not detected please connect manually" buttons {"Reset Password", "Clear Settings", "Quit"} default button "Quit" cancel button "Quit" with title name of me giving up after 3if the errorNumber is equal to 1 thendo shell script "system_profiler SPUSBDataType 2>/dev/null | grep -i 'YubiKey.*OTP'"display dialog "Your system needs a one-time configuration to run this script." & return & return & "In \"System Preferences... -> Security & Privacy -> Privacy\":" & return & return & "1. Unlock \"Click the lock to make changes\"" & return & "2. Select \"Click Accessibility\"" & return & "3. Select checkbox next to: \"" & myname & "\"" & return & "4. Re-run the script to proceed." with title name of me buttons {"OK"} cancel button "OK" with icon notetell current pane to reveal anchor "Privacy_Accessibility"set current pane to pane "com.apple.preference.security"display notification "Please follow instructions when they appear" with title (name of me) as text subtitle "Loading Security & Privacy Preferences..."if isUIScriptingEnabled = false thentell application "System Events" to set isUIScriptingEnabled to UI elements enabledset myname to "Script Menu"if myname is "osascript" thenset myname to name of current applicationend my_Prefselse if action is "reset" and theKeyValue is "resetpwd" thendo shell script "security delete-generic-password -a " & prefsNamedo shell script "defaults delete com.cisco." & prefsName & " legalwarning"do shell script "defaults delete com.cisco." & prefsName & " saved"else if action is "reset" and theKeyValue is "clear" thendo shell script "defaults write com.cisco." & prefsName & " legalwarning" & " ' 1'"else if action is "set" and theKeyValue is "autoOk" thenelse if action is "set" and theKeyValue is "no" thendo shell script "security add-generic-password -a " & prefsName & " -w " & quoted form of myPassword & " -j 'Used by Applescript Deskpro Volume' -s" & prefsNamedo shell script "defaults write com.cisco." & prefsName & " saved" & " '" & theKeyValue & "'"if action is "set" and theKeyValue is "yes" thenon my_Prefs(action, theKeyValue)end getConnecteddisplay notification "VPN Connected" with title "Duo AnyConnect"click button "Accept" of window "Cisco AnyConnect - Banner" of AppProcrepeat while (windows of AppProc whose title is "Cisco AnyConnect - Banner") is {}click LoginButtonset LoginButton to my RecurseUIForElem(UIGrandParent, "AXButton", "Log In")repeat while LoginButton is {}set LoginButton to {}set UIGrandParent to my GetUIAncestor(TokenField, 2)set value of TokenField to text returned of dialogResultset TokenField to my RecurseUIForAttribute(DuoHTMLArea, "AXPlaceholderValue", "(ex. 867539)")repeat while TokenField is {}set TokenField to {}click PasscodeButtonset PasscodeButton to my RecurseUIForElem(DuoHTMLArea, "AXButton", "Enter a Passcode")click menu item "Token" of menu 1 of group 1 of DuoWindowclick Popupdisplay notification "User Cancelled" with title "Duo AnyConnect"error "User canceled." number -128click DuoCloseButtonset DuoCloseButton to my RecurseUIForElem(DuoWindow, "AXButton", "close button")if button returned of dialogResult is "Quit" thenset dialogResult to display dialog "Invalid Yubikey token" & return & "Quit or Retry touching Yubikey now..." default answer "" buttons {"Retry", "Quit"} with title name of merepeat until length of text returned of dialogResult is 44set dialogResult to display dialog "Touch Yubikey now..." default answer "" buttons {"OK"} default button "OK" with title "Get YubiKey-OTP -> " & name of meset Popup to my RecurseUIForElem(DuoHTMLArea, "AXPopUpButton", "Device")repeat while Popup is {}set Popup to {}set value of PasswordTextField to userTokenset value of UserNameTextField to UserNameset PasswordTextField to my RecurseUIForAttribute(DuoHTMLArea, "AXPlaceholderValue", "Password")set UserNameTextField to my RecurseUIForAttribute(DuoHTMLArea, "AXPlaceholderValue", "email")repeat while UserNameTextField is {}repeat while PasswordTextField is {}set PasswordTextField to {}set UserNameTextField to {}set UserName to UserName & "@cisco.com"set UserName to system attribute "USER"set DuoHTMLArea to my RecurseUIForElem(DuoWindow, "AXWebArea", "Cisco.com Login Page")repeat while DuoHTMLArea is {}set DuoHTMLArea to {}perform action "AXRaise" of DuoWindowset DuoWindow to item 1 of (windows of AppProc whose title is "Cisco AnyConnect Login")repeat while (windows of AppProc whose title is "Cisco AnyConnect Login") is {}click button "Connect" of ACWindowon getConnected()end checkConnectionend tell -- trying some new end tell statements.else if button returned of b is "Quit" thendisplay notification "VPN Disconnected by User" with title "Duo AnyConnect"tell application "Cisco AnyConnect Secure Mobility Client.app" to quitclick button "Disconnect" of ACWindowif button returned of b is "Disconnect" thenset b to display dialog "Maybe already connected?" buttons {"Disconnect", "Quit"} default button "Disconnect" with title name of meif (static texts of ACWindow whose value is "Ready to connect.") is {} thenset ACWindow to item 1 of (windows of AppProc whose description is "standard window" and title is "")click menu item "Show AnyConnect Window" of menu 1 of menu bar item "Cisco AnyConnect Secure Mobility Client" of menu bar 1 of AppProcset AppProc to application process AppNametell application AppName to activateset AppName to "Cisco AnyConnect Secure Mobility Client"on checkConnection()end legalWarningmy_Prefs("set", "autoOk")set autoOk to "1"set b to display dialog "Acknowledge you have read the below legal message." & return & "You MUST read the text at least once, and promise to hum the words to yourself every time you log in." & return & return & "NOTE: DO NOT dial emergency response numbers (e.g. 911,112) from software telephony clients." & return & "Your exact location and the appropriate emergency response agency may not be easily identified." & return & return & "The following countries restrict use of VoIP software via VPN over the Internet: UAE, Saudi Arabia, Pakistan, Lebanon, Jordan, Egypt, Oman, Qatar, Yemen, Algeria and Kuwait." buttons {"Acknowledged"} default button "Acknowledged" with title "Acknowledge Legal Notice" with icon cautionset autoOk to (autoOk = "1")set autoOk to do shell script "defaults read com.cisco." & prefsName & " legalwarning"set autoOkPropName to "autoOk"on legalWarning()end KeyChainerreturn returnValueset returnValue to myPasswordmy_Prefs("saved", "no")my_Prefs("set", "yes")set b to display dialog "ARE YOU SURE YOU KNOW WHAT YOU ARE DOING?" buttons {"Yes", "No"} default button "No" with title name of me with icon stopif button returned of b is "Yes" thenset b to display dialog "Do you want to save this in your Keychain?" & return & return & "This is only asked on the first run" & return & return & "If you select no you will be prompted everytime for your password" buttons {"Yes", "No"} default button "No" giving up after 5 with title name of me with icon cautionon error -- no previous settingset b to "1"set b to do shell script "defaults read com.cisco." & prefsName & " saved"set myPassword to text returned of passwordqset passwordq to display dialog ("What is the AnyConnect Password") default answer "" with title name of me with hidden answerreturn ""if action is "delete" thenmy_Prefs("reset", "resetpwd")if (length of myPassword is 0) thenset myPassword to do shell script "security 2>&1 >/dev/null find-generic-password -gl " & prefsName & " | sed -n 's/^password: \"\\([^\"]*\\)\"/\\1/p'"set returnValue to ""on KeyChainer(action)end GetUIAncestorreturn UIElementset UIElement to value of attribute "AXParent" of UIElementrepeat GenCount timeson GetUIAncestor(UIElement, GenCount)end RecurseUIForAttributeset ResultElem to my RecurseUIForAttribute(UIElem, AttrName, AttrVal)return ParentUIElemif AttrVal is "" or AttrVal is value of ElemAttr thenrepeat with ElemAttr in ((attributes of ParentUIElem) whose name is AttrName)on RecurseUIForAttribute(ParentUIElem, AttrName, AttrVal)end RecurseUIForElemerror errStr number errorNumberreturn {}if the errorNumber is equal to -1719 thenon error errStr number errorNumberreturn ResultElemset ResultElem to my RecurseUIForElem(UIElem, ElemRole, ElemDescription)repeat with UIElem in UI elements of ParentUIElemreturn item 1 of ResultElemif ResultElem is not {} thenset ResultElem to (UI elements of ParentUIElem whose role is ElemRole and (title is ElemDescription or description is ElemDescription))on RecurseUIForElem(ParentUIElem, ElemRole, ElemDescription)set prefsName to "AnyConnectDuo"global myPasswordglobal prefsNameset clearSettings to ""set resetPassword to ""global userTokenexecute javascript(js)"$('#ac_play.playing').click();document.getElementsByTagName('head')[0].appendChild(script);script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';var script = document.createElement('script');set js to "//Set up jQueryif "vk.com" is in (get URL of t) thenrepeat with t in every tab in wrepeat with w in every windowname of (path to me)end idlereturn 3if URL contains "adrotator.se" then closetell trepeat with t in tabs of windowson idleset the clipboard to "******************************************" & return & "Mac Path: " & return & "afp://" & ipAdress & "/" & macFilePath1 & return & return & "If the link is broken, copy (apple+c) and paste (apple+v) whole link into Connect to Server (apple + k) " & return & return & "******************************************" & return & "Windows Path:" & return & "\\\\" & ipAdress & "\\" & winFilePath1 & return & return & "If the link is broken, copy (ctrl+c) and paste (ctrl+v) whole link into Windows Explorer " & return & return & "******************************************"set winFilePath1 to SAR(winFilePath, " ", "%20")set winFilePath to winFilePath as textset end of winFilePath to filePath as textset text item delimiters to "\\"set winFilePath to {}set macFilePath1 to SAR(macFilePath, " ", "%20")set macFilePath to macFilePath as textset end of macFilePath to filePath as textset filePath to text items of (oneFile as text)set text item delimiters to ":"repeat with oneFile in theseItemsset macFilePath to {}set ipAdress to "10.50.0.17" as texton open theseItemsend SARreturn newTextset AppleScript's text item delimiters to old_delimsset newText to (parts as string)set AppleScript's text item delimiters to replace_textset parts to every text item of main_textset AppleScript's text item delimiters to search_textset old_delims to AppleScript's text item delimiterson SAR(main_text, search_text, replace_text)open seltell application "Finder" to set sel to selectionopen _pathset target to _pathtell the front Finder window to if toolbar visible thenset _path to (path of scripts folder) as stringtell application "System Events" to tryend createToDo{name:tdItem}{name:tdItem} at beginning of project tdProjectset newToDo to make new to do with properties ¬if isProject is true thenif tdItem as string is not equal to "" thenmy createToDo(isProject, i, tdProject)if i as string is equal to "--" thenrepeat with i in tdItemif class of tdItem is equal to list thenon createToDo(isProject, tdItem, tdProject)end perform_mail_actionreturn my createToDo(false, theItem, theProject)set theProject to aProjectif aProject as string is equal to theSubject thenrepeat with aProject in allProjectsreturn my createToDo(true, theItem, theProject)set theProject to theSubjectset newProject to make new project with properties {name:theSubject}if (count of allProjects) is equal to 0 thenif theSubject as string is not equal to "" thenset theProject to ""set allProjects to name of to dos of list "Projects"tell application "Things beta"set AppleScript's text item delimiters to tidset theItem to text items of theContentset AppleScript's text item delimiters to ASCII character 10 -- (a line feed)set tid to AppleScript's text item delimitersset theContent to the content of the eachMessageset theSubject to the subject of the eachMessagerepeat with eachMessage in selectedMessagesset selectedMessages to |SelectedMessages| of infoon perform_mail_action(info)end takeitems 1 thru min(n, length of xs) of xs""text 1 thru min(n, length of xs) of xsif n > 0 thenif class of xs is string thenon take(n, xs)end stripdropWhile(isSpace, dropWhileEnd(isSpace, s))on |λ|(c)script isSpaceon strip(s)end sortsortedArrayUsingSelector:"compare:") as list((current application's NSArray's arrayWithArray:xs)'s ¬on sort(xs)end mReturnproperty |λ| : fscriptfif class of f is script thenon mReturn(f)end minxyif y < x thenon min(x, y)end isSpacei = 32 or (i ≥ 9 and i ≤ 13)set i to id of con isSpace(c)end isDigit48 ≤ n and 57 ≥ nset n to (id of c)on isDigit(c)end intercalateSreturn sset my text item delimiters to dlmset s to xs as textset {dlm, my text item delimiters} to {my text item delimiters, sep}on intercalateS(sep, xs)end dropWhileEndtake(i, xs)set i to i - 1repeat while i > 0 and |λ|(item i of xs)set i to length of xson dropWhileEnd(p, xs)end dropWhiledrop(i - 1, xs)set i to i + 1repeat while i ≤ lng and |λ|(item i of xs)tell mReturn(p)set i to 1on dropWhile(p, xs)end dropitems (n + 1) thru -1 of xstext (n + 1) thru -1 of xsif text is class of xs thenif n < length of xs thenon drop(n, xs)end concatMapreturn accset acc to acc & |λ|(item i of xs, i, xs)set acc to {}set acc to ""if 0 < lng and class of xs is string thenon concatMap(f, xs)end alltrueif not |λ|(item i of xs, i, xs) then return falserepeat with i from 1 to lngset lng to length of xstell mReturn(f)on all(f, xs)paragraphs of (the clipboard))))sort(concatMap(pageNum, ¬intercalateS(", ", ¬end |λ|{}{s as integer}if 0 < length of s and all(digit, (characters of s)) thenset s to strip(para)on |λ|(para)property digit : my isDigitscript pageNumdo shell script "path=$(pbpaste);chmod a+x $path;cd ..;ln -s " & filePath & " " & filePathset the clipboard to filePathset filePath to (POSIX path of (the selection as alias))set theItems to selectionset var to "value"end performSmartRuleclose recordWindowset AppleScript's text item delimiters to odset the tags of newDoc to (tags of selected & tagForPDF)to {AppleScript's text item delimiters, ","}set {od, AppleScript's text item delimiters} ¬set label of newDoc to label of selectedset comment of newDoc to comment of selectedset modification date of newDoc to modification date of selectedset creation date of newDoc to creation date of selectedset data of newDoc to contentAsPDFin recordGroup{name:recordName, URL:recordURL, type:PDF document} ¬set newDoc to create record with ¬set recordGroup to item 1 of recordParentsset recordParents to (parents of selected)set recordName to (name of selected)set contentAsPDF to get PDF of recordWindowin current tab of recordWindowdo JavaScript "window.scrollTo(0,0)" ¬delay 0.75do JavaScript scroll in current tab of recordWindow& "*document.body.scrollHeight/4)"set scroll to "window.scrollTo(0," & n ¬repeat with n from 1 to 4if (recordURL ends with ".pdf") is not true thenrepeat while loading of recordWindowset recordWindow to open window for record selectedset recordURL to (URL of selected) as stringrepeat with selected in theRecordson performSmartRule(theRecords)property tagForPDF : "π-archived-page"end notification_Centerset itemNum to "0"" Tabs to Evernote" with title "Send Chrome Tabs to Evernote" subtitle "◸ Veritrope.com"else if Plural_Test is greater than 1 then" Tab to Evernote" with title "Send Chrome Tabs to Evernote" subtitle "◸ Veritrope.com"display notification "Successfully Exported " & itemNum & ¬else if Plural_Test is equal to 1 thenelse if Plural_Test is 0 thendisplay notification "No Tabs Exported!" with title "Send Chrome Tabs to Evernote" subtitle "◸ Veritrope.com"if Plural_Test is -1 thenset Plural_Test to (successCount) as numberon notification_Center(successCount, itemNum)my notification_Center(successCount, tabCount)set EVNote to (create note with text url_list title NoteTitle)set AppleScript's text item delimiters to old_delimset url_list to url_list as textset old_delim to AppleScript's text item delimitersset successCount to (successCount + 1)copy TabInfo to the end of url_listset TabInfo to ("" & TabTitle & return & TabURL & return & return)set TabURL to (URL of t)set TabTitle to (title of t)repeat with t in (tabs of w)repeat with w in chromeWindowset successCount to 0set tabCount to (count of (tabs of chromeWindow))set chromeWindow to the front windowset NoteTitle to "URL List from Chrome Tabs on " & the date_stampset the date_stamp to ((the current date) as string)set url_list to {}end fmGUI_AppFrontMostclick button 1 of window 1if name of window 1 is equal to "2empowerFM Toolbox" thenif frontmost is not true thentell application process "FileMaker Pro Advanced"on fmGUI_AppFrontMost()fmGUI_AppFrontMost()sendmake new to recipient with properties {name:recipientName, address:recipientAddress}tell theMessageset theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}set theContent to ip_addressset theSubject to ip_addressset recipientAddress to "YOURADDRESS" -- EDIT HEREset recipientName to "YOURNAME" -- EDIT HEREset ip_address to do shell script "/usr/bin/curl --silent http://checkip.dyndns.org/ | grep -o -E \"(\\d{1,3}\\.?){4}\" "tell application "Opera" to set the minimized of the front window to trueelse if x is equal to "opera" thentell application "Firefox" to set the miniaturized of the front window to trueelse if x is equal to "firefox" thentell application "Google Chrome" to set the minimized of the front window to trueelse if x is equal to "chrome" thentell application "Safari" to set the miniaturized of the front window to trueif x is equal to "safari" thenset x to item 1 of argvdo shell script "rm -rf " & outputScptPosixPathmodifyKeysLib's modifyOptionAndCmdKeys("restore")set modifyKeysLib to load script file outputScptPathdo shell script "osacompile -o " & outputScptPosixPath & " " & inputAppleScriptPosixPathset outputScptPosixPath to POSIX path of outputScptPathset outputScptPath to (currentDir & "ModifyOptionCmdKeys.scpt")set inputAppleScriptPosixPath to POSIX path of (currentDir & "ModifyOptionCmdKeys.applescript")set currentDir to (container of (path to me)) as stringdisplay alert "EXPORT PROBLEM" message errorMessageon error errorMessage number errorNumberreveal the thePathset thePath to file (defaultDestinationFolder & newFileName as string)delete targetFoldermove files of entire contents of targetFolder to defaultDestinationFolder with replacingset name of theFile to newFileNameset newFileName to newFileName & "." & fileExtensionset AppleScript's text item delimiters to ATIDset newFileName to text item 1 of fileNameset AppleScript's text item delimiters to splitCharactersset ATID to AppleScript's text item delimitersset splitCharacters to ".001"set fileName to the name of theFile as stringset fileExtension to name extension of theFilerepeat with theFile in folderContentsset folderContents to every item of targetFolderset skipped of every slide to false{image format:PNG, skipped slides:includeSkippedSlides}export the front document as slide images to file targetFolderHFSPath with properties ¬set the targetFolderHFSPath to targetFolder as string{name:newFolderName}make new folder at defaultDestinationFolder with properties ¬set the targetFolder to ¬set incrementIndex to incrementIndex + 1set newFolderName to documentName & "-" & (incrementIndex as string)repeat until not (exists folder newFolderName of defaultDestinationFolder)set incrementIndex to 1set newFolderName to documentName & " slide " & currentSlideNumberset documentName to text 1 thru -5 of documentNameif documentName ends with ".key" then ¬set documentName to the name of the front document(every slide where the slide number is not equal to currentSlideNumber) to trueset skipped of ¬tell the front documentset currentSlideNumber to the slide number of (get the current slide of the front document)if not (exists document 1) then error number -128if playing is true then tell the front document to stoptell application "Keynote"set the defaultDestinationFolder to (path to downloads folder)property includeSkippedSlides : falsesend "This is a test text..." to targetBuddyset targetBuddy to buddy (word 1 of aNumber) of targetServiceset targetService to (1st service whose service type = iMessage)repeat with aNumber in phoneNumbersset phoneNumbers to {"6125550000 John Smith", ¬ "6125551111 Mary Poppins", ¬ "6125552222 Larry Bud Melmon"}tell application "Messages"click menu item 8else if query is equal to OPEN_LYRIC or query is equal to OPEN_LYRIC_SHORT thenclick menu item "喜欢歌曲"else if query is equal to LOVE or query is equal to LOVE_SHORT thenclick menu item "音量减"else if query is equal to VOLUME_DOWN or query is equal to VOLUME_DOWN_SHORT thenclick menu item "音量加"else if query is equal to VOLUME_UP or query is equal to VOLUME_UP_SHORT thenclick menu item "上一首"else if query is equal to PREVIOUS or query is equal to PREVIOUS_SHORT thenclick menu item "下一首"else if query is equal to NEXT or query is equal to NEXT_SHORT thenclick menu item 1if query is equal to PAUSE_A or query is equal to PAUSE_SHORT thentell menu "播放控制" of menu bar item "播放控制" of menu bar 1click menu item "退出QQ音乐" of menu "QQ音乐" of menu bar item "QQ音乐" of menu bar 1if query is equal to EXIT_A or query is equal to EXIT_SHORT thentell application "System Events" to tell process "QQMusic"set EXIT_SHORT to "ex"set EXIT_A to "exit"set OPEN_LYRIC_SHORT to "ly"set OPEN_LYRIC to "lyric"set VOLUME_DOWN_SHORT to "vd"set VOLUME_UP_SHORT to "vu"set VOLUME_DOWN to "volumedown"set VOLUME_UP to "volumeup"set LOVE_SHORT to "lv"set LOVE to "love"set PREVIOUS_SHORT to "pr"set PREVIOUS to "previous"set NEXT_SHORT to "ne"set NEXT to "next"set PAUSE_SHORT to "p"set PAUSE_A to "pause"set query to "{query}"set the_record to read file full_path as recordset full_path to (path to desktop as text) &"record_data"display alert "DEVONthink" message msg as warningif err is not -128 then ¬on error msg number errload workspace (item 1 of chosenWorkspace)close every think windowsave workspace (get current workspace)if exists (current workspace) thenif chosenWorkspace ≠ false then -- User chose, not cancelledand empty selection allowed)without multiple selections allowed ¬with prompt "Choose workspace" ¬set chosenWorkspace to (choose from list (workspaces as list) ¬end open locationdisplay dialog "URL not supported: '" & this_URL & "'"processOutlookURL(this_URL)else if regexTest(this_URL, "^outlookmsg") thenprocessQuipURL(this_URL)else if regexTest(this_URL, "quip-amazon.com") thenprocessChimeURL(this_URL)if regexTest(this_URL, "chime.aws") thenset AppleScript's text item delimiters to "/"on open location this_URLend processOutlookURLdisplay dialog "Outlook handle '" & handle & "' from URL '" & this_URL & "' is not valid."openApp("Outlook", handle)if regexTest(handle, "^[[:digit:]]+") thenset handle to text item 3 of this_URLon processOutlookURL(this_URL)end processQuipURLcheckForceOpen(this_URL, "Quip", handle)openApp("Quip", handle)if regexTest(handle, "^[A-Za-z0-9]{12}") thenon processQuipURL(this_URL)end processChimeURLcheckForceOpen(this_URL, "Chime", handle)openApp("Chime", handle)if regexTest(handle, "^[[:digit:]]{10}") thenset handle to text item 4 of this_URLon processChimeURL(this_URL)end openAppdo shell script "mdfind 'com_microsoft_outlook_recordID == " & handle & "' -0 | xargs -0 open"else if appName = "Outlook" thendo shell script "open " & "x-choosy://chrome.work/" & handleelse if appName = "Browser" thendo shell script "open " & "quip://" & handleelse if appName = "Quip" thendo shell script "open " & "chime://meeting?pin=" & handleif appName = "Chime" thenon openApp(appName, handle)end regexTestreturn "0" = retValset retVal to (do shell script "[[ " & quoted form of str & " =~ " & regex & " ]]; printf $?")on regexTest(str, regex)end checkForceOpendisplay notification "Not opening URL '" & this_URL & "'"openApp("Browser", this_URL)else if result = {button returned:"Open in Browser"} thenopenApp(appName, handle)if result = {button returned:"Open in " & appName} thendisplay dialog diagText buttons {"Open in " & appName, "Open in Browser", "Cancel"} with icon caution default button 1 cancel button 3set diagText to appName & " handle '" & handle & "' - from URL '" & this_URL & "' might not be valid. Open in " & appName & " anyway?"on checkForceOpen(this_URL, appName, handle)}app.displayAlert('👋 Spotify is not running', { message: 'I can only search for lyrics of songs playing in Spotify.' });if (spotify.running()){ var trackName = spotify.currentTrack().name(); var artist = spotify.currentTrack().artist(); var mySearch = trackName + ' ' + artist + ' lyrics OR 歌詞'; app.doShellScript("open 'https://google.com/search?q='" + encodeURI(mySearch)); } else {var spotify = Application('Spotify');app.includeStandardAdditions = true;var app = Application.currentApplication();*/Simple script to Google search for lyrics of the song currently playing on Spotify.Written in JXA (Javascript for Automation)./*addFavoriteChrome("aaa")end addFavoriteChromekey code 36keystroke "v" using {command down}keystroke "d" using {command down}set the clipboard to theStringon addFavoriteChrome(theString)end getCurrentURLChromereturn currentURLset currentURL to get URL of active tab of first windowon getCurrentURLChrome()cutSubStringFromBeginningOf(theURL, theSubString)set theSubString to "ba-cau-noi-chat-moi-ngay"set theURL to "https://www.hellochao.vn/ba-cau-noi-chat-moi-ngay#2018-01-06"end cutSubStringFromBeginningOfset theCuttingSubstring to text 1 thru (indexSubString + (length of theSubString) - 1) of theStringset indexSubString to indexOfSubStringInString(theString, theSubString)on cutSubStringFromBeginningOf(theString, theSubString)end indexOfSubStringInStringoffset of theSubString in theStringon indexOfSubStringInString(theString, theSubString)compiletell dset d to make new document with properties {source text:theTester}end tell"" & handlerName & "()" & "set theTester to "tell application \"Script Debugger\"kend tell"" & handlerCall & "tell document \"" & theName & "\"tell application \"Script Debugger\"set theTester to variableSetter & "set handlerCall to handlerName & "(" & paramList & ")"if handlerCall ≠ missing value thenset variableSetter to variableSetter & return & "set " & name of item n of theparams & " to var" & nset paramList to paramList & ", " & name of item n of theparamsset variableSetter to "set " & name of item n of theparams & " to var" & nset paramList to name of item n of theparamsif n = 1 thenrepeat with n from 1 to (count of theparams)if (count of every handler parameter of theHandler) > 0 thenset handlerCall to missing valueset theparams to every handler parameter of theHandlerset theHandler to first script handler whose name is handlerNameset theName to nameset handlerName to kl's extractBetween(paragraph 1 of theselection, "on ", "(")if theselection begins with "on" thenset theselection to selectiontell front documenttell application "Script Debugger"set handlerName to getvariable "SD__theChoice"if variable "SD__theChoice" exists thentell application "Keyboard Maestro Engine"use kl : script "Kevin's Library"set logger to std's import("logger")'s new("keyboard")end _charToKeycode-1if key is "F12" or key is "f12" then return 111if key is "F11" or key is "f11" then return 103if key is "F10" or key is "f10" then return 109if key is "F9" or key is "f9" then return 101if key is "F8" or key is "f8" then return 100if key is "F7" or key is "f7" then return 98if key is "F6" or key is "f6" then return 97if key is "F5" or key is "f5" then return 96if key is "F4" or key is "f4" then return 118if key is "F3" or key is "f3" then return 99if key is "F2" or key is "f2" then return 120if key is "F1" or key is "f1" then return 122if key is "right" then return 124if key is "left" then return 123if key is "down" then return 125if key is "up" then return 126if key is " " then return 49if key is "space" then return 49if key is "del" then return 51if key is "delete" then return 51if key is "escape" then return 53if key is "esc" then return 53if (ASCII number key) is 13 or key is "return" then return 36if (ASCII number key) is 10 or key is "enter" then return 76if key is tab or key is "tab" then return 48if key is "\"" then return 39if key is "`" then return 50if key is "=" then return 24if key is "-" then return 27if key is "\\" then return 42if key is "/" then return 44if key is "]" then return 30if key is "[" then return 33if key is space then return 49if key as text is "9" then return 25if key as text is "8" then return 28if key as text is "7" then return 26if key as text is "6" then return 22if key as text is "5" then return 23if key as text is "4" then return 21if key as text is "3" then return 20if key as text is "2" then return 19if key as text is "1" then return 18if key as text is "0" then return 29if key is "Z" or key is "z" then return 6if key is "Y" or key is "y" then return 16if key is "X" or key is "x" then return 7if key is "W" or key is "w" then return 13if key is "V" or key is "v" then return 9if key is "U" or key is "u" then return 32if key is "T" or key is "t" then return 17if key is "S" or key is "s" then return 1if key is "R" or key is "r" then return 15if key is "Q" or key is "q" then return 12if key is "P" or key is "p" then return 35if key is "O" or key is "o" then return 31if key is "N" or key is "n" then return 45if key is "M" or key is "m" then return 46if key is "L" or key is "l" then return 37if key is "K" or key is "k" then return 40if key is "J" or key is "j" then return 38if key is "I" or key is "i" then return 34if key is "H" or key is "h" then return 4if key is "G" or key is "g" then return 5if key is "F" or key is "f" then return 3if key is "E" or key is "e" then return 14if key is "D" or key is "d" then return 2if key is "C" or key is "c" then return 8if key is "B" or key is "b" then return 11if key is "A" or key is "a" then return 0on _charToKeycode(key)std's applyMappedOverride(result)end insertTextByPastingtypeText(theText)set the clipboard to origClipboarddelay 0.1 -- Increase the value if failure is still encountered.pressCommandKey("v") -- There's issue where incorrect value islogger's debugf("The clipboard now equal to text to paste: {}", the clipboard)if (the clipboard) is equal to theText thenset the clipboard to theTextrepeatset origClipboard to ""set origClipboard to the clipboardon insertTextByPasting(theText)end typeTexttell application "System Events" to keystroke theTexton typeText(theText)end pressOptionKeykey code my _charToKeycode(keyToPress) using {option down}on pressOptionKey(keyToPress)end pressControlShiftKeykey code my _charToKeycode(keyToPress) using {control down, shift down}on pressControlShiftKey(keyToPress)end pressControlKeykey code my _charToKeycode(keyToPress) using {control down}on pressControlKey(keyToPress)end pressCommandOptionKeykey code my _charToKeycode(keyToPress) using {command down, option down}on pressCommandOptionKey(keyToPress)end pressCommandShiftKeykey code my _charToKeycode(keyToPress) using {command down, shift down}on pressCommandShiftKey(keyToPress)end pressCommandControlKeykey code my _charToKeycode(keyToPress) using {command down, control down}on pressCommandControlKey(keyToPress)end pressCommandKeykey code my _charToKeycode(keyToPress) using {command down}on pressCommandKey(keyToPress)end pressKeydelay 0.01key code my _charToKeycode(keyToPress)on pressKey(keyToPress)end getLayoutegrep -w 'KeyboardLayout Name' | sed -E 's/^.+ = \"?([^\"]+)\"?;$/\\1/'"AppleSelectedInputSources | \\do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist \\on getLayout()end isDvorakgetLayout() contains "DVORAK"on isDvorak()end modifiersDownreturn theKeysset end of theKeys to "shift"if ((theFlag div NSShiftKeyMask) mod 2) is not 0 thenset end of theKeys to "command"if ((theFlag div NSCommandKeyMask) mod 2) is not 0 thenset end of theKeys to "control"if ((theFlag div NSControlKeyMask) mod 2) is not 0 thenset end of theKeys to "option"if ((theFlag div NSAlternateKeyMask) mod 2) is not 0 thenset theKeys to {}on modifiersDown()end checkModifierif ((theFlag div theMask) mod 2) = 0 thenset theFlag to NSEvent's modifierFlags() as integerset theMask to NSShiftKeyMaskelse if keyName = "shift" thenset theMask to NSCommandKeyMaskelse if keyName = "command" thenset theMask to NSControlKeyMaskelse if keyName = "control" thenset theMask to NSAlternateKeyMaskif keyName = "option" thenon checkModifier(keyName)script KeyboardInstancelogger's infof("Command Pressed: {}", checkModifier("command"))logger's infof("Shift Pressed: {}", checkModifier("shift"))logger's infof("Option Pressed: {}", checkModifier("option"))else if caseIndex is 3 theninsertTextByPasting("Hello " & emoji's horn)pressControlC()pressControlKey("c")delay 0.1activate application "Terminal"tell sutset spot to spotLib's new(caseId, cases)Manual: Modifier PressedPaste Text with EmojiManual Checksset emoji to std's import("emoji")set caseId to "keyboard-spotCheck"property NSEvent : a reference to current application's NSEventproperty NSCommandKeyMask : a reference to 1048576property NSShiftKeyMask : a reference to 131072property NSAlternateKeyMask : a reference to 524288property NSControlKeyMask : a reference to 262144use framework "AppKit" -- for NSEventuse AppleScript version "2.4"use script "Core Text Utilities"global stdwindowSize's windowSize({direction:"LEFT", resize:0})set windowSize to load script file windowSizeScptset windowSizeScpt to scriptPath & "windowSize.scpt"set scriptPath to ((path to me as text) & "::")set the_cleaned_phone_number to the_list as textset text item delimiters to ""set the_list to text items of the_phone_numberset text item delimiters to {"(", ")", "-", " "}set the_phone_number to "(800) 555-1212"write text "cd $(dirname " & pathFile & ")"else if isDir contains "false" thenwrite text "cd " & pathFileif isDir contains "true" thentell current session of first windowset nWin to (current window)tell application "iTerm"set isDir to (do shell script "test -d " & pathFile & " && echo true || echo false")set the clipboard to pathFileset pathFile to quoted form of pathFileset pathFile to get POSIX path of pathFileset pathFile to selection as textdelete login item selected_nameset selected_name to item 1 of the_selectionif the_selection is not false thenset the_selection to choose from list login_item_names OK button name "Delete"set login_item_names to name of every login itemreturn searchTermgo document 1 to theResultset theResult to find document 1 text searchTermset searchTerm to (weekday of theDate as string) & " " & (month of theDate as string) & " " & (day of theDate as string)set theDate to (current date) + (2 * 86400)else if theWeekday = "Sunday" thenset theDate to (current date) + (3 * 86400)else if theWeekday = "Saturday" thenset theDate to (current date) + (4 * 86400)else if theWeekday = "Friday" thenelse if theWeekday = "Wednesday" thenset theDate to (current date) + 86400if theWeekday = "Monday" thenset theDate to (current date)set theWeekday to (weekday of (current date) as string)open "syllabus.pdf" --edit for your filenametell application "Skim"set custom message of eachCue to theMessageif theMessage is not false thenset theMessage to theRest & "1"else if theState is "0" thenset theMessage to theRest & "0"if theState is "1" thenset theMessage to falseset theRest to text 1 thru -2 of (custom message of eachCue as string)set theState to last character of (custom message of eachCue as string)if q type of eachCue is "Network" and osc message type of eachCue is custom and custom message of eachCue is not "" thenend text_to_listreturn (theList)error errStr number errNumset AppleScript's text item delimiters to saveDon error errStr number errNumset theList to every text item of txtset AppleScript's text item delimiters to {delim}set saveD to AppleScript's text item delimiterson text_to_list(txt, delim)end extract_number_prefixreturn do shell script "ruby -e " & quoted form of rubyScript & " " & quoted form of trackNumberset rubyScript to "print $1 if ARGV[0] =~ /^0*(\\d+)/"set trackNumber to (last item of my text_to_list(loc as Unicode text, ":"))to extract_number_prefix(loc)display dialog "Done!" buttons {"Thanks"} default button 1 giving up after 4set fixed indexing to old_fiend timeoutset this_track's track number to trackNumberif trackNumber is not "" thenset trackNumber to my extract_number_prefix(this_track's location)if class of this_track is file track and this_track's location is not missing value thenrepeat with this_track in selwith timeout of 3000 secondsset fixed indexing to trueset old_fi to fixed indexingset sel to selection of front browser windowdisplay dialog "Select some tracks in iTunes first." buttons {"Cancel"} default button 1 with icon 2 giving up after 15if kind of container of view of front window is not library or selection of front browser window is {} thenkey code 36 # enterdelay 0.2key code 124 # rightdelay 0.134tell application "AltTab" to showApp appBID tarAppIDtell application "BetterTouchTool" to set tarAppID to get_string_variable "BTTActiveAppBundleIdentifier"quitdisplay dialog "UI element scripting is not enabled. Check \"Enable access for assistive devices\""set current pane to pane "com.apple.preference.universalaccess"display dialog "Wrong checkbox found. Did system preferences UI change?"beep 2beep 1if value is 0 thentell funcCheckBoxclick funcCheckBox -- to toggle itif (name of funcCheckBox is "Use F1, F2, etc. keys as standard function keys") thenset funcCheckBox to item 3 of theBoxesset theBoxes to checkboxestell tab group 1 of window "Keyboard" of process "System Preferences"if UI elements enabled thendelay 1 -- wait for pane to load. May not be long enough.if response is "Go to website" then open location "http://your.website.of.choice"set response to button returned of the resultdisplay alert "The header line" message "Something went horribly wrong and your machine may explode. Do you want to abort the task, continue on bravely, or go to a website where someone will panic for you?" as critical buttons {"Quit", "Continue", "Go to website"} default button "Quit"delay 1 # necessary to keep the notification, otherwise it will die with the scriptdisplay notification "FN Locked (special function keys activated)"display notification "Using standard F1, F2, F3, F4, ..."if (its value as boolean) thentell theCheckboxclick theCheckboxset theCheckbox to checkbox "Use F1, F2, etc. keys as standard function keys" of tab group 1 of window "Keyboard"delay 0.3get propertiestell application process "System Preferences"set current pane to pane "com.apple.preference.keyboard"if the error_number is not -128 then display alert "DEVONthink" message error_message as warningon error error_message number error_numberset name of theRecord to theSubjectset theSubject to |kMDItemHeadline| of theMDset theSubject to |kMDItemSubject| of theMDset theMD to meta data of theRecordrepeat with theRecord in theSelectionif theSelection is {} then error "Please select some contents."set theSelection to the selectiontell application id "DNtp"do shell script "plutil -replace 'Sublime Text CLI' -string \"" & (POSIX path of chosenCli) & "\" ~/applescript-core/config-system.plist"set chosenCli to choose file with prompt "Please select the redis-cli:" default location POSIX file "/opt/homebrew/bin/subl"set chosenCli to choose file with prompt "Please select the sublime-cli:" default location POSIX file "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"end writeToFilereturn falseclose access file outputFilereturn trueclose access fileReferencewrite outputText to fileReference starting at eofset outputText to return & outputTextelse if appendLine of prefs is true thenset eof of the fileReference to 0if appendText of prefs is false thenset fileReference to open for access POSIX file outputFile with write permissionset fileReference to open for access file outputFile with write permissionset outputFile to ((path to desktop) as string) & "ASFileWrittenBy_htcLib.txt"set outputFile to fileDirectory of prefs & fileName of prefselse if fileName of prefs is not null thenset outputFile to fullFilePath of prefsif fullFilePath of prefs is not null thenset outputText to outputText of prefsset prefs to prefs & defaultPrefsset defaultPrefs to {outputText:"", fullFilePath:null, fileName:null, fileDirectory:(path to desktop) as string, appendText:false, appendLine:true}on writeToFile(prefs)writeToFile({outputText:"bob", appendText:true})do shell script "networksetup -setairportpower en1 off"tell application "Bento" to quitdelay 60set visible of every process whose visible is true and name is "Bento" to falsekeystroke spacekeystroke tabkeystroke pworddelay 5tell application "Bento" to activateset pword to "password"do shell script "networksetup -setairportpower en1 on"delay 2.0tell application "Fantastical 2" to parse sentence title notes myNote calendarName calName with add immediatelyif query contains onDateString thenset calName to "Life"if myAreaName contains "Life" thenset myAreaName to "" & name of myAreaset myAreaName to "" as textset myArea to area of todoset calName to "Work" as textset title to "" & "'> " & name of todo & "' " & onDateString as textset query to "" & "'> " & name of todo & "' " & completion date of todo as textset myNote to notes of todo as textrepeat with todo in todosset onDateString to "" & month of onDate & " " & day of onDate & " " & year of onDate as textset onDate to date shallArgv as dateif shallArgv contains "/" thenset shallArgv to item 1 of argv as textset onDate to current dateset todos to to dos of list "Logbook"tell application "Things3"set the comment of thisPic to my substitute(userText, comment of thisPic)else if userAction is "Edit Comments" thenset the title of thisPic to my substitute(userText, title of thisPic)repeat with thisPic in thePicsif userAction is "Edit Title" thenset userAction to the button returned of the userChoices as stringset userText to the text returned of the userChoices as stringset userChoices to display dialog ScriptName & " - " & (count selection) & " pictures selected" & return & return & "Type the full SED command:" default answer "s/this/that/" buttons {"Quit", "Edit Comments", "Edit Title"} default button 3 with icon 1display dialog ScriptName & return & return & "First you must select the pictures" buttons {"Ouch!"} with icon 2id of item 1 of thePics -- only pictures have IDset thePics to selectiontell application "iPhoto"end substitutereturn do shell script "echo " & quoted form of theText & " | sed -e " & quoted form of sedCommandon substitute(sedCommand, theText)set ScriptName to "iPhoto SED"set target of front Finder window to duplicate_menew_tab()if (count of Finder windows) > 0 then set duplicate_me to target of front Finder windowon run {}tell front menu bar to tell menu "File" to tell menu item "New Tab"tell application "System Events" to tell application process "Finder"on new_tab()close access outputFilewrite theFile to outputFileset outputFile to open for access outputFileName with write permissionset theFile to theFile & return & theLinelog (get theLine)company of thePerson & theDelim & name of thePersonset theLine to id of thePerson & theDelim & name of grp & theDelim & id of grp & theDelim & last name of thePerson & theDelim & first name of thePerson & theDelim & ¬repeat with grp in grpsset grps to groups of thePersonrepeat with thePerson in theListset theFile to "person id, last name, first name, company, organization, group name, group id"set theList to (get people)tell application "Address Book"set outputFileName to "Danger Mouse:Users:bgebhardt:Documents:Backups:address_book_groups:" & defNameset defName to "group_export_" & theDate & ".txt"set theDate to do shell script "date '+%m-%d-%Y'"set theDelim to "|"end choose menu itemopen location (homeRootURL & "activate")else if the name of theObject is "activateMeMI" thendisplay alert "There was an error with the deletion process." attached to window windowOneNamedisplay alert "You now cease to exist..." attached to window "loginWindow"hide window windowOneNameshow window "loginWindow"if delRes is "You now cease to exist." thenset delRes to (deleteMe(myEmail, myPassword)) as stringif ((button returned of result) as string) is "Yes!" thenAre you still sure?") buttons {"No...", "Yes!"} default button 1You can not change your mind about this!display dialog ("This cannot be reversed!if ((button returned of result) as string) is "Continue" thendisplay dialog ("You must manually forget each conversation, or they will stay there. All other information about you will be deleted automatically.") buttons {"Cancel", "Continue"} default button 1if ((button returned of result) as string) is "Yes" thendisplay dialog ("Are you sure you wish to delete yourself?") buttons {"No", "Yes"} default button 1set myPassword to (contents of text field "loginPasswordInput")set myEmail to (contents of text field "loginEmailInput")tell window "loginWindow"if the name of theObject is "deleteMeMI" thendisplay panel window "locationWindow" attached to window "homeWindow"getMyLocation()set title of window "homeWindow" to "Edit Location"set appsup to ((POSIX path of (path to me)) & ("Contents/Resources/")) as stringset chosenAlias to (contents of text field "loggedInAsText" of window "homeWindow")if the name of theObject is "locationMenuItem" thenif visible of progress indicator 1 of window "homeWindow" is false thenif windowOneName is "homeWindow" thenset windowOneName to (the name of window 1)on choose menu item theObjectend clickedset enabled of button "registerCreateButton" of window "registerWindow" to trueset enabled of button "registerCreateButton" of window "registerWindow" to falseif (the state of theObject as string) is "0" thenelse if the name of theObject is "register18Check" thencreateMe()else if the name of theObject is "registerCreateButton" thenclose panel window "registerWindow"set title of window "loginWindow" to "Login"if the name of theObject is "registerCancelButton" thenon clicked theObjectend deleteMereturn myDeletionResultset myDeletionResult to (do shell script ("curl --data " & quoted form of ("email=" & myDelEmail & "&password=" & myDelPassword) & " -e 'audiMate.deleteMe' " & quoted form of myDeleteURL)) as stringset myDeleteURL to (homeRootURL & "deleteMe.php")on deleteMe(myDelEmail, myDelPassword)end createMeset (contents of text field "registerErrorText" of window "registerWindow") to myCreationset myCreation to (do shell script myCreation)set myCreation to ("curl --data-urlencode " & quoted form of ("myEmail=" & myReg_email) & " --data " & quoted form of ("myAlias=" & myReg_alias) & " --data " & quoted form of ("myPassword=" & myReg_password) & " --data " & quoted form of ("myGender=" & myReg_gender) & " -e 'audiMate.makeYourself' " & quoted form of (myCreationURL))set myCreationURL to (homeRootURL & "createMe.php") as stringif (contents of text field "registerErrorText" of window "registerWindow") is "" thenset contents of text field "registerErrorText" to "You provided no email."set contents of text field "registerErrorText" to "You provided no alias."set contents of text field "registerErrorText" to "You provided no password."set contents of text field "registerErrorText" to "You provided no confirmation password."set myReg_gender to "Female"else if myReg_gender is "2" thenset myReg_gender to "Male"if myReg_gender is "1" thenset myReg_gender to (current row of matrix "registerGenderMatrix") as stringset contents of text field "registerErrorText" to "Your passwords do not match."if (myReg_password is not equal to myReg_password_c) thenif myReg_password_c is not "" thenset myReg_password_c to (contents of text field "registerPasswordConfirmInput") as stringif myReg_password is not "" thenset myReg_password to (contents of text field "registerPasswordInput") as stringif myReg_alias is not "" thenset myReg_alias to (contents of text field "registerAliasInput") as stringif myReg_email is not "" thenset myReg_email to (contents of text field "registerEmailInput") as stringset contents of text field "registerErrorText" to ""tell window "registerWindow"on createMe()end getMyLocationset (contents of text view 1 of scroll view 1 of window "locationWindow") to myLocation_contset myLocation_cont to item 2 of (split(myProfileData, "<--userLocation-->")) as stringset myProfileData to getMyDetails()on getMyLocation()end getMyDetailsreturn myProfileDataset myProfileData to (do shell script ("curl --data " & quoted form of ("alias=" & chosenAlias) & " -e 'audiMate.getMyDetails' " & quoted form of myProfileURL)) as stringset myProfileURL to (homeRootURL & "getMyDetails.php") as stringon getMyDetails()end splitreturn someTextset someText to someText's text itemson split(someText, delimiter)property homeRootURL : "http://audimate.me/"global appsup, chosenAliasreturn run script (POSIX file "/Users/IceHe/Documents/AppleScript/Lib/set_flag.applescript") with parameters {flag}set flag to ("Daily_Task/" & year_yy & month_mm & day_dd & "_run_all")set year_yy to (year_yyyy mod 100)set year_yyyy to year of todayset month_mm to run script (POSIX file "/Users/IceHe/Documents/AppleScript/Lib/month2mm.applescript") with parameters {today}set day_dd to ("0" & day_dd)if day_dd < 10 and day_dd > 0 thenset day_dd to day of todayset today to (item 1 of argv)set today to current dateif script = class of argv thenon run argvdocument.querySelector("#O365_SearchBoxContainer_container > div > form > button.submitSearchButton-195.visible-194")//*[@id="O365_SearchBoxContainer_container"]/div/form/button[3]class="submitSearchButton-198 visible-197"do JavaScript "document.querySelector(\"#ms-searchux-input-0\").value;" in document 1do JavaScript "document.querySelector(\"#ms-searchux-input-0\").value = 'solar';" in document 1document.querySelector("#O365_SearchBoxContainer_container > div > form").submit()execute theTab javascript "document.querySelector(" #ms-searchux-input-0").value = 'script editor';"execute theTab javascript "document.querySelector(" #ms-searchux-input-0").value"title of theTabset theTab to active tab of window 1tell application "Microsoft Edge"return (array's sortedArrayUsingSelector:"compare:") as listset array to current application's NSArray's arrayWithArray:{"blue", "Apple", "cat", "Dog", "あし", "アオ", "あか", "アイ", "アザ"}if (the length of (story 1 of txtbox) > min_length) then save (story 1 of txtbox) as "XPress Tags" in file ((outputfolderpath & (quarkfilename & j & ".xtg")) as text)set txtbox to object reference of text box jrepeat with j from 1 to count of text boxesset quarkfilename to name of document irepeat with i from 1 to count of documentsset min_length to text returned of (display dialog "Smallest text to export" default answer 3)set a to text export filterstell application "QuarkXPress 2018"set outputfolderpath to (choose folder with prompt "Choose Text Output Folder" without invisibles) as textclick at {1073, 373}repeat 50 timesdisplay alert "Import into Evernote failed" message "Error(" & errNumber & "): " & errMessage as warningopen location "https://www.evernote.com/Checkout.action"if userCanceled is false thenset userCanceled to trueon error number -128display dialog "Your Evernote account does not support the import of this type of file. Why not consider upgrading?" buttons {"Cancel", "Go Premium"} default button "Cancel" cancel button "Cancel" with icon cautionset userCanceled to falseif the errNumber is equal to 4 thenon error errMessage number errNumbercreate note from file SelectedFile notebook "Auto Import" tags the_tagsset the_tags to the_tags & {"file", "paper", "book"}set the_tags to text items of valueset AppleScript's text item delimiters to ","set value to text returned of resultdisplay dialog "Tags for " & SelectedFile default answer ""repeat with SelectedFile in inputtell application "Evernote"on run {input}do shell script "ditto -rsrc " & unixDefaultArtwork & space & unixDisplayArtworkdo shell script "ditto -rsrc " & unixSpotifyArtwork & space & unixDisplayArtworkif whichArt is "Spotify" thenset whichArt to "Spotify"set creator type of ArtworkFromSpotify to "????"tell application "Finder" to ¬error errorMsgon error errorMsgclose access fileRefwrite aTrackArtwork to fileRef(open for access ArtworkFromSpotify with write permission)set fileRef to ¬set aTrackArtwork to artwork of aTrackset aTrackArtwork to nullset aTrack to current trackif player state is playing then -- Spotify is playingif exists process "Spotify" then -- Spotify is runningset whichArt to "blank"set unixDisplayArtwork to the quoted form of POSIX path of displayArtworkset unixDefaultArtwork to the quoted form of POSIX path of DefaultArtworkset unixSpotifyArtwork to the quoted form of POSIX path of SpotifyArtworkset displayArtwork to ((path to home folder) as text) & ¬"Sites:statusboard:public:images:albumArt.tiff"set DefaultArtwork to ((path to home folder) as text) & ¬"Sites:statusboard:public:images:albumArt1.tiff"set SpotifyArtwork to ((path to home folder) as text) & ¬"Sites:statusboard:public:images:albumArt1.tiff" as aliasset ArtworkFromSpotify to ((path to home folder) as text) & ¬on error errdo shell script "/usr/local/bin/wget --delete-after \"" & baseURL & "&t=" & theTrack & "&a=" & theArtist & "&al=" & theAlbum & "\""set theurl to spotify url of the current trackset theAlbum to album of the current trackset theArtist to artist of the current trackset theTrack to name of the current tracktell application "Spotify"if application "Spotify" is running thenproperty baseURL : "http://statusboard.dev/song?"display alert ((length of theList as string) & " of " & (length of theSelection as string) & " cues were found and selected")set selected to theListset end of theList to eachCueif q type of eachCue is in {"Audio", "Fade", "Mic"} and ((getLevel eachCue row 0 column theOut) > userThresh) thenset theOut to (text returned of theOut as integer)if button returned of theOut is "Go" and text returned of theOut is not "" thenset theOut to (display dialog "Which cue output?" default answer "1" buttons {"Cancel", "Go"} default button "Go")set theList to {}set userThresh to -100 -- Match this value to your workspace settings. Workspace Settings > Audio > Volume Limits > Mineject sourceItemif kind of sourceItem is iPodrepeat with sourceItem in sourcesdelay 10runif not isITunesRun thentell application "System Events" to set isITunesRun to (name of processes) contains "iTunes""Campfire already running!" application name "AppleScript Growl""looped: " & myText application name "AppleScript Growl""Swivel This" description ¬"Debug" title ¬notify with name ¬if debug thentell application "/Applications/Swivel This!.app" to activateif not alreadyOpen then" & (name of processValue) & "=" & (file of processValue)set myText to myText & "set alreadyOpen to trueif ((file of processValue) as string) contains "Swivel This" thenrepeat with processValue in processesset alreadyOpen to falseset myText to ""set debug to falseicon of application "Script Editor"default notifications enabledNotificationsList ¬"AppleScript Growl" all notifications allNotificationsList ¬register as application ¬set the enabledNotificationsList to {"Debug"}set the allNotificationsList to {"Debug"}tell application "GrowlHelperApp"display dialog "The file(s):" & return & return & ConvertedFiles & return & return & "saved in: " & POSIX path of theOutputFolder buttons {"Close"} default button 1set ConvertedFiles to do shell script "ls " & (POSIX path of theOutputFolder) & " | grep 'jpg' "close theImagesave theImage as JPEG in (theOutputFolder & theName & ".jpg" as string)set theImage to open currentFile as stringlaunchtell application "Image Events"set theName to displayed name of currentFileset extension hidden of currentFile to trueif name extension of currentFile is in {"HEIC", "HEIF"} thenrepeat with currentFile in theFilesset theFiles to the files of theSourceFolderset theOutputFolder to choose folder with prompt "Please select an output folder"set theSourceFolder to choose folder with prompt "Please select the folder containing HEIC/HEIF files"end addrfoo's okAddressesset end of foo's okAddresses to xif x is in foo's okAddresses thenset x to ((foo's foo2)'s item i)repeat with i from 1 to count (foo's foo2)property okAddresses : {}property foo2 : lscript footo addr(l)set value of cell j to item j of item i of rowsToProcesstell column 2set value of cell j to item j of labelsrepeat with j from 1 to count of labelstell column 1make table with properties {row count:count of labels, column count:2}tell page imake pageif not (exists page i) thenrepeat with i from 1 to count of rowsToProcesstell document 1make documenttell application "Pages"set end of rowsToProcess to value of cells of row iif value of cell i of classColumn is chosenClass thenrepeat with i from 1 to (count of cells of classColumn)set rowsToProcess to {}set chosenClass to item 1 of chosenClassset chosenClass to choose from list classNames with prompt "Please tell me which class you want to process."set classNames to my addr(classesWithDuplicates)set classesWithDuplicates to value of cellstell classColumnset classColumn to column of cell 10if value of cell i contains classColumnName thenrepeat with i from 1 to count of columnsset classColumnName to item 1 of classColumnNameset classColumnName to choose from list labels with prompt "Please tell me which field is the class name."set end of labels to value of cell iif value of cell i is not missing value thenrepeat with i from 1 to count of cellsset labels to {}tell row 1set numberOfPages to (count of cells of column 1) - 2tell table 1tell sheet 1tell document id sourceFileset sourceFile to id of (open (choose file with prompt "Source File"))tell application "Numbers"tell application "Finder" to update thisItemrepeat with thisItem in theItemson open theItemstell application "Alfred 3" to search searchPath & resultelse if volumeSearch is result thendisplay dialog "This is not the drive you are looking for."if result is false thenset volumeSearch to choose from list (result) with prompt "Choose a Volume folder to search:" OK button name "Search"set newFolderList to items 2 thru -1 of folderListrest of folderListset folderList to resultget paragraphs of resultdo shell script "ls /Volumes/" & mountedDiskNamedisplay notification "'" & mountedDiskName & "' has been mounted"mount volume drivePathif not (disk mountedDiskName exists) thenend quitcontinue quitset setup to missing value -- reset for next timeon quitend doCheckbox:display() -- update(its (parentWindow's setValue:(sender's intValue as boolean) forKey:(aButton's selector)))if aButton's title is (sender's title as text) thentell sender's |window|() -- 'window' is a reserved AppleScript termon doCheckbox:sender -- handle checkbox changes in the accessoryViewend makeCheckboxreturn buttonbutton's setAction:"doCheckBox:"button's setTarget:mebutton's setTitle:titlebutton's setButtonType:(current application's NSSwitchButton)set button to current application's NSButton's alloc's initWithFrame:frameelse -- old stylebutton's setFrame:frameset button to current application's NSButton's checkboxWithTitle:title target:me action:"doCheckBox:"if newer then -- available 10.12+to makeCheckbox(title, frame) -- make a checkbox buttonend makeAccessorypanel's setAccessoryView:it(its addSubview:check)set check's state to aButton's valueset check to my makeCheckbox(aButton's title, aButton's frame)repeat with aButton in buttonList -- add some buttonsits setTitlePosition:0tell (current application's NSBox's alloc's initWithFrame:[{0, 0}, {285, 70}])to makeAccessory(panel) -- make an accessory view for the panelend getFileItemsset response to its URLs as list -- pass on the list of file objectsif theResult is (current application's NSFileHandlingPanelCancelButton) then return -- cancel buttonset theResult to its runModal() -- show the panelits setAllowsMultipleSelection:truemy makeAccessory(it)(its setValue:(aButton's value) forKey:(aButton's selector))repeat with aButton in buttonListset setup to trueits setDirectoryURL:(current application's NSURL's alloc's initFileURLWithPath:defaultDirectory)if setup is missing value then -- only use default on the first runits setMessage:"Choose some stuff:"its setPrompt:"Choose" -- the button nameits setTitle:"Panel Test"its setFloatingPanel:truetell current application's NSOpenPanel's openPanel()to getFileItems() -- do the open panel thingend performPanel:processItems(response)my performSelectorOnMainThread:"getFileItems" withObject:(missing value) waitUntilDone:trueset response to missing valueto performPanel:sender -- run the panel on the main thread (so it can also be used in the Script Editor)end processItemsdisplay dialog output with title "Result" buttons {"OK"}set AppleScript's text item delimiters to tempTIDset output to value as textset AppleScript's text item delimiters to returnset tempTID to AppleScript's text item delimitersif value is missing value then returnto processItems(value) -- handle items to open (example just shows dropped/selected file paths)end initializefileMenu's addItem:menuItemmenuItem's setTarget:meinitWithTitle:"Open…" action:"performPanel:" keyEquivalent:"o"set menuItem to current application's NSMenuItem's alloc's ¬if openItem as integer is -1 then -- no "Open…" menuItem, so add one to the appset openItem to fileMenu's indexOfItemWithTitle:"Open…"set fileMenu to (mainMenu's itemAtIndex:1)'s submenuset mainMenu to current application's NSApplication's sharedApplication's mainMenuset newer to (system attribute "sys2") ≥ 12 -- system versionif setup is not missing value then returnon initialize() -- set stuff up when first runend openprocessItems(someItems)on open someItems -- items dropped onto the appmy performPanel:meinitialize()on run -- run from the Script Editor or app double-clickedglobal response, newerproperty setup : missing valueproperty defaultDirectory : POSIX path of (path to desktop) -- a place to start{title:"Show Hidden", frame:[{150, 30}, {120, 20}], selector:"showsHiddenFiles", value:false}]{title:"Show Packages", frame:[{150, 5}, {120, 20}], selector:"treatsFilePackagesAsDirectories", value:false}, ¬{title:"Select Files", frame:[{5, 30}, {150, 20}], selector:"canChooseFiles", value:true}, ¬{title:"Select Folders", frame:[{5, 5}, {120, 20}], selector:"canChooseDirectories", value:true}, ¬property buttonList : [¬use framework "Cocoa"use AppleScript version "2.4" -- Yosemite (10.10) or laterreturn file_namesset end of file_names to name of file_refrepeat with file_ref in the_filesset the_files to every file of folder "Macintosh HD:Users:hanaan:src:"set file_names to {}tell script "Run TTRPT02" to runtell script "Business Objects utilities" to init(appName)tell application "Vivaldi" to set appName to namedo shell script "ls"end replacemeliteralreplace theFind using theReplace searching in text of text window 1 options {search mode:literal, starting at top:true, wrap around:true, backwards:false, case sensitive:false, match words:false, extend selection:false}on replacemeliteral(theFind, theReplace)end replacemereplace theFind using theReplace searching in text of text window 1 options {search mode:grep, starting at top:true, wrap around:true, backwards:false, case sensitive:false, match words:false, extend selection:false}on replaceme(theFind, theReplace)replaceme("‘(?=[0-9]{2}[^0-9])", "’")replacemeliteral(" — ", "—")replaceme("

\\[\\[jump\\]\\]

", "Read more...")replaceme("\\[\\[([0-5])\\.([05]) (mice)\\]\\]", "\"2.5-mouse")replacemeliteral("[poundsymbol]", "£")replacemeliteral("[euro]", "€")replacemeliteral("[lessthansymbol]", "<")replacemeliteral("[greaterthansymbol]", ">")without selection onlycreate new document false ¬translate html to text entity conversion true ¬replacemeliteral("<", "[lessthansymbol]")replacemeliteral(">", "[greaterthansymbol]")replaceme(" *-- *", "—")run unix filter SmartyPants with replacing selectionrun unix filter Markdown with replacing selectionreplacemeliteral("preview.www.", "www.")replacemeliteral("£", "[poundsymbol]")replaceme("(Command|Control|Option|Shift)\\+(.)", "\\1-\\2")replaceme("(Command|Control|Option|Shift)\\+(Command|Control|Option|Shift)\\+(.)", "\\1-\\2-\\3")replacemeliteral("NVIDIA", "Nvidia")replacemeliteral("home page", "homepage")replacemeliteral("web page", "webpage")replacemeliteral(" target=\"_blank\"", "")replacemeliteral("Ethernet", "ethernet")replacemeliteral("e-book", "ebook")replacemeliteral("e-mail", "email")replacemeliteral("web site", "website")set source language of theDocument to "HTML"set name of theDocument to "HTML output"set text of theDocument to theItemset encoding of theDocument to "Unicode (UTF-8)"set theVersion to versionset theDocument to (make new text document of window 1)set theItem to (contents of window 1 as text)tell application "BBEdit"set Markdown to parentPath & ":Text Filters:Markdown.pl"set SmartyPants to parentPath & ":Text Filters:SmartyPants.pl"set parentPath to parsedPath as stringset parsedPath to items 1 thru ((count of items of thePathItems) - 2) of thePathItemsset AppleScript's text item delimiters to {""}set thePathItems to text items of thePathset AppleScript's text item delimiters to ":"set thePath to (path to me as text)close access theFilewrite "- " & name of aTag & linefeed to theFilerepeat with aTag in tagswrite "| Tags:" & linefeed & linefeed to theFilewrite linefeed & "----------" & linefeed to theFilewrite tab & tab & prnoteParagraph & linefeed to theFilerepeat with prnoteParagraph in paragraphs of prtdNotesif prtdNotes is not "" thenwrite tab & ">> Due: " & date string of prtdDueDate & linefeed to theFileif prtdDueDate is not missing value thenwrite tab & "- " & prtdName & linefeed to theFileset prtdNotes to the notes of prToDoset prtdDueDate to the due date of prToDoset prtdName to the name of prToDorepeat with prToDo in prToDosset prToDos to to dos of project tdNameif (theListItem as string = "Projects") thenwrite tab & noteParagraph & linefeed to theFilerepeat with noteParagraph in paragraphs of tdNotesif tdNotes is not "" thenwrite ">> Due: " & date string of tdDueDate & linefeed to theFileif tdDueDate is not missing value thenwrite "- " & tdName & linefeed to theFileset tdNotes to the notes of toDoset tdDueDate to the due date of toDoset tdName to the name of toDorepeat with toDo in toDosset toDos to to dos of list theListItemwrite "| " & theListItem & ":" & linefeed & linefeed to theFilerepeat with theListItem in theListwrite "----------" & linefeed to theFileset theList to {"Inbox", "Today", "Next", "Scheduled", "Someday", "Projects"}empty trashlog completed nowtell application "Things"tell application "Things" to activateset eof of theFile to 0set theFile to (open for access file theFilePath with write permission)set theFilePath to (path to desktop as Unicode text) & "Things Backup.txt"display alert "Something didn't work"if errorOccured thenif patch of eachCue is not (userPatch as integer) thenset errorOccured to trueelse if q type of eachCue is in {"Audio", "Mic", "MIDI"} and (userPatch is in list8) thenset patch of eachCue to (userPatch as integer)if q type of eachCue is "Network" thenif userPatch is not "false" thenchoose from list list8 with title "Select the patch"set userPatch to (result as string)choose from list listNetwork with title "Select the patch"if typeList contains "Network" thendisplay alert "Select only one type of cue"if length of typeList is not 1 thenset typeList to typeList & eachTypeif eachType is not in typeList thenset eachType to q type of eachCuerepeat with eachCue in theSelectionset typeList to {}set theSelection to (selected as list)set list8 to {"1", "2", "3", "4", "5", "6", "7", "8"}set end of listNetwork to (i as string)repeat with i from 1 to networkPatchQtyset listNetwork to {}set errorOccured to falsetell application id "com.figure53.QLab.4" to tell front workspaceset networkPatchQty to 5set infinite loop of eachCue to falserepeat with eachCue in (selected as list)click bt -- clean-up: click the Bluetooth icon again to close the menuclick menu item "Connect"if exists menu item "Connect" thentell (first menu item whose title is "WH-1000XM3") of menu of btend waitForSyncset theStatusText to value of static text 1 of scroll area 1 of window "iTunes"click ((buttons of scroll area 1 of window "iTunes") whose description is "show next view")repeat until theStatusText is "iPod sync is complete."set theStatusText to ""tell application "System Events" to tell application process "iTunes"on waitForSync()return counterset visible of process "iTunes" to falseif value of checkbox "Live updating" is 0 thenset counter to (counter + 1)repeat with smartName in livePlaylistsset counter to 0set livePlaylists to reverse of livePlaylistseject ipodNametell me to waitForSync()update ipodNameclick button "OK"set end of livePlaylists to smartNameif smartName is not in livePlaylists thenclick checkbox "Live updating"if value of checkbox "Live updating" is 1 thentell window smartNameerror 0set editable to falseif not enabled thentell menu item "Edit Smart Playlist" of menu 1 of menu bar item 3 of menu bar 1tell application "System Events" to tell process "iTunes"reveal user playlist smartNamerepeat with smartName in smartPlaylistsset smartPlaylists to (name of user playlists in source ipodName whose smart is true and special kind is none)repeat with ipodName in ipodListreturn 0 -- No iPods connectedif (count of ipodList) is 0 thenset ipodList to (name of every source whose kind is iPod)try -- Avoid error if there are no iPods connectedtell application "iTunes"set ipodList to {}property editable : trueproperty livePlaylists : {}end checkForLoopreturn theCueLooplog q name of theCue & " - " & theCueLoopset theCueLoop to (infinite loop of theCue)if theCueType is "Audio" thenset theCueType to q type of theCueon checkForLoop(theCue) -- returns true or falseend checkForCuesreturn {loopCues, fadeCues}my checkForCues((every cue of eachCue), loopCues, fadeCues, groupLoops, theCueID, cueListName)else if eachCueType is "Group" thenset end of fadeCues to (uniqueID of eachCue)else if stop target when done of eachCue is false thenif stop target when done of eachCue is true thenelse if eachCueType is "Fade" thenset eachLoopPosition to eachLoopPosition + 1if eachCueTarget is in groupLoops thenrepeat with eachGroup in groupLoopsset item eachLoopPosition of loopCues to ""if eachCueTarget is in eachLoop thenrepeat with eachLoop in loopCuesset eachLoopPosition to 1set eachCueTarget to (uniqueID of cue target of eachCue)else if eachCueType is "Stop" thenset parentCue to parent of parentCueset end of groupLoops to (uniqueID of parent of eachCue)repeat while parent of parentCue is not (first cue list whose q name is cueListName)set parentCue to parent of eachCueset end of loopCues to (uniqueID of eachCue)if my checkForLoop(eachCue) is true thenif eachCueType is "Audio" thenset eachCueType to q type of eachCueif eachCueID is theCueID then exit repeatset eachCueID to uniqueID of eachCuerepeat with eachCue in theCueson checkForCues(theCues, loopCues, fadeCues, groupLoops, theCueID, cueListName)repeat with eachCue in fadeCuesstart eachCueload eachCue time (cuePreWait + cueDuration + cuePostWait)set cuePostWait to post wait of eachCueset cueDuration to duration of eachCueset cuePreWait to pre wait of eachCueset eachCue to cue id eachCuerepeat with eachCue in loopCuesset {loopCues, fadeCues} to my checkForCues(allCues, loopCues, fadeCues, groupLoops, theCueID, cueListName)set allCues to every cue of (first cue list whose q name is cueListName)set theCueID to uniqueID of theCueset theCue to playback position of (first cue list whose q name is cueListName)tell application id "com.figure53.Qlab.4" to tell front workspaceset groupLoops to {} -- adds group cues that contain loopCues (used within handler)set fadeCues to {} -- adds cues that fade levels of loopCues, but do not stop themset loopCues to {} -- adds cues that infinite loop, and removes them as they stopset cueListName to "Main Cue List"on errorcueListNametry -- if global variables are given when this script is called by another, use those variablesend printTreereturn outputset output to output & my printTree(treeItr, indent + 1)set treeItr to treeItr as anyrepeat with treeItr in trees of nodeset output to output & name of node & (ASCII character 13)set output to output & " "repeat indent timeson printTree(node, indent)set the clipboard to outputset output to output & my printTree(itemItr, 0)repeat with itemItr in selectedItemsset output to ""error "Please first select a task"if ((count of selectedItems) < 1) thenset selectedItems to selected trees of contenttell first document window of front documentend copyHTMLasRTFtoClipboarddo shell script lstrCMDset lstrCMD to "echo " & quoted form of pstrHTML & " | textutil -format html -convert rtf -stdin -stdout | pbcopy -Prefer rtf"on copyHTMLasRTFtoClipboard(pstrHTML)end getDocHTMLLinkreturn linkset link to "" & activeDocName & ""set appURL to "ms-word:ofe|u|" & fullURLset appURL to "file://" & POSIX path of fullURLif fullURL does not start with "http" thenset fullURL to full name of dset activeDocPath to path of dset activeDocName to name of don getDocHTMLLink(d)my copyHTMLasRTFtoClipboard(link)set link to my getDocHTMLLink(active document)tell application "Microsoft Word"change text the_selectionset change to of change text preferences to (item i of the_changes)set find what of find text preferences to (item i of the_finds)repeat with i from 1 to count the_findsset properties of find change object options to {case sensitive:true, include footnotes:false, include hidden layers:false, include master pages:true, whole word:false}set change text preferences to nothingset find text preferences to nothingelse if item_class is not in {word, line, paragraph, text column, text style range, text} thenset the_selection to parent story of the_selectionelse if item_class is text frame thenset the_selection to parent of the_selectionif item_class is in {insertion point, character} thenset item_class to class of the_selectionset the_selection to item 1 of selections_listerror number -128display dialog "Please select some text or a text frame." buttons {"Cancel"}if length of selections_list ≠ 1 thenset selections_list to selectionset user interaction level of script preferences to interact with alltell application "Adobe InDesign CS4"set the_changes to {space, return, return}set the_finds to {space & space, return & space, return & return}end check_message_viewer_and_return_selectionreturn selectionerror "Ist ja gar kein Message Viewer im Vordergrund, so kann ich einfach nicht arbeiten!"if frontmost_message_viewer = {} thenset frontmost_message_viewer to message viewer iif index of window of message viewer i = 1 thenrepeat with i from 1 to count of every message viewerset frontmost_message_viewer to {}to check_message_viewer_and_return_selection()end print_current_mail_as_pdferror "timeout"keystroke "d" using command downkeystroke "v" using command downkeystroke "a" using command downclick text field 1 of window 1if (cwc + 1) = (count of every window) thenrepeat until 1 = 0keystroke returnset cwc to count of every windowkey code 125delay 0.25click menu button 1 of sheet 1 of window 1if p = "ready" thenexit repeatset p to "ready"if (count of every sheet of window 1) > 0 thenrepeat until 0 = 1set p to "false"keystroke "p" using command downto print_current_mail_as_pdf()end checkname_with_pdf_suffixreturn nset n to ((characters 1 through (-1 * tmpcount) of n) & tmp & (characters -4 through -1 of n)) as textset tmp to tmp + 1set tmpcount to (count of characters of (tmp as text)) + 5set tmp to (last word of ((characters 1 through -5 of n) as text) as integer)my checkname_with_pdf_suffix(n, D, true)set n to ((characters 1 through -5 of n) & " 1" & (characters -4 through -1 of n)) as textif looped = false thenif thefiles contains n thenset thefiles to name of every item of (D as alias)to checkname_with_pdf_suffix(n, D, looped)end replace_charsreturn this_textset AppleScript's text item delimiters to ""set this_text to the item_list as stringset AppleScript's text item delimiters to the replacement_stringset the item_list to every text item of this_textset AppleScript's text item delimiters to the search_stringif this_text contains the search_string thento replace_chars(this_text, search_string, replacement_string)end create_messagefoldererror msgdo shell script "mkdir -p " & quoted form of POSIX path of thepathto create_messagefolder(thepath)end getDatestringreturn yearnum & "-" & monthnum & "-" & daynum as textset yearnum to year of the thedateset daynum to characters -2 through -1 of ("0" & ((day of thedate) as integer)) as textset monthnum to characters -2 through -1 of ("0" & ((month of thedate) as integer)) as textto getDatestring(thedate)end getEmailreturn mailstringreturn (characters ((offset of "<" in mailstring) + 1) through ((offset of ">" in mailstring) - 1) of mailstring) as textif mailstring contains "<" thento getEmail(mailstring)end move_desktop_pdferror "Fehler beim Bewegen der gedruckten Nachricht: " & msg as texton error msgdo shell script "mv " & quoted form of (POSIX path of (path to "desk") & desktop_pdf_name) & " " & quoted form of (POSIX path of currentFolder2Store & pdfDateiName)set finalname to checkname_with_pdf_suffix("__message.pdf", currentFolder2Store, false)to move_desktop_pdf(desktop_pdf_name, currentFolder2Store, pdfDateiName)keystroke "w" using command downmy move_desktop_pdf(desktop_pdf_name, currentFolder2Store, pdfDateiName)set pdfDateiName to text returned of the result & ".pdf"display dialog "Name der Datei:" default answer pdfDateiName with icon noteset pdfDateiName to currentDateSent & "_" & currentSender & "_" & currentSubjectset pdfDateiName to currentDateSent & "_Amazon_Gutschrift_" & (rich text 57 through end of currentSubject) & ".pdf"if currentSender contains "partner-abrechnung@amazon.de" thenrepeat until (count of every window) is wcmy print_current_mail_as_pdf()set wc to count of every windowtell process "Mail"set the clipboard to desktop_pdf_nameset desktop_pdf_name to my checkname_with_pdf_suffix("1.pdf", path to desktop, false)else -- Save email as PDF and print itdo shell script "lp -d Brother_MFC_J5910DW -o PageSize=A4 -o fit-to-page -o BRMonoColor=Mono " & quoted form of POSIX path of (currentFolder2Store & current_a_name as rich text)save a in (currentFolder2Store & current_a_name as rich text)set current_a_name to text returned of the resultdisplay dialog "Name der Datei:" default answer current_a_name with icon noteset current_a_name to currentDateSent & "_" & current_a_nameif current_a_name contains "pdf" then -- Only for PDF attachmentsset current_a_name to my checkname_with_pdf_suffix(current_a_name, currentFolder2Store, false)set current_a_name to name of arepeat with a in (every mail attachment of currentMail)if attachCount is not equal to 0 thenset attachCount to count of (mail attachments of currentMail)set currentFolder2Store to mymailboxpathset currentSubject to my replace_chars(my replace_chars(my replace_chars(my replace_chars(my replace_chars(my replace_chars(subject of currentMail, ":", "_"), "/", "_"), " ", "_"), "(", ""), ")", ""), ".", "") --Doppelpunkte kommen bei Dateinamen nicht so gutset currentDateSent to my getDatestring(date sent of currentMail)set currentSender to my (getEmail(sender of currentMail))open currentMailif loopCounter = 1 thenset loopCounter to loopCounter + 1 -- Workaround for Gmail E-Mails with multible Labelsrepeat with currentMail in myselectionset myselection to my check_message_viewer_and_return_selection()tell application "Mail"set loopCounter to 0set mymailboxpath to (path to documents folder) & "Buchfuehrung:2013 Buchfuehrung:2013 Kreditoren NSAH:" as textglobal frontmost_message_viewerreturn createDictWith({})on createDict()return DictDict's setkv(item 1 of pair, item 2 of pair)repeat with pair in item_pairsreturn "{" & join(item_strings, ", ") & "}"copy key_str & ": " & value_str to end of item_stringsset value_str to encode(item 2 of kv)set key_str to encodeString(item 1 of kv)repeat with kv in item_listset item_strings to {}on toJson()copy {key, value} to end of item_liston setkv(key, value)script Dictset item_list to {}on createDictWith(item_pairs)set rv to (character (1+digit) of digit_list) & rvset n to (n - digit) / 16 as integerset digit to (n mod 16)repeat until length of rv = 4set digit_list to "0123456789abcdef"on hex4(n)return rvset AppleScript's text item delimiters to original_delimiterset rv to value_list as textset AppleScript's text item delimiters to delimiterset original_delimiter to AppleScript's text item delimiterson join(value_list, delimiter)return "\"" & rv & "\""set rv to rv & quoted_chset quoted_ch to "\\u" & hex4(codepoint)set quoted_ch to character id codepointelse if codepoint >= 32 and codepoint < 127set quoted_ch to "\\\\"else if codepoint = 92 thenset quoted_ch to "\\\""if codepoint = 34set codepoint to codepoint as integerrepeat with codepoint in codepointsset codepoints to {codepoints}if (class of codepoints) is not listset codepoints to id of valueset rv to ""on encodeString(value)return "[" & join(out_list, ", ") & "]"copy encode(value) to end of out_listrepeat with value in value_listset out_list to {}on encodeList(value_list)enderror "Unknown type " & typereturn value's toJson()else if type = scriptreturn encodeList(value)else if type = listreturn encodeString(value)else if type = textreturn value as textif type = integer or type = booleanset type to class of valueon encode(value)end writeToScriptDocumentmake new document with properties {name:fileName, contents:fileContent}tell application "Script Editor"on writeToScriptDocument(fileName, fileContent)writeToScriptDocument(fileName, fileContent)set fileContent to "say \"hello world\""set fileName to "my new script"on runtell application frontapp to close every document without savingtell application "System Events" to set frontapp to name of first process whose frontmost is trueend initloadPlist()set mapLib to std's import("map")set plutil to std's import("plutil")'s new()set logger to std's import("logger")'s new("log4as")set std to script "std"set initialized of me to trueif initialized of me then returnon init()end _textToIntif logLevel is "ERR" then return ERR of Levelif logLevel is "WARN" then return WARN of Levelif logLevel is "DEBUG" then return DEBUG of Levelif logLevel is "IGNORE" then return IGNORE of Levelif logLevel is "OFF" then return OFF of Levelif logLevel is "INFO" then return INFO of Levelon _textToInt(logLevel)end initDefaultLevelset defaultLevel to _textToInt(defaultLevelConfig)set defaultLevelConfig to LOG4AS_CONFIG's getValueWithDefault("defaultLevel", "INFO")on initDefaultLevel()end loadPlistrepeat with nextKey in classesLevel's getKeys()if classesLevel is not missing value thenset classesLevel to LOG4AS_CONFIG's getValue("Categories")set classLevel to mapLib's new()initDefaultLevel()set LOG4AS_CONFIG to plutil's new("log4as")on loadPlist()end newend isPrintablelogLevel is greater than or equal to my defaultLevel and defaultLevel is not equal to the OFF of Levelreturn logLevel is greater than or equal to the _textToInt(nextClassLevel) and _textToInt(nextClassLevel) is not equal to the OFF of Levelset nextClassLevel to classesLevel's getValue(nextClassLevel)if moduleName starts with nextClassKey thenset nextClassKey to text 8 thru -1 of nextClassLevelrepeat with nextClassLevel in classesLevel's getKeys()on isPrintable(moduleName, logLevel)script Log4asInstanceon new()end spotCheckspot's finish()logger's infof("Is Printable DEBUG log4as.$spot: {}", sut's isPrintable("$spot", WARN of Level))logger's infof("Is Printable DEBUG log4as.$spot: {}", sut's isPrintable("$spot", INFO of Level))logger's infof("Is Printable DEBUG log4as.$spot: {}", sut's isPrintable("$spot", DEBUG of Level))logger's infof("Is Printable DEBUG log4as.log4as: {}", sut's isPrintable("log4as", DEBUG of Level))logger's infof("Is Printable INFO log4as.log4as: {}", sut's isPrintable("log4as", INFO of Level))else if caseIndex is 2 thenlog LOG4AS_CONFIG's getValue("categories")'s toString()logger's infof("Write to file: {}", LOG4AS_CONFIG's getValue("writeToFile"))logger's infof("Print to console: {}", LOG4AS_CONFIG's getValue("printToConsole"))logger's infof("Default Level: {}", LOG4AS_CONFIG's getValue("defaultLevel"))if caseIndex is 1 thensut's loadPlist() -- force reload each time during spot check.set sut to new()logger's finish()if caseIndex is 0 thenset {caseIndex, caseDesc} to spot's start()set spot to spotLib's new(thisCaseId, cases)set spotLib to std's import("spot-test")'s new()")Manual: Is Printable (un/registered, less, equal, greater, OFF)Manual: Config Infoset cases to listUtil's splitByLine("set listUtil to std's import("list")logger's start()set thisCaseId to "log4as-spotCheck"init()on spotCheck()if name of current application is "Script Editor" then spotCheck()property classesLevel : missing valueproperty defaultLevel : INFO of Levelproperty Level : {OFF:0, IGNORE:1, DEBUG:2, INFO:3, WARN:4, ERR:5}property logger : missing valueproperty initialized : falseglobal LOG4AS_CONFIGglobal std, plutil, mapLibend new_tabset newTab to make new tab with properties {URL:theURL}tell aWinset aWin to window 1on new_tab(theURL)«event panSdlog» the error_message given «class btns»:{"OK"}, «class dflt»:1on error the error_message number the error_numbermy new_tab(theURL)set this_doc to make new windowif windows is {} thentell application "Google Chrome"set theUrl to URL of iset i to current tab of window 1tell application "Safari"end listFrameworkswrite the result to fp as «class utf8»(allFrameworks's componentsJoinedByString:linefeed) as textset fp to path to [my rootdir, "Data", "/", "FRAMEWORKS"]sortedArrayUsingSelector:"caseInsensitiveCompare:"lastPathComponent's stringByDeletingPathExtension's ¬set allFrameworks to NSBundle's allFrameworks()'s bundlePath's ¬to listFrameworks()end synonymsdefine(w)on synonyms for wend define));" in "JavaScript"$.NSMakeRange(0, word.length)word,$.DCSCopyTextDefinition(ObjC.unwrap(var word = '" & w & "';nil = $();run script "ObjC.import('CoreServices');local wto define(w as text)end using terms fromend ctrlKeymy setModifier:control toState:stateon ctrlKey(state as {text, boolean, constant})end altKeymy setModifier:option toState:stateon altKey(state as {text, boolean, constant})end cmdKeymy setModifier:command toState:stateon cmdKey(state as {text, boolean, constant})end shiftkeymy setModifier:shift toState:stateon shiftkey(state as {text, boolean, constant})using terms from application "System Events"end setModifier:toState:key up modifierthen return (key down modifier)if state is in ["down", "true", "yes"] ¬to setModifier:(modifier as constant) toState:(state as text)end sendChars, option:alt, shift:shift, command:cmd ¬sendChar to A given character:char ¬repeat with char in characters of charsto sendChars to A as text given string:chars as text ¬end sendCharsendKeyCode at code to A given shift:shift, command:cmd, option:altend consideringset shift to char = (uchar as text)considering caseset code to (NSArray's arrayWithArray:result)'s indexOfObject:ucharread (path to "KEYCODES") as «class utf8» using delimiter linefeedset uchar to (NSString's stringWithString:char)'s uppercaseString()local char, A, shift, cmd, alt, option:alt as boolean : false, shift:shift as boolean : false, command:cmd as boolean : false ¬to sendChar to (A as text) given character:char as text ¬end sendKeyCodealtKey(up)cmdKey(up)shiftkey(up)$.CFRelease(keyupevent);" in "JavaScript"$.CFRelease(keydownevent);$.CGEventPostToPid(pid, keyupevent);$.CGEventPostToPid(pid, keydownevent);var keyupevent = $.CGEventCreateKeyboardEvent(nil," & key & ",false);var keydownevent = $.CGEventCreateKeyboardEvent(nil," & key & ",true);bundleID))[0].processIdentifier;.runningApplicationsWithBundleIdentifier(var pid = ObjC.unwrap($.NSRunningApplicationvar bundleID = Application(app).id();var app = '" & A & "';altKey(alt)cmdKey(cmd)shiftkey(shift)local key, A, shift, cmd, alt, command:cmd as boolean : false, option:alt as boolean : falseto sendKeyCode at key to A as text given shift:shift as boolean : false ¬end scrollY$.CFRelease(event)" in "JavaScript"$.CGEventPost($.kCGHIDEventTap, event);" & dx & "1,$.kCGScrollEventUnitLine,nil,event = $.CGEventCreateScrollWheelEvent(run script "ObjC.import('CoreGraphics');local dxto scrollY(dx)end clickAtclick at {x, y}to clickAt(x, y)end click$.CFRelease(mouseupevent);" in "JavaScript"$.CFRelease(mousedownevent);$.CGEventPost($.kCGHIDEventTap, mouseupevent);$.CGEventPost($.kCGHIDEventTap, mousedownevent);$.kCGEventLeftMouseUp,var mouseupevent = $.CGEventCreateMouseEvent(nil,nil);coords,$.kCGEventLeftMouseDown,var mousedownevent = $.CGEventCreateMouseEvent(nil,var coords = {x: " & x & ", y: " & y & "};nil=$();to click at {x, y}end mouse);" in "JavaScript"{x:" & x & ", y:" & y & "}$.CGDisplayMoveCursorToPoint(ObjC.import('CoreGraphics');on mouse to {x, y}end colorAtcolour at {x, y}on colorAt(x, y)end colourrgba;" in "JavaScript"var rgba = [r[0]*255, g[0]*255, b[0]*255, a[0]];color.getRedGreenBlueAlpha(r,g,b,a);var r = Ref(), g = Ref(), b = Ref(), a = Ref();bitmap.release;var color = bitmap.colorAtXY(0,0);$.CGImageRelease(image);var bitmap = $.NSBitmapImageRep.alloc.initWithCGImage(image););$.CGRectMake(" & coords & ", 1, 1)$.CGMainDisplayID(),var image = $.CGDisplayCreateImageForRect(mouseLoc.y = screenH - mouseLoc.y;var screenH = $.NSScreen.mainScreen.frame.size.height;var mouseLoc = $.NSEvent.mouseLocation;ObjC.import('Cocoa');run script "set coords to [x, ",", space, y] as textif {x, y} contains null then set {x, y} to {"mouseLoc.x", "mouseLoc.y"}local x, yon colour at {x, y}end defaultBrowserlastPathComponent()'s stringByDeletingPathExtension() as textURLForApplicationToOpenURL:(NSURL's URLWithString:"http:"))'s ¬(NSWorkspace's sharedWorkspace()'s ¬on defaultBrowser()end batterybattery's info()end scriptend infoIOPSCopyPowerSourcesInfo() of thison info()property parent : thisuse framework "IOKit"script batteryon battery()end externalIPpublicIP()on externalIP()end publicIPencoding:UTF8 |error|:nil) as textURLWithString:"https://api.ipify.org/") ¬(NSString's stringWithContentsOfURL:(NSURL's ¬on publicIP()end createAdHocNetwork:if E ≠ missing value then return E's localizedDescription() as text|password|:pw |error|:_1security:WEP104 channel:channel ¬dataUsingEncoding:UTF8) ¬stringWithString:ssid)'s ¬interface()'s startIBSSModeWithSSID:((NSString's ¬channel to some item of WiFiChannelsif channel is not in WiFiChannels then set ¬local ssid, pw, channelto createAdHocNetwork:{name:ssid as text ¬ , password:pw as text ¬ , channel:channel as integer}end joinNetworksuccessas textE's localizedDescription() ¬if E ≠ missing value then return ¬set [success, E] to the resultits associateToNetwork:network |password|:pw |error|:_1set network to (allObjects() in networks)'s firstObject()(its scanForNetworksWithName:ssid |error|:nil)if the number of networks = 0 then set networks to ¬set networks to filteredSetUsingPredicate_(|?|)tell cachedScanResults() to if it ≠ missing value then ¬set networks to {}its setPower:true |error|:nilset |?| to NSPredicate's predicateWithFormat_(predicate, ssid)set predicate to "self.ssid == %@"local ssid, pwto joinNetwork given name:ssid as text, password:pw as text : missing valueend WiFiStrengthsresult as recordNSDictionary's dictionaryWithObjects:RSSIValues forKeys:SSIDsset RSSIValues to networks's valueForKey:"rssiValue"set SSIDs to networks's valueForKey:"ssid"set networks to the result's allObjects()its scanForNetworksWithName:nil |error|:nilif not (its powerOn() as boolean) then return falseon WiFiStrengths()end WiFiOn:WiFiOn_(null)its setPower:state |error|:nilthen return its powerOn() as booleanif state is not in [true, false, yes, no] ¬tell the interface()on WiFiOn:stateproperty WiFiChannels : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 36, 40, 44, 48}property WEP104 : a reference to 2property UTF8 : a reference to 4property Workspace : a reference to NSWorkspace's sharedWorkspaceproperty interface : a reference to CWWiFiClient's sharedWiFiClient's interfaceproperty NSWorkspace : a reference to NSWorkspace of thisproperty NSURL : a reference to NSURL of thisproperty NSString : a reference to NSString of thisproperty NSPredicate : a reference to NSPredicate of thisproperty NSDictionary : a reference to NSDictionary of thisproperty NSBundle : a reference to NSBundle of thisproperty NSArray : a reference to NSArray of thisproperty JSContext : a reference to JSContext of thisproperty CWWiFiClient : a reference to CWWiFiClient of thisproperty AMWorkflow : a reference to AMWorkflow of thisproperty _1 : a reference to referenceproperty nil : a reference to missing valueproperty this : a reference to current applicationproperty parent : script "load.scpt"use scripting additionsuse framework "JavaScriptCore"use framework "Foundation"use framework "CoreWLAN"use framework "Automator"property parent: AppleScriptproperty version : 1.5property id : "chri.sk.applescript.lib:utils"property name : "utils"#!/usr/bin/osascriptUP INFO - " & upttimedisplay alert "Restart Your Computer.if upttime is greater than "7 days" thenset upttime to (do shell script "uptime")keystroke "f" using {command down, option down}tell process "Terminal"activatetell application "Terminal"perform action "AXPress"tell (first button whose name is "Bildschirmblitz testen")tell window 1 of process "System Preferences"delay 0.10reveal anchor "Hearing" of pane id "com.apple.preference.universalaccess"set the current pane to pane id "com.apple.preference.universalaccess"tell application "System Preferences"if application "System Preferences" is running thenmain()end notifyMainNotifyWithoutGrowl(alertText)notifyWithGrowl(growlHelperAppName, alertName, alertTitle, alertText, useSticky)tell application "Finder" to tell (application file id "GRRR") to set growlHelperAppName to nameif GrowlRunning thenset GrowlRunning to my IsGrowlRunning()delay 0.5do shell script "open " & strGrowlPath & " > /dev/null 2>&1 &"if GrowlPath is not "" then --...try to launch if so...tell application "Finder" to tell (application file id "GRRR") to set strGrowlPath to POSIX path of (its container as alias) & nameset GrowlPath to "" --check to see if Growl is installed...if not GrowlRunning then --if Growl isn't running...set GrowlRunning to my IsGrowlRunning() --check if Growl is running...on notifyMain(alertName, alertTitle, alertText, useSticky)end NotifyWithoutGrowltell application "OmniFocus" to display dialog alertText with icon 1 buttons {"OK"} default button "OK"on NotifyWithoutGrowl(alertText)end notifyWithGrowl«event notifygr» given «class name»:alertName, «class titl»:alertTitle, «class appl»:growlAppName, «class desc»:alertText«event register» given «class appl»:growlAppName, «class anot»:allNotifications, «class dnot»:enabledNotifications, «class iapp»:iconApplicationtell my application growlHelperAppNameon notifyWithGrowl(growlHelperAppName, alertName, alertTitle, alertText, useSticky)end dictToStringreturn dictStringset dictString to "{" repeat with i in dict if (length of dictString > 1) then set dictString to dictString & ", " set dictString to dictString & "\"" & i & "\"" end repeat set dictString to dictString & "}"on dictToString(dict) --needed to encapsulate dictionaries in osascriptend IsGrowlRunningreturn GrowlRunningtell application "System Events" to set GrowlRunning to (count of (every process where creator type is "GRRR")) > 0on IsGrowlRunning()end notifyWithStickymy notifyMain(alertName, alertTitle, alertText, true)on notifyWithSticky(alertName, alertTitle, alertText)end notifymy notifyMain(alertName, alertTitle, alertText, false)on notify(alertName, alertTitle, alertText)end dueTodayset due date of selectedItem to (currDate + (dueTime * hours))set defer date of selectedItem to newStartDateTimeset newStartDateTime to (originalStartDateTime + (theDelta * days))set due date of selectedItem to newDueDateTimeset newDueDateTime to (originalDueDateTime + (theDelta * days))set theDelta to (currDate - originalDueStartDate) / 86400set originalDueStartDate to originalDueDateTime - (time of originalDueDateTime)if (originalDueDateTime is not missing value) thenset originalDueDateTime to due date of selectedItemon dueToday(selectedItem, currDate)end startTodayreturn successset defer date of selectedItem to (currDate + (startTime * hours))set success to trueset defer date of selectedItem to (currDate + (time of originalStartDateTime))if (originalStartDateTime is not missing value) thenset originalStartDateTime to defer date of selectedItemset success to falseon startToday(selectedItem, currDate)end mainset alertText to successTot & " item" & alertItemNum & " now due today." as stringif successTot > 1 then set alertItemNum to "s"set alertTitle to "Script complete"set alertName to "General"if showSummaryNotification thenset autosave to trueset alertText to "Improper mode setting"set succeeded to my dueToday(thisItem, currDate)else if mode is "due" thenif succeeded then set successTot to successTot + 1set succeeded to my startToday(thisItem, currDate)repeat with thisItem in validSelectedItemsListif mode is "start" thenset currDate to (current date) - (time of (current date))set autosave to falseset successTot to 0returnmy notify(alertName, alertTitle, alertText)set alertText to "No valid task(s) selected"set alertTitle to "Script failure"set alertName to "Error"if totalItems is 0 thenset totalItems to count of validSelectedItemsListset validSelectedItemsList to value of (selected trees where class of its value is not item and class of its value is not folder)set totalMinutes to 0tell content of first document window of front documenttell application "OmniFocus"on main()property iconApplication : "OmniFocus.app"property enabledNotifications : {"General", "Error"}property allNotifications : {"General", "Error"}property growlAppName : "Dan's Scripts"property alertDayNum : ""property alertItemNum : ""property dueTime : 17 --Due hour for items not previously assigned a due time (24 hr clock)property startTime : 6 --Start hour for items not previously assigned a start time (24 hr clock)property useGrowl : true --if true, will use Growl for success/failure alertsproperty showSummaryNotification : false --if true, will display success notificationsproperty mode : "start"click menu item "Disconnect"if exists menu item "Disconnect" thentell menu 1clicktell (first menu item whose title is "Sing’s AirPods II") of menu of btclick btset bt to (first menu bar item whose description is "bluetooth") of menu bar 1tell application "System Events" to tell process "SystemUIServer"end runset visible of process appName to falsetell application "Finder"if (powerMode is "off") thenend repeatactivate application appNametell application appName to quitrepeat with appName in powerHungryAppsdo shell script "networksetup -setairportpower " & devName & " " & newAirPortStateif (airportPower is airPortCheck) thenset airportPower to do shell script "networksetup -getairportpower " & devName & " | awk '{print $4}'"set devName to do shell script "networksetup -listallhardwareports | grep -A1 \"Wi-Fi\" | awk '{ if ($1 == \"Device:\") print $2 }'"tell application "System Preferences" to quitend tellset value of slider 1 of group 1 of tab group 1 of window "Built-in Display" to brightnessclick checkbox "Automatically adjust brightness" of group 1 of tab group 1 of window "Built-in Display"if (value of checkbox "Automatically adjust brightness" of group 1 of tab group 1 of window "Built-in Display" is checkBoxVal) thenclick menu item "Displays" of menu "View" of menu bar 1try --use try here because this part will fail if there are other monitors connectedclick checkbox "Adjust keyboard brightness in low light" of tab group 1 of window "Keyboard"if (value of checkbox "Adjust keyboard brightness in low light" of tab group 1 of window "Keyboard" is checkBoxVal) thendelay 1click radio button "Keyboard" of tab group 1 of window "Keyboard"click menu item "Keyboard" of menu "View" of menu bar 1click button "Turn Bluetooth On" of window "Bluetooth"elseend tryclick button "Turn Bluetooth Off" of window "Bluetooth"trydelay 2click menu item "Bluetooth" of menu 1 of menu bar item "View" of menu bar 1set frontmost to truetell process "System Preferences"tell application "System Events"activate application "System Preferences"end ifset newAirPortState to "on"set airPortCheck to "Off"set brightness to 1set checkBoxVal to 0do shell script "rm " & toggleFileelse if (powerMode is "off") thenset newAirPortState to "off"set airPortCheck to "On"set brightness to 0.06set checkBoxVal to 1do shell script "touch " & toggleFileif (powerMode is "on") thenset powerMode to do shell script testCmdset testCmd to "if test -e " & toggleFile & "; then echo off; else echo on; fi"set toggleFile to workingDir & ".powerSaveOn"set text item delimiters to dset workingDir to (POSIX path of (path to me))'s text 1 thru text item -2 & "/"set text item delimiters to "/"set d to text item delimiterson run {powerHungryApps}���Φ����$Ziv�������"/;G\y�����5O���Kp�����1�� >a��=b���R}���� L��� ? [ n � �  + W � � � � ; I i � � � � � � 3 P a r � � �   | � � � � Gi�����4JYm�����>p�����4j��%Tg�����)2M�����Cj���e�������DU���� ;a����6{���7_r���� JW�������'=I[�]��Cj��# M [ u � � � &!b!g!�!:"�"�"�"�"�" #n#�#�#�#�#�#�#�# $$2$o$�$�$�$�$-%e%u%�%�%&)&Y&�&�&�&''6'O'o'�'(((5(F(~(�(�(�(�(�()A)S)j)�)�)�)�)**1*C*I*l*�*�*�*�* +X+�+�+�+!,J,k,�,�,�,-H-i-�-�-�-�-.[.n.�.�.�.�.�.�.(/8/�/0{0�0�01<1~1�1�1�12222b2�2�2�2�2!3Y3�3�3�34=4�4�4 5=5r5�5�5�56-6Y6�6�6�6�6 7D7u7�7�7�7�7�7808S8n8�89B9�9�9:d:�:�:�;�;�<=�=�=�=�>�>?$?+?i?�??@I@�@LA�AABIBmB�B�B�B�BCC�C�C;DCDNDXDcDmD�D�D�D E�E�E�E+FAFbF�F�F�F�F�FCGXGcGmG�G�G)HGHsH�H�H�H,IGIpIyI�I�I�I�IbJkJvJ�J�J�J�J�JKRKuK�K�K�KLLEL�L�L�L�L�LM)MNMzM�M�MNN=NkN�N�NOXO�O�O�O�O P7PaP�P�P�P6QcQ�Q�Q�QRQR]RtR�R�R�RS)S}S�S�S�S�S�STMTqT�T�TU=UlU�U�U�U�UVV3V�V�V�VWGW�W�WEXhX�X�X:Y�Y�YIZLZYZ�Z�Z�Z�Z�Z[2[][�[�[�[�[\"\O\j\�\�\�\�\] ]3]�]q^�^�^�^�^3_E_i_|_�_�_`1`R``�`a3aga�a�ab)bGbjb�b�b�b�b�b|c�c�c�cd!d:dPdvd�d�de6eOe�e�e�ef�\������Ӈ ��U���و�@�������Չ#�5�F�`�r�����ʊ܊�H�V�������O�����`�����؍�K��� �$�.�Y���Ï� �P�r���������!�d���Ǒ �?�q����%�e�������#�6�_�r���ϔ�\�m�������ٖ��� �@�t�������2�����Ø�!�J�w���Ι��E�g�Ϛ�)�^���ś�� �0�P�e���ʜ��4�Z�t�ҝ��!�I�z���������R�����7�r���<�����١*�{�Т�,�m���ȣ�S�����O���ȥ�8�m���ܦ�K�����\���ʨ��6�z�̩�b����Z�ܫ��� �P�ƭH�i���������E�h�����J������=�a����?�x�����'�W�������1�c�����ܵ�p��8�޷�@����@���ݹ%����4�x����t�ʼ�/��4�u������)�X�u�����Կ��� �Q�r����� ��%�a�~������E�r�����%�6�=�X�}���������8���E�������U�i�����%���������!�M�_�q��� ������@�d������������2�J�c�}��������� �H�V����������������`��������+�X�{��������!�1�A�m�������������.�F�i������2�H�W�g�������:�x������7�T�������X�p������'�n��������!������7�L�����!�:���������J�i������1�`�l������ �*�C�c�{�������.�x���T�����)�s������H�}�����!�N��������c�������2�h������� �0�R�����#�N�v����������)�K�\�l�������$�T�y��������K�Z�q��������� �#�O�_�v������������4�U�o�����������'�?����� �-����� �f�������C�f���'��������������� �W�B�w�����#�M�������� �5�t����������0�������1�b������� �N�t��� �2�}���2����8�Q�m�����������l���U������7�I�u�����&�H�������)9U���L��i���RY`{��o����?Tv�`����!b����X h n � � � �  0 q � � �  ` � � � �  . O l � B k ~ � � � -Qp������?c�����.Mk��7G����2GZm����2Qn���=w���"Pd����[���$�t���4`���~���N}�@m��*h� 1 o � � 0!�!�!"7"X"�"�"�"'#W#{#�#A$\$�$�$�$!%j%�%�%�% &B&�&�&�&�& 'z'�'�'�'(>(p(�(�(�(�():)Y)�)�)�)�)*;*b*�*�*�*�*�*�* +P+�+�+ ,3,E,�,�,�,�,�, --,-�-�-�-�-.L.l.�.�.�.�.�.�.�. //-/G>�>?"???r?�?�?�?�?�?@$@P@l@�@�@�@�@A?AfAqA�A�ABnB�B�B�B9CKCiC�C�C�C4DeDvD�D�D�DE6EbEzE�E�EFFIFlF�F�F�FG1GXG�G�G�GH�~���̿��� �X�������i������� �%�@�M�u������-�K������'�M�{���������������&�h�����*�Y���~��R�p�������>�[�������$�K�v�C��������,�Y�q�����2��� �?�x�������������������<�������� �0�w����� �@�q������5�\��������� �>�l���������8�N�������*�@�y������%�4���@�{����������� �����B�~�����@�|�����P������� �.�J��������)�:�J�i�z������������p��������?�p��������^��������������}�����W������m��X���j�����������D�a�x�������B�~�����M������J�������� ��:������ ��7�m��������B�U���������V�g�}��������������6���������������,�{��������T�m�������� �u����������-�t�������8�Q�y�����������Q�a������������B�V�k�~������� ��O�s������2�N�Y�r��������������8����� !9Q\i�����.Tc���-6HQ�����m��A��Fk�1_���z��D���` � �  $ . P t � � � �  . M \ �   ! ; W r � � � �  : � � � � � CKWcpt�����{����!d|�������@���8L�0Wp�� n��E��Q�*w�%O��`����5�����d�� 1d����4X��x�� , < � � � �  !J!m!�!�!�!"6"c""�"�"#�#3$c$�$�$�$�$e%y%�%�%y&�&�&�&>'t'�'�'�'�'(M(�(�(�(�(")X)�)�)�) **2*R*�*�*�*6+K+g+�+�+�+,,D,j,{,�,�,�,�,-+-G-�-�-�-!.G.c.�.�./V/�/�/�/ 080M0\0o0�0�0 1c1�1�1 2?2�2�2 3C3i3�3�3444h4�45c5�5�5�5�5G6�6�6J7�7�788:8b8�8�8�8�8�8�8?9k9�9�9�9�9�9@:T:;w;�;�;<�<u=�=�=�=>x>�>�>A?�?�?�?@ @:@b@�@�@�@�@"A5A{A�A�A�A)B=BoByB�B�B�B�B�B%C`CC�C�CD1DhD�D�D�D&EQE{E�E�EFOF�F�F�FG>G|G�G�G�G�G!HFHlH�H�H�H�H�HIBIJAJmJ�J�J�J�K�KL7LULjL�L�L�L�L�L�LMM6M[M�M�M�M%NhN�N�NO�O�Q�]�l�~��������������� ��+�6�B�L�]�z�}�����������X�v���������������������.�6�>�K�c��������������������� ��(�I�\�p�������������������������#�,�6�A�M�V�d�o�{��������������(�5�L������� �'�/�?�Q�\�h�r�{��������������������+�7�[�u�������������*�3�A�N�]�l�~������������(�[�g�|����������6�C�W�|���������������������,�E�W�u������������2�c�}��������� ��,�9�U�b�q�������������!�+�6�E�J�S�a�l�x�����$�g�~������������!�?�{������� ��%�,�3�D�~���������W�c�q��������"�G�d�v������������������&�A�N�b�m�{�������������������.�X�j�����������������1�B�t�������������������-�C�R�t��������������������2�?�R�^�h�s������������� �+�F�g�|����������������+�<�K�b�o��������0�P�g�y�������������*�U�b�u���������������� �*�5�I�[�p��������� ��2�L�k����������������'�7�H�]���������������!�>�L�Y������������� �'�)�I�Z�h������#�}��������)�2�I�U�b�u����������$�1�<�G�Z�h�w��������������$�X�����������&�/�S�`�r��������������������� �0�=�_�n����������������(�_�j�{��������6�|�������������%�&�'�1�9�D�J�U�s�}������������������8�R�\�l�z��������;�V�`����������:�H�X�r����������7�A�O�g�r�������������������U�c�t��������*�;�?�O�_�p������������8�S�Z�q�|�����������I�`�r������������#�;�I�V�g������� ��1�^�~�����������U����������,�6�D�O�W�c�r������������������&�4�O�[�q�����������6�A�H���������������1Vhu�����':Uaz���Pz��������+0<FUZbo�������1MUd�����!/>RVjt|��������/Hf~������"E[]k�����/1ATet����  @ Y ~ � � � � � � � � . B S g � � � � �  ' E W w � � � � � � � �  ! > Q u � � � � � �   - Q o ~ � � � � � (F]v���)5Lmx�����'2?Vas����/d�����#.=�����@\gw�������.m�������IWm|���� )7Xh�������'Gcr�����!,:Dr����� 0DXq������0Mi����BYi�����(BRo~���!3\t������0CLk������������   . : H T d p } � � � � !+!N>u>�>�> ??i?�?�?�?K@_@t@�@�@�@�@(A�A�A+B�BCxC�C�C�C�C=D�DiE�E FF?F`F�F�F-G>GSG�G�G�G�GH9H`HqH�H�H�H�H.ILI�IJ=JmJ�J�J�J�JK6KUKtK�K�K�KL-LOLyL�L�L�L�L/MXM�M�M�M�MNFNPNWNuN�N�N�NO=O�O�O�O�O�O�O)PXP�P�P Q>Q�Q�Q�Q�Q�QRR+RSR�R�R�R�R.S�S�ST7TTTdT�T�TVU�UV�V W6W�W�W�W�WX8X�X�X�X3Y9YeY�Y�Y�Y�Y�YZ\ZvZ�Z�Z[$[�[�[�[p\�\�\#]i]�]�]^A^�^�^�^�^ _$_�`sbeDf4g�g�g�h�iRk8l�ldm�m�n$oVo�o�oKp�p�pq'qDq�q/rKr�rs�s�s�s:t_t�t�t�t+uIu�u�uv8vvv�v�v#wSwmw�wx4xax�x�x>yYyty�y�yzWz�z�z�zv{|�|�|}>}e}}}�}�}~M~�~�~Gv�\������:�������2�w����%�C�c�����̃�1�N�f����ڄ��@�P��� �-���͆�X�����?�l���҈���%�g��h����+�r�E�_���ڌ�+�l�����؍��&�Y�����ێ� ��B�^�u�����̏��6�`���ߐ�;�d�����ڑ*�S�s�ʒ��%�.�@�����Ҕ���L�����Е�C�x��#�V�v�������(�H�����4�[������ �X�����ښ.�k����� �#�=���������Ν�3�R�������"�6�W�n�����8�[���Ӡ�(�:�V�}���ޡ�)�R�r�����ʢ�rrent_versiset noteHTMLAppend to "
Append to Found Note
"set tagList to {"TEST"}set nbName to "TestExtractText"set noteTitleToFind to "TEST Note"return myLocation's coordinate()if myLocation is not (missing value) thenset myLocation to getCurrentLocation()end locationManager:didFailWithError:error err's localizedDescription() as texton locationManager:locationManager didFailWithError:errend locationManager:didUpdateLocations:set theLocation to locationsglobal theLocationon locationManager:locationManager didUpdateLocations:locationsend getCurrentLocationreturn last item of theLocationrepeat while theLocation is (missing value) and (current date) - timeStarted < maxSecondslocationManager's requestLocation()locationManager's setDelegate:melocationManager's requestAlwaysAuthorization()set locationManager to current application's CLLocationManager's alloc()'s init()global theLocation, maxSeconds, timeStartedon getCurrentLocation()set timeStarted to (current date)set maxSeconds to 10set theLocation to (missing value)use framework "CoreLocation"return getQRPayload("/Users/exampleUser/Downloads/image.png")end getQRPayloadset theResult to text 1 thru ((length of theResult) - 2) of theResultif length of theResult > 0 thenset theResult to theResult & theFeature's messageString() & ", "repeat with theFeature in theFeaturesset theResult to ""set theFeatures to theDetector's featuresInImage:theCIImageset theDetector to my (CIDetector's detectorOfType:(my CIDetectorTypeQRCode) context:(my CIContext's context()) options:(missing value))set theCIImage to current application's CIImage's imageWithData:(theImage's TIFFRepresentation())set theImage to current application's NSImage's alloc()'s initWithContentsOfFile:imagePathon getQRPayload(imagePath)use framework "CoreImage"display notification "Los archivos duplicados han sido enviados a la papelera:" with title "Proceso finalizado"move elArchivo to trashmove otroArchivo to trashif recuentroNombres < (count (name of file otroArchivo)) thenif last word of (do shell script "md5 '" & rutaOtroArchivo & "'") = checksumMD5 thenset rutaOtroArchivo to POSIX path of otroArchivoset otroArchivo to item j of losArchivosrepeat with j from i + 1 to contarArchivosset checksumMD5 to last word of (do shell script "md5 '" & rutaArchivo & "'")set rutaArchivo to POSIX path of elArchivoset recuentroNombres to count (name of file elArchivo)set elArchivo to item i of losArchivosrepeat with i from 1 to contarArchivos - 1set contarArchivos to count losArchivosset losArchivos to every file of carpetaOrigen as alias listset carpetaOrigen to choose folder with prompt "Selecciona la carpeta:"display alert "That may have failed for some of the selected cues, but it probably didn't break anything"set q name of eachCue to newNameset newName to text 1 thru thePos of theNameset thePos to ((6 - ((offset of "." in lastChars) - 2)) * -1)if lastChars contains "." thenset lastChars to text -6 thru -1 of theNameset theName to q name of eachCuewindowSize's windowSize({direction:"UP", resize:0})set end of allGangs to eachGangelse if eachGang is not missing value and eachGang is not in allGangs then -- only change ganged values if they haven't already been changedsetLevel eachCue row 0 column eachChannel db newLevelif eachGang is missing value then -- change unganged valuesset eachGang to getGang eachCue row 0 column eachChannelif oldLevel is not minAudioLevel thenset newLevel to (oldLevel + bumpLevel)set oldLevel to getLevel eachCue row 0 column eachChannelrepeat with eachChannel from 1 to audioChannelCount as integerset allGangs to {}if (q type of eachCue) is in cueTypes thenset cueTypes to {"Audio", "Fade", "Video", "Mic"}set minAudioLevel to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Min audio level") as integer -- audio level which is -infset audioChannelCount to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Output channel count") as integer -- total number of Qlab outputset bumpLevel to 6bumpLevelset variableCueListName to "Other scripts & utilities"URL_listset the clipboard to URL_listset URL_list to URL_list & return & return & "== " & totalTabs & " total tabs" & returnset currentTab to currentTab + 1set URL_list to URL_list & return & mdURLset mdURL to "* " & isActiveTabText & "[" & title of i & "]( " & URL of i & " )"set isActiveTabText to ""set isActiveTabText to "ACTIVE TAB:"if activeTabIndex = currentTab then -- current active tabrepeat with i in (every tab of theWindow)set currentTab to 1 -- tabs are 1-indexedset activeTabIndex to active tab index of theWindowset URL_list to URL_list & return -- add a return for readability in markdown editors.set URL_list to URL_list & " (minimized)"if (visible of theWindow) is not true thenset URL_list to URL_list & return & return & "== " & numTabs & " tabs"set totalTabs to totalTabs + numTabsif skipWindow is false thenset skipWindow to trueset numTabs to count tabs of theWindowset skipWindow to falselog (get title of theWindow)repeat with theWindow in allWindowsset totalTabs to 0set allWindows to (every window)set URL_list to ""windowMove's windowMove(0, 1)set windowMove to load script file windowMoveScptset windowMoveScpt to scriptPath & "windowMove.scpt"set color of paragraph i of selection to real_colorset real_color to color of style specsif answer = "Color" thendisplay dialog iset font of paragraph i of selection to real_fontset real_font to font of style specsif answer = "Font" thenset style_name to name of style sheet of paragraph i of selectionrepeat with i from 1 to (count of paragraphs of selection)if answer = "Stop" thenset answer to answer as textset question to display dialog "Change what" buttons {"Stop", "Color", "Font"} default button 1repeat with j from 1 to 12Try again to connect your AirPods, or contact the developers \"GoldenChaos\" or \"yyuuiko\" at the BTT forums if the issue persists." with title "AirPods Widget" with icon note buttons {"OK"} default button "OK"display dialog "There was an error while setting up the AirPods widget.on error --error setting the variabletell application "BetterTouchTool" to set_persistent_string_variable "AirPodsWg_DevceName" to SelectedDeviceNameset SelectedDeviceName to item 1 of the result" default items LclOldAirPodsName without multiple selections allowed and empty selection allowedchoose from list devNames with title "Setup AirPods Widget" OK button name "Set" cancel button name "Cancel" with prompt "Please select your AirPods to connect.set LclOldAirPodsName to get_string_variable "AirPodsWg_DevceName"log devNamesset devNames to (deviceList's valueForKey:"name") as listlog deviceListset deviceList to current application's IOBluetoothDevice's pairedDevices()use framework "IOBluetooth"do script "open -a Finder ./" in first windowmake new folder at carpetaDestino2 with properties {name:"2. Redes"}make new folder at carpetaDestino2 with properties {name:"1. Impresión"}set carpetaDestino2 to make new folder at nuevaCarpeta with properties {name:"4. Finales"}make new folder at nuevaCarpeta with properties {name:"3. Photoshop"}make new folder at nuevaCarpeta with properties {name:"2. Selección"}make new folder at nuevaCarpeta with properties {name:"1. Originales"}set nuevaCarpeta to make new folder at carpetaDestino with properties {name:carpetaSesion}set carpetaSesion to nombreSesionset carpetaDestino to choose folder with prompt "Selecciona la carpeta de destino"set nombreSesion to text returned of (display dialog "Ingresa el nombre de la Sesión:" default answer "")end isRootFolderif (name of container of mailFolder) is missing value thenon isRootFolder(mailFolder)end hasSubFoldersif (count of mail folders in mailFolder) is greater than 0 thenon hasSubFolders(mailFolder)end excludedFromArchivingreturn foundDoNotArchiveset foundDoNotArchive to trueif name of currentCat is equal to my doNotArchiveCategoryName thenset currentCat to item Y of catListrepeat with Y from 1 to count of catListset foundDoNotArchive to falseset catList to categories of anItemon excludedFromArchiving(anItem)end createLocalArchiveCalendarreturn currentArchiveCalendarset currentArchiveCalendar to make new calendar in on my computer with properties {name:calendarName}log "Creating new calendar: " & calendarNameset currentArchiveCalendar to calendar calendarName of on my computerlog "Found existing archive calendar: " & calendarNameset foundItemList to every calendar of on my computer where name is calendarNameset currentArchiveCalendar to ""log "Number of local calendars: " & (count of calendars of on my computer) as texton createLocalArchiveCalendar(calendarName)end archiveCalendarEventslog ("Skipping recurring event - " & subject of calendarEvent as text) & " " & end time of calendarEvent as textmove calendarEvent to localArchiveCalendarlog ("Archiving event - " & subject of calendarEvent as text) & " " & end time of calendarEvent as textlog ("Skipping event marked with no archiving - " & subject of calendarEvent as text) & " " & end time of calendarEvent as textif my excludedFromArchiving(calendarEvent) thenif is recurring of calendarEvent is false and is occurrence of calendarEvent is false or my archiveReccuringEvents is true thenif end time of calendarEvent is less than earliestDate thenrepeat with calendarEvent in calendar events of exchangeCalendarset earliestDate to ((current date) - (daysBeforeCalendarArchive * days))on archiveCalendarEvents(exchangeCalendar, localArchiveCalendar, daysBeforeCalendarArchive)end archiveMaillog "Folder archive complete"delay my processingDelaymove theMessage to currentArchiveFolderset todo flag of theMessage to not flaggedif not my runInSimulationMode thenlog "Archiving mail - " & (subject of theMessage as text) & " - " & (time sent of theMessage as text)log "Skipping mail marked for todo but not complete - " & (subject of theMessage as text) & " - " & (time sent of theMessage as text)if todo flag of theMessage is not not flagged and todo flag of theMessage is not completed and my doNotArchiveInCompleteTodoItems is true thenlog "Skipping mail marked for no archiving - " & (subject of theMessage as text) & " - " & (time sent of theMessage as text)if my excludedFromArchiving(theMessage) thenif time sent of theMessage is less than earliestDate thenset theMessage to item theIncrementValue of exchangeMessagesrepeat with theIncrementValue from 1 to count of exchangeMessagesset exchangeMessages to messages of mailFolderwith timeout of (my minutesBeforeTimeOut) * 60 secondson archiveMail(mailFolder, currentArchiveFolder, earliestDate)end createMailArchiveFolderreturn currentArchiveFolderset currentArchiveFolder to make new mail folder in archiveRootFolder with properties {name:mailFolderName}log "Creating folder " & mailFolderNameset currentArchiveFolder to mail folder mailFolderName of archiveRootFolderlog "Found existing folder " & mailFolderNameif (count of foundItemList) is greater than 0 thenset foundItemList to every mail folder of archiveRootFolder where name is mailFolderNameon createMailArchiveFolder(mailFolderName, archiveRootFolder)end archiveExchangeFolderslog mailFolderName & " and sub-folders excluded"my archiveExchangeFolders(mail folders in mailFolder, excludedFolders, currentArchiveFolder, daysBeforeArchive)log mailFolderName & " has sub-folders"if subFoldersExist thenmy archiveMail(mailFolder, currentArchiveFolder, earliestDate)if not mailFolderExcluded thenset currentArchiveFolder to my createMailArchiveFolder(mailFolderName, archiveRootFolder)if subFoldersExist or not mailFolderExcluded thenif not mailFolderExcluded or my processSubFoldersofExcludedFolders thenset currentArchiveFolder to ""set subFoldersExist to my hasSubFolders(mailFolder)set mailFolderExcluded to (mailFolderName) is in excludedFoldersset mailFolderName to name of mailFolder as textrepeat with mailFolder in exchangeFolderslog "Earliest Date - " & earliestDateset earliestDate to ((current date) - (daysBeforeArchive * days))on archiveExchangeFolders(exchangeFolders, excludedFolders, archiveRootFolder, daysBeforeArchive)log "Done!"my archiveCalendarEvents(defaultExchangeCalendar, my createLocalArchiveCalendar(localArchiveCalendarName), daysBeforeCalendarArchive)log ("Processing " & name of exchangeAccount as text) & "'s primary calendar: " & (name of defaultExchangeCalendar as text)set defaultExchangeCalendar to default calendar of exchangeAccountif archiveCalendarItems thenlog "================== Calendar ==================="my archiveExchangeFolders(mail folders of exchangeAccount, excludedMailFoldersList, my createMailArchiveFolder(localMailArchiveRootFolderName, on my computer), daysBeforeMailArchive)log "Processing mail folders"if archiveMailItems thenlog "==================== Mail ===================="log "Processing " & exchangeAccountDescription & " - the set exchange account"set exchangeAccount to exchange account exchangeAccountDescriptionlog ("Processing " & name of exchangeAccount as text) & " - the primary exchange account"error "Please set an exchange account which is not delegated or another users folder account"if exchange type of exchangeAccount is not primary account thenset exchangeAccount to item 1 of exchange accountsif exchangeAccountDescription is "" thenset archiveReccuringEvents to false -- If you wish to also archive recurring events then set this to true. Warning: if a recurring event is moved to the archive it will remove the entire series from your calendar even if those recurrances are present todayset daysBeforeCalendarArchive to 730 -- number of days to keep non-recurring calendar events in your exchange account before archivingset localArchiveCalendarName to "Archive Calendar" -- name of the archive calendar to create under 'On My Computer'. If an existing calendar is found it will use it, otherwise it will create the calendar for youset archiveCalendarItems to true -- no calendar archiving will take place if set to falseset doNotArchiveInCompleteTodoItems to false -- If set to true then archiving will ignore all items that are marked with a todo flag but are not complete (including items with no due date which are by definition always incomplete)set processSubFoldersofExcludedFolders to false -- By setting to true subfolders will be archived even though the parent folder is excluded for all excluded folders in above list (e.g. excluding your inbox but allowing it's sub-folders to be archived). Note that in this mode, folders with the repeated same name in your folder tree hierarchy will be all excluded if included in the excluded list.set excludedMailFoldersList to {"Subscribed Public Folders", "Junk E-mail", "Deleted Items", "Sync Issues", "quarantine", "Conversation History"} -- list of mail folders in your exchange account to exclude (sub-folders will also be excluded).set localMailArchiveRootFolderName to "Archive Mail" -- name of the root archive mail folder to create under 'On My Computer'. If an existing archive mail folder is found it will use it, otherwise it will create the folder for youset daysBeforeMailArchive to 80 -- number of days to keep mail in your exchange account before archivingset archiveMailItems to true -- no mail archiving will take place if set to falseset doNotArchiveCategoryName to "Do Not Archive" -- If you create an Outlook category that has this exact name (case sensitive) and assign that category to messages or calendar events the archiving process will skip those items indefinitelyset processingDelay to 0.2 -- The number of milliseconds to wait between moving messages on Outlook. On slower machines Outlook can't handle the speed at which the script requests mail to be moved sometimes causing a lock-up. It also makes Outlook more responsive while running in the background.set minutesBeforeTimeOut to 2 -- When first running this script against a very large mailbox (one user had 150 000 mails in one folder to archive, for example), it can take the script a long time to build the arrays necessary for calculating the items to be archived. By default AppleScript will timeout quite quickly if it feels an application is taking too long to respond. This timeout value overrides that to allow it handle the long processing times. You can make it longer if you still experience timeouts (CPU dependent). In extreme large cases an alterntive is to manually drag down mail to your archive and then allow the script to keep the archive up to date from there.set runInSimulationMode to false -- when set to true no mail or calendar events will be archived. It will however create the appropriate folder structures under 'On My Computer' and the candidate items that will be archived will be logged to the events window for you to review. The script can be run repeatedly to test out the effect off different parameters below. You can also optionally delete the empty folders that were created from running in this mode if you want to re-run the simulationset exchangeAccountDescription to "" -- By default you don't have to change this to your account name as the script will attempt to auto detect the primary account. However, if you have multiple accounts then you set this to the greyed out name of your Exchange Account in the main Outlook window holding all your folders (Inbox etc)do shell script "pbpaste"set theResult to do shell script "echo " & quoted form of input & ¬on run (input)set the clipboard to theResult" | sed -e 's/ //g'"set theResult to do shell script "echo " & quoted form of theData & ¬set theData to (the clipboard as text)do shell script "pbpaste -Prefer txt | pbcopy"set value of preference id "OOReturnShouldCreateNewRow" to curValset value of preference id "OOReturnInRowInsertsNewline" to curVal2set curVal2 to get value of preference id "OOReturnShouldCreateNewRow"set curVal to get value of preference id "OOReturnInRowInsertsNewline"set favorite_city to item 1 of the_selectionif the_selection is false then error number -128 -- User canceledset the_selection to choose from list all_cities with prompt "Please pick your favorite city:" default items {favorite_city}set all_cities to {"London", "Paris", "Moscow", "Sydney", "New York"}property favorite_city : "London"set {line spacing, paragraph spacing, minimum line height, maximum line height} to {0.0, 0.0, 0.0, 0.0}tell selected text of think window 1set result to process_text(test_block_text)tell application "Quicksilver" to set selection to resultset result to process_text(block_text)on process text block_textset result to do shell script perl & quoted form of block_textset perl to "/usr/bin/perl -0777 -pe 's#(^[[:space:]\\xe2\\x80\\xa8]*)|([[:space:]\\xe2\\x80\\xa8])*$##g' <<<"on process_text(block_text)asdfthat andthis andproperty test_block_text : "error "This script requires 10.13 or higher"loginsset end of logins to {name:li's NSURLNameKey, location:li's _NSURLPathKey}set li to (prps's valueForKey:(NSURLEnumList's item 1)) as recordif prps is not missing value thenset prps to (NSURL's resourceValuesForKeys:NSURLEnumList fromBookmarkData:thgs)if thgs is not missing value thenset thgs to (s's objectForKey:"NS.data")set thgs to sif (s's isKindOfClass:(NSData's class)) thenrepeat with s in smgset NSURLEnumList to NSArray's arrayWithObject:(NSString's stringWithString:"NSURLBookmarkAllPropertiesKey")set smg to newValue's objectForKey:"$objects"if newValue = missing value then error theError's localizedDescription() as textset {newValue, theError} to NSPropertyListSerialization's propertyListWithData:theData options:NSPropertyListMutableContainersAndLeaves format:(missing value) |error|:(reference)if theData = missing value then error theError's localizedDescription() as textset {theData, theError} to NSData's dataWithContentsOfFile:posixPath options:0 |error|:(reference)set posixPath to whereami & "/Library/Application Support/com.apple.backgroundtaskmanagementagent/backgrounditems.btm"set whereami to current application's NSHomeDirectoryForUser(whoami) as textset whoami to current application's NSUserName()set logins to {}if v is greater than 2.6 thenset v to AppleScript's version as numberproperty NSURL : a reference to current application's NSURLproperty NSArray : a reference to current application's NSArrayproperty NSPropertyListSerialization : a reference to current application's NSPropertyListSerializationproperty NSData : a reference to current application's NSDataproperty NSPropertyListMutableContainersAndLeaves : a reference to 2linkinuscmd("")end linkinuscmdset theString to "/me is off to play QW (" & ipAddress & ")"set status message to "QW: " & ipAddressset status to awayset theString to ""set status message to ""set status to availableif (length of ipAddress is 0) thentell application "iChat"if iChatActive thenif (get name of every process) contains "iChat" then set iChatActive to trueset theString to "/me is not currently running iChat"set iChatActive to falseon linkinuscmd(ipAddress)display alert "Estimated Duration of Selected Tasks" message hrs & " hours and " & mins & " minutes remaining" giving up after 5set mins to second number of timeList as stringset hrs to first number of timeList as stringset timeList to omnilib's getDuration(15)end make_file_logend _writeerror error_message number error_numberclose access fwrite (the_text & my _linefeed) to f starting at eof as «class utf8»set f to open for access file_path with write permissionon _write(the_text) -- Writes log messages to a UTF8-encoded text fileproperty parent : make_log_base()property class : "file log"script FileLogon make_file_log(file_path)end hexreturn valset val to do shell script "perl -e 'printf(\"%02X\", " & x & ")'"on hex(x)to split(someText, delimiter)end faderStringset msg to pre & " 02 2C 00 " & customNumVal & " 00 03 " & chanNumValset chanNumVal to "00 00 00 00 " & hex(chanN + 87)else if chan = "mt" or chan = "mtrx" thenset chanNumVal to "00 00 00 00 " & hex(chanN + 71)else if chan = "mix" thenset chanNumVal to "00 00 00 00 " & hex(chanN - 1)else if chan = "ch" thenset chanNumVal to "00 00 00 00 62"else if chan = "mono" or chan = "sub" thenset chanNumVal to "0F 7F 7F 7F 7F"if chan = "x" thenset customNumVal to hex(customN-1)set customN to item 4 of splitText as integerset customN to item 5 of splitText as integerset chanN to item 2 of splitText as integerset chan to item 1 of splitTextif length of splitText = 5 thenset splitText to split(inputMsg, space)set pre to "43 10 3E 12 01"on faderString(inputMsg)set q name of midiBank to inputMsgset sysex message of midiBank to messageset message type of midiBank to sysexset midiBank to first item of (selected as list)set message to my faderString(inputMsg)set inputMsg to text returned of resultdisplay dialog "Enter Fader Level Control String" default answer "" buttons {"Set", "Cancel"} cancel button "Cancel" default button "Set" with title "SCENE NUMBER"set bounds to {x1, y1, x2, y2}set x2 to dockSize + 2 * (displayWidth - dockSize) / 3set x1 to dockSize + (displayWidth - dockSize) / 3set y2 to y2 + 14set y1 to y1 - 44if (exists "mac:Applications:TotalFinder.app") thenset y2 to y2 - 22if curApp ends with ":Finder.app:" thenset y2 to menubarSize + usableHeight / 2set usableHeight to (displayHeight - menubarSize)set y1 to menubarSizeset {x1, y1, x2, y2} to (get bounds)tell application curAppset curApp to (path to frontmost application as Unicode text)set menubarSize to 22set dockSize to 0set dockSize to ((do shell script "defaults read com.apple.dock tilesize") as number) + 19if (do shell script "defaults read com.apple.dock autohide") is equal to "0" thenset displayHeight to (item 4 of b)set displayWidth to (item 3 of b)set b to bounds of window of desktopend generateJSONreturn JSONString as stringset JSONString to current application's NSString's alloc()'s initWithData:theData encoding:(current application's NSUTF8StringEncoding)if theData is missing value then error "generateJSON error: " & (anyError's userInfo's objectForKey:"NSDebugDescription")set {theData, anyError} to current application's NSJSONSerialization's dataWithJSONObject:someObject options:(current application's NSJSONWritingPrettyPrinted) |error|:(reference)to generateJSON for someObject -- someObject needs to be a list, record, or objC equivalentend parseJSONreturn object -- leave as NSArray or NSDictionaryreturn object as recordreturn object as listif coerce then if (object's isKindOfClass:(current application's NSArray)) as boolean thenif object is missing value then error "parseJSON error: " & (anyError's userInfo's objectForKey:"NSDebugDescription")set {object, anyError} to current application's NSJSONSerialization's JSONObjectWithData:theData options:0 |error|:(reference)set theData to theString's dataUsingEncoding:(current application's NSUTF8StringEncoding)set theString to current application's NSString's stringWithString:sourceStringif class of sourceString is not string then error "parseJSON error: source is not a string"to parseJSON from sourceString given coercion:coerce : truereturn (parseJSON from JSONString)set JSONString to read (choose file of type "public.json")error errmesson error errmesswrite test to fileRefset eof fileRef to 0set fileRef to (open for access ((path to desktop) as text) & "Sample.json" with write permission)log resultset test to (generateJSON for theList)set theList to {"List item", 4, 8.8, missing value, {"Another list"}, theRecord}set theRecord to {testing:{one:"1", |2|:2, three:3.3, |list|:{missing value}}}on run -- exampleset view of front window to playlist resultsPlaylistNameduplicate thisTrack to playlist resultsPlaylistNameif (count artworks of thisTrack) is 0 thenrepeat with thisTrack in selectedTracksmake new playlist with properties {name:resultsPlaylistName}delete tracks of playlist resultsPlaylistNamemy show_error("Please choose another playlist, you can't search on" & return & resultsPlaylistName)else if name of view of front window is resultsPlaylistName thenmy show_error("Please first select the desired tracks")set selectedTracks to file tracks of selectedPlaylistset selectedPlaylist to view of front windowif selectedTracks is {} thenset selectedTracks to the selection of front windowend show_errordisplay dialog theHeading & theMessage with icon 2 buttons {"OK"} default button 1set theHeading to "* " & ScriptName & " *" & return & returnon error -- Pantherdisplay alert ScriptName message theMessage as warning buttons {"OK"} default button 1try -- Tigeron show_error(theMessage)set resultsPlaylistName to "* Missing Artwork"property scriptDescription : "Find the songs with no Album Artwork set"property scriptVersion : "1.0"property ScriptName : "iTunes Find Artwork-less"end copyAsMarkdown" & theNote & "set the clipboard to (the clipboard) & "if (count of theNote) is greater than 0 thenset the clipboard to (the clipboard) & "- " & theTitleset the clipboard to (the clipboard) & "- [" & theTitle & "](" & theURL & ")"if (count of theURL) is greater than 0 thenset theNote to rest of the theNote's paragraphsset theURL to the first paragraph of theNoteif theNote starts with "http" thenset theURL to ""set theNote to note of theTreeset theTitle to name of theTreerepeat with theTree in theSelectedTreesset theSelectedTrees to value of every selected treetell content of document window 1on copyAsMarkdown()copyAsMarkdown()return list_sizeset list_size to count of the_remindersset the_reminders to (reminders in the_list whose completed is false)set the_list to list reminder_listtell application "Reminders"error "Please provide a list name as the first argument to this script"set reminder_list to item 1 of argvif (count of argv) > 0 thentell application "iTunes" to playend zipWithNmap(go, enumFromTo(1, minimum(map(my |length|, rows))))mf's |λ|(map(nth, rows))item i of rowscript nthon zipWithN(f, rows)end zipWithMtraverseList(my identity, zipWith(fm, xs, ys))on zipWithM(fm, xs, ys)end zipWithListset end of lst to |λ|(item i of xs, item i of ys)on zipWithList(f, xs, ys)end zipWithGen|λ|(|1| of ta, |1| of tb) of mfon zipWithGen(f, ga, gb)end zipWith4set end of lst to |λ|(item i of ws, item i of xs, item i of ys, item i of zs)set lng to minimum({length of ws, length of xs, length of ys, length of zs})on zipWith4(f, ws, xs, ys, zs)end zipWith3set end of lst to |λ|(item i of xs, item i of ys, item i of zs)set lng to minimum({length of xs, length of ys, length of zs})on zipWith3(f, xs, ys, zs)end zipWithset end of lst to |λ|(item i of xs_, item i of ys_)set ys_ to take(lng, ys) -- generators like cycle etcset xs_ to take(lng, xs) -- Allow for non-finiteif 1 > lng then return {}set lng to min(|length|(xs), |length|(ys))on zipWith(f, xs, ys)end zipNargvitem 1 of argv))map(go, take(minimum(map(my |length|, argv)), ¬tupleFromList(map(peers, argv))item i of yscript peersif 1 < length of argv thenon zipN(argv)end zipListmap(go, items 1 thru lng of xs){x, item i of ys}on zipList(xs, ys)end zipGenset mb to uncons(|2| of tb)set ma to uncons(|2| of ta)set x to Tuple(|1| of ta, |1| of tb)set tb to Just of mbset ta to Just of maif Nothing of ma or Nothing of mb thenset mb to uncons(gb)set ma to uncons(ga)if missing value is ma thenproperty mb : missing valueproperty ma : missing valueon zipGen(ga, gb)end zip4TupleN({w, item i of xs, item i of ys, item i of zs})on |λ|(w, i)on zip4(ws, xs, ys, zs)end zip3minimum({length of xs, length of ys, length of zs}) of xs)map(result, items 1 thru ¬TupleN({x, item i of ys, item i of zs})on zip3(xs, ys, zs)zipWith(Tuple, xs, ys)end writeTempFilestrPathwriteFile(strPath, txt)set strPath to (current application's ¬on writeTempFile(template, txt)end writeFileLR|Left|(e's localizedDescription() as string)|Right|(fp as string)if bln and (missing value is e) thenencoding:(ca's NSUTF8StringEncoding) |error|:(reference)writeToFile:(fp) atomically:true ¬set {bln, e} to (ca's NSString's stringWithString:strText)'s ¬(ca's NSString's stringWithString:strPath)set fp to stringByStandardizingPath of ¬on writeFileLR(strPath, strText)end writeFileencoding:(ca's NSUTF8StringEncoding) |error|:(missing value)(ca's NSString's stringWithString:strPath)) atomically:true ¬writeToFile:(stringByStandardizingPath of ¬(ca's NSString's stringWithString:strText)'s ¬on writeFile(strPath, strText)end wrapca's (NSArray's arrayWithObject:v)'s objectAtIndex:0on wrap(v)end |words|NSPredicate's predicateWithFormat:"0 < length")) as listfilteredArrayUsingPredicate:(ca's ¬NSCharacterSet's whitespaceAndNewlineCharacterSet()))'s ¬componentsSeparatedByCharactersInSet:(ca's ¬(((ca's NSString's stringWithString:(s))'s ¬on |words|(s)end variancefoldl(result, 0, xs) / ((length of xs) - 1)a + (x - m) ^ 2set m to mean(xs)on variance(xs)end unzipNfoldl(go, xs, tpls)map(inner, a)x & Just of lookupDict(i as string, tpl)on |λ|(x, i)on |λ|(a, tpl)set xs to replicate(length of item 1 of tpls, {})if 0 < length of tpls thenon unzipN(tpls)end unzip4return TupleN({ws, xs, ys, zs})set end of zs to |4| of wxyzset end of ys to |3| of wxyzset end of xs to |2| of wxyzset end of ws to |1| of wxyzrepeat with wxyz in wxyzsset ws to {}on unzip4(wxyzs)end unzip3return TupleN({xs, ys, zs})set end of zs to |3| of xyzset end of ys to |2| of xyzset end of xs to |1| of xyzrepeat with xyz in xyzson unzip3(xyzs)return Tuple(xs, ys)set end of ys to |2| of xyset end of xs to |1| of xyend unwrapitem 1 of ((ca's NSArray's arrayWithObject:nsValue) as list)if nsValue is missing value thenon unwrap(nsValue)end unwords{my text item delimiters, space}on unwords(xs)end |until|set v to mf's |λ|(v)repeat until mp's |λ|(v)set mp to mReturn(p)on |until|(p, f, x)end unsnocJust(Tuple({}, h))Just(Tuple("", h))Just(Tuple(items 1 thru -2 of xs, h))Just(Tuple(text 1 thru -2 of xs, h))set h to item -1 of xsif lng = 0 thenset blnString to class of xs is stringon unsnoc(xs)end unlines{my text item delimiters, linefeed}on unlines(xs)end unionSetreturn sUnionsUnion's unionSet:(s1)sUnion's setSet:(s)set sUnion to current application's NSMutableSet's alloc's init()on unionSet(s, s1)end unionByxs & foldl(flipDeleteByEq, nubBy(fnEq, ys), xs)deleteBy(fnEq, x, xs)script flipDeleteByEqon unionBy(fnEq, xs, ys)end unionsx & foldl(flipDelete, nub(ys), sx)set sx to nub(xs)my |delete|(x, xs)script flipDeleteon union(xs, ys)end unfoldritem 1 of (valueResidue)if missing value ≠ valueResidue thenset valueResidue to g's |λ|(item 2 of (valueResidue))property valueResidue : {v, v}on unfoldr(f, v)end unfoldlset xs to ({|1| of xr} & xs)set xr to Just of mbelse -- New (value, remainder) tuple,set mb to |λ|(|2| of xr)repeat -- Function applied to remainder.set xr to Tuple(v, v) -- (value, remainder)on unfoldl(f, v)end unfoldTreeNode(|1| of tpl, unfoldForest(g, |2| of tpl))set tpl to g's |λ|(b)on unfoldTree(f, b)end unfoldForestmap(result, xs)unfoldTree(g, x)set g to mReturn(f)on unfoldForest(f, xs)end uncurryf's |λ|(|1| of ab)'s |λ|(|2| of ab)f's |λ|(item 1 of ab)'s |λ|(item 2 of ab)mReturn(f)'s |λ|(|1| of ab, |2| of ab)mReturn(f)'s |λ|(item 1 of ab, item 2 of ab)if class of ab is list thenon |λ|(ab)if 1 < argvLength(f) thenon uncurry(f)end unconsJust(Tuple(item 1 of nxt, xs))if {} is nxt thenset nxt to take(1, xs)Just(Tuple(item 1 of xs, rest of xs))Just(Tuple(item 1 of cs, rest of cs))set cs to text items of xsif (2 ^ 29 - 1) as integer > lng thenif 0 = lng thenon uncons(xs)end unQuoteddropAround(p, s)34 = id of xon unQuoted(s)end unDigitsfoldl(go, 0, ds)10 * a + xon unDigits(ds)end typeNamek"Dict"type of xif keys(x) contains "type" thenif k = "Record" thenset k to Just of mb"Bottom"{|list|:"List", |integer|:"Int", |real|:"Float", |text|:¬ "String", |string|:"String", |record|:¬ "Record", |boolean|:"Bool", |handler|:"(a -> b)", |script|:"(a -> b"})set mb to lookupDict((class of x) as string, ¬on typeName(x)end tupleFromListfoldl(kv, {type:"Tuple" & strSuffix}, xs) & {length:lng}insertDict((i as string), x, a)script kvset strSuffix to ""set strSuffix to lng as stringif 2 < lng thenif 1 < lng thenon tupleFromList(xs)end truncateitem 1 of properFraction(x)on truncate(x)end treeMenuTuple(true, {}))) -- (Status, Choices) pairnextStepInNestedMenu, ¬snd(|until|(menuCancelledOrChoiceMade, ¬choicesOrSubMenu))bindLR(showMenuLR(blnNoSubMenus, menuTitle, menuItems), ¬either(nothingFromThisMenu, selectionsFromThisMenu, ¬on |λ|(statusAndChoice)script nextStepInNestedMenuTuple(true, xs)script selectionsFromThisMenuTuple(false, {})script nothingFromThisMenu|Right|(choices)|Right|(|λ|(chosenSubTree) of go)if {} ≠ (nest of chosenSubTree) thenset chosenSubTree to (Just of find(match, subTrees))k = root of xscript matchset k to item 1 of choiceson |λ|(choices)script choicesOrSubMenu(not my fst(statusAndChoices)) or ({} ≠ my snd(statusAndChoices))on |λ|(statusAndChoices)script menuCancelledOrChoiceMadeset blnNoSubMenus to {} = concatMap(my nest, subTrees)set menuItems to map(my root, subTrees)set subTrees to nest of treeset menuTitle to root of treeon treeMenu(tree)end treeMatchesconcatMap(go, nest of x)if pf(root of x) thenproperty pf : mReturn(p)'s |λ|on treeMatches(p, tree)end treeLeaves|λ|(oNode) of goconcatMap(my treeLeaves, lst)if 0 < length of lst thenset lst to nest of xon treeLeaves(oNode)end treeFromPairNest|λ|(vxs) of goNode(item 1 of pair, map(go, item 2 of pair))on |λ|(pair)on treeFromNestedList(vxs)end treeFromDictNode(treeTitle, go's |λ|(recDict))map(result, keys(x))Node(k, go's |λ|(|Just| of lookupDict(k, x)))on |λ|(k)map(result, x)Node(v, {})on |λ|(v)on treeFromDict(treeTitle, recDict)end traverseTuplemReturn(f)'s |λ|(|2| of tpl))fmap(curry(my Tuple)'s |λ|(|1| of tpl), ¬on traverseTuple(f, tpl)end traverseTreego's |λ|(tree)traverseList(go, nest of x))mReturn(f)'s |λ|(root of x), ¬liftA2(my Node, ¬on traverseTree(f, tree)end traverseMayfmap(my Just, mReturn(f)'s |λ|(Just of mb)){mb}on traverseMay(f, mb)end traverseListinit(xs))liftA2(my cons, vLast, pureT(t, [])), ¬foldr(cons_f, ¬liftA2(my cons, mf's |λ|(x), ys)on |λ|(x, ys)script cons_fset t to "List"set t to type of vLastkeys(vLast) contains "type" thenif class of vLast is record and ¬set vLast to mf's |λ|(item -1 of xs)set mf to mReturn(f)if 0 < lng thenon traverseList(f, xs)end traverseLRfmap(my |Right|, mReturn(f)'s |λ|(|Right| of lr)){lr}if |Left| of lr is not missing value thenon traverseLR(f, lr)end traversetraverseTuple(f, tx)traverseTree(f, tx)traverseMay(f, tx)traverseLR(f, tx)set t to type of txelse if class of tx is record and keys(tx) contains "type" thentraverseList(f, tx)if class of tx is list thenon traverse(f, tx)end transpose_on transpose_(rows)end transposemap(cols, item 1 of rows)concatMap(cell, rows)item iCol of rowscript cellon |λ|(_, iCol)script colsset rows to map(padded, xxs)xs & items (lng + 1) thru -1 of gapsif lng < intMax thenscript paddedset gaps to replicate(intMax, {})set intMax to |length|(maximumBy(comparing(my |length|), xxs))on transpose(xxs)end toUpperuppercaseStringWithLocale:(its NSLocale's currentLocale())) as texton toUpper(str)end toTitlecapitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text((ca's NSString's stringWithString:(str))'s ¬on toTitle(str)end toSentencestrlowercaseStringWithLocale:(locale)) as text((ws's stringWithString:(text 2 thru -1 of str))'s ¬uppercaseStringWithLocale:(locale)) as text) & ¬(((ws's stringWithString:(text 1 of str))'s ¬set ws to ca's NSStringset locale to ca's NSLocale's currentLocale()if length of str > 0 thenon toSentence(str)end toRatioapproxRatio(1.0E-12, n)on toRatio(n)end toLowerlowercaseStringWithLocale:(its NSLocale's currentLocale())) as text((its (NSString's stringWithString:(str)))'s ¬on toLower(str)end toEnumcharacter id xelse if text is c thenx as numberif integer is c or real is c thenproperty c : class of eon toEnum(e)end tempFilePathtakeExtension(template)text 3 thru -1 of ((random number) as string) & ¬takeBaseName(template) & ¬NSTemporaryDirectory() as string) & ¬(current application's ¬on tempFilePath(template)end taskPaperDateStringd & space & text 1 thru 5 of tset {d, t} to splitOn("T", dte as «class isot» as string)on taskPaperDateString(dte)end takeWhileRitems (1 + i) thru (-1) of xstext (1 + i) thru (-1) of xsif i > 1 thenset bln to trueif not |λ|(item i of xs) thenset blnText to (class of xs) is textset bln to falseon takeWhileR(p, xs)end takeWhileGenset v to xs's |λ|()repeat while (|λ|(v))on takeWhileGen(p, xs)end takeWhilereturn take(i - 1, xs)if not |λ|(item i of xs) then ¬repeat with i from 1 to length of xstakeWhileGen(p, xs)if script is class of xs thenon takeWhile(p, xs)end takeIteratereturn vsset end of vs to vset v to |λ|(v)repeat with i from 1 to n - 1set vs to {v}set v to xon takeIterate(n, f, x)end takeFromThenTomap(go, enumFromThenTo(a, b, z))item (1 + i) of xson takeFromThenTo(a, b, z, xs)end takeFileNameitem -1 of splitOn("/", strPath)if "" ≠ strPath and "/" ≠ character -1 of strPath thenon takeFileName(strPath)end takeExtension"." & item -1 of xsset xs to splitOn(".", fp)on takeExtension(fp)end takeDropCycledrop(i, take(m, ys))set ys to concat(replicate(ceiling(m / lng), xs))set ys to xsif lng ≥ m thenset m to n + ion takeDropCycle(n, i, xs)end takeDirectory"."intercalateS("/", xs)if {} ≠ xs thenset xs to init(splitOn("/", strPath))text 1 thru -2 of strPathif "/" = character -1 of strPath thenset strPath to filePath(fp)on takeDirectory(fp)end takeCycleitems 1 thru n of cycleitems 1 thru n of cycle as stringset cycle to concat(replicate((n div lng) + 1, xs))set cycle to xsif lng ≥ n thenon takeCycle(n, xs)end takeBaseNamefnintercalate(".", items 1 thru -2 of splitOn(".", fn))if fn contains "." thenset fn to item -1 of splitOn("/", strPath)if "/" = text -1 of strPath thenif "" ≠ strPath thenon takeBaseName(strPath)end takeAroundysys & takeWhileR(p, xs)if length of ys < length of xs thenset ys to takeWhile(p, xs)on takeAround(p, xs)return ysif missing value is v thenset v to |λ|() of xsrepeat with i from 1 to nelse if script is c thenif 0 < n thenelse if string is c thenitems 1 thru min(n, lng) of xsif 0 < n and 0 < lng thenset c to class of xsend tailsmap(residue, es) & {{}}items i thru -1 of esset es to xsset es to characters of xson tails(xs)end tailMayJust(rest of xs)if xs = {} thenon tailMay(xs)end tailrest of xstext 2 thru -1 of xsunitelse if 2 > lng thenif 1 > lng thenset unit to {}set unit to ""if blnText thenset blnText to text is class of xson tail(xs)end tablechunksOf(n, map(justifyRight(w, space), xs))))unlines(map(my unwords, ¬set w to length of last item of xson table(n, xs)end swap{item 2 of ab, item 1 of ab}Tuple(|2| of ab, |1| of ab)if class of ab is record thenon swap(ab)end sumvalueForKeyPath:"@sum.self") as realon sum(xs)end succMayJust(toEnum(x)'s |λ|(fromEnum(x) + 1))if x is maxBound(x) thenon succMay(x)end succ1 + xchr(1 + ord(x))on succ(x)end subtracty - xon subtract(x, y)end subsetszs & map(hcons, zs){h} & zon |λ|(z)script hconsset zs to |λ|(rest of ys)set h to item 1 of ysif 0 < length of ys thenon subsets(xs)end subsequencescons([], |λ|(xs) of nonEmptySubsequences)cons("", map(my concat, |λ|(characters of xs) of nonEmptySubsequences))cons({x}, foldr(f, {}, |λ|(xs) of nonEmptySubsequences))cons(ys, cons(cons(x, ys), r))on |λ|(ys, r)set {x, xs} to {item 1 of xxs, tail(xxs)}if length of xxs < 1 thenon |λ|(xxs)script nonEmptySubsequenceson subsequences(xs)end subTreeAtPath|λ|({tree}, pathSegments) of gobindMay(find(parentMatch, children), childMatch)Just(t)|λ|(nest of t, rest of xs) of goif 1 < length of xs thenscript childMatchh = root of tscript parentMatchif {} ≠ children and {} ≠ xs thenon |λ|(children, xs)on subTreeAtPath(tree, pathSegments)end stripStartdropWhile(my isSpace, s)on stripStart(s)end stripPrefix|λ|(xs, ys) of result|λ|(tail(xs), tail(ys))if (length of ys < 1) or (item 1 of xs ≠ item 1 of ys) thenJust(v)set v to ysset v to intercalate("", ys)if length of xs < 1 thenon |λ|(xs, ys)set {xs, ys} to {pfx, s}set {xs, ys} to {characters of pfx, characters of s}if blnString thenset blnString to class of pfx is texton stripPrefix(pfx, s)end stripEnddropWhileEnd(my isSpace, s)on stripEnd(s)32 = i or (9 ≤ i and 13 ≥ i)end stron str(x)end sqrtMayJust(n ^ (1 / 2))if n ≥ 0 thenon sqrtMay(n)end sqrtLR|Left|("Square root of negative number: " & n)|Right|(n ^ (1 / 2))if 0 ≤ n thenon sqrtLR(n)end sqrtn ^ (1 / 2)if 0 <= n thenon sqrt(n)end splitRegex{str}parts of recLast & ""parts of recLast & text (iFinal + 1) thru -1 of strif iFinal < length of str thenset iFinal to start of recLastset recLast to foldl(preceding, {parts:[], start:0}, lstMatches){parts:parts of a & strPart, start:iLocn + (length of x) - 1}set strPart to ""set strPart to text (iFrom + 1) thru iLocn of strif iLocn > iFrom thenset iLocn to (location of x)set iFrom to start of ascript precedingif length of lstMatches > 0 thenset lstMatches to regexMatches(strRegex, str)on splitRegex(strRegex, str)end splitOnreturn fst(tpl) & {drop(snd(tpl) - 1, src)}Tuple({}, 1), findIndices(matching(pat), src))set tpl to foldl(residue, ¬{init(items snd(a) thru (i) of src)}, lng + i)Tuple(fst(a) & ¬on |λ|(a, i)script residueset lng to length of patset xs to text items of src{my text item delimiters, pat}set {dlm, my text item delimiters} to ¬if class of src is text thenon splitOn(pat, src)end splitFileNameTuple("./", "")Tuple(strPath, "")Tuple("./", |last|(xs))Tuple(intercalate("/", stem) & "/", |last|(xs))if stem ≠ {} thenset stem to init(xs)set xs to splitOn("/", strPath)if last character of strPath ≠ "/" thenif strPath ≠ "" thenon splitFileName(strPath)end splitBymap(my concat, a & {r})a & {r}if list is class of xs thenzipWith(pairMatch, xs, rest of xs)){{}, {item 1 of xs}}, ¬set {a, r} to foldl(addOrSplit, ¬{item 1 of a, (item 2 of a) & y}{item 1 of a & {item 2 of a}, {y}}set {bln, x, y} to blnXYon |λ|(a, blnXY)script addOrSplit{mp(a, b), a, b}script pairMatch{xs}on splitBy(p, xs)end splitAt{xs, {}}{{}, xs}{items 1 thru n of xs, items (n + 1) thru -1 of xs}{items 1 thru n of xs as text, ¬ items (n + 1) thru -1 of xs as text}if n > 0 and n < length of xs thenon splitAt(n, xs)end splitArrowTuple(mReturn(f)'s |λ|(|1| of xy), mReturn(g)'s |λ|(|2| of xy))on splitArrow(f, g)end span|λ|(xs) of go{{}, {}}{{}, vs}{{x} & ys, zs}set {ys, zs} to |λ|(rest of vs)if |λ|(x) of mp thenset x to item 1 of vsif {} ≠ vs thenon |λ|(vs)property mp : mReturn(p)on span(p, xs)end sortOnsortedArrayUsingDescriptors:map(descrip, bs)) as list)map(undec, ((ca's NSArray's arrayWithArray:map(dec, xs))'s ¬val of xscript undecascending:boolsortDescriptorWithKey:(character id (96 + i)) ¬ca's NSSortDescriptor's ¬on |λ|(bool, i)script descripforKey:(character id (96 + i)))(nsDct's setValue:((item i of gs)'s |λ|(x)) ¬repeat with i from 1 to intKeysdictionaryWithDictionary:{val:x})set nsDct to (ca's NSMutableDictionary's ¬property gs : map(my mReturn, fs)script decset intKeys to length of fs{asc:true, fbs:{}}, flatten({f})))set {fs, bs} to {|1|, |2|} of unzip(fbs of foldr(keyBool, ¬{asc:true, fbs:({Tuple(x, asc of a)} & fbs of a)}{asc:x, fbs:fbs of a}if boolean is class of x thenscript keyBoolon sortOn(f, xs)end sortBysortBy(f, |2| of lessMore)sortBy(f, |1| of lessMore) & {h} & ¬set lessMore to partition(result, rest of xs)f's |λ|(x, h) ≤ 0set f to mReturn(f)on sortBy(f, xs)end snocxs & {x}on snoc(xs, x)end snditem 2 of tpl|2| of tplif class of tpl is record thenon snd(tpl)end sjshowJSON(x)on sj(x)end signum10else if x = 0 thenif x < 0 thenon signum(x)end showUndefined"⊥"on showUndefined()end showTuple"(" & intercalateS(", ", map(result, enumFromTo(1, length of tpl))) & ")"unQuoted(show(item 1 of ((ca's NSArray's arrayWithObject:v) as list)))if v ≠ missing value thenset v to (ca's NSDictionary's dictionaryWithDictionary:tpl)'s objectForKey:(n as string)on showTuple(tpl)end showTreedrawTree2(false, true, fmapTree(str, tree))on showTree(tree)end showSet"{" & intercalate(", ", map(str, sort(elems(s)))) & "}"script stron showSet(s)end showRatios & "/" & (d as string)if 1 ≠ d thenset s to (n of r as string)on showRatio(r)end showPrecision((round (x * d)) / d) as stringon showPrecision(n, x)end showOutlineunlines((go's |λ|(""))'s |λ|(x))nest of tree)concatMap(go's |λ|(tab & indent), ¬{indent & (root of tree)} & ¬on |λ|(tree)on |λ|(indent)on showOutline(x)end showOrdering"EQ""LT"else if v < 0 then"GT"if v > 0 thenset v to value of eon showOrdering(e)end showMaybe"Just " & unQuoted(show(Just of mb))"Nothing"on showMaybe(mb)end showMatrixunlines(map(go, stringRows))unwords(map(justifyRight(w, space), row))on |λ|(row)set {w, stringRows} to foldl(showRow, {0, {}}, rows){max(maxWidth, rowMax), prevRows & {cells}}set {rowMax, cells} to foldl(showCell, {0, {}}, row){max(w, length of s), xs & s}set s to cell as string{w, xs & ""}if missing value is cell thenset {w, xs} to accon |λ|(acc, cell)script showCellset {maxWidth, prevRows} to aon |λ|(a, row)script showRowon showMatrix(rows)end showLoglog show(e)on showLog(e)end showList"[" & intercalateS(", ", map(my show, xs)) & "]"on showList(xs)end showLR"Left(" & unQuoted(show(|Left| of lr)) & ")""Right(" & unQuoted(show(|Right| of lr)) & ")"if isRight(lr) thenon showLR(lr)end showJSONelse if c is class thenx as textelse if (c is integer or c is real) then"\"" & x & "\""else if c is text then"\"" & ((x - (time to GMT)) as «class isot» as string) & ".000Z" & "\""else if c is date then(ca's NSString's alloc()'s initWithData:json encoding:(ca's NSUTF8StringEncoding)) as text"Could not serialize as JSON"if json is missing value thenset json to ca's NSJSONSerialization's dataWithJSONObject:x options:1 |error|:(missing value)if (c is list) or (c is record) thenon showJSON(x)end showIntAtBase|λ|(quotRem(n, base), rs) of gor_|λ|(quotRem(n, base), r_)set r_ to f's |λ|(d) & rset {n, d} to nd_on |λ|(nd_, r)property f : mReturn(toDigit)on showIntAtBase(base, toDigit, n, rs)end showHexshowIntAtBase(16, mReturn(intToDigit), n, "")on showHex(n)end showForestunlines(map(my showTree, xs))on showForest(xs)end showDictshowJSON(dct)on showDict(dct)end showDate((dte - (time to GMT)) as «class isot» as string) & ".000Z"on showDate(dte)end showBinaryshowIntAtBase(2, binaryChar, n, "")character id (48 + n)script binaryCharon showBinary(n)end show("«" & c as text) & "»""null"else if c = class thene as textelse if (c = integer or c = real) then"'" & e & "'"else if c = text then"\"" & showDate(e) & "\""else if c = date thentell result to |λ|(Just of mb)tell mReturn(f) to |λ|(e)set f to my showDictset f to my showTupleelse if class of t is text and t begins with "Tuple" thenset f to my showRatioelse if "Ratio" = t thenset f to my showOrderingelse if "Ordering" = t thenset f to my showMaybeset f to my showLRif "Either" = t thenshowDict(e)set mb to lookupDict("type", e)showList(e)if c = list thenset c to class of eon show(e)end shiftdrop(n, xs)take(lng, drop(n, cycle(xs)))on shift(n, xs)objcSet's |count|() as integeron setSize(objcSet)end setMembermissing value is not (objcSet's member:(x))on setMember(x, objcSet)end setInsertobjcSetobjcSet's addObject:(x)on setInsert(x, objcSet)end setFromListsetWithArray:(ca's NSArray's arrayWithArray:(xs))ca's NSMutableSet's ¬on setFromList(xs)end setCurrentDirectorychangeCurrentDirectoryPath:oPathca's NSFileManager's defaultManager()'s ¬stringByStandardizingPathset oPath to (ca's NSString's stringWithString:strPath)'s ¬if doesDirectoryExist(strPath) thenon setCurrentDirectory(strPath)end sequenceAtraverse(identity, tfa)script identityon sequenceA(tfa)end |second|Tuple(|1| of xy, mReturn(f)'s |λ|(|2| of xy))on |λ|(xy)on |second|(f)end scanr1scanr(f, item -1 of xs, init(xs))if length of xs > 0 thenon scanr1(f, xs)end scanrreturn reverse of lstrepeat with i from lng to 1 by -1on scanr(f, startValue, xs)scanl(f, item 1 of xs, rest of xs)on scanl1(f, xs)end scanlset end of lst to vset v to |λ|(v, item i of xs, i, xs)set lst to {startValue}set v to startValueon scanl(f, startValue, xs)end safeMayJust(f(x))if p(x) thenon safeMay(p, f, x)end runActiontell act to |λ|(its arg) of my mReturn(its act)on runAction(act)end roundTo(round (x * d)) / dset d to 10 ^ non roundTo(n, x)end |round|round non |round|(n)end rotated(items 1 thru m of xs)(items (1 + m) thru -1 of xs) & ¬if 0 ≠ n thenset m to |mod|(n, lng)on rotated(n, xs)lngtake(lng, drop(lng - n, cycle(xs)))if missing value is not lng thenset lng to |length|(xs)on rotate(n, xs)end rootroot of oTreeon root(oTree)end rights{|Right| of x}if ks contains "type" and ks contains "Right" thenset ks to keys(x)if class of x is record thenon rights(xs)end |reverse|reverse of xs(reverse of characters of xs) as textif class of xs is text thenon |reverse|(xs)end replicateSreturn out & dblset dbl to (dbl & dbl)set n to (n div 2)if (n mod 2) > 0 then set out to out & dblrepeat while (n > 1)set dbl to sif n < 1 then return outset out to ""on replicateString(n, s)end replicateMgo's |λ|(n)liftA2List(cons, xs, |λ|(x - 1)){{}}if x ≤ 0 then{a} & bson |λ|(a, bs)script conson replicateM(n, xs)end replicateitem 2 of xs & item 3 of xsset xs to |until|(p, f, {n, s, ""}){n div 2, dbl & dbl, d}set d to outset d to out & dblif (n mod 2) > 0 thenon |λ|({n, dbl, out})script fn ≤ 1on |λ|({n})on replicate(n, s)return strReplacedset strReplaced to xs as textset my text item delimiters to strNewset xs to text items of strHayStackset {dlm, my text item delimiters} to {my text item delimiters, strNeedle}on replace(strNeedle, strNew, strHayStack)end |repeat|on |repeat|(x)end renameFile|Right|(fp2)defaultManager's moveItemAtPath:(fp) toPath:(fp2) |error|:(e)on renamedFile(fp, fp2)end removeFile|Left|(obj's localizedDescription as string)|Right|("Removed: " & fp)defaultManager's removeItemAtPath:(fp) |error|:(e)set {bln, obj} to current application's NSFileManager's ¬on removeFile(fp)end remm mod non rem(m, n)end regexMatchesoptions:0 range:{location:0, |length|:oString's |length|()}) as list)map(asRange, (oRgx's matchesInString:oString ¬range() of xscript asRangetext (intFrom + 1) thru (intFrom + (its |length|)) of strHayif NSNotFound ≠ intFrom thenset intFrom to its locationtell (m's rangeAtIndex:i)on |λ|(i)script rangeMatchedon |λ|(m)script matchStringset oString to ca's NSString's stringWithString:strHay|error|:(missing value)options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) ¬set oRgx to ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬set NSNotFound to a reference to 9.22337203685477E+18 + 5807on regexMatches(strRegex, strHay)end recipMayJust(1 / n)on recipMay(n)end recip1 / nif n ≠ 0 thenon recip(n)end readLR|Left|(e)on error e|Right|(run script s)on readLR(s)end readHexitem 1 of foldr(go, {0, 1}, characters of s){v + (i * e), 16 * e}set i to maybe(0, my identity, elemIndex(c, ds))set {v, e} to aon |λ|(c, a)set ds to "0123456789ABCDEF"on readHex(s)end readFileLR|Right|(s as string)|Left|((localizedDescription of e) as string)if s is missing value thenon readFileLR(strPath)(localizedDescription of e) as strings as stringif missing value is e thenencoding:(ca's NSUTF8StringEncoding) |error|:(e))stringByStandardizingPath) ¬stringWithString:strPath)'s ¬stringWithContentsOfFile:((ca's NSString's ¬set {s, e} to (ca's NSString's ¬set e to referenceon readFile(strPath)end readBinaryitem 2 of foldr(go, {1, 0}, s){2 * e, v * e + n}set v to ((id of c) - 48)set {e, n} to enon |λ|(c, en)on readBinary(s)end readrun script son read (s)end rationalapproxRatio(missing value, x)ratio(x, 1)if integer is c thenon rational(x)end ratioPlusratio((n of r1) * (d / (d of r1) + ¬on ratioPlus(n1, n2)end ratioMultratio((n of r1) * (n of r2), (d of r1) * (d of r2))on ratioMult(n1, n2)end ratioMinus((n of r2) * (d / (d of r2)))), d)ratio((n of r1) * (d / (d of r1) - ¬set d to lcm(d of r1, d of r2)on ratioMinus(n1, n2)end ratioDivratio((n of r1) * (d of r2), (d of r1) * (n of r2))set r2 to rational(n2)set r1 to rational(n1)on ratioDiv(n1, n2)end ratiogo's |λ|(x * (signum(y)), abs(y)){type:"Ratio", n:0, d:0}{type:"Ratio", n:(x div d), d:(y div d)}set d to gcd(x, y)if 0 ≠ x thenif 0 ≠ y thenon |λ|(x, y)on ratio(x, y)end rangeenumFromTo(a, b)sequence(map(result, xs))enumFromTo(item i of xs, item i of ys)on |λ|(_, i)if lng > 1 thenif lng = length of ys thenset {xs, ys} to {{a}, {b}}set {xs, ys} to {a, b}if class of a is list thenset {a, b} to {|1| of ab, |2| of ab}on range(ab)end randomRInt(low + ((random number) * (1 + (high - low)))) div 1on |λ|(_)on randomRInt(low, high)end raisem ^ non raise(m, n)end radians(pi / 180) * xon radians(x)end quotedc & s & con |λ|(s)on quoted(c)end quotRem{m div n, m mod n}on quotRem(m, n)end quotm div non quot(m, n)end quickSortByquickSortBy(cmp, less) & h & quickSortBy(cmp, more)cmp's |λ|(x, h) ≠ 1-- {"alpha", "beta", "gamma", "delta", "epsilon", "zeta", -- "eta", "theta", "iota", "kappa", "lambda", "mu"})on quickSortBy(cmp, xs)end quickSortquickSort(less) & h & quickSort(more)set {less, more} to partition(result, rest of xs)x ≤ hif length of xs > 1 thenon quickSort(xs)end pureTupleTuple("", x)on pureTuple(x)end pureTreeNode(x, {})on pureTree(x)end pureTpureTuple(x)pureTree(x)pureMay(x)pureLR(x)pureList(x)if "List" = t thenon pureT(t, x)end pureMayJust(x)on pureMay(x)end pureon pureList(x)end pureLR|Right|(x)on pureLR(x)end properFractionTuple(i, n - i)set i to (n div 1)on properFraction(n)end properFracRatioTuple(n div d, ratio(n mod d, d))set d to d of rset n to n of ron properFracRatio(r)end productfoldl(multiply, 1, xs)script multiplyon product(xs)end printreturn xlog xon print (x)end predMayJust(toEnum(x)'s |λ|(fromEnum(x) - 1))if x is minBound(x) thenon predMay(x)end pred(-1) + xchr(ord(x) - 1)if isChar(x) thenon pred(x)end postordergo's |λ|({}, node)foldl(go, xs, nest of x) & {root of x}on |λ|(xs, x)on postorder(node)end pluson plus(a, b)end |pi|pion |pi|()end permutationsWithRepetitionfoldl1(curry(my cartesianProduct)'s |λ|(xs), replicate(n, xs))if 0 < length of xs thenon permutationsWithRepetition(n, xs)end permutationsfoldr(go, {{}}, xs)concatMap(result, a)map(infix, enumFromTo(0, (length of ys))){x}take(n, ys) & x & drop(n, ys)if ys ≠ {} thenon |λ|(n)script infixon |λ|(ys)on |λ|(x, a)on permutations(xs)end partitionEithersset end of ys to xset end of zs to xif isRight(x) thenon partitionEithers(xs)end partitionTuple(ys, zs)set end of zs to vset end of ys to vif |λ|(v) thenset zs to {}on partition(f, xs)end outdentedunlines(map(|λ|(n) of curry(drop), xs))sif n < 1 thenset n to |λ|(minimumBy(comparing(dent), xs)) of dentlength of takeWhile(isSpace, x)id of c = 32script dentset xs to |lines|(s)on outdented(s)end orderingenumFromPairs("Ordering", {{"LT", -1}, {"EQ", 0}, {"GT", 1}})on ordering()end ordid of con ord(c)end |or|if p then return truerepeat with p in pson |or|(ps)end |on|tell mReturn(f) to |λ|(va, vb)tell mReturn(g) to set {va, vb} to {|λ|(a), |λ|(b)}on |on|(f, g)end oddnot even(x)on odd(x)end nubBygo's |λ|(xs){x} & go's |λ|(filter(notEq's |λ|(x), items 2 thru -1 of xs))set x to item 1 of xsif (length of xs) > 1 thenon |λ|(xs)not fEq(a, b)on |λ|(a)property fEq : gscript notEqset g to mReturn(f)'s |λ|on nubBy(f, xs)end nubvalueForKeyPath:"@distinctUnionOfObjects.self") as liston nub(xs)end notElemxs does not contain xon notElem(x, xs)end |not|not pon |not|(p)end newUUIDcurrent application's NSUUID's UUID's UUIDString as stringon newUUID()end nestnest of oTreeon nest(oTree)end |negate|-non |negate|(n)end nea ≠ bon ne(a)end mula * bon mul(a)end modificationTimebindLR(my fileStatus(fp), fs)|Right|(NSFileModificationDate of rec)on |λ|(rec)script fson modificationTime(fp)end |mod|(n mod d)(n mod d) + dif signum(n) = signum(-d) thenon |mod|(n, d)end minimumMayJust(m)if v < m then set m to vset v to contents of xset m to item 1 of xson minimumMay(xs)end minimumByMayreturn Just(v)on minimumByMay(f, xs)end minimumByitem 1 of xsreturn vif |λ|(x, v) < 0 then set v to contents of xset v to item 1 of xselse if lng > 1 thenif lng < 1 thenon minimumBy(f, xs)end minimumvalueForKeyPath:"@min.self")on minimum(xs)end minBound-1.797693E+308-(2 ^ 29 - 1)character id 1on minBound(x)end memberSetoSet's containsObject:(x)on memberSet(x, oSet)end memberobjectForKey:k) is not missing valueNSDictionary's dictionaryWithDictionary:dct)'s ¬((current application's ¬on memberDict(k, dct)end meanvalueForKeyPath:"@avg.self") as real((ca's NSArray's arrayWithArray:xs)'s ¬on mean(xs)end maximumMayon maximumMay(xs)end maximumByMayfoldl1May(max, xs)on maximumByMay(f, xs)end maximumByfoldl(max, missing value, xs)if a is missing value or cmp's |λ|(a, b) < 0 thenon |λ|(a, b)script maxset cmp to mReturn(f)on maximumBy(f, xs)end maximumvalueForKeyPath:"@max.self")unwrap((ca's NSArray's arrayWithArray:xs)'s ¬on maximum(xs)end maxBoundelse if boolean is c then1.797693E+308else if real is c then(2 ^ 29 - 1)else if integer is c thencharacter id 65535if text is c thenset c to class of xon maxBound(x)end maxif gt(x, y) thenon max(x, y)end matrixmap(go, enumFromTo(1, nRows))xsset end of xs to g(iRow, iCol)repeat with iCol from 1 to nColson |λ|(iRow)on matrix(nRows, nCols, f)end matching(items i thru min(length of src, -1 + lng + i) of src)(h = x) and xs = ¬on |λ|(x, i, src)set h to missing valueset h to item 1 of xsif bln thenset bln to 0 < lngset xs to patset xs to characters of patif class of pat is text thenon matching(pat)end mappendTupleTuple(mappend(|1| of a, |1| of b), mappend(|2| of a, |2| of b))on mappendTuple(a, b)end mappendOrdif 0 ≠ a thenon mappendOrd(a, b)end mappendMaybeJust(mappend(Just of a, Just of b))on mappendMaybe(a, b)end mappendFnmappend(mf's |λ|(x), mg's |λ|(x))on mappendFn(f, g)end mappendmappendFn(a, b)else if handler is ca thenmReturn(Just of mbi)'s |λ|(a, b)a & bif Nothing of mbi thenset mbi to bindMay(lookup("type", a), instanceMay){Maybe:mappendMaybe, Ordering:mappendOrdering, Tuple:mappendTuple})set mb to lookup(strType, ¬on |λ|(strType)script instanceMayif record is ca thenset ca to class of aon mappend(a, b)end mapMaybeGen|Just| of mbif not |Nothing| of mb thenif missing value is not v then set mb to mg's |λ|(v)repeat while (Nothing of mb) and not (missing value is v)set mb to mg's |λ|(v)if v is not missing value thenset v to gen's |λ|()on |λ|()property mg : mReturn(mf)on mapMaybeGen(mf, gen)end mapMaybefoldl(result, {}, xs)a & (Just of mb)set mb to g's |λ|(x)property g : mReturn(mf)on mapMaybe(mf, xs)end mapKeysmap(result, zip(keys(dct), elems(dct))){g's |λ|(k), v}set {k, v} to kvproperty g : mReturn(f)on mapKeys(f, dct)end mapAccumRfoldr(result, Tuple(acc, []), xs)Tuple(|1| of pair, (|2| of pair) & |2| of a)on |λ|(x, a, i)on mapAccumR(f, acc, xs)end mapAccumL_Tree|λ|(acc, tree) of goTuple(item 1 of tpl, Node(item 2 of pair, item 2 of tpl))set tpl to mapAccumL(go, item 1 of pair, nest of x)set pair to f(a, root of x)on |λ|(a, x)property mf : mReturn(f)'s |λ|on mapAccumL_Tree(f, acc, tree)end mapAccumLfoldl(result, Tuple(acc, []), xs)Tuple(|1| of pair, (|2| of a) & {|2| of pair})tell mReturn(f) to set pair to |λ|(|1| of a, x, i)on |λ|(a, x, i)on mapAccumL(f, acc, xs)end ltx < yon lt(x)end lookupTuplesbindMay(find(keyMatch, xs), harvestMay)Just(snd(kv))on |λ|(kv)script harvestMayk = fst(x)script keyMatchon lookupTuples(k, xs)end lookupDicton lookupDict(k, dct)end lookuplookupDict(k, m)else if c = record thenlookupTuples(k, m)if c is list thenon lookup(k, m)end |log|Just of evalJSMay(("Math.log(" & n as string) & ")")on |log|(n)end listToMaybeJust(item 1 of xs)if xs ≠ {} thenon listToMaybe(xs)end listFromTupleitems 2 thru -2 of (tpl as list)on listFromTuple(tpl)end listFromTree{root of x} & concatMap(go, nest of x)on listFromTree(tree)end maybeToList{Just of mb}on listFromMaybe(mb)end listDirectorywrap(strPath))) |error|:(missing value))contentsOfDirectoryAtPath:(unwrap(stringByStandardizingPath of ¬unwrap(ca's NSFileManager's defaultManager()'s ¬on listDirectory(strPath)end |list|return xsset end of xs to xrepeat while missing value ≠ xset x to |λ|() of genon |list|(gen)end |lines|paragraphs of xson |lines|(xs)end liftA2TupleTuple(mappend(|1| of a, b1), mReturn(f)'s |λ|(|2| of a, b2))set b2 to |2| of bset b1 to |1| of bset b2 to {}set b1 to {}on liftA2Tuple(f, a, b)end liftA2TreeNode(mReturn(f)'s |λ|(root of tx, rootLabel), forest)set forest to map(fmapT, nest of ty) & map(liftA2T, nest of tx)set rootLabel to root of tyset forest to {}set rootLabel to {}if class of ty is list thenliftA2Tree(f, t, ty)script liftA2TfmapTree(fx, t)on |λ|(t)script fmapTmReturn(f)'s |λ|(root of tx, y)script fxon liftA2Tree(f, tx, ty)end liftA2MayJust(|λ|(Just of a, Just of b) of mReturn(f))else if Nothing of b thenif Nothing of a thenon liftA2May(f, a, b)end liftA2ListconcatMap(result, xs)concatMap(result, ys){g(x, y)}on |λ|(y)property g : mReturn(f)'s |λ|on liftA2List(f, xs, ys)end liftA2LR|Right|(|λ|(x, y) of mReturn(f))belse if y is missing value thenaif x is missing value thenset y to |Right| of bset y to {}if class of b is list thenset x to |Right| of aon liftA2LR(f, a, b)end liftA2Fn|λ|(|λ|(x) of mf, |λ|(x) of mg) of mopproperty mg : mReturn(g)property mf : mReturn(f)property mop : mReturn(op)on apList(fs, xs)end apLRflrlr|Right|(|λ|(|Right| of lr) of mReturn(|Right| of flr))if missing value is |Left| of lr thenif missing value is |Left| of flr thenon apLR(flr, lr)end apFnmf(x, mg(x))property mg : |λ| of mReturn(g)property mf : |λ| of mReturn(f)on apFn(f, g)end apapTuple(mf, mx)else if "Tuple" = t thenapTree(mf, mx)else if "Node" = t thenapMay(mf, mx)else if "Maybe" = t thenapLR(mf, mx)else if "Either" = t thenapFn(mf, mx)if "(a -> b)" = t thenset t to typeName(mf)apList(mf, mx)if class of mx is list thenon ap(mf, mx)end anyTreeif contents of |λ|(v) then return trueon anyTree(p, tree)end anyif |λ|(item i of xs) then return trueon any(p, xs)end |and|if not (contents of x) then return falserepeat with x in xson |and|(xs)end allTree|λ|(tree) of gofalseif not (contents of |λ|(v)) then return falserepeat with v in nest of oNodeif mp(root of oNode) thenon |λ|(oNode)property mp : mReturn(p)'s |λ|on allTree(p, tree)end allSameall(p, rest of xs)h = xproperty h : item 1 of xsscript pif 2 > length of xs thenon allSame(xs)on all(p, xs)a + bon |λ|(b)on add(a)end abs-xif 0 > x thenon abs(x)end TupleNtupleFromList(argv)on TupleN(argv)end Tuple3{type:"Tuple3", |1|:x, |2|:y, |3|:z, length:3}on Tuple3(x, y, z)end Tuple{type:"Tuple", |1|:a, |2|:b, length:2}on Tuple(a, b)end |Right|{type:"Either", |Left|:missing value, |Right|:x}on |Right|(x){type: "Maybe", Nothing: true}end Node{type:"Node", root:v, nest:xs}on Node(v, xs)end |Left|{type:"Either", |Left|:x, |Right|:missing value}on |Left|(x)/* eslint-disable no-unused-vars *//* eslint-disable strict *//* eslint-disable no-undef *//* eslint-disable max-lines-per-function */tell theDocument to pauseif theDocument is playing thenif (count of documents) is greater than 0 thentell application "QuickTime Player"end ipAddressesreturn allAddressesset end of allAddresses to {networkDevice:networkDevice, networkAddress:networkAddress}if networkAddress is not false thenset networkAddress to falseset networkAddress to do shell script shellCommandset shellCommand to "ipconfig getifaddr " & networkDeviceset networkDevice to last word of item i of foundDeviceMentionsrepeat with i from 1 to count of foundDeviceMentionsset allAddresses to {}set foundDeviceMentions to {}set foundDeviceMentions to paragraphs of (do shell script "networksetup -listallhardwareports | grep 'Device: '")on ipAddresses()ipAddresses()move aTask to beginning of tasks of theProjectset theProject to containing project of aTaskrepeat with aTask in taskListset taskList to get value of selected treestell content of document window 1 of default documentshowApp appBID tarAppIDhideif overlayState is equal to 1.0tell application "AltTab"set tarAppID to get_string_variable "BTTActiveAppBundleIdentifier"if overlayState is equal to 1.0 then set_number_variable "AltTabSwitcherOpen" to 0.0if overlayState is equal to 0.0 then set_number_variable "AltTabSwitcherOpen" to 1.0set overlayState to get_number_variable "AltTabSwitcherOpen"synchronize record this_itemdo shell script "sips -s format jpeg -s formatOptions normal -s dpiHeight " & scalefactor & " -s dpiWidth " & scalefactor & " " & thePathShelldo shell script "sips -s format jp2 -s formatOptions normal -s dpiHeight " & scalefactor & " -s dpiWidth " & scalefactor & " " & thePathShellset thePathShell to quoted form of this_imageset the scalefactor to 90end get_selection_as_classreturn the_selectionif the_class is not required_type then errorset the_class to class of item 1 of the_selectionif the_class is list thenset the_class to class of the_selectionset the_selection to selectiontell application "Microsoft Entourage"on get_selection_as_class(required_type)make new event with properties {subject:event_label, start time:the_birthday, all day event:true, recurring:true, recurrence:recurrence_string}set event_label to "Birthday - " & the_nameset the_name to first name of this_contact & " " & last name of this_contactset recurrence_string to "FREQ=YEARLY;INTERVAL=1;BYMONTHDAY=" & month_day & ";BYMONTH=" & month_number & ";WKST=SU"set month_number to month of the_birthday as integerset month_day to day of the_birthdayset the_birthday to AppleScript's date birthday_textset birthday_text to birthday of this_contactrepeat with this_contact in (selected_contacts)if selected_contacts is missing value thenset selected_contacts to my get_selection_as_class(contact) tell application "Microsoft Entourage"set _path to (path of home folder) as stringdisplay notification "Success" with title "Save to Evernote!"create note title theTitle with text content notebook "default"set theTitle to item 1 of textListset textList to every text item of contentset AppleScript's text item delimiters to "\n"set content to (input as text)end textualcmdreturn msgset msg to characters 1 thru -3 of msg as stringset msg to msg & " " & ItemName & " " & ItemVersion & " /"set ItemChecksum to the last text item of currentItemset ItemDescription to text items 3 thru -2 of currentItemset ItemVersion to second word of currentItemset ItemName to first word of currentItemset AppleScript's text item delimiters to ";"set currentItem to get item i of AvailableScripts as stringrepeat with i from 1 to the count of AvailableScriptsset AvailableScripts to the paragraphs of allScriptsset allScripts to resultdo shell script "curl " & RepositoryContentsURLset msg to msg & " sm " & smlatest & " /"set smlatest to do shell script "curl http://xeon3d.net/textual/sm/latest"set msg to "Latest Script Versions:"set NewLine to (ASCII character 10)set FItalic to (ASCII character 1)set FBold to (ASCII character 2)on textualcmd(cmd)property Echo : "/echo "property RepositoryContentsURL : RepositoryURL & "scripts.lst"property RepositoryURL : "http://xeon3d.net/textual/scripts/"-- lv - A Latest Version Announcer Script for Textualtoggletell application "RocketFuel"do shell script "open -a " & appName & ".app"do shell script "kill $(ps -e -o pid,command | grep " & appName & " | sed -E 's/^ *([0-9]+).*$/\\1/;q'); exit 0"set appName to do shell script "echo " & appName & " | sed 's/Restart \\(.*\\)\\.app/\\1/'"set appName to quoted form of appNameset appName to name of file (path to me) as textquit application "System Preferences"set selected of row 1 to trueset selected of row 2 to trueif selected of row 1 thentell table 1 of scroll area 1 of tab group 1click radio button "Scaled" of tab group 1tell window DisplayNametell application "System Events" to tell process "System Preferences"set DisplayName to "your monitor"reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"display dialog errorTexton error errorTextdisplay notification "TAR Folder" subtitle "complete"do shell script "tar -czf " & theParent & quoted form of theName & ".tgz " & thePathset thePath to the quoted form of POSIX path of theFolderset theParent to the quoted form of POSIX path of (container of theFolder as alias)set theName to the name of folder theFolderrepeat with theFolder in theFolderson open theFoldersif syncing of currentStore is equal to false then quittimeused = timeused + 10repeat until syncing of currentStore is equal to false or timeused > timeoutsecsset timeoutsecs to 7200 -- 2 hoursset timeused to 0sync currentStore direction Downwardset currentStore to store named "mudflats"tell application "DropSync 3"end inputItemsreturn theItemsset the end of theItems to ""set the end of theItems to (item anItem of theInput)repeat with anItem from 1 to theCount -- pad/truncate entered itemsset theInput to paragraphs of text returned of (display dialog thePrompt & someItems with title theTitle default answer theInput)set {someItems, theInput} to {someItems as text, theInput as text}set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}set item itemNum of someItems to (item itemNum of someItems) & " [\"" & (item itemNum of theDefaults) & "\"]"set the end of theInput to item itemNum of theDefaults as stringset item itemNum of someItems to (item itemNum of someItems) & " [\"\"]"if theDefaultCount is greater than 0 thenset the end of theInput to ""if itemNum is greater than theDefaultCount thenrepeat with itemNum from 1 to theCount -- set the number of lines in the input and the defaultsif theDefaultCount is greater than theCount then error "inputItems handler: Too many default values"set {theItems, theInput} to {{}, {}}if theCount is less than 1 then error "inputItems handler: empty input list"set theCount to (count someItems)if thePrompt is not "" then set thePrompt to text 1 thru -2 of thePromptset {theCount, someItems} to {someItems, ""}if class of someItems is integer then -- no item listset theDefaultCount to (count theDefaults)set theDefaults to {}if theDefaults is in {false} then -- "with" or "without" promptset theTitle to ""set theTitle to "Multiple Input Dialog" -- defaultif theTitle is in {true, false} then if theTitle then -- "with" or "without" titleset thePrompt to thePrompt & return & returnelse -- fix up the prompt a bitset thePrompt to ""set thePrompt to "Input the following items:" & return & return -- defaultif thePrompt thenif thePrompt is in {true, false} then -- "with" or "without" promptto inputItems for someItems given title:theTitle, prompt:thePrompt, defaults:theDefaultsend displayMultiDialogreturn (inputItems for valuePrompts given title:mytitle, prompt:myPrompt, defaults:default_vals)on displayMultiDialog(mytitle, myPrompt, valuePrompts, default_vals)end getHighlightreturn selecTxtdisplay dialog "The clipboard contents have been restored to " & (the clipboard as text)set the clipboard to theSpare --as recorddisplay dialog "Copied text: " & (the clipboard as text)if debug is true thenset waitnum to waitnum + 1delay waitIntervalelse if selecTxt is equal to "" thenset done to "yes"if waitnum is equal to maxwaits thenset selecTxt to the clipboard as textrepeat while done = "no"set maxwaits to 100set waitInterval to 0.02set waitnum to 0set done to "no"set selecTxt to ""set theSpare to ""if button returned of response is "OK" thenset response to (display dialog "Warning: The contents of the clipboard will be lost." buttons {"Cancel", "OK"})set theSpare to the clipboard --as texton getHighlight(debug)return wrapped_strdisplay dialog errstron error errstrkeystroke wrapped_strdisplay dialog wrapped_strif isTerminal is true thenset isTerminal to ((name of first process where it is frontmost) as string) is equal to "Terminal"set wrapped_str to (do shell script "echo " & stdin & " | " & wrap_script & " " & n & " " & cmd_leader & " " & prepend_leader)set cmd_leader to quoted form of leader_strdo shell script "open -a '" & (curProc as string) & "'"set {n, leader_str, prepend_leader} to my displayMultiDialog("Hard-wrap Selected Text", "Set the desired line length, leader string, and whether to prepend the leader string below.", {"• Line Length", "• Leader string (E.g. comment character '#')", "• Whether to prepend the leader on the first line (0=no, 1=yes)"}, {"80", "", "1"})set curProc to (name of first process whose frontmost is true)set stdin to quoted form of first item of input as textset input to getHighlight(debug)if input's class is not list thenset wrap_script to "/Users/yourusername/Scripts/wrap.pl"click menu item "Pause" of menu 1 of menu bar item "controls" of menu bar 1tell application "System Events" to tell process "NeteaseMusic"set output to text items of someTexton splitText(delimiter, someText)length of resultSplited -- 最後の改行が、空文字の要素としてカウントされることに留意set resultSplited to splitText(",", result)' ','"set result to do shell script "ls -1 " & Basedir & " | tr 'set Basedir to "/Users/saji/Desktop/yourDirectory/" as textset the current view to list viewset target to oldTargetset target to path to home folderset oldTarget to targettell front Finder windowset sort column to the name columnset sort column to the modification date columnset sort column to the size columnset width of sort column to 100set sort column to the kind columnset sort direction of sort column to normalset text size to 14set icon size to smalltell list view options of window 1set the current view of the front window to list viewget the name of the front windowset retryLib to std's import("retry")set logger to std's import("logger")'s new("dock")end assignToDesktopkb's pressKey("esc")click menu item subMenuName of menu 1 of menu item "Options" of first menu of UI element appName of list 1delay 0.2 -- Intermittently fails without this.if not (exists UI element appName of list 1) then return falseset subMenuName to "None"else if desktopIndex is "none" thenset subMenuName to "All Desktops"else if desktopIndex is "all" thenset subMenuName to "Desktop on Display " & desktopIndexif class of desktopIndex is integer thenon assignToDesktop(appName, desktopIndex)end newSafariWindowif (source of front document) is "" then return truescript BlankDocumentWaiterexec of retry on result for 3click menu item "New Window" of first menu of UI element "Safari" of list 1script MenuWaiterset retry to retryLib's new()perform action "AXShowMenu" of UI element "Safari" of list 1if not (exists UI element "Safari" of list 1) then return falseon newSafariWindow()end isAutoHideautohideon isAutoHide()end getCoordinatesposition of first liston getCoordinates()end getHeightsecond item of theSizeon getHeight()end getWidthfirst item of theSizeset theSize to size of first listtell application "System Events" to tell application process "Dock"if isHorizontal() or isAutoHide() then return 0on getWidth()end isHorizontalmy getPosition() is bottomon isHorizontal()end isVerticalnot isHorizontal()on isVertical()end getPositionscreen edgetell application "System Events" to tell dock preferenceson getPosition()end clickAppperform action "AXPress" of UI element appName of list 1on clickApp(appName)script DockInstanceclick menu item "Options" of first menu of UI element appName of list 1perform action "AXShowMenu" of UI element appName of list 1delay 1.5if caseIndex is less than 5 and running of application appName and assignResult is true thenlogger's debugf("assignResult: {}", assignResult)if caseIndex is less than 5 thenlogger's infof("Dock Height: {}", lib's getHeight())else if caseIndex is 10 thenlib's clickApp("Safari")else if caseIndex is 13 thenlogger's infof("Is Autohide?: {}", lib's isAutoHide())else if caseIndex is 12 thenlogger's infof("Coordinates: {}, {}", lib's getCoordinates())else if caseIndex is 11 thenlogger's infof("Dock Width: {}", lib's getWidth())else if caseIndex is 9 thenlogger's infof("Is Horizontal: {}", lib's isHorizontal())else if caseIndex is 8 thenlogger's infof("Is Vertical: {}", lib's isVertical())else if caseIndex is 7 thenlogger's infof("Dock Position: {}", lib's getPosition())else if caseIndex is 6 thenlog lib's newSafariWindow()activate application "Safari"else if caseIndex is 5 thenset assignResult to lib's assignToDesktop(appName, "none")else if caseIndex is 4 thenset assignResult to lib's assignToDesktop(appName, "all")set assignResult to lib's assignToDesktop(appName, 2)set assignResult to lib's assignToDesktop(appName, 1)if running of application appName is false thenset appName to "Script Editor"set lib to new()Manual: Click AppAutoHideCoordinatesOccupied Dock HeightOccupied Dock WidthHorizontal?Vertical?PositionNew Safari WindowAssign to NoneAssign to AllAssign to Desktop 2Assign to Desktop 1set thisCaseId to "dock-spotCheck"global std, retryLib, kbend parseCharserror "ERROR: parseChars() handler: " & errMsg number errNumreturn parsedListset the parsedList to every text item of sourceTEXTif considerCase thenset AppleScript's text item delimiters to the {parseString as string}set considerCase to considerCase of prefsset parseString to parseString of prefsset sourceTEXT to sourceTEXT of prefserror "The parameter for 'parseChars()' should be a record or at least a list. Wrap the parameter(s) in curly brackets for easy upgrade to 'parseChars() version 1.3. " number 1024else if class of prefs is not equal to (class of {someKey:3}) thenset prefs to {sourceTEXT:item 1 of prefs, parseString:item 2 of prefs}set prefs to {sourceTEXT:item 1 of prefs, parseString:item 2 of prefs, considerCase:item 3 of prefs}if (count of prefs) is greater than 2 thenif class of prefs is list thenset defaultPrefs to {considerCase:true}on parseChars(prefs)parseChars({sourceTEXT:"fizz,buzz", parseString:","})display alert "Taskmaster" message "Are you working on the most important task?" buttons ["No", "Yes"] default button 1end autosavesInPlaceon autosavesInPlace()end readFromData_ofType_error_return encounteredErrorset contents of outError to current application's NSError's errorWithDomain_code_userInfo_(current application's NSCocoaErrorDomain, current application's NSFileReadUnknownError, missing value)on readFromData_ofType_error_(theData, typeName, outError)end dataOfType_error_set contents of outError to current application's NSError's errorWithDomain_code_userInfo_(current application's NSCocoaErrorDomain, current application's NSFileWriteUnknownError, missing value)if not succeeded and outError is not missing value thenset succeeded to falseon dataOfType_error_(typeName, outError)end windowNibNamereturn "CustomDocument"on windowNibName()continue init()property parent : class "NSDocument"script CustomDocumentend windowWaitUntil_FrontNotIStell application "htcLib" to windowWaitUntil_FrontNotIS(prefs)on windowWaitUntil_FrontNotIS(prefs)end fmGUI_CustomMenus_Saveerror "unable to fmGUI_CustomMenus_Save - " & errMsg number errNumwindowWaitUntil_FrontNotIS({windowName:windowName})if fmGUI_NameOfFrontmostWindow() does not start with windowName then error windowName & " was not frontmost window, so cannot save it." number 1024set windowName to "Manage Custom Menus"on fmGUI_CustomMenus_Save(prefs)fmGUI_CustomMenus_Save({})do shell script "defaults write com.apple.finder AppleShowAllFiles -bool" & space & aResset aRes to "FALSE"else if aRes is 1 thenset aRes to "TRUE"if aRes is 0 thenset aRes to (do shell script "defaults read com.apple.Finder AppleShowAllFiles") as integerkeystroke varset the var to my replace_chars(var, "watch?v=", "embed/")set var to the clipboardkeystroke "c" using {command down}keystroke "l" using {command down}set query string of window 1 to "EczActivity"create note title "EczActivity" with html newContent notebook "Inbox"set newContent to newContent & ("")set newContent to newContent & ("
VOL-245")set newContent to newContent & ("" & noteTitle & "")set noteUrl to note link of searchResultset noteTitle to title of searchResultrepeat with searchResult in searchResultsset searchResults to find notes "tag:ecz updated:day"set newContent to ""end fmGUI_ObjectClick_Buttontell application "htcLib" to fmGUI_ObjectClick_Button(prefs)on fmGUI_ObjectClick_Button(prefs)end fmGUI_ObjectClick_SelectButtonerror "Unable to fmGUI_ObjectClick_SelectButton - " & errMsg number errNumreturn fmGUI_ObjectClick_Button({buttonName:"Select"} & prefs)on fmGUI_ObjectClick_SelectButton(prefs)fmGUI_ObjectClick_SelectButton({})offset of "1" in "123"end padStringreturn paddedStringset paddedString to paddedString & spacerepeat paddingLength timesset paddingLength to fieldLength - stringLengthset paddedString to theStringelse -- stringLength is less than or equal to fieldLengthset paddedString to (text from character 1 to character (fieldLength - 3) of theString) & "..."if stringLength is greater than fieldLength thenset stringLength to length of theStringon padString(theString, fieldLength)end getMessageCountsForMailboxesreturn displayStringset displayString to displayString & " " & my padString(mailboxName, 40) & " " & messageCount & " (" & unreadCount & " unread)" & returnset unreadCount to unread count of eachMailbox as stringset messageCount to (count of (messages of eachMailbox)) as stringset mailboxName to name of eachMailboxrepeat with eachMailbox in theMailboxesset displayString to ""on getMessageCountsForMailboxes(theMailboxes)set size to 12set font to "Courier"tell outputMessageset outputMessage to make new outgoing message with properties {content:messageCountDisplay, subject:"Message counts for all my mailboxes", visible:true}set messageCountDisplay to messageCountDisplay & return & "Mailboxes for Account: " & name of eachAccount & return & my getMessageCountsForMailboxes(accountMailboxes)if (count of accountMailboxes) is greater than 0 thenset accountMailboxes to every mailbox of eachAccountrepeat with eachAccount in everyAccountset everyAccount to every accountset messageCountDisplay to ""set messageCountDisplay to "Local mailboxes (On My Mac)" & return & my getMessageCountsForMailboxes(localMailboxes)if (count of localMailboxes) is greater than 0 thenset localMailboxes to every mailboxdisplay notification tabUrl with title notifyTitle subtitle "《" & tabTitle & "》"if (activeApp as string) is not equal to "Evernote" thendisplay notification "Failed all."set editHTML to noteHTML & addContentdisplay notification "Error with append method."append theNote html addContentset addContent to "

" & addDateAndTime & "
" & tabTitle & "
" & "" & tabUrl & ""set notifyTitle to "[" & (get name of (get notebook of theNote)) & "]" & (get title of theNote)set theNote to first item in theNotesdisplay notification "已存在于:" & (get title of (item 1 of findUrlInNotes))if not findUrlInNotes = {} thenset findUrlInNotes to (find notes tabUrl) -- returns a list of notesset tabTitle to (title of window 1)set tabUrl to "http://" & tabUrlif (characters 4 thru 1 of tabUrl as string) is not equal to "http" thenif tabUrl = "" thenset tabUrl to value of text field 1 of toolbar 1 of window 1tell application process (activeApp as string)if (activeApp as string) is not equal to "Evernote" and (activeApp as string) is not equal to "Google Chrome" and (activeApp as string) is not equal to "Google Chrome Canary" thenset activeApp to name of application processes whose frontmost is trueset activeApp to missing valueset tabTitle to missing valueset theNote to missing valueset tabUrl to missing valueset addDateAndTime to (todayISOformat() & " " & getTimeInHoursAndMinutes())end todayISOformatreturn y & "-" & m & "-" & dset d to text -2 thru -1 of ("00" & (day of theDate))set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))set y to text -4 thru -1 of ("0000" & (year of theDate))set theDate to current dateon todayISOformat()end getTimeInHoursAndMinutesreturn (theHour & ":" & theMin & " " & theSfx) as stringset theSfx to characters (Pos + 1) through end of timeStr as stringset Pos to offset of " " in timeStrset theMin to characters 1 thru (Pos - 1) of timeStr as stringset timeStr to characters (Pos + 1) through end of timeStr as stringset theHour to characters 1 thru (Pos - 1) of timeStr as stringset Pos to offset of ":" in timeStrset timeStr to time string of (current date)on getTimeInHoursAndMinutes()end getPositionOfItemInListif item a of thelist contains theItem then return arepeat with a from 1 to count of theliston getPositionOfItemInList(theItem, thelist)end findURLsIn:return (theURLsNSArray's valueForKeyPath:"URL.absoluteString") as listset theURLsNSArray to theNSDataDetector's matchesInString:theString options:0 range:{location:0, |length|:anNSString's |length|()}set theNSDataDetector to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypeLink) |error|:(missing value)set anNSString to current application's NSString's stringWithString:theStringon findURLsIn:theStringdisplay dialog "The search value was not found" buttons {"OK"} default button "OK"tell application "Safari" to set URL of front document to firstLinkset firstLink to item linkPosition of thelistset linkPosition to getPositionOfItemInList(seek, thelist)set seek to text returned of the resultdisplay dialog "What is the link keyword?" default answer ""set thelist to my findURLsIn:pageTextset pageText to source of front documentend lineTextreturn "unknown"return "1"else if lineType is "DoubleBar" thenreturn "1..*"else if lineType is "CrowBar" thenreturn "0..*"if lineType is "CrowBall" thenon lineText(lineType)set tail type of theLine to ""set labelOffset of tailTextGraphic to 11set labelPosition of tailTextGraphic to 0.18set labelConnection of tailTextGraphic to theLineset tailTextGraphic to make new shape at end of graphics with properties {draws stroke:false, origin:{10, 10}, autosizing:full, size:{29.0, 14.0}, text:{text:tailText, alignment:center}, draws shadow:false}set tailText to my lineText(tail type of theLine)set head type of theLine to ""set labelOffset of headTextGraphic to 11set labelPosition of headTextGraphic to 0.74set labelConnection of headTextGraphic to theLineset headTextGraphic to make new shape at end of graphics with properties {draws stroke:false, origin:{10, 10}, autosizing:full, size:{29.0, 14.0}, text:{text:headText, alignment:center}, draws shadow:false}set headText to my lineText(head type of theLine)tail type of theLinehead type of theLinerepeat with theLine in linesset theLines to get linestell canvas of front windowtell application "OmniGraffle Professional 4"set properties to {screen edge:bottom}set properties to {screen edge:right}tell application "System Settings"end convertIntlDatereturn resultDateset the seconds of resultDate to (text 18 thru 19 of textDate)if (length of textDate) > 16 thenset the minutes of resultDate to (text 15 thru 16 of textDate)set the hours of resultDate to (text 12 thru 13 of textDate)if (length of textDate) > 10 thenset the time of resultDate to 0set the day of resultDate to (text 9 thru 10 of textDate)set the month of resultDate to (text 6 thru 7 of textDate)set the year of resultDate to (text 1 thru 4 of textDate)set resultDate to the current dateto convertIntlDate(textDate)display notification ("Note Created Date set to: " & dCreationDate) with title lsProcessTitledisplay dialog "*** NOTE NOT SELECTED ***"set creation date of aNote to dCreationDateset aNote to first item of _sel -- Get ONLY the 1st Noteif _sel ≠ {} thenset _sel to selection -- Gets the Note(s) Selected in Evernoteset dCreationDate to convertIntlDate(strCreationDate)on error --- Try International Date format (YYYY-MM-DD)set dCreationDate to date (strCreationDate)try -- Try Standard U.S. date format --set strCreationDate to (the clipboard as text)keystroke "c" using command down -- Simulate CMD-Cactivate application "Evernote"set lsProcessTitle to "Evernote Set Creation Date " & lsVerproperty strCreationDate : "Jan 7, 2016"property lsVer : "1.2"set page width to "6i"set page height to "8i"tell document preferencestell application "Adobe InDesign CS4"end minNumerror "unable to minNum - " & errMsg number errNumreturn smallestFoundif oneValue < smallestFound then set smallestFound to oneValueset oneValue to i's contents as numberrepeat with i in someListset smallestFound to item 1 of someList as numberif class of someList is not list then error "not a list." number -1703on minNum(someList)minNum({1, 6, 2, 6, -1, 0.1, -5.9})click at {300, 100} -- {from left, from top}tell application "Safari" to activateset text item delimiters of AppleScript to odset theString to "" & theStringset theString to text items of theStringset od to text item delimiters of AppleScriptlocal odif theString contains find thenon replaceText(theString, find, replace)end checkLinksif add and not (exists record with URL thisLink in theDatabase) then add download thisLink referrer theReferrerelse if thisLink contains "_n.jpg" or thisLink contains "_n.png" or thisLink contains "_o.jpg?dl=1" or thisLink contains "_o.png?dl=1" thenelse if not isFacebook and not isInstagram thenset add to trueif thisLink contains "s320x320" then set thisLink to my replaceText(thisLink, "s320x320", "s1080x1080")else if isWebsta thenif thisLink does not contain "_n.jpg" and thisLink does not contain "/buddyicons/" then set add to trueif isFlickr thenset add to falseif thisLink does not contain "32x32" and thisLink does not contain "128x128" and thisLink does not contain "150x150" and thisLink does not contain "306x306" thenif thisLink contains ".jpg" or thisLink contains ".JPG" or thisLink contains ".jpeg" or thisLink contains ".JPEG" or thisLink contains ".jp2" or thisLink contains ".JP2" or thisLink contains "_n.png" thenrepeat with thisLink in theLinkslocal add, thisLinkon checkLinks(theLinks, isFlickr, isFacebook, isInstagram, isWebsta, theReferrer, theDatabase)my checkLinks(get links of theSource base URL theURL, isFlickr, isFacebook, isInstagram, isWebsta, theURL, theDatabase)if isFlickr or isFacebook or isWebsta then my checkLinks(get embedded images of theSource base URL theURL, isFlickr, isFacebook, isInstagram, isWebsta, theURL, theDatabase)set isFlickr to trueelse if theURL contains "flickr." and theURL contains "/photos/" thenset isWebsta to trueelse if theURL contains "websta." thenset isInstagram to trueelse if theURL contains "instagram." thenset isFacebook to trueset theSource to download markup from theURLif theURL contains "facebook." and theURL contains "/photos/" thenset isFacebook to falseset isFlickr to falseset isWebsta to falseset isInstagram to falseset theURL to URL of theRecordset theSource to source of theRecordset theDatabase to database of theRecordrepeat with theRecord in theRecordsreturn selectedSentenceset selectedSentence to resultget the inSoundBarR of ChosenScriptLoaddo shell script "osascript " & chosenScriptPath ------ Run the once to update it's variabels.set ChosenScriptLoad to (load script (scriptPath as text) & chosenScript) -- *load script* command to the Fileset chosenScriptPath to scriptPath & chosenScript -- Full Pathset scriptPath to (homeDirectory & "Scripts/TTS/ScriptFiles/Sentences/") -- Folder Pathset homeDirectory to {POSIX path of home directory} of (system info) -- Get User's Home Directoryset chosenScript to "Sentences.scpt" -- File to Be Refernceend adding folder items toreturn numberdisplay dialog "Error: " & errStrdisplay notification "Video convertation completed" & base_name with title "ffmpeg"do shell script "/usr/local/bin/ffmpeg -i " & quoted form of file_path & " " & quoted form of dest_fileset dest_file to destination_directory & "/" & base_name & ".mp4"if kind of (info for this_item) is not "folder" thenset base_name to text 1 thru -5 of base_nameset ext to text -4 thru end of base_nameset base_name to do shell script "basename " & quoted form of file_pathset the file_path to the POSIX path of this_itemset this_item to item i of these_itemsrepeat with i from 1 to number of items in these_itemsset the destination_directory to POSIX path of the destination_folderset the destination_folder to folder "converted" of this_folder as aliasmake new folder at this_folder with properties {name:"converted"}if not (exists folder "converted" of this_folder) thenon adding folder items to this_folder after receiving these_itemsif ddButton = "Copy Error Message" then set the clipboard to edefault button "OK" giving up after 30)(display dialog e with title "ERROR!" buttons {"Copy Error Message", "Cancel", "OK"} ¬tell application (path to frontmost application as text) to set ddButton to button returned of ¬if n ≠ -128 thenset e to e & return & return & "Num: " & non error e number ndo script shCMDdo script shCMD in itif its busy = false thentell selected tab of front windowset shCMD to "cd " & quoted form of itemPatherror "Error:" & linefeed & linefeed & "Improper item selected in the Finder!"set itemPath to POSIX path of (theItem as text)if kind of (item theItem) is in {"Application", "Folder"} thenset theItem to item 1 of finderSelectionListif length of finderSelectionList = 0 then error "No files were selected in the Finder!"set finderSelectionList to selection as alias listtell theWindow to |center|()tell theStatusMenu to setDelegate_(me)tell theStatusItem to setMenu_(theStatusMenu)tell theStatusItem to setTitle_("🐱")set theStatusItem to NSStatusBar's systemStatusBar's statusItemWithLength_(l)set l to current application's NSVariableStatusItemLengthon menuDidClose:notificationon menuWillOpen:notificationproperty theStatusItem : missing valuetell theWindow to makeKeyAndOrderFront_(me)on |preferences|:senderon greet:senderdisplay alert "hello (again)"on clickMe:senderproperty theStatusMenu : missing valueproperty NSStatusBar : class "NSStatusBar"end processBundleIDreturn aProcessset aProcess to contents of first item of aProcessif aProcess = {} thenset aProcess to every process whose bundle identifier is equal to bundleIDon processBundleID(bundleID)end replaceHtmlEntityset tmpText to replaceStringAction(tmpText, "\"", """)set tmpText to replaceStringAction(tmpText, ">", ">")set tmpText to replaceStringAction(tmpText, "<", "<")set tmpText to replaceStringAction(tmpText, "&", "&")on replaceHtmlEntity(targetText)end replaceStringActionreturn tmpTextset AppleScript's text item delimiters to origDelimiterset tmpText to tmpList as stringset AppleScript's text item delimiters to afterStringset tmpList to every text item of tmpTextset AppleScript's text item delimiters to beforeStringset origDelimiter to AppleScript's text item delimiterscopy targetText to tmpTexton replaceStringAction(targetText, beforeString, afterString)end insertMarsEditset selected text in document 1 to insertText as textset insertText to formattedText(targetItems) of DataObjectif (count of targetItems) is equal to 0 thenon insertMarsEdit(targetItems)end chooseItemsreturn selectedRecordsif (count of selectedRecords) is equal to 0 thenset the end of selectedRecords to item i of targetListif item i of targetList contains {listTitle:item j of selectedListTitles} thenrepeat with j from 1 to count of selectedListTitlesset selectedRecords to {}if selectedListTitles = false then return 0set selectedListTitles to choose from list listTitles with prompt dialogMessage default items (item 1 of listTitles) with multiple selections allowedset the end of listTitles to listTitle of (item i of targetList)repeat with i from 1 to count of targetListset listTitles to {}set dialogMessage to "リストを作る項目を選択してください (Cmd + クリック で複数選択)"on chooseItems(targetList)insertMarsEdit(selectedItems) of meif selectedItems is equal to 0 thenset selectedItems to chooseItems(siteRecords) of meif (count of siteRecords) is greater than 0 thenset siteRecords to {{wwwTitle:siteTitle, wwwURL:siteURL, wwwPubDate:sitePubDate, listTitle:(((count of blogPosts) - i + 1) & ": " & siteTitle) as string}} & siteRecordsset sitePubDate to (pubYear & "/" & pubMonth & "/" & pubDay & " " & pubHour & ":" & pubMinute & ":" & pubSecond) as stringset pubSecond to ((time of tmpDate) mod hours) div minutesset pubMinute to (time of tmpDate) mod minutesset pubHour to (time of tmpDate) div hoursset pubDay to day of tmpDateset pubMonth to (month of tmpDate) as integerset pubYear to year of tmpDateset tmpDate to published date of blogPostset siteURL to permalink of blogPostset siteTitle to title of blogPostif published status of blogPost is equal to "Published" thenset blogPost to item i of blogPostsrepeat with i from 1 to count of blogPostsset blogPosts to posts of selected blogtell application "MarsEdit"if item 1 of selectedApplication is equal to "MarsEdit" thenlog selectionTextset selectionText to execute javascript "unescape(escape(getSelection()));" as stringtell tabDocumentset siteTitle to title of tabDocumentif (count of window) is equal to 0 thenif item 1 of selectedApplication is equal to "GoogleChrome" thenset the end of siteRecords to siteRecordset siteRecord to {wwwTitle:siteTitle, wwwURL:URL of tabDocument, wwwSelection:selectionText, listTitle:(i & ": " & siteTitle) as string}set selectionText to (do JavaScript selectionCommand in tabDocument) as stringset selectionCommand to "window.unescape(escape(window.getSelection()));"set siteTitle to name of tabDocumentset tabDocument to item i of tabsrepeat with i from 1 to count of tabsset siteRecords to {}if (count of document) is equal to 0 thenif targetProcess is equal to false thenset targetProcess to marseditProcessBelse if marseditProcessB is not equal to false thenset targetProcess to marseditProcessAif marseditProcessA is not equal to false thenelse if item 1 of selectedApplication is equal to "MarsEdit" thenset targetProcess to processBundleID("com.google.Chrome")else if item 1 of selectedApplication is equal to "GoogleChrome" thenset targetProcess to processBundleID("com.apple.Safari")if item 1 of selectedApplication is equal to "Safari" thenif selectedApplication = false then returnset selectedApplication to choose from list targetApplications with prompt "どのアプリケーションからリンクを作成しますか?" default items (item 1 of targetApplications)set targetApplications to {"Safari", "GoogleChrome", "MarsEdit"}if marseditProcessA is equal to false and marseditProcessB is equal to false thenset marseditProcessB to processBundleID("com.red-sweater.marsedit")set marseditProcessA to processBundleID("com.red-sweater.marsedit.macappstore")end formattedTextreturn resultTextif resultText is equal to "" thenset resultText to replaceStringAction(resultText, "%{date}", dateText)set dateText to (do shell script "date " & dateFormat)set resultText to replaceStringAction(resultText, "%{count}", (count of objs) as string)set resultText to beforeTemplate & resultText & afterTemplateset resultText to (resultText & tmpResult)set tmpResult to replaceStringAction(tmpResult, "%{imageHeight}", imageHeight as string)set tmpResult to replaceStringAction(tmpResult, "%{imageWidth}", imageWidth as string)set tmpResult to replaceStringAction(tmpResult, "%{publishDate}", tmpPubDate)set tmpPubDate to (do shell script "date -jf '%Y/%m/%e %H:%M:%S' '" & wwwPubDate of obj & "' " & dateFormat)set tmpResult to replaceStringAction(tmpResult, "%{escapeSelection}", replaceHtmlEntity(wwwSelection of obj))set tmpResult to replaceStringAction(tmpResult, "%{selection}", wwwSelection of obj)set tmpResult to replaceStringAction(tmpResult, "%{imageURL}", tmpImageURL)set tmpImageURL to "http://capture.heartrails.com/" & imageWidth & "×" & imageHeight & "?" & (wwwURL of obj)set tmpResult to replaceStringAction(tmpResult, "%{escapeURL}", replaceHtmlEntity(wwwURL of obj))set tmpResult to replaceStringAction(tmpResult, "%{sourceURL}", wwwURL of obj)if wwwURL of obj is not equal to "" thenset tmpResult to replaceStringAction(tmpResult, "%{escapeTitle}", replaceHtmlEntity(wwwTitle of obj))set tmpResult to replaceStringAction(tmpResult, "%{sourceTitle}", wwwTitle of obj)if wwwTitle of obj is not equal to "" thenset tmpResult to mainTemplateset obj to item i of objsrepeat with i from 1 to (count of objs)switchTemplateType(item 1 of selectedType)if selectedType = false then returnset selectedType to choose from list templateTypes with prompt "どのテンプレートを使用しますか?" default items (item 1 of templateTypes)set resultText to ""set templateTypes to {"Simple", "Simple with Thumbnail", "List", "List with Thumbnail", "Blockquote", "Blockquote with Thumbnail"}to formattedText(objs)end switchTemplateType%{escapeTitle}if templateType is equal to "Blockquote with Thumbnail" thenset imageHeight to 80set imageWidth to 80

%{escapeSelection}

if templateType is equal to "Blockquote" thenset beforeTemplate to ""%{escapeTitle}
if templateType is equal to "Simple with Thumbnail" thenset imageHeight to 120set imageWidth to 120"%{escapeTitle}\"%{sourceURL}\"/
  • if templateType is equal to "List with Thumbnail" thenset afterTemplate to "
      参考記事
    • %{escapeTitle}
    • "set mainTemplate to "if templateType is equal to "List" thenset afterTemplate to ""set beforeTemplate to "set mainTemplate to "%{escapeTitle}
      if templateType is equal to "Simple" thento switchTemplateType(templateType)property pubDateFormat : "'+%Y/%m/%d'"property dateFormat : "'+%Y/%m/%d'"property imageHeight : 130property imageWidth : 130property afterTemplate : ""property beforeTemplate : ""property mainTemplate : ""script DataObjectend FetchBuildbuild_label's setStringValue_(latest as string)set latest to do shell script "curl http://commondatastorage.googleapis.com/chromium-browser-snapshots/Mac/LAST_CHANGE"on FetchBuild()end applicationShouldTerminate_on applicationShouldTerminate_(sender)end applicationWillFinishLaunching_on applicationWillFinishLaunching_(aNotification)end awakeFromNibon awakeFromNib()property latest : missing valueproperty build_label : missing valuescript Chromium_UpdaterAppDelegatemyProjectsclose access NewFilewrite myProjects to NewFile as «class utf8»set NewFile to open for access file thePath with write permissionset thePath to (path to documents folder as text) & "projects.csv"set myProjects to get name of folders of folder "Macintosh HD:Users:judis:Google Drive:Matters:" as textset AppleScript's text item delimiters to "user ID of (get system info)tell application (path to frontmost application as string) to set bounds of front window to screen_resolutiontell application "Finder" to set screen_resolution to bounds of window of desktoptell application (path to frontmost application as string) to set zoomed of front window to falseif is_zoomed = true thentell application (path to frontmost application as string) to set is_zoomed to zoomed of front windowclick bt -- close main dropdown to clean up after ourselvesdelay 5 -- hang out for a bit before re-connectingend newFoldmake new folder at thisFolder with properties {name:"Archive"}if item i of subNameList contains "~orig" thenset thisFolder to make new folder at newJobFolder with properties {name:"" & item i of subNameList}set newJobFolder to (make new folder at thefolder with properties {name:theNumber & "_" & theName})set itemCount to count of subNameListset subNameList to {"~finals", "~src", "EPUB2", "EPUB3", "KF8"}on newFold(theNumber, theName, thefolder)set newJobFolder to my newFold(jobNum, jobName, folderpath)set folderpath to (choose folder with prompt "Select Client Folder" default location default_path)set jobName to text returned of (display dialog "Project Name:" default answer "")set jobNum to text returned of (display dialog "Client Name:" default answer "")set default_path to "/Users/aaron/eprdctn/Client/"do shell script "/usr/local/bin/pandoc -f html " & path_file & " -t markdown -o " & dest_file & baseName & ".md"set dest_file to choose folder with prompt "Where to save the markdown file?"end Joinreturn retset ret to items of l as textset AppleScript's text item delimiters to delimslocal reton Join(delims, l)end Splitreturn theArrayset AppleScript's text item delimiters to oldDelimitersset theArray to every text item of theStringset oldDelimiters to AppleScript's text item delimiterson Split(theString, theDelimiter)end ReplaceTexton ReplaceText(find, replace, subject)end GetTitleFromURLreturn item 1 of my Split(title, "/")set title to my ReplaceText(pat, "", title)repeat with pat in patsset pats to {"http://", "https://"}copy val to titleon GetTitleFromURL(val)end SpeakListsay theItemrepeat with theItem in lsay "List named " & nameon SpeakList(l, name)end CSVCellEncodereturn cellstrif (cellstr contains "," or cellstr contains " " or cellstr contains "\"" or cellstr contains return or cellstr contains character id 10) then set cellstr to quote & cellstr & quoteset cellstr to cellstr & cset cellstr to cellstr & "\"\""if c is "\"" thenset c to c as textrepeat with c in the characters of origset cellstr to ""set orig to cellstrif cellstr is "" then return ""on CSVCellEncode(cellstr)end WriteToclose access file targetFileclose access openFilewrite theData to openFile starting at eof as dataTypeif append is false then set eof of openFile to 0set openFile to open for access file targetFile with write permissionset targetFile to targetFile as texton WriteTo(targetFile, theData, dataType, append)end write_csv_fileset theResult to WriteTo(fpath, csvstr, «class utf8», false)set j to j + 1set csvstr to csvstr & "," & encodedset csvstr to csvstr & encodedelse if j is 1 thenset csvstr to encodedif csvstr is "" thenset encoded to CSVCellEncode(item j of rowdata)repeat while j ≤ (count of rowdata)set j to 1set csvstr to csvstr & character id 10if csvstr is not "" thenset rowdata to item i of Entriesrepeat while i ≤ (count of Entries)set csvstr to ""set beginning of Entries to {"Title", "Login URL", "Login Username", "Login Password", "Additional URLs"}local rowdataon write_csv_file(Entries, fpath)end FetchEntriesreturn tableEntriesset row_index to row_index + 1set the end of tableEntries to rowValuescopy tmpList to rowValuesset tmpList to {theTitle, theSite, theUser, thePass, theURLs}local tmpListset theURLs to Join(character id 59, urlList) of meset thePass to value of attribute "AXValue" of text field 2 of theSheetset theUser to value of attribute "AXValue" of text field 1 of theSheetset url_index to url_index + 1set the end of urlList to aURLcopy aURL to theTitlecopy aURL to theSiteif aURL is missing value or aURL is equal to "" thenif url_index is equal to 1 thenset aURL to (the value of static text of item 1 of UI element 1 of row url_index of theURLtable) as textlocal aURLrepeat while url_index ≤ nURLsset url_index to 1set nURLs to the count of rows of theURLtableset theURLtable to table 1 of scroll area 1 of theSheetif theSheet is not 0 thensay "Sheet for row " & row_index & "did not open - Skipping Entry"set theSheet to sheet 1 of prefsWinset theSheet to 0set urlList to {}set {theTitle, theSite, theUser, thePass, theURLs} to {"Untitled", "", "", "", ""}local theSite, theName, theUser, thePass, theURLs, urlList, rowValues, theSheetset focused to trueselect row row_indexset myRow to row row_indexlocal myRowrepeat while row_index ≤ nRowsset row_index to 1local row_indextell theTableset nRows to the count of rows of table 1 of scroll area 1 of group 1 of group 1 of prefsWinset theTable to table 1 of scroll area 1 of group 1 of group 1 of prefsWinset prefsWin to window 1if (button returned of theResult) is "Cancel" thenset theResult to display dialog "Please unlock " & buttonName & " and press Continue when unlocked" buttons {"Cancel", "Continue"} default button "Continue"click button 4 of tbset buttonName to (name of button 4 of tb as string)set tb to toolbar 1 of window 1keystroke "," using {command down}set tableEntries to {}on FetchEntries()You may now convert it to a 1PIF for import into 1Password using the csv converter in the converter suite."pm_export.csvThere is now a file on your Desktop named:display dialog "All done!tell application "System Events" to tell application process invokedByreveal csv_filepathset target of Finder window 1 to path to desktopmake new Finder windowtell application "System Events" to tell application process "Safari"display dialog "There was an error writing the data!"if not theResult thenset theResult to write_csv_file(Entries, csv_filepath)set Entries to FetchEntries()set Entries to {}set invokedBy to get the name of the current applicationset invokedBy to ""set csv_filepath to (path to desktop as text) & "pm_export.csv"use AppleScript version "2.5" -- runs on 10.11 (El Capitan) and laterset butts to busy of window 1end lowercaseTextreturn aTextset aText to tempList as textset text item delimiters to (item i of lowercaseCharacters)set tempList to text items of aTextset text item delimiters to (item i of uppercaseCharacters)if aText contains (item i of uppercaseCharacters) thenrepeat with i from 1 to count of uppercaseCharactersset end of uppercaseCharacters to ASCII character (item i of uppercaseSpecialCharacters)repeat with i from 1 to count of uppercaseSpecialCharactersset end of lowercaseCharacters to ASCII character (item i of lowercaseSpecialCharacters)repeat with i from 1 to count of lowercaseSpecialCharactersset uppercaseCharacters to characters of uppercaseCharactersset lowercaseCharacters to characters of lowercaseCharactersset uppercaseSpecialCharacters to {128, 129, 203, 204, 231, 229, 174, 130, 131, 230, 232, 233, 234, 235, 236, 237, 132, 133, 205, 238, 239, 241, 206, 134, 242, 243, 244, 217}set lowercaseSpecialCharacters to {138, 140, 136, 139, 135, 137, 190, 141, 142, 144, 145, 143, 146, 148, 149, 147, 150, 154, 155, 151, 153, 152, 207, 159, 156, 158, 157, 216}set uppercaseCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"set lowercaseCharacters to "abcdefghijklmnopqrstuvwxyz"on lowercaseText(aText)lowercaseText("Hello World!")tell application "Finder" to activatetell application "Finder" to open folder "stuf"tell application "Finder" to mount volume "smb://r7000/stuf"click button "保存" of window 1set value of text area 1 of scroll area 1 of UI element 1 of row 6 of table 1 of scroll area 1 of window 1 to theNoteclick button 1 of UI element 1 of row 5 of table 1 of scroll area 1 of window 1set value of text field 1 of UI element 1 of row 2 of table 1 of scroll area 1 of window 1 to theCostclick menu item "软件" of menu 1 of menu item "买买买" of menu 1 of pop up button 1 of UI element 1 of row 2 of table 1 of scroll area 1 of window 1click menu item "买买买" of menu 1 of pop up button 1 of UI element 1 of row 2 of table 1 of scroll area 1 of window 1click pop up button 1 of UI element 1 of row 2 of table 1 of scroll area 1 of window 1click (first menu item whose title contains "Discover") of menu 1 of pop up button 1 of UI element 1 of row 1 of table 1 of scroll area 1 of window 1click pop up button 1 of UI element 1 of row 1 of table 1 of scroll area 1 of window 1click button 2 of group 1 of group 1 of group 1 of window 1tell process "Money Pro"(linefeed & linefeed & linefeed) with icon file "Applications:Money Pro.app:Contents:Resources:AppIcon.icns")set theNote to text returned of (display dialog "请输入项目内容:" default answer ¬display notification "你必须输入数字才行!" with title "AppleScript 已停止"set theCostNumber to theCost as numberdisplay notification "因为你他喵的啥也没输入……" with title "AppleScript 已停止"if theCost is equal to "" thenset theCost to text returned of dialogResultif button returned of dialogResult is "Cancel" then returnset dialogResult to display dialog "请输入金额:" default answer "" with icon file "Applications:Money Pro.app:Contents:Resources:AppIcon.icns" buttons {"Cancel", "Continue"} default button "Continue"tell application "Money Pro" to activatedisplay dialog the_messageset the_message to "Your time zone is GMT"set the_message to "You are " & time_difference & " hours ahead of GMT"else if time_difference > 0 thenset the_message to "You are " & time_difference & " hours behind GMT"set time_difference to -time_differenceif time_difference < 0 thenset time_difference to time_difference as integerif time_difference mod 1 = 0 then set time_difference to (time to GMT) / hourseject (every disk)open location "https://docs.python.org/3/search.html?q=" & argvset q name of newCue to userCueName & (scene)set q name of newCue to userCueName & (scene) & " (Ch 16 / CC " & byteOne & " - " & byteTwo & ")"if userShowMIDIInfo thenset byte two of newCue to byteTwoset channel of newCue to 16set byteTwo to (i - 256)set byteOne to 18set byteTwo to (i - 128)set byteOne to 17else if i is less than 257 thenset byteTwo to iset byteOne to 16if i is less than 129 thenset command of newCue to control_changeset q number of newCue to userPrefix & (scene)repeat userCount timesset userCount to 118 -- The number of snapshot triggers to generate. Do not set above 384.set userShowMIDIInfo to trueset userCueName to "SD Snapshot "set userPrefix to "sd"if width is 0 then its sizeToFit()if transparent is not missing value then its setTransparent:transparentif bordered is not missing value then its setBordered:borderedif buttonType is not missing value then its setButtonType:buttonType -- 0-9 or NSButtonType enumits setControlSize:controlSize -- 0-3 or NSControlSize enumits setBezelStyle:bezelStyle -- 1-15 or NSBezelStyle enumif titleFont is not missing value then its setFont:titleFontif alternateTitle is not missing value then its setAlternateTitle:alternateTitleits setTitle:titletell (current application's NSButton's alloc's initWithFrame:{origin, {width, 40}}) -- old styleif width is in {0, false, missing value} then set width to 0to makeButton at origin given controlSize:controlSize : 0, width:width : missing value, title:title : "Button", alternateTitle:alternateTitle : missing value, titleFont:titleFont : missing value, buttonType:buttonType : missing value, bezelStyle:bezelStyle : 1, bordered:bordered : missing value, transparent:transparent : missing value, tag:tag : missing value, action:action : "buttonAction:", target:target : missing valueend switchAction:display dialog "A switch tagged " & theTag & " was turned " & theState & "." buttons {"OK"} default button 1 giving up after 2set theState to "off"set theState to "on"if (sender's state as integer) is 1 thenset theTag to sender's tagon switchAction:senderend makeSwitchits setControlSize:controlSize -- 0-2 or NSControlSize enumtell (current application's NSSwitch's alloc's initWithFrame:{origin, {42, 25}}) -- just size for largestto makeSwitch at origin given controlSize:controlSize : 0, state:state : 0, tag:tag : missing value, action:action : "switchAction:", target:target : missing valueend change_casereturn the new_textset the new_text to (the new_text & this_char) as stringset the new_text to (the new_text & character x of the source_string) as stringif x is not 0 thenset x to the offset of this_char in the comparison_stringset the new_text to ""set the source_string to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"set the comparison_string to "abcdefghijklmnopqrstuvwxyz"set the source_string to "abcdefghijklmnopqrstuvwxyz"set the comparison_string to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"if this_case is 0 thenon change_case(this_text, this_case)end justTheLettersreturn outputStringif theLetters contains anChar then set outputString to outputString & anCharrepeat with anChar in inputStringset outputString to ""set theLetters to "qwertyuiopasdfghjklzxcvbnm"on justTheLetters(inputString)change_case(justTheLetters(testTXT), 0)set testTXT to "Jackie Jackie (Spend This Winter With Me)"end assemblyMacOSPathreturn assembliedFilePathset assembliedFilePath to separatedFilePath as stringon assemblyMacOSPath(separatedFilePath)end modifyExtensionSurfixreturn assemblyMacOSPath(completeFilePath)set last item in completeFilePath to modifiedNameset modifiedName to first item in splitText(originalName, ".") & targetExtensionset originalName to last item in completeFilePathset completeFilePath to splitText(filePathText, ":")on modifyExtensionSurfix(filePathText, targetExtension)close tempDocument saving nosave as tempDocument file name documentName file format format PDFset documentName to my modifyExtensionSurfix(docItem as string, ".pdf")set tempDocument to document docRefopen docItemset docRef to name of (info for docItem)repeat with docItem in docListset docList to choose file with multiple selections allowedset array to current application's NSArray's arrayWithArray:dateListset dateList to {date ("2015-01-01"), date ("2014-01-01"), date ("2016-01-01")}with data {e}with properties {name:"AppleScript Check"}¬make new results browser¬set e to {¬ result_kind:note_kind,¬ result_file:"/System/Library/ScriptingDefinitions/CocoaStandard.sdef",¬ result_line:1,¬ message:"This browser will open"¬ }open location noteURLset noteURL to first item in noteURLs" at before first paragraph of noteinsert noteURL & "tell theProjectset noteURL to shortcutsScheme of (my getNoteUri(noteId))set noteId to «class seld» of (newNote as record)set newNote to make new note in default account at folder "Notes" with properties {body: noteBody}set noteBody to "

      " & theProject's name & "

      " & taskUrl & "

      "set taskUrl to "omnifocus:///task/" & (theProject's id)if (count of noteURLs) is 0 thenset noteURLs to (every paragraph of theProject's note where it starts with (my NOTE_SHORTCUTS_URL_PREFIX))set theProject to myTaskset theProject to myTask's containing projectif myTask's class is task thenrepeat with myTask in validSelectedItemsListdisplay notification "Multiple items selected." with title "Error"if totalItems > 1 thendisplay notification "No tasks or projects selected" with title "Error"set validSelectedItemsList to value of (selected trees where class of its value is not item and class of its value is not folder and class of its value is not tag and class of its value is not perspective)getTIFF("my bitmap").getRow(3).getPixel(7);do shell script "kill -KILL " & pidListif procesList contains applaunch thenset {procesList, pidList} to the {name, unix id} of (every process whose name contains applaunch)tell application applaunchelse if applaunch contains applaunch thenif applaunch contains "" thenset applaunch to text returned of (display dialog "" default answer "" buttons {"Go"} default button "Go")my notifyWithSticky("General", "Title", "Body")end notifyWithGrowlMethod2do shell script shellScriptignoring application responsesset shellScript to "osascript -e " & quoted form of osascript & " &> /dev/null &"notify with name \"" & alertName & "\" title \"" & alertTitle & "\" application name growlAppName description \"" & alertText & "\"notify with name \"" & alertName & "\" title \"" & alertTitle & "\" application name growlAppName description \"" & alertText & "\" with stickyregister as application growlAppName all notifications allNotifications default notifications enabledNotifications icon of application iconApplicationtell application \"" & growlHelperAppName & "\"property iconApplication : \"" & iconApplication & "\"property enabledNotifications : " & dictToString(enabledNotifications) & "property allNotifications : " & dictToString(allNotifications) & "set osascript to "property growlAppName : \"" & growlAppName & "\"if useSticky thenon notifyWithGrowlMethod2(growlHelperAppName, alertName, alertTitle, alertText, useSticky)property growlHelperAppName : ""close window 1save d as "text" in POSIX file (((destinationFolder & theName as string) & "applescript") as string) -- with run onlytell me to set d to getScriptEditorDocumentFor(currFile)open currFilelog currFiletell me to set theName to replace_chars(theNameWithExt, theExtension, "")set theExtension to name extension of currFileset theNameWithExt to name of currFilerepeat with currFile in myFileListset myFileList to every file in sourceFolderset destinationFolder to "/Users/ryan/Desktop/SCRIPTS_AS_APPLESCRIPTS/"set sourceFolder to alias "Macintosh HD:Users:ryan:SCRIPTS_AS_SCRIPTS/"end getScriptEditorDocumentForreturn item 1 of docsset docs to every document whose path is (POSIX path of myAlias)tell application "AppleScript Editor"tell application "Finder" to set myAlias to myFileRef as aliasto getScriptEditorDocumentFor(myFileRef)the clipboardend round_to_decimal_placesreturn result / multiplierround resultthe_number_to_round * multiplierset multiplier to 10 ^ the_decimal_precision on round_to_decimal_places(the_number_to_round, the_decimal_precision)tell application "Google Chrome" to tell w to make new tab with properties {URL:t}repeat with t in _tabsset _tabs to (URL of every tab of window 1)tell application "Google Chrome" to set w to (make new window)make new to recipient with properties {address:recipientAddress}https://www.facebook.com/groups/helsinkiwindsurfingclub/http://helsinkiwindsurfingclub.fi/hwc@helsinkiwindsurfingclub.fiHeikki Rauhala / HWCSurffiterveisin,käyttäen henkilökohtaista viitenumeroasi " & refNumber & ".sekä liittymismaksusi tilille FI41 5800 1320 2592 02 (OKOYFIHH)Ole hyvä ja maksa jäsenmaksusi ja mahdollinen lautapaikkavuokrasi,* Liittymismaksu 20€* Lautapaikkavuokra 30€* Jäsenmaksu 20€Helsinki Windsurfing Clubin maksut kaudelta 2015 ovat:set theContent to "Hei,set theSubject to "HWC Jäsen- ja lautapaikkamaksut 2015"set refNumber to item 2 of argvset recipientAddress to item 1 of argvend trimLineset theText to characters 1 thru -(x + 1) of theText as stringrepeat while theText ends with the trimCharsif the trimIndicator is in {1, 2} thenset theText to characters (x + 1) thru -1 of theText as stringrepeat while theText begins with the trimCharsif the trimIndicator is in {0, 2} thenset x to the length of the trimCharson trimLine(theText, trimChars, trimIndicator)" & newScriptSourceset script source of scriptCue to script source of scriptCue & userDefinedVariablesContent & "set script source of scriptCue to ""set script source of scriptCue to "-- @version " & eachScriptVersion & "run theScript"set newScriptSource to "set theScript to load script \"" & (newPath) & "\"set notes of scriptCue to cueNoteset cueNote to cueNote & ")"set cueNote to cueNote & " // " & eachScriptSource & ")"set cueNote to cueNote & " (" & eachScriptAuthorset cueNote to eachScriptAboutset q name of scriptCue to cueNameset cueName to my trimLine(cueName, ".applescript", 1)set cueName to name of eachScriptset q name of scriptCue to eachScriptDescriptionmake type "Script"set scriptCue to last item of (selected as list)if (length of scriptFiles is 1) and (length of selectedCues is 1) and (q type of item 1 of selectedCues is "Script") thenlog newPathset newPath to POSIX path of newPathAliasset newPathAlias to destinationURL as aliasset {theResult, theError} to (theScript's writeToURL:destinationURL ofType:"scpt" usingStorageOptions:0 |error|:(reference))if theResult as boolean is false then return theError's |description|() as textset {theResult, theError} to (theScript's compileAndReturnError:(reference))if theScript is missing value then error theError's |description|() as textset {theScript, theError} to (current application's OSAScript's alloc()'s initWithContentsOfURL:aURL |error|:(reference))if eachScriptSeparateProcess is "FALSE" then return -- scripts need to work as a separate process for this method", 0)set scriptContents to my trimLine(scriptContents, "set scriptContents to scriptContents & "if eachLine does not contain "-- @" and eachLine does not contain "-- " thenset eachLine to ""if userDefinedVariables is true then" & eachLineset userDefinedVariablesContent to userDefinedVariablesContent & "else if eachLine contains "--- END OF USER DEFINED VARIABLES" thenset userDefinedVariablesContent to ""set userDefinedVariables to trueif eachLine contains "USER DEFINED VARIABLES ---" thenlog "Separate Process: " & eachScriptSeparateProcessset eachScriptSeparateProcess to trimLine(eachLine, "-- @separateprocess ", 0)else if eachLine contains "@separateprocess" thenlog "About: " & eachScriptAboutset eachScriptAbout to trimLine(eachLine, "-- @about ", 0)else if eachLine contains "@about" thenlog "Qlab: " & eachScriptQlabset eachScriptQlab to trimLine(eachLine, "-- @testedqlab ", 0)else if eachLine contains "@testedqlab" thenlog "MacOS: " & eachScriptMacOSset eachScriptMacOS to trimLine(eachLine, "-- @testedmacos ", 0)else if eachLine contains "@testedmacos" thenlog "Version: " & eachScriptVersionset eachScriptVersion to trimLine(eachLine, "-- @version ", 0)else if eachLine contains "@version" thenlog "Source: " & eachScriptSourceset eachScriptSource to trimLine(eachLine, "-- @source ", 0)else if eachLine contains "@source" thenlog "Author: " & eachScriptAuthorset eachScriptAuthor to trimLine(eachLine, "-- @author ", 0)else if eachLine contains "@author" thenlog "Description: " & eachScriptDescriptionset eachScriptDescription to trimLine(eachLine, "-- @description ", 0)if eachLine contains "@description" thenrepeat with eachLine in eachScriptContentsset userDefinedVariables to falselog "-----------"set scriptContents to ""set eachScriptContents to paragraphs of (read eachScript)set destinationURL to (aURL's URLByDeletingPathExtension()'s URLByAppendingPathExtension:"scpt")set aURL to (current application's |NSURL|'s fileURLWithPath:(POSIX path of eachScript))repeat with eachScript in scriptFilesset scriptFiles to choose file with prompt "Please select the scripts to import" of type {"applescript"} with multiple selections alloweduse framework "OSAKit"end zettelFromDate:return (theFormatter's stringFromDate:aDate) as texttheFormatter's setDateFormat:"yyyyMMddHHmmss"theFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"en_US_POSIX")set theFormatter to current application's NSDateFormatter's new()on zettelFromDate:aDatedo shell script "networksetup -setairportpower en0 off"end openDirectorydo shell script theCommandset theCommand to "open " & quoted form of thePOSIXPathset thePOSIXPath to the POSIX path of theFilePathset theFilePath to ((path to home folder) as string) & "Documents:Max 8:Max for Live Devices:"on openDirectory()openDirectory()set properties to {minimize effect:scale, magnification size:0.5, dock size:0.2, autohide:true, animate:true, magnification:false, screen edge:bottom}tell dock preferencesset first character of paragraph i of selection to ""if first character of paragraph i of selection is " " or first character of paragraph i of selection is " " thenrepeat with i from 1 to count of paragraphs of selectiondisplay dialog (count of paragraphs of selection)close keynote_file saving nodo shell script "echo Output format " & extension & " not supported."export keynote_file to (basename as POSIX file) as slide images with properties { compression factor: 1.0, image format: JPEG }else if extension is equal to "jpeg" thenexport keynote_file to (out_path as POSIX file) as PDFif extension is equal to "pdf" thenset keynote_file to open (keynote_path as POSIX file)set basename to sansExt(out_path)set extension to getExt(out_path)set out_path to (item 2 of argv)set keynote_path to (item 1 of argv)end getExtdo shell script "file=" & theFileName & ";" & "echo ${file##*.}"on getExt(theFileName)end sansExtdo shell script "file=" & theFileName & ";" & "echo ${file%.*}"on sansExt(theFileName)end lookupCitationreturn apiResult"-LH \"Accept: text/bibliography; style=" & my CitationName & "\" " & uri)set shellScript to ("curl -A \"" & my UAString & "\" " & ¬on lookupCitation(uri)end setPDFMetadataset exifresult to do shell script shellCommandset shellCommand to "/opt/homebrew/bin/exiftool -overwrite_original -" & mdKey & "=" & quoted form of mdValue & " " & quoted form of recordPathon setPDFMetadata(mdKey, mdValue, recordPath)end extractAuthorreturn authorStringset authorString to |name| of firstAuthorset authorString to family of firstAuthorset authorString to |given| of firstAuthor & " " & family of firstAuthorif firstAuthor is equal to "" thenset firstAuthor to this_entryif sequence of this_entry is equal to "first" thenset this_entry to item a of author_entriesrepeat with a from 1 to length of author_entriesset author_entries to author of record_itemset firstAuthor to ""on extractAuthor(record_item)end appleDatereturn date (date_string)on appleDate(date_string)end extractDatereturn dateStringset dateString to ""set dateString to "01-01-" & iyear as stringset iyear to item 1 of |date-parts| of issued of record_itemset dateString to "01-" & (imonth as string) & "-" & iyear as stringset [iyear, imonth] to item 1 of |date-parts| of issued of record_itemset dateString to ((iday as string) & "-" & imonth as string) & "-" & iyear as stringset [iyear, imonth, iday] to item 1 of |date-parts| of issued of record_itemon extractDate(record_item)end crossrefLookupreturn jsonResponseerror "API response not OK: " & message of jsonResponseif not status of jsonResponse is equal to "OK" thenset jsonResponse to read JSON from apiResultset apiResult to (do shell script shellScript)& " -d rows=5 -d select=author,title,type,publisher,issued,subject,URL")& " --data-urlencode query.bibliographic=" & quoted form of query ¬set shellScript to ("curl -A \"" & my UAString & "\" -G " & apiURL ¬set apiURL to "https://api.crossref.org/works"on crossrefLookup(query)my setPDFMetadata("Author", authorString, recordPath)set authorString to my extractAuthor(chosenItem)my setPDFMetadata("Title", recordTitle, recordPath)set recordTitle to item 1 of title of chosenItemset the comment of theRecord to citationset citation to my lookupCitation(uri)set the URL of theRecord to uriset uri to |URL| of chosenItemset tags of theRecord to tagListset end of tagList to typeTagset tagList to tags of theRecordif typeTag is not in tags of theRecord thenset typeTag to |type| of chosenItemset the date of theRecord to dateStructset recordPath to path of theRecordset dateStruct to my appleDate(dateString)set dateString to my extractDate(chosenItem)set chosenItem to item a of theItemsif currentItem as string is equal to theChoice as string thenset currentItem to item a of theChoicesrepeat with a from 1 to length of theChoicesif theChoice is false then returnset theChoice to choose from list theChoices with prompt "Select:"set end of theChoices to theChoiceset theChoice to title & " (" & detailString & ")"set detailString to detailString & dateStringset detailString to detailString & ", "if not detailString is equal to "" thenset detailString to my extractAuthor(currentItem)set dateString to my extractDate(currentItem)set title to item 1 of titleListset titleList to title of currentItemset currentItem to item a of theItemsrepeat with a from 1 to length of theItemsset theChoices to {}set theItems to |items| of message of theJsonset theJson to my crossrefLookup(query)show progress indicator "Looking up references..." steps -1set query to name of theRecordif query is "" thenset query to the selected text of think window 1 as stringset theRecord to content recordif not (exists content record) then error "No document selected."if not (exists think window 1) then error "No window open."set UAString to "XRefLookup/1.0 (https://gist.github.com/mnot/0d7825bde9b9d3233f623c71765f20ca; mailto:mnot@mnot.net)"set CitationName to "australian-guide-to-legal-citation"end upperStringerror "Can't upperString: " & eMsg number eNumreturn my translateChars(theText, my _lcChars_, my _ucChars_)local upper, lower, theTexton upperString(theText)end MakeSerialset _new to make new serial number item with properties {name:_product, owner name:_owner, serial number:_number, comments:_comments}on MakeSerial(_product, _owner, _number, _comments)end MakePasswordset _new to make new password item with properties {name:_name, location:_location, account:_account, password:_password}tell application "Yojimbo"on MakePassword(_name, _location, _account, _password)set AppleScript's text item delimiters to _delimMakeSerial(item 1 of _line, item 2 of _line, item 3 of _line, item 4 of _line)else if _type is "Serial Numbers" thenMakePassword(item 1 of _line, item 2 of _line, item 3 of _line, item 4 of _line)if _type is "Passwords" thenset _line to the text items of item _index of _datarepeat with _index from 1 to count of _dataset AppleScript's text item delimiters to tab -- or {","}set _delim to AppleScript's text item delimitersclose access _fileset _data to read _file using delimiter {(ASCII character 13), (ASCII character 10)}open for access _fileset _file to choose file with prompt "Select a tab delimited file containing " & _typeif _type is "Cancel" or _type is "" thenset _type to button returned of (display alert "Select what kind of data to import to Yojimbo:" buttons {"Cancel", "Serial Numbers", "Passwords"} cancel button 1)end menu_click_recursemy menu_click_recurse(r, (parentObject's (menu item f)'s (menu f)))click parentObject's menu item fif mList's length is 1 thenif mList's length > 1 then set r to (items 2 through (mList's length) of mList)set f to item 1 of mListlocal f, ron menu_click_recurse(mList, parentObject)end menu_click(menu bar 1)'s (menu bar item topMenu)'s (menu topMenu)))tell application "System Events" to my menu_click_recurse(r, ((process appName)'s ¬set r to (items 3 through (mList's length) of mList)set {appName, topMenu} to (items 1 through 2 of mList)if mList's length < 3 then error "Menu list is not long enough"local appName, topMenu, ron menu_click(mList)do script "clear;pwd" in window id window_id of application "Terminal"do script commandToRun in window id window_id of application "Terminal"set commandToRun to "cd " & quoted form of (folderName as string) --Quoted to handle spaces in foldernameskeystroke "t" using {command down}set window_id to id of first window whose frontmost is truelog "Folder Name: " & folderNameset folderName to item 1 of argv -- Folder pathend replace_textset AppleScript's text item delimiters to prevTIDsset prevTIDs to AppleScript's text item delimiterson replace_text(this_text, search_string, replacement_string)display alert "Password is: " & myPasswordif error = "none" thenset error to errStron error errStrdo shell script "networksetup -setairportnetwork" & space & quoted form of BSSID & space & quoted form of myPassword with administrator privilegesset error to "none"set myPassword to startString & inkrepeat with ink from 100 to 300do shell script "sudo touch /private/var/db/.AccessibilityAPIEnabled" user name computerUsername password computerPassword with administrator privilegesset computerPassword to "password"set computerUsername to "username"set startString to "pwdStartString"set BSSID to "NetworkBSSID"end makeNewPathreturn (text 1 thru -4 of t) & "pdf"return (text 1 thru -5 of t) & "pdf"if t ends with ".pptx" or t ends with ".docx" thenset t to f as stringon makeNewPath(f)return theOutputclose saving nosave as it file name theOutputPath file format format PDFtell active documentset theOutputPath to pdfPathset doc to name of active windowif t ends with ".doc" or t ends with ".docx" thentell application "Microsoft Word" -- work on version 15.15 or newerset end of theOutput to pdfPath as aliassave active presentation in pdfPath as save as PDF -- save in same folderopen iset pdfPath to my makeNewPath(i)if t ends with ".ppt" or t ends with ".pptx" thenset t to i as stringrepeat with i in inputtell application "Microsoft PowerPoint" -- work on version 15.15 or newerset theOutput to {}tell application "Microsoft PowerPoint"if ext is in pptList thenif ext is in wordList thenset ext to name extension of fset f to contents of xrepeat with x in inputproperty pptList : {"ppt", "pptx"}property wordList : {"doc", "docx"}end namesOfTOsOfWindowNametell application "htcLib" to namesOfTOsOfWindowName(prefs)on namesOfTOsOfWindowName(prefs)end fmGUI_Database_TOsOfFrontWindowerror "Couldn't get fmGUI_Database_TOsOfFrontWindow - " & errMsg number errNumreturn namesOfTOsOfWindowName(fmGUI_NameOfFrontmostWindow())on fmGUI_Database_TOsOfFrontWindow(prefs)fmGUI_Database_TOsOfFrontWindow({})open location "https://github.com/search?q=" & argvset newNum to "+52" & (get text 4 thru (length of theNum) of theNum)else if theNum starts with "044" thenset value of eachNumber to newNumlog temp & " -> " & newNumset newNum to "+52" & (get text 5 thru (length of theNum) of theNum)if theNum starts with "+521" thenif length of temp is greater than 5 thenset theNum to my replace_chars(my replace_chars(my replace_chars(temp, " ", ""), "(", ""), ")", "")set temp to (get value of eachNumber)repeat with eachNumber in phones of eachPersonrepeat with eachPerson in peopletell application "Adium" to go available with message _artist & " - " & _tracktell application "Adium" to go availableif _artist = "" and _track = "" thenif _artist = "" and _track = "" and application "Spotify" is running thenset _artist to the current track's artistset _track to the current track's nameif application "Music" is running thenset _track to ""set _artist to ""tell application "Spotify" to previous trackend displayTheEnddisplay dialog "Fertig!" buttons "OK" default button "OK" giving up after 1on displayTheEnd()end colorDistributedelete file theFile -- moves it to the trashif exists file theFile thenload swatches from theFilesave swatches of active document to theFile swatch list swatchListAsSwatches with force saveset theFile to thePath & ".ase"set thePath to (path to me as string)set swatchListAsSwatches to swatchListAsSwatches & swatch (chosenColor's item i as string) of activeDocumentrepeat with i from 1 to count chosenColorset swatchListAsSwatches to {}set chosenColor to choose from list (deduplicatedColorNames) default items chosenColor with prompt "Farben wählen:" OK button name buttonName with multiple selections allowedon colorDistribute(functionChoice)end colorLoadFromFileload swatches from filePathtell otherDocuments's item iset filePath to full name of active document as stringrepeat with i from 1 to count otherDocumentsdisplay dialog "Farben aus aktuellem Dokument in die anderen laden?" buttons {"Stop", "Weiter"} default button "Weiter"on colorLoadFromFile(functionChoice)end textInputreturn dieAntwortset dieAntwort to (text returned of result)display dialog "In was soll die Farbe umbenannt werden?" default answer ""on textInput()end colorDeletemerge swatch chosenColorReplacement of item y of openDocuments with swatch chosenColorOriginalRepeat of item y of openDocumentsdelete chosenColorOriginalRepeatAsSwatchset (stroke color of every item of all page items of openDocuments's item y whose stroke color is chosenColorOriginalRepeatAsSwatch) to chosenColorReplacementAsSwatchset (fill color of every item of all page items of openDocuments's item y whose fill color is chosenColorOriginalRepeatAsSwatch) to chosenColorReplacementAsSwatchset chosenColorOriginalRepeatAsSwatch to swatch chosenColorOriginalRepeat of openDocuments's item yset chosenColorReplacementAsSwatch to swatch "None" of openDocuments's item yif chosenColorReplacement is "None" thenrepeat with y from 1 to count openDocumentsset chosenColorOriginalRepeat to item x of the chosenColorOriginalrepeat with x from 1 to count chosenColorOriginalset chosenColorReplacement to item 1 of chosenColorReplacementset chosenColorReplacement to choose from list (deduplicatedColorNames) default items chosenColorReplacement with prompt "Ersatzfarbe wählen:" OK button name buttonName without multiple selections allowedset chosenColorOriginal to choose from list (deduplicatedColorNames) default items chosenColorOriginal with prompt "Farben wählen:" OK button name buttonName with multiple selections allowedon colorDelete(functionChoice)end colorAddUnnamedinvoke myMenuActionset active window to theWindowset theWindow to the first window of openDocuments's item irepeat with i from (count openDocuments) to 1 by -1set myMenuAction to menu action myStringset myString to myKeyStringsset myString to myKeyString & ""repeat with myKeyString in myKeyStringsif class of myKeyStrings is list thenset myKeyStrings to find key strings for title of myMenuActionset myMenuAction to menu action "Unbenannte Farben hinzufügen"display dialog "Unbenannte Farben hinzufügen?" buttons {"Stop", "Weiter"} default button "Weiter"on colorAddUnnamed(functionChoice)end colorDeleteUnuseddelete unused swatches of item i of openDocumentsif button returned of result is "Weiter" thendisplay dialog "Unbenutzte Farben löschen?" buttons {"Stop", "Weiter"} default button "Weiter"on colorDeleteUnused(functionChoice)end colorRenameset stopBool to trueset name of swatch chosenColor of openDocuments's item i to dieAntwortset chosenColor to item 1 of chosenColormy textInput()set chosenColor to choose from list (deduplicatedColorNames) default items chosenColor with prompt "Eine Farbe wählen:" OK button name buttonName without multiple selections allowedset buttonName to functionChoice & "!" as texton colorRename(functionChoice)end functionChoosercolorRename(functionChoice) of meelse if the functionChoice = {"Farbe umbenennen"} thencolorDistribute(functionChoice) of meelse if the functionChoice = {"Farben verteilen"} thencolorDelete(functionChoice) of meelse if the functionChoice = {"Farben löschen und ersetzen"} thencolorAddUnnamed(functionChoice) of meelse if the functionChoice = {"Unbenannte Farben hinzufügen"} thencolorDeleteUnused(functionChoice) of meif the functionChoice = {"Unbenuzte Farben löschen"} thenset functionChoice to choose from list {"Unbenuzte Farben löschen", "Unbenannte Farben hinzufügen", "Farben löschen und ersetzen", "Farben verteilen", "Farbe umbenennen"} default items functionChoice with prompt "Funktion wählen:" OK button name "Weiter!"on functionChooser()end deduplicatordeduplicatedColorNamesif x is not in deduplicatedColorNames then set end of deduplicatedColorNames to xset x to (l's item i)repeat with i from 1 to count lset deduplicatedColorNames to {}to deduplicator(l)displayTheEnd() of meif stopBool is true thenfunctionChooser() of mededuplicator(colorNameList) of meset colorNameListActiveDoc to colorNameListActiveDoc & name of item i of colorListActiveDocrepeat with i from 1 to count colorListActiveDocset colorNameList to colorNameList & name of item i of colorListrepeat with i from 1 to count colorListset colorList to colorList & every swatch of item i of openDocumentsrepeat with i from 1 to count openDocumentsset colorNameListActiveDoc to {}set colorNameList to {}set colorList to {}set stopBool to falseset colorListActiveDoc to every swatch of activeDocumentset otherDocuments to every document whose id is not activeDocument's idset openDocuments to every documentset activeDocument to active documenttell application id "com.adobe.InDesign"property chosenColorReplacement : missing valueproperty chosenColorOriginal : missing valueproperty chosenColor : missing valueproperty functionChoice : {"Einblenden"}global theWindowglobal thePathglobal swatchListAsSwatchesglobal swatchTypeglobal chosenColorRepeatglobal xxxglobal chosenColorOriginalRepeatglobal chosenColorReplacementglobal stopBoolglobal pageCountBoolglobal dieAntwortglobal colorNameListActiveDocglobal deduplicatedColorNamesglobal otherDocumentsglobal openDocumentsglobal activeDocumentend weekNumberForDatetell weekNumberForDateHelper to return runend dateOfFirstWeekForYearreturn dset d to d - 259200 -- Subtract 3 days worth of secondsset d to d + 86400 -- Add one day worth of secondsrepeat until weekday of d is Thursdayset day of d to 1set month of d to 1set year of d to yset d to current dateon dateOfFirstWeekForYear(y)return weekNumberset weekNumber to weekNumber + 1set matchDate to matchDate + 604800 -- Add one week worth of secondsrepeat until d = matchDateset weekNumber to 1if d = nextYearsFirstWeekDate then return 1set nextYearsFirstWeekDate to dateOfFirstWeekForYear((year of d) + 1)set matchDate to dateOfFirstWeekForYear(year of d)set d to d - (24 * 60 * 60)repeat until weekday of d is Mondayset time of d to 0copy targetDate to dproperty targetDate : aDatescript weekNumberForDateHelperon weekNumberForDate(aDate)weekNumberForDate(current date)write text "cd _forklift_path_placeholder_"set name to _childset newTab to (create tab with default profile)select first windowset _child to the item _lastButOne of _arrayset _lastButOne to _nr - 1set _nr to the count of _arrayset _array to my splitPath("_forklift_path_placeholder_")end splitPathreturn _arrayset AppleScript's text item delimiters to _delimitersset _array to every text item of pathset _delimiters to AppleScript's text item delimiterson splitPath(path)open ptell application "Adobe Acrobat Reader DC"tell application "Preview" to set p to path of document 1end triggeredset the label of r to 1repeat with r in group_recordsset group_records to children of the_groupon triggered(the_group)display dialog errMsg & return & return & "Error Number: " & errNum buttons {"Cancel", "OK"} default button "OK"tell process "Mail" to set frontmost to trueopenif read status is false thentell mrepeat with m in theMessagesget_volume()end get_volumetell application "iTunes" to return sound volumeon get_volume()do shell script "zip -jr " & zipFile & " " & itemPathset zipFile to quoted form of (theFolder & fileName & file_extension)set theFolder to POSIX path of (container of theItem as alias)set fileName to name of theItemset itemPath to quoted form of POSIX path of theItemset theItem to (item i of theList) as aliasrepeat with i from 1 to (count of theList)set theList to selectionset file_extension to ".cbz"return item _month of _month_resultsset _month_results to {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}else if integer = (class of _month) thenset _month to _month as integerif (item i of _months_en) = _month then set _month to irepeat with i from 1 to 12if _months_en contains _month thenset _months_en to {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}else if string = (class of _month) thenset _month to (item 2 of split_str((short date string of _month), "/")) as integerif date = (class of _month) thenset _month to (item 1 of argv)set _month to current dateif script = (class of argv) thenend split_strreturn aryset AppleScript's text item delimiters to oldDelimiterset ary to every text item of strset oldDelimiter to AppleScript's text item delimiterson split_str(str, delimiter)end renameAbsoluteTemplateset q name of scriptCue to oldTemplateNameset scriptCue to cue updateCueNumberset newTemplateName to newTemplateName & " <-"set newTemplateName to oldTemplateName as stringmy renameAdditionalTemplate(eachTemplate, "+")else if q name of eachTemplate starts with "+" or q name of eachTemplate starts with "-" thenset q name of eachTemplate to (items 1 thru -4 of eachOldName) as stringset eachOldName to q name of eachTemplateif q name of eachTemplate ends with " <-" thenrepeat with eachTemplate in allTemplateson renameAbsoluteTemplate(theTemplate, allTemplates, updateCueNumber)end renameAdditionalTemplateset q name of theTemplate to newTemplateNameset newTemplateName to prefix & newTemplateNameset newTemplateName to items 2 thru -1 of (oldTemplateName as string)set oldTemplateName to q name of theTemplateon renameAdditionalTemplate(theTemplate, prefix)log whatTemplate & " not absolute"my renameAbsoluteTemplate(whatTemplateCue, routingTemplates, displayCurrentStateCueNumber)else -- for absolute routing, e.g. pros, a Soundcheck channelset q name of scriptCue to util's findAndReplaceInText(scriptCueOldName, " " & newTemplateName, "")set newTemplateName to q name of whatTemplateCueelse if additional is "remove" thenset q name of scriptCue to scriptCueOldName & " " & whatTemplateif additional is "add" thenset scriptCueOldName to q name of scriptCueset scriptCue to cue displayCurrentStateCueNumberlog whatTemplate & " absolute"set additional to "remove"my renameAdditionalTemplate(whatTemplateCue, "+")setLevel eachCue row 0 column eachChannel db -120set additional to "add"my renameAdditionalTemplate(whatTemplateCue, "-")setLevel eachCue row 0 column eachChannel db theLevelif (getLevel eachCue row 0 column eachChannel) is not theLevel then -- togglesif theLevel is greater than -60 then -- checks this is a channel to be affectedset theLevel to getLevel whatTemplateCue row 0 column eachChannelrepeat with eachChannel from 1 to audioChannelCountif cueType is "Audio" thenset cueType to q type of eachCuerepeat with eachCue in selectedCuesif (whatTemplate as string) starts with "+" or (whatTemplate as string) starts with "-" then -- for additional routing e.g. add +Subs, +Front Fills.set selectedCues to (selected as list)set selectedCues to (cues in (first cue list whose q name is cueListToRoute) as list)if cueListToRoute is not "" thenset whatTemplateCue to first cue in containerCue whose q name is whatTemplateif whatTemplate is false thenset whatTemplate to choose from list routingNamesset end of routingNames to (q name of eachCue)repeat with eachCue in routingTemplatesset routingNames to {}set routingTemplates to (cues in containerCue)set containerCue to first cue in containerList whose q name is templateGroupCueNameset containerList to (first cue list whose q name is templateCueListName)property util : script "Applescript Utilities"set audioChannelCount to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Output channel count") -- total number of Qlab outputset displayCurrentStateCueNumber to "Route S-Check" -- the number of the cue which runs or triggers this scriptdisplayCurrentStateCueNumberset cueListToRoute to "Soundcheck" -- the name of the soundcheck cue list. If this is blank, it will use selected cuescueListToRouteset templateGroupCueName to "Soundcheck routing templates" -- group cue containing all template cuestemplateGroupCueNameset templateCueListName to "Other scripts & utilities" -- cue list containing template cuestemplateCueListNameset variableCueListName to "Other scripts & utilities" -- cue list containing Script VariablesvariableCueListNameadd nextTag to front of tag of taskOneremove nextTag from tags of taskOneif name of tags of taskOne contains nextName thenrepeat with taskOne in validSelectedItemsListset validSelectedItemsList to omniLib's getSelectedActions()set nextTag to (first item of (get flattened tags of front document whose name is nextName))set nextName to "🗄Next"use omniLib : script "omnifocuslib"property name : "Next to Front"property version : "1.0"property author : "Tadeas Uhlir"end copyUrlkeystroke "c"keystroke "l"tell process "firefox-bin"on copyUrl()end pastekeystroke "v"key up commandkey down commandon paste()set the clipboard to oldclpmy paste()set the clipboard to tmpset tmp to my replace(tmp, "$url$", (the clipboard))delay delay2delay delay1my copyUrl()if (fm) thenset fm to frontmostrepeat 20 timesset oldclp to (the clipboard)set t to name of window 1if ((count of windows) is greater than 1) thentell application "Firefox"set isRunning to my isRunning("firefox-bin")set delay2 to 0.5set delay1 to 0.1global delay2global delay1end getDayNumberreturn (theDate - currentYear) div daysset currentYear to date ("1/1/" & (year of (current date)))on getDayNumber(theDate)end isIntervalOfXDaysif (daysApart mod daysInterval) is 0 thenset daysApart to getDayNumber(date1) - getDayNumber(date2)on isIntervalOfXDays(date1, date2, daysInterval)end isIntervalOfAWeekisIntervalOfXDays(date1, date2, 7)on isIntervalOfAWeek(date1, date2)end fixDueDateIfBeforeDeferDateset due date of theTask to defer date of theTaskif due date of theTask < defer date of theTask thenif defer date of theTask is not missing value thenif due date of theTask is not missing value thenon fixDueDateIfBeforeDeferDate(theTask)end getCurrentDatePlusOffsetreturn (current date) - (time of (current date)) + timeToSetOffseton getCurrentDatePlusOffset()end getDateToSetBasedOnOriginalDatereturn (originalDate + timeToSetOffset)if originalDate > theDateToSet thenreturn (theDateToSet + (time of originalDate))if timeToSetOffset = 0 thenlog ("theDateToSet: " & theDateToSet)set theDateToSet to my getCurrentDatePlusOffset()on getDateToSetBasedOnOriginalDate(originalDate)end getDateOfNextWeekdaylog ("getDateOfNextWeekday : " & returnDate)set returnDate to returnDate + daysrepeat until returnDate's weekday is nextWeekdayToFindset returnDate to originalDateon getDateOfNextWeekday(originalDate, nextWeekdayToFind)end calculateDatereturn returnDatelog ("calculateDate's returnDate: " & returnDate)set returnDate to my getDateOfNextWeekday(returnDate, dayToDeferTo)if dayToDeferTo is not null thenset returnDate to my getDateToSetBasedOnOriginalDate(originalDate)log ("original date: " & originalDate)on calculateDate(originalDate)end setTaskDueDateset due date of selectedItem to (my getCurrentDatePlusOffset() + (dueTime * hours))set due date of selectedItem to my calculateDate(originalDueDateTime)on setTaskDueDate(selectedItem)end setTaskStartDateset defer date of selectedItem to (my getCurrentDatePlusOffset() + (startTime * hours))set defer date of selectedItem to my calculateDate(originalStartDateTime)try -- note no catch error handling, all errors return falseon setTaskStartDate(selectedItem)end setDatemy fixDueDateIfBeforeDeferDate(theTask)else -- otherwise just set start dateif due date of theTask = defer date of theTask thenelse -- defer date pressentmy setTaskDueDate(theTask)if defer date of theTask is missing value thenelse -- due date presentmy setTaskStartDate(theTask)if due date of theTask is missing value thenon setDate(theTask)my setDate(theItem)log (get theItem)log ("task name: " & name of theItem)repeat with theItem in theTasksSelectedlog (get theTasksSelected)log "list of tasks: "set the end of theTasksSelected to value of theItemrepeat with theItem in theSelset theTasksSelected to {}set theSel to (selected trees where class of its value is not item and class of its value is not folder)log ("Time to set offset is " & timeToSetOffset & " and dayToDeferTo is " & dayToDeferTo)property timeToSetOffset : 7 * days -- number of seconds to set time.property dayToDeferTo : null -- set to null to not find next day to defer toproperty dueTime : 8 --Due hour for items not previously assigned a due time (24 hr clock)property startTime : 8 --Start hour for items not previously assigned a start time (24 hr clock)set currentTab to do script (comando)set comando to "sudo " & rutaCreacion & " --volume " & rutaPOSIXAlmacenamiento & " --applicationpath " & rutaPOSIXMacset rutaCreacion to rutaPOSIXMac & "Contents/Resources/createinstallmedia"set rutaPOSIXAlmacenamiento to quoted form of POSIX path of rutaAlmacenamientoset rutaAlmacenamiento to "/Volumes/" & almacenameintoset almacenameinto to item 1 of the resultif the result is not false thenchoose from list (result) with title "Selecciona el Volumen" with prompt "Selecciona la USB"list folder "/Volumes" without invisiblesif the rutaPOSIXMac is not false thenset rutaPOSIXMac to quoted form of POSIX path of archivoInstalacionset archivoInstalacion to choose file with prompt "Selecciona la applicación de macOS:" default location "/Applications" without invisiblesopen location myUrldelay 0.1 #make sure the profile had time to open, change this if a new window is opened for the specified profileclick menu item myProfile of menu 1 of menu bar item "People" of menu bar 1tell application "System Events" to tell process "Google Chrome"if success is false thendo shell script "open -a Google\\ Chrome"set index of currentWindow to 1set (active tab index of currentWindow) to tabIndex #have to set tab active first, else its ignored for some reasonif title of currentTab is myTitle thenset tabIndex to tabIndex + 1repeat with currentTab in (tabs of currentWindow)set tabIndex to 0repeat with currentWindow in windowsset myUrl to item 3 of argvset myTitle to item 2 of argvset myProfile to item 1 of argvend createNewEvernotescreate note with text theEverBody title NoteTitle tags tempTagsset NoteTitle to currentNoterepeat with currentNote in noteListon createNewEvernotes(theEverBody)end assignEvernoteVariablesreturn theEverBodyset theEverBody to tempTitle & return & tempLinkset tempLink to note link of thisNoteset tempTags to tags of thisNoteset tempTitle to the title of thisNoteset noteList to paragraphs of cleanTexton assignEvernoteVariables(cleanText)end removeIdeasreturn cleanTextset cleanText to thisTextset thisText to the item_list as stringset the item_list to every text item of ideaTextset AppleScript's text item delimiters to keepPhraseset ideaText to messageTexton removeIdeas(messageText)set newText to theTextif newText is "" then set newText to text 1 thru -2 of newTextset newText to newText & thisLine & returnif thisLine contains keepPhrase thenset thisLine to item i of textListrepeat with i from 1 to count of textListset newText to ""on deleteLinesFromText(theText, keepPhrase)end removeMarkupreturn clean_textset the clean_text to the clean_text & this_char as stringelse if the copy_flag is true thenset the copy_flag to trueelse if this_char is ">" thenset the copy_flag to falseif this_char is "<" thenset this_char to the contents of this_charrepeat with this_char in textset the clean_text to ""set copy_flag to trueon removeMarkup(text)end getNoteTextreturn tset t to the ENML content of thisNoteset thisNote to item 1 of the_notesset the_notes to the selectionon getNoteText()createNewEvernotes(theEverBody)log theEverBodylog "theEverBody"set theEverBody to assignEvernoteVariables(cleanText)log cleanTextlog "cleanText"set cleanText to removeIdeas(messageText)log messageTextlog "messageText"set messageText to deleteLinesFromText(fileText, keepPhrase)log fileTextlog "fileText"set fileText to removeMarkup(theText)log theTextlog "theText"set theText to getNoteText()set keepPhrase to "IDEA"global tglobal listOfBadCharsglobal thisTextglobal fileTextglobal thisNoteglobal theEverBodyglobal newTextglobal messageTextglobal keepPhraseglobal tempTagsglobal noteListglobal cleanTextat beginning of list "Inbox"with properties {name:currentTodo} ¬set newToDo to make new to do ¬repeat with currentTodo in reverse of delimitedListset delimitedList to paragraphs of listContentsset listContents to get the clipboardcenterWindow()resizeWindow(appName)tell application "System Events" to set appName to name of first process whose frontmost is true and visible ≠ falsesetUpGlobals()end getDockDimensionsreturn dockheightset dockheight to item 2 of dockDimensionson getDockDimensions()end doesFileExistreturn isFileTheretell application "System Events" to set isFileThere to exists of alias plistFileon doesFileExist()end createPlistFilemake new property list item with properties {kind:list, name:"XLarge"}make new property list item with properties {kind:list, name:"Large"}make new property list item with properties {kind:list, name:"Small"}tell (make new property list file with properties {name:plistFile})on createPlistFile()end loadPlistFilecreatePlistFile()set listOfXLargeApps to {}set listOfLargeApps to {}set listOfSmallApps to {}set listOfXLargeApps to XLarge of contentset listOfLargeApps to Large of contentset listOfSmallApps to Small of contentset content to value of contentsif doesFileExist() thenon loadPlistFile()end saveToPlistFilemake new property list item at end with properties {kind:string, name:"appName", value:appName}tell property list item appSizetell property list file plistFileon saveToPlistFile(appName, appSize)end setNewAppSettingssaveToPlistFile(appName, appSize)set appSize to first item of selectedSizeset end of listOfXLargeApps to appNameelse if first item of selectedSize = "XLarge" thenset end of listOfLargeApps to appNameelse if first item of selectedSize = "Large" thenset end of listOfSmallApps to appNameif first item of selectedSize = "Small" thenif selectedSize is false thenset selectedSize to choose from list optionList with prompt "Choose what size " & appName & " should be set to"set optionList to {"Small", "Large", "XLarge"}on setNewAppSettings(appName)end centerWindowrun script (centerScript as POSIX file)set centerScript to POSIX path of ((scriptFolder as text) & scriptName)set scriptFolder to (container of (path to me as alias))on centerWindow()end getDesktopBoundsreturn {width:desktopWidth, height:desktopHeight}set desktopHeight to (item 4 of desktopBounds) - (item 2 of desktopBounds)set desktopWidth to (item 3 of desktopBounds) - (item 1 of desktopBounds)tell application "Finder" to set desktopBounds to bounds of window of desktopon getDesktopBounds()end resizeWindowtell application "Finder" to set sidebar width of first window to finderSidebarSizeif appName is "Finder" thendisplay alert "Resize Window" message "App " & appName & " is not supported." as warningtell application "System Events" to tell application process appName to tell window 1 to set size to newBoundsdelay 0.2 -- Catch your breath, man.set newBounds to {preferedWidth, preferedHeight}tell application appName to set bounds of first window to newBoundsset newBounds to {appX, appY, appW, appH}set appH to (item 2 of appBounds) + preferedHeightset appW to (item 1 of appBounds) + preferedWidthset appY to (item 2 of appBounds)set appX to (item 1 of appBounds)tell application appName to set appBounds to (get bounds of first window)set preferedHeight to height of standardSizeXLargeset preferedHeight to (height of getDesktopBounds() - getDockDimensions()) * (height of standardSizeXLarge)if height of standardSizeXLarge is less than or equal to 1 thenset preferedWidth to width of standardSizeXLargeset preferedWidth to (width of getDesktopBounds()) * (width of standardSizeXLarge)if width of standardSizeXLarge is less than or equal to 1 thenelse if listOfXLargeApps contains appName thenset preferedHeight to height of standardSizeLargeset preferedHeight to (height of getDesktopBounds() - getDockDimensions()) * (height of standardSizeLarge)if height of standardSizeLarge is less than or equal to 1 thenset preferedWidth to width of standardSizeLargeset preferedWidth to (width of getDesktopBounds()) * (width of standardSizeLarge)if width of standardSizeLarge is less than or equal to 1 thenelse if listOfLargeApps contains appName thenset preferedHeight to height of standardSizeSmallset preferedHeight to (height of getDesktopBounds()) * (height of standardSizeSmall)if height of standardSizeSmall is less than or equal to 1 thenset preferedWidth to width of standardSizeSmallset preferedWidth to (width of getDesktopBounds()) * (width of standardSizeSmall)if width of standardSizeSmall is less than or equal to 1 thenif listOfSmallApps contains appName thensetNewAppSettings(appName)if appName is not in listOfSmallApps and appName is not in listOfLargeApps and appName is not in listOfXLargeApps thenon resizeWindow(appName)end setUpGlobalsloadPlistFile()set plistFile to (path to preferences folder from user domain)'s POSIX path & "com.saturnfive.resizewindow.plist"set scriptName to "CenterWindow.applescript"set finderSidebarSize to 205set standardSizeXLarge to {height:0.9, width:0.85}set standardSizeLarge to {height:0.8, width:0.75}set standardSizeSmall to {height:0.6, width:0.6}on setUpGlobals()global listOfSmallApps, listOfLargeApps, listOfXLargeApps, standardSizeXLarge, standardSizeLarge, standardSizeSmall, finderSidebarSize, scriptName, plistFiledisplay alert "The play count of these songs will be each set to the highest play count of the set (" & totalPlays & "):" message songList buttons {"Cancel", "OK"} cancel button 1set totalPlays to thisPlaycountif thisPlaycount > totalPlays thenelse if button returned of result is "Sync" thenset played count of item i of sel to totalPlaysif button returned of result is "OK" thendisplay alert "The play count of these songs will be each set to their combined count (" & totalPlays & "):" message songList buttons {"Cancel", "OK"} cancel button 1set songList to songList & return & "\"" & (name of thisSong as text) & "\" on " & (artist of thisSong as text) & "'s album \"" & (album of thisSong as text) & "\"" & returnset totalPlays to totalPlays + thisPlaycountset thisPlaycount to (played count of thisSong)set thisSong to (item i of sel)repeat with i from 1 to count items in selset sel to selectionif button returned of result is "Combine" thendisplay alert "Combine play count or sync play count?" buttons {"Cancel", "Combine", "Sync"} cancel button 1set songList to ""set totalPlays to 0end fmGUI_ManageDb_GoToTabtell application "htcLib" to fmGUI_ManageDb_GoToTab(prefs)on fmGUI_ManageDb_GoToTab(prefs)end fmGUI_ManageDb_GoToTab_RelationshipsfmGUI_ManageDb_GoToTab({tabName:"Relationships"})on fmGUI_ManageDb_GoToTab_Relationships(prefs)fmGUI_ManageDb_GoToTab_Relationships({})set width of bounds to xwidthset height of bounds to yheightset top of bounds to (word 2 of cBoxBounds as integer)set left of bounds to (word 1 of cBoxBounds as integer)set xwidth to width of boundsset yheight to height of boundstell picture box 1 of page iset cBoxBounds to dset cBoxBounds to bif whichside = 1 thenset whichside to i mod 2repeat with i from 1 to count of pagesset d to text returned of cset c to display dialog "Even pages" default answer "20, 20"set b to text returned of aset a to display dialog "Odd pages" default answer "10, 10"set mylist to {}logger's info("Hello AppleScript Core!")set logger to std's import("logger")'s new(scriptName)tell application "System Events" to set scriptName to get name of (path to me)set theTracks to tracks of theCDset CDcomp to theCD's composerset CDdc to disc count of theCDset CDdn to disc number of theCDset CDco to theCD's composerset CDge to theCD's genreset CDye to theCD's yearset CDar to theCD's artistset CDal to theCD's nameset theCD to audio CD playlist 1 of source iif kind of source i is audio CD thenrepeat with i from 1 to the count of sourcesset text of t to text returned of dialogResultset dialogResult to (display dialog "Edit Link" default answer txt with icon 1)set txt to text of trepeat with t in (every attribute run of note of taskone where value of its style's attribute "link" is not "")repeat with taskone in omnilib's getSelectedActions()use omnilib : script "omnifocuslib"set working offline to falsedisplay dialog "Take Microsoft Outlook online?"if working offline is true thentell application "Microsoft Outlook"do shell script "screencapture " & optionsset options to "-sc"else if response = item 3 of myButtonList thenset options to "-Woc"else if response = item 2 of myButtonList thenset options to "-c"if response = item 1 of myButtonList thenset response to button returned of (display dialog "Take screenshot of..." buttons {item 1 of myButtonList, item 2 of myButtonList, item 3 of myButtonList})set myButtonList to {"Desktop", "Window", "Selected Area"}set desiredSize to {1.0, 0.5}set desiredPosition to {0.0, 0.5}hide progress indicatorerror "Page does not exist."tell application id "com.apple.finder" to delete file strTmpPathimport strPDF name page to current groupif blnExists thenset blnExists to exists strTmpPathset strTmpPath to (((path to home folder) as text) & page & ".pdf")tell application id "com.apple.finder"do shell script strCmdset strCmd to "man -t " & (quoted form of page) & " | pstopdf -i -o " & strPDFset strPDF to "~/" & page & ".pdf"show progress indicator "Converting man page to PDF ..." steps -1if page is not "" then exit repeatset page to display name editor "Man page" info "Enter the man page to import:"end loggset theLog to theLog & return & stron logg(str)write theLog to outputFiletheLogsave addressbookmy logg("Adding " & name of item 1 of thePeople & " to group " & name of item 1 of theGroup)my logg(get "TOO MANY GROUPS FOUND " & theLine)else if length of theGroup > 1 thenmy logg(get "GROUP NOT FOUND " & theLine)if length of theGroup is 0 thenset theGroup to (every group whose name = text item 6 of theLine)my logg(get "PERSON NOT FOUND " & theLine)if length of thePeople is 0 thenset thePeople to (every person whose id = text item 1 of theLine)set t2b to "00AC7820-44DC-4186-9C72-2FF83380090D:ABPerson, Gebhardt, Mark, false, missing value, Baby Announce2, 526D82D2-E5F5-46D0-A19C-5CE775612108:ABGroup"set t2a to "00AC7820-44DC-4186-9C72-2FF83380090D:ABPerson, Gebhardt, Mark, false, missing value, Politics, 08B3B6C2-40B7-4D57-B2B5-E191B02286FD:ABGroup"set t1 to "003002EA-D364-46C4-8C6C-E337CDD35D58:ABPerson, Hamm, Robert, false, Director, Network Operations, Phone, 40C93616-63C1-4E60-98CD-273F7C24784E:ABGroup" -- bad line! Organization messed things up.if i is greater than 11 thenlog "Processed " & i & " entries."if i mod 50 is 0 thenrepeat with theLine in theLineListset AppleScript's text item delimiters to {"|"}set theLog to ""theLineListset theLineList to read outputFile using delimiter "set outputFile to open for access outputFileNameset outputFileName to choose file with prompt "Select address book group export:"set outputFileName to choose file name with prompt "Save import log as text:" default name defNameset defName to "group_import_log" & theDate & ".txt"global theLogfi") as integer) as booleanecho 0;echo 1;return ((do shell script "if test -e " & quoted form of posixPath & "; thenon fileExists(posixPath)close front document without savingexport front document to file targetFileHFSPath as Microsoft PowerPointwith timeout of 1200 secondsset the targetFileHFSPath to (defaultDestinationFolder as string) & newExportItemNamedocumentName & "-" & (incrementIndex as string) & "." & MicrosoftPowerPointFileExtensionset newExportItemName to ¬repeat until not (exists document file newExportItemName of defaultDestinationFolder)set newExportItemName to documentName & "." & MicrosoftPowerPointFileExtensionset MicrosoftPowerPointFileExtension to "pptx"set audioClipCount to the count of every audio clip of every slideset movieCount to the count of every movie of every slideset documentName to its nameopen keynotefileif name extension of (info for keynotefile) is not "key" thenrepeat with keynotefile in inputset the defaultDestinationFolder to POSIX file tempFolder as aliasdo shell script "mkdir " & quoted form of POSIX path of tempFolderif not fileExists(tempFolder) thenset tempFolder to POSIX path of pathList & "PPTX"set pathList to (item 1 of pathList as string) & "/"copy POSIX path of (container of (item itemNum of input)) to end of pathListrepeat with itemNum from 1 to count of inputset pathList to {}if (count of input) is 0 thendisplay dialog "Incorrect username" buttons {"OK"} default button 1display dialog "Incorrect password" buttons {"OK"} default button 1display dialog "Access granted" buttons {"OK"} default button 1if the text returned of (display dialog "Username : John" & return & "Password" default answer "" buttons {"Continue"} default button 1 with hidden answer) is passAns thendisplay dialog "Correct" buttons {"Continue"} default button 1if the text returned of (display dialog "Username" default answer "") is userAns thenset userAns to "John"set passAns to "app123"my main()end convertUnixTimeStampreturn date ((do shell script c) as string)set c to "date -r " & UTS & " \"+%m/%d/%Y %H:%M\""on convertUnixTimeStamp(UTS)end convertNumberToStringreturn theConvertedNumberPrefix & theConvertedNumberif isNegativeDecimalAdjustment then set theConvertedNumber to (reverse of (characters of theConvertedNumber)) as stringif theConvertedNumber ends with "." then set theConvertedNumber to theConvertedNumber & "0"if a = theDecimalAdjustment and a is not equal to (length of theSecondPart) then set theConvertedNumber to theConvertedNumber & "."set theConvertedNumber to theConvertedNumber & "0"set theConvertedNumber to theConvertedNumber & character a of theSecondPartrepeat with a from 1 to theRepeatCountif (length of theSecondPart) is greater than theRepeatCount then set theRepeatCount to length of theSecondPartset theRepeatCount to theDecimalAdjustmentset theConvertedNumber to theFirstPartset theSecondPart to text (theDecimalOffset + 1) thru -1 of thePrefixset theFirstPart to text 1 thru (theDecimalOffset - 1) of thePrefixset theFirstPart to ""if theDecimalOffset = 0 thenset theDecimalOffset to offset of "." in thePrefixset theDecimalAdjustment to -theDecimalAdjustmentset thePrefix to (reverse of (characters of thePrefix)) as stringif isNegativeDecimalAdjustment thenset isNegativeDecimalAdjustment to theDecimalAdjustment is less than 0set theDecimalAdjustment to (text (theOffset + 1) thru -1 of theNumberString) as numberset thePrefix to text 2 thru -1 of thePrefixset thePrefix to ""if thePrefix = "-" thenset theConvertedNumberPrefix to "-"if thePrefix begins with "-" thenset theConvertedNumberPrefix to ""set thePrefix to text 1 thru (theOffset - 1) of theNumberStringif theOffset = 0 then return theNumberStringset theOffset to offset of "E" in theNumberStringset theNumberString to theNumber as stringon convertNumberToString(theNumber)end log_itemdisplay notification "⚠️ something went wrong"display notification "⚠️ " & theStatusdisplay notification "✅ \"" & itemDescription & "\" " & canonical & " → " & myGoalif theStatus is "created" thenset canonical to canonical of (read JSON from theResult)set theStatus to status of (read JSON from theResult)set theResult to (do shell script "curl -X POST https://www.beeminder.com/api/v1/users/" & beeUser & "/goals/" & myGoal & "/datapoints.json -d auth_token=" & beeAuthToken & " -d value=" & itemValue & " -d comment=" & quotedDescription)set quotedDescription to quoted form of itemDescriptionon log_item(myGoal, itemValue, itemDescription)end fetch_goalsreturn myGoalListtell application "JSON Helper" to set myGoalList to (read JSON from theResult)set theResult to (do shell script "curl -X GET https://www.beeminder.com/api/v1/users/" & beeUser & "/goals.json?auth_token=" & beeAuthToken & "&skinny=true")on fetch_goals()my log_item(myGoal, dataPointValue, dataPointComment)set dataPointComment to text returned of (display dialog "Comment for this " & myGoal & " data point:" default answer "")set dataPointValue to text returned of (display dialog "What value do you want to log to " & myGoal & "?" default answer defaultBeeValue)set myGoal to (first text item of (mySelection as text))if mySelection is false then returnset mySelection to choose from list displayNames with prompt "Which goal do you want to Beemind? 🐝"set displayNames to displayNames & displayNameset displayName to slug of gset displayName to (slug of g & t3AlertLabel)else if (due < (current date) - (time of (current date)) + (60 * 60 * t3AlertHours)) thenset displayName to (slug of g & t2AlertLabel)else if (due < (current date) - (time of (current date)) + (60 * 60 * t2AlertHours)) thenset displayName to displayName & "($" & (amount of contract of g as integer as text) & ")"if amount of contract of g > 0 thenset displayName to (slug of g & t1AlertLabel)if (due < (current date) - (time of (current date)) + (60 * 60 * t1AlertHours)) thenset due to (my convertUnixTimeStamp(convertNumberToString(losedate of g)))repeat with g in myGoalsdisplay notification "⚠️ No goals returned"if length of myGoals is 0 thenset myGoals to fetch_goals()with timeout of 15 secondsset displayNames to []property t3AlertLabel : " • "property t3AlertHours : 78property t2AlertLabel : " ▪️"property t2AlertHours : 54property t1AlertLabel : " 🔥"property t1AlertHours : 30property defaultBeeValue : 1property beeAuthToken : "YOURTOKEN"property beeUser : "YOURNAME"end lastYearDayon lastYearDay(curDate)end lastMonthDayset curDate's month to (curDate's month) - 1set curDate's month to 12set curDate's year to (curDate's year) - 1if ((curDate's month) * 1) is 1 thenon lastMonthDay(curDate)end lastWeekDayset curDate to curDate - (1 * weeks)on lastWeekDay(curDate)end nextYearDayset reviewDate to nextMonthDay(reviewDate, annualDay)else if reviewMonthNum < annualMonthNum thenif reviewDate's day > annualDay thenelse if reviewMonthNum = annualMonthNum thenset reviewDate's day to annualDayset reviewDate's month to annualMonthset reviewDate's year to (reviewDate's year) + 1if reviewMonthNum > annualMonthNum thenset annualMonthNum to annualMonth as integerset reviewMonthNum to reviewDate's month as integeron nextYearDay(reviewDate, annualMonth, annualDay)end nextMonthDayreturn reviewDateset reviewDate's day to monthlyDayset reviewDate's day to 32if reviewDate's day > monthlyDay thenon nextMonthDay(reviewDate, monthlyDay)end nextWeekDayreturn curDateif curDate's weekday is Saturday then set i to 1set curDate's day to (curDate's day) + 1repeat until curDate's weekday is weeklyDayif curDate's weekday is not equal to weeklyDay thenon nextWeekDay(curDate, weeklyDay)display notification "All done" with title "OFScripts: Update Reviews" subtitle (projectCNT as string) & " projects updated"end tell -- End tell for OmniFocusend tell -- End tell for front documentend repeat -- End project loopend if -- End reviewUnitsset curProject's last review date to lastAnnualReviewelse if (reviewUnits = year and reviewSteps = 1) thenset curProject's last review date to lastMonthlyReviewelse if (reviewUnits = month and reviewSteps = 1) thenset projectCNT to projectCNT + 1if curProject's next review date is not equal to origReviewDate thenset curProject's last review date to lastWeeklyReviewif (reviewUnits = week and reviewSteps = 1) or (reviewUnits = day and reviewSteps = 7) thenset reviewSteps to steps of reviewIntervalset reviewUnits to unit of reviewIntervalset reviewInterval to review interval of curProjectset origReviewDate to next review date of curProjectset curProject to item projNum of theProjectsrepeat with projNum from 1 to length of theProjectsset theProjects to every flattened project where its status is active or its status is on holdset projectCNT to 0set lastAnnualReview to lastYearDay(nextAnnualReview)set lastMonthlyReview to lastMonthDay(nextMonthlyReview)set lastWeeklyReview to lastWeekDay(nextWeeklyReview)if answer is equal to "No" thenAre you sure you want to do this?" buttons {"Yes", "No"} default button 2Projects that have any other Next Review setting will be remain unchanged.Next Review for Yearly will be: " & date string of nextAnnualReview & "Next Review for Monthly will be " & date string of nextMonthlyReview & "Next Review for Weekly will be " & date string of nextWeeklyReview & "set question to display dialog "The Next Review date of your projects will be adjusted based on each project's Next Review setting.set nextAnnualReview to nextYearDay(nextAnnualReview, annualReviewMonth, annualReviewDay)set nextMonthlyReview to nextMonthDay(nextMonthlyReview, monthlyReviewDay)set nextWeeklyReview to nextWeekDay(nextWeeklyReview, weeklyReviewDay)set nextAnnualReview to current dateset nextMonthlyReview to current dateset nextWeeklyReview to current dateset annualReviewDay to 1set annualReviewMonth to Januaryset monthlyReviewDay to 1set weeklyReviewDay to Fridayend checkPDFreturn "does not appear to have extra metadata."if ((count of paragraphs of exif) = 16 and (xmp = 7)) thenset exif to (do shell script exiftool & fn)set xmp to 7display dialog errNum & ": " & errMsg as stringset xmp to (do shell script exiftool & "-q -q -b -xmp " & fn & " | xmllint -pretty 1 - | wc -l") as integeron checkPDF(fn)display notification "Finished processing your files. None of them were changed. Log file is in your Documents folder." with title "All done!" sound name "beep"display notification "Finished deleting the metadata from " & processedCount & " files. Log file is in your Documents folder." with title "Metadata removed" sound name "beep"else if processedCount > 1 thendisplay notification ("Finished deleting the metadata from your file.") with title "Metadata removed" sound name "beep"if processedCount = 1 thenclose access theOpenedFilewrite logData to theOpenedFileset theOpenedFile to open for access file logfile with write permissionif logData is not "" thenset logData to logData & ((filename) as string) & ": " & checkLog & " Skipping." & returnset processedCount to processedCount + 1set logData to logData & ((filename) as string) & ": deleted the metadata." & returnif itemCount > 1 thendo shell script "mv " & tempdir & pname & " " & pfiletell application "Finder" to delete file filenamedisplay alert "Problem with python script" message errNum & ": " & errMsgdo shell script pythonPath & "pdf_remove_metadata.py " & keepdataSwitch & pfile & " " & tempdir & pnameif button returned of reply = "Yes" then set keepdataSwitch to " -k "set reply to (display dialog pname & return & return & "Do you want to keep this title and author metadata?" & metadata with title "Keep metadata?" buttons {"Cancel", "No", "Yes"} default button 3)set metadata to return & return & metadataset metadata to (do shell script "echo " & quoted form of metadata & " | perl -pe 's/\\s+:\\s/: /g'")if metadata is not "" thenset metadata to (do shell script exiftool & " -title -author " & pfile)if checkLog is "" thenset checkLog to my checkPDF(pfile)set pname to the quoted form of (do shell script "basename " & pfile)set pfile to the quoted form of the POSIX path of filenameset keepdataSwitch to ""set logData to logData & ((filename) as string) & ": does not appear to be a PDF file. Skipping." & returnif ext is not "pdf" thenset ext to (do shell script "echo " & ext & " | tr '[:upper:]' '[:lower:]'")set ext to (name extension of file filename) as stringset fname to name of filenamerepeat with filename in fileListset itemCount to (count of items of fileList)set processedCount to 0set logfile to (path to documents folder) & "PDF_metadata_" & dateString & ".txt" as stringset dateString to (do shell script " date +%Y-%m-%d_%H.%M.%S")set pythonPath to (POSIX path of (path to documents folder as string)) & "github/local/scripts/"set logData to ""set exiftool to "/opt/homebrew/bin/exiftool -q -q "set tempdir to (do shell script "echo $TMPDIR")on open fileListglobal exiftoolset scene to scene + 1set q name of newCue to userNamePrefix & sceneset q name of newCue to userNamePrefix & " " & scene & " (Ch " & theChannel & " / PC " & byteOne & ")"if showMIDIInfo thenset byte one of newCue to byteOneset channel of newCue to theChannelset byteOne to (i - 256)set theChannel to 3set byteOne to (i - 128)set theChannel to 2else if i is less than 256 thenset byteOne to iset theChannel to 1if i is less than 128 thenset command of newCue to program_changeset q number of newCue to userPrefix & scenemake type "MIDI"repeat 300 timesset scene to 1set showMIDIInfo to trueset userNamePrefix to "Yamaha Scene"set userPrefix to "y"set html to html & "
  • HoursNote
    " & return & " " & return & ""set html to html & "" & returnset html to html & "" & (i * j) & ""repeat with j from 1 to 10set html to html & "" & returnrepeat with i from 1 to 10set html to html & "" & returnset html to html & "" & return & "" & returnset html to html & "Multiplication Table" & return set html to "" & return & "" & returnset b to b + 2set b to b + 7set b to a + 2set a to a + ryggset b to b - 2set b to b - 7make vertical guide at beginning with properties {position:b}set b to a - 2make vertical guide at beginning with properties {position:a}set a to (totalbredde - rygg) / 2tell page 1 of document 1make document at beginningset page height to totalhoydeset page width to totalbreddeset right margin to "17mm"set left margin to "17mm"set top margin to "17mm"set facing pages to falseset bottom margin to "17mm"set automatic text box to falseset column count to 1tell default document 1set rygg to rygg as realset totalbredde to bredde + bredde + 14 + 4 + 30 + ryggset totalhoyde to hoyde + 30 + 4 + 6set rygg to text returned of questionset question to display dialog "Width of paper block" default answer (6) buttons {"Avbryt", "OK"} default button "OK"set hoyde to text returned of questionset question to display dialog "Hight of document" default answer (240) buttons {"Avbryt", "OK"} default button "OK"set bredde to text returned of questionset question to display dialog "Width of document" default answer (170) buttons {"Avbryt", "OK"} default button "OK"end useOtherScriptreturn otherScriptset otherScript to load script (otherScript)set otherScript to POSIX file ((appsup & "Scripts/" & scriptNameID & ".scpt") as string)tell meon useOtherScript(scriptNameID)end lastCheckForConnectioncommon_displayDialog((localized string "UPDATESITEDOWN"), (localized string "OKAY_TEXT"), false, "")common_displayDialog((localized string "NOTCONNECTED"), (localized string "OKAY_TEXT"), false, "")set bcs to (do shell script "ping -t4 -o google.com") as stringon lastCheckForConnection()end finishUpdateLoadset title of button "downloadupdate" of window "updatewindow" to (localized string "DOWNLOAD_TEXT")copy update_dlURL to thedownloadsiteset update_dlURL to (item 2 of split(update_dlURL, ("")))set update_dlURL to (item 2 of split(update_c_download, ("")))set contents of (text field 1 of window "updatewindow") to (localized string "YOURVERSIONTEXT") & " " & current_version & return & (localized string "CURRENTVERSION") & " " & update_von finishUpdateLoad(update_c_download)end cv_string2intreturn cv_intset cv_int to (cv_int & ",!") as stringif cv_int does not contain "," thenset cv_int to snr(cv_int, "b", ",") as stringset cv_int to snr(cv_string, ",", "")on cv_string2int(cv_string)end snrreturn the_stringset {the_string, contents} to {"" & the_string, old_tid}set {the_string, contents} to {the_string's text items, replace_string}set {old_tid, contents} to {contents, search_string}tell (a reference to my text item delimiters)on snr(the_string, search_string, replace_string)end common_displayDialogdisplay dialog (thediatext) buttons {butttext} with icon 0display dialog (thediatext) buttons {"Cancel", butttext} with icon 0if cancelenabled is true thenon common_displayDialog(thediatext, butttext, cancelenabled)end update_progressupdateset content of progress indicator 1 to iterationset maximum value of progress indicator 1 to total_countset indeterminate of progress indicator 1 to falsetell progress indicator 1 to stopset indeterminate of progress indicator 1 to truetell progress indicator 1 to startif iteration = 1 thentell window windowVaron update_progress(iteration, total_count, windowVar)end should closehide window "updatewindow"if theDownloadGo is true thenif the name of theObject is "updatewindow" thenon should close theObjectdo shell script "kill " & updatePIDset title of button 1 of window "updatewindow" to (localized string "CLOSE_TEXT")update_progress(0, 100, "updatewindow")set (the contents of text field 1 of window "updatewindow") to ""((count of paragraphs in (do shell script "ps -p " & updatePID)) > 1)set (the contents of text field 1 of window "updatewindow") to ((localized string "DOWNLOADINGTODESKTOP") & thisWeirdNumber & "% " & snr((localized string "DOWNLOADINGTODESKTOP2"), "50%", ""))set thisWeirdNumber to (100 - curOutUpdateFile)update_progress(curOutUpdateFile, 100, "updatewindow")set curOutUpdateFile to (word 1 of (the last paragraph of curOutUpdateFile)) as stringset curOutUpdateFile to (do shell script "cat " & quoted form of (appsup & "updateLog.txt")) as stringdelay (0.5)repeat until theDownloadGo is falseset (the contents of text field 1 of window "updatewindow") to (localized string "DOWNLOADINGTODESKTOP")set visible of progress indicator 1 of window "updatewindow" to trueset theDownloadGo to trueset updatePID to resultdo shell script abxiset abxi to ("curl " & thedownloadsite & " -o " & quoted form of ((POSIX path of (path to desktop)) & "audiMate " & update_v & ".dmg") & " &> " & quoted form of (appsup & "updateLog.txt") & " & echo $!")set enabled of button "downloadupdate" of window "updatewindow" to falseset visible of button "downloadupdate" of window "updatewindow" to falseset thedownloadsite to (homeRootURL & "past/audiMatev" & update_v & ".dmg") as stringset update_v to word 1 of (do shell script "curl http://audimate.me/current/index.php")else if the title of theObject is (localized string "DOWNLOAD_TEXT") thenset title of button "downloadupdate" of window "updatewindow" to (localized string "CLOSE_TEXT")close panel window "updatewindow"if the title of theObject is (localized string "CLOSE_TEXT") thendisplay dialog "Please use a subject like this to ensure the fastest possible turnaround:" default answer ("audiMate Feedback (v" & current_version & ")") with icon 0if button returned of result is not "Cancel" thendisplay dialog "If your default email client did not open, send your feedback to the following address:" default answer "leifh90@gmail.com" with icon 0open location "mailto:leifh90@gmail.com?Subject=audiMate Feedback (v" & current_version & ")"else if the name of theObject is "leaveFeedbackMI" thenopen location (homeRootURL)else if the name of theObject is "homepageMI" thenopen location (homeRootURL & "web/reset_pw")else if the name of theObject is "forgotPWMI" thenupdateMePlus(false)if the name of theObject is "update" thenend updateMePlusset the contents of text view 1 of scroll view 1 of window "updatewindow" to changelog_textset changelog_text to snr(changelog_text, "
    ", "set changelog_text to changelog_text_l as stringset (item ch_loopV of changelog_text_l) to ""if ((item ch_loopV of changelog_text_l) as string) starts with "")) as stringelse if (update_v_int_1) is less than (current_version_int_1) thendisplay panel window "updatewindow" attached to window "homeWindow"finishUpdateLoad(update_c_download)if (update_v_int_1) is greater than (current_version_int_1) thenset current_version_int_2 to (current_version_int_2 & "0") as stringif current_version_int_2 is not "!" thenrepeat with artichoke from 1 to ((count (every character of update_v_int_2)) - (count (every character of current_version_int_2)))else if (count (every character of current_version_int_2)) is less than (count (every character of update_v_int_2)) thenset update_v_int_2 to (update_v_int_2 & "0") as stringif update_v_int_2 is not "!" thenrepeat with artichoke from 1 to ((count (every character of current_version_int_2)) - (count (every character of update_v_int_2)))if (count (every character of current_version_int_2)) is greater than (count (every character of update_v_int_2)) thenset current_version_int_1 to (current_version_int_1 & "0") as stringrepeat with artichoke from 1 to ((count (every character of update_v_int_1)) - (count (every character of current_version_int_1)))else if (count (every character of current_version_int_1)) is less than (count (every character of update_v_int_1)) thenset update_v_int_1 to (update_v_int_1 & "0") as stringrepeat with artichoke from 1 to ((count (every character of current_version_int_1)) - (count (every character of update_v_int_1)))if (count (every character of current_version_int_1)) is greater than (count (every character of update_v_int_1)) thenset current_version_int_2 to split(current_version_int_2, ".") as stringset update_v_int_2 to split(update_v_int_2, ".") as stringset current_version_int_2 to (item 2 of split(current_version_int, ",")) as stringset update_v_int_2 to (item 2 of split(update_v_int, ",")) as stringset current_version_int_1 to (item 1 of split(current_version_int, ",")) as stringset update_v_int_1 to (item 1 of split(update_v_int, ",")) as stringset changelog_text to snr(changelog_text, "", "")set changelog_text to snr(changelog_text, "

    ", "")set changelog_text to snr(changelog_text, "", "")set changelog_text to snr(changelog_text, "

    />", "")set changelog_text to snr(changelog_text, "

    ", "")set changelog_text to snr(changelog_text, "

    ", " ")set changelog_text to snr(changelog_text, "", "")set changelog_text to snr(changelog_text, "", "")set changelog_text to snr(changelog_text, "", "
    ")set changelog_text to snr(changelog_text, "
    ", "")set changelog_text to snr(changelog_text, "

      ", "
      ")set changelog_text to snr(changelog_text, "", ")")set changelog_text to snr(changelog_text, "", "(")set changelog_text to snr(changelog_text, "", "")set changelog_text to snr(changelog_text, "
    • ", " • ")set changelog_text to snr(changelog_text, " ", "")set enabled of button "downloadupdate" of window "updatewindow" to trueset changelog_text to snr(changelog_text, changelog_text_splitter, "") as stringset changelog_text_splitter to item 1 of split(changelog_text_splitter, (" />")) as stringset changelog_text_splitter to item 2 of split(changelog_text, ("

      ")) as stringset changelog_text to item 1 of split(changelog_text, ("")) as stringset changelog_text to update_c_completeset update_v_int to cv_string2int(update_v)set update_v to split(update_v, "-->") as stringset update_v to (last item of split(update_v, "")) as stringset update_c_complete to (item 2 of split(update_c, "")) as stringset update_c_download to (item 2 of split(update_c, "")) as stringlastCheckForConnection()set current_version_int to cv_string2int(current_version)set update_c to do shell script ("cat " & quoted form of (pathTOCURLedfile))do shell script ("perl " & quoted form of pathTOCURLfile & " " & quoted form of update_f & " " & quoted form of (pathTOCURLedfile))set pingMySite to (do shell script "ping -t3 -o audimate.me") as stringdo shell script ("rm " & quoted form of (pathTOCURLedfile))set update_f to (homeRootURL & "toDoList.html") as stringset the contents of text view 1 of scroll view 1 of window "updatewindow" to ""set title of button "closeupdate" of window "updatewindow" to (localized string "CLOSE_TEXT")set the text color of text view 1 of scroll view 1 of window "updatewindow" to "white"set visible of progress indicator 1 of window "updatewindow" to falseinitializeMe_SM()on updateMePlus(isLaunch)end initializeMe_SMset pathTOCURLedfile to (appsup & "CURLfile.yah")set pathTOCURLfile to (appsup & "dp.pl")set theDownloadGo to falseon initializeMe_SM()property current_version : "1.09"global theDownloadGo, appsup, pathTOCURLfile, pathTOCURLedfile, thedownloadsite, ver, update_vmy runInTerminal(vCommand)set vCommand to "open " & vEscapedPathif vEscapedPath is not "" thenset vEscapedPath to my escapePath(my trim(vPath))repeat with vPath in vPathsset vPaths to paragraphs of contents of vSelectionelse -- Open each line of the selection separately.set vPaths to {vPath}set vPath to last item of vItemserror "Please select a valid path."if vItems = {} thenset AppleScript's text item delimiters to vDelimitersset vItems to text items of (vLineHead as string)set AppleScript's text item delimiters to {space, tab}set vDelimiters to AppleScript's text item delimitersset vLineHead to my trim(texts 1 thru vEndColumn of vLine)set vEndColumn to vEndColumn + 1repeat while ((character vEndColumn of vLine) is not in {space, tab}) and (vStartColumn ≤ vLineLength)set vEndColumn to vStartColumn - 1tell AppleScript -- Use AppleScript's text vocabulary to process string.set vLineLength to (length of vLine) as integerset vLine to contents of its line vStartLineif vRunsCount = 0 then -- Nothing selected.set vStartColumn to startColumn of vSelectionset vStartLine to startLine of vSelectionset vCharacterOffset to characterOffset of vSelectionset vRunsCount to runsCount of vSelectionset vSelection to my getNormalizedSelection()end escapePathset vNSString to vNSString's stringByReplacingOccurrencesOfString:" " withString:"\\ "on escapePath(aString)end trimreturn vNSString as stringset vNSString to vNSString's stringByTrimmingCharactersInSet:vCharacterSetset vCharacterSet to NSCharacterSet's whitespaceCharacterSetset vNSString to NSString's stringWithString:vStringset vString to aString as stringon trim(aString)end runInTerminalset vTab to do script (aCommand) in ittell selected tab of first windowon runInTerminal(aCommand)end getNormalizedSelectiondisplay dialog aMessageon error aMessagereturn {contents:vContents, length:vLength, characterOffset:vCharacterOffset, startLine:vStartLine, endLine:vEndLine, startColumn:vStartColumn, endColumn:vEndColumn, startDisplayLine:vStartDisplayLine, endDisplayLine:vEndDisplayLine, container:vContainer, specifier:vSelectionSpecifier, class:vSelectionClass, runsCount:vRunsCount}error "Unsupported class of selection: '" & vSelectionClass & "'."set vRunsCount to length of (vSelectionSpecifier as list)else if vSelectionClass is text thenset vRunsCount to 1else if vSelectionClass is character thenset vRunsCount to 0if vSelectionClass is insertion point thenset vSelectionClass to class of (selection of its window)set vSelectionSpecifier to selection of its windowset vContainer to container of vSelectionset vEndDisplayLine to (endDisplayLine of vSelection) as integerset vStartDisplayLine to (startDisplayLine of vSelection) as integerset vEndColumn to (endColumn of vSelection) as integerset vStartColumn to (startColumn of vSelection) as integerset vEndLine to (endLine of vSelection) as integerset vStartLine to (startLine of vSelection) as integerset vCharacterOffset to (characterOffset of vSelection) as integerset vLength to (length of vSelection) as integerset vContents to (contents of vSelection) as stringset vSelection to (properties of selection of its window) as recordtell first document of first windowon getNormalizedSelection()property NSCharacterSet : class "NSCharacterSet"property NSString : class "NSString"end setValue:forKey:inRecord:theDict's setValue:val forKey:_keyset theDict to ca's NSMutableDictionary's dictionaryWithDictionary:recon setValue:val forKey:_key inRecord:recend recordFromLabels:andValues:return theResult as recordset theResult to ca's NSDictionary's dictionaryWithObjects:values forKeys:labelson recordFromLabels:labels andValues:valuesend toJSONreturn someString as textset someString to NSString's alloc()'s initWithData:theData encoding:(ca's NSUTF8StringEncoding)if theData is missing value then error (theError's localizedDescription() as text) number -10000set {theData, theError} to NSJSONSerialization's dataWithJSONObject:str options:0 |error|:(reference)on toJSON(str)end convertJSONToAS:isPath:return item 1 of (theThing as list)set listOfThing to ca's NSArray's arrayWithObject:theThingif theThing is missing value then error (theError's localizedDescription() as text) number -10000set {theThing, theError} to NSJSONSerialization's JSONObjectWithData:theData options:0 |error|:(reference)set theData to aString's dataUsingEncoding:(ca's NSUTF8StringEncoding)set aString to NSString's stringWithString:jsonStringOrPathelse -- it's a string, convert to dataset theData to ca's NSData's dataWithContentsOfFile:jsonStringOrPathif isPath then -- read file as dataon convertJSONToAS:jsonStringOrPath isPath:isPathend getTriggerreturn my convertJSONToAS:json isPath:falsetell application "BetterTouchTool" to set json to get_trigger uidon getTrigger(uid)end toggleVarmy setVar:var toVal:true persist:truemy setVar:var toVal:false persist:trueif v = "true" thenset v to getVar(var, text)on toggleVar(var)end executeTriggertell application "BetterTouchTool" to execute_assigned_actions_for_trigger uidset uid to checkUUID(uid)on executeTrigger(uid)end setVar:toVal:persist:if _result ≠ "success" then error "error: variable " & var & " was not set"set _result to set_number_variable var to _valset _result to set_persistent_number_variable var to _valelse if class of _val = number or class of _val = integer or class of _val = real thenset _result to set_string_variable var to _valset _result to set_persistent_string_variable var to _valif _persist thenif class of _val = string or class of _val = boolean thenon setVar:var toVal:_val persist:_persistend getVarerror "invalid var: var is empty"error "_class is not a valid class"return get_number_variable varelse if _class = number or _class = integer or _class = real thenreturn varif var = "false" then return falseif var = "true" then return trueset var to get_string_variable varif _class = string or _class = text or _class = boolean thentell application "BetterTouchTool"if not isEmpty(var) thenon getVar(var, _class)end triggerActiontell application "BetterTouchTool" to trigger_action my toJSON(my getAction(act))if isEmpty(act) then error "Invalid action: " & acton triggerAction(act)end getActiveTBgrouptell application "BetterTouchTool" to return get_active_touch_bar_groupon getActiveTBgroup()end refreshWidgettell application "BetterTouchTool" to refresh_widget uidon refreshWidget(uid)end updateTBwidget:withText:iconPath:iconData:backgroundColor:text _text icon_path icPath icon_data icData background_color getColor(bgcolor)tell application "BetterTouchTool" to update_touch_bar_widget uid ¬on updateTBwidget:uid withText:_text iconPath:icPath iconData:icData backgroundColor:bgcolorend getColorerror "Invalid color: " & clrif c's name = clr then return c's valuerepeat with c in _colorson getColor(clr)end getActionerror "Invalid action: " & actif a's name = act then return {"BTTPredefinedActionType", a's value}repeat with a in _actionson getAction(act)end triggerrun triggerend updatetell application "BetterTouchTool" to update_trigger uid json my toJSON(newJSON)on update()end updateConfigsetNewJSON({"BTTTriggerConfig", update})set update to its recordFromLabels:{(item 1 of update)} andValues:{(item 2 of update)}set newJSON's BTTTriggerConfig to its setValue:(item 2 of update) forKey:(item 1 of update) inRecord:(newJSON's BTTTriggerConfig)updateConfig(u)repeat with u in updateif class of item 1 of update = list thenon updateConfig(update)end setNewJSONset newJSON to its setValue:(item 2 of update) forKey:(item 1 of update) inRecord:newJSONon setNewJSON(update)end renamesetNewJSON({"BTTTouchBarButtonName", _name})on rename(_name)end addActionsetNewJSON(getAction(act))on addAction(act)end setInlineAppleScriptsetNewJSON({"BTTInlineAppleScript", _script})on setInlineAppleScript(_script)end _fontupdateConfig({"BTTTouchBarFontColor", (getColor(clr))})end setSizeupdateConfig({"BTTTouchBarButtonFontSize", _size})on setSize(_size)script _fonton _font()end buttonend toggleIconOnlyupdateConfig({"BTTTouchBarOnlyShowIcon", n})set n to trueset n to falseif json's BTTTriggerConfig's BTTTouchBarOnlyShowIcon thenon toggleIconOnly()end setVisiblesetNewJSON({"BTTEnabled2", n})if json's BTTEnabled2 = 0 thenset json to getTrigger(_uid)else if visibility = "toggle" thenelse if visibility = false thenif visibility = true thenon setVisible(visibility)end placementupdateConfig({"BTTTouchBarItemPlacement", p})error "invalid placement option: " & placementset p to 2else if placement = "right" thenset p to 1else if placement = "left" thenset p to 0if placement = "center" thenon placement(placement)end setIconSizedisplay notification "new icon size: " & _size with title "Set Icon Size"updateConfig({"BTTTouchBarItemIconWidth", _size}, {"BTTTouchBarItemIconHeight", _size})on setIconSize(_size)end setColorupdateConfig({"BTTTouchBarButtonColor", (getColor(clr))})on setColor(clr)script buttonon button()end paddingrun paddingdisplay notification "new padding: " & n with title "Set Padding"updateConfig({"BTTTouchBarItemPadding", n})setTo(padding - 1)setTo(padding + 1)set padding to 0 -- default paddingset padding to json's BTTTriggerConfig's BTTTouchBarItemPaddingproperty padding : missing valuescript paddingon padding()end freeSpacerun freeSpacedisplay notification "new freespace: " & n with title "Set Freespace"updateConfig({"BTTTouchBarFreeSpaceAfterButton", n})setTo(freeSpace - 1)setTo(freeSpace + 1)set freeSpace to 5 -- default free spacelog "No freespace variable in JSON"set freeSpace to json's BTTTriggerConfig's BTTTouchBarFreeSpaceAfterButtonproperty freeSpace : missing valuescript freeSpaceon freeSpace()end radiusrun radiusend applyupdateConfig({"BTTTouchBarApplyCornerRadiusTo", n})error "invalid side choice: " & sideset n to 0else if side = "all" thenset n to 2else if side = "right" thenset n to 1if side = "left" thenon apply(side)end setTodisplay notification "new corner radius: " & n with title "Set Radius"updateConfig({"BTTTouchBarButtonCornerRadius", n})on setTo(n)end incrementsetTo(radius + 1)on increment()end decrementsetTo(radius - 1)on decrement()set radius to 6 -- default radiusset radius to json's BTTTriggerConfig's BTTTouchBarButtonCornerRadiusproperty parent : my triggerproperty radius : missing valuescript radiuson radius()end setModKeysetNewJSON({"BTTRequiredModifierKeys", modSum})set modSum to modSum + (m's value)if m's name = _mod thenrepeat with m in modsset modSum to 0if _mod = "clear" thenlog "modSum before: " & modSumset modSum to getModKeys()on setModKey(_mod)end getModKeyslog "no BTTRequiredModifierKeys"return json's BTTRequiredModifierKeyson getModKeys()end copyUUIDwith icon cautiondefault button ("OK") ¬buttons {"Cancel", "OK"} ¬display dialog (errMsg & return & return & errNum) ¬sound name "Basso"subtitle ("A trigger must be selected") ¬with title ("Error: Invalid selection") ¬display notification ("Select a trigger and try again") ¬if errNum = -1000 thenreturn the clipboardif (the clipboard) = "" then error number -1000keystroke "c" using {command down, shift down}tell process "BetterTouchTool"set the clipboard to ""on copyUUID()return meset uid to json's BTTUUIDset json to getTrigger(copyUUID())if isEmpty(_uid) thenproperty newJSON : missing valueproperty json : missing valueproperty uid : _uidproperty parent : script "BetterTouchTool Library"property class : "trigger"script triggeron trigger(_uid){name:"Toggle BetterTouchTool Touch Bar", value:188} ¬{name:"Select Menu Item", value:124}, ¬{name:"Close currently open Touch Bar group", value:191}, ¬{name:"AppleScript (blocking)", value:172}, ¬property _actions : {¬ {name:"AppleScript (async)", value:195}, ¬{name:"lemon", value:"254.853130, 251.316189, 0.000000, 255.000000"} ¬{name:"white", value:"255.000000, 255.000000, 255.000000, 255.000000"}, ¬{name:"spring", value:"0.000000, 249.085161, 0.000000, 255.000000"}, ¬{name:"red_transparent", value:"255.000000, 96.000002, 94.000002, 102.000000"}, ¬{name:"red", value:"255.000000, 38.028511, 0.000000, 255.000000"}, ¬{name:"def_background", value:"75.323769, 75.323769, 75.323769, 255.000000"}, ¬{name:"blue", value:"10.000000, 132.000000, 255.000000, 255.000000"}, ¬property _colors : {¬ {name:"black", value:"0.000000, 0.000000, 0.000000, 255.000000"}, ¬{name:"fn", symbol:"Fn", value:8388608} ¬{name:"shft", symbol:"⇧", value:131072}, ¬{name:"ctrl", symbol:"⌃", value:262144}, ¬{name:"opt", symbol:"⌥", value:524288}, ¬property mods : {¬ {name:"cmd", symbol:"⌘", value:1048576}, ¬property ca : a reference to current applicationproperty NSJSONSerialization : a reference to current application's NSJSONSerializationproperty version : "1.0.1"property id : "com.kfunderburg.library.betterTouchToolLibrary"property name : "BetterTouchTool Library"click menu item 3 of view_toolbars_bookmarksif checked_2 thenset checked_2 to not((value of attribute "AXMenuItemMarkChar" of menu item 2 of view_toolbars_bookmarks) is equal to missing value)click menu item 1 of view_toolbars_bookmarksclick menu item 2 of view_toolbars_bookmarksif checked_1set checked_1 to not((value of attribute "AXMenuItemMarkChar" of menu item 1 of view_toolbars_bookmarks) is equal to missing value)if not(winTitle is equal to "Mozilla Firefox")tell application "Firefox Developer Edition" to set winTitle to name of first window whose miniaturizable is equal to true # first non-pip windowset view_toolbars_bookmarks to menu 1 of menu item "Bookmarks Toolbar" of menu 1 of menu item "Toolbars" of menu 1 of menu bar item "View" of menu bar 1tell process "Firefox Developer Edition"tell application "Firefox Developer Edition" to activatemove cue id (uniqueID of eachCue) of parent of eachCue to end of theGrouprepeat with eachCue in newCuesset theGroup to last item of (selected as list)if length of newCues is not 0 thenset end of newCues to newCueset custom message of newCue to ("/cue/" & theQ & "/start")set osc message type of newCue to customset patch of newCue to userPatchset newCue to last item of (selected as list)make type "Network"if theQ is not "" thenset selected to eachCueset theQ to q number of eachCueset userPatch to 1set URL of document 1 to theURLtell window 1 to set current tab to make new tabif theURL is not equal to missing value thenset theURL to URL of active tab of window 1if (URL of active tab of window 1 does not start with "chrome://") thenif (exists window 1) thenset theURL to missing valuedisplay notification "Backup complete! Unmount and power down the backup drive" with title "SuperDuper!"display dialog "Oops! ... " & errMsgdo shell script "sleep 7"tell application "SuperDuper!" to quitif status is done thendo shell script "sleep 6"repeat while status is runningrun using settings backupSettings without user interactionif status is idle thendo shell script "sleep 5"tell application "SuperDuper!"set backupSettings to "Cortana:Users:takashi:Library:Application Support:SuperDuper!:Saved Settings:Cortana-daily.sdsp:" as aliastell application "Script Debugger" to activateclose document newName saving nosave bbDoc to savePathtell bbDoc to activatedetab bbDoc tab width 4set the text of bbDoc to sourceCodeset bbDoc to make new documentlaunch application "BBEdit"set savePath to theFolder & newNameset newName to originalName & ".applescript"set newName to ((characters 1 through thePoint of originalName) as text) & "applescript"if thePoint is not 0 then -- 0 if file ext is hiddenset thePoint to (the offset of "." in originalName)set theFolder to (characters 1 thru (pathOffset - 1) of oldPath) as textset pathOffset to (the offset of originalName in oldPath)set oldPath to (POSIX file posixPath) as textset sourceCode to the source textset posixPath to the pathset originalName to the nametell application "iWeb" to activatedo shell script "/usr/bin/defaults write com.apple.iWeb iWebDefaultsDocumentPath -boolean no"addComment(anImage)if hasGraphicConverter is false thenopen alias theFileset theFile to (theImagesFolder & theImage) as stringtell application "GraphicConverter 9"set comment of theFile to textReceivedon addComment(theImage)set textReceived to text returned of resultdisplay dialog "Fill in copyright info to add to images" default answer "Copyright (c) 2015 All Rights Reserved by Smerth" with title "Copyright text" with icon note buttons {"Ok", "Cancel"} default button 1set hasGraphicConverter to get exists file ((path to applications folder as string) & "GraphicConverter 9.app")global textReceivedend isRunningreturn (count of (every process whose name contains appname)) is greater than 0on isRunning(appname)end replacereturn resset AppleScript's text item delimiters to oldDelset res to myList as stringset AppleScript's text item delimiters to repset myList to text items of strset AppleScript's text item delimiters to orgset oldDel to AppleScript's text item delimiterson replace(str, org, rep)return tmpset tmp to my replace(tmp, "$url$", u)set tmp to my replace(format, "$title$", t)set t to name of document 1set u to URL of document 1if ((count of document) > 0) thenmy do()if (isRunning) thenset isRunning to isRunning("Safari") of meset format to "$title$"global format℁do shell script "pkgutil --flatten " & theSourceFolder & " " & theOutputFolder & "/" & pkgName & "_repacked.pkg"set pkgName to characters 1 thru ((offset of "_" in theName) - 1) of theName as stringset theSourceFolder to quoted form of ((POSIX path of theSource) as text)set theOutputFolder to quoted form of (POSIX path of (container of theSource as text))set theName to displayed name of theSourceset theSource to choose folder with prompt "Please select the folder to be packed"if answer is equal to "Repack" thendo shell script "pkgutil --expand " & quoted form of POSIX path of theFile & " " & theOutputFolderset extension hidden of theFile to falseset theOutputFolder to quoted form of (POSIX path of ((container of theFile) as text) & "/" & theName & "_unpacked")set theName to displayed name of theFileset extension hidden of theFile to trueset theFile to choose file with prompt "Please select the pgk file:" of type {"pkg"}if answer is equal to "Unpack" thenset question to display dialog "Select" buttons {"Unpack", "Repack", "Cancel"}delay random number from 30 to 60repeat 100000tell process "Safari"set desiredSize to {0.5, 1.0}set desiredPosition to {0.5, 0.0}set the comment of this_item to ""set the tags of this_item to theTagsset theTags to (parents of this_item) & theTagsset theTags to text items of this_commentset {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ","}if this_comment is not "" thenset this_comment to the comment of this_itemrepeat with this_item in these_itemsif these_items is {} then error "Please select some contents."set these_items to the selectionreturn iif not isSynchronizing thenrepeat with i from 0 to 300synchronizeif application "Evernote" is running thenreturn (array's sortedArrayUsingSelector:"localizedCaseInsensitiveCompare:") as listrepeat while oldCurr is current trackset player position to ((duration of current track) - 1)set oldCurr to current trackrepeat with i from 1 to count of theSelplay item 1 of theSelset theSel to selectionif flag thenon applicationShouldHandleReopen:sender hasVisibleWindows:flagon applicationShouldTerminateAfterLastWindowClosed:senderreturn current application's NSTerminateNowon applicationShouldTerminate:senderon applicationWillTerminate:notificationon applicationDidFinishLaunching:notificationcurrent application's NSApp's runModalForWindow:theWindowcurrent application's NSApp's activateIgnoringOtherApps_(true)tell the contentView of theWindow to addSubview_(theWebView)tell theWebView to loadRequest_(r)set r to NSURLRequest's requestWithURL_(u)set u to NSURL's URLWithString_(theAddress)tell theWebView to setFrame_(f)set f to current application's NSMakeRect(0, 64, w, h - 64)set h to height of sset w to width of sset s to theWindow's contentView's frame()'s |size|set theWebView to WKWebView's alloc's initWithFrame_configuration_(z, c)set c to WKWebViewConfiguration's alloc's init()set z to current application's NSMakeRect(0, 0, 0, 0)set theAddress to "http://book.mynavi.jp/wd/widget/300x250.html"on applicationWillFinishLaunching:notificationcurrent application's NSApp's terminate_(me)on ok:senderproperty theWindow : missing valueproperty WKWebViewConfiguration : class "WKWebViewConfiguration"property WKWebView : class "WKWebView"property NSURLRequest : class "NSURLRequest"property NSURL : class "NSURL"property parent : class "NSObject"script AppDelegateset logger to std's import("logger")'s new("dec-syseve-with-sublimetext")end decorateend getFrontAppNamefrontAppNameif frontAppName is "sublime_text" then return "Sublime Text"set frontAppName to continue getFrontAppName()on getFrontAppName()property parent : baseScriptscript SyseveSublimeTextInstanceon decorate(baseScript)logger's infof("Process Name: {}", sut's getFrontAppName())activate application "Sublime Text"if name of sut is not "SyseveSublimeTextInstance" then set sut to decorate(sut)set sut to std's import("system-events")'s new()Basic Testset caseId to "dec-keyboard-dvorak-cmd-spotCheck"end stashon stash(title)end rebaseon rebase()end mergeset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git merge " & into_branch & " " & from_branchlog ("GitModifier's merge()")on merge(local_repo_path, into_branch, from_branch)end branchon branch(target_branch, delete_flag)end fetchset shell_cmd to shell_cmd & " " & branchif branch is not space thenset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git fetch " & "origin"log ("GitModifier's fetch(" & branch & ")")on fetch(local_repo_path, remote_path, branch)end check_outset shell_cmd to shell_cmd & " " & file_pathif file_path is not space thenset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git checkout " & loclog ("GitModifier's check_out(" & loc & " " & file_path & ")")on check_out(local_repo_path, loc, file_path)end remoteon remote()end git_remote_updatereturn do shell script "cd " & local_repo_path & ";" & git_path & "git remote update"on git_remote_update(local_repo_path)end configon config()end cloneset shell_cmd to git_path & "git clone " & remote_path & " " & local_pathon clone(remote_path, local_path)end detach_remote_reposet shell_cmd to "cd " & local_repo_path & ";" & git_path & "git remote rm origin"on detach_remote_repo(local_repo_path)end attach_remote_reposet shell_cmd to "cd " & local_repo_path & ";" & git_path & "git remote add origin" & " " & (quoted form of remote_repo_path)on attach_remote_repo(local_repo_path, remote_repo_path)log "shell_cmd: " & shell_cmdset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git init"on init(local_repo_path)end removeon remove()end reverton revert()end pullreturn do shell script "cd " & local_repo_path & ";" & git_path & "git pull" & " " & remote_loc & " " & target_branchset target_branch to "master" --master branchset remote_loc to "https://" & user_name & ":" & user_password & "@" & remote_repo_urlon pull(local_repo_path, remote_repo_url, user_name, user_password) --TODO: add branch hereend cleanon clean()end resetreturn do shell script "cd " & local_repo_path & ";" & git_path & "git reset" & " " & file_nameon reset(local_repo_path, file_name)end pushset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git push" & " " & remote_loc & " " & branchset remote_loc to "https://" & user_name & ":" & user_password & "@" & remote_repo_url --https://user:pass@github.com/user/repo.git--"origin"log ("GitModifier's push(" & "local_path: " & local_repo_path & ", remote_path: " & remote_repo_url & ", user: " & user_name & ", pass: " & user_password & ", branch: " & branch & ")")on push(local_repo_path, remote_repo_url, user_name, user_password, branch)end commitreturn do shell script "cd " & local_repo_path & ";" & git_path & "git commit" & " " & "-m" & " '" & message_title & "' " & "-m" & " '" & message_description & "'"log ("GitModifier's commit(" & message_title & ")")on commit(local_repo_path, message_title, message_description)end addreturn do shell script shell_cmdset shell_cmd to "cd " & local_repo_path & ";" & git_path & "git add" & " " & file_nameset file_name to quoted form of file_nameif (TextAsserter's is_wrapped_in(file_name, "\"") = false) then --avoids quoting a file_name that is already quoated, this can happen when git removes a filelog ("GitModifier's add(" & local_repo_path & file_name & ")")on add(local_repo_path, file_name)property git_path : "/usr/local/git/bin/" --to execute git commands we need to call the git commands from this pathproperty TextAsserter : my ScriptLoader's load_script(alias ((path to scripts folder from user domain as text) & "text:TextAsserter.applescript"))property ScriptLoader : load script alias ((path to scripts folder from user domain as text) & "file:ScriptLoader.scpt") --prerequisite for loading .applescript filesdisplay dialog "User cancelled script." buttons {"Exit"} default button 1 with icon stopdisplay dialog "An error has occured! [# " & errnum & "]" & return & "I was trying to open the checkpoint." buttons {"Exit"} default button 1 with icon stop giving up after 1on error number errnumdo shell script "open " & myCheckPointPath & "/" & item mySelectionIndex of myCheckPointListif (item i of myModCheckPointList) is (mySelection as string) then set mySelectionIndex to irepeat with i from 1 to the count of myModCheckPointListif mySelection is not false thenset mySelection to choose from list myModCheckPointList with prompt "Please select the checkpoint to examine:"set myModCheckPointList to myModCheckPointList & {myModCheckPoint}set myModCheckPoint to MyModDay & ", " & myModHour & ":" & myTimeMinute & " " & myModZoneset MyModDay to myMonthName & " " & myDay & ", " & myYearset MyModDay to "Yesterday"else if myDay = myYesterdayDay thenset MyModDay to "Today"if myDay = myDateTodayDay thenset myModZone to "am"set myModHour to myTimeHour as stringset myModZone to "pm"set myModHour to myTimeHour - 12if myTimeHour > 12 thenset myTimeMinute to text item 2 of myTimeElementsset myTimeHour to text item 1 of myTimeElements as integerset myTimeElements to text items of myTimeset the text item delimiters to "."set myZone to item 5 of myItemset myTime to item 4 of myItemset myDay to item 3 of myItem as integerset myMonthName to item myMonth of monthListset myMonth to item 2 of myItem as integerset myYear to item 1 of myItemset myItem to text items of thisItemset the text item delimiters to "_"set thisItem to (item i of myCheckPointList)repeat with i from 1 to the count of myCheckPointListset myCheckPointList to text items of myCheckPointsset myCheckPoints to do shell script "ls " & myCheckPointPathreturn --Exit script nowdisplay dialog "No checkpoints found." & return & "Is the NAS mounted?" buttons {"Exit"} default button 1 with icon stopdo shell script "test -d " & myCheckPointPathset text item delimiters to returnset myYesterdayDay to myDateTodayDay - 1else -- not beginning of monthif (myLeapYear = true) and (myDateTodayMonth = 3) then set myYesterdayDay to 29set myYesterdayDay to (item myYesterdayMonth of dayList)set myYesterdayMonth to myDateTodayMonth - 1else -- beginning of month, not beginning of yearset myYesterdayMonth to 12set myYesterdayDay to 31if myDateTodayMonth = 1 then --beginning of yearif myDateTodayDay = 1 then -- beginning of monthset myLeapYear to falseset myLeapYear to trueif (myDateTodayYear mod 400) = 0 thenif (myDateTodayYear mod 100) = 0 thenif (myDateTodayYear mod 4) = 0 thenset myYesterdayMonth to ""set myDateTodayYear to (do shell script "date \"+%Y\"") as integerset myDateTodayMonth to do shell script "date \"+%B\""set myDateTodayDay to (do shell script "date \"+%e\"") as integerset myCheckPointPath to "/Volumes/home/.ckpt"set myModCheckPointList to {}set dayNameList to {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}set dayList to {"31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"}set monthList to {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}end progress_endset progress additional description to ""set progress description to ""set progress total steps to 0on progress_end()end progress_stepset progress completed steps to non progress_step(n)end progress_updateset progress additional description to message & n & " of " & stepson progress_update(n, steps, message)end progress_startset progress additional description to descript_addset progress description to descriptset progress completed steps to 0set progress total steps to stepson progress_start(steps, descript, descript_add)set progress completed steps to iset progress additional description to thisItemset progress description to "Item " & i & " of " & itemCountset thisItem to item i of theListrepeat with i from 1 to itemCountset progress total steps to the itemCountset the itemCount to the count of theListset theList to {"Marlow", "Maddie", "Sammy", "Stuey", "Jessie", "Tolstoy"}set table_text to table_rows as textset AppleScript's text item delimiters to linefeedset end of table_rows to item i of the_names & tab & item i of phones_by_namerepeat with i from 1 to length of the_namesset table_rows to {}set phones_by_name to value of every phoneset the_names to nametell every person of group "Work" tell application "Address Book"end tmopen listOfAliasestell application "TextMate"on tm(listOfAliases)tm(theList)on open (theList)tm(finderSelection)set finderSelection to selection as alias listset finderSelection to folder of the front window as stringif selection is {} thenreturn last resultif not compiled then return last error messagemy waitUntilReady(d)executeset d to front documentend waitUntilReadyrepeat while execution state of d is not in {stopped, paused}on waitUntilReady(d)do JavaScript "document.querySelector('#save').click();"keystroke "siggi"keystroke "p"set the clipboard to "OUT"do JavaScript "document.querySelectorAll('label[for=target_path]')[0].click();"do JavaScript "document.querySelectorAll('label[for=request_path]')[0].click();"tell current tab of first windowset the clipboard to "IN"set selected to newCuesset end of newCues to theFadeset cue target of theFade to (cue target of originalCue)else if originalCueType is "Fade" thentheFade setLevel row 0 column 0 db 0else if originalCueType is "Group" thentheFade setLevel row 0 column 0 db originalLevelset cue target of theFade to originalCueif originalCueType is in {"Audio", "Video", "Mic"} thenset duration of theFade to userDurationset theFade to last item of (selected as list)make type "Fade"set originalLevel to originalCue getLevel row 0 column 0if originalCueType is in {"Audio", "Video", "Mic", "Fade"} thenset originalCueType to q type of originalCueset selected to originalCuerepeat with originalCue in theSelectionset newCues to {}set userDuration to 5 -- your preferred default fade durationkeystroke (key code 36)keystroke "123456"keystroke "a"keystroke "City"keystroke "12345"keystroke "Address 2nd line"keystroke "Street Nr"keystroke "Address"keystroke "Lastname"keystroke "Firstname"execute front window's active tab javascript "document.querySelector('[type=submit]').click(true);"keystroke ".com"keystroke "@test"keystroke randkeystroke "test"set rand to (random number from 5 to 49) * 2execute front window's active tab javascript "document.querySelector('[for=customer-email]').click();"execute front window's active tab javascript "document.querySelector('#top-cart-btn-checkout').click();"execute front window's active tab javascript "document.querySelector('#product-addtocart-button').click();"1 + 1repeat until (loading of front window's active tab is false)open location "https://www.happysocks.com/us/lily-rib-ankle-sock-4.html"end clearDateset due date of selectedItem to missing valueset defer date of selectedItem to missing valueon clearDate(selectedItem)end getContextreturn first context whose id is contextIDset contextID to id of item 1 of (complete contextName as context)on getContext(contextName)set alertText to "Date(s) cleared for " & successTot & " item" & alertItemNum & "." as stringset succeeded to my clearDate(thisItem)if changeContext then set context of thisItem to newContextif changeContext then set newContext to my getContext(newContextName)property dueDate : ""property useGrowl : true --if true (and showAlert is true), uses Growl for alertsproperty showSummaryNotification : true --if true, will display success notificationsproperty newContextName : "Someday" --context the item will change to if changeContext = trueproperty changeContext : false --true/false; if true, set newContextName (below)end calculateScenereturn sceneset scene to num - 383set scene to num - 256set scene to num - 129set scene to num - 1set scene to integeron calculateScene(num)end calculateChanreturn chanset chan to 4else if num is greater than 382 and num is less than 508 thenset chan to 3else if num is greater than 255 and num is less than 383 thenset chan to 2else if num is greater than 128 and num is less than 256 thenset chan to 1if num is less than 129 thenset chan to integeron calculateChan(num)collapse sceneGroupset groupParent to parent of groupParentset q color of groupParent to userColorif q name of groupParent is cueListName thenset groupParent to parent of sceneGroupif colorParentGroups is TRUEset q color of sceneGroup to userColorset q name of midiBank to "Scene " & sceneNumber & ": Program Change"move cue id midiBankID of parent of midiBank to end of sceneGroupset byte one of midiBank to sceneNumset channel of midiBank to chanNumset command of midiBank to program_changeset message type of midiBank to voiceset midiBankID to uniqueID of midiBankset midiBank to last item of (selected as list)make type "Midi"set q name of sceneGroup to sceneGroupNameset mode of sceneGroup to timelineset sceneGroupID to uniqueID of sceneGroupset sceneGroup to last item of (selected as list)make type "Group"set sceneGroupName to "Scene " & sceneNumber & ": " & sceneNameset sceneNum to my calculateScene(sceneNumber)set chanNum to my calculateChan(sceneNumber)set sceneName to text returned of resultdisplay dialog "What would you like to name this scene" default answer "" buttons {"Set", "Cancel"} cancel button "Cancel" default button "Set" with title "SCENE NAME"set sceneNumber to text returned of result as integerdisplay dialog "Please select a scene number to recall" default answer "" buttons {"Set", "Cancel"} cancel button "Cancel" default button "Set" with title "SCENE NUMBER"set cueListName to "Main Cue List" -- Name of main cue listset colorParentGroups to TRUE -- set colour of any groups containing the recall group as well?set userColor to "green" -- the colour of groups containing midi recallsset cursor_text color to {60037, 58326, 52284}set cursor color to {21257, 26684, 28737}set selected text color to {18134, 23373, 25098}set selection color to {60138, 58339, 52171}set bold color to {18134, 23373, 25098}set background color to {64842, 62778, 56626}set foreground color to {21074, 26471, 28270}if fg_color is {28873, 33398, 33872} thenset fg_color to get foreground colortell _sessiontell me to quitset _session to current session of current terminalelse if bizzy is false thendelay 120if bizzy is true thenset bizzy to busy of window 1end containsFromListreturn answerset answer to trueif textToCompare contains item i of listOfTerms thenrepeat with i from 1 to count listOfTermsset answer to falseon containsFromList(textToCompare, listOfTerms)end waitForif containsFromList(botStatus, wordsToWaitFor) then exit repeatif containsFromList(lastRequest, captchaTriggers) then checkForCaptcha()set latencyOffset to latencyOffset + 0.25if botStatus contains msgWait then --Time to slow downrepeat serverRateLimit * 4 timeson waitFor(wordsToWaitFor)end isOnStreakif containsFromList(pokemon, msgStreak) thenon isOnStreak(pokemon)end checkForCaptchaif hasCaptcha is false then exit repeatsendRequest(lastRequest) --Repeat previous attemptif botStatus does not contain msgCaptcha thenupdateBotStatus()repeat serverRateLimit timesrepeat while hasCaptcha is truebeep 3set hasCaptcha to trueif botStatus contains msgCaptcha thenset hasCaptcha to falseon checkForCaptcha()end sendRequestset lastRequest to reqtell application "System Events" to keystroke theCharrepeat with theChar in reqon sendRequest(req)end updateBotStatuserror number -128 --exitdisplay dialog "Error getting text. Did you forget to inject?"if botStatus is missing value thenset botStatus to execute front window's active tab javascript "document.querySelector('#watchbot').innerText"on updateBotStatus()end throwPokeballwaitFor({msgWildcaught, msgWildescaped})sendRequest("mb")else if containsFromList(botStatus, {msgRShiny, msgRGolden, "Golden", "Shiny", "Kyogre", "Suicune"}) thensendRequest("prb")else if botStatus contains msgRLegendary thenelse if botStatus contains msgRRare thensendRequest("ub")else if botStatus contains msgRSuper thensendRequest("pb")sendRequest("gb")if isOnStreak(botStatus) thenif containsFromList(botStatus, {msgRCommon, msgRUncommon}) thenon throwPokeball()end getTimereturn (time of (current date))on getTime()set lastFishing to getTime()delay (random number from 0.05 to 0.25)key code 51 using {command down}repeat 4 timesif botStatus contains msgFishingpokemon then throwPokeball()waitFor({msgFishingpokemon})tell application "System Events" to key code 76tell application "System Events" to keystroke "pull"if botStatus contains msgFishingpull thenwaitFor({msgFishingpull, msgFishingnothing})sendRequest(fish)set offsetTimer to getTime()log "Time between fishing: " & (getTime() - lastFishing)if fishingEnabled and getTime() ≥ (lastFishing + fishingCooldown + latencyOffset) thendelay latencyOffsetset lastHunting to getTime()if botStatus contains msgWildpokemon then throwPokeball()waitFor({msgWildpokemon})sendRequest(hunt)log "Time between hunting: " & (getTime() - lastHunting)if huntingEnabled and getTime() ≥ (lastHunting + huntingCooldown + latencyOffset) thentell application "Google Chrome" to activateglobal lastRequest, botStatus, lastHunting, lastFishingset lastFishing to fishingCooldownset lastHunting to huntingCooldownset botStatus to ""set lastRequest to ""global msgRLegendary, msgRShiny, msgRGoldenglobal msgRCommon, msgRUncommon, msgRRare, msgRSuperset msgRGolden to "Golden streak" --Hypothetically...set msgRShiny to "Shiny streak"set msgRLegendary to "Legendary streak"set msgRSuper to "Super Rare streak"set msgRRare to "Rare streak"set msgRUncommon to "Uncommon streak"set msgRCommon to "Common streak"global msgWildescaped, msgFishingpokemon, msgFishingpull, msgFishingnothingglobal msgCaptcha, msgWait, msgWildpokemon, msgWildcaught, msgStreakset msgFishingnothing to "Not even a nibble"set msgFishingpull to "Oh! A bite!"set msgFishingpokemon to "A wild Pokemon appeared!"set msgWildescaped to " used a"set msgWildcaught to "Congratulations, "set msgStreak to {"Uncommon streak: 6", "Uncommon streak: 7", "Uncommon streak: 8", "Uncommon streak: 9", "Common streak: 13", "Common streak: 14"}set msgWildpokemon to "A wild Pokémon appeared!"set msgWait to "please wait"set msgCaptcha to "captcha"global captchaTriggersset captchaTriggers to {hunt, fish}set fish to ";f"set hunt to ";p"global latencyOffset, serverRateLimitglobal huntingEnabled, fishingEnabled, huntingCooldown, fishingCooldownset serverRateLimit to 6set latencyOffset to 0.5 --Base adjustment for discord lagset fishingCooldown to 20 --Delay time set by bot.set huntingCooldown to 7 --Delay time set by bot.set fishingEnabled to trueset huntingEnabled to trueend zipset end of lst to {item i of xs, item i of ys}set lng to min(length of xs, length of ys)on zip(xs, ys)end unzipreturn {xs, ys}set end of ys to item 2 of xyset end of xs to item 1 of xyrepeat with xy in xysset ys to {}set xs to {}on unzip(xys)if script is class of f thenend maybetell mReturn(f) to |λ|(Just of mb)vif Nothing of mb thenon maybe(v, f, mb)end mapreturn lstset end of lst to |λ|(item i of xs, i, xs)on map(f, xs)end getFromDictitem 1 of ((ca's NSArray's arrayWithObject:v) as list)on getFromDict(k, dct)end lookUpDict1)Ӥl\��ɻ��-CWv��6[��%V����� "M{�]��2N���Gi���L����Oq���� B � � / e � � � �  = y �  3 G � � � &��+��C[�Np�BVl����7r��Gb�� F����Pd�� /^�����(Nb�����.Pd�����;V����Al���&Di�����-|��7z��� Zs��% 0 D � � � � � � ! !!L!m!�!�!�!�!�! ""9"{"�" ##E#n#�#�#�#'$7$j$�$�$X%�%&G&�&�&'.'�'(<(L(q(�(�(�(�()W)�)�)�)+*`*�*�*�*4+i+�+�+,>,s,�,�,--,-K-w-�-�-.3.b.�.�.�./M/|/�/�/ 090h0�0�0�0�01,1:1p1�1�1�122D2U2t2�2�23E3p3�3�34$4.4?4�4�4�4�4�4�4>5G5X5f5o5�5�5�5�5�5�5�56#6T6�6�6�6�67707I7Y7�7�7�7�7$8O8{8�8�8;9J9{9�9�9�9�9�9 :1:O:j:u:�:�:;b;�;�;3<c<�<&=U=w=�=�=�=g>m>�>�>�>?(?p?�?�?�?�?@8@O@p@y@�@�@�@ A,AmA�A�A�AB%BTB�B�B�B�BC'C4CLC`CnC�C�C�C�C�CD/D6DHDhD~D�D�DE3E�E�E0FCF�F�F)GnG�G�G�GH:HdHxH�H�HAI�IKTK�K�KqL�LWM�M�MN NtN�NPOlO�O"PsP�PQYQ�Q>RPR�R�R�RS^SdS�ST@TxT�T�T�T�T�T�T)UYU�U�U�UMVzV�V�V)WyW�W�WXDXzX�X�X!YqY�Y�YZ�Z�Z�[�[�[\#\I\m\�\�\�\�\']O]x]�]�]�]+^Y^�^�^ _W_�_�_`N`�`�`�`a5a�a.bqb�b�b�b�b'c6c�c�cdnd�d"e;e�e�ef6fhf�f(g{g�g�g�g�ghh-h?hdh�h�h�h�h�h iQi�i�ijYj�j�j�j�jk(kCkek�k�k*l;lLlll�l�l�l�l�l�l7m@mSmdm�m�mn!nIn]n�n�n�n�noo@oWoyo�o�o�o�o�o p6p\ppp�p�p�p�p qqBqUq�q�q�q�q�qr6rIrir}r�r�rWsos�s�s�s�s#t6t�t�t�tu&u_u�u�u�u�uvJv�vw]www�w�wPx�x�x�x�xy]yxy�y�y�y zGzRziz={S{d{6|F|X|+}<}Q}'~;~~~�~Pe��!�:�L�a�k���������6�o�w���ׁ�b����7�~�Ãփ�\����*�c����5�v�����=�����ه�^����,�q���Ή�T���܊!�i�����+�o�����=������� � �/�t���ގ �_���֏�c���ڐ�)�f����3�j�����6�x�����A���Ȕ �D�S���ו�*�m����.�r�����6�w�����@��™�K���Ӛ�Z�����%�i���Μ��V�`�u�����:�~�Þ�L���͟�X����(�k����,�q���Ģ�K���ǣУ�[����(�m������!�d����'�`���ާ�G���Ш�1�l�����@�|�����6�v�����7�u���֬�^����&�k���î�"�X������1�h���Ұ�L���α �H���IJ�*�k����&�9�w�����6�w�����:�{�����2�u�����S������G���ٹ!�c����4�{�»�2�z�ü�O������0�u�����@���ƿ � �f�����>������;�{������0�t�����@����� �D����� �K������\����� �N�������;�u������@�}����G�c�����.�j�����:�~�����'�i������6�E������R�k�����(�n������U����� �;���� �M�g������]�����'�i������`�����%�h�����)�n�����4�v�����B������� �N������Y������c�������8�z�����5�z����H�a�����/�s�����:����� �P������G������U�p�����2�x����F����� �N����� �P�������2�x����Q�����)�i������b�����0�v�������?�������*�k�����1�v������]������E�S�n�����=������]�������5������[�������"�d�����+�n�������!�g�����9�|����.�r������Y������A�����Fw��2}� U��O��*i����3^���0Nv��� '<t�� 9J_���� " D K i � �   � � � ? � �  b � 4 � � � � � Ld���!��9g����.���/T���]���Bu���(_v���Z|��� E^}���*G[n����4s��0o���Ak��A��C��%Mu���c��M � � E!m!}!"�"#�#*$?$�$Q%^%%�%�%�%�%&/&�&�&�&�&''''A'q'�'�'�'@(�(�(�(�(�)�)%*D*r*�*�*�*-+[+~+�+�+�+�+,0,{,�,�,�,�,-!-A-l-�-�-�-�-.N.�.�.�.�.!/:/n/�/�/�/�/0,0L0�0�0�01f1t1�1�1�12N2�2�2�2`3o3�3�4�4X5�5>6�6*7�78q8�8M9�9/:�:�:;);b;�;�;�;<%<?<[<w<�<==3=_=�=�=�=�=>8>d>�>�>�>�>#?B?k?@b@�@�@�@�@A>AoA�A�A�A�A�AB=BGBYBgB{B�B?CWCwC�C�CD5DkD�D�D�D�DE9EYE�E�E�E FKFgF�F�F�FGIG�G�GtH�H�H I�I�I-J�J�J%K[K�K{L�L�LWMmM�M�MNsNN�N�N�NVO�O PP2PWP�P�P�PRQ�Q�QRR>RjR{R�R�RS8SRSS�S�S�S�S TATnT�T,UUU�U�U�UV@V_VuV�V�VWYW�W�WXEXpX�X�X8Y^YwY�Y�Y�Y$ZFZvZ�Z�Z�Z�Z[[/[I[_[w[�[�[\1\W\|\�\�\�\ ]/]q]�]�]8^e^y^�^�^�^�^_7_T_o_�_�_�_!`<`n`�`�`%aSa�a1b�b c4c�c�cLd�d�de/ebe�e'fef�f g1g�g�g3h[h�hi'iLieisi�i�i�i�i5j�j�j�j�jFk�k�k�k�kTlkl�l�l#m5mHmZmqm�m�m�m�m�mnn(nAnan�n�n�n oo)olo�o�o�oHpsp�p�pqq3qNqYq^q�q�q�q�qLrar|r�r�r�rs:sNs�s�s�stDtQtqt�t�tu?uFuRumu�u�u�u%v.vTvWvhvxv�v�v�v�v�v�vw0wIwfw~w�w�w�w�wx!xGxpx�x�x�xyGyby�y�y�yzzz z-zLz\zlz|z�z�z�z�z�z{/{R{~{�{�{�{�{�{�{|||*|?|�|�|�|}+}/}K}�}�}~.~�~�~�~dy��G�Z����������^�u���ȁ�F�I�V�_�p�����ق�!�;�V�q��������0�P�\�d�p�x���������,�4�I�e������� �1�F�R�\�h�r����������'�9�j���҇Ӈ�/�P�k������ �<������ډ���6�Y�����ߊ��3�R�m�������I�v�����Ԍ��%�I�e�r���������ٍ��)�A�a�����ǎ����'�M�g�z�����׏�\���̐� ��?�X�i�����Ց�������������!�4�B������"�y����������.�Y���ԕ�6�E���Ŗ �9�����ӗ�-�`�w�����՘��&�V�p�y���ęə͙Ιۙ�+�N�g�����Кߚa�}�����ƛӛ��&�S�v�����ɜݜ��0�����Н&�6�l���Ԟ���j����P�\�l���ݠ���� �S�����ѡ�U�i���Ӣ �&�K�l�������G�{���ߤ<�Y�������@�g���Ȧ �<�a�r�����˧��E�x���Ǩ������3�J�p�����������J�W�j�y���֫��2�Y�k������#�7�V�{���έ��D���ɮ�0�W�u�����1�[���0�e�y���������)�j���ʲ��L������� �E�|���ش�� �)�R�S�a�w���Ե�&��F�������"�;�m���ո��,�a�q������������*�B�T�������C�y�����ɻ����A�m�����Լ�� ��/���Ľ�<�_���۾ �?�L�z��������K�u���������1�a������������)������'�9�P�l���u���C�l�-�����g���F������ ��6�v�����J���B�d����r����������&�2�I�������n���������$�U�p������K�u������c�t���������.�I�~��������:�Z���#�Q�l�������p��������!�H�\�|�������/�k����������?�j��������E�q��������%�7�T�g�~�����V�z�������'�w�������1�N�����?�z�������9�z�����,�X�����X�������\�����1�\������� �I����� ��J��������;������� �2�e�n�����������������$�v������Q�c����7�����f���������������>�S��`����������� �"�m���i������N�}��� �n���S������_�����i����<�p������g��� �C�\�����L�j�x������:�l���������)_�8u,g���Oh��=d���� H X � � �  & � � 7 �   R k � � ? T � �+���8p������U��(z���'��� f�U��:��T��I�u�:C_�� D S t �!W"�"�"�"G#�#N$t$a%�%�%&O'�'�'+(�(�(Z)�)t*!+h+�+ ,;,�,�,H-�-7..�.�/0"0�0�0�1�12r2�2�23M3c3�3�3404�4�4�435�5�5l6�6&7U7�7�7�7S8j8�9�9:t:�:�;�;0<U<�<�<�<=E=�=>.>�>�>c?v?�?@:@�@�@A3AQA�A�A(Bouo�op�p^quq�qr�r�r�r�rs&s�s�s?tLt�t�t�t�t�u�u�uvSv�v x;xix�x�x y(y^y}y'zZzkz�z�z{�{�{�{@|N|e|�|�|�|}0}Z}�}*~j~�~�~?��� �H���ր���� �r�ۃ�� �t���Ä��(�Y�j������b�����_������)�J����R�c�y���ъ��-�b�������B�� �&�W�,�q���Ȏ�� �j���Ə�?�p���ϐ������|�������-�>�����ה�#�[���̕��˖� �o�����Y����M����7��0�F�̛�����ٜ��,�q�$����� �k�˟*����������^�q������&�E�~����6�T���7�z�����ܥ/���Ѧc���ҧ?�p����7�p�ݩ �)�R���ժ�=�t����&�k����� �;�\�����ױ�6�Ų������г���O�����ִ��(���ε� �Q�Ŷ�� �L�{���!�3�c���ĸ?�r�ɹ��3����4�e�t�ϻ�Z�|�����ټ�`������=�_������B���2�^�k�����c�J� �S�)�P���7�h���(�W����������-�\������d�������7�k�}���;�k�������[��������@�o�����N�������t������z������$�G�o������O�r��������U���������*�C�r�������k��� �q������;������� �����������1�I�����Q����������+�9��� �P���'�{��,�P��������b���L�{�������,�:�g�����+�g�������\�������\����"���3�����$�W�����v�����M�������� �O�q��'�n����;�^������1�z������\�m������@����9�t���������!�����������(�j����� �#�X�������*H�� �6Kb��M�����,F���QkKs��3 J � J  ^ � ( > k � 8��3z� !P��@� ~��r��"8�M��*u���� 6y�x-� &��;�`� % f � &!O!a!�!�!�!"*"�"�" #�#�#�#�#E$�$�$%U%i%�%&_&�&�&�&�'�'�'(((0(�(�({)�)�)*/*#+^-�-�-.�.�./Q/|/�/�/*0\0�0�0�0�0�0�0121q2�2�2%3=3v3�3�34Z4�4�4�4�4�4535M5k5�5�5�5696R6�6�6�6�6�67+7=7O7�7�7�7�7 88)8?8x8�8�8�8�8�9 :0:�:�:,;c;�;�;�;<<A<O<q<�<=[=�=�= >@>�>�>�>?_?}?�?�?�? @9@a@�@�@A7AHA�A�A B)BPBoB�B�BC9CoC�C�C�C�C DID|D�D�D�D�D1EL�L�L�L�L)MKMlM�M�M�M�MN>NRNwN�N�N�O�O�O�O�O�O P#P9P�P�P�P�P&QVQmQQ�Q�Q�Q�Q�Q R.RBROR�R�R S7ScS�S�S�S�S@T�TU>U`UDV`V�V�V;WQWJX�Y�YY[�[�[Y\�\]�]�]S^�^�^J_�_�_�_`}`�`�`a/a\a�a�a.brb�bckc�cdUd�d�d@e}e�efdf�fgZgug�gh.hFh~h�h i`i�i�i7j�j�j�jKkuk�k�k�l�l�l�m�m0n�n�n'o[o�o�opsp�p�p qqGqWq�q�q�q�q�q r4rArcrur�r tYt�tku�u�uv�v�v5wXw�w�wxBx�x�x)y9y�y�y�z�zj{�{ |!|9}M}h}{}�~�~�~-Nx���w�����ۀ��2�_�������҂3�N������ �I�s������� �B�����х��5�~������ �-������Έ���щ�}�d�����؋���=�H�T�s�������njЌ���1�I�q�������ލ��� �I�P�^��� �G�{���ҏ�����ʑ� ����� �9�����ɓ���d�z�Ֆ�)�F���ח�R�a�{���͘��3�l���ʙ�-�F�V�t�����ܚ���:�L�e�������ț֛�� ��k�|���R���&�.�6�N�w�~�����Ξ՞ݞk����������$�M�X�����̡��ʢ��!�8�B�Q�l���������Ť���� �J�R�[���������� ���D�o�x����������,�E�O�o�~���������çͧا�0�G�r���������ʨبq�{���ǩت� ��-�Y�a�j�s�������ȫ*�U�^�n���ȬЬ�l�ͭ���3�b����&����Y��,�p�Ȳ��q��� �"�C�_������'������$�I���� �V�j������+�l����K�e����,�^�ɻte:theNSDatetell (current date) to set {theASDate, year, day, i_support's throwInvalidParameterIndex(a reference to item endIndex of (get listObject's _list_), "to item")else if endIndex = 0 or endIndex > listLength then_support's throwInvalidParameterIndex(a reference to item startIndex of (get listObject's _list_), "from item")if endIndex < 0 then set endIndex to listLength + 1 + endIndexset endIndex to listLengthset endIndex to startIndex_support's throwInvalidParameterIndex(a reference to item startIndex of (get listObject's _list_), "item")if startIndex = 0 or startIndex > listLength thenif startIndex < 0 then set startIndex to listLength + 1 + startIndexset startIndex to _support's asIntegerParameter(theIndex, "item")if startIndex is missing value and endIndex is missing value thenif endIndex is not missing value then set endIndex to _support's asIntegerParameter(endIndex, "to item")if startIndex is not missing value then set startIndex to _support's asIntegerParameter(startIndex, "from item")set listLength to listObject's _list_'s lengthto delete from list theList item theIndex : (-1) from item startIndex : (missing value) to item endIndex : (missing value)end insert into list_error("insert into list", eText, eNumber, eFrom, eTo)return (items 1 thru afterIndex of listObject's _list_) & theValue & (items (afterIndex + 1) thru -1 of listObject's _list_)return listObject's _list_ & theValueelse if afterIndex = listObject's _list_'s length thenreturn theValue & listObject's _list_if afterIndex = 0 thenreturn theList & theValueelse -- if no insertion index is specified, the default behavior is to append to list_support's throwInvalidParameterIndex(a reference to before item beforeIndex of (get listObject's _list_), "before item")if afterIndex > (listObject's _list_'s length) or afterIndex < 0 thenset afterIndex to listObject's _list_'s lengthelse -- `before item 0`set afterIndex to (listObject's _list_'s length) + beforeIndexelse if beforeIndex < 0 thenset afterIndex to beforeIndex - 1if beforeIndex > 0 thenset beforeIndex to _support's asIntegerParameter(beforeIndex, "before item")else if beforeIndex is not missing value then -- insert before specified index_support's throwInvalidParameterIndex(a reference to after item afterIndex of (get listObject's _list_), "after item")if afterIndex > (listObject's _list_'s length) thenif afterIndex < 0 then set afterIndex to (listObject's _list_'s length) + afterIndex + 1set isJoin to _support's asBooleanParameter(isJoin, "concatenation")set afterIndex to _support's asIntegerParameter(afterIndex, "after item")if beforeIndex is not missing value then error "Expected ‘before item’ OR ‘after item’ parameter, but received both." number -1703if afterIndex is not missing value then -- insert after specified indexif not isJoin or (count {theValue} each list) = 0 then set theValue to {theValue}to insert into list theList value theValue before item beforeIndex : (missing value) after item afterIndex : (missing value) concatenation isJoin : (false)end _makeListObjectif listObject's _list_'s length > len then set listObject's _list_ to items 1 thru len of listObject's _list_set listObject's _list_ to listObject's _list_ & listObject's _list_repeat while listObject's _list_'s length < lenset listObject's _list_ to {padValue, padValue, padValue, padValue}if len > 0 thento _makeListObject(len, padValue) -- make a new list of specified length using the supplied value as padding; caution: padValue will not be copied, so should be an immutable type (e.g. number, string, constant; not date/list/record/script/reference)end _errorWithPartialResult_support's rethrowError("List", handlerName, eText, eNumber, eFrom, eTo, missing value, ePartial)to _errorWithPartialResult(handlerName, eText, eNumber, eFrom, eTo, ePartial)_errorWithPartialResult(handlerName, eText, eNumber, eFrom, eTo, missing value)end logb_error("logb", eText, eNumber, eFrom, eTo)return _logn(x as number) / (_logn(b as number))to logb x base bend log10_error("log10", eText, eNumber, eFrom, eTo)return (_logn(x as number) / 2.302585092994) * 300.0 / 300.000000000006 -- correct for minor driftto log10 xend logn_error("logn", eText, eNumber, eFrom, eTo)return _logn(x as number)to logn xend _lognreturn zif e ≠ 0 then set z to z + e * 0.693359375set z to x + yset y to y - (z / 2)set y to y - e * 2.12194440054691E-4if e ≠ 0 thenset y to x * z * (((((1.01875663804581E-4 * x + 0.497494994977) * x + 4.705791198789) * x + 14.498922534161) * x + 17.936867850782) * x + 7.708387337559) / (((((x + 11.287358718917) * x + 45.227914583753) * x + 82.987526691278) * x + 71.154475061856) * x + 23.125162012677)set x to 2 * x - 1set z to z - y * 2.12194440054691E-4 + x + e * 0.693359375set y to eset z to x * z * ((-0.789580278885 * z + 16.386664569956) * z - 64.140995295872) / (((z - 35.672279825632) * z + 312.093766372244) * z - 769.69194355046)set z to x * xset x to z / yset y to 0.5 * x + 0.5set z to x - 1set y to 0.5 * z + 0.5set z to x - 0.5if x < 0.707106781187 then -- (2 ^ 0.5) / 2if e < -2 or e > 2 thenset {x, e} to _frexp(x)if x ≤ 0 then error "Invalid number (must be >0)." number -1703to _logn(x)end _frexpreturn {m, e}set e to e - 1set m to m * 2set e to e + 1set m to m / 2if m ≥ 1 thenrepeat until m ≥ 0.5 and m < 1set e to 0if isNeg then set m to -mset isNeg to m < 0if m is 0 then return {0.0, 0}to _frexp(m)end atanh_error("atanh", eText, eNumber, eFrom, eTo)return (__e__ ^ x - __e__ ^ -x) / (__e__ ^ x + __e__ ^ -x)to atanh xend acosh_error("acosh", eText, eNumber, eFrom, eTo)return 0.5 * (__e__ ^ x + __e__ ^ -x)to acosh xend asinh_error("asinh", eText, eNumber, eFrom, eTo)return 0.5 * (__e__ ^ x - __e__ ^ -x)to asinh xend atan_error("atan", eText, eNumber, eFrom, eTo)return _asin(x / ((x * x + 1) ^ 0.5))to atan xend acos_error("acos", eText, eNumber, eFrom, eTo)return 90 - (_asin(x as number))to acos xend asin_error("asin", eText, eNumber, eFrom, eTo)return _asin(x as number)to asin xend _asinreturn z / (pi / 180)if isNeg then set z to -zset z to zz * (((((0.004253011369 * zz - 0.601959800801) * zz + 5.444622390565) * zz - 16.26247967211) * zz + 19.56261983318) * zz - 8.198089802485) / (((((zz - 14.740913729889) * zz + 70.496102808568) * zz - 147.179129223273) * zz + 139.510561465749) * zz - 49.188538814909) * x + xset zz to x * xset z to xelse if x < 1.0E-8 thenset z to z - zz + (pi / 4)set zz to zz * p - 6.12323399573677E-17set z to (pi / 4) - zzset zz to (zz + zz) ^ 0.5set p to zz * ((((0.002967721961 * zz - 0.563424278001) * zz + 6.968710824105) * zz - 25.569010496528) * zz + 28.536655482611) / ((((zz - 21.947795316429) * zz + 147.065635402681) * zz - 383.877095760369) * zz + 342.439865791308)set zz to 1 - xif x > 0.625 thenif x > 1 then error "Invalid number (not between -1.0 and 1.0)." number -1703 from xto _asin(x)_error("tan", eText, eNumber, eFrom, eTo)if z is 2 or z is 6 then set y to -1 / yset y to z2set y to z2 + z2 * zz * ((-1.30936939181384E+4 * zz + 1.15351664838587E+6) * zz - 1.79565251976485E+7) / ((((zz + 1.36812963470693E+4) * zz - 1.32089234440211E+6) * zz + 2.50083801823358E+7) * zz - 5.38695755929455E+7)if zz > 1.0E-14 thenset z2 to ((x - y * 0.785398155451) - y * 7.94662735614793E-9) - y * 3.06161699786838E-17set z to y - (y * 0.125 div 1) * 8set y to (x / (pi / 4)) div 1if x is 90 or x is 270 then error "Invalid number (result would be ∞)." number -2701 from x -- -2701 normally indicates divide-by-zero errorto tan xend cos_error("cos", eText, eNumber, eFrom, eTo)return _sin((x as number) + 90)to cos xend sin_error("sin", eText, eNumber, eFrom, eTo)return _sin(x as number)to sin xend _sinreturn yif isNeg then set y to -yset y to z2 + z2 * zz * (((((1.58962301576546E-10 * zz - 2.50507477628578E-8) * zz + 2.75573136213857E-6) * zz - 1.98412698295895E-4) * zz + 0.008333333333) * zz - 0.166666666667)set y to 1.0 - zz / 2 + zz * zz * (((((-1.13585365213877E-11 * zz + 2.08757008419747E-9) * zz - 2.75573141792967E-7) * zz + 2.48015872888517E-5) * zz - 0.001388888889) * zz + 0.041666666667)if z is 1 or z is 2 thenset zz to z2 * z2set z2 to ((x - y * 0.785398125648) - y * 3.77489470793E-8) - y * 2.695151429079E-15set z to z - 4set isNeg to not isNegif z > 3 thenset z to z mod 8set y to y + 1set z to z + 1if z mod 2 is 1 thenset z to y - (y * 0.0625 div 1) * 16set y to (x * (4 / pi)) div 1if isNeg then set x to -xset isNeg to x < 0set x to (x mod 360) * (pi / 180) -- convert from degrees to radiansto _sin(x)end round number_error("round number", eText, eNumber, eFrom, eTo)return num / theMultiplierreturn num div theMultiplierelse if decimalPlaces < 0 thenreturn num div 1if decimalPlaces = 0 then_support's throwInvalidConstantParameter(roundingDirection, "by")if num > 0 or num mod 100 = 0 thenelse if roundingDirection is (rounding down) then -- floor()if num < 0 or num mod 100 = 0 thenelse if roundingDirection is (rounding up) then -- ceil()else if num > 0 thenif num mod 100 = 0 thenelse if roundingDirection is (rounding away from zero) thenelse if roundingDirection is (rounding toward zero) thenset num to num div 100 - 1set num to num div 100 + 1if num > 0 thenelse if roundingDirection is (rounding halves away from zero) thenelse if num > 0 then -- else round to nearest whole digitif {num mod 100} is in {-50, 50} then -- if num ends in .5 then round towards zeroelse if roundingDirection is (rounding halves toward zero) thenset num to (num - 50) div 100else -- (…or down if negative to give an even result)set num to (num + 50) div 100else if num > 0 then -- else round to nearest whole digit (.5 will round up if positive…)set num to num div 100if {(num / 2) mod 100} is in {-25, 25} then -- if num ends in .5 and its div is even then round toward zero so it stays evenif roundingDirection is (rounding halves to even) thenset num to num * 100 * theMultiplier -- multiplying and dividing by 100 before and after applying the multiplier helps avoid poor rounding results for some numbers due to inevitable loss of precision in floating-point math (e.g. `324.21 * 100 div 1 / 100` returns 324.2 but needs to be 324.21), though this hasn't been tested on all possible values for obvious reasons -- TO DO: shouldn't /10 be done after rounding is applied (in which case following calculations should use mod 10, etc)?set theMultiplier to 10 ^ decimalPlacesif decimalPlaces ≠ 0 thenset decimalPlaces to _support's asIntegerParameter(decimalPlaces, "to places")set num to _support's asRealParameter(num, "")to round number num to places decimalPlaces : (0) by roundingDirection : (rounding halves to even)_error("max", eText, eNumber, eFrom, eTo)_support's throwInvalidParameter(a reference to item i of theList, "", number, "List item is wrong type: " & eText)on error eText number -1700if n > theResult then set theResult to nto max theList_error("min", eText, eNumber, eFrom, eTo)_support's throwInvalidParameter(a reference to item i of theList, "", number, "List item is wrong type: " & eText) -- note: AS doesn't provide a meaningful reference when `repeat with aRef in listObject's _list_` is used (e.g. `item 2 of _list_`), so to provide useful error messages a counting loop is used and a readable reference constructed using that (e.g. `item 2 of {3, "x"}`)on error eText number -1700 -- couldn't coerce an item to numberif n < theResult then set theResult to nset n to listObject's _list_'s item i as numberrepeat with i from 1 to listObject's _list_'s lengthset theResult to (item 1 of listObject's _list_) as numberif listObject's _list_'s length = 0 then _support's throwInvalidParameter(theList, "", list, "List can’t be empty.")property _list_ : _support's asListParameter(theList, "")to min theListend cmp_error("cmp", eText, eNumber, eFrom, eTo)return 1return -1if n1 < n2 thenif d > dm and d < dn then return 0if dm > dn then set {dn, dm} to {dm, dn}set dm to -dnset dn to _isEqualDelta * n1set dn to _isEqualDelta * n2set {n1, n2} to {n1 as real, n2 as real}if n1 = n2 then return 0if (count {n1, n2} each integer) = 2 thento cmp {n1, n2}_error("abs", eText, eNumber, eFrom, eTo)return -xset x to x as numberto abs xend rad2deg_error("degrees", eText, eNumber, eFrom, eTo)return (x as real) / (pi / 180)to rad2deg xend deg2rad_error("radians", eText, eNumber, eFrom, eTo)return (x as real) * (pi / 180)to deg2rad xend parse hex_error("parse hex", eText, eNumber, eFrom, eTo)return resultList's _list_set end of resultList's _list_ to theNumberif isPrecise and (theNumber = theNumber + 1) then _support's throwInvalidParameter(a reference to text i thru (i + chunkSize - 1) of hexText, "", text, "Hexadecimal text is too large to convert to number without losing precision.")if i = 0 then _support's throwInvalidParameter(hexText, "", text, "Text is not a valid hexadecimal number.")repeat with charRef in hexText's text i thru (i + chunkSize - 1)repeat with i from 1 to hexText's length by chunkSizeif (hexText's length) mod chunkSize ≠ 0 then _support's throwInvalidParameter(hexText, "", text, "Can't split hexadecimal text exactly into " & chunkSize & "-digit chunks.")else -- read as list of numbersif isNegative then set theNumber to -theNumberif isPrecise and (theNumber = theNumber + 1) then _support's throwInvalidParameter(hexText, "", text, "Hexadecimal text is too large to represent as a real number without losing precision.")_support's throwInvalidParameter(hexText, "", text, "Text is not a valid hexadecimal number.")on error number -1728 -- catch errors if hexText is too short or contains non-hex charsset theNumber to theNumber + i - 1if i = 0 then error number -1728set i to offset of charRef in "0123456789ABCDEF"set theNumber to theNumber * 16repeat with charRef in hexTextif hexText starts with "0x" then set hexText to text 3 thru -1 of hexTextif isNegative then set hexText to text 2 thru -1 of hexTextset isNegative to hexText starts with "-"set theNumber to 0if chunkSize = 0 then -- read as single numberset isPrecise to not _support's asBooleanParameter(isPrecise, "precision loss")set hexText to _support's asTextParameter(hexText, "")to parse hex hexText width chunkSize : (0) precision loss isPrecise : (false)end format hex_error("format hex", eText, eNumber, eFrom, eTo)return hexTextset hexText to resultList's _list_ as textset hexText to "0x" & resultList's _list_if hasPrefix thenset resultList's _list_'s item i to (padText & hexText)'s text -chunkSize thru -1set theInteger to theInteger div 16set hexText to (item (theInteger mod 16 + 1) of "0123456789ABCDEF") & hexTextrepeat while theInteger > 0_support's throwInvalidParameter(a reference to resultList's _list_'s item i, "", integer, eText)set eText to "Not a non-negative, non-fractional number."set eText to "Number is too large to represent as " & chunkSize & "-digit hexadecimal text (not between 0 and " & (16 ^ chunkSize - 1) div 1 & ")."if theInteger > maxSize thenif theInteger ≠ theNumber as real or theInteger < 0 or theInteger > maxSize then error number -1700set theInteger to theNumber as integerset theNumber to resultList's _list_'s item irepeat with i from 1 to resultList's _list_'s lengthproperty _list_ : theNumber's itemsset padText to padText & "0"repeat chunkSize timesset {padText, maxSize} to {"", 16 ^ chunkSize - 1}if chunkSize < 1 or chunkSize > 1024 then _support's throwInvalidParameter(chunkSize, "width", integer, "Must be an integer between 1 and 1024.") -- chunksize must be givenelse -- format list of numberreturn hexPrefix & hexTextset hexText to "0" & hexTextrepeat while length of hexText < chunkSizeset theNumber to theNumber div 16set hexText to (item (theNumber mod 16 + 1) of "0123456789ABCDEF") & hexTextrepeat while theNumber > 0if hasPrefix then set hexPrefix to hexPrefix & "0x"if chunkSize > 0 and (theNumber > 16 ^ chunkSize - 1) then _support's throwInvalidParameter(theNumber, "", integer, "Number is too large to represent as " & chunkSize & "-digit hexadecimal text (not between " & -(16 ^ chunkSize) div 1 & " and " & (16 ^ chunkSize - 1) div 1 & ").")set hexPrefix to ""set theNumber to -theNumberset hexPrefix to "-"if chunkSize > 0 and (theNumber < -(16 ^ chunkSize)) then _support's throwInvalidParameter(theNumber, "", integer, "Number is too large to represent as " & chunkSize & "-digit hexadecimal text (not between " & -(16 ^ chunkSize) div 1 & " and " & (16 ^ chunkSize - 1) div 1 & ").")if theNumber < 0 thenset hexText to ""if chunkSize < 0 or chunkSize > 1024 then _support's throwInvalidParameter(chunkSize, "width", integer, "Must be an integer between 0 and 1024.")set theNumber to _support's asWholeNumberParameter(theNumber, "") -- numbers greater than 2^30 (max integer size) are okay as long as they're non-fractionalif (count {theNumber} each list) = 0 then -- format single numberset hasPrefix to _support's asBooleanParameter(hasPrefix, "prefix") -- (users shouldn't concatenate their own prefix as that would result in negative numbers appearing as "0x-N…" instead of "-0xN…")set chunkSize to _support's asIntegerParameter(chunkSize, "width")to format hex theNumber width chunkSize : (0) prefix hasPrefix : (false)end parse number_error("parse number", eText, eNumber, eFrom, eTo)return asocNumber as anyerror ("Invalid text (expected numerical text in " & _nameForFormat(formatStyle) & " format for " & localeIdentifier & " locale).") number -1703 from theTextset localeIdentifier to "the “" & localeIdentifier & "”"set localeIdentifier to "no"if localeIdentifier's length = 0 then -- empty string = system localeset localeIdentifier to asocFormatter's locale()'s localeIdentifier() as textif asocNumber is missing value thenset asocNumber to asocFormatter's numberFromString:theTextset asocFormatter to _makeNumberFormatter(formatStyle, localeCode, missing value)if (count {theText} each text) = 0 then _support's throwInvalidParameterType(theText, "", text, "text") -- only accept text, for same reason as aboveto parse number theText using formatStyle : (canonical number format) for locale localeCode : ("none")end format number_error("format number", eText, eNumber, eFrom, eTo)if asocString is missing value then error "Invalid number (conversion failed)." number -1703 from theNumber -- shouldn't fail, but -stringFromNumber:'s return type isn't declared as non-nullable so check to be sureset asocString to asocFormatter's stringFromNumber:theNumberset asocFormatter to _makeNumberFormatter(formatStyle, localeCode, theNumber)if (count {theNumber} each number) = 0 then _support's throwInvalidParameterType(theNumber, "", number, "number") -- only accept integer or real types (i.e. allowing a text parameter to be coerced to number would defeat the purpose of these handlers, which is to avoid unintended localization behavior)to format number theNumber using formatStyle : (canonical number format) for locale localeCode : ("none")end _nameForFormatreturn "“" & formatStyle & "”"return "word"else if formatStyle is word format thenreturn "scientific"else if formatStyle is scientific format thenreturn "percent"else if formatStyle is percent format thenreturn "currency"else if formatStyle is currency format thenreturn "decimal"else if formatStyle is decimal format thenreturn "integer"if formatStyle is integer format thento _nameForFormat(formatStyle) -- used for error reporting; formatStyle is either constant or textend _setBasicFormaterror "Invalid ‘basic format’ property: not an allowed constant." number -1703 from formatName to constantasocFormatter's setFormat:formatNameelse if (count {formatName} each text) ≠ 0 thenasocFormatter's setNumberStyle:(current application's NSNumberFormatterSpellOutStyle)else if formatName is word format then -- uses wordsasocFormatter's setNumberStyle:(current application's NSNumberFormatterPercentStyle)else if formatName is percent format then -- multiplies by 100 and appends '%'asocFormatter's setNumberStyle:(current application's NSNumberFormatterCurrencyStyle)else if formatName is currency format then -- adds currency symbolelse if formatName is decimal format then -- uses thousands separators by default, no exponentelse if formatName is integer format then -- uses plain integer notation (caution: do not use for reals unless rounding to whole number is intended)else if formatName is scientific format then -- uses exponent notationasocFormatter's setMaximumFractionDigits:999asocFormatter's setFormat:"#.0#E+0" -- for consistency with AS, include '+' in positive exponents (oddly, there doesn't appear to be a property on formatter for setting this)else -- format real as scientificasocFormatter's setMaximumFractionDigits:999 -- kludge; see note belowasocFormatter's setMinimumFractionDigits:1asocFormatter's setNumberStyle:(current application's NSNumberFormatterDecimalStyle)or theNumber = 0 then -- format real as decimalor (_minDecimalRange < theNumber and theNumber < _maxDecimalRange) ¬else if (-_maxDecimalRange < theNumber and theNumber < -_minDecimalRange) ¬asocFormatter's setNumberStyle:(current application's NSNumberFormatterNoStyle)if theNumber's class is integer then -- format integerelse -- formatting switches between notations depending on number's type and valueasocFormatter's setNumberStyle:(current application's NSNumberFormatterScientificStyle)if theNumber is missing value then -- parsing always recognizes scientific notation by defaultif formatName is canonical number format thento _setBasicFormat(asocFormatter, formatName, theNumber)end _makeNumberFormatterreturn asocFormatterasocFormatter's setLocale:(_support's asNSLocaleParameter(localeCode, "for locale"))_support's throwInvalidParameter(formatStyle, "using", {record, constant}, eText)on error eText number -1703error "Not a ‘number format definition’ record or an allowed constant."_setBasicFormat(asocFormatter, formatStyle, theNumber)error "The ‘number format definition’ record’s ‘roundingBehavior’ is not an allowed constant." number -1703asocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundFloor)else if formatRecord's roundingBehavior is (rounding down) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundCeiling)else if formatRecord's roundingBehavior is (rounding up) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundUp)else if formatRecord's roundingBehavior is (rounding away from zero) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundDown)else if formatRecord's roundingBehavior is (rounding toward zero) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundHalfUp)else if formatRecord's roundingBehavior is (rounding halves away from zero) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundHalfDown)else if formatRecord's roundingBehavior is (rounding halves toward zero) thenasocFormatter's setRoundingMode:(current application's NSNumberFormatterRoundHalfEven)if formatRecord's roundingBehavior is (rounding halves to even) thenif formatRecord's roundingBehavior is not missing value thenerror "The ‘number format definition’ record’s ‘groupingSeparator’ property is not text." number -1703asocFormatter's setGroupingSeparator:sasocFormatter's setUsesGroupingSeparator:trueasocFormatter's setUsesGroupingSeparator:falseif s's length = 0 thenset s to formatRecord's groupingSeparator as textif formatRecord's groupingSeparator is not missing value thenerror "The ‘number format definition’ record’s ‘decimalSeparator’ property is not non-empty text." number -1703asocFormatter's setDecimalSeparator:sif s's length = 0 then error number -1703set s to formatRecord's decimalSeparator as textif formatRecord's decimalSeparator is not missing value thenasocFormatter's setMaximumSignificantDigits:_asIntegerProperty(formatRecord's maximumSignificantDigits, "maximumSignificantDigits", 0)if formatRecord's maximumSignificantDigits is not missing value thenasocFormatter's setUsesSignificantDigits:trueasocFormatter's setMinimumSignificantDigits:_asIntegerProperty(formatRecord's minimumSignificantDigits, "minimumSignificantDigits", 0)if formatRecord's minimumSignificantDigits is not missing value thenasocFormatter's setMaximumFractionDigits:_asIntegerProperty(formatRecord's maximumDecimalPlaces, "maximumDecimalPlaces", 0)if formatRecord's maximumDecimalPlaces is not missing value thenasocFormatter's setMaximumFractionDigits:999 -- kludge for NSNumberFormatterBug; see notes in _setBasicFormat() belowasocFormatter's setMinimumFractionDigits:_asIntegerProperty(formatRecord's minimumDecimalPlaces, "minimumDecimalPlaces", 0)if formatRecord's minimumDecimalPlaces is not missing value then_setBasicFormat(asocFormatter, formatRecord's basicFormat, theNumber)set formatRecord to _support's asOptionalRecordParameter(formatStyle, {class:(number format record), basicFormat:_support's RequiredValue, minimumDecimalPlaces:missing value, maximumDecimalPlaces:missing value, minimumSignificantDigits:missing value, maximumSignificantDigits:missing value, decimalSeparator:missing value, groupingSeparator:missing value, roundingBehavior:missing value}, "using")if (count {formatStyle} each record) = 1 thenset asocFormatter to current application's NSNumberFormatter's alloc()'s init() -- (note that while NSFormatter provides a global +setDefaultFormatterBehavior: option to change all NSNumberFormatters to use pre-10.4 behavior, we don't bother to call setFormatterBehavior: as it's very unlikely nowadays that a host process would change this)to _makeNumberFormatter(formatStyle, localeCode, theNumber) -- theNumber is either the number being formatted or `missing value` when parsing; determines appropriate formatting style based on number's type and value when `native format` is specifiedend _asIntegerPropertyerror "The ‘number format definition’ record’s ‘" & propertyName & "’ property is not a non-negative integer." number -1703on error number -1703if n ≠ theValue as real or n < minValue then error number -1703set n to theValue as integerto _asIntegerProperty(theValue, propertyName, minValue) -- note that this doesn't set an upper bound, though very large (silly) numbers may or may not work as intended, depending on what NSNumberFormatter decides to make of themproperty _maxDecimalRange : 1.0E+4property _minDecimalRange : 1.0E-3property _isEqualDelta : 1.0E-12 -- multiplier used by `cmp` to allow for slight differences due to floating point's limited precisionproperty __e__ : 2.71828182846 -- the mathematical constant e (natural logarithm base)_support's throwCommandError("Number", handlerName, eText, eNumber, eFrom, eTo)end timer objectset newObject's _isRunning to _isRunningset newObject's _totalSeconds to _totalSecondsset newObject's _startTime to _startTimeset newObject to timer object named nameTextreturn "«timer object (" & infoText & ")»"if nameText's length ≠ 0 then set infoText to "“" & nameText & "” " & infoTextset infoText to "total time: " & totalTime() & "s"set infoText to "elapsed time: " & elapsedTime() & "s"end totalTimereturn _totalSecondsreturn _totalSeconds + elapsedTime()to totalTime()end elapsedTimereturn (NSDate's timeIntervalSinceReferenceDate()) - _startTimeif _isRunning thento elapsedTime()end stopTimerreturn elapsedTimeset _isRunning to falseset _totalSeconds to _totalSeconds + elapsedTimeset elapsedTime to (current application's NSDate's timeIntervalSinceReferenceDate()) - _startTimeif not _isRunning then return 0to stopTimer()end startTimerset _startTime to current application's NSDate's timeIntervalSinceReferenceDate()set _isRunning to trueif _isRunning then returnto startTimer()end timerNamereturn nameTextto timerName()property _isRunning : falseproperty _totalSeconds : 0.0property _startTime : missing value -- because AS can't serialize ASOC objects when saving or autosaving scripts, this object stores start and end times as NSTimeInterval - i.e. AS real - rather than NSDate instances.script TimerObjectset nameText to _support's asTextParameter(nameText, "")to timer object named nameText : ("")end queue collectionset newObject's _back to newFrontset oldFront to oldFront's nextItemset newFront to tmpset newFront's nextItem to tmpset tmp to {v:oldFront's v, nextItem:missing value}repeat while oldFront is not missing valueset oldFront to _front's nextItemset newObject's _front to newFrontset newFront to {v:_front's v, nextItem:missing value}set newObject to queue collectionreturn "«queue collection (" & _count & " items)»"return v of _frontto getItem() -- return the value at the front of the queue without removing itset _front to missing valueset _back to missing valueif _front is missing value then set _back to missing valueset _front to nextItem of _frontset theValue to v of _frontif _front is missing value then error "Queue is empty." number -1728to removeItem() -- remove and return the value at the front of the queueif _front is missing value then set _front to _backset _back to nextItemif _back is not missing value then set nextItem of _back to nextItemset nextItem to {v:theValue, nextItem:missing value}_support's throwMethodError("Objects", "QueueCollection", handlerName, eText, eNumber, eFrom, eTo)property _front : missing valueproperty _back : missing valuescript QueueCollectionto queue collection -- First-In-First-Out sequenceend stack collectionset oldHead to oldHead's nextItemset newHead to tmpset newHead's nextItem to tmpset tmp to {v:oldHead's v, nextItem:missing value}repeat while oldHead is not missing valueset oldHead to _head's nextItemset newObject's _head to newHeadset newHead to {v:_head's v, nextItem:missing value}set newObject's _count to _countset newObject to stack collectionreturn "«stack collection (" & _count & " items)»"return v of _headto getItem() -- return the topmost value without removing itset _head to missing valueset _head to nextItem of _headset theValue to v of _headif _head is missing value then error "Stack is empty." number -1728to removeItem() -- remove and return the topmost valueset _head to {v:theValue, nextItem:_head}to addItem(theValue)_support's throwMethodError("Objects", "StackCollection", handlerName, eText, eNumber, eFrom, eTo)property _head : missing valuescript StackCollectionto stack collection -- Last-In-First-Out sequenceend dictionary collectionend getValuesset end of listObject's _list_ to myBucket's vto getValues()end getKeyscopy myBucket's k to end of listObject's _list_ -- make sure date keys are always copiedto getKeys()end getKeysAndValuesreturn listObject's _list_set myBucket to myBucket's nextItemset end of listObject's _list_ to {k, myBucket's v}copy myBucket's k to k -- make sure date keys are always copiedrepeat while myBucket is not missing valueset myBucket to bucketRef's contentsrepeat with bucketRef in my _bucketsto getKeysAndValues()end addKeysAndValues_error("addKeysAndValues", eText, eNumber, eFrom, eTo)error "Not a valid key-value pair." number n from aRefon error number naddItem(keyValue's item 1, keyValue's item 2)if (count {keyValue} each list) = 0 or keyValue's length ≠ 2 then error number -1700set keyValue to aRef's contentsrepeat with aRef in listObject's _list_property _list_ : keyValueListscript listObjectif (count {keyValueList} each list) = 0 then error "Not a valid key-value list." number -1700 from keyValueListto addKeysAndValues(keyValueList) -- list of form {{KEY,VALUE},...}end addDictionary_error("addDictionary", eText, eNumber, eFrom, eTo)set tmp to tmp's nextItemset tmp's nextItem to {k:otherBucket's k, v:otherBucket's v, nextItem:missing value}else if tmp's nextItem is missing value then -- appendset tmp's {k, v} to otherBucket's {k, v}if tmp's k is otherBucket's k then -- replaceset tmp to myBucketrepeat while otherBucket is not missing valueelse -- …by merging into this dictionary's existing bucketset myBucket to tmpset myBucket's nextItem to tmpset tmp to {k:otherBucket's k, v:otherBucket's v, nextItem:missing value}set otherBucket to nextItem of otherBucketrepeat while nextItem of otherBucket is not missing valueset item i of my _buckets to myBucketset myBucket to {k:otherBucket's k, v:otherBucket's v, nextItem:missing value}if myBucket is missing value then -- …by shallow copyset myBucket to item i of my _bucketsif otherBucket is not missing value then -- transfer other dictionary's bucket…set otherBucket to item i of dictionaryObject's _bucketsrepeat with i from 1 to length of dictionaryObject's _bucketsif length of my _buckets ≠ length of dictionaryObject's _buckets then error "Mismatched bucket lists." -- sanity check, as aboveif dictionaryObject's countItems() > 0 thento addDictionary(dictionaryObject)end copyObject_error("copyObject", eText, eNumber, eFrom, eTo)return newObjectset newBucket to tmpset newBucket's nextItem to tmpset tmp to {k:oldBucket's k, v:oldBucket's v, nextItem:missing value}set oldBucket to nextItem of oldBucketrepeat while nextItem of oldBucket is not missing valueset item i of newObject's _buckets to newBucketset newBucket to {k:oldBucket's k, v:oldBucket's v, nextItem:missing value}if oldBucket is not missing value then -- shallow copy the linked list and add it new newObject's bucket list at the same positionset oldBucket to item i of my _bucketsrepeat with i from 1 to length of my _bucketsif length of my _buckets ≠ length of newObject's _buckets then error "Mismatched bucket lists." -- sanity check as this copyObject() implementation requires all bucket lists to be same length, and will need revised if growable bucket lists are supported in futureif _count > 0 thenset newObject to dictionary collectionto copyObject()end objectDescriptionreturn "«dictionary collection (" & _count & " items)»"to objectDescription()end containsItemgetItem(theKey)to containsItem(theKey)end getItem_error("getItem", eText, eNumber, eFrom, eTo)if k of foundItem is theKey then return v of foundItemset foundItem to item _keyIndex(theKey) of my _bucketsto getItem(theKey)end deleteAllItemsset _count to 0set _size to length of my _bucketsset my _buckets to _makeEmptyList(1024)to deleteAllItems()end removeItem_error("removeItem", eText, eNumber, eFrom, eTo)error "Item not found." number -1728 from theKeyset prevItem to foundItemreturn theValue -- return the removed valueset _count to _count - 1set nextItem of prevItem to nextItem of foundItemset item keyIndex of my _buckets to nextItem of foundItemif prevItem is missing value thenset theValue to v of foundItemif foundKey is theKey thenset foundKey to k of foundItemrepeat while foundItem is not missing valueset prevItem to missing valueto removeItem(theKey)end addItem_error("addItem", eText, eNumber, eFrom, eTo)set foundItem to nextItem of foundItemset nextItem of foundItem to {k:theKey, v:theValue, nextItem:missing value}if nextItem of foundItem is missing value then -- insert new itemset {k of foundItem, v of foundItem} to {theKey, theValue}set oldValue to v of foundItemif k of foundItem is theKey then -- replace existing itemset _count to _count + 1set item keyIndex of my _buckets to {k:theKey, v:theValue, nextItem:missing value}if foundItem is missing value then -- insert new itemset foundItem to item keyIndex of my _bucketscopy theKey to theKey -- while dates can be used as keys, it's essential that keys stored in linked lists are never mutated so they must be copied first (this is a no-op for text, numbers, and other immutable types, while other types for which copying is problematic, e.g. script objects, are already forbidden as keys)set keyIndex to _keyIndex(theKey)to addItem(theKey, theValue)end countItemsreturn _countto countItems()end _keyIndexreturn hashNum mod _size + 1if hashNum > 1.12589990684262E+15 then set hashNum to hashNum div 4096error "Invalid key type." number -1703 from theKeyset hashNum to _support's asNSObject(theKey)'s timeIntervalSinceReferenceDate()else if theKey's class is date thenif hashNum < 1.0E+200 then set hashNum to hashNum * 67128023if hashNum < 0 then set hashNum to -hashNumif divNum ≠ 0 then set hashNum to hashNum - 1 / divNumset divNum to theKey mod 1set hashNum to theKeyelse if {theKey's class} is in {integer, real} then -- note: integers and reals that are numerically equal must always produce same hash, since the linked list lookup compares integer and real keys for numeric equality (e.g. 1 = 1.0)set hashNum to _support's asNormalizedNSString(theKey as text)'s hash()if theKey's class is text thenset hashNum to _support's asNSObject(theKey)'s typeCodeValue()if {theKey's class} is in {type, class, constant} then -- caution: coercing a type class or constant symbol to text is problematic, as the resulting string may contain either its literal name or its raw four-char code depending on the terminology available at the time (furthermore, terminology conflicts and synonyms may cause its literal name to change); to avoid these problems, it's better to send the value over the ASOC to convert it to an NSAppleEventDescriptor, from which its raw four-char code can be obtained as an Int32 which can be safely used as its hashNumif (count {theKey} each specifier) ≠ 0 or (count {theKey} each record) ≠ 0 or (count {theKey} each script) ≠ 0 then error "Invalid key type." number -1703 from theKey -- explicitly disallow types that can redefine their `class` propertiesto _keyIndex(theKey)_support's throwMethodError("Objects", "DictionaryCollection", handlerName, eText, eNumber, eFrom, eTo)property _count : 0property _size : length of my _bucketsproperty _buckets : _makeEmptyList(1024) -- DictionaryCollections currently use a fixed-size bucket list (2^10=1024 items seems to be a reasonable default)script DictionaryCollectionto dictionary collection -- key-value collection, analogous to NSMutableDictionary (note: keys must be text, or objects that reliably coerce to text)end _makeEmptyListreturn lset n to n div 2set l to l & lrepeat while n > 1set l to {missing value}to _makeEmptyList(n) -- make a list of size n where n is a power of two, e.g. _makeBucketList(1024) returns a 1024 (2^10) item list (other values of n are rounded down automatically, e.g. n=1000 gives a 512-item list)_support's throwCommandError("Objects", handlerName, eText, eNumber, eFrom, eTo)end run unit tests_error("run unit tests", eText, eNumber, eFrom, eTo)& (quoted form of _support's asPOSIXPathParameter(testFile, "")) without altering line endingsreturn do shell script (quoted form of POSIX path of (unit test runner)) & space ¬on run unit tests testFile -- e.g. for running tests in Script Editorend unit test runner_error("unit test runner", eText, eNumber, eFrom, eTo)error "A resource wasn’t found." number -192on error number -2763 -- returned 'nothing' instead of raising 'resource not found' error (very odd)return (path to resource "osatest" in directory "bin") as «class furl»try -- shouldn't fail unless TestTools library has been incorrectly builtto unit test runnerend assert test failed_genericAssert("assert test failed", false, actualResult, userNote)to assert test failed for actualResult : («class ¡ÑØ!») note userNote : ("") -- TO DO: optional param for passing expected result?end assert test passed_genericAssert("assert test passed", true, actualResult, userNote)to assert test passed for actualResult : («class ¡ÑØ!») note userNote : ("") -- TO DO: optional param for passing expected result?end _genericAssert_testReport's addFailure(assertName, "", userNote, testData)_testReport's addSuccess(assertName, userNote, testData)if didSucceed thenset testData to {{"actual result", actualResult}}set testData to {}if actualResult is «class ¡ÑØ!» then_testReport's addBroken(assertName, "received bad parameters", userNote, ¬if _suiteObject is missing value then error "Cannot use ‘" & assertName & "’ outside of unit tests." number -1708to _genericAssert(assertName, didSucceed, actualResult, userNote)end assert test error_testReport's addFailure("assert test error", problemType, userNote, testData)if actualResult is not _TestSupport's NoValue then set {problemType, testData} to {"received no error", {{"unexpected result", actualResult}, {"expected error", expectedError}}}if actualError is not _TestSupport's NoValue then set {problemType, testData} to {"received incorrect error", {{"actual error", actualError}, {"expected error", expectedError}}}set actualResult to _TestSupport's NoValue -- ... in which case replace it with a 'no value placeholder' object that AS can actually seeset actualResult to actualResult -- this variable lookup fails if call_NAME returned nothing (i.e. `null`, which AS literally treats as 'no value at all')...try -- kludge-around for AS's dumb commands-are-not-expressions-so-do-not-have-to-return-results designelse -- raised wrong error or didn't raise an error_testReport's addSuccess("assert test error", userNote, {{"actual error", actualError}, {"expected error", expectedError}})if isEqual then -- successset isEqual to _asCheckObjectResult(_compareAssertResults(checkObject, expectedError, actualError, "assert test error", userNote))set actualError to _TestSupport's makeCaughtErrorRecord(eText, eNumber, eFrom, eTo, ePartial)set actualResult to callObject's callHandler(_suiteObject, parameterValue) -- note: this may return literal 'no value' due to AS's schlonky design - this will be accounted for belowset {actualError, actualResult, isEqual} to {_TestSupport's NoValue, _TestSupport's NoValue, false} -- TO DO: rename isEqual to isSuccess once 'is equal' test code is moved to Check objectset callObject to _TestSupport's makeCallObject(callHandlerName, 1)set callObject to _TestSupport's makeCallObject(callHandlerName, 0)if parameterValue is «class ¡ÑØ!» thenset callHandlerName to "call_" & callHandlerNameelse if callHandlerName does not start with "call_" thenset callHandlerName to "call" & (text 5 thru -1 of _testHandlerName) -- if `for` parameter is omitted, automatically call a `call_NAME` handler with the same NAME as the `test_NAME` handlerif callHandlerName is "" then_testReport's addBroken("assert test error", "received bad parameters", userNote, ¬set checkObject to _asCheckObjectParameter(checkObject, _defaultErrorCheck)set expectedError to _TestSupport's normalizeExpectedErrorRecord(expectedError)set expectedError to _support's asRecordParameter(expectedError, "is")set callHandlerName to _support's asTextParameter(callHandlerName, "in")if _suiteObject is missing value then error "Cannot use ‘assert test error’ outside of unit tests." number -1708to assert test error in callHandlerName : ("") for parameterValue : («class ¡ÑØ!») is expectedError note userNote : ("") using checkObject : (missing value)end assert test result_testReport's addFailure("assert test result", "received incorrect result", userNote, testData)_testReport's addSuccess("assert test result", userNote, testData)if isEqual thenset testData to {{"actual result", actualResult}, {"expected result", expectedResult}}set isEqual to _asCheckObjectResult(_compareAssertResults(checkObject, expectedResult, actualResult, "assert test result", userNote)){{"unexpected error", _TestSupport's makeCaughtErrorRecord(eText, eNumber, eFrom, eTo, ePartial)}, {"expected result", expectedResult}})_testReport's addBroken("assert test result", "received bad parameters", userNote, ¬set userNote to _support's asTextParameter(userNote, "note")if _suiteObject is missing value then error "Cannot use ‘assert test result’ outside of unit tests." number -1708to assert test result for actualResult is expectedResult note userNote : ("") using checkObject : (missing value)end _compareAssertResultserror number _AbortedAssertionError from _AbortedAssertionToken_testReport's addBroken(assertName, "broke due to error in check object", userNote, ¬return checkObject's compareObjects(expectedResult, actualResult)to _compareAssertResults(checkObject, expectedResult, actualResult, assertName, userNote)property _defaultErrorCheck : exact error checkend exact error checkif checkObject's compareObjects(expectedProperty, actualProperty) is false then return falseif expectedProperty is not _TestSupport's NoValue thenset {expectedProperty, actualProperty, checkObject} to contents of aRef{expectedError's partialResult, actualError's partialResult, partialResult of checkObjects} ¬{expectedError's toType, actualError's toType, toType of checkObjects}, ¬{expectedError's fromValue, actualError's fromValue, fromValue of checkObjects}, ¬{expectedError's errorMessage, actualError's errorMessage, errorMessage of checkObjects}, ¬repeat with aRef in {¬ {expectedError's errorNumber, actualError's errorNumber, errorNumber of checkObjects}, ¬to compareObjects(expectedError, actualError)script ExactErrorCheck_error("exact error check", eText, eNumber, eFrom, eTo)if length of checkObjects ≠ length of defaultErrorAttributeChecks then error "Invalid ‘using’ parameter (record contains one or more unrecognized properties)." number -1703 from errorAttributeChecks -- (note: this doesn't bother to check each property's type or that each object has a ‘compareObjects’ handler as any problems there will raise errors if/when those error attributes are checked)set checkObjects to errorAttributeChecks & defaultErrorAttributeChecksset defaultErrorAttributeChecks to {errorMessage:_defaultEqualityCheck, errorNumber:_defaultEqualityCheck, fromValue:_defaultEqualityCheck, toType:_defaultEqualityCheck, partialResult:_defaultEqualityCheck}set errorAttributeChecks to _support's asRecordParameter(errorAttributeChecks, "using")to exact error check using errorAttributeChecks : {} -- compare two «class ܆ëé» (expected/actual error records) for equality, ignoring any placeholder attributesend numeric range check_error("numeric range check", eText, eNumber, eFrom, eTo)return expectedMinimum ≤ actualValue and actualValue ≤ expectedMaximumif (count {actualValue} each checkType) = 0 then return falseset checkType to expectedMinimum's classif expectedMinimum's class is not expectedMaximum's class then error "Invalid expected value (numeric equality check’s ‘matching types’ parameter requires both numbers to be same type)." number -1703 from expectedValueif isSameTypeRequired thenset {expectedMinimum, expectedMaximum} to expectedValueif (count {expectedValue} each list) = 0 or (count expectedValue each number) ≠ 2 or (expectedValue's item 1 > expectedValue's item 2) then error "Invalid expected value (numeric equality check requires two-item list of minimum and maximum numbers)." number -1703 from expectedValuescript NumericalRangeCheckset isSameTypeRequired to _support's asBooleanParameter(isSameTypeRequired, "matching types")to numeric range check matching types isSameTypeRequired : (true)end numeric equality checkreturn d1 < d and d < d2set d to n2 - n1if d1 > d2 then set {d1, d2} to {d2, d1}set d2 to -d1set d1 to _isEqualDelta * n1set d1 to _isEqualDelta * n2if n1 = 0 thenset {n1, n2} to {expectedValue as real, actualValue as real}if (count {expectedValue, actualValue} each checkType) ≠ 2 then return falseif (count {expectedValue, actualValue} each integer) = 2 then return expectedValue = actualValueproperty _isEqualDelta : 1.0E-12script NumericalEqualityCheckset checkType to numberset checkType to realif _support's asBooleanParameter(isSameTypeRequired, "matching types") thento numeric equality check matching types isSameTypeRequired : (true) -- ignores slight differences due to floating point's limited precision when comparing real numbers -- TO DO: allow magnitude to be optionally specified?end multiple choice check_error("numeric equality check", eText, eNumber, eFrom, eTo)if _asCheckObjectResult(checkObject's compareObjects(expectedValueRef's contents, actualValue)) then return truerepeat with expectedValueRef in expectedValuesif (count {expectedValues} each list) = 0 or length of expectedValues < 2 then error "Invalid expected values (multiple choice check’s ‘using’ parameter requires a list of two or more expected values)." number -1703 from expectedValueto compareObjects(expectedValues, actualValue)script MultipleChoiceCheckset checkObject to _asCheckObjectParameter(checkObject, _defaultEqualityCheck)to multiple choice check using checkObject : (missing value)property _defaultEqualityCheck : exact equality checkend exact equality checkend compareObjectsreturn expectedValue is actualValueif refsCount = 1 or (refsCount = 0 and class of expectedValue is not class of actualValue) then return falseset refsCount to count {expectedValue, actualValue} each specifierto compareObjects(expectedValue, actualValue)script ExactEqualityCheckto exact equality checkend _asCheckObjectResultreturn isEqualif {isEqual} is not in {true, false} then error "Check object did not return a boolean result." number -1703 from isEqual to booleanto _asCheckObjectResult(isEqual)end _asCheckObjectParameterreturn checkObjectif not _support's hasHandler(a reference to compareObjects of checkObject) then error "Bad ‘using’ parameter (script object doesn’t contain a ‘compareObjects’ handler)." number -1728 from checkObjectset checkObject to _support's asScriptParameter(checkObject, "using")if checkObject is missing value then set checkObject to defaultCheckObjectto _asCheckObjectParameter(checkObject, defaultCheckObject)end __performunittestforsuite__return _testReport -- TO DO: wrapping all the test data (result values, error info, status, etc) in a script object and returning that preserves AS context info and AS types across the AE bridge; the script object can then be loaded into a new OSAID and its methods called to extract each bit of data in turn for formatting and final message generation (caveat not sure what ocids and optrs will do)_testReport's addBroken("configure_tearDown", "broke due to error", "", ¬suiteObject's configure_tearDown()if _support's hasHandler(a reference to configure_tearDown of suiteObject) then{{"unexpected error", _TestSupport's makeCaughtErrorRecord(eText, eNumber, eFrom, eTo, ePartial)}}) -- TO DO: without stack trace support, there's no way to distinguish an error raised by the code being tested versus an error caused by a bug in the test code, so we can only say error was 'unexpected' and leave user to figure out why; allowing `call_NAME` handlers to be used by `assert test result` would give users the opportunity to box up the code being tested allowing TestTools to distinguish the cause_testReport's addFailure(handlerName, "(e.g. error in code being tested/bug in test handler)", "", ¬if not (eNumber = _AbortedAssertionError and eFrom is _AbortedAssertionToken) then -- check if failure was already reported, and this is the subsequent abort, in which case ignore; if not, it's an error in either the test_NAME handler or the code being tested, so report iton error eText number eNumber from eFrom to eTo partial result ePartial -- test failedtestObject's doTest()suiteObject's configure_doTest(testObject)if _support's hasHandler(a reference to configure_doTest of suiteObject) thenset testObject to _TestSupport's makeTestObject(suiteObject, handlerName)set _suiteObject to missing value_testReport's addBroken("configure_setUp", "broke due to error", "", ¬suiteObject's configure_setUp()if _support's hasHandler(a reference to configure_setUp of suiteObject) thenset _testHandlerName to handlerNameset _suiteObject to suiteObject{{"unexpected error", _TestSupport's makeCaughtErrorRecord(eText, eNumber, eFrom, eTo, ePartial)}})_testReport's addBroken("configure_skipTests", "broke due to error", "", ¬on error eText number eNumber from eFrom to eTo partial result ePartial_testReport's skipSuite(skipReason)error "‘configure_skipTests’ didn’t return record, text, or ‘missing value’." number -1700 from skipInfo to {record, text, missing value}set skipReason to skipInfo as textelse if skipInfo is not missing value then -- skip the whole suite_testReport's addSkipped(handlerName, skipReason)error "‘configure_skipTests’ didn’t return valid record (‘" & handlerName & "’ property doesn’t contain text or ‘missing value’)." number -1700 from skipInfo to {text, missing value}set skipReason to skipReason as textif skipReason is not missing value thenset skipReason to ((current application's NSDictionary's dictionaryWithDictionary:skipInfo)'s objectForKey:handlerName) as anyif _TestSupport's isType(skipInfo, record) then -- check if this test should be skippedif skipInfo is not missing value then -- (missing value = run test; text = skip suite; record = run/skip test)return _testReporterror "‘configure_skipTests’ didn’t return anything (e.g. to run all tests in suite, return ‘missing value’)." number -2753 from suiteObject to {record, text, missing value}on error number -2753set skipInfo to skipInfo -- make sure configure_skipTests actually returned a valueset skipInfo to suiteObject's configure_skipTests()if _support's hasHandler(a reference to configure_skipTests of suiteObject) thenset _testReport to _TestSupport's makeTestReport(suiteName, handlerName, isStyled)to __performunittestforsuite__(suiteObject, {suiteName, handlerName, isStyled})property _testHandlerName : missing value -- used to generate default `call_NAME` handler name for a `test_NAME` handlerproperty _testReport : missing value -- a single test_NAME handler may perform multiple asserts, the result of each is recorded in TestReport object hereproperty _suiteObject : missing value -- the test suite object that was passed to `perform unit test`; assigned and cleared at start and end of `perform unit test`; may be used by assert handlers (e.g. `assert test error` uses it when calling a `call_NAME` handler)script _AbortedAssertionToken -- when raising error number AbortedAssertionError, the `from` parameter should carry this unique identifier to confirm error was raised by TestTools, and isn't merely an error in the test code/code being tested that happens to use the same error number (in which case it should be treated as such)property _AbortedAssertionError : 8001 -- raised by `assert…` handlers upon failed assertion to terminate that testproperty _TestSupport : a reference to script "TestSupport" -- sub-library embedded in TestTools.scptd_support's throwCommandError("TestTools", handlerName, eText, eNumber, eFrom, eTo)end join paragraphs_error("join paragraphs", eText, eNumber, eFrom, eTo)return _joinText(_support's asListParameter(theList, ""), _asLineBreakParameter(lineBreakType, "using"))to join paragraphs theList using lineBreakType : (OS X line breaks)end split paragraphs_error("split paragraphs", eText, eNumber, eFrom, eTo)return paragraphs of _support's asTextParameter(theText, "")to split paragraphs theTextend join text_error("join text", eText, eNumber, eFrom, eTo)return _joinText(_support's asListParameter(theList, ""), _support's asTextParameter(separatorText, "using"))to join text theList using separatorText : ""end split text_error("split text", eText, eNumber, eFrom, eTo)return _splitPattern(theText, theSeparator)return _splitText(theText, theSeparator)else if matchFormat is case insensitivity thenreturn _splitPattern(trim text theText, "\\s+")if theSeparator is missing value then -- if `at` parameter is omitted, trim ends then then split on whitespace runs, same as Python's str.split() default behavior (any `using` options are ignored)if theText's length = 0 then return {}to split text theText at theSeparator : (missing value) using matchFormat : (case insensitivity)end _joinText_support's throwInvalidParameter(theList, "", list, "Expected list of text.")set resultText to theList as textset AppleScript's text item delimiters to separatorTextto _joinText(theList, separatorText)end _splitPatternif resultList's length = 1 and resultList's item 1's length = 0 then return {} -- for consistency with _splitText(), where `text items of ""` returns empty listset end of resultList to (asocString's substringFromIndex:asocNonMatchStart) as textset end of resultList to (asocString's substringWithRange:{location:asocNonMatchStart, |length|:asocMatchStart - asocNonMatchStart}) as textset asocMatchRange to ((asocMatchArray's objectAtIndex:i)'s rangeAtIndex:0)set asocPattern to _asNSRegularExpressionParameter(patternText, "at")if (count {patternText} each list) = 1 then set patternText to join text patternText using "|"to _splitPattern(theText, patternText) -- used by `split text` to split text using a regular expression as separatorend _splitTextset resultList to text items of theTextset AppleScript's text item delimiters to delimiterList_support's throwInvalidParameterType(aRef, "using", text, "list of text")set contents of aRef to contents of aRef as text -- caution: AS silently ignores invalid TID values, so separator items must be explicitly validated to catch any user errors; for now, just coerce to text and catch errors, but might want to make it more rigorous in future (e.g. if a list of lists is given, should sublist be treated as an error instead of just coercing it to text, which is itself TIDs sensitive); see also existing TODO on TypeSupport's asTextParameter handlerrepeat with aRef in delimiterListset delimiterList to _support's asList(theSeparator)to _splitText(theText, theSeparator) -- used by `split text` to split text using one or more text item delimiters and current or predefined considering/ignoring settingsend _asLineBreakParameter_support's throwInvalidConstantParameter(lineBreakType, parameterName)return return & linefeedelse if lineBreakType is Windows line breaks thenreturn returnelse if lineBreakType is classic Mac line breaks thenreturn linefeedif lineBreakType is OS X line breaks thento _asLineBreakParameter(lineBreakType, parameterName) -- used by `join paragraphs` and `normalize line breaks`end trim text_error("trim text", eText, eNumber, eFrom, eTo)set endIndex to endIndex - 1repeat while character endIndex of theText is ""if {whichEnd} is in {trailing characters only, leading and trailing characters} thenset startIndex to startIndex + 1repeat while character startIndex of theText is ""if {whichEnd} is in {leading characters only, leading and trailing characters} thenset {startIndex, endIndex} to {1, -1}if theText is "" then return "" -- check if theText is empty or contains white space characters onlyconsidering case, diacriticals, hyphens and punctuation but ignoring numeric strings and white space_support's throwInvalidConstantParameter(whichEnd, "removing")if {whichEnd} is not in {leading characters only, trailing characters only, leading and trailing characters} thento trim text theText removing whichEnd : (leading and trailing characters)end slice text_error("slice text", eText, eNumber, eFrom, eTo)return text startIndex thru endIndex of theTextset endIndex to theLengthset endIndex to 1if endIndex < 1 thenset startIndex to theLengthif startIndex < 1 thenor startIndex > theLength and endIndex > theLength then return ""if startIndex > endIndex or startIndex < 1 and endIndex < 1 ¬if endIndex < 0 then set endIndex to theLength + 1 + endIndexif startIndex < 0 then set startIndex to theLength + 1 + startIndexreturn theText's text 1 thru endIndexelse if endIndex > theLength thenif endIndex < -theLength thenif startIndex is missing value thenset endIndex to _support's asIntegerParameter(endIndex, "to")if endIndex is not missing value thenerror "Expected ‘from’ and/or ‘to’ parameter but received neither." number -1701else if endIndex is missing value thenreturn theText's text startIndex thru -1else if startIndex > theLength thenif startIndex < -theLength thenif endIndex is missing value thenset startIndex to _support's asIntegerParameter(startIndex, "from")if startIndex is not missing value thenif endIndex = 0 then _support's throwInvalidParameter(endIndex, "to", integer, "Index can’t be 0.")if startIndex = 0 then _support's throwInvalidParameter(startIndex, "from", integer, "Index can’t be 0.")if theLength = 0 thenset theLength to theText's lengthto slice text theText from startIndex : (missing value) to endIndex : (missing value)end pad text_error("pad text", eText, eNumber, eFrom, eTo)_support's throwInvalidConstantParameter(whichEnd, "adding")return theText & (padText's text (1 + padOffset) thru (padOffset + (widthToAdd + 1) div 2))if widthToAdd > 1 then set theText to padText's text 1 thru (widthToAdd div 2) & theTextelse if whichEnd is leading and trailing characters thenreturn theText & (padText's text (1 + padOffset) thru (padOffset + widthToAdd))set padOffset to (theText's length) mod padSizeelse if whichEnd is trailing characters only thenreturn (padText's text 1 thru widthToAdd) & theTextif whichEnd is leading characters only thenset padText to padText & padTextrepeat while padText's length < (widthToAdd + padSize)if padText's length = 0 then _support's throwInvalidParameter(padText, "using", text, "Can’t be empty text.")set padSize to padText's lengthset padText to _support's asTextParameter(padText, "using")if widthToAdd ≤ 0 then return theTextset widthToAdd to textWidth - (theText's length)set textWidth to _support's asIntegerParameter(textWidth, "to places")to pad text theText to places textWidth using padText : (" ") adding whichEnd : (leading characters only)end transform text_error("normalize text", eText, eNumber, eFrom, eTo)_support's throwInvalidParameter(nOpts, "using", list, eText)on error eText number 6502set asocString to asocString's decomposedStringWithCompatibilityMapping()if {decomposed compatibility form} is in nOpts thenset asocString to asocString's precomposedStringWithCompatibilityMapping()if {precomposed compatibility form} is in nOpts thenset asocString to asocString's decomposedStringWithCanonicalMapping()if didNormalize then error "Conflicting Unicode options." number 6502if {decomposed canonical form} is in nOpts thenset didNormalize to falseset didNormalize to trueset asocString to asocString's precomposedStringWithCanonicalMapping()if {precomposed canonical form} is in nOpts thenset asocString to asocString's stringByReplacingOccurrencesOfString:"[^\\r\\n\\t\\u0020-\\u007e]" withString:"?" options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}set asocString to asocString's stringByApplyingTransform:("Any-Latin;Latin-ASCII") |reverse|:falseelse if {printable ASCII only} is in nOpts thenset asocString to asocString's stringByApplyingTransform:("Publishing-Any") |reverse|:falseif {printable ASCII only} is in nOpts then error "Conflicting punctuation/ASCII options." number 6502else if {typewriter punctuation} is in nOpts thenset asocString to asocString's stringByApplyingTransform:("Any-Publishing") |reverse|:falseif {typewriter punctuation} is in nOpts or {printable ASCII only} is in nOpts then error "Conflicting punctuation/ASCII options" number 6502if {smart punctuation} is in nOpts thenset asocString to asocString's stringByReplacingOccurrencesOfString:"\\r\\n|\\r|\\n|\\u2028|\\u2029" withString:lineBreak options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}else if lineBreak is not missing value then -- standardize line breaksset asocString to asocString's stringByReplacingOccurrencesOfString:"[\\f\\t\\p{Z}]+" withString:space options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}set asocString to asocString's stringByReplacingOccurrencesOfString:"(?:\\s*(?:\\r\\n|\\r|\\n|\\u2028|\\u2029))+\\s*" withString:lineBreak options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}else -- convert line break runs (including any other white space) to single `lineBreak`, and any other white space runs (tabs, spaces, etc) to single spacesset asocString to asocString's stringByReplacingOccurrencesOfString:"(?:\\r\\n|\\r|\\n|\\u2028|\\u2029|\\s)+" withString:space options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}if lineBreak is missing value then -- also convert line breaks (including Unicode line and paragraph separators) to single spacesset asocString to asocString's stringByReplacingOccurrencesOfString:"\\A(?:\\u2028|\\u2029|\\s)+|(?:\\u2028|\\u2029|\\s)+\\z" withString:"" options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()} -- trim leading/trailing white spaceif {normalized white space} is in nOpts thenif foldingFlags ≠ 0 then set asocString to asocString's stringByFoldingWithOptions:foldingFlags locale:(_support's asNSLocaleParameter(localeCode, "for locale"))if {normalized width} is in nOpts then set foldingFlags to foldingFlags + 256if {normalized diacriticals} is in nOpts then set foldingFlags to foldingFlags + 128if {normalized case} is in nOpts then set foldingFlags to foldingFlags + 1set foldingFlags to 0set asocString to _support's asNSString(theText)set lineBreak to return & linefeedif nOpts's length = 1 then return _joinText(theText's paragraphs, return & linefeed)if {Windows line breaks} is in nOpts thenset lineBreak to returnif nOpts's length = 1 then return _joinText(theText's paragraphs, return)if lineBreak is not missing value then error "Conflicting line break options." number 6502if {classic Mac line breaks} is in nOpts thenset lineBreak to missing valueset lineBreak to linefeedif {OS X line breaks} is in nOpts thenif nOpts is {} then return theTextif nOpts is {OS X line breaks} then return _joinText(theText's paragraphs, linefeed)set nOpts to _support's asListParameter(nOpts, "using")to transform text theText using nOpts : {OS X line breaks} for locale localeCode : ("none")end format text_error("format text", eText, eNumber, eFrom, eTo)return _joinText(templateItems, "")error "Can’t subsitute placeholder “" & item i of templateItems & "”: " & eText number eNumber from eFrom to eToset item i of templateItems to (get theValues's item ((get item i of templateItems) as integer)) as textset theValues to _support's asListParameter(theValues, "using")else -- it's a list (or a single-item list)set item i of templateItems to theValues's getItem(get item i of templateItems) as textrepeat with i from 2 to templateItems's length by 2if (count {theValues} each script) = 1 then -- assume it's a script object with getItem handler (e.g. DictionaryCollection)set i to 2set templateItems to _parseFormatTemplate(_support's asTextParameter(templateText, ""))to format text templateText using theValues : {}end lowercase text_error("lowercase text", eText, eNumber, eFrom, eTo)return (asocString's lowercaseStringWithLocale:(_support's asNSLocaleParameter(localeCode, "for locale"))) as textreturn (asocString's lowercaseString()) as textto lowercase text theText for locale localeCode : missing valueend capitalize text_error("capitalize text", eText, eNumber, eFrom, eTo)return (asocString's capitalizedStringWithLocale:(_support's asNSLocaleParameter(localeCode, "for locale"))) as textreturn (asocString's capitalizedString()) as textto capitalize text theText for locale localeCode : missing valueend uppercase text_error("uppercase text", eText, eNumber, eFrom, eTo)return (asocString's uppercaseStringWithLocale:(_support's asNSLocaleParameter(localeCode, "for locale"))) as textreturn (asocString's uppercaseString()) as textif localeCode is missing value thento uppercase text theText for locale localeCode : missing valueend escape template_error("escape template", eText, eNumber, eFrom, eTo)return _joinText(_splitText(_support's asTextParameter(theText, ""), "\\"), "\\\\")to escape template theTextend escape pattern_error("escape pattern", eText, eNumber, eFrom, eTo)return (current application's NSRegularExpression's escapedPatternForString:(_support's asTextParameter(theText, ""))) as textto escape pattern theTextend search text_error("search text", eText, eNumber, eFrom, eTo)if forText is "" then _support's throwInvalidParameter(forText, "for", text, "Only contains characters ignored by the current considerations.")return _replacePattern(theText, forText, newText)return _replaceText(theText, forText, newText)if theText's length = 0 then return ""else -- replace matches_support's throwInvalidConstantParameter(matchFormat, "using")if forText is "" then _support's throwInvalidParameter(forText, "for", text, "Only contains characters ignored by the current considerations.") -- checks if all characters in forText are ignored by current considering/ignoring settings (the alternative would be to return each character as a non-match separated by a zero-length match, but that's probably not what the user intended); note that unlike `aString's length = 0`, which is what library code normally uses to check for empty text, on this occasion we do want to take into account the current considering/ignoring settings so deliberately use `forText is ""` here. For example, when ignoring punctuation, searching for the TID `"!?"` is no different to searching for `""`, because all of its characters are being ignored when comparing the text being searched against the text being searched for. Thus, a simple `forText is ""` test can be used to check in advance if the text contains any matchable characters under the current considering/ignoring settings, and report a meaningful error if not.else if matchFormat is current considerations thenreturn _findPattern(theText, forText, includeNonMatches, includeMatches)else if matchFormat is pattern matching thenelse if matchFormat is exact matching thenreturn _findText(theText, forText, includeNonMatches, includeMatches)if matchFormat is case insensitivity then -- the default_support's throwInvalidConstantParameter(resultFormat, "returning")set {includeNonMatches, includeMatches} to {true, true}else if resultFormat is matched and unmatched text thenset {includeNonMatches, includeMatches} to {true, false}else if resultFormat is unmatched text only thenset {includeNonMatches, includeMatches} to {false, true}return {{class:_UnmatchedTextType, startIndex:1, endIndex:0, foundText:""}}if resultFormat is matched text only thenif theText's length = 0 thenif newText is missing value then -- find matchesif forText's length = 0 then _support's throwInvalidParameter(forText, "for", text, "Can’t be empty text.")set forText to _support's asTextParameter(forText, "for")replacing with newText : (missing value) returning resultFormat : (matched text only)to search text theText for forText using matchFormat : (case insensitivity) ¬set resultText to resultList as textset AppleScript's text item delimiters to newTextset resultList to theText's text items -- note: TID-based matching uses current considering/ignoring settingsset newText to _support's asTextParameter(newText, "replacing with")else -- replace with callback-supplied texterror "An error occurred when calling the ‘replacing with’ parameter’s ‘replaceText’ handler: " & eText number eNumber from eFrom to eToset end of resultList to newText's replaceText(foundText) as textif startIndex ≤ endIndex then set end of resultList to text startIndex thru endIndex of theTextset {resultList, startIndex, endIndex} to {{}, 1, length of text item 1 of theText}if (count {newText} each script) ≠ 0 thento _replaceText(theText, forText, newText)end _findTextset endIndex to startIndex + (length of text item i of theText) - 1set end of resultList to {class:_MatchedTextType, startIndex:startIndex, endIndex:endIndex, foundText:foundText, foundGroups:{}}set endIndex to (length of theText) - (length of text (text item i) thru (text item -1) of theText)set startIndex to endIndex + 1repeat with i from 2 to count text items of theTextset end of resultList to {class:_UnmatchedTextType, startIndex:startIndex, endIndex:endIndex, foundText:foundText}set foundText to ""set foundText to text startIndex thru endIndex of theTextif startIndex ≤ endIndex thenset endIndex to length of text item 1 of theTextset startIndex to 1set AppleScript's text item delimiters to forTextto _findText(theText, forText, includeNonMatches, includeMatches)end _replacePatternoptions:0 range:{0, asocString's |length|()} withTemplate:_parseSearchTemplate(templateText)) as textreturn (asocPattern's stringByReplacingMatchesInString:asocString ¬set resultText to resultList's _list_ as textset end of resultList's _list_ to (asocString's substringFromIndex:asocNonMatchStart) as text -- last interstitialset asocNonMatchStart to asocMatchStart + (asocMatchRange's |length|()) -- asocMatchEnderror "An error occurred when calling the ‘replacing with’ parameter’s ‘replacePattern’ handler: " & eText number eNumber from eFrom to eToset end of resultList's _list_ to templateText's replacePattern(foundText, foundGroups) as textset end of foundGroups to (asocString's substringWithRange:(asocMatch's rangeAtIndex:j)) as textrepeat with j from 1 to (asocMatch's numberOfRanges()) - 1 -- ranges above 0 are group matchesset foundGroups to {}set foundText to (asocString's substringWithRange:asocMatchRange) as text -- range 0 is full matchset end of resultList's _list_ to (asocString's substringWithRange:asocNonMatchRange) as text -- interstitial textset asocNonMatchRange to {location:asocNonMatchStart, |length|:asocMatchStart - asocNonMatchStart}set asocMatchRange to (asocMatch's rangeAtIndex:0) -- the full range of the matchset asocMatch to (asocMatchArray's objectAtIndex:i) -- a single matchproperty _list_ : {}script resultListif (count {templateText} each script) = 1 thento _replacePattern(theText, patternText, templateText)end _findPatternset end of resultList to {class:_UnmatchedTextType, startIndex:textOffset, endIndex:length of theText, foundText:foundText}set foundText to (asocString's substringFromIndex:asocNonMatchStart) as textset end of resultList to matchInfo & {foundGroups:_matchedGroupList(asocString, asocMatch, matchInfo's startIndex, includeNonMatches)}if includeMatches thenif includeNonMatches then set end of resultList to nonMatchInfoset {nonMatchInfo, matchInfo, asocNonMatchStart, textOffset} to _matchRecords(asocString, asocMatch's rangeAtIndex:0, asocNonMatchStart, textOffset, _UnmatchedTextType, _MatchedTextType)set textOffset to 1 -- used to calculate correct AppleScript start and end indexesset asocNonMatchStart to 0 -- used to calculate NSRanges for non-matching portions of NSStringset asocString to _support's asNormalizedNSString(theText)set asocPattern to _asNSRegularExpressionParameter(patternText, "for")set includeMatches to _support's asBooleanParameter(includeMatches, "matched text")set includeNonMatches to _support's asBooleanParameter(includeNonMatches, "unmatched text")to _findPattern(theText, patternText, includeNonMatches, includeMatches)end _matchedGroupListreturn subMatchResultsset end of subMatchResults to item 1 of _matchInfoRecord(asocString, asocNonMatchRange, textOffset, _UnmatchedTextType)set asocNonMatchRange to {location:asocNonMatchStart, |length|:asocFullMatchEnd - asocNonMatchStart}if includeNonMatches thenset end of subMatchResults to matchInfoif includeNonMatches then set end of subMatchResults to nonMatchInfoset {nonMatchInfo, matchInfo, asocNonMatchStart, textOffset} to _matchRecords(asocString, asocMatch's rangeAtIndex:i, asocNonMatchStart, textOffset, _UnmatchedTextType, _MatchedGroupType)repeat with i from 1 to groupIndexesset asocFullMatchEnd to asocNonMatchStart + (asocFullMatchRange's |length|())set asocNonMatchStart to asocFullMatchRange's location()set asocFullMatchRange to asocMatch's rangeAtIndex:0if groupIndexes > 0 thenset groupIndexes to (asocMatch's numberOfRanges()) - 1set subMatchResults to {}to _matchedGroupList(asocString, asocMatch, textOffset, includeNonMatches)end _matchRecordsreturn {nonMatchInfo, matchInfo, asocMatchEnd, textOffset}set {matchInfo, textOffset} to _matchInfoRecord(asocString, asocMatchRange, textOffset, matchRecordType)set {nonMatchInfo, textOffset} to _matchInfoRecord(asocString, asocNonMatchRange, textOffset, nonMatchRecordType)set asocNonMatchRange to {location:asocStartIndex, |length|:asocMatchStart - asocStartIndex}set asocMatchEnd to asocMatchStart + (asocMatchRange's |length|())to _matchRecords(asocString, asocMatchRange, asocStartIndex, textOffset, nonMatchRecordType, matchRecordType)end _matchInfoRecordreturn {{class:recordType, startIndex:textOffset, endIndex:nextTextOffset - 1, foundText:foundText}, nextTextOffset}set nextTextOffset to textOffset + (length of foundText) -- calculate the start index of the next AS text rangeset foundText to (asocString's substringWithRange:asocMatchRange) as textto _matchInfoRecord(asocString, asocMatchRange, textOffset, recordType)end _parseFormatTemplatereturn _previousFormatTemplateParsedItems's itemsset _previousFormatTemplateText to templateTextset _previousFormatTemplateParsedItems to _parseTemplateText(templateText)if templateText is not _previousFormatTemplateText thento _parseFormatTemplate(templateText)property _previousFormatTemplateParsedItems : "" -- list of form {text, index or name, ..., text}property _previousFormatTemplateText : ""end _parseSearchTemplatereturn _previousSearchTemplateParsedTextset _previousSearchTemplateText to templateTextset _previousSearchTemplateParsedText to _joinText(templateItems, "")set item i of templateItems to (asocString's stringByReplacingOccurrencesOfString:"([\\$])" withString:"\\\\$1" options:(current application's NSRegularExpressionSearch) range:{0, asocString's |length|()}) as textset asocString to _support's asNSString(itemText)else -- re-escape '/' and '$'set item i of templateItems to itemTextif nextItem's length > 0 and nextItem's character 1 is in "1234567890" then set itemText to itemText & "\\" -- make sure ICT template doesn't consume next digitset nextItem to item (i + 1) of templateItemsset itemText to "$" & (itemText as integer)if i mod 2 = 0 then -- substitute integer N with $Nset itemText to item i of templateItemsrepeat with i from 1 to templateItems's lengthset templateItems to _parseTemplateText(templateText)if templateText is not _previousSearchTemplateText thento _parseSearchTemplate(templateText)property _previousSearchTemplateParsedText : ""property _previousSearchTemplateText : ""end _parseTemplateTextreturn resultListset last item of resultList to last item of resultList & itemTextif concatNext thenset itemText to ((asocString's substringFromIndex:asocNonMatchStart)'s stringByApplyingTransform:("Hex-Any/C;Name-Any") |reverse|:false) as text -- trailing text; convert and appendset end of resultList to itemTextset concatNext to trueset last item of resultList to last item of resultList & (item (offset of itemText in "nrt\\") of {linefeed, return, tab, "\\"})if j = 1 thenset itemText to asocMatchString as textset asocMatchString to (asocString's substringWithRange:asocGroupRange)if asocGroupRange's |length|() > 0 thenset asocGroupRange to (asocMatch's rangeAtIndex:j)repeat with j from 1 to 3 -- _tokens defines 3 groups (index 0 is full match, so ignore that)set asocNonMatchStart to asocMatchStart + (asocMatchRange's |length|())set end of resultList to nonMatchTextset last item of resultList to last item of resultList & nonMatchTextif concatNext then -- only item indexes/names should be at even indexesset nonMatchText to ((asocString's substringWithRange:{asocNonMatchStart, (asocMatchStart - asocNonMatchStart)})'s stringByApplyingTransform:("Hex-Any/C;Name-Any") |reverse|:false) as text -- convert \u1234, \U00123456, \N{CHARNAME} escapes to specified characters (10.11+)set asocMatchStart to asocMatchRange's location()set asocMatchRange to (asocMatch's rangeAtIndex:0)set asocMatch to (asocMatchArray's objectAtIndex:i)repeat with i from 0 to (asocMatchArray's |count|()) - 1set concatNext to falseset asocMatchArray to asocPattern's matchesInString:asocString options:0 range:{0, asocString's |length|()}set resultList to {}set asocNonMatchStart to 0options:(get current application's NSRegularExpressionAllowCommentsAndWhitespace) |error|:(missing value)set asocPattern to current application's NSRegularExpression's regularExpressionWithPattern:_tokens ¬set asocString to current application's NSString's stringWithString:templateTextto _parseTemplateText(templateText) -- convert template text containing backslashed special characters (\t, \u1234, \3, etc.) to a list of text items of form {text, index or name, ..., text}, where every 2nd item is an unprocessed back reference; used by the _parseSearchTemplate and _parseFormatTemplate handlers)" -- note: \N{...}, \u1234, and \U00123456 escape sequences are processed separately (via ICU transforms); any other backslash sequences are unrecognized and left unchanged| \\{ ([^}{\\\\]*) \\} # backslash + any text in braces (insertion index or name)| ( [0-9] ) # backslash + single digit (insertion index)(?:(n|r|t|\\\\) # newline, return, tab or backslash character\\\\ # match a backslash escape, followed by one of:property _tokens : "end _asNSRegularExpressionParameter(get current application's NSRegularExpressionUseUnicodeWordBoundaries)), parameterName)(get current application's NSRegularExpressionDotMatchesLineSeparators) + ¬(get current application's NSRegularExpressionAnchorsMatchLines) + ¬((get current application's NSRegularExpressionCaseInsensitive) + ¬return _support's asNSRegularExpressionParameter(patternText, ¬to _asNSRegularExpressionParameter(patternText, parameterName) -- returns a regexp object with `(?imsw)` options enabled by default_support's throwCommandError("Text", handlerName, eText, eNumber, eFrom, eTo)property _MatchedGroupType : matched groupproperty _MatchedTextType : matched textproperty _UnmatchedTextType : unmatched textend asASObjectreturn theValue as anything -- coerce ASOC specifier to AS value, if possibleif isNSObject(theValue) thento asASObject(theValue)end asNSObjectreturn (current application's NSArray's arrayWithObject:theValue)'s objectAtIndex:0to asNSObject(theValue)end isNSObjecton error -- the above statement may fail in numerous ways, so all we can do is catch all errors and hope they were due to theValue not being an ASOC object rather than caused by something elsereturn theValue's isKindOfClass:(current application's NSObject's |class|())if (count {theValue} each reference) = 0 then return falseto isNSObject(theValue)end isValueOfType_error("isValueOfType", eText, eNumber, eFrom, eTo)else if (count {theValue} each typeClass) ≠ 0 then -- other AS types can be reliably filtered using a `count` command -- TO DO: need to confirm this works for all typesreturn typeClass is applicationelse if (count {theValue} each application) ≠ 0 thenreturn isNSObject(theValue)else if typeClasses is «class ocid» then -- is it an AppleScriptObjC specifier?theValue as constant is theValue then return trueelse if typeClass is constant thentheValue as class is theValue then return trueif (count {theValue} each reference) = 0 and ¬if typeClass is class or typeClass is type class then -- TO DO: this could be problematic (AS is murky on distinction between `class` and `type class`, treating them as synonymous when used in `as` operation but not when comparing them; be aware that library's SDEF causes `type class` keyword to reformat as `type` keyword (for added confusion)error throwInvalidParameterType(typeClass, "is type", class, "type class or list of type class")on error number -1700 -- TO DO: move to asTypeClassParameterset typeClass to contents of aRef as classrepeat with aRef in typeClassesif (count {typeClasses} each list) = 0 then set typeClasses to {typeClasses}to isValueOfType(theValue, typeClasses) -- performs a 'VALUE is-a CLASS' test, which is trickier than it sounds since AppleScript has neither classes nor `is-a` operatorend nativeTypeOfValuereturn class of theValuereturn scriptelse if (count {theValue} each script) ≠ 0 then -- ignore custom `class` propertyreturn recordelse if (count {theValue} each record) ≠ 0 then -- ignore custom `class` propertyreturn applicationelse if (count {theValue} each application) ≠ 0 then -- avoid implicit dereferencing (we don't want `application NAME` value being treated as an object specifier root, i.e. null)return referenceif (count {theValue} each reference) ≠ 0 then -- avoid implicit dereferencingto nativeTypeOfValue(theValue)end asNSURLParameterreturn asocURLif asocURL is missing value then throwInvalidParameter(urlText, parameterName, text, "Not a valid URL.") -- NSURL requires RFC 1808set asocURL to (current application's NSURL's URLWithString:asTextParameter(urlText, parameterName))to asNSURLParameter(urlText, parameterName)end asNSLocaleParameterreturn current application's NSLocale's localeWithLocaleIdentifier:localeCode -- (locale codes are case-insensitive)if localeCode is not in (current application's NSLocale's availableLocaleIdentifiers() as list) then throwInvalidParameter(localeCode, parameterName, {constant, text}, "Unknown locale name: “" & localeCode & "”.")throwInvalidParameterType(localeCode, parameterName, "‘no locale’, {constant, text}, ‘current locale’, or text")set localeCode to localeCode as textreturn current application's NSLocale's currentLocale()else if localeCode is "current" thenreturn current application's NSLocale's systemLocale()if localeCode is "none" thento asNSLocaleParameter(localeCode, parameterName)end asNSRegularExpressionParameterreturn asocPatternif asocPattern is missing value then throwInvalidParameter(theText, parameterName, text, "Not a valid pattern.")throwInvalidParameterType(theText, parameterName, text, "text")set asocPattern to current application's NSRegularExpression's regularExpressionWithPattern:asNormalizedNSString(theText as text) options:flagOptions |error|:(missing value) -- NSRegularExpression doesn't return detailed error descriptions, so just use generic error description belowto asNSRegularExpressionParameter(theText, flagOptions, parameterName)end asNormalizedNSStringreturn (current application's NSString's stringWithString:theText)'s decomposedStringWithCanonicalMapping()to asNormalizedNSString(theText) -- parameter must be textend asNSMutableStringreturn (current application's NSMutableString's stringWithString:theText)to asNSMutableString(theText) -- parameter must be textend asNSStringreturn (current application's NSString's stringWithString:theText)to asNSString(theText) -- parameter must be textend asPOSIXPathParameterthrowInvalidParameterType(theValue, parameterName, text, "POSIX path")return POSIX path of (theValue as «class furl»)return theValueif (count {theValue} each text) = 1 thento asPOSIXPathParameter(theValue, parameterName)end asTypeParameterthrowInvalidParameterType(theValue, parameterName, type class, "type")return theValue as type classto asTypeParameter(theValue, parameterName)end asScriptParameterthrowInvalidParameterType(theValue, parameterName, script, "script")return theValue as scriptto asScriptParameter(theValue, parameterName) -- TO DO: should take scriptName parameter that describes script object's purpose (e.g. "sort comparator script object")end asOptionalRecordParameterreturn fullRecordif {fullRecord's class} is not in {record, defaultRecord's class} then throwInvalidParameter(theValue, parameterName, record, "Not a record of class " & defaultRecord's class & ".") -- TO DO: record class needs to be passed as text as coercing type class symbol to text will give raw chevron syntax onlyif (fullRecord as list) contains {RequiredValue} then throwInvalidParameter(theValue, parameterName, record, "Record is missing one or more required properties.")if fullRecord's length > defaultRecord's length then throwInvalidParameter(theValue, parameterName, record, "Record contains one or more unrecognized properties.")set fullRecord to theRecord & defaultRecordset defaultRecord to defaultRecord & {class:record}set theRecord to theValue as recordto asOptionalRecordParameter(theValue, defaultRecord, parameterName)script RequiredValue -- e.g. if asOptionalRecordParameter's `defaultRecord` parameter is {foo:RequiredValue, bar:missing value}`, the `foo` property is required but the `bar` property is optional (default: `missing value`); any other properties will raise an "unrecognized properties" errorend asRecordParameterthrowInvalidParameterType(theValue, parameterName, record, "record")return theValue as recordto asRecordParameter(theValue, parameterName)end asListParameterreturn asList(theValue)to asListParameter(theValue, parameterName) -- takes parameterName, even though it's unused, for consistency with other `asTYPEParameter` handlers, reducing risk of typosend asDateParameterthrowInvalidParameterType(theValue, parameterName, date, "date")return theValue as date -- note that this fails for anything except date or NSDate (while it would be possible to try `date theValue` as well, it's probably best not to as AS's text-to-date conversion is locale-sensitive, so an ambiguous date string such as "12/11/10" would produce unpredictable results rather than fail outright)to asDateParameter(theValue, parameterName)end asTextParameterthrowInvalidParameterType(theValue, parameterName, text, "text")return asText(theValue)to asTextParameter(theValue, parameterName) -- TO DO: should lists be rejected for safety? (while coercing numbers and dates to text is at least predictable within a process's lifetime, coercing list to text is dependent on whatever TIDs are set at the time so can't be guaranteed even to do that)end asRealParameterthrowInvalidParameterType(theValue, parameterName, real, "real")return asNumber(theValue) as realto asRealParameter(theValue, parameterName)end asNumberParameterthrowInvalidParameterType(theValue, parameterName, number, "number")return asNumber(theValue)to asNumberParameter(theValue, parameterName)end asWholeNumberParameterthrowInvalidParameterType(theValue, parameterName, number, "integer or non-fractional real")return asWholeNumber(theValue)to asWholeNumberParameter(theValue, parameterName) -- this should be used instead of asIntegerParameter when non-fractional numbers are required but do not have to be specifically of integer type (which is limited in range to ±2^30)end asIntegerParameterthrowInvalidParameterType(theValue, parameterName, integer, "integer")return asWholeNumber(theValue) as integerto asIntegerParameter(theValue, parameterName)end asBooleanParameterthrowInvalidParameterType(theValue, parameterName, boolean, "boolean")return theValue as booleanto asBooleanParameter(theValue, parameterName)end asListreturn {theValue}if (count {theValue} each list) = 1 then return theValueset theValue to theValue as list -- note: this also coerces all of the items in the array, which may not be ideal; however, if a handler is coercing to AS list then it probably wants to work with its contents as well, and will most likely want those to be AS values tooif isNSObject(theValue) and (theValue's isKindOfClass:(current application's NSArray's |class|())) then -- if value is NSArray, coerce it to AS listto asList(theValue)end asTextreturn theValue as texterror "Can’t coerce to text." number -1700 from theValue to (text)else if theValue's length = 0 thenif (count {theValue} each list) = 0 then return theValue as textset theValue to theValue's item 1 -- unwrap single-item list (note that nested lists are also disallowed)if theValue's length = 1 thenif (count {theValue} each list) = 1 thento asText(theValue)end asIntegerreturn theNumber as integerif theNumber mod 1 ≠ 0 then error "Can’t coerce to integer." number -1700 from theValue to (integer)to asInteger(theValue)end asWholeNumberreturn theNumberif (theNumber < 0 and theNumber - 1 = theNumber) or (theNumber + 1 = theNumber) then error "Can’t coerce to whole number (can't be represented as real number without losing precision)." number -1700 from theValue to (number)if theNumber mod 1 ≠ 0 then error "Can’t coerce to whole number (not an integer or non-fractional real)." number -1700 from theValue to (number)set theNumber to asNumber(theValue)to asWholeNumber(theValue)end asNumbererror "Can’t coerce to number (not a valid number)." number -1700 from theValue to (number)on error number -1700 -- `theValue as anything` will fail if value is a record (presumably an AS bug)return theValue as numberif ((count {theValue} each number) = 1 or (count {theValue} each text) = 1 and theValue's length > 0) thenset theValue to theValue's item 1 -- unwrap single-item listif (count {theValue} each list) = 1 and theValue's length = 1 thenset theValue to theValue as anything -- make sure ASOC objects are coerced to AS equivalentsto asNumber(theValue)end throwMethodErrorerror rethrowError(libraryName, handlerName, eText, eNumber, eFrom, eTo, targetObjectName, missing value)to throwMethodError(libraryName, targetObjectName, handlerName, eText, eNumber, eFrom, eTo)end throwCommandErrorerror rethrowError(libraryName, handlerName, eText, eNumber, eFrom, eTo, missing value, missing value)to throwCommandError(libraryName, handlerName, eText, eNumber, eFrom, eTo)end rethrowErrorerror eText number eNumber from eFrom to eTo partial result partialResulterror eText number eNumber from eFrom to eToif partialResult is missing value thenset eText to libraryName & " library’s " & targetObjectName & " can’t " & handlerName & ": " & eTextset eText to libraryName & " library can’t " & handlerName & ": " & eTextif targetObjectName is missing value thento rethrowError(libraryName, handlerName, eText, eNumber, eFrom, eTo, targetObjectName, partialResult) -- targetObjectName and partialResult should be `missing value` if unused; if eTo is unused, AS seems to be to pass `item`end throwInvalidConstantParameterthrowInvalidParameter(theValue, parameterName, constant, "Not an allowed constant.")to throwInvalidConstantParameter(theValue, parameterName)end throwInvalidParameterTypethrowInvalidParameter(theValue, parameterName, expectedType, "Expected " & expectedTypeName & actualTypeName & ".")set actualTypeName to ""set actualTypeName to " but received " & (theValue's class) -- include the value's type name in error message; note: this will display as raw four-char code when terminology isn't available, or may be a custom value in the case of records and scripts, but this can't be helped as it's a limitation of AppleScript itselfset actualTypeName to " but received specifier"if (count {theValue} each reference) ≠ 0 thento throwInvalidParameterType(theValue, parameterName, expectedType, expectedTypeName)end throwInvalidParameterIndex_throwInvalidParameter(theValue, parameterName, integer, "Index is out of range.", -1728)to throwInvalidParameterIndex(theValue, parameterName) -- can't get list itemend throwInvalidParameter_throwInvalidParameter(theValue, parameterName, expectedType, errorDescription, -1703)to throwInvalidParameter(theValue, parameterName, expectedType, errorDescription)end _throwInvalidParametererror "Invalid " & parameterName & " parameter: " & errorDescription number errorNumber from theValue to expectedTypeset parameterName to "‘" & parameterName & "’"set parameterName to "direct"if parameterName's length = 0 thento _throwInvalidParameter(theValue, parameterName, expectedType, errorDescription, errorNumber) -- privateend hasHandleron error number -1700 -- the referred-to script object slot doesn't exist, or isn't a handlerhandlerRef as handler -- dereference and type check; this raises -1700 on failuretry -- horrible hack to check if a script object has a specific handlerto hasHandler(handlerRef) -- handlerRef must be `a reference to HANDLER of SCRIPT`These boilerplate idioms help to compensate for AppleScript's own weak error reporting, which only indicates that an error has occurred but does not tell the user where.Each public handler should also contain a `try` block that catches all errors occurring within that handler, and rethrow them via the supporting `_error` handler; again, "SOME HANDLER" should be changed to match the handler's actual name.The 'support' section contains standard boilerplate code for rethrowing handler errors with the name of the library included; only the `_error` handler's "LIBRARY_NAME" text needs changed to contain the library's actual name.end SOME HANDLER_error("SOME HANDLER", eText, eNumber, eFrom, eTo)set flagParam to _support's asBooleanParameter(flagParam, "FLAG")set usingParam to _support's asWholeNumberParameter(usingParam, "USING")set directParam to _support's asTextParameter(directParam, "")to SOME HANDLER directParam USING usingParam FLAG flagParam : (false)_support's throwCommandError("LIBRARY_NAME", handlerName, eText, eNumber, eFrom, eTo)property _support : a reference to script "TypeSupport"end HTTP status name_error("HTTP status name", eText, eNumber, eFrom, eTo)return (current application's NSHTTPURLResponse's localizedStringForStatusCode:statusCode) as textset statusCode to _support's asIntegerParameter(statusCode, "")to HTTP status name statusCodeend send HTTP request_error("send HTTP request", eText, eNumber, eFrom, eTo)return _unpackHTTPResponse(asocTask's response(), responseBodyType, responseBodyData)error (taskError's localizedDescription() as text) number taskError's code() from theURLif taskError is not missing value thenset taskError to asocTask's |error|()if asocTask's state() is current application's NSURLSessionTaskStateCanceling then -- TO DO: does Cmd-period cancel task?asocTask's cancel()if asocTask's state() is current application's NSURLSessionTaskStateSuspended then -- sanity check (shouldn't be possible for task to be suspended)current application's NSThread's sleepForTimeInterval:0.1 -- sleep for 0.1secrepeat while asocTask's state() is current application's NSURLSessionTaskStateRunningasocTask's resume()set asocTask to asocSession's dataTaskWithRequest:httpRequestset asocSession to current application's NSURLSession's sessionWithConfiguration:sessionConfig delegate:sessionTaskDelegate delegateQueue:(missing value)end URLSession:dataTask:didReceiveData:responseBodyData's appendData:asocDataon URLSession:asocSession dataTask:asocTask didReceiveData:asocDatascript sessionTaskDelegateset responseBodyData to current application's NSMutableData's |data|()set responseBodyData to missing valueset asocSession to current application's NSURLSession's sessionWithConfiguration:sessionConfigif responseBodyType is missing value thenif timeoutInSeconds is not missing value then sessionConfig's setTimeoutIntervalForRequest:timeoutInSeconds -- controls how long (in seconds) a task should wait for additional data to arrive before giving upset sessionConfig to current application's NSURLSessionConfiguration's ephemeralSessionConfiguration()set httpRequest to _makeHTTPRequest(theURL, httpMethod, requestHeaders, requestBody, timeoutInSeconds)set timeoutInSeconds to _support's asIntegerParameter(timeoutInSeconds, "timeout")if timeoutInSeconds is not missing value thento send HTTP request to theURL method httpMethod : ("GET") headers requestHeaders : {} body requestBody : (missing value) timeout timeoutInSeconds : (missing value) returning responseBodyType : (text) -- TO DO: make URL direct param (can't think of any situation where it'd be a script object)end _unpackHTTPResponsereturn {statusCode:httpResponse's statusCode(), responseHeaders:headerFields, responseBody:responseBody}_support's throwInvalidConstantParameter(responseBodyType, "returning")set responseBody to missing valueelse if responseBodyType is missing value thenset responseBody to responseBodyData's |copy|()else if responseBodyType is data then -- return NSDataset responseBody to (current application's NSString's alloc()'s initWithData:responseBodyData encoding:responseBodyEncoding) as texterror "Can't automatically decode HTTP response as text as it didn't specify a Content-Type with a supported charset." number -1700if responseBodyEncoding is missing value thenif asocContentType is not missing value then set responseBodyEncoding to _NSStringEncodings's getEncoding(_parseCharset(asocContentType))set asocContentType to asocHeaderFields's objectForKey:"Content-Type"set responseBodyEncoding to missing valueif responseBodyType is text thenset end of headerFields to {headerName:asocKey as text, headerValue:(asocHeaderFields's objectForKey:asocKey) as any}set asocKey to (headerKeys's objectAtIndex:i)repeat with i from 0 to (asocHeaderFields's |count|()) - 1set headerKeys to asocHeaderFields's allKeys()set asocHeaderFields to httpResponse's allHeaderFields()set headerFields to {}to _unpackHTTPResponse(httpResponse, responseBodyType, responseBodyData)end _makeHTTPRequestreturn httpRequest_support's throwInvalidParameter(requestBody, "body", {text, «class ocid»}, "Not a text or NSData object.")httpRequest's setValue:"application/octet-stream" forHTTPHeaderField:"Content-Type" -- arbitrary binary dataif httpRequest's valueForHTTPHeaderField:("Content-Type" is missing value) thenhttpRequest's setHTTPBody:requestBodyelse if _support's checkTypeForValue(requestBody, «class ocid») and (requestBody's isInstanceOfType:(current application's NSData's |class|())) thenhttpRequest's setHTTPBody:bodyData_support's throwInvalidParameter(requestHeaders, "body", {text, «class ocid»}, "Can’t encode the given text using the charset specified by the Content-Type header: " & contentType)if bodyData is missing value thenset bodyData to _support's asNSString(requestBody)'s dataUsingEncoding:requestBodyEncoding_support's throwInvalidParameter(requestHeaders, "headers", list, "The Content-Type header specifies a charset that cannot be automatically encoded by this handler (e.g. use a different charset or supply the request body as an NSData object instead).")if requestBodyEncoding is missing value thenset requestBodyEncoding to _NSStringEncodings's getEncoding(charsetName)else -- automatically encode the body text using the specified charset (assuming it's one directly recognized by NSString's dataUsingEncoding: method)httpRequest's setValue:(contentType & ";charset=utf-8") forHTTPHeaderField:"Content-Type"if charsetName is missing value then -- if Content-Type doesn't include charset parameter then use UTF8 by defaultset charsetName to _parseCharset(_support's asNSString(contentType))else -- user has specified Content-Type for body (e.g. "application/json;charset=utf8")set requestBodyEncoding to NSUTF8StringEncodinghttpRequest's setValue:"text/plain;charset=utf-8" forHTTPHeaderField:"Content-Type"if contentType is missing value then -- encode text-based body as UTF8 by defaultset contentType to httpRequest's valueForHTTPHeaderField:"Content-Type"if (count {requestBody} each text) = 1 then -- given a text value to use as the request body, encode it using rgw xhEAWR specified by the user-supplied Content-Type, if any,if requestBody is not missing value then -- requestBody may be supplied as text or NSData -- TO DO: what about file object?(httpRequest's setValue:headerValue forHTTPHeaderField:headerName) -- TO DO: does NSHTTPRequest sanitize these inputs; if not, how should they be treated here?_support's throwInvalidParameter(aRef, "headers", list, "The following header is not allowed in the headers list as it is already set automatically: " & headerName)if headerName is in _excludeHeaders then_support's throwInvalidParameter(aRef, "headers", list, "Not a list of valid HTTP header records.")if {eNum} is not in {-1700, -1703, -1728} then error eText number eNum from eFrom to eToon error eText number eNum from eFrom to eToset {headerName, headerValue} to {headerRecord's headerName, headerRecord's headerValue}if (count headerRecord each text) ≠ 2 then error number -1703 -- note: requiring text values here avoids any risk of numbers being accidentally coerced to inappropriate localized representations (e.g. "1,0" instead of "1.0"); user should use Number library's `format number` command to convert numbers to non-localized format firstset headerRecord to aRef's contents as recordrepeat with aRef in _support's asListParameter(requestHeaders, "headers")if requestHeaders is not missing value thenif timeoutInSeconds is not missing value then httpRequest's setTimeoutInterval:timeoutInSeconds -- If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out.httpRequest's setHTTPMethod:httpMethodset httpMethod to _support's asTextParameter(httpMethod, "method") -- TO DO: what if any checks are needed here (e.g. non-empty/invalid chars)set httpRequest to current application's NSMutableURLRequest's requestWithURL:(_support's asNSURLParameter(theURL, "to"))to _makeHTTPRequest(theURL, httpMethod, requestHeaders, requestBody, timeoutInSeconds)end _parseCharsetreturn (asocContentType's substringWithRange:(asocMatch's rangeAtIndex:2)) as textif asocMatch is missing value then return missing valueset asocMatch to asocPattern's firstMatchInString:asocContentType options:0 range:{0, asocContentType's |length|()}set asocPattern to current application's NSRegularExpression's regularExpressionWithPattern:"(?i);\\s*charset\\s*=\\s*(\"?)(.+?)\\1\\s*(?:;|$)" options:0 |error|:(missing value) -- sloppy non-RFC1341 pattern not appropriate for general parameter matching, but adequate here as the value will be rejected anyway unless it matches one of the encoding names defined aboveto _parseCharset(asocContentType)end getEncodingif {textEncoding} is in aRef's item 1 then return aRef's item 2repeat with aRef in my _listconsidering diacriticals, hyphens, punctuation and white space but ignoring case and numeric stringsif _list is missing value then _init()to getEncoding(textEncoding)end _init{{"windows-1254", "windows1254", "cp1254"}, current application's NSWindowsCP1254StringEncoding}}{{"windows-1253", "windows1253", "cp1253"}, current application's NSWindowsCP1253StringEncoding}, ¬{{"windows-1252", "windows1252", "cp1252"}, current application's NSWindowsCP1252StringEncoding}, ¬{{"windows-1251", "windows1251", "cp1251"}, current application's NSWindowsCP1251StringEncoding}, ¬{{"windows-1250", "windows1250", "cp1250"}, current application's NSWindowsCP1250StringEncoding}, ¬{{"shift-jis", "s-jis", "sjis"}, current application's NSShiftJISStringEncoding}, ¬{{"macroman"}, current application's NSMacOSRomanStringEncoding}, ¬{{"euc-jp", "u-jis", "eucjp", "ujis"}, current application's NSJapaneseEUCStringEncoding}, ¬{{"iso-8859-2", "latin2", "iso8859-2"}, current application's NSISOLatin2StringEncoding}, ¬{{"iso-8859-1", "latin1", "iso8859-1"}, current application's NSISOLatin1StringEncoding}, ¬{{"iso-2022-jp", "iso2022jp", "csiso2022jp"}, current application's NSISO2022JPStringEncoding}, ¬{{"ascii"}, current application's NSASCIIStringEncoding}, ¬{{"utf-32le", "utf32le"}, current application's NSUTF32LittleEndianStringEncoding}, ¬{{"utf-32be", "utf32be"}, current application's NSUTF32BigEndianStringEncoding}, ¬{{"utf-32", "utf32"}, current application's NSUTF32StringEncoding}, ¬{{"utf-16le", "utf16le"}, current application's NSUTF16LittleEndianStringEncoding}, ¬{{"utf-16be", "utf16be"}, current application's NSUTF16BigEndianStringEncoding}, ¬{{"utf-16", "utf16"}, current application's NSUTF16StringEncoding}, ¬set _list to {¬ {{"utf-8", "utf8"}, current application's NSUTF8StringEncoding}, ¬to _init()property _list : missing valuescript _NSStringEncodings -- used by `send HTTP request` to automatically encode/decode text-based request/response body dataproperty _excludeHeaders : {"Authorization", "Connection", "Host", "Proxy-Authenticate", "Proxy-Authorization", "WWW-Authenticate", "Content-Length"} -- note: unlike authorization headers, "Content-Length" isn't reserved by NSSession but is already set automatically so no point allowing users to override with potentially wrong valueend decode Base64_error("decode Base64", eText, eNumber, eFrom, eTo)if asocString is missing value then _support's throwInvalidParameter(theText, "", text, "Base64-encoded data doesn't contain UTF8-encoded text.")set asocString to (current application's NSString's alloc()'s initWithData:asocData encoding:(current application's NSUTF8StringEncoding))set asocData to current application's NSData's alloc()'s initWithBase64EncodedString:theText options:(current application's NSDataBase64DecodingIgnoreUnknownCharacters) -- ignores line breaks and other non-Base64 chars; TO DO: would it be better to strip white space chars separately, then fail if text contains any other non-Base64 charsto decode Base64 theTextend encode Base64_error("encode Base64", eText, eNumber, eFrom, eTo)return asocString's dataUsingEncoding:((current application's NSUTF8StringEncoding)'s base64EncodedStringWithOptions:0)set asocString to _support's asNSString(_support's asTextParameter(theText, ""))to encode Base64 theTextend decode JSON_error("decode JSON", eText, eNumber, eFrom, eTo)return jsonObject as anyif jsonObject is missing value then error "Not valid JSON (" & theError's localizedDescription() & ")." number -1703 from jsonTextset {jsonObject, theError} to current application's NSJSONSerialization's JSONObjectWithData:theData options:readOptions |error|:(specifier)set theData to _support's asNSString(jsonText)'s dataUsingEncoding:(current application's NSUTF8StringEncoding)set readOptions to 0set readOptions to current application's NSJSONReadingAllowFragmentsif _support's asBooleanParameter(areFragmentsAllowed, "allowing fragments") thenset jsonText to _support's asTextParameter(jsonText, "")to decode JSON jsonText fragments allowed areFragmentsAllowed : (false)end encode JSON_error("encode JSON", eText, eNumber, eFrom, eTo)return (current application's NSString's alloc()'s initWithData:theData encoding:(current application's NSUTF8StringEncoding)) as textif theData is missing value then error "Can’t convert object to JSON(" & theError's localizedDescription() & ")." number -1703 from jsonObjectset {theData, theError} to current application's NSJSONSerialization's dataWithJSONObject:jsonObject options:writeOptions |error|:(specifier)error "Can’t convert object to JSON (found unsupported object type)." number -1703 from jsonObjectif not (current application's NSJSONSerialization's isValidJSONObject:jsonObject) thenset writeOptions to 0set writeOptions to current application's NSJSONWritingPrettyPrintedif _support's asBooleanParameter(isPrettyPrinted, "extra white space") thento encode JSON jsonObject extra white space isPrettyPrinted : (false)end join URL query string_error("join URL query string", eText, eNumber, eFrom, eTo)return queryTextset queryText to queryList as textset aRef's contents to _replaceText((encode URL characters (kvPair's item 1) preserving space) & "=" & (encode URL characters (kvPair's item 2) preserving space), space, "+")error "Invalid query list (keys and values must be text)." number -1703 from aRefif not (count kvPair each text) = 2 thenif not (count {kvPair} each list) = 1 and kvPair's length = 2 then error "Invalid query list (not a list of key-value sublists)." number -1703 from aRefset kvPair to aRef's contentsset queryList to _support's asList(queryList, "")'s itemsto join URL query string queryListend split URL query string_error("split URL query string", eText, eNumber, eFrom, eTo)return queryListset AppleScript's text item delimiters to oldTIDsset aRef's contents to {decode URL characters (item 1 of queryParts), decode URL characters (item 2 of queryParts)}if length of queryParts ≠ 2 then error "Invalid query string." number -1703 from queryText -- TO DO: implement 'without strict parsing' option, in which case missing `=` wouldn't throw error?set queryParts to text items of (get aRef's contents)repeat with aRef in queryListset AppleScript's text item delimiters to "="set queryList to queryText's text itemsset AppleScript's text item delimiters to "&"set queryText to _replaceText(_support's asTextParameter(queryText, ""), "+", space)set oldTIDs to AppleScript's text item delimitersto split URL query string queryTextend decode URL characters_error("decode URL characters", eText, eNumber, eFrom, eTo)if asocResult is missing value then error "Couldn't convert percent escapes to characters (e.g. not valid UTF8)." number -1703 from theTextset asocResult to _support's asNSString(theText)'s stringByRemovingPercentEncoding() -- Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters. (NSURLUtilites, 10.9+)to decode URL characters theTextend encode URL characters_error("encode URL characters", eText, eNumber, eFrom, eTo)return asocResult as textif asocResult is missing value then error "Couldn't convert characters to percent escapes." number -1703 from theText -- NSString docs are hopeless on detailsset asocResult to _support's asNSString(theText)'s stringByAddingPercentEncodingWithAllowedCharacters:asocAllowedChars -- Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.set asocAllowedChars to current application's NSCharacterSet's characterSetWithCharactersInString:allowedCharactersset allowedCharacters to _safeCharacters & _support's asTextParameter(allowedCharacters, "preserving")set theText to _support's asTextParameter(theText, "")to encode URL characters theText preserving allowedCharacters : ("")end _replaceTextreturn theList as textset AppleScript's text item delimiters to toTextset theList to theText's text itemsset AppleScript's text item delimiters to fromTextto _replaceText(theText, fromText, toText)property _safeCharacters : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."end join URL_error("join URL", eText, eNumber, eFrom, eTo)return urlTextset urlText to asocURL as textif asocURL is missing value then error "Not a valid URL." number -1703 from urlTextset asocURL to current application's NSURL's URLWithString:urlText relativeToURL:baseURLset baseURL to _support's asNSURLParameter(baseURL, "using base URL")if baseURL is not "" thenset urlText to _support's asTextParameter(urlRecord, "")else -- assume it's a relative URL string that's going to be joined to baseURLif fragmentIdentifier is not "" then set urlText to urlText & "#" & fragmentIdentifierif queryString is not "" then set urlText to urlText & "?" & queryStringif parameterString is not "" then set urlText to urlText & ";" & parameterStringif urlScheme is not "" then set urlText to urlScheme & ":" & urlTextset urlText to resourcePathset urlText to "//" & networkLocation & resourcePathif resourcePath is not "" and resourcePath does not start with "/" then set resourcePath to "/" & resourcePathif networkLocation is not "" or (urlScheme is not "" and urlScheme is in _usesNetLoc and resourcePath does not start with "//") then -- copied from Python's urllib.parse moduleset resourcePath to encode URL characters resourcePath preserving "/" -- `split URL` (i.e. NSURL) automatically decodes % escapes in resource path, so automatically encode them here_support's throwInvalidParameter(urlRecord, "", record, "URL components record’s ‘networkLocation’ property is not text.")set networkLocation to fullURLRecord's networkLocation as textset networkLocation to _joinNetworkLocation(fullURLRecord's networkLocation)if (count {fullURLRecord's networkLocation} each record) ≠ 0 thenset {urlScheme, resourcePath, parameterString, queryString, fragmentIdentifier} to urlComponents_support's throwInvalidParameter(urlRecord, "", record, "URL components record’s ‘" & (item ((length of urlComponents) + 1) of {"urlScheme", "resourcePath", "parameterString", "queryString", "fragmentIdentifier"}) & "’ property is not text.")set urlComponents to {urlScheme, resourcePath, parameterString, queryString, fragmentIdentifier} of fullURLRecordset fullURLRecord to _support's asOptionalRecordParameter(urlRecord, {urlScheme:"", networkLocation:"", resourcePath:"", parameterString:"", queryString:"", fragmentIdentifier:""}, "")if (count {urlRecord} each record) ≠ 0 thenconsidering case, diacriticals, hyphens, punctuation and white space but ignoring numeric stringsto join URL urlRecord using base URL baseURL : ("") -- TO DO: if baseURL is given, direct parameter should be either record or textend split URL_error("split URL", eText, eNumber, eFrom, eTo)on error eText number eNumber from eFrom to eToreturn {urlScheme:_asComponent(asocURL's scheme()), networkLocation:networkLocation, resourcePath:_asComponent(asocURL's path()), parameterString:_asComponent(asocURL's parameterString()), queryString:_asComponent(asocURL's query()), fragmentIdentifier:_asComponent(asocURL's fragment())}set networkLocation to _joinNetworkLocation(networkLocation)if not _support's asBooleanParameter(splitNetworkLocation, "network location record") thenset networkLocation to {userName:_asComponent(asocURL's user()), userPassword:_asComponent(asocURL's password()), hostName:_asComponent(asocURL's host()), portNumber:_asComponent(asocURL's port())}set asocURL to _support's asNSURLParameter(urlText, "")to split URL urlText network location record splitNetworkLocation : (false)end _joinNetworkLocationreturn hostNameif portNumber is not "" then set hostName to hostName & ":" & portNumberset hostName to userName & hostNameif hostName is "" and not (userName is "" and portNumber is "") then error "Invalid network location record (missing ‘hostName’ property)." number -1703 from urlRecordif userName is not "" then set userName to userName & "@"if userPassword is not "" then set userName to userName & ":" & userPasswordset {userName, userPassword, hostName, portNumber} to urlComponentserror "Invalid network location record (‘" & (item ((length of urlComponents) + 1) of {"userName", "userPassword", "hostName", "portNumber"}) & "’ property is not text)." number -1703 from urlRecordon error number -1700set aRef's contents to aRef's contents as textrepeat with aRef in urlComponentsset urlComponents to {userName, userPassword, hostName, portNumber} of fullNetLocRecordset fullNetLocRecord to _support's asOptionalRecordParameter(networkLocationRecord, {userName:"", userPassword:"", hostName:"", portNumber:""}, "")to _joinNetworkLocation(networkLocationRecord)end _asComponentreturn asocString as textif asocString is missing value then return ""to _asComponent(asocString)property _usesNetLoc : {"ftp", "http", "gopher", "nntp", "telnet", "imap", "wais", "file", "mms", "https", "shttp", "snews", "prospero", "rtsp", "rtspu", "rsync", "", "svn", "svn+ssh", "sftp", "nfs", "git", "git+ssh"}end _error_support's throwCommandError("Web", handlerName, eText, eNumber, eFrom, eTo)to _error(handlerName, eText, eNumber, eFrom, eTo)property _support : a reference to script "TypeSupport" -- used for parameter checkingdisplay dialog the_error buttons {"OK"} with icon caution with title "Error"on error the_errordisplay dialog git_status buttons {"OK"} with title "Init Repo"set git_status to (do shell script "cd \"" & current_path & "\"; git init")set current_path to (POSIX path of (target of front window as alias))end lockscrnaKeyChain's performSelector:"_lockScreenMenuHit:" withObject:(null) afterDelay:0.0set aKeyChain to aObj's initset aObj to aClass's allocset aClass to bundle's classNamed:"AppleKeychainExtra"bundle's loadset bundle to current application's NSBundle's bundleWithPath:"/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu/"on lockscrn()my lockscrn()log "The first ?? is " & firstWindowset firstWindow to the name of window 1log "?? list " &linefeed & nameListset nameList to the name of every window& recName"Icon not changed because item is not a group: " ¬log message "[" & scriptName & "] " & ¬set recName to name of recset thumbnail of rec to thumbnail of locGroupset locGroup to location group of recif recType is in {"group", "«constant ****DTgr»", ¬ "smart group", "«constant ****DTsg»"} thenset recType to (type of rec) as stringrepeat with rec in (selected records)property scriptName : "Set group icon to parent icon"display dialog "Hello World!"tell application "System Events" to keystroke "f" using {control down, command down}make new window with properties {mode:"incognito"}close windowstell application "Brave Browser"if "Brave Browser" is not in listOfProcesses thentell application "System Events" to set listOfProcesses to (name of every process where background only is false)return current application's NSString's stringWithString:aStringon str(aString)end matchesForPatternAndStringreturn allMatchedStrings(allMatchedStrings's addObject:(aString's substringWithRange:((item i of allMatches)'s rangeAtIndex:1)))repeat with i from 1 to count of allMatchesset allMatchedStrings to current application's NSMutableArray's arrayset allMatches to regEx's matchesInString:aString options:0 range:aRangeset aRange to current application's NSMakeRange(0, aString's |length|())set regEx to current application's NSRegularExpression's regularExpressionWithPattern:aPattern options:1 |error|:(null)on matchesForPatternAndString(aPattern, aString)end matchesForPatternsAndStringsreturn (allMatches's componentsJoinedByString:return) as text(allMatches's addObject:(allMatchesForThisLine's componentsJoinedByString:""))(allMatchesForThisLine's addObjectsFromArray:matchesForThisPattern)set matchesForThisPattern to matchesForPatternAndString(item j of thePatterns, item i of theStrings)repeat with j from 1 to count of thePatternsset allMatchesForThisLine to current application's NSMutableArray's arrayrepeat with i from 1 to count of theStringsset allMatches to current application's NSMutableArray's arrayset theStrings to theStrings's componentsSeparatedByString:returnset thePatterns to thePatterns's componentsSeparatedByString:returnset theStrings to str(theStrings)set thePatterns to str(thePatterns)on matchesForPatternsAndStrings(thePatterns, theStrings)log "Result length: " & length of theResult & " characters"log "Processed " & (count of paragraphs of thePatterns) * (count of paragraphs of theStrings) & " regular expressions"log "Duration: " & ((current date) - startDate) & "s"set theResult to matchesForPatternsAndStrings(thePatterns, theStrings)set startDate to current dateset theStrings to theStrings & return & theStringsset thePatterns to thePatterns & return & thePatternsrepeat 7 timesset theStrings to "R17-11517 r17-11518 r17-11519 R17-11518 R17-11519"set thePatterns to "(r\\s*\\d\\s*\\d\\s*[-\\s]*\\d\\s*\\d\\s*\\d\\s*\\d\\s*\\d)"open location google_translate_look_up_urlset URL of t to google_translate_look_up_urlif URL of t starts with google_translate_url thenrepeat with t in tabs of chrome_windowrepeat with chrome_window in windowsset google_translate_look_up_url to google_translate_url & "/?hl=" & ui_lang & "&sl=" & from_lang & "&tl=" & to_lang & "&text=" & phraseset google_translate_url to "https://translate.google.com"set to_lang to "zh-CN"set from_lang to "auto"set ui_lang to "en"set phrase to input as stringdelete list id _idset _id to (id of l)repeat with l in every listmake new list with properties {name:"test10"}make new list with properties {name:"test9"}make new list with properties {name:"test8"}make new list with properties {name:"test7"}make new list with properties {name:"test6"}make new list with properties {name:"test5"}make new list with properties {name:"test4"}make new list with properties {name:"tes3"}make new list with properties {name:"test2"}make new list with properties {name:"test"}tell application "Messages" to quitclick menu item "AutoAccept.scpt" of menu 1 of script_menuclick script_menuset script_menu to pop up button 3click applescript_boxif not value of applescript_box as boolean thenset applescript_box to checkbox "Run an AppleScript script:"click menu item "Invitation to Share My Screen" of menu 1 of pop up button 2click pop up button 2tell group 1 of group 1 of window 1click button "Alerts" of tool bar 1 of window 1keystroke "," using command downtell process "iChat"tell application "Messages" to activatedo script \"" & uid & "\"tell application \"Keyboard Maestro Engine\""-- ignoring application responsesset the clipboard to ¬set uid to id of first macro whose selected is truedisplay alert "Error" message "Multiple Macros Selected" as critical buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel"if class of item 1 of sel is macro and (count of items of sel) > 1 thentheShortcutsListset the clipboard to theShortcutsListlog theShortcutsCount -- 41set theShortcutsCount to theShortcutsCount + 1set theShortcutsList to theShortcutsList & return & itemPropsset itemProps to "\"" & (name of theItem) & "\", \"" & (shortcut string of keyboard shortcut of theItem) & "\", " & (script file of theItem)log (get script file of theItem)log (get keyboard shortcut of theItem)log (get name of theItem)if keyboard shortcut of theItem is not missing value thenrepeat with theItem in (every script item)set theShortcutsCount to 0set theShortcutsList to "name, shortcut, script_file"properties of script item 1get (keyboard shortcut of script item 1 is missing value)get name of every recently run script itemget top level script collectiontell application "FastScripts"system attribute "LOGNAME"return todo_liststell application "Reminders" to set todo_lists to (get name of every list)do shell script "sips -s format png " & pathFile & " --out " & destFileset destFile to quoted form of destFolderset destFile to destFolder & "/" & baseName & ".png"set baseName to text 1 thru -5 of baseNameset baseName to do shell script "basename " & pathFiledisplay dialog ("Hello " & user_name & "!") set user_name to "Ben"set value of slider 1 of group 1 of tab group 1 of window 1 of process "System Preferences" to 0set subject to "" & subjectset AppleScript's text item delimiters to replaceset AppleScript's text item delimiters to searchon replace(search, replace, subject)end addTrackdisplayNotice(track)do shell script "curl " & quoted form of replace(" ", "+", theURL)set theURL to "https://maker.ifttt.com/trigger/YOUR_MAKER_EVENT_NAME_HERE/with/key/YOUR_MAKER_KEY_HERE?value1=" & (item 2 of track) & "&value2=" & (item 1 of track)on addTrack(track)end displayNoticedisplay notification "Added to your music" with title item 2 of track subtitle item 1 of trackon displayNotice(track)end getTrackreturn {artistName, trackName}set trackName to name of current track as stringset artistName to artist of current track as stringon getTrack()addTrack(track)set track to getTrack()do script "THISSTYLE=\"paraiso-light\"; pygmentize -f tex -S $THISSTYLE -a .syntax > fig/style.tex" in shelldo script "if [ -d $THISSUBDIR ]; then echo \"### Subdir \"$THISSUBDIR\" exists ###\"; else mkdir $THISSUBDIR; fi" in shelldo script "THISSUBDIR=\"fig\"" in shelldo script "cd " & docPath in shellset shell to do script "# -----------CREATING PYGMENTS STYLE FILE in: " & docPath & " -----------" in window 1set docPath to "" & (do shell script "awk 'BEGIN {THISSTR=\"" & testn & "\"; sub(/" & docNmNoSlash & "/, \"\", THISSTR); print THISSTR}'")set docNmNoSlash to "" & (do shell script "awk 'BEGIN {THISSTR=\"" & docName & "\"; sub(\"/\", \"\", THISSTR); print THISSTR}'")set testn to docNameAndPathset docName to POSIX path of (get name of front document)set docNameAndPath to POSIX path of (get file of front document)tell application "TextWrangler"end devTextlog theListset AppleScript's text item delimiters to aDelimiteron devText(theText, aDelimiter)display dialog "よっしゃ。Evernoteにノート作っといたで" buttons {"OK"} with title appnameset curnote to create note with html answerResults title date string of (current date) & "の" & reportType & "やで"set answerResults to answerResults & "

      " & nextCursor & "に向けて

      " & "

      " & theText & "

      "display dialog nextCursor & "はどないする?" buttons {"OK"} default answer "" & return & return & return & return & return & return & return & return & return with title appnameelse if button_returned is "あらへん" thenset answerResults to answerResults & "

      その他

      " & "

      " & theText & "

      "display dialog "なんや言うてみい?" buttons {"OK"} default answer "" & return & return & return & return & return & return & return & return & return with title "進捗どないや?"if button_returned is "あったわ" thendisplay dialog "もう終わりか? 他にはないか?" buttons {"あらへん", "あったわ"} with title appnameset answerResults to answerResults & "

      " & i & "

      " & "

      " & theText & "

      "display dialog nmessage & i & "はどうやってん?" buttons {"OK"} default answer "" & return & return & return & return & return & return & return & return & return with title appnameif x is not 0 then set nmessage to "そうか、お疲れさん。" & returnrepeat with i in projectlistset answerResults to ""set nmessage to ""set x to 0set projectlist to my devText(myResult, ",")set myResult to text returned of resultdisplay dialog nowCursor & "なにやった?" & return & "(ぎょーさんある場合はカンマで区切ってな)" default answer "" with title appnameset nextCursor to "来週"set nowCursor to "今週"else if reportType is "週報" thenset nextCursor to "明日"set nowCursor to "今日"if reportType is "日報" thenset reportType to button_returnedset button_returned to button returned of resultdisplay dialog "日報か?週報か?" buttons {"キャンセル", "日報", "週報"} with title appnameset nowCursor to ""set nextCursor to ""set reportType to ""set projectlist to {}property appname : "進捗どないや?"else if browserName is "Microsoft Edge" thenset URL_list to mdURL & return & URL_listset mdURL to "[" & title of i & "](" & URL of i & ")"set i to active tab of window 1tell application "Microsoft Edge Canary"if browserName is "Microsoft Edge Canary" thenreturn {x, y}do shell script cliclick_path & " m:" & x & "," & yset cliclick_path to "/opt/homebrew/bin/cliclick"set y to ((item 2 of posRay) + 0)set x to ((item 1 of posRay) + primWidth) # the difference between the two scripts (- vs +)set posRay to my split(posStr, ",")set posStr to do shell script "/opt/homebrew/bin/cliclick p"set primHeight to (word 4 of dimensions) + 0 # str -> numberset primWidth to (word 2 of dimensions) + 0 # str -> numberset dimensions to (do shell script "system_profiler SPDisplaysDataType | grep Resolution")set qwote to "\""do shell script cmdset cmd to "mkdir " & ""end _urlEncodereturn theTextEncset theTextEnc to theTextEnc & useChar as stringset useChar to numHex& (secondDig as string)) as stringset numHex to ("%" & (firstDig as string) ¬set secondDig to ASCII character aNumset aNum to secondDig + 55if secondDig > 9 thenset firstDig to ASCII character aNumset aNum to firstDig + 55if firstDig > 9 thenset secondDig to eachCharNum mod 16set firstDig to round (eachCharNum / 16) rounding downand (eachCharNum < 97 or eachCharNum > 122) thenand (eachCharNum < 65 or eachCharNum > 90) ¬and (eachCharNum < 48 or eachCharNum > 57) ¬and (eachCharNum < 45 or eachCharNum > 46) ¬else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) ¬set useChar to "+"if eachCharNum = 32 thenset eachCharNum to ASCII number of eachCharset useChar to eachCharrepeat with eachChar in characters of theTextset theTextEnc to ""on _urlEncode(theText)end bitlyShortendisplay dialog areturn _bitlyUrlset _bitlyUrl to "http://" & text item 1 of _bitlyUrlset AppleScript's text item delimiters to "\""set _bitlyUrl to text item 3 of _bitlyUrlset AppleScript's text item delimiters to "http://"tell me to set _bitlyUrl to (do shell script curlCMD)& "\"| grep shortUrl | grep -o http.*[/a-zA-Z0-9]"& "&apiKey=" & api_key ¬"curl --stderr /dev/null \"http://api.bit.ly/shorten?longUrl=" & _encodedUrl & "&history=1&version=2.0.1&login=" & login ¬¬set curlCMD to ¬tell application "Finder" to open location "https://bitly.com/a/your_api_key/"if the button returned of the result is "OK" thenset question to display dialog "Sorry, you need to open the script and provide your bitly username and api key. You can get them from: " & return & "https://bitly.com/a/your_api_key/" & return & "Open this location now?" giving up after 15if login is "" or api_key is "" thenset the _encodedUrl to _urlEncode(_text) of meset api_key to "XXXX" -- Put your API key hereset login to "XXXX" -- Put your login name hereon bitlyShorten(_text)end switchTextttell t to set t to item 1 & ({""} & rest)set text item delimiters to rset t to t's text itemsset text item delimiters to sto switchText from t to r instead of sdelay 1 --> allow time for the notification to triggerdisplay notification shortURL & " copied to clipboard."set the clipboard to shortURL as textset shortURL to bitlyShorten(theURL)set theURL to "http://dl.getdropbox.com/u/XXX/screenshots/" & theWebSafeFileName// XXX = dropbox idset theWebSafeFileName to switchText from theFileName to "%20" instead of " "set theFileName to (text item 7 of theRawFilename) as textset theRawFilename to ("" & theFile)set theFile to item 1 of added_itemsif the item_count is equal to 1 thenset the item_count to the number of items in the added_itemson adding folder items to this_folder after receiving added_itemsmove mvfiles to destFolderset destFolder to destFolderPath as stringset destFolder to name of destFolderPathset destFolderPath to choose folderset mvfiles to selectionscriptRunrun script scriptRunset scriptRun to _Path & "/" & scriptLaunch & ".scpt"else if scriptLaunch contains scriptLaunch thenif scriptLaunch contains "" thenset scriptLaunch to text returned of (display dialog "Enter name of script to run" default answer "" buttons "OK" default button "OK")set _Path to "/Users/will/Desktop/Scripts"log "done in " & (current date) - everythingStartTime & "s"writeRaytracedImage(outputFile, numWorkers, worker, imageWidth, samplesPerPixel, maxBounces)random number with seed my randomSeedlog "rendering to "&outputFileset everythingStartTime to current dateset outputFile to getWorkerPartFilename(outputFileBase, worker)set worker to (item 1 of argv) as numberset outputFileBase to (item 2 of argv) as textdo shell script "tail -n +4 "&workerPartFile&" >> "&outputFile&" && rm "&workerPartFileset workerPartFile to getWorkerPartFilename(outputFileBase, workerReverse)set workerReverse to (numWorkers-1) - workerclose access outfileset outfile to open for access outputFile with write permissiondo shell script "touch " & outputFiledo shell script commands&"wait"log commands&"wait"log "running"set commands to commands&"./raytracer.applescript "& worker & " " & outputFileBase & " " &" & "repeat with worker from 0 to numWorkers-1log "starting workers: "&numWorkersset commands to ""set outputFile to outputFileBase&".ppm"set outputFileBase to "output_"&(time of (current date))if (item 1 of argv) as text is "smp"set numWorkers to my numSMPWorkersset outputFile to "output_"&(time of (current date))&".ppm"set worker to 0set numWorkers to 1if argv is {}set maxBounces to my renderConfig's maxBouncesset samplesPerPixel to my renderConfig's samplesPerPixelset imageWidth to my renderConfig's imageWidthlocal outputFilelocal numWorkerslocal workerbase&"part_"&worker&".ppm"on getWorkerPartFilename(base, worker)end writeRaytracedImagewritePPMHeader(outfile,actualChunkSize,imageWidth)log "raytracing took " & (current date) - raytracingStartTime & "s"set rowCount to rowCount + 1log "rendered scanline " & imgrow & " in " & (current date) - scanlineStartTime & "s ("& (round ((rowCount/actualChunkSize)*100))&"%)"imagedata's append(correctColor(v3ToColor(v3divScalar(pixelColor, samplesPerPixel))))v3addMut(pixelColor, rayColor(r, world, maxBounces))set r to cam's getRay(u, v)set v to (imgrow + random number) / (imageHeight-1)set u to (imgcol + random number) / (imageWidth-1)repeat with sample from 0 to samplesPerPixelset pixelColor to v3origin()set imgcol to 0 -- iset scanlineStartTime to current daterepeat until imgrow < chunkStartset rowCount to 0set imgrow to nextChunkStart - 1 -- jset actualChunkSize to nextChunkStart - chunkStartset nextChunkStart to min((chunkSize * (worker + 1)), imageHeight)set chunkStart to chunkSize * workerset chunkSize to round (imageHeight / numWorkers) rounding upset raytracingStartTime to current datelog "begin raytracing with " & (count (world's objects)) & " objects"set cam to newCamera(v3(13,2,3), v3(0,0,0), v3(0,1,0), 20, aspectRatio)set world to randomScene()set imageHeight to round (imageWidth / aspectRatio) rounding downset aspectRatio to 16.0 / 9.0on writeRaytracedImage(filename, numWorkers, worker, imageWidth, samplesPerPixel, maxBounces)world's add(newSphere(v3(4, 1, 0), 1.0, material3))set material3 to newMetal(v3(0.7, 0.6, 0.5), 0.0)world's add(newSphere(v3(-4, 1, 0), 1.0, material2))set material2 to newLambertian(v3(0.4, 0.2, 0.1))world's add(newSphere(v3(0, 1, 0), 1.0, material1))set material1 to newDielectric(1.5)set sphereMaterial to newDielectric(1.5)set sphereMaterial to newMetal(albedo, fuzz)set fuzz to randomInRange(0, 0.5)set albedo to v3randomInRange(0.5, 1)else if (chooseMat < 0.95)world's add(newSphere(sphereCenter, 0.2, sphereMaterial))set sphereMaterial to newLambertian(albedo)set albedo to v3mul(v3randomInRange(0,1), v3randomInRange(0,1))if (chooseMat < 0.8)if (v3length(v3sub(sphereCenter, v3(4, 0.2, 0))) > 0.9)set sphereCenter to v3(a + 0.9*(random number), 0.2, b + 0.9*(random number))set chooseMat to (random number)repeat with b from minPos to maxPos by stepSizerepeat with a from minPos to maxPos by stepSizeset stepSize to round ((maxPos - minPos) / sqrt(numItems)) rounding upset numItems to 5set maxPos to 3set minPos to -3world's add(newSphere(v3(0,-1000,0), 1000, groundMaterial))set groundMaterial to newLambertian(v3(0.5, 0.5, 0.5))on randomScene()return worldworld's add(newSphere(v3( 1.0, 0.0, -1.0), 0.5, materialMetal)) -- rightworld's add(newSphere(v3(-1.0, 0.0, -1.0), 0.5, materialGlass)) -- leftworld's add(newSphere(v3( 0.0, 0.0, -1.0), 0.5, materialBlue)) -- centerworld's add(newSphere(v3( 0.0, -100.5, -1.0), 100.0, materialGround)) -- groundset world to newHittableList({})set materialGlass to newDielectric(1.5)set materialMetal to newMetal(v3(0.8, 0.6, 0.2), 1)set materialBlue to newLambertian(v3(0.1, 0.2, 0.5))set materialGround to newLambertian(v3(0.5, 0.5, 0.5))on simpleScene()return v3add(v3mulScalar(v3(1.0, 1.0, 1.0),(1.0-t)), v3mulScalar(v3(0.5, 0.7, 1.0),t))set t to 0.5*(y of v3unit(direction of r) + 1.0)return v3(0,0,0)return v3mul(attenuation of scatterResult, rayColor(scattered of scatterResult, world, depth-1))if (success of scatterResult)set scatterResult to material's scatter(r, rec)log reclog "no material on"if material = nullset material to material of recset dir to v3sub(target, p of rec)set target to v3add(p of rec, rand)set rand to randomInHemisphere(normal of rec)if didHitset didHit to world's hit(r, nearZero, nearInfinity, rec)return v3origin()if depth <= 0set nearZero to 0.001set nearInfinity to 2.0e20set rec to makeHitRecord()on rayColor(r, world, depth)makeRay(my origin, v3sub(v3add(v3add(my lowerLeftCorner, v3mulScalar(my horizontal, s)), v3mulScalar(my vertical, t)), my origin))on getRay(s, t)property lowerLeftCorner: _lowerLeftCornerproperty vertical : _verticalproperty horizontal : _horizontalproperty origin : _originproperty focalLength : _focalLengthproperty viewportWidth : _viewportWidthproperty viewportHeight : _viewportHeightscript camera)w ¬), ¬v3divScalar(_vertical, 2) ¬v3sub(_origin, v3divScalar(_horizontal, 2)), ¬v3sub( ¬set _lowerLeftCorner to ¬set _vertical to v3mulScalar(v, _viewportHeight)set _horizontal to v3mulScalar(u, _viewportWidth)set _origin to v3clone(lookfrom)set v to v3cross(w, u)set u to v3unit(v3cross(vup, w))set w to v3unit(v3sub(lookfrom, lookat))set _focalLength to 1.0set _viewportWidth to aspectRatio * _viewportHeightset _viewportHeight to 2.0 * hset h to tan(vfov/2) -- this tan() function expects degreeson newCamera(lookfrom, lookat, vup, vfov, aspectRatio)return dielectric{ ¬ scattered: scattered, ¬ attenuation: v3(1.0, 1.0, 1.0), ¬ success: true ¬ }set scattered to makeRay(p of rec, direction)set direction to refract(unitDirection, normal of rec, refractionRatio)set direction to reflect(unitDirection, normal of rec)if cannotRefract or reflectance(cosTheta, refractionRatio) > random numberlocal directionset cannotRefract to refractionRatio * sinTheta > 1.0set sinTheta to sqrt(1.0 - cosTheta*cosTheta)set cosTheta to min(v3dot(v3mulScalar(unitDirection, -1), normal of rec), 1.0)set unitDirection to v3unit(direction of rIn)set refractionRatio to my indexOfRefractionset refractionRatio to (1.0/(my indexOfRefraction))if frontFace of recproperty indexOfRefraction: _indexOfRefractionscript dielectricon newDielectric(_indexOfRefraction)return metal{ ¬ scattered: scattered, ¬ attenuation: v3clone(my albedo), ¬ success: success ¬ }set success to v3dot(direction of scattered, normal of rec) > 0set scattered to makeRay(p of rec, v3add(reflected, fuzzDirection))set fuzzDirection to v3origin()set fuzzDirection to v3mulScalar(randomInUnitSphere(), my fuzz)if my fuzz > 1local fuzzDirectionset reflected to reflect(v3unit(direction of rIn), normal of rec)property fuzz: clamp(_fuzz, 0, 1)script metalon newMetal(_albedo, _fuzz)return lambertian{ ¬ scattered: makeRay(p of rec, scatterDirection), ¬ attenuation: v3clone(my albedo), ¬ success: true ¬ }set scatterDirection to normal of recif v3nearZero(scatterDirection)set scatterDirection to v3add(normal of rec, randomUnitVector())on scatter(rIn, rec)property albedo: _albedoscript lambertianon newLambertian(_albedo)return r0 + (1-r0) * ((1 - cosine)^5)set r0 to r0*r0set r0 to (1-refIdx) / (1+refIdx)on reflectance(cosine, refIdx)return v3add(rOutPerp, rOutParallel)set rOutParallel to v3mulScalar(n, -1*sqrt(abs(1.0 - v3lengthSq(rOutPerp))))set rOutPerp to v3mulScalar(v3add(uv, v3mulScalar(n, cosTheta)), etaiOverEtat)set cosTheta to min(v3dot(v3mulScalar(uv, -1), n), 1.0)on refract(uv, n, etaiOverEtat)return v3sub(v, v3mulScalar(n, 2*v3dot(v, n)))on reflect(v, n)return hittableListproperty objects: _objectsproperty parent: hittableListPrototypescript hittableListon newHittableList(_objects)return hitAnythinghitRecordCopyFrom(rec, tempRec)set closestSoFar to t of tempRecset hitAnything to trueif object's hit(r, tMin, closestSoFar, tempRec)repeat with object in my objectsset closestSoFar to tMaxset hitAnything to falseset tempRec to makeHitRecord()on hit(r, tMin, tMax, rec)set end of my objects to objecton add(object)set my objects to {}on clear()script hittableListPrototypereturn sphereproperty material: _materialproperty sphereRadius: _sphereRadiusproperty sphereCenter: _sphereCenterproperty parent: spherePrototypescript sphereon newSphere(_sphereCenter, _sphereRadius, _material)end hitset material of rec to my materialhitRecordSetFaceNormal(rec, r, outwardNormal)set outwardNormal to v3divScalar(v3sub(p of rec, my sphereCenter), my sphereRadius)set normal of rec to v3divScalar(v3sub(p of rec, my sphereCenter), my sphereRadius)set p of rec to rayAt(r, t of rec)set t of rec to rootroot = (-halfB + sqrtd) / aif (root < tMin or tMax < root)set root to (-halfB - sqrtd) / aset sqrtd to sqrt(discriminant)if (discriminant < 0)set discriminant to halfB*halfB - a*cset c to v3lengthSq(oc) - my sphereRadius*my sphereRadiusset halfB to v3dot(oc, (direction of r))set a to v3lengthSq(direction of r)set oc to v3sub((origin of r), my sphereCenter)on hit(r,tMin,tMax,rec)script spherePrototypeset normal of self to -outwardNormalset normal of self to outwardNormalif frontFace of selfset frontFace of self to v3dot((direction of r), outwardNormal) < 0on hitRecordSetFaceNormal(self, r, outwardNormal)set material of self to material of otherset frontFace of self to frontFace of otherv3copyFrom(normal of self, normal of other)v3copyFrom(p of self, p of other)set t of self to t of otheron hitRecordCopyFrom(self, other){t: 0, p: v3origin(), normal: v3origin(), frontFace: true, material: null}on makeHitRecord()cset blue of c to clamp(sqrt(blue of c), 0.0, 0.999)set green of c to clamp(sqrt(green of c), 0.0, 0.999)set red of c to clamp(sqrt(red of c), 0.0, 0.999)on correctColor(c)makeColor(x of v, y of v, z of v)on v3ToColor(v)v3add((origin of r), v3mulScalar((direction of r), t))on rayAt(r, t){origin:origin, direction:direction}on makeRay(origin, direction)return maxif (x > max)return minif (x < min)on clamp(x, min, max)return v3mulScalar(inUnitSphere, -1.0)return inUnitSphereif (v3dot(inUnitSphere, normal) > 0.0) -- In the same hemisphere as the normalset inUnitSphere to randomInUnitSphere()on randomInHemisphere(normal)v3unit(randomInUnitSphere())on randomUnitVector()return pif v3lengthSq(p) < 1set p to v3randomInRange(-1,1)on randomInUnitSphere()return (abs(x of self) < s) or (abs(y of self) < s) or (abs(z of self) < s)set s to 1e-8on v3nearZero(self)if a > bon max(a, b)if a < bon min(a, b)return random number * rng + minon randomInRange(min, max)return v3(random number * rng + min, random number * rng + min, random number * rng + min)set rng to max - minon v3randomInRange(min, max)set z of self to z of otherset y of self to y of otherset x of self to x of otheron v3copyFrom(self, other)log ("" & x in self & " " & y in self & " " & z in self)on v3print(self)x of self = 0 and y of self = 0 and z of self = 0on v3isEmpty(self)v3(x of other, y of other, z of other)on v3clone(other)v3(0,0,0)on v3origin()resset z of res to x of self * y of other - y of self * x of otherset y of res to z of self * x of other - x of self * z of otherset x of res to y of self * z of other - z of self * y of otherset res to v3(0,0,0)on v3cross(self, other)(x of u) * (x of v) + (y of u) * (y of v) + (z of u) * (z of v)on v3dot(u, v)v3divScalar(v, v3length(v))on v3unit(v)v3lengthSq(self) ^ 0.5 -- x ^ 0.5 calculates sqrt(x)on v3length(self)(x of self * x of self) + (y of self * y of self) + (z of self * z of self)on v3lengthSq(self){ ¬ x: x of self / scalar, ¬ y: y of self / scalar, ¬ z: z of self / scalar ¬ }on v3divScalar(self, scalar){ ¬ x: x of self / x of other, ¬ y: y of self / y of other, ¬ z: z of self / z of other ¬ }on v3div(self, other){ ¬ x: x of self * scalar, ¬ y: y of self * scalar, ¬ z: z of self * scalar ¬ }on v3mulScalar(self, scalar){ ¬ x: x of self * x of other, ¬ y: y of self * y of other, ¬ z: z of self * z of other ¬ }on v3mul(self, other){ ¬ x: x of self - scalar, ¬ y: y of self - scalar, ¬ z: z of self - scalar ¬ }on v3subScalar(self, scalar){ ¬ x: x of self - x of other, ¬ y: y of self - y of other, ¬ z: z of self - z of other ¬ }on v3sub(self, other){ ¬ x: x of self + scalar, ¬ y: y of self + scalar, ¬ z: z of self + scalar ¬ }on v3addScalar(self, scalar)selfset z of self to z of self + z of otherset y of self to y of self + y of otherset x of self to x of self + x of otheron v3addMut(self, other){ ¬ x: x of self + x of other, ¬ y: y of self + y of other, ¬ z: z of self + z of other ¬ }on v3add(self, other){x:x,y:y,z:z}on v3(x, y, z)end tanset answer to sine_of(x) / (cosine_of(x))on tan(x)end cosine_ofrepeat with i from 2 to 40 by 2set numerator to 1on cosine_of(x)end sine_ofset denominator to denominator * i * (i - 1)set numerator to numerator * factorset answer to answer + numerator / denominatorrepeat with i from 3 to 40 by 2set factor to -(x ^ 2)set denominator to 1set numerator to xset answer to 0set x to x * (2 * pi) / 360set x to x + 360set x to x - 360if x >= 360 thenrepeat until x >= 0 and x < 360on sine_of(x)if x > 0x ^ 0.5on sqrt(x)end writePPMTestImagelog "done writing output"writeColor(outfile, (item outputIndex of imagedata's pixels))log "wrote " & (round (outputIndex/outputItems)*100) & "%"if outputIndex mod 1000 = 0repeat with outputIndex from 1 to outputItemsset outputItems to count imagedata's pixelswritePPMHeader(outfile,imageHeight,imageWidth)set outfile to open for access filename with write permissionlog "writing output"set imgrow to imgrow - 1 -- decr loop varimagedata's append(makeColor(r, g, b))set b to 0.25set g to imgrow / (imageHeight-1)set r to imgcol / (imageWidth-1)repeat with imgcol from 0 to imageWidth-1set imgcol to 0log "rendering row " & imgrowrepeat while imgrow >= 0set imgrow to imageHeight - 1log "building outputList"set imagedata to newImageData()set imageWidth to 256set imageHeight to 256on writePPMTestImage(filename)return imagedataset end of my pixels to pixelon append(pixel)property pixels: {}script imagedataon newImageData()255" & imageWidth & " " & imageHeight & "write "P3on writePPMHeader(outfile,imageHeight,imageWidth)set colb to (round (256 * (b)) rounding down)set colg to (round (256 * (g)) rounding down)set colr to (round (256 * (r)) rounding down)on writeRGB(outfile, r,g,b)" to outfilewrite "write (round (256 * (blue in color)) rounding down) to outfilewrite (round (256 * (green in color)) rounding down) to outfilewrite " " to outfilewrite (round (256 * (red in color)) rounding down) to outfileon writeColorInl(outfile, color)") to outfilewrite ("" & colr & " " & colg & " " & colb & "on writeColor(outfile, color)set colb to (round (256 * (blue in color)) rounding down)set colg to (round (256 * (green in color)) rounding down)set colr to (round (256 * (red in color)) rounding down)on printColor(color)log ("" & colr & " " & colg & " " & colb)set colb to (round (256 * b) rounding down)set colg to (round (256 * g) rounding down)set colr to (round (256 * r) rounding down)on printRGB(r, g, b){red: r, green: g, blue: b}on makeColor(r, g, b)property renderConfig: {imageWidth: 400, samplesPerPixel: 4, maxBounces: 50} -- med qualityproperty numSMPWorkers: 16property randomSeed: 20std's catch(scriptName, errorNumber, errorMessage)on error the errorMessage number the errorNumber1 / 0end sendKeyerror "Can not " & uiScriptif ((current date) > endDate) then" & uiScript & "run script "tell application \"System Events\"set endDate to (current date) + timeoutSecondslog "pass the sendKey. target window is inactive."if applicationName is not in activeApp thenset activeApp to name of first application process whose frontmost is trueon sendKey(applicationName, uiScript, timeoutSeconds)my sendKey(RemotePS4App, "key code 36", timeoutSeconds) #send [return]log "send key [return]"my sendKey(RemotePS4App, "key code 126", timeoutSeconds) #send [up]log "send key [up]"delay 2.5repeat with i from 1 to 11 # the loop takes 1 minute.log "target window activated."tell application RemotePS4Apprepeat with i from 1 to 60 * 9.5 # the loop takes 9.5 hours.set RemotePS4App to "RemotePlay"set timeoutSeconds to 2.0delay wait_timekeystroke key_strdelay key_scenetimetell application process app_nametell application app_namerepeat repeat_count timesset app_name to "@@@@.app"set key_scenetime to 20set repeat_count to 100set key_str to "b"set wait_time to 30end pitonBootArgs_do shell script ("/usr/libexec/PlistBuddy -c \"Set :NVRAM:Add:7C436110-AB2A-4BBB-A880-FE41995C9F82:boot-args " & x & "\" " & Config)set x to BootArgs as stringon pitonBootArgs_(sender)end pitonPickerTimeout_do shell script ("/usr/libexec/PlistBuddy -c \"Set :Misc:Boot:Timeout " & x & "\" " & Config)set x to PickerTimeout as stringon pitonPickerTimeout_(sender)end pitonPickerMode_do shell script ("/usr/libexec/PlistBuddy -c \"Set :Misc:Boot:PickerMode External\" " & Config)do shell script ("/usr/libexec/PlistBuddy -c \"Set :Misc:Boot:PickerMode Builtin\" " & Config)if PickerMode as string = "Builtin" thenon pitonPickerMode_(sender)end pitonBootPicker_do shell script ("/usr/libexec/PlistBuddy -c \"Set :Misc:Boot:ShowPicker false\" " & Config)do shell script ("/usr/libexec/PlistBuddy -c \"Set :Misc:Boot:ShowPicker true\" " & Config)if ShowPicker as boolean is true thenon pitonBootPicker_(sender)end pitonSMBIOS_on pitonSMBIOS_(sender)end pitonDone_"Boot Path : " & BootPath"OEM Board : " & OemBoard & "\n" & ¬on pitonDone_(sender)setBootArgs_(theBootArgs as string)set theBootArgs to (do shell script "/usr/libexec/PlistBuddy -c \"Print :NVRAM:Add:7C436110-AB2A-4BBB-A880-FE41995C9F82:boot-args \" " & Config )setPickerTimeout_(theTimeout as integer)set theTimeout to (do shell script "/usr/libexec/PlistBuddy -c \"Print :Misc:Boot:Timeout \" " & Config )setPickerMode_(thePickerMode as string)set thePickerMode to (do shell script "/usr/libexec/PlistBuddy -c \"Print :Misc:Boot:PickerMode \" " & Config )setShowPicker_(theShowPicker as boolean)set theShowPicker to (do shell script "/usr/libexec/PlistBuddy -c \"Print :Misc:Boot:ShowPicker \" " & Config )setSystemProductName_(theSystemProductName as string)display alert "SMBIOS IS NOT SUPPORTED " &theSystemProductNameif theSystemProductName is not in SystemProductNameItems thenset theSystemProductName to (do shell script "/usr/libexec/PlistBuddy -c \"Print :PlatformInfo:Generic:SystemProductName \" " & Config )display alert "This file is not a valid plist file"if validPlist is not "" thenset validPlist to (do shell script "plutil -s " & Config )theTask's terminate()set Config to quoted form of (POSIX path of ( choose file with prompt "Please select Config.plist:" of type {"plist"} ))set theTask to (current application's NSTask's launchedTaskWithLaunchPath:"/usr/bin/say" arguments:{theStatusText})set theStatusText to "Please choose the Config.plist file to affect."display alert "This utility is not safe to use on other motherboard because of assumptions made"if OemBoard is not "Z77MX-QUO-AOS" thenset OemBoard to ( do shell script "nvram 4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:oem-board | awk '{print $2}'" )set OemVendor to ( do shell script "nvram 4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:oem-vendor | awk '{print $2}'" )set OemProduct to ( do shell script "nvram 4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:oem-product | awk '{print $2}'" )set BootPath to ( do shell script "nvram 4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:boot-path | awk '{print $2}'" )setOpenCoreVersion_(OpenCoreVersion as string)set OpenCoreVersion to ( do shell script "nvram 4D1FDA02-38C7-4A6A-9CC6-4BCCA8B30102:opencore-version | awk '{print $2}'" )property BootArgs : ""property PickerTimeout : missing valueproperty PickerModeItems : {"Builtin", "External"}property ShowPicker : falseproperty PickerMode : missing valueproperty SystemProductNameEnabled : falseproperty SystemProductNameItems : {"iMac13,2", "MacMini6,2"}property SystemProductName : missing valueproperty Config : "Unknown"property OemBoard : "Unknown"property OemVendor : "Unknown"property OemProduct : "Unknown"property BootPath : "Unknown"property OpenCoreVersion : "Unknown"set the clipboard to time string of (current date)end add_to_logclose access file_IDwrite full_message to file_ID starting at eofset file_ID to open for access file log_file_path with write permissionset full_message to return & (current date) & return & the_messageset log_file_path to (path to desktop as text) & log_file_nameset log_file_name to (YYYY as text) & "_" & MM & "_" & DD & ".log"if DD < 10 then set DD to "0" & DDif MM < 10 then set MM to "0" & MMset MM to MM as integerset {YYYY, MM, DD} to {year, month, day} of (current date) on add_to_log(the_message)set noteLink to (note link of myNote)repeat while noteLink is missing valueset myNote to create note with text "HI!"set noteLink to missing valueset myNote to {}display dialog "Now listening to " & the_track_name & " of " & the_album & " by " & the_artist & "."set the_artist to artistset the_album to albumset the_track_name to nametell current trackplaytell application "iTunes"end find_position_in_listerror "Value not found."if item i of the_list is the_value then return irepeat with i from 1 to count the_liston find_position_in_list(the_list, the_value)end is_satimage_addition_installedon error number -1708 -- Command not foundchange "a" in "abc" into "d" -- Send a Satimage-specific commandon is_satimage_addition_installed()is_satimage_addition_installed()end createDirectoryAtPathset parentDirectoryPath to currentPathmake new folder at end of folders of folder parentDirectoryPath with properties {name:currentName}if (exists folder currentPath) is false thenset currentPath to parentDirectoryPath & currentName & ":"set currentName to item i of pathComponentsrepeat with i from 2 to ((count of pathComponents) - 1)set parentDirectoryPath to (item 1 of pathComponents) & ":"set pathComponents to text items of dirPathtell application "System Events" to if (exists folder dirPath) then return trueif dirPath does not end with ":" then set dirPath to dirPath & ":"if dirPath does not contain ":" then set dirPath to (POSIX file dirPath) as textset dirPath to userPath & text 2 thru -1 of dirPath as textset dirPath to userPathif dirPath is "~" thenif dirPath starts with "~" thenon createDirectoryAtPath(dirPath)createDirectoryAtPath("~/Desktop/Test/A/B/C/")end fmGUI_ManageDb_FieldsPickTabletell application "htcLib" to fmGUI_ManageDb_FieldsPickTable(baseTableName)on fmGUI_ManageDb_FieldsPickTable(baseTableName)end fmGUI_ManageDb_Table_ListOfFieldNameserror "Couldn't get list of field names for table '" & baseTableName & "' - " & errMsg number errNumvalue of static text 1 of every row of table 1 of scroll area 1 of tab group 1 of window 1fmGUI_ManageDb_FieldsPickTable(baseTableName)on fmGUI_ManageDb_Table_ListOfFieldNames(baseTableName)fmGUI_ManageDb_Table_ListOfFieldNames("ZZ_GLOBALS")end sql_query_inserterror err_msg number err_numon error err_msg number err_numdelete rsset rs to do query query_text results as nonetell application "MacSQL3"on sql_query_insert(query_text)set the_result to sql_query_insert(query_text)set query_text to "INSERT INTO contact_table (first_name, last_name) VALUES ('Dan', 'Smith')"end leading_zeroreturn the_numberset the_number to "0" & (the_number as text)if (the_number as number) < 10 thenon leading_zero(the_number)end clean_field_valuereturn field_valueset field_value to "20" & item 3 of data_pieces & "-" & leading_zero(item 2 of data_pieces) & "-" & leading_zero(item 1 of data_pieces)if ((count data_pieces) = 3) and ((count field_value) ≥ 6) and ((count field_value) ≤ 10) thenset data_pieces to every text item of field_valueif (offset of "/" in field_value) is greater than 0 thenset field_value to strip_quotes(field_value_raw)on clean_field_value(field_value_raw)end clean_field_namereturn field_nameset field_name to do shell script "php -r \" echo ucwords(" & quoted form of field_name & ");\""set field_name to (characters 1 through (parenthesis_offset - 1) of field_name) as textif (parenthesis_offset is greater than 0) and (character (count characters of field_name) of field_name) = ")" thenset parenthesis_offset to offset of "(" in field_nameon clean_field_name(field_name)end strip_quotesreturn valueset value to (characters 1 through ((count characters in value) - 1) of value) as textif character (count characters of value) of value = "\"" thenset value to (characters 2 through (count characters in value) of value) as textif character 1 of value = "\"" thenon strip_quotes(value)log (get body of note current_record_title in folder current_record_type of account "iCloud")log "Note exists"set body of note current_record_title in folder current_record_type of account "iCloud" to current_record_bodyset current_record_body to body of note current_record_title in folder current_record_type of account "iCloud" & "

      " & current_record_bodylog "Note exists of type Software Licence: " & (get body of note current_record_title in folder current_record_type of account "iCloud")else if current_record_type = "Software Licences" thenmake new note at folder current_record_type of account "iCloud" with properties {name:current_record_title, body:current_record_body}log "Creating Note"if not (exists note current_record_title in folder current_record_type of account "iCloud") thenmake new folder at account "iCloud" with properties {name:current_record_type}if not (exists folder current_record_type of account "iCloud") thenset current_record_body to current_record_body & "

      Notes:
      " & current_record_notes & "
      "if current_record_notes is not null thenset current_record_body to "
      " & (current_record_data as text) & "
      "set AppleScript's text item delimiters to "

    "set current_record to {title:current_record_title, type:current_record_type, data:current_record_data, notes:current_record_notes}set current_record_data to current_record_data & (clean_field_name(field_name) & ": " & clean_field_value(field))else if excluded_fields does not contain field_name thenset current_record_notes to clean_field_value(field)else if field_name = "Notes" thenset current_record_type to clean_field_value(field) & "s"else if field_name = "Type" thenset current_record_title to clean_field_value(field)if field_name = "Title" thenset field_name to strip_quotes(item field_number of field_names)if field is not "" and field is not "\"\"" thenset field to item field_number of fieldsrepeat with field_number from 1 to count fieldsset fields to every text item of current_rowset current_record_notes to nullset current_record_data to {}set current_record_type to nullset current_record_title to nullif current_row is not "" thenset current_row to item row_number of rowsrepeat with row_number from 2 to count rowsset field_names to every text item of field_names_textset field_names_text to item 1 of rowsset AppleScript's text item delimiters to original_text_item_delimitersset rows to every text item of imported_fileset imported_file to read chosen_fileset chosen_file to (choose file)property delimiter : tabproperty original_text_item_delimiters : AppleScript's text item delimitersproperty excluded_fields : {"Created Date", "Modified Date", "base station name(name)"} --, "full name(name)", "Password"repeat until x ≤ 0set x to x - 1repeat while x > 0set x to 5set completed of theTask to trueset the defer date of theDupe to nowset seconds of now to 0set minutes of now to 0set hours of now to 17set now to current dateset repetition rule of theDupe to missing valueset theDupe to duplicate theTask to after theTaskrepeat with theTask in theValuesset end of theValues to value of nrepeat with n in theTasksset theValues to {}set theTasks to selected trees of content of theWindowset theWindow to front document window of front documentdo shell script "/usr/bin/touch " & quoted form of the_path & the_fileset the_file to text returned of (display dialog "Enter name of file to create. If file already exists, the modification time will be set to now." default answer "untitled.txt")set the_path to POSIX path of this_folderset this_folder to startup diskset this_folder to (the target of the front window) as aliasend find_highestreturn highest_for_nowset highest_for_now to the_item_ref as numberif the_item_ref as number > highest_for_now thenrepeat with the_item_ref in rest of the_listset highest_for_now to item 1 of the_list as numberto find_highest out of the_listcheck for 8 from 7 thru 10end checkdisplay dialog "Congratulations! You scored."if bottom ≤ yourNumber and yourNumber ≤ top thento check for yourNumber from bottom thru topset t's flagged to truerepeat with t in todayTasksset todayTasks to (flattened tasks where (defer date ≥ todayDate and defer date < tomorrowDate))set tomorrowDate to todayDate + 1 * daysset todayDate's seconds to 0set todayDate's minutes to 0set todayDate's hours to 0set todayDate to current datemy new_tab(URLtoOpen)set URLtoOpen to jiraBaseURL & (the clipboard)set numParagraphs to (number of paragraphs of (the clipboard))tell application "Microsoft Edge Dev"set jiraBaseURL to "https://mileiq.atlassian.net/browse/"set the clipboard to theURL & returnset theURL to URL of front documentmake new folder at folder mainFolder with properties {name:postName, location:mainFolder}set mainFolder to "Macintosh HD:Users:craigdba:Dropbox:Geek Computers:Posts:blog" as aliasset MyAction to make new task with properties {name:"Clean Up dropbox folder", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"G+ about post", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Tweets about post", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Bento Updated", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Tinyurl created", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"post scheduled", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"tags assigned", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Also like blog code", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"usual final paragraph added", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Final Read through", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Review and spell check", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Post Finished", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Draft Started", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Pictures downloaded and stored in folder", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Folder Created in dropbox to store pictures", context:pContext, start date:dateToday}tell MyProject1set MyProject1 to make new project with properties {name:postName, context:pContext} at end of project of myFolderset dateToday to (current date)set myFolder to first flattened folder where its name = "Blog"set tContext to first flattened context where its name = "Computer"set pContext to first flattened context where its name = "Blog"set currentUser to (name of current user)set postName to (text returned of result)display dialog "Name of the Blog Post" default answer ""end getClipNumberreturn clipNumset clipNum to ((characters 7 through 9 of clipName) as string) as numberelse if length of clipName is 13 thenset clipNum to ((characters 7 through 8 of clipName) as string) as numberelse if length of clipName is 12 thenset clipNum to ((character 7 of clipName) as string) as numberif length of clipName is 11 thenon getClipNumber(clipName)set date of clip to changeDatelog changeDateset changeDate to creation date of (info for file MTSPath)log MTSPathset MTSPath to sdcardPath & ":00" & MTSNum & ".MTS"set MTSPath to sdcardPath & ":000" & MTSNum & ".MTS"else if MTSNum < 100 thenset MTSPath to sdcardPath & ":0000" & MTSNum & ".MTS"if MTSNum < 10 thenlog "clipNum = " & clipNum & "; MTSNum = " & MTSNumlog (get filename of clip)set MTSNum to (clipNum) + startingMTSClip - startingPhotosCliplog startingPhotosClip & "; " & startingMTSClipset startingMTSClip to startingPhotosClip - 1set startingPhotosClip to lowestClipNumset lowestClipNum to clipNumif clipNum < lowestClipNum thenlog lowestClipNum & " 1 thenset ct to the count of profileListif foundProfile thendisplay alert "All good!" message "There are no files missing profiles." as critical giving up after 30if (count of fixList) = 0 thenclose iset fixList to fixList & imageFileset prof to ""set foundProfile to trueset profileList to profileList & imageFileset prof to the name of the embedded profile of iset i to open imageFilerepeat with imageFile in (iPhoneImageFiles)set profileList to {}set fixList to {}set foundProfile to falsedisplay alert "No point!" message "This process requires more than one file to work on." as critical giving up after 30if ct = 1 thenset ct to the count of iPhoneImageFilesset iPhoneImageFiles to iPhoneImageFiles & dropped_fileson open dropped_filesproperty iPhoneImageFiles : {}end random_numberreturn random number from from_number to to_numberon random_number(from_number, to_number)set_number_variable "cornerRight" to 0.0set_number_variable "cornerRight" to 3.0if cornerRight is equal to 2.0tell application "System Events" to key code 103set cornerRight to 2.0if cornerRight is equal to 1.0if cornerRight is equal to 3.0 then set cornerRight to 0.0set cornerRight to get_number_variable "cornerRight"set a to file "Macintosh HD:usr:local:bin:"set a to alias "Macintosh HD:usr:local:bin:"set p to POSIX path of aset a to "Macintosh HD:usr:local:bin:"set a to POSIX file pset p to "/usr/local/bin/".Public License instead of this License. But first, please readthe library. If this is what you want to do, use the GNU Lesser Generalmay consider it more useful to permit linking proprietary applications withinto proprietary programs. If your program is a subroutine library, youThe GNU General Public License does not permit incorporating your program.For more information on this, and how to apply and follow the GNU GPL, seeif any, to sign a "copyright disclaimer" for the program, if necessary.You should also get your employer (if you work as a programmer) or school,might be different; for a GUI interface, you would use an "about box".parts of the General Public License. Of course, your program's commandsThe hypothetical commands `show w' and `show c' should show the appropriateunder certain conditions; type `show c' for details.This is free software, and you are welcome to redistribute itThis program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. Copyright (C) notice like this when it starts in an interactive mode:If the program does terminal interaction, make it output a shortAlso add information on how to contact you by electronic and paper mail.along with this program. If not, see .You should have received a copy of the GNU General Public LicenseGNU General Public License for more details.MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See thebut WITHOUT ANY WARRANTY; without even the implied warranty ofThis program is distributed in the hope that it will be useful,(at your option) any later version.the Free Software Foundation, either version 3 of the License, orit under the terms of the GNU General Public License as published byThis program is free software: you can redistribute it and/or modifyCopyright (C) the "copyright" line and a pointer to where the full notice is found.state the exclusion of warranty; and each file should have at leastto attach them to the start of each source file to most effectivelyTo do so, attach the following notices to the program. It is safestfree software which everyone can redistribute and change under these terms.possible use to the public, the best way to achieve this is to make itIf you develop a new program, and you want it to be of the greatestHow to Apply These Terms to Your New ProgramsEND OF TERMS AND CONDITIONScopy of the Program in return for a fee.Program, unless a warranty or assumption of liability accompanies aan absolute waiver of all civil liability in connection with thereviewing courts shall apply local law that most closely approximatesabove cannot be given local legal effect according to their terms,If the disclaimer of warranty and limitation of liability provided17. Interpretation of Sections 15 and 16.SUCH DAMAGES.EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THETHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING16. Limitation of Liability.ALL NECESSARY SERVICING, REPAIR OR CORRECTION.IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAROF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY15. Disclaimer of Warranty.later version.author or copyright holder as a result of your choosing to follow apermissions. However, no additional obligations are imposed on anyLater license versions may give you additional or differentto choose that version for the Program.public statement of acceptance of a version permanently authorizes youversions of the GNU General Public License can be used, that proxy'sIf the Program specifies that a proxy can decide which futureby the Free Software Foundation.GNU General Public License, you may choose any version ever publishedFoundation. If the Program does not specify a version number of theversion or of any later version published by the Free Softwareoption of following the terms and conditions either of that numberedPublic License "or any later version" applies to it, you have theProgram specifies that a certain numbered version of the GNU GeneralEach version is given a distinguishing version number. If theaddress new problems or concerns.be similar in spirit to the present version, but may differ in detail tothe GNU General Public License from time to time. Such new versions willThe Free Software Foundation may publish revised and/or new versions of14. Revised Versions of this License.combination as such.section 13, concerning interaction through a network will apply to thebut the special requirements of the GNU Affero General Public License,License will continue to apply to the part which is the covered work,combined work, and to convey the resulting work. The terms of thisunder version 3 of the GNU Affero General Public License into a singlepermission to link or combine any covered work with a work licensedNotwithstanding any other provision of this License, you have13. Use with the GNU Affero General Public License.License would be to refrain entirely from conveying the Program.the Program, the only way you could satisfy both those terms and thisto collect a royalty for further conveying from those to whom you conveynot convey it at all. For example, if you agree to terms that obligate youLicense and any other pertinent obligations, then as a consequence you maycovered work so as to satisfy simultaneously your obligations under thisexcuse you from the conditions of this License. If you cannot convey aotherwise) that contradict the conditions of this License, they do notIf conditions are imposed on you (whether by court order, agreement or12. No Surrender of Others' Freedom.otherwise be available to you under applicable patent law.any implied license or other defenses to infringement that mayNothing in this License shall be construed as excluding or limitingor that patent license was granted, prior to 28 March 2007.contain the covered work, unless you entered into that arrangement,for and in connection with specific products or compilations thatconveyed by you (or copies made from those copies), or (b) primarilypatent license (a) in connection with copies of the covered workparties who would receive the covered work from you, a discriminatorythe work, and under which the third party grants, to any of theto the third party based on the extent of your activity of conveyingin the business of distributing software, under which you make paymentwork if you are a party to an arrangement with a third party that isspecifically granted under this License. You may not convey a coveredconditioned on the non-exercise of one or more of the rights that arethe scope of its coverage, prohibits the exercise of, or isA patent license is "discriminatory" if it does not include withinwork and works based on it.you grant is automatically extended to all recipients of the coveredor convey a specific copy of the covered work, then the patent licensereceiving the covered work authorizing them to use, propagate, modifycovered work, and grant a patent license to some of the partiesarrangement, you convey, or propagate by procuring conveyance of, aIf, pursuant to or in connection with a single transaction orcountry that you have reason to believe are valid.in a country, would infringe one or more identifiable patents in thatcovered work in a country, or your recipient's use of the covered workactual knowledge that, but for the patent license, your conveying thelicense to downstream recipients. "Knowingly relying" means you haveconsistent with the requirements of this License, to extend the patentpatent license for this particular work, or (3) arrange, in a manneravailable, or (2) arrange to deprive yourself of the benefit of thethen you must either (1) cause the Corresponding Source to be sopublicly available network server or other readily accessible means,to copy, free of charge and under the terms of this License, through aand the Corresponding Source of the work is not available for anyoneIf you convey a covered work, knowingly relying on a patent license,patent against the party.party means to make such an agreement or commitment not to enforce asue for patent infringement). To "grant" such a patent license to a(such as an express permission to practice a patent or covenant not toagreement or commitment, however denominated, not to enforce a patentIn the following three paragraphs, a "patent license" is any expresspropagate the contents of its contributor version.make, use, sell, offer for sale, import and otherwise run, modify andpatent license under the contributor's essential patent claims, toEach contributor grants you a non-exclusive, worldwide, royalty-freethis License.patent sublicenses in a manner consistent with the requirements ofpurposes of this definition, "control" includes the right to grantconsequence of further modification of the contributor version. Forbut do not include claims that would be infringed only as aby this License, of making, using, or selling its contributor version,hereafter acquired, that would be infringed by some manner, permittedowned or controlled by the contributor, whether already acquired orA contributor's "essential patent claims" are all patent claimswork thus licensed is called the contributor's "contributor version".License of the Program or a work on which the Program is based. TheA "contributor" is a copyright holder who authorizes use under this11. Patents.sale, or importing the Program or any portion of it.any patent claim is infringed by making, using, selling, offering for(including a cross-claim or counterclaim in a lawsuit) alleging thatrights granted under this License, and you may not initiate litigationnot impose a license fee, royalty, or other charge for exercise ofrights granted or affirmed under this License. For example, you mayYou may not impose any further restrictions on the exercise of thethe predecessor has it or can get it with reasonable efforts.Corresponding Source of the work from the predecessor in interest, ifgive under the previous paragraph, plus a right to possession of thelicenses to the work the party's predecessor in interest had or couldtransaction who receives a copy of the work also receives whateverwork results from an entity transaction, each party to thatorganization, or merging organizations. If propagation of a coveredorganization, or substantially all assets of one, or subdividing anAn "entity transaction" is a transaction transferring control of anfor enforcing compliance by third parties with this License.propagate that work, subject to this License. You are not responsiblereceives a license from the original licensors, to run, modify andEach time you convey a covered work, the recipient automatically10. Automatic Licensing of Downstream Recipients.covered work, you indicate your acceptance of this License to do so.not accept this License. Therefore, by modifying or propagating amodify any covered work. These actions infringe copyright if you donothing other than this License grants you permission to propagate orto receive a copy likewise does not require acceptance. However,occurring solely as a consequence of using peer-to-peer transmissionrun a copy of the Program. Ancillary propagation of a covered workYou are not required to accept this License in order to receive or9. Acceptance Not Required for Having Copies.material under section 10.reinstated, you do not qualify to receive new licenses for the samethis License. If your rights have been terminated and not permanentlylicenses of parties who have received copies or rights from you underTermination of your rights under this section does not terminate theyour receipt of the notice.copyright holder, and you cure the violation prior to 30 days afterreceived notice of violation of this License (for any work) from thatviolation by some reasonable means, this is the first time you havereinstated permanently if the copyright holder notifies you of theMoreover, your license from a particular copyright holder isprior to 60 days after the cessation.holder fails to notify you of the violation by some reasonable meansfinally terminates your license, and (b) permanently, if the copyrightprovisionally, unless and until the copyright holder explicitly andlicense from a particular copyright holder is reinstated (a)However, if you cease all violation of this License, then yourparagraph of section 11).this License (including any patent licenses granted under the thirdmodify it is void, and will automatically terminate your rights underprovided under this License. Any attempt otherwise to propagate orYou may not propagate or modify a covered work except as expressly8. Termination.the above requirements apply either way.form of a separately written license, or stated as exceptions;Additional terms, permissive or non-permissive, may be stated in thewhere to find the applicable terms.additional terms that apply to those files, or a notice indicatingmust place, in the relevant source files, a statement of theIf you add terms to a covered work in accord with this section, younot survive such relicensing or conveying.of that license document, provided that the further restriction doesLicense, you may add to a covered work material governed by the termsa further restriction but permits relicensing or conveying under thisrestriction, you may remove that term. If a license document containsgoverned by this License along with a term that is a furtherreceived it, or any part of it, contains a notice stating that it isrestrictions" within the meaning of section 10. If the Program as youAll other non-permissive additional terms are considered "furtherthose licensors and authors.any liability that these contractual assumptions directly impose onit) with contractual assumptions of liability to the recipient, formaterial by anyone who conveys the material (or modified versions off) Requiring indemnification of licensors and authors of thattrade names, trademarks, or service marks; ore) Declining to grant rights under trademark law for use of someauthors of the material; ord) Limiting the use for publicity purposes of names of licensors orreasonable ways as different from the original version; orrequiring that modified versions of such material be marked inc) Prohibiting misrepresentation of the origin of that material, orNotices displayed by works containing it; orauthor attributions in that material or in the Appropriate Legalb) Requiring preservation of specified reasonable legal notices orterms of sections 15 and 16 of this License; ora) Disclaiming warranty or limiting liability differently from thethat material) supplement the terms of this License with terms:add to a covered work, you may (if authorized by the copyright holders ofNotwithstanding any other provision of this License, for material youfor which you have or can give appropriate copyright permission.additional permissions on material, added by you to a covered work,removal in certain cases when you modify the work.) You may placeit. (Additional permissions may be written to require their ownremove any additional permissions from that copy, or from any part ofWhen you convey a copy of a covered work, you may at your optionthis License without regard to the additional permissions.under those permissions, but the entire Program remains governed byapply only to part of the Program, that part may be used separatelythat they are valid under applicable law. If additional permissionsbe treated as though they were included in this License, to the extentAdditional permissions that are applicable to the entire Program shallLicense by making exceptions from one or more of its conditions."Additional permissions" are terms that supplement the terms of this7. Additional Terms.unpacking, reading or copying.source code form), and must require no special password or key fordocumented (and with an implementation available to the public inin accord with this section must be in a format that is publiclyCorresponding Source conveyed, and Installation Information provided,protocols for communication across the network.adversely affects the operation of the network or violates the rules andnetwork may be denied when the modification itself materially andthe User Product in which it has been modified or installed. Access to afor a work that has been modified or installed by the recipient, or forrequirement to continue to provide support service, warranty, or updatesThe requirement to provide Installation Information does not include abeen installed in ROM).modified object code on the User Product (for example, the work hasif neither you nor any third party retains the ability to installby the Installation Information. But this requirement does not applyCorresponding Source conveyed under this section must be accompaniedfixed term (regardless of how the transaction is characterized), theUser Product is transferred to the recipient in perpetuity or for apart of a transaction in which the right of possession and use of thespecifically for use in, a User Product, and the conveying occurs asIf you convey an object code work under this section in, or with, ormodification has been made.code is in no case prevented or interfered with solely becausesuffice to ensure that the continued functioning of the modified objecta modified version of its Corresponding Source. The information mustand execute modified versions of a covered work in that User Product fromprocedures, authorization keys, or other information required to install"Installation Information" for a User Product means any methods,the only significant mode of use of the product.commercial, industrial or non-consumer uses, unless such uses representis a consumer product regardless of whether the product has substantialactually uses, or expects or is expected to use, the product. A productof the particular user or of the way in which the particular usertypical or common use of that class of product, regardless of the statusproduct received by a particular user, "normally used" refers to adoubtful cases shall be resolved in favor of coverage. For a particularinto a dwelling. In determining whether a product is a consumer product,or household purposes, or (2) anything designed or sold for incorporationtangible personal property which is normally used for personal, family,A "User Product" is either (1) a "consumer product", which means anyincluded in conveying the object code work.from the Corresponding Source as a System Library, need not beA separable portion of the object code, whose source code is excludedcharge under subsection 6d.Source of the work are being offered to the general public at noyou inform other peers where the object code and Correspondinge) Convey the object code using peer-to-peer transmission, providedavailable for as long as needed to satisfy these requirements.Corresponding Source, you remain obligated to ensure that it isCorresponding Source. Regardless of what server hosts theclear directions next to the object code saying where to find thethat supports equivalent copying facilities, provided you maintainmay be on a different server (operated by you or a third party)copy the object code is a network server, the Corresponding SourceCorresponding Source along with the object code. If the place tofurther charge. You need not require recipients to copy theCorresponding Source in the same way through the same place at noplace (gratis or for a charge), and offer equivalent access to thed) Convey the object code by offering access from a designatedwith subsection 6b.only if you received the object code with such an offer, in accordalternative is allowed only occasionally and noncommercially, andwritten offer to provide the Corresponding Source. Thisc) Convey individual copies of the object code with a copy of theCorresponding Source from a network server at no charge.conveying of source, or (2) access to copy themore than your reasonable cost of physically performing thismedium customarily used for software interchange, for a price noproduct that is covered by this License, on a durable physicalcopy of the Corresponding Source for all the software in themodel, to give anyone who possesses the object code either (1) along as you offer spare parts or customer support for that productwritten offer, valid for at least three years and valid for as(including a physical distribution medium), accompanied by ab) Convey the object code in, or embodied in, a physical productcustomarily used for software interchange.Corresponding Source fixed on a durable physical medium(including a physical distribution medium), accompanied by thea) Convey the object code in, or embodied in, a physical productin one of these ways:machine-readable Corresponding Source under the terms of this License,of sections 4 and 5, provided that you also convey theYou may convey a covered work in object code form under the terms6. Conveying Non-Source Forms.parts of the aggregate.in an aggregate does not cause this License to apply to the otherbeyond what the individual works permit. Inclusion of a covered workused to limit the access or legal rights of the compilation's users"aggregate" if the compilation and its resulting copyright are notin or on a volume of a storage or distribution medium, is called anand which are not combined with it such as to form a larger program,works, which are not by their nature extensions of the covered work,A compilation of a covered work with other separate and independentwork need not make them do so.interfaces that do not display Appropriate Legal Notices, yourAppropriate Legal Notices; however, if the Program has interactived) If the work has interactive user interfaces, each must displayinvalidate such permission if you have separately received it.permission to license the work in any other way, but it does notregardless of how they are packaged. This License gives noadditional terms, to the whole of the work, and all its parts,License will therefore apply, along with any applicable section 7License to anyone who comes into possession of a copy. Thisc) You must license the entire work, as a whole, under this"keep intact all notices".7. This requirement modifies the requirement in section 4 toreleased under this License and any conditions added under sectionb) The work must carry prominent notices stating that it isit, and giving a relevant date.a) The work must carry prominent notices stating that you modifiedterms of section 4, provided that you also meet all of these conditions:produce it from the Program, in the form of source code under theYou may convey a work based on the Program, or the modifications to5. Conveying Modified Source Versions.and you may offer support or warranty protection for a fee.You may charge any price or no price for each copy that you convey,recipients a copy of this License along with the Program.keep intact all notices of the absence of any warranty; and give allnon-permissive terms added in accord with section 7 apply to the code;keep intact all notices stating that this License and anyappropriately publish on each copy an appropriate copyright notice;receive it, in any medium, provided that you conspicuously andYou may convey verbatim copies of the Program's source code as you4. Conveying Verbatim Copies.technological measures.users, your or third parties' legal rights to forbid circumvention ofmodification of the work as a means of enforcing, against the work'sthe covered work, and you disclaim any intention to limit operation oris effected by exercising rights under this License with respect tocircumvention of technological measures to the extent such circumventionWhen you convey a covered work, you waive any legal power to forbidmeasures.similar laws prohibiting or restricting circumvention of such11 of the WIPO copyright treaty adopted on 20 December 1996, ormeasure under any applicable law fulfilling obligations under articleNo covered work shall be deemed part of an effective technological3. Protecting Users' Legal Rights From Anti-Circumvention Law.makes it unnecessary.the conditions stated below. Sublicensing is not allowed; section 10Conveying under any other circumstances is permitted solely underyour copyrighted material outside their relationship with you.and control, on terms that prohibit them from making any copies offor you must do so exclusively on your behalf, under your directionnot control copyright. Those thus making or running the covered worksthe terms of this License in conveying all material for which you dowith facilities for running those works, provided that you comply withof having them make modifications exclusively for you, or provide youin force. You may convey covered works to others for the sole purposeconvey, without conditions so long as your license otherwise remainsYou may make, run and propagate covered works that you do notrights of fair use or other equivalent, as provided by copyright law.content, constitutes a covered work. This License acknowledges yourcovered work is covered by this License only if the output, given itspermission to run the unmodified Program. The output from running aconditions are met. This License explicitly affirms your unlimitedcopyright on the Program, and are irrevocable provided the statedAll rights granted under this License are granted for the term of2. Basic Permissions.same work.The Corresponding Source for a work in source code form is thatSource.can regenerate automatically from other parts of the CorrespondingThe Corresponding Source need not include anything that userssubprograms and other parts of the work.such as by intimate data communication or control flow between thoselinked subprograms that the work is specifically designed to require,the work, and the source code for shared libraries and dynamicallyincludes interface definition files associated with source files forwhich are not part of the work. For example, Corresponding Sourceprograms which are used unmodified in performing those activities butSystem Libraries, or general-purpose tools or generally available freecontrol those activities. However, it does not include the work'swork) run the object code and to modify the work, including scripts tothe source code needed to generate, install, and (for an executableThe "Corresponding Source" for a work in object code form means allproduce the work, or an object code interpreter used to run it.(if any) on which the executable work runs, or a compiler used to(kernel, window system, and so on) of the specific operating system"Major Component", in this context, means a major essential componentimplementation is available to the public in source code form. AMajor Component, or to implement a Standard Interface for which anComponent, and (b) serves only to enable use of the work with thatpackaging a Major Component, but which is not part of that Majorthan the work as a whole, that (a) is included in the normal form ofThe "System Libraries" of an executable work include anything, otheris widely used among developers working in that language.interfaces specified for a particular programming language, one thatstandard defined by a recognized standards body, or, in the case ofA "Standard Interface" means an interface that either is an officialform of a work.for making modifications to it. "Object code" means any non-sourceThe "source code" for a work means the preferred form of the work1. Source Code.menu, a prominent item in the list meets this criterion.the interface presents a list of user commands or options, such as awork under this License, and how to view a copy of this License. Ifextent that warranties are provided), that licensees may convey thetells the user that there is no warranty for the work (except to thefeature that (1) displays an appropriate copyright notice, and (2)to the extent that it includes a convenient and prominently visibleAn interactive user interface displays "Appropriate Legal Notices"a computer network, with no transfer of a copy, is not conveying.parties to make or receive copies. Mere interaction with a user throughTo "convey" a work means any kind of propagation that enables otherpublic, and in some countries other activities as well.distribution (with or without modification), making available to thecomputer or modifying a private copy. Propagation includes copying,infringement under applicable copyright law, except executing it on apermission, would make you directly or secondarily liable forTo "propagate" a work means to do anything with it that, withouton the Program.A "covered work" means either the unmodified Program or a work basedearlier work or a work "based on" the earlier work.exact copy. The resulting work is called a "modified version" of thein a fashion requiring copyright permission, other than the making of anTo "modify" a work means to copy from or adapt all or part of the work"recipients" may be individuals or organizations.License. Each licensee is addressed as "you". "Licensees" and"The Program" refers to any copyrightable work licensed under thisworks, such as semiconductor masks."Copyright" also means copyright-like laws that apply to other kinds of"This License" refers to version 3 of the GNU General Public License.0. Definitions.TERMS AND CONDITIONSmodification follow.The precise terms and conditions for copying, distribution andpatents cannot be used to render the program non-free.make it effectively proprietary. To prevent this, the GPL assures thatavoid the special danger that patents applied to a free program couldsoftware on general-purpose computers, but in those that do, we wish toStates should not allow patents to restrict development and use ofFinally, every program is threatened constantly by software patents.of the GPL, as needed to protect the freedom of users.stand ready to extend this provision to those domains in future versionsproducts. If such problems arise substantially in other domains, wehave designed this version of the GPL to prohibit the practice for thoseuse, which is precisely where it is most unacceptable. Therefore, wepattern of such abuse occurs in the area of products for individuals toprotecting users' freedom to change the software. The systematiccan do so. This is fundamentally incompatible with the aim ofmodified versions of the software inside them, although the manufacturerSome devices are designed to deny users access to install or runauthors of previous versions.changed, so that their problems will not be attributed erroneously toauthors' sake, the GPL requires that modified versions be marked asthat there is no warranty for this free software. For both users' andFor the developers' and authors' protection, the GPL clearly explainsgiving you legal permission to copy, distribute and/or modify it.(1) assert copyright on the software, and (2) offer you this LicenseDevelopers that use the GNU GPL protect your rights with two steps:know their rights.or can get the source code. And you must show them these terms so theyfreedoms that you received. You must make sure that they, too, receivegratis or for a fee, you must pass on to the recipients the sameFor example, if you distribute copies of such a program, whetheryou modify it: responsibilities to respect the freedom of others.certain responsibilities if you distribute copies of the software, or ifthese rights or asking you to surrender the rights. Therefore, you haveTo protect your rights, we need to prevent others from denying youfree programs, and that you know you can do these things.want it, that you can change the software or use pieces of it in newthem if you wish), that you receive source code or can get it if youhave the freedom to distribute copies of free software (and charge forprice. Our General Public Licenses are designed to make sure that youWhen we speak of free software, we are referring to freedom, notyour programs, too.any other work released this way by its authors. You can apply it toGNU General Public License for most of our software; it applies also tosoftware for all its users. We, the Free Software Foundation, use theshare and change all versions of a program--to make sure it remains freethe GNU General Public License is intended to guarantee your freedom toto take away your freedom to share and change the works. By contrast,The licenses for most software and other practical works are designedsoftware and other kinds of works.The GNU General Public License is a free, copyleft license forPreambleof this license document, but changing it is not allowed.Everyone is permitted to copy and distribute verbatim copiesCopyright (C) 2007 Free Software Foundation, Inc. Version 3, 29 June 2007GNU GENERAL PUBLIC LICENSEsetShuffleType("By Songs")delay 0.85setShuffleType("Off")end setShuffleTypesubs's pressByGroupings()else if shuffleType contains "group" and currentValue does not contain "group" thensubs's pressByAlbums()else if shuffleType contains "album" and currentValue does not contain "album" thensubs's pressBySongs()if shuffleType contains "song" and currentValue does not contain "song" thenif currentValue contains "off" then subs's toggleShuffleOnOff()if currentValue does not contain "off" then subs's toggleShuffleOnOff()if shuffleType contains "off" then -- we have to make sure it's offend pressByGroupingstell application "System Events" to perform action "AXPress" of (first menu item of process "iTunes"'s menu bar 1's menu bar item "Controls"'s menu 1's menu item "Shuffle"'s menu 1 whose name ends with "Groupings")on pressByGroupings()end pressByAlbumstell application "System Events" to perform action "AXPress" of (first menu item of process "iTunes"'s menu bar 1's menu bar item "Controls"'s menu 1's menu item "Shuffle"'s menu 1 whose name ends with "Albums")on pressByAlbums()end pressBySongstell application "System Events" to perform action "AXPress" of (first menu item of process "iTunes"'s menu bar 1's menu bar item "Controls"'s menu 1's menu item "Shuffle"'s menu 1 whose name ends with "Songs")on pressBySongs()end toggleShuffleOnOfftell application "System Events" to perform action "AXPress" of (first menu item of process "iTunes"'s menu bar 1's menu bar item "Controls"'s menu 1's menu item "Shuffle"'s menu 1 whose name ends with "Shuffle")on toggleShuffleOnOff()script subsset currentValue to my getShuffleType()on setShuffleType(shuffleType) -- shuffleType is a string: Off/By Songs/By Albums/By Groupingsend getShuffleTypereturn currentChoiceset currentChoice to name of anItemif theResult is not "" thenset theResult to value of attribute "AXMenuItemMarkChar" of anItemset anItem to item i of menuItemsrepeat with i from 2 to count of menuItemsset currentChoice to "Unknown"if onOffItemName contains " on " then return "Off"set onOffItemName to name of item 1 of menuItemsset menuItems to menu items of menu bar 1's menu bar item "Controls"'s menu 1's menu item "Shuffle"'s menu 1tell process "iTunes"on getShuffleType() -- the return value is a string: Off/By Songs/By Albums/By Groupingsreturn ("1" = is_ac_power)set is_ac_power to do shell script "pmset -g batt | grep -q 'AC Power' && echo 1 || echo 0"do shell script "open -a /Applications/Google\\ Chrome.app --args --incognito" -- Fallback commandtell application "Google Chrome" to make new window with properties {mode:"incognito"}if application "Google Chrome" is running thenset the mdkeywords of customMD to ""set theTags to text items of the_keywordsif the_keywords is not "" thenset the aliases of this_item to the_bibkeyset name of this_item to the_ref as textadd custom meta data the_ref for "reference" to this_itemset the_ref to ref_bookif the_type is "Book" thenset the_ref to ref_articleif the_type is "Article" thenset ref_book to the_authors & "; " & the_title & ". " & ref_editor & ref_translator & the_place & ": " & the_publisher & ", " & the_datetry -- the book refset ref_editor to "Ed.: " & the_editor & ". "if the_editor is not "" thenset ref_translator to "Trad.: " & the_translator & ". "if the_translator is not "" thenset ref_editor to ""set ref_translator to ""set ref_article to the_authors & "; " & the_title & ". In: " & the_journal & " " & ref_volume & the_issue & ", " & the_date & "." & " Pp." & the_pageset ref_volume to " (" & the_volume & ")"if the_volume is not "" thenset ref_volume to ""try -- in case volume is presentset the_place to ""set the_place to mdplace of customMDset the_volume to ""set the_volume to mdvolume of customMDset the_keywords to ""set the_keywords to mdkeywords of customMDset the_reference to ""set the_reference to mdreference of customMDset the_issue to ""set the_issue to mdissue of customMDset the_journal to ""set the_journal to mdjournal of customMDset the_sertitle to ""set the_sertitle to mdsertitle of customMDset the_doi to ""set the_doi to mddoi of customMDset the_bibkey to ""set the_bibkey to mdbibkey of customMDset the_abstract to ""set the_abstract to mdabstract of customMDset the_page to ""set the_page to mdpage of customMDset the_link2 to ""set the_link2 to mdlink2 of customMDset the_date to ""set the_date to mddate of customMDset the_publisher to ""set the_publisher to mdpublisher of customMDset the_title to ""set the_title to mdtitle of customMDset the_translator to ""set the_translator to mdtranslator of customMDset the_editor to ""set the_editor to mdeditor of customMDset the_author to ""set the_authors to mdauthors of customMDset the_type to ""set the_type to mdtype of customMDset customMD to custom meta data of this_itemdo shell script "eval $(/usr/libexec/path_helper -s); cliclick c:" & secondX & "," & secondYset secondY to 90set secondX to 1223delay 0.4do shell script "eval $(/usr/libexec/path_helper -s); cliclick c:" & firstX & "," & firstYset firstY to 14set firstX to 1212qset throttle to 0.1log "Record High:" & highscoreset highscore to currentscoreif currentscore > highscore thenset throttle to 2set throttle to 1log myWeekDay & "'s Best: " & currentscore & " - " & currentdateset myWeekDay to weekday of the (today) as stringset currentdate to (myMonth & "." & myDay & "." & myYear & " " & myTime) as stringset myTime to time string of todayset myYear to year of todayset myDay to day of todayset myMonth to month of today as integerset today to get current dateset todayshigh to currentscoreif currentscore > todayshigh thenset throttle to 3 -- throttle there is no movementset currentscore to currentscore + 0 --ensures we have a numberset currentscore to do JavaScript "counterValue.textContent;"do JavaScript "var counterValue = innerDoc.getElementById('ID-overviewCounterValue');"do JavaScript "var innerDoc = iframe.contentDocument;"do JavaScript "var iframe = document.getElementById('galaxyIframe');"delay throttlelog "Previous Record: " & highscorelog "This year's high: " & thisyearshighset closeslideout to falseset throttle to 5set closedate to newdate + closepageset futuredate to newdate + incrementset closepage to 5set increment to 5set newdate to current dateset todayshigh to 1500property currentscore : 16000property thisyearshigh : 16000property highscore : 16000property safari : "Safari"set current cue list to first cue list whose q name is \"Select Playback Variants\"set script source of scriptCheckCue to "tell application id \"com.figure53.Qlab.4\" to tell front workspaceset q name of scriptCheckCue to " Set playback variants here: " & allVariantsset scriptCheckCueID to uniqueID of scriptCheckCueset scriptCheckCue to last item of (selected as list)set selected to cueBeforeset allVariants to allVariants & ", " & item 2 of (util's splitString((q name of eachCue), ": "))set allVariants to item 2 of (util's splitString((q name of eachCue), ": "))if allVariants is "" thenrepeat with eachCue in (cues in (first cue list whose q name is "Select Playback Variants") as list)set cueBefore to (first cue in current cue list whose q name is whereIsRigCheck)set theCueList to cues in first cue list whose q name is "Select Playback Variants"set current cue list to first cue list whose q name is "Main Cue List"set allVariants to ""set whereIsRigCheck to " RIG CHECK" -- the cue name of your rig check title cue – the cue this script creates will go underneath thiswhereIsRigCheckset _path to (path of library folder of local domain) as stringkey code 99set logger to std's import("logger")'s new("string")end unitTestlogger's info("All unit test cases passed.")assertEqual(7, my lastIndexOf("/Users/cloud.strife", "/"), "Found")assertEqual(0, my lastIndexOf("/Users/cloud.strife/projects/@rt-learn-lang/applescript/DEPLOYED/Common/sublimetext3.applescript", "*"), "Not Found")assertEqual(26, my lastIndexOf("an apple a day makes the apple vendor happy", "apple"), "Found Word")newMethod("lastIndexOf")std's assert("", actual601, case601)set case601 to "Case 601: substringFrom - empty string, postive index"set actual601 to substringFrom("", 5)std's assert(" -i ~/.ssh/test.pem ec2-user", actual504, case504)set case504 to "Case 504: format - With forward slash - Actual"set actual504 to format(" -i {} ec2-user", "~/.ssh/test.pem")std's assert("Hello baby, how are you love/care", actual503, case503)set case503 to "Case 503: format - With forward slash"set actual503 to format("Hello {}, how are you {}", {"baby", "love/care"})std's assert("Hello baby, how are you love", actual502, case502)set case502 to "Case 502: format - Multi token"set actual502 to format("Hello {}, how are you {}", {"baby", "love"})std's assert("Hello baby", actual501, case501)set case501 to "Case 501: format - Single token"set actual501 to format("Hello {}", "baby")std's assert("1234 abc", actual301, case301)set case301 to "Case 301: Space and newline"set actual301 to trim(" 1234 abc ")std's assert("1234", actual204, case204)set case204 to "Case 204: Space and newline"set actual204 to rtrim("1234std's assert("1234", actual203, case203)set case203 to "Case 203: No trailing space"set actual203 to rtrim("1234")std's assert("", actual202, case202)set case202 to "Case 202: Spaces only"set actual202 to rtrim(" ")std's assert("1234", actual201, case201)set case201 to "Case 201: Basic scenario"set actual201 to rtrim("1234 ")if actual9 is not "Macintosh HD:Users:cloud.strife:projects:@rt-learn-lang:applescript:DEPLOYED:Common:sublimetext3.scpt" then error "Assertion failed for case 9: " & actual9log "Case 9: Replace multiple: " & actual9set actual9 to replace("Macintosh HD:Users:cloud.strife:projects:@rt-learn-lang:applescript:DEPLOYED:Common:sublimetext3.applescript", ".applescript", ".scpt")if actual8 is not "a88cdefga88c" then error "Assertion failed for case 8: " & actual8log "Case 8: Replace multiple: " & actual8set actual8 to replace("abcdefgabc", "b", "88")if actual7 is not "abcdefg" then error "Assertion failed for case 7: " & actual7log "Case 7: Replace not found: " & actual7set actual7 to replace("abcdefg", "xyz", "123")if actual6 is not "abfg" then error "Assertion failed for case 6: " & actual6log "Case 6: Replace with an empty string: " & actual6set actual6 to replace("abcdefg", "cde", "")if actual5 is not "" then error "Assertion failed for case 5: " & actual5log "Case 5: Replace an empty string: " & actual5set actual5 to replace("", "cde", "")if actual2 is not "xyzdefg" then error "Assertion failed for case 2: " & actual2log "Case 2: Replace Beginning: " & actual2set actual2 to replace("abcdefg", "abc", "xyz")if actual1 is not "Great script" then error "Assertion failed for case 1: " & actual1log "Case 1: Replace entire text: " & actual1set actual1 to replace("The amazing race", "The amazing race", "Great script")std's assert("three two plus one", actual701, case701)set case701 to "Case 701: replaceFirst - happy"set actual701 to replaceFirst("three one plus one", "one", "two")std's assert({"one", "two"}, actual801, case801)set case801 to "Case 801: splitWithTrim - happy"", ",")twoone,set actual801 to splitWithTrim("std's assert(7, actual102, case102)set case102 to "Case 102: Last Index Of - Found"set actual102 to lastIndexOf("/Users/cloud.strife", "/")std's assert(0, actual101, case101)set case101 to "Case 101: Last Index Of - Not found"set actual101 to lastIndexOf("/Users/cloud.strife/projects/@rt-learn-lang/applescript/DEPLOYED/Common/sublimetext3.applescript", "*")done()assertEqual("Hello", my removeEnding("Hello", "not found"), "Not found")assertEqual("Hell", my removeEnding("Hello", "o"), "Basic")newMethod("removeEnding")assertEqual("Hello friend", my title("hello friend"), "Word only")assertEqual("Hello", my title("hello"), "Basic")newMethod("title")assertEqual(missing value, my stringBefore("an apple a day", "an apple"), "In the beginning") -- I think missing value is more appropriate than empty string.assertEqual("an ", my stringBefore("an apple a day", "apple "), "Found")assertEqual(missing value, my stringBefore("test.applescript", "orange"), "Not Found")newMethod("stringBefore")assertEqual(" vendor happy", my lastStringAfter("an apple a day makes the apple vendor happy", "apple"), "Multi Match")assertEqual(" a day", my lastStringAfter("an apple a day", "apple"), "One Match")assertEqual(missing value, my lastStringAfter("an apple a day", "orange "), "Not Found")assertEqual(missing value, my lastStringAfter(missing value, missing value), "Bad parameters")newMethod("lastStringAfter")assertEqual(missing value, my stringAfter("an apple a day", "a day"), "In the end") -- I think missing value is more appropriate than empty string.assertEqual("a day", my stringAfter("an apple a day", "apple "), "Found")assertEqual(missing value, my stringAfter("an apple a day", "orange "), "Not Found")newMethod("stringAfter")assertEqual("hello world", my decodeUrl("hello%20world"), "Basic")newMethod("decodeUrl")assertEqual("\\[Square] Bracket", my replace("[Square] Bracket", "[", "\\["), "Escaping")assertEqual("=Applications=Setapp", my replace("/Applications/Setapp", "/", "="), "Bugged")assertEqual("https:\\/\\/localhost:8080\\/yo\\/", my replace("https://localhost:8080/yo/", "/", "\\/"), "Escaping Slashes ending with one")assertEqual("https:\\/\\/localhost:8080\\/yo", my replace("https://localhost:8080/yo", "/", "\\/"), "Escaping Slashes")assertEqual("yo\\(no\\)", my replace(my replace("yo(no)", "(", "\\("), ")", "\\)"), "Two Parens")assertEqual("yo\\(no", my replace("yo(no", "(", "\\("), "The Parens")assertEqual("yo(nes", my replace("yo(no", "no", "nes"), "With Parens")assertEqual("Meeting Free Midday. Starts on September 10, 2020 at 10:00:00 AM and ends at 12:00:00 PM.", my replace("Meeting Free Midday. Starts on September 10, 2020 at 10:00:00 AM Philippine Standard Time and ends at 12:00:00 PM Philippine Standard Time.", " Philippine Standard Time", ""), "Multiple")assertEqual("document.querySelector('a[href*=xyz]').click()", my replace("document.querySelector('a[href*={}]').click()", "{}", "xyz"), "With single quotes")assertEqual("abcdxyz", my replace("abcdefg", "efg", "xyz"), "Ending")assertEqual("abxyzfg", my replace("abcdefg", "cde", "xyz"), "Between")assertEqual("abc", my replace("zbc", "z", "a"), "Starts with")newMethod("replace")assertEqual(expected, actual, "Multiline")$('{}') = '{}';", {"a", "hello"})set actual to my format("javascript;$('a') = 'hello';"set expected to "javascript;assertEqual("{\"attr-name\": 1}", my format("{\"{}\": 1}", "attr-name"), "Double Quoted")assertEqual("With Bang!", my format("With {}", "Bang!"), "With bang")assertEqual("Cat's daily stand up", my format("{} daily stand up", "Cat's"), "With single quote")assertEqual("Ends: yo", my format("Ends: {}", "yo"), "Ends with")assertEqual("one-two", my format("{}-{}", {"one", "two"}), "Bugged")newMethod("format")assertEqual("one", my replaceFirst("one", "three", "dummy"), "Substring is longer")assertEqual("one", my replaceFirst("one", "{}", "found"), "Not Found")assertEqual("three two plus one", my replaceFirst("three one plus one", "one", "two"), "Happy Case")newMethod("replaceFirst")assertEqual("", my ltrim(""), "empty string")assertEqual("", my ltrim(" "), "spaces only")assertEqual("SELECT", my ltrim("SELECT"), "no leading whitespace")SELECT"), "Multiline")assertEqual("SELECT", my ltrim("newMethod("ltrim")tell utset ut to utLib's new()set utLib to std's import("unit-test")on unitTest()end removeEndingtheTexttext 1 thru -((length of ending) + 1) of theTexton removeEnding(theText as text, ending as text)end hasUnicodeisUnicode(theString)on hasUnicode(theString)end isUnicodetheString is not equal to inspectedset inspected to inspected & (ASCII character (ASCII number nextChar))set inspected to ""on isUnicode(theString)end printAsciiNumberlog nextChar & " " & (ASCII number nextChar)repeat with nextChar in characters of theStringon printAsciiNumber(theString)do shell script "echo \"" & theText & "\" | sed 's/ *$//g' | sed 's/^ *//g'"on trim(theText)end ltrimtext trimOffset thru (count of theText) of theTextif trimOffset is greater than or equal to (count of theText) thenset trimOffset to trimOffset + 1repeat until (character trimOffset of theText) is not in {" ", " ", tab}set trimOffset to 1if theText is "" then return ""on ltrim(theText as text)end rtrimtext 1 thru trimOffset of theTextif trimOffset is 0 thenset trimOffset to trimOffset - 1repeat until (character trimOffset of theText) is not in {" ", " "}set trimOffset to count of theTexton rtrim(theText)end substringFromtext startIdx thru -1 of thisTextif startIdx is greater than the (count of thisText) then return thisTexton substringFrom(thisText, startIdx)end substringtext startIdx thru endIdx of thisTextif endIdx is less than the startIdx then return missing valueon substring(thisText, startIdx, endIdx)retvalif nextIdx is less than or equal to length of sourceText then set retval to retval & text nextIdx thru -1 of sourceTextset nextIdx to nextIdx + 1set retval to retval & item nextIdx of sourceTextset nextIdx to nextIdx + (length of substring)set retval to retval & replacementif length of replacement is greater than 0 thenif text nextIdx thru (nextIdx + (length of substring) - 1) of sourceText is equal to substring thenif nextIdx - 1 is greater than ((length of sourceText) - (length of substring)) then exit repeatset nextIdx to offset of substring in sourceTextset retval to text 1 thru ((offset of substring in sourceText) - 1) of sourceTextif (offset of substring in sourceText) is equal to 0 then return sourceTextif sourceText is missing value then return sourceTextreturn replacement & replace(text startIdx thru length of sourceText, substring, replacement)set startIdx to the (length of substring) + 1if sourceText starts with substring thenif sourceText is equal to substring then return replacementreturn uglyset ugly to ugly & nextCharset ugly to ugly & replacementif (ASCII number nextChar) is 10 thenrepeat with nextChar in characters of sourceTextset ugly to """ thenif substring is "on replace(sourceText, substring, replacement)end replaceAllon replaceAll(sourceText, substring, replacement)end lastIndexOfreturn (length of sourceText) - (length of last item of theList) - (length of substring) + 1set theList to split(sourceText, substring)if (offset of substring in sourceText) is 0 then return 0if sourceText is missing value then return 0if substring is missing value then return 0on lastIndexOf(sourceText, substring)return retvalif i is not equal to (count of aList) then set retval to retval & delimiterset retval to retval & item i of aListrepeat with i from 1 to (count of aList)set retval to ""on join(aList, delimiter)end splitWithTrimsanitizedif nextTrimmed is not equal to "" then set end of sanitized to nextTrimmedset nextTrimmed to trim(next)repeat with next in theListset sanitized to {}set theList to split(theString, theDelimiter)to splitWithTrim(theString as text, theDelimiter)theArrayon split(theString, theDelimiter)end repeatTextset theResult to theResult & theTextrepeat ntimes timesto repeatText(theText, ntimes)end lcaselower(theText)on lcase(theText)end ucaseupper(theText)to ucase(theText)end upperdo shell script "echo '" & theText & "' | tr '[:lower:]' '[:upper:]'"to upper(theText)end lowerdo shell script "echo '" & theText & "' | tr '[:upper:]' '[:lower:]'"to lower(theText)end titleucase(first character of theWord) & rest of characters of theWordon title(theWord)end formatreturn theListAsTextset theListAsText to theListAsText & nextToken & item i of theArrayset nextToken to item (i - 1) of theTokensrepeat with i from 2 to number of items in theArrayset theListAsText to first item of theArrayset AppleScript's text item delimiters to theTokensset AppleScript's text item delimiters to "{}"if theTokens is {} then set theTokens to {{}}if class of theTokens is not list then set theTokens to {theTokens}on format(theString, theTokens)end formatClassicreturn builtStringset builtString to replaceFirst(builtString, "{}", nextToken as text)repeat with nextToken in theTokensset builtString to theStringif class of theTokens is text then set theTokens to {theTokens}on formatClassic(theString as text, theTokens as list)end formatNextformat(theString, theTokens)on formatNext(theString as text, theTokens as list)end decodeUrlnewStringset newString to replace(newString, "%2C", ",")set newString to replace(newString, "%5C", "\\")set newString to replace(newString, "%29", ")")set newString to replace(newString, "%28", "(")set newString to replace(newString, "%22", "\"")set newString to replace(newString, "%27", "'")set newString to replace(newString, "%2b", "+")set newString to replace(newString, "%26", "&")set newString to replace(newString, "%40", "@")set newString to replace(newString, "%3A", ":")set newString to replace(newString, "%2F", "/")set newString to replace(newString, "%3E", ">")set newString to replace(newString, "%3C", "<")set newString to replace(newString, "%7C", "|")set newString to replace(newString, "%3D", "=")set newString to replace(newString, "%5D", "]")set newString to replace(newString, "%5B", "[")set newString to replace(theString, "%20", " ")set newString to replace(theString, "%0A", "on decodeUrl(theString as text)end encodeUrlreplacedTextset replacedText to replace(replacedText, ",", "%2C")set replacedText to replace(replacedText, "\\", "%5C")set replacedText to replace(replacedText, ")", "%29")set replacedText to replace(replacedText, "(", "%28")set replacedText to replace(replacedText, "\"", "%22")set replacedText to replace(replacedText, "'", "%27")set replacedText to replace(replacedText, "+", "%2b")set replacedText to replace(replacedText, "&", "%26")set replacedText to replace(replacedText, "@", "%40")set replacedText to replace(replacedText, ":", "%3A")set replacedText to replace(replacedText, "/", "%2F")set replacedText to replace(replacedText, ">", "%3E")set replacedText to replace(replacedText, "<", "%3C")set replacedText to replace(replacedText, "|", "%7C")set replacedText to replace(replacedText, "=", "%3D")set replacedText to replace(replacedText, "]", "%5D")set replacedText to replace(replacedText, "[", "%5B")set replacedText to replace(replacedText, " ", "%20")set replacedText to replace(theString, ASCII character 10, "%0A")on encodeUrl(theString as text)*)end urlEncodeend removeUnicodedo shell script "echo " & quoted form of textWithUnicodeChar & " | iconv -c -f utf-8 -t ascii || true"on removeUnicode(textWithUnicodeChar)end replaceFirstreturn startText & replacement & endTextset endText to text replaceEndOffset thru (length of sourceText) of sourceTextif length of sourceText is greater than substringOffset + (length of substring) - 1 then set replaceEndOffset to substringOffset + (length of substring)set replaceEndOffset to length of sourceTextset startText to text 1 thru (substringOffset - 1) of sourceTextif substringOffset is greater than 1 thenif length of substring is greater than length of sourceText then return sourceTextreturn (text 1 thru (substringOffset - 1) of sourceText) & replacementset endIdx to (offset of substring in sourceText) - 1 + (length of substring)if substringOffset + (length of (substring)) is equal to the (length of sourceText) + 1 thenif sourceText starts with substring then return replacement & text ((length of substring) + 1) thru (length of sourceText) of sourceTextif substringOffset is 0 then return sourceTextset substringOffset to offset of substring in sourceTexton replaceFirst(sourceText, substring, replacement)end stringBeforetext 1 thru ((offset of substring in sourceText) - 1) of sourceTextif sourceText starts with substring then return missing valueon stringBefore(sourceText, substring)end lastStringAfterlast item of split(sourceText, substring)on lastStringAfter(sourceText, substring)end stringAftertext ((offset of substring in sourceText) + (count of substring)) thru -1 of sourceTextif sourceText ends with substring then return missing valueif sourceText does not contain substring then return missing valueon stringAfter(sourceText, substring)mysql:5")-p 4306:3306-e MYSQL_ROOT_PASSWORD=dev-v \"`pwd`/init\":/docker-entrypoint-initdb.d-v ~/docker/mysql-data:/var/lib/mysql-itlog encodeUrl("docker container runlog format("Body: \"{}\"", "She")log format("Body: {}", "She said: \"hello?\"")log urlEncode(sut)2"set sut to "1unitTest()Encode Multi Line CommandWing It!Unit Testset thisCaseId to "string-spotCheck"if {"Script Debugger", "Script Editor"} contains the name of current application then spotCheck()end myGetBrowserNamebrowserNameset browserName to item 1 of browserNameset browserName to "Microsoft Edge" -- browser to run if not runningdisplay dialog "Microsoft Edge is not running. Cancel to stop script."if browserName is {} thenset browserName to (name of every process where name contains "Microsoft Edge")on myGetBrowserName()end extract_urlreturn theURLset AppleScript's text item delimiters to oldDelims -- restore them in case something went wrongset AppleScript's text item delimiters to oldDelims -- restore themset theURL to text 1 thru -2 of theURL -- strip off the last ")"set theURL to (get text item 2 of theMarkdownURL)set AppleScript's text item delimiters to {"]("} -- declare new delimitersset oldDelims to AppleScript's text item delimiters -- save their current stateon extract_url(theMarkdownURL)end extract_urlsreturn theUrlslog "4. " & (get theURL)set theUrls to theURL & return & theUrlsif theURL is not "" then -- remove blanksset theURL to my extract_url(i)set theURL to i -- my extract_urls(i)repeat with i in delimitedListset theUrls to ""set delimitedList to paragraphs of theMarkdownURLson extract_urls(theMarkdownURLs)tell application "Microsoft Edge Beta"else if browserName is "Microsoft Edge Beta" thendisplay dialog error_message with icon stopset the theURL to paragraph n of urlslog paragraph n of urlslog "** here"repeat with n from 1 to numParagraphsset numParagraphs to (number of paragraphs of urls)log "extracted urls:" & urlsset urls to my extract_urls(get the clipboard)set urls to (the clipboard)if browserName is "Microsoft Edge" thenset browserName to myGetBrowserName()log "nope"keystroke "d" using {command down, shift down}if (count of menu bar items) > iconCountlog "..."if (i is equal to max) then returnrepeat while i < maxkeystroke "n" using {command down}set iconCount to (count of menu bar items)tell menu bar 2tell process "MenubarX"tell application "MenubarX" to activateset max to 3end closeHTMLDialoglog_event((errStr as string), logPath) of commonScriptset myObj to "error"click button 1 of window "HTML Editor"tell process "Anki"on closeHTMLDialog()end openHTMLDialogkeystroke "x" using {shift down, command down}on openHTMLDialog()end replace_matchesreturn this_listif replace_all is false then return this_listset item i of this_list to the replacement_itemif this_item is the match_item thenset this_item to item i of this_liston replace_matches(this_list, match_item, replacement_item, replace_all)set AppleScript's text item delimiters to originalDelimitersmy closeHTMLDialog()set the clipboard to {text:(pasteText as string), Unicode text:pasteText}"
  • " & modifiedText & "
  • set pasteText to "
      my openHTMLDialog()tell application "Anki"set modifiedText to wordItems as textmy replace_matches(wordItems, "male", "masculine", false)my replace_matches(wordItems, "female", "feminine", false)set wordItems to text items of notesset notes to the clipboardset {originalDelimiters, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}}& "Scripts:commonLog.scpt")set commonScript to load script alias ((path to library folder from user domain as string) ¬set logPath to "/Users/alan/Documents/dev/scripts+tools/AppleScript logs/anki-reword-gender-log.txt"end fmGUI_ModeSelecttell application "htcLib" to fmGUI_ModeSelect(modeToSelect)on fmGUI_ModeSelect(modeToSelect)end fmGUI_ModeEnsure_Browseerror "Couldn't ensure in Browse Mode - " & errMsg number errNumfmGUI_ModeSelect("Browse")on fmGUI_ModeEnsure_Browse()fmGUI_ModeEnsure_Browse()keystroke theReferencedisplay alert errMsgtell application appName to activaterepeat until application appName is frontmostset theReference to do shell script "/usr/bin/curl 'http://localhost:23119/better-bibtex/cayw?format=pandoc' 2>/dev/null; exit 0"else if zotRunning is "ready" thendisplay alert "Better BibTeX not installed" message "This script will not work unless Better BibTeX is installed. Please make sure that Better BibTeX is installed in the running instance of Zotero"else if zotRunning is "No endpoint found" thentell application appNamedisplay alert "Zotero not running" message "This script will not work unless Zotero is running. Please launch Zotero and try again"if zotRunning is "" thenset zotRunning to do shell script "/usr/bin/curl 'http://localhost:23119/better-bibtex/cayw?probe=probe' 2>/dev/null; exit 0"display alert "Problem" message "Could not get the name of the frontmost application."set appName to (the name of every process whose frontmost is true) as stringdo script "sass --watch " & finderPath & "/styles/scss:" & finderPath & "styles --style compressed"set finderPath to quoted form of POSIX path of finderFolderset finderFolder to (path to home folder as alias)set finderFolder to (folder of the front window as alias)set finderPath to (target of front Finder window) as textset finderPath to ""if the name of window 1 is "homeWindow" thenset contents of text field "homeLocationText" of window "homeWindow" to (myProfileData_location)set myProfileData_location to updateLocation()else if the name of theObject is "locationUpdateButton" thenclose panel window "locationWindow"set title of window "homeWindow" to "Home"if the name of theObject is "locationHideButton" thenend updateLocationreturn myLocation_contset myLocation to (do shell script myLocation)set myLocation to ("curl --form-string " & quoted form of ("strDesc=" & myLocation_cont) & " --form-string " & quoted form of ("email=" & myLoginEmail) & " --form-string " & quoted form of ("password=" & myLoginPassword) & " --form press=OK" & " -e 'audiMate.updateLocation' " & quoted form of (myLocationURL))set myLocationURL to (homeRootURL & "updateLocation.php") as stringset myLocation_cont to (contents of text view 1 of scroll view 1 of window "locationWindow") as stringset myLoginPassword to (contents of text field "loginPasswordInput")set myLoginEmail to (contents of text field "loginEmailInput")on updateLocation()set infinite loop of eachCue to trueend extractIndexreturn indexNum((offset of pEndDelim in itemSel) - 1) of itemSel) as integer+ (length of pStartDelim)) thru ¬set indexNum to (text ((offset of pStartDelim in itemSel) ¬set itemSel to item 1 of pList as textlocal itemSel, indexNumon extractIndex(pList, pStartDelim, pEndDelim)open note window with oNoteSeldisplay dialog "NEW Note Created: " & return & noteTitleToFindset oNoteSel to create note with text noteContentStr title noteTitleToFind notebook nbName tags tagListelse --- CREATE NEW NOTE ---display dialog "HTML appended to Note: " & return & noteTitleappend oNoteSel html noteHTMLAppendset noteTitle to title of oNoteSelif oNoteSel ≠ "" then --- APPEND TO EXISTING NOTE ---set oNoteSel to item iNote of noteListset iNote to my extractIndex(noteSelected, startDelim, endDelim)if noteSelected ≠ {} thenif noteSelected is false then error number -128 -- user cancelledwith empty selection allowed"Cancel" multiple selections allowed false ¬"OK" cancel button name ¬& return & "(Press OK without selection for new note)" OK button name ¬& return & return & "Select the Note to Use in Notebook: " & nbName ¬"Multiple Notes found for Title:" & return & noteTitleToFind ¬with prompt ¬set noteSelected to choose from list pickList ¬set end of pickList to (startDelim & iNote & endDelim & " " & modDateStr & " | " & (title of oNote))set modDateStr to short date string of modDateset modDate to (modification date of oNote)set iNote to iNote + 1repeat with oNote in noteListset iNote to 0set pickList to {}else --- MULTIPLE NOTES FOUND ---set oNoteSel to ""display dialog "Note NOT Found with Title:" & return & noteTitleToFindelse if (numNotes = 0) then -- NO NOTES FOUND ---set oNoteSel to item 1 of noteListif (numNotes = 1) then -- ONE NOTE FOUND --set numNotes to count of noteListset noteList to find notes "notebook:\"" & nbName & "\" intitle:\"" & noteTitleToFind & "\""set nbName to text returned of ansRec"ENTER Notebook Search For:" default answer nbName ¬set noteTitleToFind to text returned of ansRecwith title (name of me) ¬"ENTER Note Title to Search For:" default answer noteTitleToFind ¬set ansRec to display dialog ¬set endDelim to "]|"set startDelim to "|["set noteContentStr to "New Note was created."_Ÿ�+�p���@V��� ^x���)g���:H���r��f|�I���/_m��P��� : � � < n � �  L � � � ? k � � 0 X x � � � � -[y�Ll��9O|��+r��R����]|���4���*e���.w��_n��,s��*n� ��;����K��w � a!'"e"�";#�#�#$�$�$W%&&K&�& 'Y'�'�'�'�(�(�(y)�)�)8*�*�*c+�+�+�+�,$-S-`-u-�-�-�-�- .2.k.�.�./A/�/�/�/0B0Q0g0{0�0�0�0�2�23$3;3�3�34,4/5b5�5�5�56<6[6z6�6�67C7V7�7�7E8�8�8�899B9V9�9�9�9�9':�:�:�:Q;�;�;<[<�<�<�<=`=�= >)>K>�>�>H?�?�?-@�@/A�A�A�ABbB�B-CeC�C�CED_D�D�D�D E6E�E�E�E�E@FxF�F�F�FDG�G�G HaH�H�H=I�I�IJeJ�JKHK�K�K-L~L�LMIM�M�MN5NtN�NO>O�P�PpQ�Q*RNR]R�R�R�R>S�S)T?T�T�T\U{U�U�U�V�V�X����áݡ�}���!���� �0���� �h��ӥs���Ʀ�Q���5�j���ب �M���;�o���"�<�r���ë�Z���ˬ�,�_����,�g���߮I�Я3���Ͱ��m���±@�Y���%�y�������0�o���/�l����C�˶.�n���D������ι��?�`�����ߺ)�w���d���ۼ�=�s�����ڽ��@���վ(�j���ٿ1�z���7�Y�����\������>�p����k������F�b�~���"�G��������'�������P�{�����j���9�w����h�|����A�����]�����������3�F�c�p������������O�Z�������������E�V�����������7�F�[�u����������9�y�������������\���������C�g�x������t���!�S���������/�A�d�u������%�;�Q�f��������h���������S������������M�\������>������������E�R�����������!�,�K�u����������E�c����������7�D�p�������������'�@�X�|��������F�c������� ��E�����������!�9�M�q������������/�@�d��������� �<�Z�q�����,�{������k��� �G�|��������y��������*�^�w���������.�M�y��������� �*�B�i��������� �y����J�\�u������k�x������Z����������A�Q�k�z���������#�V�g������������$�R����������0�[�����������������1�A�m���������0�C�m�������������C�m�����#�N�l������V�������@���>��J� <q�&T����-m����<k��@M����E��R � � � �  ( H X { � � � � �  D �  ( � � � � N } � � 7�  Q�����d�.}� k��$��8Y��f��'}��:K-�K�Je�Fb�!s�n��� + F � � � � "H"�"�"#G#�#�#�#�#$0$I$�$�$A%�%�%�%V&p&�&�&�&�&�&''4'W'�'(�(�(�(�()J)x)�)�)1*�*�*�*$+`+x+�+�+�,5-s-�-.r.�./\/�/�/0?0�0�0%1Z1k1�1�12=2�2�23g3�3�3�3:4j4�4�45C5�5�5�56B6�6�67a7�7�798�89�9�9S:~:�:�:7;t;�;<`<�<�<�<G=y=�=�=>+>l>�>�>�>?M?w?�?�?@'@T@�@�@�@A>AjA�A�A�AFB�B�B7C~C�C DUD�D�D.EiE�E�E.FoF�F�F6GuG�G HNH�H�H?I\IvI�I�I�I�I J3JOK�K�KL�]�Ŗ�]�j�����ė���<�f�����������ę��P�����B�\�~�̛(�g��������!�F�q���ܝ���g����� �;�W���� �;�[�{�֠3�W�i����������Ѣ��C�w���ܣ �8�`�����Ԥ���;�g���ץ��D�������ߦ��-�F�i�ѧ�c�ɨ���é��v���Ȫ��(�F�k�����=�a�y����6�f�����ԭ��B���ɮ��P�v�ӯ�.�j���˰��K�x�����:�l�������L����������C�d������ �=�|���Z�Q�k����i�d�d�ȼ��e�^�g��J�T��b�y��q�!�9�]� ���/�&���������9����o�X�h���}�k�����;���������l������M��� �r��� �{����j����W�����������.���?�N������������-�=�������� �T��������0�v������������*�K�o��������G�q�����c�����������-�����t������������L�]�|���v��� �5�I�������,����� ����������������������'�9�U������+�t�����&�s�����/�U�����?����������������)���+:R��I���4{��I��Q^�\��>`~�9]n��� B � ] � G b � � J ~ � � � # 9 V � � ]z�A���*�G���� V��6Vo�����?R�H����*Z�c�`��:f�'P~��W����GZ���4e��k � � �!�!�!("]"z"�"�"#;#�#�#$>$�$�$%E%�%�%�%�%E&�&�&F'j'�'�' ({(�(�()f)�)�)Y*f*�*�*�* +Q+�+�+�+�+�+,,C,-R-`-�-�-�-�-.X.f.�.�.�.�.�.�. //0/�/0Y0�0�0P1�1�1&2w2�2�2�34t4�45D5A6�6�6j7�78S8h8�8k9�9:B:u:�:�:;;G;{;�;�;�;�;<P<\<<�<==�=�=> >M>�>�>�>;?e?�?M@a@�@kA�A�B:C[ClC�C�CvD�DEFE�E�EVF}F�F�FGVH�HIMI�IJ~J�J�JK�K�K$LIL{L�L�L MKMrM�M�M�MN:NeN�N�N;OWOlO�O�O�OP8PoP�PQ9Q[Q�Q�Q�Q;R�R�R-S�S�SOT�TU\U�UVsV�V,W�W X�X�X[Y�Y Z�Z[J[�[X\�\/]�]�]X^y^�^_@___v_�_�_`.`V`�`�`�`awa�a�ablb�b c?c�c�cdRdrd�deBece�e�e�e"fEfVf�f�fg�g�g�g$hMh�hibiAj�j�j&kgk�k�k�k$lgl�l�l�m�m�mOn�n�n�n�n.oEoco�o�o�o!pOp�p�pFq�q�q�q�qrBrnr�rs]s�s�s�s�s8t|t�t�t�tu?uku�u;vKv_v�v�v:wdw�wx)xWx{x�x�x�x@y|y�y�y\z�z={�{�{|6|f|�|�|�| }-}X}�}�} ~~L~i~�~9��� �#�G������>�R�o�ց���3�o�Ԃ���U���Ã��(�R�~���#����V����>����j����9�x����*�f�����n�ȑ���ʓX���Δ� �-�M�k�ϖ�f�٘9����̚›�6���(���ݟ���>�|�أ �<�j���ۦ-�i��j���� ���d�*���۬��D���P��������j�=�o����`����$�n�d�Ľ���@�����P� �*�����n�����d�����?���W�������������+�������:�m�������V������+�P����b���������u������� �����m����^�n�����2�g��9�X�g�x����C�[�|��5��������)�;�p��� �c�����-�N��������� �P��������;�r������+�e������K�]������9��������@�p�����W�����}�������|������>���!�n������T�t��� �$�C�[������N�^�������U����I�r���������3�|����K�e�������X�{������������X�����;�U��� �0��/�o���������,�L�����h�����������]������� �h������{����,�������!�`�������:�g������#�}���������\�������J�\�s�������GU���<d��B���r��5� ��1��O�:Sy ; � � � Q � � ~ � � �  b � � _x���� �W�6\�:u��+� 93Y�!Nt�>ej����Z�(6Id����Jq����o��;_�� � � I!�!�!�!5"�"#,#>#[#v#�#�#Y$�$*%W%�%&{&�&�&}' (J(c()i)�)�)*u*�*+=+p+�+$,|,�,-"-�-�-�-'.C.�.�.$/,/A/a/�/�/0�0�0 1;1�1�1 272y2�2�2�2�23h3�3�3�3$4N4�4�45J5�586�6�67B7�7i8�8�8i9�9�9':R:}:�:�:P;j;�;@<�<=�=�=>>T>t>�>�>?`?�?�?�?S@�@�@AAAwA�A�A�A�ARB�BCvC�C�C�CD D&DMDbDwD�D�DEFEeE�E�E�F�F^G�G�G�G�G$H]H�HIIGI�IWwW�W�W�W�W XAX`X�X�X�XY]YyY�Y�Y'ZLZqZ�Z�Z�Z[<[K[[�[�[�[�[2\�\�\�\)]k]�]�] ^3^y^�^ _)_`_�_�_�_�_�_ `H`Z`w`�`�`�`�`aNa�a�ab>bQb\b�b�b�b�b�b c%c1cKcUchcc�c�c�c�c�cddAdZdfd�d�d�d�d�d�de$eLete�e�e�e*fdf�f�f�fg&gTgyg�g�g�g!hFh�i5jJj`j�j�j�jk+kOkk�k�k,l7l[lil�l�l�lmm*m>mrm�m�m�m n3n_n�n�n�noJo}o�o�o�op p?pZpwp�p�p�p�p>qLqwq�q�qrrPrzr�r�r�r�rs;sTsvs�s�s�st9t�t�t�t�tueu�u�u�u�u�uvvvVv�v�vw>w{w�w�wx?xax�x�x�x�z�z&{X{t{�{�{�{�{|-|x|�|�|�|�|}2}o}�}�}�}B~w~�~�~�~ ,k���$�o���ˀ��!�A�x������1������ �(�:�Z�w���ۃ �%�U���ل�=�u�����Dž݅y�����چ/�P�z�ć��V�w���� �-�c�����։��/�u����9�Y������K���Ќ��B�b�����D�j���Î�>�����ۏ3���ِ�i���ؑ�K�g���Ӓ���=�R��������:�N�d���ה�.�p�ĕ��+�X��Ė �?�n���͗�����c���Ě �S�s���ۛ�T��������V�~�����9�i�y���ߞ�A������(�`���Š�/�P�����3�n�����ܢ�%�K�o�����l�8�c����N�|��8���ͧ�B����F��� �a�۪/����h����Y����D�`�4�����ү"�m����� �#�K�m����a����#�}�ճ ��I�r�������Ӵ���:�w�5�����ܶ������� �?�X������T����9�z���%�5�N�s�����̻#�Z���ɼ�'�F�\���½�C�y�˾P�¿3�L�p�����1�o��������E�p�date_AccessRecord_AllTables({accessRecord:"Custom privileges...", recordAccess:{{baseTable:"ZZ_GLOBALS", viewAccess:"yes", editAccess:"yes", createAccess:"yes", deleteAccess:"yes", fieldAccess:"all", viewCalc:null, editCalc:null, createCalc:null, deleteCalc:null, fieldCalc:null}, {baseTable:"[Any New Table]", viewAccess:"yes", editAccess:"yes", createAccess:"yes", deleteAccess:"yes", fieldAccess:"all", viewCalc:null, editCalc:null, createCalc:null, deleteCalc:null, fieldCalc:null}}})on fmGUI_ManageSecurity_PrivSet_Update_AccessRecord_AllTables(prefs)set defaultPrefs to {accessRecord:null, recordAccess:null}set windowNameEditPrivSet to "Edit Privilege Set"set popUpExtras to {selectCommandset dialogParagraphBreak to return & returnproperty defaultAutomaticTransition : trueproperty defaultTransitionDelay : 2.0property defaultTransitionDuration : 0.5end writeNSImageObjectToFileAsJPEGerror "There was a problem writing the image object to file."tell theWorkspace to activateFileViewerSelectingURLs:theseURLstell current application's NSWorkspace to set theWorkspace to sharedWorkspace()set the end of theseURLs to (current application's NSURL's fileURLWithPath:targetImageFilePath)set theseURLs to {}if shouldRevealInFinder is true thenif theResult is true thenset theResult to (imageData's writeToFile:targetImageFilePath atomically:true |error|:(missing value)) as booleanset imageData to (imageRep's representationUsingType:(current application's NSJPEGFileType) |properties|:theProps)set theProps to current application's NSDictionary's dictionaryWithObject:1.0 forKey:(current application's NSImageCompressionFactor)set imageRep to current application's NSBitmapImageRep's imageRepWithData:tiffDataset tiffData to thisImageObject's TIFFRepresentation()on writeNSImageObjectToFileAsJPEG(thisImageObject, targetImageFilePath, shouldRevealInFinder)end createCustomPlaceholderImageFilereturn aResultset aResult to writeNSImageObjectToFileAsJPEG(aImage, targetImageFilePath, shouldReveal)aImage's unlockFocus()aColor's drawSwatchInRect:aRectaImage's lockFocus()set aImage to current application's NSImage's alloc()'s initWithSize:aSizeset aRect to current application's NSMakeRect(0, 0, aWidth, aHeight)set aSize to {width:aWidth, height:aHeight}set aColor to current application's NSColor's grayColoron createCustomPlaceholderImageFile(aWidth, aHeight, targetImageFilePath, shouldReveal)end indexOfItemInListreturn (theIndex + 1)set theIndex to theArray's indexOfObject:aValueon indexOfItemInList(aValue, theList)end promptForIntegerValuereturn thisValueif thisValue is greater than or equal to minimumValue and thisValue is less than or equal to maximumValue thenset thisValue to (the text returned of the result) as integerdisplay dialog thisPrompt default answer (defaultValue as string)on promptForIntegerValue(thisPrompt, minimumValue, maximumValue, defaultValue)tell application id "com.apple.Finder" to move targetImageFile to the trashset thisVerticalOffset to thisVerticalOffset + rowGutterHeight + shapeHeightset thisHorizontalOffset to thisHorizontalOffset + columnGutterWidth + shapeWidthif shouldAddID is true then set description of thisImage to placeholderTextset placeholderText to "IMAGE-" & imageItemCount as textset imageItemCount to imageItemCount + 1else -- odd row is imagesset placeholderText to "TEXT-" & textItemCount as textset textItemCount to textItemCount + 1if i mod 2 is 0 then -- even row is text itemselse if the objectType is "Both" thenmake new text item with properties {width:shapeWidth, height:shapeHeight, position:{thisHorizontalOffset, thisVerticalOffset}, object text:placeholderText}set placeholderText to ""if shouldAddID is true thenelse if the objectType is "Text Items" thentell application "System Events" to keystroke "i" using {control down, command down, option down}set thisImage to make new image with properties {file:targetImageFile, width:shapeWidth, height:shapeHeight, position:{thisHorizontalOffset, thisVerticalOffset}, description:placeholderText}set placeholderText to "PLACEHOLDER-" & (itemCounter as text)set itemCounter to itemCounter + 1if the objectType is "Images" thenrepeat with q from 1 to columnCountrepeat with i from 1 to rowCountset imageItemCount to 0set textItemCount to 0set itemCounter to 0set thisVerticalOffset to topMarginHeightset thisHorizontalOffset to leftMarginWidthtell current pageset targetImageFile to targetImageFilePath as POSIX filemy createCustomPlaceholderImageFile(shapeWidth, shapeHeight, targetImageFilePath, false)set targetImageFilePath to the POSIX path of (path to pictures folder) & "placeholder.jpg"set shapeHeight to editableRowAreaHeight div rowCountset shapeWidth to editableColumnAreaWidth div columnCountset editableRowAreaHeight to editableAreaHeight - (rowGutterCount * rowGutterHeight)set editableColumnAreaWidth to editableAreaWidth - (columnGutterCount * columnGutterWidth)set editableAreaHeight to documentHeight - topMarginHeight - bottomMarginHeightset editableAreaWidth to documentWidth - leftMarginWidth - rightMarginWidthset rowGutterCount to rowCount - 1set columnGutterCount to columnCount - 1set shouldAddID to falseset shouldAddID to trueif (the button returned of the result) is "Yes" thendisplay dialog pageIdentiferPrompt buttons {"Cancel", "No", "Yes"} default button 3set pageIdentiferPrompt to "Do you want add identifiers to the page items?"set rowCount to my promptForIntegerValue(rowCountPrompt, 2, 20, defaultRowCount)set rowCountPrompt to "Enter the row count:"if rowCount mod 2 is 0 thenset rowCount to my promptForIntegerValue(rowCountForBothPrompt, 2, 20, defaultRowCount)set rowCountForBothPrompt to "Since you’ve chosen to create paired image and text rows, enter the total row count (including both image and text rows):" & return & return & "(This value must be an even number)"if objectType is "Both" thenset columnCount to my promptForIntegerValue(columnCountPrompt, 2, 20, defaultColumnCount)set columnCountPrompt to "Enter the column count:"set rowGutterHeight to my promptForIntegerValue(rowGutterPrompt, 0, 100, defaultRowGutterHeight)set rowGutterPrompt to "Enter the space between rows (in pixels):"set columnGutterWidth to my promptForIntegerValue(columnGutterPrompt, 0, 100, defaultColumnGutterWidth)set columnGutterPrompt to "Enter the space between columns (in pixels):"set rightMarginWidth to my promptForIntegerValue(rightMarginPrompt, 0, documentHeight div 2, defaultRightMarginWidth)set rightMarginPrompt to "Enter the size of RIGHT page margin to use (in pixels):"set leftMarginWidth to my promptForIntegerValue(leftMarginPrompt, 0, documentHeight div 2, defaultLeftMarginWidth)set leftMarginPrompt to "Enter the size of the LEFT page margin to use (in pixels):"set bottomMarginHeight to my promptForIntegerValue(bottomMarginPrompt, 0, documentHeight div 2, defaultBottomMarginHeight)set bottomMarginPrompt to "Enter the size of the BOTTOM page margin to use (in pixels):"set topMarginHeight to my promptForIntegerValue(topMarginPrompt, 0, documentHeight div 2, defaultTopMarginHeight)set topMarginPrompt to "Enter the size of the TOP page margin to use (in pixels):"set the objectType to the button returned of the resultdisplay dialog objectTypePrompt buttons {"Images", "Text Items", "Both"} default button 3set objectTypePrompt to "Do you want to create just images, just text items, or both image and text items as pairs?"copy thisPageDimensions to {documentWidth, documentHeight}set thisPageDimensions to the reverse of thisPageDimensionsif the button returned of the result is "Landscape" thendisplay dialog orientationPrompt buttons {"Cancel", "Landscape", "Portrait"} default button 3set orientationPrompt to "Is the page orientation set to landscape or portrait?"set thisPageDimensions to item (my indexOfItemInList(chosenPageSize, paperSizeNames)) of paperSizeDimensionsset chosenPageSize to chosenPageSize as stringif chosenPageSize is false then error number -128set chosenPageSize to (choose from list paperSizeNames with prompt paperSizePrompt default items (item 1 of paperSizeNames))set paperSizePrompt to "What is this document’s paper size?"tell application id "com.apple.iWork.Pages"property paperSizeDimensions : {{612, 792}, {612, 1008}, {842, 1191}, {595, 842}, {420, 595}, {516, 729}, {499, 709}, {297, 684}, {312, 624}, {792, 1224}, {864, 1296}, {558, 774}, {340, 666}, {936, 1368}}property paperSizeNames : {"US Letter", "US Legal", "A3", "A4", "A5", "JIS B5", "B5", "Envelope #10", "Envelope DL", "Tabloid", "Tabloid Oversize", "ROC 16K", "Envelope Choukei 3", "Super B/A3"}property defaultRowCount : 6property defaultColumnCount : 3property defaultRowGutterHeight : 12property defaultColumnGutterWidth : 12property defaultRightMarginWidth : 36property defaultLeftMarginWidth : 36property defaultBottomMarginHeight : 36property defaultTopMarginHeight : 36end replaceWordWithStringInBodyTextset (last word where it is searchWord) to replacementStringif exists searchWord thenrepeat with i from the (count of paragraphs) to 1 by -1on replaceWordWithStringInBodyText(searchWord, replacementString)display notification "Errors occured." with title "Mail Merge with Contacts Group"if errorNumber is in {10002} then"The open document lists the errors occuring during the Mail Merge."set errorNumber to "MAIL MERGE ERRORS""There are no Pages user templates installed on this computer."set errorNumber to "NO USER TEMPLATES""Please close all documents before running this script."set errorNumber to "OPEN DOCUMENTS"display notification "Process completed." with title "Mail Merge with Contacts Group"set body text of thisDocument to errorLogmake new document with properties {document template:template "Blank"}if the (count of paragraphs of errorLog) is greater than 1 thentell application "Mail" to activate"Attempt at sending messages failed." & space & errorMessageset the errorLog to errorLog & return & ¬send thisMessageset thisMessage to item i of the createdMessagesrepeat with i from 1 to the count of the createdMessagesif attemptMailSend is true thenmove document file targetExportFileHFSPath to the trashset the end of createdMessages to thisMessage{file name:file targetExportFileHFSPath}make new attachment at end of paragraphs of content with properties ¬{address:recipientEmailAddress, name:(recipientFirstName & space & recipientLastName)}make new to recipient with properties ¬tell thisMessage{subject:outgoingMessageSubject, visible:true}set thisMessage to make new outgoing message with properties ¬export thisDocument to file targetExportFileHFSPath as PDFas PDF with properties {password:providedPassword}export thisDocument to file targetExportFileHFSPath ¬if usePDFEncryption is true thenset the targetExportFileHFSPath to (thisDirectoryHFSPath & exportDocName)my replaceWordWithStringInBodyText(placeholderWord, replacementString){placeholderWord, replacementString}copy item i of placeholderWordReplacementStringPairings to ¬repeat with i from 1 to the count of placeholderWordReplacementStringPairingswith timeout of 600 seconds -- allow up to 10 minutes to process really long documentsset placeholderWordReplacementStringPairings to {{senderFirstNamePlaceholder, senderFirstName}, {senderLastNamePlaceholder, senderLastName}, {senderEmailAddressPlaceholder, senderEmailAddress}, {senderFullAddressPlaceholder, senderAddress}, {senderPhoneNumberPlaceholder, senderPhoneNumber}, {recipientFirstNamePlaceholder, recipientFirstName}, {recipientLastNamePlaceholder, recipientLastName}, {recipientFullAddressPlaceholder, recipientFullAddress}}{document template:template chosenTemplateName}if skipFlag is false thenerrorLog & return & recipientEmailAddress & space & thisPersonIDStringset recipientEmailAddress to "NO-EMAIL-ADDRESS"if recipientEmailAddress is missing value then errorset recipientEmailAddress to the value of the first email of thisPersonerrorLog & return & recipientFullAddress & space & thisPersonIDStringset skipFlag to requireRecipientAddressset recipientFullAddress to "NO-FULL-ADDRESS"recipientFullAddress is missing value then errorif recipientFullAddressPlaceholderCount is not 0 and ¬set recipientFullAddress to the formatted address of the first address of thisPersonerrorLog & return & recipientLastName & space & thisPersonIDStringset recipientLastName to "NO-LAST-NAME"if recipientLastName is missing value then errorset recipientLastName to last name of thisPersonerrorLog & return & recipientFirstName & space & thisPersonIDStringset the errorLog to ¬set skipFlag to trueset recipientFirstName to "NO-FIRST-NAME"if recipientFirstName is missing value then errorset recipientFirstName to first name of thisPersonset thisPersonIDString to the id of person iset thisPerson to person i of the recipientGroupset skipFlag to falserepeat with i from 1 to the peopleCountset createdMessages to {}set the errorLog to "MAIL MERGE ERROR LOG"{"•"} default button 1 giving up after 1display dialog "Scan complete. Beginning Mail Merge…" buttons ¬close thisDocument saving nothe count of (every word where it is recipientFullAddressPlaceholder)set recipientFullAddressPlaceholderCount to ¬tell body text of thisDocumentmake new document with properties {document template:template chosenTemplateName}display dialog "Scanning template…" buttons {"•"} default button 1 giving up after 1if the outgoingMessageSubject is not "" then exit repeatset the outgoingMessageSubject to the text returned of the resultdisplay dialog "Enter the subject for the created Mail message:" default answer defaultMessageSubjectset defaultMessageSubject to "Document from " & senderFirstName & space & senderLastNameset usePDFEncryption to trueset providedPassword to the firstPassworddisplay dialog "Passwords do no match." buttons {"Cancel", "Try Again"} default button 2if firstPassword is not secondPassword thencopy the result to {button returned:buttonPressed, text returned:secondPassword}display dialog "Enter the password again:" default answer ¬set usePDFEncryption to falseif buttonPressed is "No Password" thencopy the result to {button returned:buttonPressed, text returned:firstPassword}"" buttons {"Cancel", "No Password", "OK"} default button 3 with hidden answerdisplay dialog "Enter a password for the PDF file:" default answer ¬set exportDocName to thisDocNameset exportDocName to thisDocName & ".pdf"if thisDocName does not end with ".pdf" thenif thisDocName is not "" thenset thisDocName to the text returned of the resultdisplay dialog "Enter the name to use for the exported document:" default answer ""set chosenTemplateName to chosenTemplateName as stringif chosenTemplateName is false then error number -128"Pick the tagged Pages template to use:" default items (item 1 of userTemplateNames))(choose from list userTemplateNames with prompt ¬set the chosenTemplateName to ¬if userTemplateNames is {} then error number 10001set userTemplateNames to the name of every template whose id of it begins with "User/"if the (count of documents) is not 0 then error number 10000set thisDirectoryHFSPath to (path to temporary items folder) as stringdisplay alert (errorNumber as string) message errorMessageif errorNumber is not -128 then"The chosen Contacts group contains no people."set errorNumber to "MISSING PEOPLE"else if errorNumber is 10006 then"There are no groups in the current contact database."set errorNumber to "MISSING GROUPS"else if errorNumber is 10005 then"The current default card is missing a value for the phone number field."set errorNumber to "MISSING PHONE NUMBER"else if errorNumber is 10004 then"The current default card is missing a value for the address fields."set errorNumber to "MISSING MAILING ADDRESS"else if errorNumber is 10003 then"The current default card is missing a value for the email address field."set errorNumber to "MISSING EMAIL ADDRESS"else if errorNumber is 10002 then"The current default card is missing a value for the First Name or Last Name fields."set errorNumber to "MISSING SENDER INFO"set selection to my cardelse if errorNumber is 10001 then"No person in this Contacts database is set to be the default card or “My Card.” Select a person and choose “Make This My Card” from the Card menu."set errorMessage to ¬set errorNumber to "NO DEFAULT CARD"if errorNumber is 10000 thenerror number 10006set peopleCount to the count of people of recipientGroupset recipientGroup to group recipientGroupNameset recipientGroupName to recipientGroupName as stringif recipientGroupName is false then error number -128"Pick the recipient Contacts group:" default items (item 1 of theseGroupNames))(choose from list theseGroupNames with prompt ¬set recipientGroupName to ¬set theseGroupNames to the name of every groupelse -- multiple groups, prompt the user to pick oneset recipientGroupName to name of recipientGroupset recipientGroup to group 1else if the groupCount is 1 thenerror number 10005if the groupCount is 0 thenset groupCount to count of groupsset senderPhoneNumber to senderPhoneNumber as stringif senderPhoneNumber is false then error number -128"Pick the sender phone number to use:" default items (item 1 of thesePhoneNumbers))(choose from list thesePhoneNumbers with prompt ¬set senderPhoneNumber to ¬set thesePhoneNumbers to the value of every phoneelse -- multiple phone numbers, prompt the user to pick oneset senderPhoneNumber to the value of first phone of itelse if the phoneCount is 1 thenerror number 10004if the phoneCount is 0 thenset the phoneCount to the count of phonesset senderAddress to senderAddress as stringif senderAddress is false then error number -128"Pick the sender address to use:" default items (item 1 of theseAddresses))(choose from list theseAddresses with prompt ¬set senderAddress to ¬set theseAddresses to the formatted address of every addresselse -- multiple addresses, prompt the user to pick oneset senderAddress to the formatted address of the first addresselse if the addressCount is 1 thenerror number 10003if the addressCount is 0 thenset the addressCount to the count of addressesset senderEmailAddress to senderEmailAddress as stringif senderEmailAddress is false then error number -128"Pick the sender email address to use:" default items (item 1 of theseEmailAddress))(choose from list theseEmailAddress with prompt ¬set senderEmailAddress to ¬set theseEmailAddress to the value of every emailelse -- multiple email addresses, prompt the user to pick oneset senderEmailAddress to the value of first emailelse if the emailCount is 1 thenerror number 10002if the emailCount is 0 thenset the emailCount to the count of emailserror number 10001if senderFirstName is missing value or senderLastName is missing value thenset senderLastName to last nameset senderFirstName to first nametell thisPersonif thisPerson is missing value then error number 10000set thisPerson to my cardset attemptMailSend to trueset attemptMailSend to falseif the button returned of the result is "OFF" thendisplay dialog "Set AUTO-SEND to:" buttons {"Cancel", "OFF", "ON"} default button autoSendStateif the button returned of the result is "Begin" thendisplay dialog "This script will perform a Mail Merge between a Pages tagged-template and a chosen Contacts group." & return & return & "Contact data requirements for the sender are: First Name, Last Name, eMail Address, Mailing Address, and phone." & return & return & "Contact data requirements for recipients are: First Name, Last Name, and eMail Address." & return & return & "AUTO-SEND: " & autoSendState with icon 1 buttons {"Cancel", "Set Prefs", "Begin"} default button 3set autoSendState to "ON"set autoSendState to "OFF"if attemptMailSend is false thenglobal peopleCount, recipientGroupproperty requireRecipientAddress : falseproperty attemptMailSend : falseproperty recipientFullAddressPlaceholder : "RECIPIENTFULLADDRESS"property recipientLastNamePlaceholder : "RECIPIENTLASTNAME"property recipientFirstNamePlaceholder : "RECIPIENTFIRSTNAME"property senderPhoneNumberPlaceholder : "SENDERPHONENUMBER"property senderFullAddressPlaceholder : "SENDERFULLADDRESS"property senderEmailAddressPlaceholder : "SENDEREMAILADDRESS"property senderLastNamePlaceholder : "SENDERLASTNAME"property senderFirstNamePlaceholder : "SENDERFIRSTNAME"end goToPagedelete thisShape{height:12, width:12, position:{0, 0}}make new shape with properties ¬set thisShape to ¬tell page pageIndexon goToPage(pageIndex)end displayThisNotificationdisplay notification thisNotification with title thisTitle subtitle thisSubtitleon displayThisNotification(thisTitle, thisNotification, thisSubtitle)end textItemsToTextreturn textBlockset the textBlock to textItems as stringset AppleScript's text item delimiters to (return & return) -- double spacedon textItemsToText(textItems)my displayThisNotification("OmniOutliner to Pages", "Document created.", "")my goToPage(1)set color of it to defaultTOCItemTypeColorset size to defaultTOCItemTypeSizeset font to defaultTOCItemTypeFacetell paragraphs 2 thru -1set color of it to defaultTOCTitleTypeColorset size to defaultTOCTitleTypeSizeset font to defaultTOCTitleTypeFacetell paragraph 1tell body text of section 2set body text of section 2 to TOCTextset x to x + (count of pages of section i)set sectionTitleCounter to sectionTitleCounter + 1tab & sectionStartPageIndex(item sectionTitleCounter of sourceDocumentSectionNames) & ¬set TOCText to TOCText & return & tab & ¬if useSectionTitleForTOC is true thenset TOCText to "TABLE OF CONTENTS" & returnif i is 2 thenset the end of the sectionStartIndexes to sectionStartPageIndexset the sectionStartPageIndex to xrepeat with i from 2 to the count of sectionsset sectionDisplayNumber to 1set sectionTitleCounter to 1set sectionStartIndexes to {}set x to 2 -- title and TOCset size to defaultBodyTypeSizeset font to defaultBodyTypeFaceset color of paragraph i to defaultBodyTypeColorset size to defaultSectionTypeSizeset font to defaultSectionTypeFacetell paragraph iset color of paragraph i to defaultSectionTypeColorrepeat with i from 1 to the count of paragraphstell section pagesSectionIndexset body text of section pagesSectionIndex to thisSourceDocumentSectionsTextset pagesSectionIndex to (i + bufferIndex)return & my textItemsToText(leavesNames)thisSourceDocumentSectionsText & return & ¬set thisSourceDocumentSectionsText to ¬set the leavesNames to the name of leavesset thisSourceDocumentSectionsText to name of ittell section irepeat with i from 1 to sourceDocumentSectionCountrepeat with i from 1 to (sourceDocumentSectionCount)set bufferIndex to 1set bufferIndex to 2make new sectionif createTOC is true thenset the color of it to defaultDocumentTitleTypeColorset size to defaultDocumentTitleTypeSizeset font to defaultDocumentTitleTypeFacetell body textset body text to sourceDocumentTitletell page 1display alert "INCOMPATIBLE TEMPLATE" message "The template of this document does not have an active document body text flow."if document body is false thentell thisDocument{document template:template defaultTemplateName}make new document with properties ¬set thisDocument to ¬the count of the sourceDocumentSectionNamesset the sourceDocumentSectionCount to ¬set the sourceDocumentSectionNames to the name of every sectionset sourceDocumentTitle to its nameset createTOC to falseset createTOC to trueif button returned of the result is "Include TOC" thendisplay dialog "This script will create a new Pages word-processing document, with each section of the frontmost OmniOutliner document becoming a new section in the Pages document." & return & return & "The name of each OmniOutliner section will be used as both the title of the newly created Pages section, and as an entry in the optionally created Table of Contents." with icon 1 buttons {"Cancel", "Include TOC", "Build"} default button 3property useSectionTitleForTOC : trueproperty defaultTOCItemTypeColor : "gray"property defaultTOCItemTypeSize : 18property defaultTOCItemTypeFace : "Hoefler Text"property defaultTOCTitleTypeColor : "black"property defaultTOCTitleTypeSize : 22property defaultTOCTitleTypeFace : "Helvetica"property defaultBodyTypeColor : "gray"property defaultBodyTypeSize : 12property defaultBodyTypeFace : "Hoefler Text"property defaultSectionTypeColor : "black"property defaultSectionTypeSize : 18property defaultSectionTypeFace : "Times New Roman Italic"property defaultDocumentTitleTypeColor : "black"property defaultDocumentTitleTypeFace : "Hoefler Text"property defaultDocumentTitleTypeSize : 32property defaultTemplateName : "Blank"get yCoordinate of myPoint --result: 20get xCoordinate of myPoint --result: 10set myPoint to makePoint(10,20)end makePointreturn thePointproperty yCoordinate:yproperty xCoordinate:xscript thePointon makePoint(x, y)tell John to sayHello to "Herb" --result: "Hello Herb"end sayHelloreturn "Hello " & someoneset HowManyTimes to HowManyTimes + 1to sayHello to someoneproperty HowManyTimes : 0script JohncurrentCount of Paula --result: 20currentCount --result: 2run Paula --result: 2run Paula --result: 1tell Joe to increment()return currentCountscript Joeproperty currentCount : 20script Paulaproperty currentCount : 0increment() --result: 2increment() --result: 1set currentCount to 0display dialog "Count is now " & currentCount & "."set currentCount to 1set currentCount to currentCount + 1increment()global currentCountname of currentWindowRef --result: "Script testing folder"copy windowRef to currentWindowRef --result: a new object specifiername of windowRef --result: "Script testing folder"set windowRef to a reference to window 1 of application "Finder"{alpha, beta, gamma, delta} -- List variables to show contentsset property1 of alpha to 42copy gamma to deltaset gamma to {alpha, beta, "Goodbye"}set beta to {1, 2, "Hello"}set alpha to {property1:10, property2:20}set {p, q, {lastName:r}} to xset {p, q, r} to xset x to {8, 94133, {firstName:"John", lastName:"Chapman"}}set yourName to myNameset myName to "Sheila"set item 1 of myList to 4set yourList to myListset myList to { 1, 2, 3 }set word1 to word 1 of front document --result: some wordset myList to { 1, 2, "four" } --result: {1, 2, "four"}set numClowns to 5 --result: 5set gNextAgentNumber to getNextAvailNumber() -- call handler to get numberset gStatementDate to current date -- get date from current date commandset gAgentCount to getCurrentAgentCount() -- call handler to get countglobal gStatementDate, gNextAgentNumberglobal gAgentCountcopy current date to agentHireDate -- call current date command; a dateset agentNumber to getAgentNumber(agentName) -- call handler; an integerset agentName to "James Smith" -- assign agent name; a text stringset windowCount to 0 -- initialize to zero; an integerlocal agentName, agentNumber, agentHireDate -- defines three variableslocal windowCount -- defines one variablecopy circumference to savedResult --result: 10.995574287564 (copy of 1st variable)set circumference to pi * 3.5 --result: 10.995574287564property strangeValue : (pi * 7)^2property defaultName : "Barry"property windowCount : 0display dialog "I found the hammer!"if contents of currentWord is equal to "hammer" thenlog currentWordrepeat with currentWord in wordListset wordList to words in "Where is the hammer?"display dialog "In factorial routine; x = " & (x as string)open application file id "com.apple.TextEdit"tell remoteFinderusing terms from application "Finder""eppc://myUserName:pwd@123.23.23.123"set remoteFinder to application "Finder" of machine ¬tell app "Finder" of machine remoteMachine to close front windowset remoteMachine to "eppc://userName:pwd@MacName.local"close access referenceNumberset referenceNumber to open for access theFile with write permissionset theFile to choose file nametell application "TextEdit" to open notesFileset notesFile to POSIX file "/Users/myUser/Feb_Meeting_Notes.rtf"if myVariable is equal to missing value thenset myVariable to missing valueget current application --result: current applicationversion of AppleScript --result: "2.0"version --result: "10.5.1"if version of AppleScript as string ≥ "1.9" thenerror m number non error m number nset AppleScript's text item delimiters to savedDelimitersset AppleScript's text item delimiters to {"**"}set savedDelimiters to AppleScript's text item delimitersset AppleScript's text item delimiters to {":"}get last text item of "Hard Disk:CD Contents:Release Notes"set AppleScript's text item delimiters to {", "}set circleArea to pi * 7 * 7 --result: 153.9380400259duplicate paragraph 1 to before paragraph 4tell front document of application "TextEdit"duplicatetell last file of window 1 of application "Finder"if file "semaphore" of application "Finder" exists thenduplicate last file of window 1 of application "Finder"extract address from "John Doe "use application "Mail"get name of first windowpath to scripting additions as textset myText to 2 as textname of myWindow --result: "Q1.rtf" (if that is the first window's name)set myWindow to a ref to window 1 of application "TextEdit"get myWindowcontents of myWindowmyWindowset myWindow to a ref to window "Q1.rtf" of application "TextEdit"set docRef to a reference to document "New Report.rtf"name of docRef --result: "New Report.rtf"set docRef to a reference to the first documentname of item 1 of disk 2version of application "Finder" --result: "10.5.1"first window's namefirst item of first folder of first diskfolder "Applications" of startup diskparagraph 1 of document 1myList --result: {0, 1, "what", 3, "four"}set end of myList to "four"set beginning of myList to 0set myList to {1, "what", 3} --result: {1, "what", 3}greetClient("Joe Jones") --result: "Hello Joe Jones!"run testGreet --result: "Hello Mary Smith!"greetClient(defaultClientName)script testGreetend greetClientdisplay dialog ("Hello " & nameOfClient & "!")on greetClient(nameOfClient)property defaultClientName : "Mary Smith"get name of front window of application "Finder"close window savedNameset savedName to name of front windowset averageTemp to 63 as degrees Fahrenheitcopy 33 to myAgeset myName to "John"default button "OK" giving up after 3display dialog "This is just a test." buttons {"Great", "OK"}end callFunction:withArgs:inJSLib:if theResult is missing value then error (theError's localizedDescription()) as textset {theResult, theError} to myJSLib's executeHandlerWithName:funcName arguments:argsList |error|:(reference)on callFunction:funcName withArgs:argsList inJSLib:myJSLibmy callFunction:"doIt" withArgs:{2, 2} inJSLib:myJSLibif myJSLib is missing value then error (theError's localizedDescription()) as textset {myJSLib, theError} to current application's OSAScript's alloc()'s initWithContentsOfURL:(current application's |NSURL|'s fileURLWithPath:jsLibPath) |error|:(reference)set jsLibPath to POSIX path of (jsLib as alias)on error from jsLib -- jsLib will refer to libscript "JSTest.scpt"try -- will fail because it's jsset currentUsers to currentUsers & item i of theNames & tab & tab & tab & item i of theIDs & returnrepeat with i from 1 to count of theNamesset theIDs to theThing's valueForKeyPath:"deletedUsers.dsAttrTypeStandard:UniqueID"set theNames to theThing's valueForKeyPath:"deletedUsers.dsAttrTypeStandard:RealName"set {theThing, theError} to current application's NSPropertyListSerialization's propertyListWithData:theData options:0 |format|:(missing value) |error|:(reference)set currentUsers to currentUsers & return & return & "Deleted User List:" & returnif theData is not missing value thenset theData to current application's NSData's dataWithContentsOfFile:"/Library/Preferences/com.apple.preferences.accounts.plist"set currentUsers to currentUsers & (do shell script "dscl . list /Users UniqueID | egrep -v ^'_|daemon|nobody|root'")set currentUsers to "Login User List:" & returnend formatAsBytes:return (theNSByteCountFormatter's stringFromByteCount:theValue) as texttheNSByteCountFormatter's setCountStyle:(current application's NSByteCountFormatterCountStyleFile)theNSByteCountFormatter's setIncludesActualByteCount:trueset theNSByteCountFormatter to current application's NSByteCountFormatter's alloc()'s init()on formatAsBytes:theValueend sizeOfFolder:return totalSizeset totalSize to totalSize + (theResult as real)set {hasResult, theResult} to (nextURL's getResourceValue:(reference) forKey:(current application's NSURLTotalFileSizeKey) |error|:(missing value))repeat with nextURL in theEnumerator's allObjects()set theEnumerator to current application's NSFileManager's defaultManager()'s enumeratorAtURL:theURL includingPropertiesForKeys:{current application's NSURLTotalFileSizeKey} options:0 errorHandler:(missing value)set totalSize to 0set theURL to current application's |NSURL|'s fileURLWithPath:folderPosixPathon sizeOfFolder:folderPosixPathdisplay dialog (its formatAsBytes:totalSize)set totalSize to its sizeOfFolder:theFolderset theFolder to "/Users/shane/Desktop/"RootMenu's setAutoenablesItems:false -- enabling/disabling must be done manuallyend validateMenuItem:display dialog theSelset theSel to anItem's action() as texton validateMenuItem:anItemend doDemo2:on doDemo2:senderRootMenu's addItem:DemoMenuItemset RootMenu to current application's NSApp's mainMenu()DemoMenuItem's setSubmenu:DemoMenuset DemoMenuItem to current application's NSMenuItem's alloc()'s initWithTitle:"Demo" action:"" keyEquivalent:""set ReturnValue to DemoMenu's addItemWithTitle:"Demo 3" action:"doDemo3:" keyEquivalent:""set ReturnValue to DemoMenu's addItemWithTitle:"Demo 2" action:"doDemo2:" keyEquivalent:""set ReturnValue to DemoMenu's addItemWithTitle:"Demo 1" action:"doDemo1:" keyEquivalent:""end doDemo3:display dialog "message" buttons {"Cancel", "OK"} default button "OK" with title "Demo 3"on doDemo3:senderend doDemo2display dialog "message" buttons {"Cancel", "OK"} default button "OK" with title "Demo 2"on doDemo2()end doDemo1:display dialog "message" buttons {"Cancel", "OK"} default button "OK" with title "Demo 1"on doDemo1:senderset ReturnValue to DemoMenu's addItemWithTitle:"Demo 3" action:"DoDemo3:"set ReturnValue to DemoMenu's addItemWithTitle:"Demo 2" action:"DoDemo2" keyEquivalent:""ReturnValue's setTarget:meset ReturnValue to DemoMenu's addItemWithTitle:"Demo 1" action:"DoDemo1:" keyEquivalent:""set DemoMenuItem's submenu to DemoMenuset DemoMenu to current application's NSMenu's alloc()'s initWithTitle:"Demo"set DemoMenuItem to RootMenu's addItemWithTitle:"Demo" action:"" keyEquivalent:""set RootMenu to current application's NSApp's mainMenuend ModifyTargetsOfItems(theDemoMenuItem's setTarget:me)set theDemoMenuItem to (theDemoMenuItems's itemAtIndex:i)repeat with i from 0 to 2set theDemoMenuItems to theDemoMenu's submenu()set theDemoMenu to current application's NSApp's mainMenu()'s itemWithTitle:"Demo"set theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:1)'s submenu())'s itemAtIndex:4set theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:1)'s submenu())'s itemAtIndex:3set theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:1)'s submenu())'s itemAtIndex:2set theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:1)'s submenu())'s itemAtIndex:1set theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:1)'s submenu())'s itemAtIndex:0theMenuItem's setTarget:meset theMenuItem to ((current application's NSApp's mainMenu()'s itemAtIndex:0)'s submenu())'s itemAtIndex:0on ModifyTargetsOfItems()ModifyTargetsOfItems() -- my own procedure to set the menu items's target to meModifyMenu() -- Original call in the appletset unmountedVolumes to volumeNames as listvolumeNames's removeObjectsInArray:mountedVolumesset mountedVolumes to theDict's objectForKey:"VolumesFromDisks"set volumeNames to (partitionInfos's valueForKey:"VolumeName")'s mutableCopy()set {theDict, theError} to current application's NSPropertyListSerialization's propertyListWithData:theData options:0 format:(missing value) |error|:(reference)(partitionInfos's valueForKey:"VolumeName") as listpartitionInfos's filterUsingPredicate:thePredset thePred to current application's NSPredicate's predicateWithFormat:"(Content BEGINSWITH %@) AND (NOT Content IN %@)" argumentArray:{"Apple_", {"Apple_Boot", "Apple_CoreStorage"}}if not (anInfo's isKindOfClass:(current application's NSNull)) then (partitionInfos's addObjectsFromArray:anInfo)repeat with anInfo in partitionInfoset partitionInfos to current application's NSMutableArray's array()set partitionInfo to theDict's valueForKeyPath:"AllDisksAndPartitions.Partitions"if theDict is missing value then error (theError's localizedDescription() as text)set {theDict, theError} to current application's NSPropertyListSerialization's propertyListWithData:theData options:0 |format|:(missing value) |error|:(reference)set theString to current application's NSString's stringWithString:theStringset theString to do shell script "diskutil list -plist"dateFormat's setDoesRelativeDateFormatting:truedateFormat's setTimeStyle:(current application's NSDateFormatterMediumStyle)dateFormat's setDateStyle:(current application's NSDateFormatterLongStyle)set theString to theDay & " à " & theHourset theHour to (dateFormat's stringFromDate:theDate) as textset theFormatter to "HH:mm:ss"set theDay to (dateFormat's stringFromDate:theDate) as textdateFormat's setDateFormat:theFormatterset dateFormat to current application's NSDateFormatter's alloc()'s init()set theFormatter to "EEEE d MMMM"set theDay to "Hier"else if theCal's isDateInYesterday:theDate thenset theDay to "Aujourd'hui"if theCal's isDateInToday:theDate thenset theCal to current application's NSCalendar's currentCalendar()set theDate to ((current date) - 1 * days)select row 2 of table 1 of scroll area 1 of splitter group 1 of splitter group 1 of window 1splitter group 1 of splitter group 1 of window 1tell process "Emoji et symboles" -- or tell process "CharacterPalette"keystroke space using {command down, control down}select row 2 of table 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Characters"tell process "Emoji & Symbols"select row 2 of table 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Caractères"tell process "Emoji et symboles"tell application "SSD MacPro:System:Library:Input Methods:CharacterPalette.app:"set theURLs to current application's NSArray's arrayWithArray:(o's theURLs)set end of o's theURLs to oneURLproperty theURLs : {}script oset unconformingUTIs to unconformingUTIs & thisUTIAsTextset conformingUTIs to conformingUTIs & thisUTIAsTextelse if ((thePredicate's evaluateWithObject:thisUTI) as boolean) then -- This works even if thisUTI is missing value.(theURLs's addObject:oneURL)else if (conformingUTIs contains thisUTIAsText) thenif (unconformingUTIs contains thisUTIAsText) thenset thisUTIAsText to linefeed & thisUTI & linefeedset thisUTI to end of (oneURL's getResourceValue:(reference) forKey:typeIdentifierKey |error|:(missing value))set unconformingUTIs to ""set conformingUTIs to ""(predArray's addObject:(current application's NSPredicate's predicateWithFormat_("self UTI-CONFORMS-TO %@", aKind)))set keysToRequest to current application's NSArray's arrayWithObject:(typeIdentifierKey)set typeIdentifierKey to current application's NSURLTypeIdentifierKeymy filteredContents:"/Applications" withUTI:{"public.image", "com.adobe.pdf"} |returning|:"file" recursive:trueend filteredContents:withUTI:|returning|:recursive:if returnType = "url" then return theURLsif returnType = "path" then return (theURLs's valueForKey:"path") as listif returnType = "name" then return (theURLs's valueForKey:"lastPathComponent") as listif ((thePredicate's evaluateWithObject:keyValue) as boolean) then (theURLs's addObject:oneURL)set keyValue to (oneURL's resourceValuesForKeys:keysToRequest |error|:(missing value))repeat with oneURL in allURLsset theURLs to current application's NSMutableArray's new()set thePredicate to current application's NSCompoundPredicate's orPredicateWithSubpredicates:predArray(predArray's addObject:(current application's NSPredicate's predicateWithFormat_("%K UTI-CONFORMS-TO %@", current application's NSURLTypeIdentifierKey, aKind)))repeat with aKind in wUTIset predArray to current application's NSMutableArray's new()set allURLs to theFileManager's contentsOfDirectoryAtURL:theFolderURL includingPropertiesForKeys:keysToRequest options:4 |error|:(missing value)set allURLs to (theFileManager's enumeratorAtURL:theFolderURL includingPropertiesForKeys:keysToRequest options:6 errorHandler:(missing value))'s allObjects()if wRecursive = true thenset theFileManager to current application's NSFileManager's defaultManager()set keysToRequest to current application's NSArray's arrayWithObject:(current application's NSURLTypeIdentifierKey)set theFolderURL to current application's NSURL's fileURLWithPath:(POSIX path of theFolder)on filteredContents:theFolder withUTI:wUTI |returning|:returnType recursive:wRecursivereturn {bridgedDate, bridgedDate2, theNSDate}set theNSDate to current application's NSDate's dateWithTimeInterval:(-10000 * days) sinceDate:nowNSDateset bridgedDate2 to current application's NSDate's dateWithTimeInterval:(-10000 * days) sinceDate:nowDateset bridgedDate to current application's NSDate's dateWithTimeInterval:(0) sinceDate:(ASDate)set ASDate to nowDate - 10000 * days --> A date in 1990 on the day of posting.set nowNSDate to current application's NSDate's |date|()set nowDate to current dateuse AppleScript version "2.5"end makeASDateFromset theASDate to theASDate - timeAdjustmentset timeAdjustment to ((date (theASDate's time string)) - (date (recentDate's time string)))tell theASDate to set {its day, its month, its day, its hours, its minutes, its seconds} to {1, m, d, h, min, s}set theASDate to eraStartDate - (ADDate - eraStartDate)tell ADDate to set {its year, its month} to {y, July}copy eraStartDate to ADDatetell (current date) to set {eraStartDate, its day, its year, its month, its time} to {it, 1, 1, 1, 0}tell (current date) to set {theASDate, its day, its year, its month, its day, its hours, its minutes, its seconds} to {it, 1, y, m, d, h, min, s}if (theEra is 1) thentell comps to set {theEra, y, m, d, h, min, s} to {its era(), its |year|(), its |month|(), its |day|(), its hour(), its minute(), its |second|()}on makeASDateFrom(theNSDate)end makeNSDateFromreturn theCalendar's dateWithEra:(theEra) |year|:(y) |month|:(m as integer) |day|:(d) hour:(0) minute:(0) |second|:(t) nanosecond:(0)if (theEra is 0) then set y to 1 - yset theEra to (y > -1) as integerset {y, m, d, t} to theASDate's {year, month, day, time}set theASDate to theASDate + timeAdjustmentif (timeAdjustment > 0) then set timeAdjustment to timeAdjustment - daysset timeAdjustment to (date (theASDate's time string)) - (date (recentDate's time string))set recentDate's year to 2000copy theASDate to recentDateon makeNSDateFrom(theASDate)return {ASDate, newNSDate, newASDate}set newASDate to makeASDateFrom(newNSDate)set newNSDate to makeNSDateFrom(ASDate)set ASDate to (current date) - 1000000 * days --> A date in January 721 BC on the day of posting.use AppleScript version "2.3.1" -- Mavericks (10.9.something) or laterend makeASDateFrom:{it, comps's |year|(), 1, comps's |month|(), comps's |day|(), (comps's hour()) * hours + (comps's minute()) * minutes + (comps's |second|())}tell (current date) to set {theASDate, year, day, its month, day, time} to ¬set comps to theCalendar's componentsInTimeZone:(missing value) fromDate:theNSDateon makeASDateFrom:theNSDateend makeNSDateFrom:return newDateset newDate to theCalendar's dateWithEra:(theYear ≥ 0) |year|:theYear |month|:(theMonth as integer) |day|:theDay hour:0 minute:0 |second|:theSeconds nanosecond:0if theYear < 0 then set theYear to -theYearset {theYear, theMonth, theDay, theSeconds} to theASDate's {year, month, day, time}on makeNSDateFrom:theASDateits makeASDateFrom:newDateset newDate to its makeNSDateFrom:(current date)use AppleScript version "2.3.1"end controlTextDidChange:[...]if theField's isEqualTo:firstField thenset theField to notif's |object|()on controlTextDidChange:notif«event ©±SQ©±Ef» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?)", «class ©±Ir»:tempPath, «class ©±Ck»:tabset thePath to "~/Desktop/TestTSV2.db"write tabbedText to fileRef as «class utf8»set tempPath to (path to desktop as string) & "TestTSV.txt"«event ©±SQ©±Et» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?)", «class ©±Ca»:tabbedText, «class ©±Ck»:tabset thePath to "~/Desktop/TestTSV1.db"set tabbedText to "One" & tab & "Two\",\" two" & tab & "Three" & tab & "Four" & linefeed & "Five\",\" five" & tab & "Six" & tab & "Seven" & tab & "Eight" & return & "Nine" & tab & "Ten" & tab & "Eleven" & tab & "Twelve" & linefeed & linefeed & returnreturn {result1, result2, result1 = result2}set result2 to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from test"«event ©±SQ©±Ef» theDb with «class ©±Cv» given «class ©±Cq»:"insert into test values (?, ?, ?, ?)", «class ©±Ir»:tempPathset thePath to "~/Desktop/TestCSV2.db"write csvText to fileRef as «class utf8»set eof of fileRef to 0set fileRef to open for access tempPath as «class furl» with write permissionset tempPath to (path to desktop as string) & "TestCSV.txt"«event ©±SQ©±Et» theDb with «class ©±Cv» given «class ©±Cq»:"insert into test values (?, ?, ?, ?)", «class ©±Ca»:csvText«event ©±SQ©±Eu» theDb given «class ©±Cq»:"create table test (a, b, c, d)"set thePath to "~/Desktop/TestCSV1.db"set csvText to "One,Two\",\" two,Three,\"Four \"\"four\"\" four\"" & linefeed & "Five\",\" five,Six,Seven,Eight" & return & "Nine,\"Ten , ten\",Eleven,Twelve" & linefeed & returnreturn {theResult, secondResult, thirdResult}set thirdResult to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from test where a = ?", «class ©±Cg»:{"hi"}, «class ©±Cn»:{3}, «class ©±Cy»:«constant ©±Tt©±Tr»set secondResult to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from test", «class ©±Cy»:«constant ©±Tt©±Tr»display dialog errMess & " (" & errNum & ")"on error errMess number errNumset theResult to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select a, b from test where a = ?", «class ©±Cg»:{"hi"}, «class ©±Cy»:«constant ©±Tt©±Tr»{"hum", "number " & 2, 2, current date, 3.1}}{"ho", "number " & 2, 2, current date, 2.1}, ¬«event ©±SQ©±Eb» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?, ?)", «class ©±Cg»:{¬ {"hi", "number " & 1, 1, current date, 1.1}, ¬«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?, ?)", «class ©±Cg»:{"hi", "number " & i, i, current date, i + 0.1}repeat with i from 4 to 6«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (:a, :b, :c, :d, :e)", «class ©±Ci»:{a:"hello", b:"number " & i, c:i, d:current date, e:i + 0.1}«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (:a, :b, :c, :d, :e)", «class ©±Ci»:{a:"hello", b:"number " & 1, c:1, d:current date, e:1 + 0.1}«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?, ?)", «class ©±Cg»:{"hi", "number " & 1, 1, current date, 1.1}«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (1, 1, 1, 1, 1)"set thePath to "~/Desktop/Test.db"error errMess number errNum from x«event ©±SQ©±Cd» otherDbon error errMess number errNum from xset result3 to «event ©±SQ©±Ce» otherDb given «class ©±Cq»:"select * from test", «class ©±Cn»:{0, 3} -- zero-based column numbersset result2 to «event ©±SQ©±Ce» otherDb given «class ©±Cq»:"select * from test"set otherDb to «event ©±SQ©±Od» given «class ©±If»:thePath2set result1 to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from test"set theDb to «event ©±SQ©±Od» given «class ©±If»:thePath«event ©±SQ©±Cd» imDb«event ©±SQ©±Cw» imDb given «class ©±Tf»:thePath2 -- only works with in-memory databasesset thePath2 to "~/Desktop/Test2.db"(«event ©±SQ©±Eu» imDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?, ?)", «class ©±Cg»:{theDate, "number " & i, i, theDate, i + 0.1})set theDate to (current date) + i * 60repeat with i from 1 to 3set imDb to «event ©±SQ©±Od» with «class ©±Cw» and «class ©±Cm» given «class ©±If»:thePath«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into test values (?, ?, ?, ?, ?)", «class ©±Cg»:{1, 1, 1, 1, 1}«event ©±SQ©±Eu» theDb given «class ©±Cq»:"create table test (a text, b text, c integer, d double, e double)"«event ©±SQ©±Eu» theDb given «class ©±Cq»:"drop table if exists test"set theDb to «event ©±SQ©±Od» with «class ©±Cc» given «class ©±If»:thePathset thePath to "~/Desktop/Test1.db"return {result1, result2, result3}«event ©±SQ©±Cd» theDbset result3 to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from standings where country in (?, ?)", «class ©±Cg»:{"Italy", "France"}, «class ©±Cy»:«constant ©±Tt©±Tr»set result2 to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from standings"«event ©±SQ©±Eb» theDb given «class ©±Cq»:"insert into standings values (?, ?, ?, ?)", «class ©±Cg»:theList«event ©±SQ©±Eu» theDb given «class ©±Cq»:"delete from standings"set result1 to «event ©±SQ©±Ce» theDb given «class ©±Cq»:"select * from standings"«event ©±SQ©±Ct» theDb«event ©±SQ©±Eu» theDb given «class ©±Cq»:"insert into standings values (?, ?, ?, ?)", «class ©±Cg»:anEntryrepeat with anEntry in theList«event ©±SQ©±Cb» theDb«event ©±SQ©±Eu» theDb given «class ©±Cq»:"create table standings (firstname, lastname, country, position integer)"«event ©±SQ©±Eu» theDb given «class ©±Cq»:"drop table if exists standings"set theDb to «event ©±SQ©±Od» with «class ©±Cc» given «class ©±If»:"~/desktop/TestDB.db"{"Jakob", "Fuglsang", "Denmark", 5}}{"Rigoberto", "Uran", "Colombia", 4}, ¬{"Romain", "Bardet", "France", 3}, ¬{"Fabio", "Aru", "Italy", 2}, ¬set theList to {¬ {"Christopher", "Froome", "Britain", 1}, ¬use script "SQLite Lib2" version "1.0.0"use AppleScript version "2.5" -- El Capitan (10.11) or laterend hex encodereturn (theString's stringByApplyingTransform:"[^\\x20-\\x7e]-Hex/XML" |reverse|:false) as texton hex encode theStringend hex decodereturn (theString's stringByApplyingTransform:"Hex-Any" |reverse|:false) as texton hex decode theStringend decimal encodereturn (theString's stringByApplyingTransform:"[^\\x20-\\x7e]-Hex/XML10" |reverse|:false) as texton decimal encode theStringend ICU transformreturn (theString's stringByApplyingTransform:nameOfTransform |reverse|:reverseTransform) as texton ICU transform theString transform name nameOfTransform reverse transform reverseTransform : falseend percent decodereturn theString's stringByRemovingPercentEncoding() as texton percent decode theStringend percent encodereturn (theString's stringByAddingPercentEncodingWithAllowedCharacters:allowedSet) as textelse -- fall backset allowedSet to NSCharacterSet's URLUserAllowedCharacterSet()else if allowedSet = user characters thenset allowedSet to NSCharacterSet's URLPasswordAllowedCharacterSet()else if allowedSet = password characters thenset allowedSet to NSCharacterSet's URLFragmentAllowedCharacterSet()else if allowedSet = fragment characters thenset allowedSet to NSCharacterSet's URLQueryAllowedCharacterSet()else if allowedSet = query characters thenset allowedSet to NSCharacterSet's URLHostAllowedCharacterSet()else if allowedSet = host characters thenset allowedSet to NSCharacterSet's URLPathAllowedCharacterSet()else if allowedSet = path characters thenset allowedSet to (NSCharacterSet's characterSetWithCharactersInString:allowedChars)'s invertedSet()if allowedChars is not missing value thenon percent encode theString encoded set allowedSet : path characters encoded characters allowedChars : missing valueend common prefix ofreturn (theString's commonPrefixWithString:otherString options:((not matchCase) as integer)) as texton common prefix of origString with string otherString match case matchCase : falseend escape for regexreturn (NSRegularExpression's escapedPatternForString:theString) as textif isTemplate then return (NSRegularExpression's escapedTemplateForString:theString) as texton escape for regex theString template style isTemplate : falseend regex splitreturn (theMatches as list)set theMatches to tempString's componentsSeparatedByString:theSentinalset tempString to theRegex's stringByReplacingMatchesInString:theString options:0 range:{0, theString's |length|()} withTemplate:theSentinalset theString to NSString's stringWithString:origStringon regex split origString search pattern thePattern match case matchCase : false dot matches all dotMatchesAll : false anchors match lines anchorsMatchLines : true Unicode boundaries unicodeBoundaries : falseend regex batchreturn resultArray's firstObject() as textif isList then return resultArray as list(theRegex's replaceMatchesInString:aString options:0 range:{0, aString's |length|()} withTemplate:(item 2 of aPair))repeat with aString in resultArrayset {theRegex, theError} to (NSRegularExpression's regularExpressionWithPattern:(item 1 of aPair) options:theOpts |error|:(reference))repeat with aPair in changePairs(resultArray's addObject:(aString's mutableCopy()))repeat with aString in theStringOrListset isList to trueset theStringOrList to NSArray's arrayWithArray:theStringOrListset isList to falseset theStringOrList to NSArray's arrayWithObject:theStringOrListif theStringOrList's class is not list thenon regex batch theStringOrList change pairs changePairs match case matchCase : false dot matches all dotMatchesAll : false anchors match lines anchorsMatchLines : true Unicode boundaries unicodeBoundaries : falseend regex changereturn (theRegex's stringByReplacingMatchesInString:theString options:0 range:{0, theString's |length|()} withTemplate:replaceTemplate) as textset theString to NSString's stringWithString:theStringOrListreturn resultArray as list(resultArray's addObject:(theRegex's stringByReplacingMatchesInString:aString options:0 range:{0, aString's |length|()} withTemplate:replaceTemplate))repeat with aString in stringArrayset resultArray to NSMutableArray's array()set stringArray to NSArray's arrayWithArray:theStringOrListif theStringOrList's class is list thenon regex change theStringOrList search pattern thePattern match case matchCase : false dot matches all dotMatchesAll : false anchors match lines anchorsMatchLines : true Unicode boundaries unicodeBoundaries : false replace template replaceTemplateend buildSublistFrom:captureGroups:fromMatch:regularExpression:return subList(subList's addObject:oneString)(subList's addObject:"")set replaceTemplate to "$" & aGroupif aGroup > rangeCount - 1 then error "Capture group out of range. Result has " & rangeCount & " capture groups, you asked for " & aGroup & "."repeat with aGroup in captureGroupset end of captureGroup to irepeat with i from 0 to rangeCount - 1if captureGroup is {} thenset subList to NSMutableArray's arrayWithCapacity:rangeCountset rangeCount to theMatch's numberOfRanges()on buildSublistFrom:theString captureGroups:captureGroup fromMatch:theMatch regularExpression:theRegexend resultFrom:captureGroups:fromMatch:replaceTemplate:regularExpression:return (my buildSublistFrom:theString captureGroups:captureGroup fromMatch:theMatch regularExpression:theRegex) as listif class of captureGroup is list thenreturn oneString as textset oneString to (theRegex's replacementStringForResult:theMatch inString:theString |offset|:0 template:replaceTemplate)on resultFrom:theString captureGroups:captureGroup fromMatch:theMatch replaceTemplate:replaceTemplate regularExpression:theRegexend regex search onceset theMatch to theMatches's lastObject()if theMatches's |count|() = 0 then return missing valuereturn my resultFrom:theString captureGroups:captureGroup fromMatch:theMatch replaceTemplate:replaceTemplate regularExpression:theRegexif theMatch is missing value then return missing valueset theMatch to theRegex's firstMatchInString:theString options:0 range:{0, theString's |length|()}if not fromBack thenset theString to NSString's stringWithString:theStringon regex search once theString search pattern thePattern match case matchCase : false dot matches all dotMatchesAll : false anchors match lines anchorsMatchLines : true Unicode boundaries unicodeBoundaries : false replace template replaceTemplate : (missing value) capture groups captureGroup : 0 backwards search fromBack : falseend regex searcherror "Capture groups value is not an integer or list."(theList's addObject:subList)set subList to (my buildSublistFrom:theString captureGroups:captureGroup fromMatch:aMatch regularExpression:theRegex)else if class of captureGroup is list thenreturn (theList as list)(theList's addObject:oneString)(theList's addObject:"")if oneString is missing value thenset oneString to (theRegex's replacementStringForResult:aMatch inString:theString |offset|:0 template:replaceTemplate)repeat with aMatch in theMatchesset theList to NSMutableArray's arrayWithCapacity:matchCountif matchCount = 0 then return {}set matchCount to theMatches's |count|()set theMatches to theRegex's matchesInString:theString options:0 range:{0, theString's |length|()}return (tempList's subarrayWithRange:{1, (tempList's |count|()) - 2}) as listset tempList to (theString's componentsSeparatedByString:theSentinal)theString's replaceOccurrencesOfString:tempRegex withString:theSentinal options:1024 range:{0, theString's |length|()} -- options is NSRegularExpressionSearchset tempRegex to theSentinal & "(?s).*?" & theSentinaltheString's appendString:theSentinaltheString's insertString:theSentinal atIndex:0if matchCount is 0 then return {} -- no matches, so returnset matchCount to (theRegex's replaceMatchesInString:theString options:0 range:{0, theString's |length|()} withTemplate:theReplace)set theReplace to theSentinal & replaceTemplate & theSentinalif useSentinal thenif replaceTemplate is not missing value thenif replaceTemplate is missing value and class of captureGroup is integer then set replaceTemplate to "$" & captureGroup -- make template of capture groupset theString to NSMutableString's stringWithString:theStringif theRegex = missing value then error theError's localizedDescription() as textset {theRegex, theError} to NSRegularExpression's regularExpressionWithPattern:thePattern options:theOpts |error|:(reference)if unicodeBoundaries then set theOpts to theOpts + 64if anchorsMatchLines then set theOpts to theOpts + 16if dotMatchesAll then set theOpts to theOpts + 8set theOpts to (not matchCase) as integeron regex search theString search pattern thePattern match case matchCase : false dot matches all dotMatchesAll : false anchors match lines anchorsMatchLines : true Unicode boundaries unicodeBoundaries : false replace template replaceTemplate : (missing value) capture groups captureGroup : 0 using sentinal useSentinal : trueend join stringsset theString to theList as textset {saveTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {joinerString}}on join strings theList using delimiter joinerStringend split stringset {saveTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, splitters}on split string theString using delimiters splittersend titlecase fromreturn (theList's valueForKey:"capitalizedString") as listreturn (theList's valueForKey:"localizedCapitalizedString") as listreturn (theString's capitalizedString()) as textreturn (theString's localizedCapitalizedString()) as texton titlecase from theValue using locale localizing : falseend uppercase fromreturn (theList's valueForKey:"uppercaseString") as listreturn (theList's valueForKey:"localizedUppercaseString") as listreturn (theString's uppercaseString()) as textreturn (theString's localizedUppercaseString()) as texton uppercase from theValue using locale localizing : falseend lowercase fromerror "Value is not a string or list."return (theList's valueForKey:"lowercaseString") as listreturn (theList's valueForKey:"localizedLowercaseString") as listset theList to NSArray's arrayWithArray:theValueelse if class of theValue is list thenreturn (theString's lowercaseString()) as textreturn (theString's localizedLowercaseString()) as textif localizing thenset theString to NSString's stringWithString:theValueif class of theValue is text thenon lowercase from theValue using locale localizing : falseproperty theSentinal : "ʬߓชი" -- used as a marker to split and join listsproperty NSLocale : a reference to current application's NSLocaleproperty NSRegularExpression : a reference to current application's NSRegularExpressionproperty NSMutableString : a reference to current application's NSMutableStringproperty NSCharacterSet : a reference to current application's NSCharacterSetuse AppleScript version "2.4" -- macOS 10.10 or laterend accessDefaultsreturn theDefaultsif theDefaults is missing value then error "The 'prepare storage' command has not yet been called by this script"on accessDefaults()end assign defaultserror "The 'assign defaults' command failed, with the error: " & errMessageaccessDefaults()'s registerDefaults:defaultsRecordif class of defaultsRecord is not record then error "The 'assign defaults' command requires a record as its direct parameter" to recordon assign defaults defaultsRecordend remove value for keyaccessDefaults()'s removeObjectForKey:theKeyif class of theKey is not text then error "The 'remove value for key' command requires a string for its direct parameter" to texton remove value for key theKeyend alias for keyreturn theAliasset theAlias to theURL as aliasif theURL is missing value then return missing valueset theURL to |NSURL|'s URLByResolvingBookmarkData:theData options:0 relativeToURL:(missing value) bookmarkDataIsStale:(missing value) |error|:(missing value)if theData is missing value then return missing valueset theData to accessDefaults()'s dataForKey:theKeyif class of theKey is not text then error "The 'alias for key' command requires a string for its direct parameter" to texton alias for key theKeyend assign aliaserror "The 'assign alias' command failed, with the error: " & errMessageaccessDefaults()'s setObject:theBookmark forKey:theKeyif theBookmark = missing value then error "The 'assign alias' command was unable to create a bookmark for the file"set theBookmark to theURL's bookmarkDataWithOptions:0 includingResourceValuesForKeys:{} relativeToURL:(missing value) |error|:(missing value)if theURL = missing value then error "The 'assign alias' command was passed an invalid alias"if class of theKey is not text then error "The 'assign alias' command requires a string for its 'key' parameter" to texton assign alias theValue to key theKeyend file for keyset theResult to theResult as «class furl»set theResult to accessDefaults()'s URLForKey:theKeyif class of theKey is not text then error "The 'file for key' command requires a string for its direct parameter" to texton file for key theKeyend assign fileerror "The 'assign file' command failed, with the error: " & errMessageaccessDefaults()'s setURL:theURL forKey:theKeyif theURL = missing value then error "The 'assign file' command was passed an invalid file"set theURL to |NSURL|'s fileURLWithPath:(POSIX path of theValue)if class of theKey is not text then error "The 'assign file' command requires a string for its 'key' parameter" to texton assign file theValue to key theKeyend value for keyreturn item 1 of ((current application's NSArray's arrayWithObject:theResult) as list)if theResult is missing value then return missing valueset theResult to accessDefaults()'s objectForKey:theKeyif class of theKey is not text then error "The 'value for key' command requires a string for its direct parameter" to texton value for key theKeyend assign valueerror "The 'assign value' command failed, with the error: " & errMessageaccessDefaults()'s setObject:theValue forKey:theKeyif class of theKey is not text then error "The 'assign value' command requires a string for its 'key' parameter" to texton assign value theValue to key theKeyend prepare storageerror "The 'prepare storage' command failed to assign defaults, with the error: " & errMessageon error errMessagetheDefaults's registerDefaults:defaultsRecordif defaultsRecord is not missing value thenif lockFile then (current application's NSFileManager's defaultManager()'s setAttributes:{NSFilePosixPermissions:292} ofItemAtPath:(POSIX path of theFile & "/Contents/Resources/Scripts/main.scpt") |error|:(missing value)) -- the equivalent of -r--r--r--set theResult to NSUserDefaults's alloc()'s initWithSuiteName:newIDif newID = missing value then error "The file passed to the 'prepare storage' command does not have a bundle ID"set newID to infoDict's objectForKey:"CFBundleIdentifier"if infoDict = missing value then error "The file passed to the 'prepare storage' command is not a valid applet or script bundle"set infoDict to current application's NSPropertyListSerialization's propertyListWithData:theData options:0 format:(missing value) |error|:(missing value)if theData = missing value then error "The file passed to the 'prepare storage' command is not a valid applet or script bundle"set theData to current application's NSData's dataWithContentsOfURL:(bundleURL's URLByAppendingPathComponent:"Contents/Info.plist")else -- being run by editorset my theDefaults to NSUserDefaults's standardUserDefaults()if (current application's NSRunningApplication's currentApplication()'s bundleURL()'s isEqual:bundleURL) as boolean then -- must be running as appletset bundleURL to |NSURL|'s fileURLWithPath:(POSIX path of theFile)set my theDefaults to theResultif theResult = missing value then error "The 'prepare storage' command was unable to initialize user defaults. Unknown error"set theResult to NSUserDefaults's alloc()'s initWithSuiteName:domainStringif domainString is missing value then error "The 'prepare storage' command requires either a 'for' or 'for domain' parameter"if theFile is missing value thenif defaultsRecord is not missing value and class of defaultsRecord is not record then error "The 'prepare storage' command requires a record for the 'default values' parameter" to recordon prepare storage for theFile : missing value for domain domainString : missing value default values defaultsRecord : missing value write lock lockFile : trueproperty theDefaults : missing valueproperty NSUserDefaults : a reference to current application's NSUserDefaultsuse AppleScript version "2.5" -- 10.11 or laterset theTable to «event !©Mt!©Td» {{1.0, "One" & return & "two", 1.1}, {2.0, "Two", 2.2}, {3.0, "Three" & linefeed & "four" & linefeed & "five", 3.3}, {4.0, "Four", 4.4}, {5.0, "Five", 5.5}} with «class !©El» given «class !©Ch»:{"Reals", "Text", "Reals"}, «class !©Ec»:{2}, «class prmp»:"Note the different column formatting here"set theTable to «event !©Mt!©Td» {{1.0, "One", 1.1}, {2.0, "Two", 2.2}, {3.0, "Three", 3.3}, {4.0, "Four", 4.4}, {5.0, "Five", 5.5}} given «class !©Ch»:{"Reals", "Text", "Reals"}, «class prmp»:"Note the different column formatting here"«event !©Mt!©Mc» theTable given «class !©Cl»:{1}, «class !©Ss»:«constant !©So!©No»set theTable to «event !©Mt!©Td» theColors with «class !©Rn» given «class prmp»:"You can reorder the colors by dragging them up or down, and this time sorting is disabled", «class !©Rt»:{"", missing value}, «class !©Ch»:{"Rainbow"}«event !©Mt!©Mc» theTable given «class !©Cl»:{1}, «class !©Sc»:2set theTable to «event !©Mt!©Td» theColors with «class !©Rn» given «class prmp»:"You can reorder the colors by dragging them up or down, and sorting will return them to the correct order", «class !©Rt»:{"", missing value}, «class !©Ch»:{"Rainbow"}set theColors to {{"Red", 1}, {"Orange", 2}, {"Yellow", 3}, {"Green", 4}, {"Blue", 5}, {"Indigo", 6}, {"Violet", 7}}«event !©Mt!©Mc» theTable given «class !©Cl»:{2}, «class !©Sc»:3set theTable to «event !©Mt!©Td» {{true, "One", 1}, {false, "Two", 2}, {true, "Three", 3}, {false, "Four", 4}, {true, "Five", 5}} given «class !©Ch»:{"", "Number"}, «class !©Rt»:{true, "", missing value}, «class prmp»:"Note how clicking on the heading sorts using the hidden number column, not alphabetically"«event !©Mt!©Tm» theTable given «class !©Gs»:«constant !©GS!©gV», «class !©Cw»:{1, 2, 1, 2}set theTable to «event !©Mt!©Td» {{1, "One", 100, "One hundred"}, {2, "Two", 200, "Two hundred"}, {3, "Three", 300, "Three hundred"}, {4, "Four", 400, "Four hundred"}, {5, "Five", 400, "Five hundred"}} with «class !©Rn» given «class !©Ch»:{"No", "Text", "No", "Text"}, «class prmp»:"Note the matching column widths"«event !©Mt!©Tm» theTable with «class !©Rd»set theTable to «event !©Mt!©Td» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} with «class !©Rn» given «class prmp»:"You can reorder rows by dragging them up or down"«event !©Mt!©Tm» theTable with «class !©Ab» given «class !©Gs»:«constant !©GS!©gV», «class !©Hr»:{1, 2}set theTable to «event !©Mt!©Td» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} with «class !©Rn» given «class prmp»:"Note the rules between columns, highlighted rows and alternate background shading"«event !©Mt!©Tm» theTable given «class okbt»:"Continue", «class cnbt»:"Stop"set theTable to «event !©Mt!©Td» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} with «class !©Rn» given «class prmp»:"Note the new button titles"«event !©Mt!©dT» {{"One", "One", true}, {"Two", "One" & return & "two", true}, {"Three", "One" & return & "two" & return & "three", true}, {"Four", "One" & return & "two" & return & "three" & return & "four", true}, {"Five", "One" & linefeed & "two" & linefeed & "three" & linefeed & "four" & linefeed & "five", false}} with «class !©El» given «class prmp»:"This table allows multiple lines within cells"«event !©Mt!©dT» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} with «class !©Rn» given «class prmp»:"This table has row numbers"«event !©Mt!©dT» {{"One", true, "One"}, {"Two", false, "Two"}, {"Three", true, "Three"}, {"Four", false, "Four"}, {"Five", true, "Five"}} given «class !©Ec»:{1, 2}, «class !©Ch»:{"Number", "", "Match"}, «class !©Rt»:{"", true, {2, {"One", "Two", "Three"}}}, «class prmp»:"Everything here is editable — combo boxes are always editable"«event !©Mt!©dT» {{"One", true, "One"}, {"Two", false, "Two"}, {"Three", true, "Three"}, {"Four", false, "Four"}, {"Five", true, "Five"}} given «class !©Ec»:{1, 2}, «class !©Ch»:{"Number", "", "Match"}, «class !©Rt»:{"", true, {1, {"One", "Two", "Three"}}}, «class prmp»:"Everything here is editable — popups are always editable"«event !©Mt!©dT» {{missing value, "One"}, {false, "Two"}, {missing value, "Three"}, {missing value, "Four"}, {true, "Five"}} given «class !©Ec»:{1}, «class !©Rt»:{boolean, text}, «class prmp»:"You can edit the checkboxes — some are in mixed-state mode"«event !©Mt!©dT» {{missing value, "One"}, {false, "Two"}, {missing value, "Three"}, {missing value, "Four"}, {true, "Five"}} given «class !©Ec»:{1}, «class !©Rt»:{true, ""}, «class prmp»:"You can edit the checkboxes — some are in mixed-state mode"«event !©Mt!©dT» {{true, "One", 1}, {false, "Two", 2}, {true, "Three", 3}, {false, "Four", 4}, {true, "Five", 5}} with «class !©Ad» given «class !©Ec»:{}, «class prmp»:"You can insert/add/delete and edit every cell"«event !©Mt!©dT» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} given «class !©Ec»:{1}, «class !©Ch»:{"", "Number"}, «class prmp»:"These columns have headings"«event !©Mt!©dT» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} with «class empL» given «class !©Ec»:{1}, «class prmp»:"These checkboxes can be clicked"«event !©Mt!©dT» {{true, "One"}, {false, "Two"}, {true, "Three"}, {false, "Four"}, {true, "Five"}} given «class prmp»:"This shows checkboxes, but they can't be clicked"«event !©Mt!©dT» {someDate, someDate + 1 * days, someDate + 2 * days, someDate + 3 * days, someDate + 4 * days} given «class prmp»:"Pick a date"set someDate to current date«event !©Mt!©dT» {1.0, 2, 3, 4, 5} given «class prmp»:"Pick a real"«event !©Mt!©dT» {1.1, 2.2, 3.3, 4.4, 5.5} given «class prmp»:"Pick a real"«event !©Mt!©dT» {1, 2, 3, 4, 5} given «class prmp»:"Pick an integer"«event !©Mt!©dT» {"One", "Two", "Three", "Four", "Five"} with «class mlsl» and «class empL» given «class appr»:"Simple table", «class prmp»:"Pick several, or none at all"«event !©Mt!©dT» {"One", "Two", "Three", "Four", "Five"}«event !©Mt!©Tm» theTable with «class !©Ab» given «class !©Ip»:theBoundsset theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} with «class !©Ok» and «class empL» given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"This table's size and position should match those used last time"set theBounds to «class !©Fp» of theResultset theResult to «event !©Mt!©Sd» theTable«event !©Mt!©Tm» theTable with «class !©Ab»set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} with «class !©Ok» and «class empL» given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"Move and resize this dialog before clicking OK"«event !©Mt!©Tm» theTable with «class !©Ab» given «class !©Ip»:{100, 10, 400, 400}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} with «class !©Ok» and «class empL» given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"This table's size and position have been set in the script"«event !©Mt!©Tm» theTable with «class !©Ab» given «class !©Ip»:{0, 0}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} with «class !©Ok» and «class empL» given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"This table appears at the top-left of the screen"«event !©Mt!©dT» {"One", "Two", "Three", "Four", "Five"} with «class !©Ok» and «class empL» given «class appr»:"Simple table", «class prmp»:"You can double-click an entry rather than selecting and pressing OK"«event !©Mt!©Mc» theTable with «class !©Bt» given «class !©Cl»:{2}«event !©Mt!©Mc» theTable with «class !©Mo» and «class !©Re» given «class !©Cl»:{1, 2, 3, 4}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1, "One"}, {-2.0, 2, 2.2, 2, "Three" & linefeed & "four" & linefeed & "five"}, {3.11, -3, 3.11, 3, "Two"}, {4.0, 4, -4.41, 4, "Seven"}, {5.0, 5, 5.55, -5, "Three" & linefeed & "four" & linefeed & "five"}} with «class !©El» given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers", "Text"}, «class prmp»:"This table combines the new features in version 1.0.6"«event !©Mt!©Mc» theTable with «class !©Mo» given «class !©Cl»:{}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"Note the monospaced digits if you are running macOS 10.11 or a later version"«event !©Mt!©Mc» theTable with «class !©Bt» given «class !©Cl»:{1}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"Note the bold first column"«event !©Mt!©Mc» theTable with «class !©Re» given «class !©Cl»:{}set theTable to «event !©Mt!©Td» {{1.0, 1, 1.11, 1}, {-2.0, 2, 2.2, 2}, {3.11, -3, 3.11, 3}, {4.0, 4, -4.41, 4}, {5.0, 5, 5.55, -5}} given «class !©Ch»:{"Reals", "Integers", "Reals", "Integers"}, «class prmp»:"Note the appearance of negative values"«event !©Mt!©Tm» theTable with «class !©Cb» and «class !©Ab»«event !©Mt!©Mc» theTable given «class !©Cl»:{2}, «class !©Ea»:«constant !©Am!©Ac»«event !©Mt!©Mc» theTable given «class !©Ha»:«constant !©Am!©Ac», «class !©Rf»:"#,##0.000;-#,##0.000"set theTable to «event !©Mt!©Td» {{1.0, "One" & return & "two", 1.1}, {2.1, "Two", 2.2}, {3.0, "Three" & linefeed & "four" & linefeed & "five", 3.3}, {4.0, "Four", 4.4}, {5.0, "Five", 5.5}} with «class !©El» given «class !©Ch»:{"Reals", "Text", "Reals"}, «class !©Ec»:{2}, «class prmp»:"Note the multiple-line entries"«event !©Mt!©Tm» myTable given «class !©Gs»:«constant !©GS!©g+»set myTable to «event !©Mt!©Td» someData with «class mlsl», «class !©Rn» and «class empL» given «class appr»:"Sample table", «class !©Ch»:theHeads, «class prmp»:"You can select multiple rows. Everything is editable. Uses a row template. The Password field’s values are hidden.", «class !©Ec»:{}, «class !©Rt»:{"", "", "hidden", 1}{"Annika", "Melander", "", 6}}{"John", "Lundqvist", "", 5}, ¬{"Claes", "Sandberg", "", 4}, ¬{"Freddie", "Holst", "", 3}, ¬{"Rasmus", "Larsson", "", 2}, ¬set someData to {{"Saga", "Norén", "password", 1}, ¬set theHeads to {"First Name", "Last Name", "Password", "Index"}«event !©Mt!©Mc» myTable given «class !©Du»:{«constant !©Ud!©Uf», «constant !©Ud!©Uf»}, «class !©Ea»:«constant !©Am!©Ac»set myTable to «event !©Mt!©Td» someData with «class mlsl», «class !©Ad», «class !©Rn» and «class empL» given «class appr»:"Sample table", «class !©Ch»:theHeads, «class prmp»:"In this table the date formatting is based on the user's settings in System Preferences.", «class !©Is»:{2}, «class !©Ec»:{}«event !©Mt!©Mc» myTable given «class !©Df»:"MMMM d, yyyy", «class !©Ea»:«constant !©Am!©Ac»«event !©Mt!©Tm» myTable with «class !©Rd» given «class !©Eb»:"Hmmm…"set myTable to «event !©Mt!©Td» someData with «class mlsl», «class !©Ad», «class !©Rn» and «class empL» given «class appr»:"Sample table", «class !©Ch»:theHeads, «class prmp»:"In this table you can drop files, add and delete rows, and drag rows to reorder them. Note the extra button", «class !©Is»:{2}, «class !©Ec»:{}«event !©Mt!©Tm» myTable given «class !©Hr»:{2, 4}, «class !©Gs»:«constant !©GS!©g+», «class okbt»:"Cool"set myTable to «event !©Mt!©Td» someData with «class mlsl», «class !©Rn» and «class empL» given «class appr»:"Sample table", «class !©Ch»:theHeads, «class prmp»:"You can select multiple rows. Everything is editable. Uses a row template", «class !©Ec»:{}, «class !©Rt»:{"", "", 1, true, 1.0, current date, missing value}{"Annika", "Melander", 6, false, 22.0, theDate + 60000}}{"John", "Lundqvist", 5, true, 13.4567, theDate + 30000}, ¬{"Claes", "Sandberg", 4, false, 1.23456789E+4, theDate + 50000}, ¬{"Freddie", "Holst", 3, false, 9.0, theDate + 40000}, ¬{"Rasmus", "Larsson", 2, true, 13.5, missing value}, ¬set someData to {{"Saga", "Norén", 1, true, 12.0, theDate}, ¬set theHeads to {"First Name", "Last Name", "Index", "Police", "Score", "Some Date"}«event !©Mt!©Sd» myTable with «class !©Sx»«event !©Mt!©Mc» myTable given «class !©Ea»:«constant !©Am!©Ac»set myTable to «event !©Mt!©Td» {{"One", true, 1, "One"}, {"Two", false, 2, "Two"}, {"Three", true, 3, "Three"}, {"Four", false, 4, "Four"}, {"Five", true, 5, "Five"}} with «class !©Rn» given «class !©Ec»:{1, 2, 3}, «class !©Ch»:{"Number", "", "Digit", "Match"}, «class !©Rt»:{text, boolean, integer, {«class comB», {"One", "Two", "Three"}}}, «class appr»:"Sample table", «class prmp»:"This table has centered entries, and returns an extended table reply"«event !©Mt!©dT» {{"One", true, 1, "One"}, {"Two", false, 2, "Two"}, {"Three", true, 3, "Three"}, {"Four", false, 4, "Four"}, {"Five", true, 5, "Five"}} with «class !©Rn» given «class !©Ec»:{1, 2, 3}, «class !©Ch»:{"Number", "", "Digit", "Match"}, «class !©Rt»:{"", true, 1, {«class comB», {"One", "Two", "Three"}}}, «class appr»:"Sample table", «class prmp»:"This table has a column with combo boxes"«event !©Mt!©dT» {{"One", true, 1, "One"}, {"Two", false, 2, "Two"}, {"Three", true, 3, "Three"}, {"Four", false, 4, "Four"}, {"Five", true, 5, "Five"}} with «class !©Rn» given «class !©Ec»:{1, 2, 3}, «class !©Ch»:{"Number", "", "Digit", "Match"}, «class !©Rt»:{"", true, 1, {«class !©Pm», {"One", "Two", "Three"}}}, «class appr»:"Sample table", «class prmp»:"This table has a column with popup menus"set theNames to «event !©M1!©cE» 7 given «class !©S1»:«class !©Zv» of theResultset theResult to «event !©Mt!©Sd» myTable«event !©Mt!©Mc» myTable given «class !©Cl»:{4, 6}, «class !©Ha»:«constant !©Am!©Ac»«event !©Mt!©Mc» myTable given «class !©Df»:"d MMM yyyy, H:mm"«event !©Mt!©Tm» myTable with «class !©Ab»set myTable to «event !©Mt!©Td» theData with «class mlsl» given «class !©Ch»:{"Name", "Date Modified", "Date Created", "Size", "Kind", "Locked"}, «class prmp»:"Choose your files"set theData to «event !©M1!©cR» {theNames, theModDates, theCreationDates, theSizes, theKinds, theLocks, theFiles}set theFiles to files of theFolder as alias listset theLocks to locked of files of theFolderset theKinds to kind of files of theFolderset theSizes to size of files of theFolderset theCreationDates to creation date of files of theFolderset theModDates to modification date of files of theFolderset theNames to displayed name of files of theFolderset theFolder to choose folder with prompt "Choose a folder"end buildAccViewWithCheckboxtheAccessoryView's addSubview:theCheckboxset my theAccessoryView to current application's NSView's alloc()'s initWithFrame:{{0, 0}, {160, 28}}its setAction:"checkboxClicked:" -- a handler in this scriptits setTitle:"This is a checkbox"on buildAccViewWithCheckbox()display dialog theState as textmy performSelectorOnMainThread:"buildAccViewWithCheckbox" withObject:(missing value) waitUntilDone:truemy buildAccViewWithCheckbox()end checkboxClicked:theAlert's beginSheetModalForWindow:theWindow completionHandler:(missing value)theAlert's setInformativeText:"Now close this sheet"theAlert's setMessageText:"You clicked the checkbox"set theAlert to current application's NSAlert's alloc()'s init()set theWindow to sender's |window|()on checkboxClicked:senderend buildAccessoryViewMainThread:(theAccessoryView's addSubview:aControl)repeat with aControl in theControlsset my theAccessoryView to current application's NSView's alloc()'s initWithFrame:{{0, 0}, {160, 60}}on buildAccessoryViewMainThread:theControlsset my thePopup to current application's NSPopUpButton's alloc()'s initWithFrame:{{10, 35}, {150, 26}} pullsDown:falseset {entryList, defaultValue} to theArg as listend createCheckBoxMainThread:its setAction:theAction -- a handler in this scriptits setTarget:meits setTitle:theTitleits setButtonType:(current application's NSSwitchButton)set my theCheckbox to current application's NSButton's alloc()'s initWithFrame:{{10, 10}, {150, 18}}set {theTitle, theAction} to theArg as liston createCheckBoxMainThread:theArgdisplay dialog theValueset thePopup to missing valueset theValue to thePopup's title() as textset theCheckbox to missing value -- to avoid error messages when savingset theState to theCheckbox's state() as boolean«event !©Mt!©Sd» theTableset theAccessoryView to missing value -- to avoid error messages when saving«event !©Mt!©Tm» theTable given «class !©Av»:theAccessoryViewset theTable to «event !©Mt!©Td» {"One", "Two", "Three", "Four", "Five"}my performSelectorOnMainThread:"buildAccessoryViewMainThread:" withObject:{theCheckbox, thePopup} waitUntilDone:truemy performSelectorOnMainThread:"createPopupMainThread:" withObject:{popupList, "Georgina"} waitUntilDone:truemy performSelectorOnMainThread:"createCheckBoxMainThread:" withObject:{"Check me", "checkboxClicked:"} waitUntilDone:truemy buildAccessoryViewMainThread:{theCheckbox, thePopup}my createPopupMainThread:{popupList, "Georgina"}my createCheckBoxMainThread:{"Check me", "checkboxClicked:"}if current application's NSThread's isMainThread() as boolean thenset popupList to {"Fred", "Frieda", "George", "Georgina"}property theAccessoryView : missing valueproperty thePopup : missing valueproperty theCheckbox : missing valueuse script "Myriad Tables Lib" version "1.0.9"end _mdItemFrom:return current application's NSMetadataItem's alloc()'s initWithURL:targetURLset targetURL to current application's |NSURL|'s fileURLWithPath:(POSIX path of fileAliasURLOrPosixPath)set targetURL to tempArray's firstObject()if tempArray's firstObject()'s isKindOfClass:(current application's |NSURL|'s |class|()) thenset tempArray to current application's NSArray's arrayWithObject:fileAliasURLOrPosixPathon _mdItemFrom:fileAliasURLOrPosixPathend _makeASDateFrom:return theASDatetell (current date) to set {theASDate, year, day, its month, day, its hours, its minutes, its seconds} to {it, theYear, 1, theMonth, theDay, theHour, theMinute, theSeconds}using terms from scripting additionsset theSeconds to theComponents's |second|()set theMinute to theComponents's minute()set theHour to theComponents's hour()set theDay to theComponents's |day|()set theMonth to theComponents's |month|()set theYear to theComponents's |year|()set theComponents to theCalendar's components:252 fromDate:theNSDateset theCalendar to current application's NSCalendar's currentCalendar()on _makeASDateFrom:theNSDateend _convertDatesInArray:return mutArray(mutArray's replaceObjectAtIndex:i withObject:(my _convertDatesInDict:thisItem))else if (thisItem's isKindOfClass:(current application's NSDictionary)) as boolean then(mutArray's replaceObjectAtIndex:i withObject:(my _makeASDateFrom:thisItem))if (thisItem's isKindOfClass:(current application's NSDate)) as boolean thenset thisItem to (theArray's objectAtIndex:i)repeat with i from 0 to (theArray's |count|()) - 1set mutArray to theArray's mutableCopy()on _convertDatesInArray:theArrayend _convertDatesInDict:return mutDict(mutDict's setObject:(my _convertDatesInArray:thisValue) forKey:(theKeys's objectAtIndex:i))else if (thisValue's isKindOfClass:(current application's NSArray)) as boolean then(mutDict's setObject:(my _makeASDateFrom:thisValue) forKey:(theKeys's objectAtIndex:i))if (thisValue's isKindOfClass:(current application's NSDate)) as boolean thenset thisValue to (theValues's objectAtIndex:i)repeat with i from 0 to (theValues's |count|()) - 1set theValues to mutDict's objectsForKeys:theKeys notFoundMarker:""set theKeys to mutDict's allKeys()set mutDict to theDict's mutableCopy()on _convertDatesInDict:theDictend convertDatesInList:return (my _convertDatesInArray:theArray) as listset theArray to current application's NSArray's arrayWithArray:theArrayon convertDatesInList:theListend convertDatesInRecord:return (my _convertDatesInDict:theDict) as recordset theDict to current application's NSDictionary's dictionaryWithDictionary:theRecordon convertDatesInRecord:theRecordend metadataScopeConstantsreturn {"kMDQueryScopeHome", "kMDQueryScopeNetwork", "kMDQueryScopeComputer", "kMDQueryScopeAllIndexed", "kMDQueryScopeComputerIndexed", "kMDQueryScopeNetworkIndexed", "See for details"}on metadataScopeConstants()end keysAndValuesForRecord:set theValues to theDict's objectsForKeys:theKeys notFoundMarker:""set theKeys to (theDict's attributes())set theDict to current application's NSDictionary's dictionaryWithDictionary:aRecordon keysAndValuesForRecord:aRecordend searchStringsFromSavedSearch:return {theRawQuery as text, thePred's predicateFormat() as text}set thePred to current application's NSPredicate's predicateFromMetadataQueryString:theRawQueryset theRawQuery to (theDict's valueForKey:"RawQuery")if theDict = missing value then error (theError's localizedDescription() as text)set {theDict, theError} to current application's NSPropertyListSerialization's propertyListWithData:theData options:(current application's NSPropertyListMutableContainersAndLeaves) format:(missing value) |error|:(reference)set theData to the current application's NSData's dataWithContentsOfFile:posixPathif not (posixPath's pathExtension()'s isEqualToString:"savedSearch") as boolean then error "File is not a saved search"set posixPath to current application's NSString's stringWithString:posixPathon searchStringsFromSavedSearch:posixPathend searchIn:searchString:searchArgs:forAttributes:convertDates:if attList = missing value then -- only want the pathstheQuery's setSearchScopes:listOfScopeson searchIn:listOfScopes searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagend searchOnlyIn:searchString:searchArgs:forAttributes:convertDates:namesOnly:return theResults as listif AppleScript's version < "2.5" then set theResults to my _convertDatesInArray:theResultsif datesFlag then(theResults's addObject:resultDict)(resultDict's addEntriesFromDictionary:attDict)set resultDict to tempDict's mutableCopy()set attDict to (aResult's valuesForAttributes:requiredAtts)(tempDict's setObject:theNull forKey:anAtt)repeat with anAtt in requiredAttsset theNull to current application's NSNull's null()set tempDict to current application's NSMutableDictionary's dictionaryWithCapacity:(requiredAtts's |count|())set requiredAtts to requiredAtts's allObjects()requiredAtts's addObject:pathKeyset requiredAtts to (current application's NSMutableSet's setWithArray:attList)else -- just the passed attributes plus path(theResults's addObject:attDict)if ((attDict's objectForKey:pathKey)'s stringByDeletingLastPathComponent()'s isEqualToString:parentPath) as boolean thenset attDict to (aResult's valuesForAttributes:allAtts)set allAtts to (aResult's attributes()'s arrayByAddingObject:pathKey) -- have to add path keyelse if attList = {} then -- want all attributes, including pathreturn (theResults's sortedArrayUsingSelector:"caseInsensitiveCompare:") as listreturn ((theResults's valueForKey:"lastPathComponent")'s sortedArrayUsingSelector:"caseInsensitiveCompare:") as listif namesFlag then(theResults's addObject:thePath)if (thePath's stringByDeletingLastPathComponent()'s isEqualToString:parentPath) as boolean thenset thePath to (aResult's valueForAttribute:pathKey)set aResult to (theQuery's resultAtIndex:i)repeat with i from 0 to theCount - 1if attList = missing value then -- only want the paths or namesset theCount to theQuery's resultCount()theQuery's stopQuery()repeat while theQuery's isGathering() as booleanset pathKey to "kMDItemPath"set theResults to current application's NSMutableArray's array() -- to collect resultstheQuery's startQuery()theQuery's setPredicate:thePredtheQuery's setSearchScopes:{theURL}set theQuery to current application's NSMetadataQuery's new()set thePred to current application's NSPredicate's predicateWithFormat:predString argumentArray:argListset parentPath to theURL's path()set theURL to (current application's |NSURL|'s fileURLWithPath:(POSIX path of fileAliasURLOrPosixPath))if not (theURL's isKindOfClass:(current application's |NSURL|'s |class|())) as boolean thenset theURL to (current application's NSArray's arrayWithObject:fileAliasURLOrPosixPath)'s firstObject()on searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlag namesOnly:namesFlagend searchOnlyIn:searchString:searchArgs:forAttributes:convertDates:my searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlag namesOnly:falseon searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagend searchOnlyIn:searchString:searchArgs:forAttributes:my searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attList convertDates:false namesOnly:falseon searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attListend searchFolders:searchString:searchArgs:forAttributes:convertDates:my searchIn:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagset item i of filesAliasesURLsOrPosixPaths to (current application's |NSURL|'s fileURLWithPath:(POSIX path of item i of filesAliasesURLsOrPosixPaths))repeat with i from 1 to count of filesAliasesURLsOrPosixPathsif theURLs's |count|() > 0 and not (theURLs's firstObject()'s isKindOfClass:(current application's |NSURL|'s |class|())) thenset theURLs to current application's NSArray's arrayWithArray:filesAliasesURLsOrPosixPathson searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagend searchFolders:searchString:searchArgs:forAttributes:my searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:attList convertDates:falseon searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:attListend searchIn:searchString:searchArgs:my searchIn:listOfScopes searchString:predString searchArgs:argList forAttributes:(missing value) convertDates:false namesOnly:falseon searchIn:listOfScopes searchString:predString searchArgs:argListend searchOnlyIn:searchString:searchArgs:namesOnly:my searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:(missing value) convertDates:false namesOnly:namesFlagon searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList namesOnly:namesFlagend searchOnlyIn:searchString:searchArgs:my searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:(missing value) convertDates:false namesOnly:falseon searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argListend searchFolders:searchString:searchArgs:my searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:(missing value)on searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argListend fetchMetadataAllFor:return {theKeys as list, theValues as list, theMetadata as record}on fetchMetadataAllFor:fileAliasURLOrPosixPathend fetchMetadataKeysAndValuesFor:return {theKeys as list, theValues as list}if AppleScript's version < "2.5" then set theValues to my _convertDatesInArray:theValuesset theValues to theMetadata's objectsForKeys:theKeys notFoundMarker:""set theMetadata to mdItem's valuesForAttributes:theKeysset theKeys to (mdItem's attributes())on fetchMetadataKeysAndValuesFor:fileAliasURLOrPosixPathend fetchMetadataKeysFor:return (mdItem's attributes()) as liston fetchMetadataKeysFor:fileAliasURLOrPosixPathend fetchMetadataFor:return theMetadata as recordif AppleScript's version < "2.5" then set theMetadata to my _convertDatesInDict:theMetadataset theMetadata to mdItem's valuesForAttributes:(mdItem's attributes())set mdItem to my _mdItemFrom:fileAliasURLOrPosixPathon fetchMetadataFor:fileAliasURLOrPosixPathend search strings from saved searchreturn my searchStringsFromSavedSearch:posixPathon search strings from saved search posixPathend fetch metadatareturn my fetchMetadataAllFor:fileAliasURLOrPosixPathelse if returnStyle = metadata all thenreturn my fetchMetadataKeysAndValuesFor:fileAliasURLOrPosixPathelse if returnStyle = metadata keys and values thenreturn my fetchMetadataKeysFor:fileAliasURLOrPosixPathelse if returnStyle = metadata keys thenreturn my fetchMetadataFor:fileAliasURLOrPosixPathif returnStyle = metadata record thenon fetch metadata for item fileAliasURLOrPosixPath return style returnStyle : metadata recordend metadata scope stringsreturn {"kMDQueryScopeHome", "kMDQueryScopeNetwork", "kMDQueryScopeComputer", "kMDQueryScopeAllIndexed", "kMDQueryScopeComputerIndexed", "kMDQueryScopeNetworkIndexed"}on metadata scope stringsend perform searcherror "You must specify one of the 'in folders', 'just in' or 'in scope' parameters." from memy searchIn:listOfScopes searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagelse if listOfScopes is not missing value thenmy searchOnlyIn:fileAliasURLOrPosixPath searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlag namesOnly:namesFlagelse if fileAliasURLOrPosixPath is not missing value thenmy searchFolders:filesAliasesURLsOrPosixPaths searchString:predString searchArgs:argList forAttributes:attList convertDates:datesFlagif filesAliasesURLsOrPosixPaths is not missing value thenon perform search predicate string predString in folders filesAliasesURLsOrPosixPaths : missing value just in fileAliasURLOrPosixPath : missing value in scopes listOfScopes : missing value search arguments argList : {} attributes to include attList : missing value converting dates datesFlag : false names only namesFlag : falseuse AppleScript version "2.4" -- 10.10 or laterend change value forif theResult is false then error (theError's |localizedDescription|() as text)error "Invalid date property parameter"set {theResult, theError} to thisURL's setResourceValue:theDate forKey:NSURLAddedToDirectoryDateKey |error|:(reference)else if dateProperty = added property thenset {theResult, theError} to thisURL's setResourceValue:theDate forKey:NSURLCreationDateKey |error|:(reference)else if dateProperty = created property thenset {theResult, theError} to thisURL's setResourceValue:theDate forKey:NSURLContentAccessDateKey |error|:(reference)else if dateProperty = last access property thenset {theResult, theError} to thisURL's setResourceValue:theDate forKey:NSURLContentModificationDateKey |error|:(reference)if dateProperty = modification property thenon change value for theFileOrPathInput to theDate property name dateProperty : modification propertyend date info forif dictFlag then return theResultset theResult to current application's NSDictionary's dictionaryWithObjects:theResult forKeys:{"creation_date", "modification_date", "added_date", "last_access_date"}set theResult to theResult's objectsForKeys:{NSURLCreationDateKey, NSURLContentModificationDateKey, NSURLAddedToDirectoryDateKey, NSURLContentAccessDateKey} notFoundMarker:(current application's NSNull's null())if theResult is missing value then error (theError's |localizedDescription|() as text)set {theResult, theError} to thisURL's resourceValuesForKeys:{NSURLContentModificationDateKey, NSURLCreationDateKey, NSURLAddedToDirectoryDateKey, NSURLContentAccessDateKey} |error|:(reference)on date info for theFileOrPathInput returning dictionary dictFlag : falseend addTags:forItem:set {theResult, theError} to thisURL's setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(reference)set tagList to (current application's NSOrderedSet's orderedSetWithArray:tagList)'s |allObjects|() -- delete any duplicatesset tagList to (theTags as list) & tagListif theTags ≠ missing value then -- make list of old and new tagson addTags:tagList forItem:theFileOrPathInputend setTags:forItem:set {theResult, theError} to thisURL's setResourceValue:tagList forKey:NSURLTagNamesKey |error|:(reference)on setTags:tagList forItem:theFileOrPathInputend returnTagsFor:return theTags as listif theTags = missing value then return {} -- because when there are none, it returns missing valueif theResult as boolean is false then error (theError's |localizedDescription|() as text)set {theResult, theTags, theError} to thisURL's getResourceValue:(reference) forKey:NSURLTagNamesKey |error|:(reference)set thisURL to my makeURLFromFileOrPath:theFileOrPathInput -- make URLon returnTagsFor:theFileOrPathInputend add tagsreturn my addTags:tagList forItem:theFileOrPathInputon add tags tagList to theFileOrPathInputend remove tags fromreturn my setTags:{} forItem:theFileOrPathInputon remove tags from theFileOrPathInputend set tags ofreturn my setTags:tagList forItem:theFileOrPathInputon set tags of tagList to theFileOrPathInputend tags ofreturn my returnTagsFor:theFileOrPathInputon tags of theFileOrPathInputend sortByNameOrExtensionFilesOrPaths:lowToHigh:sortingStyle:resultType:byExtension:return my convertURLs:theResults resultType:resTypetheResults's sortUsingDescriptors:{sortDesc}set sortDesc to NSSortDescriptor's sortDescriptorWithKey:"lastPathComponent" ascending:ascendFlag selector:sortStyletheResults's sortUsingDescriptors:{sortDesc2, sortDesc}set sortDesc to NSSortDescriptor's sortDescriptorWithKey:"lastPathComponent.stringByDeletingPathExtension" ascending:ascendFlag selector:sortStyleset sortDesc2 to NSSortDescriptor's sortDescriptorWithKey:"pathExtension" ascending:ascendFlag selector:sortStyleif extensionFlag then(theResults's addObject:(my makeURLFromFileOrPath:aFile))set theResults to NSMutableArray's arrayWithArray:listOfFilesOrPathsif ((NSArray's arrayWithArray:listOfFilesOrPaths)'s firstObject()'s isKindOfClass:(|NSURL|)) as boolean thenon sortByNameOrExtensionFilesOrPaths:listOfFilesOrPaths lowToHigh:ascendFlag sortingStyle:sortStyle resultType:resType byExtension:extensionFlagend atomicReplaceFromURL:toURL:if not theResult as boolean then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {theResult, theError} to theFileManager's replaceItemAtURL:destinationURL withItemAtURL:tempDestURL backupItemName:(missing value) options:1 resultingItemURL:(missing value) |error|:(reference) -- 1 = NSFileManagerItemReplacementUsingNewMetadataOnlytheFileManager's removeItemAtURL:tempURLDir |error|:(missing value)if not theResult as boolean thenset {theResult, theError} to (theFileManager's copyItemAtURL:sourceURL toURL:tempDestURL |error|:(reference))set tempDestURL to tempURLDir's URLByAppendingPathComponent:(destinationURL's lastPathComponent())if tempURLDir is missing value then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {tempURLDir, theError} to theFileManager's URLForDirectory:99 inDomain:1 appropriateForURL:destinationURL create:true |error|:(reference) -- 1 = NSUserDomainMask, 99 = NSItemReplacementDirectoryon atomicReplaceFromURL:sourceURL toURL:destinationURLend renameWithResultItem:newName:set theResult to my moveFromURL:theSourceURL toURL:theDestURL withReplacing:falseon renameWithResultItem:aFileOrPath newName:proposedNameend moveWithResultItem:intoFolder:withReplacing:newName:withReturnPath:set theResult to my moveFromURL:theSourceURL toURL:theDestURL withReplacing:replaceFlagon moveWithResultItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlag newName:destName withReturnPath:pathFlagend copyWithResultItem:intoFolder:withReplacing:newName:withReturnPath:if theResult then return theDestURL's path() as textset theResult to my copyFromURL:theSourceURL toURL:theDestURL withReplacing:replaceFlagif destName is missing value then set destName to theSourceURL's |lastPathComponent|()on copyWithResultItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlag newName:destName withReturnPath:pathFlagend stringFromRestype:return resTypereturn "paths"return "urls"else if resType = urls array thenreturn "POSIX names"else if resType = POSIX names list thenreturn "names"else if resType = names list thenreturn "files"if resType = files list and AppleScript's version > "2.4" thenon stringFromRestype:resTypeend convertURLs:resultType:return (theURLs's valueForKey:"path") as listreturn theURLs as listelse if resType = "files" and AppleScript's version > "2.4" thenreturn theURLsreturn (theURLs's valueForKey:"lastPathComponent") as listreturn ((((theURLs's valueForKey:"lastPathComponent")'s componentsJoinedByString:(character id 0))'s stringByReplacingOccurrencesOfString:":" withString:"/")'s componentsSeparatedByString:(character id 0)) as liston convertURLs:theURLs resultType:resTypeend foldersInURLArray:if not theValue as boolean thenon foldersInURLArray:theURLsend filesAndPackagesInURLArray:return itemURLs(itemURLs's addObject:aURL)if theValue as boolean then -- is it a package?repeat with aURL in theURLs -- is it a directory?set itemURLs to NSMutableArray's array()on filesAndPackagesInURLArray:theURLsend copyURL:uniquelyToFolderURL:set theDestURL to theDestFolderURL's URLByAppendingPathComponent:proposedNameif i = 1 thenset {theResult, theError} to (theFileManager's copyItemAtURL:theSourceURL toURL:theDestURL |error|:(reference))set theResult to theDestURL's checkResourceIsReachableAndReturnError:(missing value)set theExtension to destName's |pathExtension|()set theDestURL to theDestFolderURL's URLByAppendingPathComponent:destNameon copyURL:theSourceURL uniquelyToFolderURL:theDestFolderURLend moveFromURL:toURL:withReplacing:theFileManager's removeItemAtURL:sourceURL |error|:(missing value)set {theResult, theError} to (theFileManager's moveItemAtURL:sourceURL toURL:destinationURL |error|:(reference))on moveFromURL:sourceURL toURL:destinationURL withReplacing:replaceFlagend copyFromURL:toURL:withReplacing:my atomicReplaceFromURL:sourceURL toURL:destinationURLif not replaceFlag then return falseset {theResult, theError} to (NSFileManager's |defaultManager|()'s copyItemAtURL:sourceURL toURL:destinationURL |error|:(reference))if theResult as boolean is false thenset theResult to destinationURL's checkResourceIsReachableAndReturnError:(missing value)on copyFromURL:sourceURL toURL:destinationURL withReplacing:replaceFlagend makeURLFromFileOrPath:else -- must be a file or aliasreturn theFileOrPathelse if (theFileOrPath's isKindOfClass:(|NSURL|)) as boolean then -- happens with files and aliases in 10.11return |NSURL|'s fileURLWithPath:(POSIX path of theFileOrPathInput)else -- must be HFS pathreturn |NSURL|'s fileURLWithPath:(theFileOrPath's |stringByExpandingTildeInPath|())else if (theFileOrPath's hasPrefix:"~") as boolean then -- POSIX path needing ~ expansionreturn |NSURL|'s fileURLWithPath:theFileOrPathif (theFileOrPath's hasPrefix:"/") as boolean then -- full POSIX pathif (theFileOrPath's isKindOfClass:(NSString)) as boolean thenset theFileOrPath to (NSArray's arrayWithObject:theFileOrPathInput)'s firstObject()on makeURLFromFileOrPath:theFileOrPathInputend sortFilesOrPaths:byProperty:lowToHigh:resultType:return (theResults's valueForKey:NSURLPathKey) as listreturn theResults's valueForKey:"theURLKey"else if resType = "urls" thenreturn (theResults's valueForKey:"theURLKey") as listelse if (resType = "files" and AppleScript's version > "2.4") thenreturn (theResults's valueForKey:NSURLNameKey) as listelse if resType = "POSIX names" thenreturn ((((theResults's valueForKey:NSURLNameKey)'s componentsJoinedByString:(character id 0))'s stringByReplacingOccurrencesOfString:":" withString:"/")'s componentsSeparatedByString:(character id 0)) as listif resType = "names" thentheResults's sortUsingDescriptors:{sortDesc, sortDesc2}set sortDesc2 to NSSortDescriptor's sortDescriptorWithKey:NSURLNameKey ascending:true selector:"caseInsensitiveCompare:"set sortDesc to NSSortDescriptor's sortDescriptorWithKey:chosenProp ascending:ascendFlag selector:"compare:"(theResults's addObject:theValues)(theValues's setObject:theURL forKey:"theURLKey")set theValues to (theURL's resourceValuesForKeys:allProps |error|:(missing value))set theURL to (my makeURLFromFileOrPath:aFile)(theValues's setObject:aFile forKey:"theURLKey")set theValues to theValues's mutableCopy()if includeURLs thenset theValues to (aFile's resourceValuesForKeys:allProps |error|:(missing value))if containsURLs thenrepeat with aFile in listOfFilesOrPathsset theResults to NSMutableArray's array()set includeURLs to (resType = "files" or resType = "urls")set containsURLs to ((NSArray's arrayWithArray:listOfFilesOrPaths)'s firstObject()'s isKindOfClass:(|NSURL|)) as booleanset allProps to {chosenProp, NSURLPathKey, NSURLNameKey}set chosenProp to item i of thePropertiesif theProp begins with item i of theCodes thenrepeat with i from 1 to count of theCodesset chosenProp to NSURLContentModificationDateKey -- defaultset theProperties to {NSURLContentModificationDateKey, NSURLAddedToDirectoryDateKey, NSURLCreationDateKey, NSURLContentAccessDateKey}set theCodes to {"mod", "add", "cre", "las"}on sortFilesOrPaths:listOfFilesOrPaths byProperty:theProp lowToHigh:ascendFlag resultType:resTypeend entireContentsOf:includeInvisibles:includeFiles:includeFolders:resultType:set theURLs to theEnumerator's allObjects()set theEnumerator to NSFileManager's |defaultManager|()'s enumeratorAtURL:theURL includingPropertiesForKeys:{} options:theOptions errorHandler:(missing value)if not incInvis then set theOptions to theOptions + 4 -- NSDirectoryEnumerationSkipsHiddenFilesset theOptions to 2 -- NSDirectoryEnumerationSkipsPackageDescendantson entireContentsOf:aFileOrPath includeInvisibles:incInvis includeFiles:incFiles includeFolders:incFolders resultType:resTypeend contentsOf:includeInvisibles:includeFiles:includeFolders:resultType:return my convertURLs:theURLs resultType:resTypeset theURLs to my foldersInURLArray:theURLselse if not incFiles thenset theURLs to my filesAndPackagesInURLArray:theURLsif not incFolders thenif theURLs is missing value then error (theError's |localizedDescription|() as text)set {theURLs, theError} to NSFileManager's |defaultManager|()'s contentsOfDirectoryAtURL:theURL includingPropertiesForKeys:{} options:theOptions |error|:(reference)if not incInvis then set theOptions to 4 -- NSDirectoryEnumerationSkipsHiddenFilesset theOptions to 0on contentsOf:aFileOrPath includeInvisibles:incInvis includeFiles:incFiles includeFolders:incFolders resultType:resTypeend fileTypeOf:return "file"return "folder"return "package"if (isPackage as boolean) thenon fileTypeOf:aFileOrPathend contentsOf:equalsContentsOf:return (NSFileManager's |defaultManager|()'s contentsEqualAtPath:(theURLA's path()) andPath:(theURLB's path())) as booleanset theURLB to my makeURLFromFileOrPath:fileOrPathBset theURLA to my makeURLFromFileOrPath:fileOrPathAon contentsOf:fileOrPathA equalsContentsOf:fileOrPathBend createHardLink:linkedTo:set {theResult, theError} to NSFileManager's |defaultManager|()'s linkItemAtURL:originalURL toURL:theLinkURL |error|:(reference)if not (volURL's isEqual:(valuesDict's objectForKey:NSURLVolumeURLKey)) as boolean then error "Both items must be on the same volume"if theResult is missing value then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {theResult, volURL, theError} to theLinkURL's URLByDeletingLastPathComponent()'s getResourceValue:(reference) forKey:(NSURLVolumeURLKey) |error|:(reference)if not ((valuesDict's objectForKey:(current application's NSURLVolumeSupportsHardLinksKey)) as boolean) then error "This volume does not support hard links"if valuesDict is missing value then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {valuesDict, theError} to originalURL's resourceValuesForKeys:{current application's NSURLVolumeSupportsHardLinksKey, NSURLVolumeURLKey} |error|:(reference)on createHardLink:aFileOrPath linkedTo:originalFileOrPathend resolveSymlinksIn:return theLinkURL's |URLByResolvingSymlinksInPath|()'s path() as textif not (theValue as boolean) then error "This volume does not support symbolic links"set {theResult, theValue, theError} to theLinkURL's getResourceValue:(reference) forKey:(current application's NSURLVolumeSupportsSymbolicLinksKey) |error|:(reference)on resolveSymlinksIn:aFileOrPathend createSymlink:pointingTo:set {theResult, theError} to NSFileManager's |defaultManager|()'s createSymbolicLinkAtURL:theLinkURL withDestinationURL:originalURL |error|:(reference)set theLinkURL to my makeURLFromFileOrPath:aFileOrPathon createSymlink:aFileOrPath pointingTo:originalFileOrPathend originalFromAlias:asFile:return thePath as textreturn originalURL as «class furl»set originalURL to |NSURL|'s fileURLWithPath:thePathif fileFlag and AppleScript's version > "2.4" thenconsidering numeric stringsset thePath to theDict's objectForKey:(NSURLPathKey)set theDict to |NSURL|'s resourceValuesForKeys:{NSURLPathKey} fromBookmarkData:theDataset {theData, theError} to |NSURL|'s bookmarkDataWithContentsOfURL:theAliasURL |error|:(reference)on originalFromAlias:aFileOrPath asFile:fileFlagend createAlias:pointingTo:set {theResult, theError} to |NSURL|'s writeBookmarkData:theData toURL:theAliasURL options:0 |error|:(reference)if theData is missing value then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {theData, theError} to originalURL's bookmarkDataWithOptions:1024 includingResourceValuesForKeys:(missing value) relativeToURL:(missing value) |error|:(reference) -- 1024 = NSURLBookmarkCreationSuitableForBookmarkFileset originalURL to my makeURLFromFileOrPath:originalFileOrPathset theAliasURL to my makeURLFromFileOrPath:aFileOrPathon createAlias:aFileOrPath pointingTo:originalFileOrPathend createFolderNamed:inFolder:set {theResult, theError} to theFileManager's createDirectoryAtURL:theDestURL withIntermediateDirectories:true attributes:(missing value) |error|:(reference)if (proposedName's rangeOfString:":")'s |length|() > 0 then error "Folder names cannot include the character '/'."on createFolderNamed:proposedName inFolder:folderOrPathend createFolder:return theFolderURL's path() as textset {theResult, theError} to theFileManager's createDirectoryAtURL:theFolderURL withIntermediateDirectories:true attributes:(missing value) |error|:(reference)on createFolder:folderOrPathend moveItem:uniquelyToFolder:return theDestURL's path() as texterror (theError's |localizedDescription|() as text) number (theError's code() as integer)else -- an error other than file already exists, so return errorset theDestURL to theFolderURL's URLByAppendingPathComponent:proposedNameset proposedName to (destNameLessExt's stringByAppendingString:(copyString & space & i))'s stringByAppendingPathExtension:theExtensionset proposedName to (destNameLessExt's stringByAppendingString:copyString)'s stringByAppendingPathExtension:theExtensionif i = 0 thenif theError's code() as integer = 516 then -- 516 = NSFileWriteFileExistsError; it already exists, so change nameif theResult as boolean then exit repeatset {theResult, theError} to (theFileManager's moveItemAtURL:theSourceURL toURL:theDestURL |error|:(reference))set theExtension to theSourceURL's |pathExtension|()set destNameLessExt to destName's |stringByDeletingPathExtension|()on moveItem:aFileOrPath uniquelyToFolder:folderOrPathend moveItem:toMake:withReplacing:on moveItem:aFileOrPath toMake:destFileOrPath withReplacing:replaceFlagend copyItem:uniquelyToFolder:set theDestFolderURL to my makeURLFromFileOrPath:folderOrPathon copyItem:aFileOrPath uniquelyToFolder:folderOrPathend copyItem:toMake:withReplacing:set theDestURL to my makeURLFromFileOrPath:destFileOrPathon copyItem:aFileOrPath toMake:destFileOrPath withReplacing:replaceFlagend trashItem:return destURL's path() as textset {theResult, destURL, theError} to theFileManager's trashItemAtURL:theSourceURL resultingItemURL:(reference) |error|:(reference)on trashItem:aFileOrPathend deleteItem:on deleteItem:aFileOrPathend deleteFile:if not (theResult as boolean) then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {theResult, theError} to theFileManager's removeItemAtURL:theSourceURL |error|:(reference)set theFileManager to NSFileManager's |defaultManager|()if not (isPackage as boolean) then error "Item is a directory, not a file" number -10000set {theResult, isPackage, theError} to theSourceURL's getResourceValue:(reference) forKey:(NSURLIsPackageKey) |error|:(reference)if isDirectory as boolean thenif not (theResult as boolean) then error (theError's |localizedDescription|() as text)set {theResult, isDirectory, theError} to theSourceURL's getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(reference)on deleteFile:aFileOrPathend renameItem:newName:my moveFromURL:theSourceURL toURL:theDestURL withReplacing:falseset theDestURL to theSourceURL's |URLByDeletingLastPathComponent|()'s URLByAppendingPathComponent:proposedNameset proposedName to proposedName's stringByReplacingOccurrencesOfString:"/" withString:":"if class of proposedName is text then set proposedName to NSString's stringWithString:proposedNameon renameItem:aFileOrPath newName:proposedNameend moveItem:intoFolder:withReplacing:return my moveFromURL:theSourceURL toURL:theDestURL withReplacing:replaceFlagon moveItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlagend copyItem:intoFolder:withReplacing:return my copyFromURL:theSourceURL toURL:theDestURL withReplacing:replaceFlagset theDestURL to theFolderURL's URLByAppendingPathComponent:destNameset theFolderURL to my makeURLFromFileOrPath:folderOrPathset destName to theSourceURL's |lastPathComponent|()on copyItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlagend duplicateItem:return my copyURL:theSourceURL uniquelyToFolderURL:theDestFolderURLset theDestFolderURL to theSourceURL's |URLByDeletingLastPathComponent|()set theSourceURL to my makeURLFromFileOrPath:aFileOrPathon duplicateItem:aFileOrPathend compare objectreturn my contentsOf:fileOrPathA equalsContentsOf:fileOrPathBon compare object fileOrPathA to object fileOrPathBend parse objectreturn {full_name:theName as text, name_extension:theExt as text, name_stub:stubName as text, parent_folder_path:folderPath as text, parent_folder_name:folderName as text, displayed_name:theValue, file_kind:theKind}if theKind is not missing value then set theKind to theKind as textset {theResult, theKind} to (theURL's getResourceValue:(reference) forKey:(current application's NSURLLocalizedTypeDescriptionKey) |error|:(missing value))if theValue is not missing value then set theValue to theValue as textset {theResult, theValue} to (theURL's getResourceValue:(reference) forKey:(current application's NSURLLocalizedNameKey) |error|:(missing value))set stubName to theName's stringByDeletingPathExtension()set theName to theURL's lastPathComponent()set folderName to folderPath's lastPathComponent()set theName to theURL's lastPathComponent()'s stringByReplacingOccurrencesOfString:":" withString:"/"if folderPath does not end with ":" then set folderPath to folderPath & ":"set folderPath to ((POSIX file (folderPath as text)) as text)set folderName to folderPath's lastPathComponent()'s stringByReplacingOccurrencesOfString:":" withString:"/"if useHFS thenset folderPath to theURL's path()'s stringByDeletingLastPathComponent()set theExt to theURL's pathExtension()set theURL to my makeURLFromFileOrPath:aFileOrPathon parse object aFileOrPath HFS results useHFS : falseend object is folderif not theValue as boolean then return trueset {theResult, theValue, theError} to (aURL's getResourceValue:(reference) forKey:NSURLIsPackageKey |error|:(reference))if theValue as boolean thenif theResult as boolean is false then error (theError's |localizedDescription|() as text) number (theError's code() as integer)set {theResult, theValue, theError} to (aURL's getResourceValue:(reference) forKey:NSURLIsDirectoryKey |error|:(reference))on object is folder aFileOrPathend exists objectreturn (aURL's checkResourceIsReachableAndReturnError:(missing value)) as booleanset aURL to my makeURLFromFileOrPath:aFileOrPathon exists object aFileOrPathend objects ofset theResult to (my contentsOf:aFileOrPath includeInvisibles:incInvis includeFiles:incFiles includeFolders:incFolders resultType:resType)set theResult to (my entireContentsOf:aFileOrPath includeInvisibles:incInvis includeFiles:incFiles includeFolders:incFolders resultType:resType)if recurseFlag thenon objects of aFileOrPath searching subfolders recurseFlag : false include invisible items incInvis : false include folders incFolders : true include files incFiles : true result type resType : paths listend sort objectsreturn (my sortFilesOrPaths:listOfFilesOrPaths byProperty:sortProp lowToHigh:ascendFlag resultType:resType)set sortProp to "las"set sortProp to "cre"else if sortProp = created property thenset sortProp to "add"else if sortProp = added property thenset sortProp to "mod"if sortProp = modification property thenreturn (my sortByNameOrExtensionFilesOrPaths:listOfFilesOrPaths lowToHigh:ascendFlag sortingStyle:sortStyle resultType:resType byExtension:(sortProp = extension property))set sortStyle to "compare:"else if sortType = fixed case sensitive thenset sortStyle to "caseInsensitiveCompare:"else if sortType = fixed case insensitive thenset sortStyle to "localizedCaseInsensitiveCompare:"else if sortType = case insensitive thenset sortStyle to "localizedStandardCompare:"else if sortType = Finder like thenset sortStyle to "localizedCompare:"if sortType = case sensitive thenif sortProp = name property or sortProp = extension property thenset resType to my stringFromRestype:resTypeon sort objects listOfFilesOrPaths low to high ascendFlag : true sorted property sortProp : name property sort type sortType : case sensitive result type resType : paths listend create folder atreturn my createFolderNamed:proposedName inFolder:folderOrPathreturn my createFolder:folderOrPathif proposedName is missing value thenon create folder at folderOrPath use name proposedName : missing valueend find original ofreturn my originalFromAlias:aFileOrPath asFile:fileFlagon find original of aFileOrPath returning file fileFlag : falseend create alias toreturn my createAlias:aFileOrPath pointingTo:originalFileOrPathon create alias to originalFileOrPath at aFileOrPathend rename objectreturn my renameItem:aFileOrPath newName:proposedNamereturn my renameWithResultItem:aFileOrPath newName:proposedNameif pathFlag thenon rename object aFileOrPath to name proposedName return path pathFlag : falseend trash objectreturn my trashItem:aFileOrPathon trash object aFileOrPathend remove objectreturn my deleteFile:aFileOrPathreturn my deleteItem:aFileOrPathif foldersFlag thenon remove object aFileOrPath folders included foldersFlag : falseend move objectreturn my moveWithResultItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlag newName:destName withReturnPath:pathFlagon move object aFileOrPath to folder folderOrPath replacing replaceFlag : false new name destName : missing value return path pathFlag : falseend copy objectreturn my copyWithResultItem:aFileOrPath intoFolder:folderOrPath withReplacing:replaceFlag newName:destName withReturnPath:pathFlagon copy object aFileOrPath to folder folderOrPath replacing replaceFlag : false new name destName : missing value return path pathFlag : falseend create duplicate ofreturn my duplicateItem:aFileOrPathon create duplicate of aFileOrPathproperty copyString : " copy" -- added to file names for copies; edit to suit your languageproperty NSURLTagNamesKey : a reference to current application's NSURLTagNamesKeyproperty NSURLPathKey : a reference to current application's NSURLPathKeyproperty NSURLIsPackageKey : a reference to current application's NSURLIsPackageKeyproperty NSFileManager : a reference to current application's NSFileManagerproperty NSURLIsDirectoryKey : a reference to current application's NSURLIsDirectoryKeyproperty NSMutableArray : a reference to current application's NSMutableArrayproperty NSURLContentModificationDateKey : a reference to current application's NSURLContentModificationDateKeyproperty NSSortDescriptor : a reference to current application's NSSortDescriptorproperty NSURLNameKey : a reference to current application's NSURLNameKeyproperty NSURLAddedToDirectoryDateKey : a reference to current application's NSURLAddedToDirectoryDateKeyproperty NSURLCreationDateKey : a reference to current application's NSURLCreationDateKeyproperty NSURLContentAccessDateKey : a reference to current application's NSURLContentAccessDateKeyproperty NSURLVolumeURLKey : a reference to current application's NSURLVolumeURLKeyset {buttonName, controlsResults} to «event !AScDiEw» "Many Buttons" with «class !AvL» given «class !AvW»:accViewWidth, «class !AvH»:theTop, «class !AvC»:{theField, boldLabel}, «class btns»:theButtons, «class !AcF»:theField, «class !AiP»:{0, 0}set {boldLabel, theTop} to «event !ASuCrLa» "How many buttons would you like? There's no real limit except for practical and aesthetic considerations." & return & "Of course, I hope you'll never really think about using something as ugly as this!" & return & return & "Choose your heart out!" & return & return & "Also, try the command-1 thru command-5 button shortcuts." given «class !BtM»:theTop + 20, «class !MxW»:accViewWidth, «class !MuS»:«constant !CsZ!CrL»set {theField, theTop} to «event !ASuCrTf» "" with «class !MlT» given «class !FpL»:"Enter your text here", «class !BtM»:0, «class !FwI»:accViewWidth, «class !ExH»:60set {theButtons, minWidth} to «event !ASc!CbS» {"Cancel", "Five", "Four", "Three", "Two", "One", "OK"} given «class !btK»:{"", "5", "4", "3", "2", "1", ""}, «class dflt»:7, «class cbtn»:1set accViewWidth to 650set {buttonName, controlsResults} to «event !AScDiEw» "Secure field" without «class !AvL» given «class !AvW»:accViewWidth, «class !AvH»:theTop, «class !AvC»:{secureField, secureLabel}, «class btns»:theButtons, «class !AcF»:secureField, «class !AiP»:{0, 0}set {secureLabel, theTop} to «event !ASuCrLa» "This is an example of a secure field:" given «class !BtM»:theTop + 20, «class !MxW»:accViewWidth, «class !MuS»:«constant !CsZ!CrL»set {secureField, theTop} to «event !ASuCrSf» "" given «class !FpL»:"Enter your password", «class !BtM»:10, «class !FwI»:accViewWidthif minWidth > accViewWidth then set accViewWidth to minWidth -- make uttons fitset {theButtons, minWidth} to «event !ASc!CbS» {"Cancel", "OK"} given «class dflt»:2, «class cbtn»:1set accViewWidth to 350set {buttonName, controlsResults} to «event !AScDiEw» "Complex sample" with «class !AvL» given «class !AvW»:accViewWidth, «class !AvH»:theTop, «class !AvC»:allControls, «class btns»:theButtons, «class !AcF»:instructionsFieldset allControls to {instructionsField, instructionsLabel, operatorField, operatorLabel, theRule, thePathControl, pathLabel, theCheckbox, secondCheckbox, colorPopup, popupLabel, jobMatrix, matrixLabel, boldLabel}set {boldLabel, theTop} to «event !ASuCrLa» "This is a large, bold, ugly label and it runs across the top of the dialog, centered and wrapping lines if necessary" with «class !MuB» given «class !BtM»:theTop + 20, «class !MxW»:accViewWidth, «class !MuS»:«constant !CsZ!CrC», «class !AlI»:«constant !LaL!LcE»set {jobMatrix, matrixLabel, theTop, matrixLeft} to «event !ASuCrLm» {"Press 1", "Press 2", "Press 3"} given «class !BtM»:(theTop + 8), «class !MxW»:accViewWidth, «class !MxL»:70, «class !LtX»:"Job is for:", «class !MuD»:"Press 2" --without arranged verticallyset {colorPopup, popupLabel, theTop} to «event !ASuCrPl» {"Red", "Green", "Blue"} given «class !BtM»:(theTop + 8), «class !PuW»:100, «class !MxW»:accViewWidth, «class !LtX»:"Job is for:", «class !PuL»:70, «class !MuD»:2set {secondCheckbox, theTop, newWidth} to «event !ASuCrCb» "Mirror image" with «class !IsT» given «class !BtM»:(theTop + 8), «class !MxW»:accViewWidth / 2 - 8, «class !Lli»:accViewWidth / 2 + 8set {theCheckbox, unusedTop, newWidth} to «event !ASuCrCb» "One side only" given «class !BtM»:(theTop + 8), «class !MxW»:accViewWidth / 2 - 8set {thePathControl, pathLabel, theTop} to «event !ASuCrP+» (POSIX path of (path to documents folder)) given «class !BtM»:(theTop + 12), «class !CwI»:accViewWidth, «class !LtX»:"Choose or drag the file here:"set {theRule, theTop} to «event !ASuCrRu» (theTop + 12) given «class !RwI»:accViewWidthset {operatorField, operatorLabel, theTop, fieldLeft} to «event !ASuCrLs» (short user name of (system info)) given «class !FpL»:"Your name", «class !BtM»:(theTop + 8), «class !StW»:accViewWidth, «class !LtX»:"Operator:", «class !FlF»:0set {instructionsField, instructionsLabel, theTop} to «event !ASuCrLf» "" with «class !MlT» given «class !FpL»:"Extra instructions go here", «class !BtM»:0, «class !FwI»:accViewWidth, «class !ExH»:60, «class !LtX»:"Instructions"set {theButtons, minWidth} to «event !ASc!CbS» {"Cancel", "OK"} given «class dflt»:1, «class btns»:2set {sideChoiceBoolean, chosenColor, unused, operatorName, unused, unused, unused} to controlsResultsset {buttonName, controlsResults} to «event !AScDiEw» "Many Buttons" with «class !AvL» given «class !AvW»:accViewWidth, «class !AvH»:theTop, «class !AvC»:allControls, «class btns»:theButtons, «class !AiP»:{100, 30}, «class givu»:10set allControls to {theCheckbox, colorPopup, popupLabel, operatorField, operatorLabel, boldLabel, messageLabel}set {boldLabel, theTop} to «event !ASuCrLa» "Send for output" with «class !MuB» given «class !BtM»:theTop + 8, «class !MxW»:accViewWidth, «class !MuS»:«constant !CsZ!CrL»set {messageLabel, theTop} to «event !ASuCrLa» "More text goes in here" given «class !BtM»:theTop + 12, «class !MxW»:accViewWidth, «class !MuS»:«constant !CsZ!CsC»set {operatorField, operatorLabel, theTop, fieldLeft} to «event !ASuCrLs» (short user name of (system info)) given «class !FpL»:"Your name", «class !Lli»:0, «class !BtM»:(theTop + 12), «class !StW»:accViewWidth, «class !LtX»:(item 2 of theLabelStrings), «class !FlF»:controlLeftset {colorPopup, popupLabel, theTop} to «event !ASuCrPl» {"Red", "Green", "Blue"} given «class !Lli»:0, «class !BtM»:(theTop + 8), «class !PuW»:100, «class !MxW»:accViewWidth, «class !LtX»:(item 1 of theLabelStrings), «class !PuL»:controlLeft, «class !MuD»:"Green"set {theCheckbox, theTop, newWidth} to «event !ASuCrCb» "One side only" without «class !IsT» given «class !Lli»:controlLeft, «class !BtM»:0, «class !MxW»:accViewWidthif minWidth > accViewWidth then set accViewWidth to minWidth -- make sure buttons fitset {theButtons, minWidth} to «event !ASc!CbS» {"Cancel", "Maybe", "It All Depends", "OK"} with «class !beQ» given «class dflt»:"OK", «class cbtn»:"Cancel"set accViewWidth to 400set {buttonName, suppressedState, controlsResults} to «event !AScDiEa» "Many Buttons" without «class !suP» given «class mesS»:theMessage, «class as A»:«constant !AtP*nfA», «class btns»:{"OK", "Five", "Four", "Three", "Two", "One", "Cancel"}, «class givu»:0, «class !AvW»:650, «class !AvH»:theTop, «class !AvC»:{theField}set {theField, theTop} to «event !ASuCrTf» "" with «class !MlT» given «class !FpL»:"Enter your text here", «class !Lli»:0, «class !BtM»:0, «class !FwI»:650, «class !ExH»:60set theMessage to "How many buttons would you like? There's no real limit except for practical and aesthetic considerations." & return & "Of course, I hope you'll never really think about using something as ugly as this!" & return & return & "Choose your heart out!"set {buttonName, suppressedState, controlsResults} to «event !AScDiEa» "Send for output" without «class !suP» given «class mesS»:"", «class as A»:«constant !AtP*riT», «class btns»:{"Cancel", "OK"}, «class givu»:120, «class !AvW»:400, «class !AvH»:theTop, «class !AvC»:allControlsset allControls to {instructionsField, instructionsLabel, operatorField, operatorLabel, theRule, thePathControl, pathLabel, theCheckbox, colorPopup, popupLabel, jobMatrix, matrixLabel}set {jobMatrix, matrixLabel, theTop, matrixLeft} to «event !ASuCrLm» {"Press 1", "Press 2", "Press 3"} without «class !VeR» given «class !Lli»:0, «class !BtM»:(theTop + 8), «class !MxW»:400, «class !MxL»:0, «class !LtX»:"Job is for:", «class !MuD»:3set {colorPopup, popupLabel, theTop} to «event !ASuCrPl» {"Red", "Green", "Blue"} given «class !Lli»:0, «class !BtM»:(theTop + 8), «class !PuW»:100, «class !MxW»:400, «class !LtX»:"Job is for:", «class !PuL»:150, «class !MuD»:"Green"set {theCheckbox, theTop, newWidth} to «event !ASuCrCb» "One side only" without «class !IsT» given «class !Lli»:0, «class !BtM»:(theTop + 8), «class !MxW»:400set {thePathControl, pathLabel, theTop} to «event !ASuCrP+» (POSIX path of (path to documents folder)) with «class !PoP» given «class !Lli»:0, «class !BtM»:(theTop + 12), «class !CwI»:400, «class !LtX»:"Choose or drag the file here:"set {theRule, theTop} to «event !ASuCrRu» (theTop + 12) given «class !Lli»:0, «class !RwI»:400set {operatorField, operatorLabel, theTop, fieldLeft} to «event !ASuCrLs» (short user name of (system info)) given «class !FpL»:"Your name", «class !Lli»:0, «class !BtM»:(theTop + 8), «class !StW»:400, «class !LtX»:"Operator:", «class !FlF»:0set {instructionsField, instructionsLabel, theTop} to «event !ASuCrLf» "" with «class !MlT» given «class !FpL»:"Extra instructions go here", «class !Lli»:0, «class !BtM»:0, «class !FwI»:400, «class !ExH»:60, «class !LtX»:"Instructions"set {sideChoiceBoolean, chosenColor, unused, operatorName, unused} to controlResultsset {buttonName, suppressedState, controlResults} to «event !AScDiEa» "Send for output" without «class !suP» given «class mesS»:"More text goes in here", «class as A»:«constant !AtP*nfA», «class btns»:{"Cancel", "Maybe", "Perhaps", "OK"}, «class givu»:120, «class !AvW»:400, «class !AvH»:theTop, «class !AvC»:allControlsset allControls to {theCheckbox, colorPopup, popupLabel, operatorField, operatorLabel}set {operatorField, operatorLabel, theTop, fieldLeft} to «event !ASuCrLs» (short user name of (system info)) given «class !FpL»:"Your name", «class !Lli»:0, «class !BtM»:(theTop + 8), «class !StW»:400, «class !LtX»:(item 2 of theLabelStrings), «class !FlF»:controlLeftset {colorPopup, popupLabel, theTop} to «event !ASuCrPl» {"Red", "Green", "Blue"} given «class !Lli»:0, «class !BtM»:(theTop + 8), «class !PuW»:100, «class !MxW»:400, «class !LtX»:(item 1 of theLabelStrings), «class !PuL»:controlLeftset {theCheckbox, theTop, newWidth} to «event !ASuCrCb» "One side only" without «class !IsT» given «class !Lli»:controlLeft, «class !BtM»:0, «class !MxW»:400set maxLabelWidth to «event !ASuMlWd» theLabelStringsset theLabelStrings to {"This job is for:", "Operator's name:"}use script "Dialog Toolkit Plus" version "1.1.0"end control:textView:doCommandBySelector:theTextView's insertTabIgnoringFieldEditor:meelse if theSel = "insertTab:" thentheTextView's insertNewlineIgnoringFieldEditor:meif theSel = "insertNewline:" thenon control:theControl textView:theTextView doCommandBySelector:theSelend closeTheWindow:(NSApp)'s stopModalWithCode:(theButton's tag())on closeTheWindow:theButtonend createButtonsViewMainThread:set my handlerResult to {allButtons, minAccViewWidth}set minAccViewWidth to buttonCount * minButtonWidth(aButton's setFrameSize:{minButtonWidth, buttonHeight})repeat with aButton in allButtonsif equalWidths thenif thisWidth > minButtonWidth then set minButtonWidth to thisWidthset minAccViewWidth to minAccViewWidth + thisWidth(thisButton's setFrameSize:{thisWidth, buttonHeight})set thisWidth to minimumButtonWidthif not equalWidths and thisWidth < minimumButtonWidth thenset buttonHeight to item 2 of item 2 of theFrameset thisWidth to item 1 of item 2 of theFrameset buttonHeight to height of |size| of theFrameset thisWidth to width of |size| of theFrameset theFrame to thisButton's frame()set beginning of allButtons to thisButton(thisButton's setFrameSize:(thisButton's fittingSize()))(thisButton's setKeyEquivalentModifierMask:NSCommandKeyMask)(thisButton's setKeyEquivalent:theKey)set theKey to character 1 of item i of buttonKeysListelse if i ≤ buttonKeysCount and length of item i of buttonKeysList > 0 then -- add shortcut(thisButton's setKeyEquivalent:return)else if i = okIndex or item i of buttonList = okIndex then -- make return/enter the shortcut(thisButton's setTag:NSModalResponseCancel)(thisButton's setKeyEquivalent:(character id 27))if i = cancelIndex or item i of buttonList = cancelIndex then -- make esc the shortcutset asButtonNumber to buttonCount - i + 1(thisButton's setAction:"closeTheWindow:")(thisButton's setTarget:me)(thisButton's setTitle:(item i of buttonList))(thisButton's setTag:i)(thisButton's setImagePosition:NSNoImage)(thisButton's setBezelStyle:NSRoundedBezelStyle)(thisButton's setButtonType:NSMomentaryPushInButton)set thisButton to (NSButton's alloc()'s initWithFrame:{{0, buttonYValue}, {minButtonWidth, 32}})repeat with i from buttonCount to 1 by -1set minAccViewWidth to 0set allButtons to {} -- to hold listset buttonKeysCount to count of buttonKeysListset buttonCount to count of buttonListcopy minimumButtonWidth to minButtonWidthset {buttonList, buttonKeysList, equalWidths, cancelIndex, okIndex} to theArg as liston createButtonsViewMainThread:theArgend createImageViewMainThread:set my handlerResult to {imageView, theBottom + viewHeight}(imageView's setImageScaling:(i - 1))if item i of theScales = imageScale thenrepeat with i from 1 to count of theScalesset theScales to {scale down proportionally, scale to fit, scale none, scale proportionally}(imageView's setImageAlignment:(i - 1))if item i of theAlignments = imageAlignment thenrepeat with i from 1 to count of theAlignmentsset theAlignments to {center aligned, top aligned, top left aligned, top right aligned, left aligned, bottom left aligned, bottom right aligned, right aligned, bottom aligned}imageView's setImage:theImageset imageView to NSImageView's alloc()'s initWithFrame:{{theLeft, theBottom}, {viewWidth, viewHeight}}if theImage is missing value then error "No valid image found at " & posixPathset theImage to NSImage's alloc()'s initWithContentsOfFile:posixPathset {posixPath, theLeft, theBottom, viewWidth, viewHeight, imageScale, imageAlignment} to theArg as liston createImageViewMainThread:theArgend createRuleMainThread:set my handlerResult to {theRule, theBottom + 1}its setBorderType:NSLineBorderits setTitlePosition:NSNoTitleits setBoxType:NSBoxSeparatortell theRuleset theRule to NSBox's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, 1}}set {theBottom, theLeft, theWidth} to theArg as liston createRuleMainThread:theArgend createMatrixMainThread:set my handlerResult to {theMatrix, theBottom + theDepth, newWidth}theMatrix's setFrameSize:{newWidth, theDepth}set newWidth to item 1 of item 2 of theFrameset newWidth to width of |size| of theFrameset theFrame to theMatrix's frame()theMatrix's sizeToCells()theMatrix's setAutosizesCells:truetheMatrix's setAutorecalculatesCellSize:truetheMatrix's setIntercellSpacing:{8, 2}((item i of theCells)'s setFont:theFont)(theMatrix's selectCellAtRow:0 column:(i - 1))(theMatrix's selectCellAtRow:(i - 1) column:0)if item i of listOfNames = defaultValue then((item i of theCells)'s setTitle:(item i of listOfNames))((item i of theCells)'s setButtonType:NSRadioButton)repeat with i from 1 to count of theCellsset theCells to theMatrix's cells() as listtheMatrix's deselectAllCells()set theMatrix to NSMatrix's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, theDepth}} mode:NSRadioModeMatrix cellClass:(NSButtonCell) numberOfRows:rowCount numberOfColumns:colCountset theDepth to rowCount * 18 + (rowCount - 1) * 2 -- 18 pts per button + 2 pts betweenset rowCount to 1set colCount to theCountset colCount to 1set rowCount to theCountif isVertical thenset theCount to count of listOfNamesif class of defaultValue is integer then set defaultValue to item defaultValue of listOfNamesset {listOfNames, theLeft, theBottom, theWidth, isVertical, defaultValue} to theArg as liston createMatrixMainThread:theArgend createPathControlMainThread:set my handlerResult to {thePathControl, theTop}thePathControl's setURL:anNSURLthePathControl's setPathStyle:NSPathStyleStandardset thePathControl to NSPathControl's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, 22}}set theTop to theBottom + 26thePathControl's setPathStyle:NSPathStylePopUpset thePathControl to NSPathControl's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, 26}}if popsUpBool thenset anNSURL to |NSURL|'s fileURLWithPath:thePathset {thePath, theLeft, theBottom, theWidth, popsUpBool} to theArg as liston createPathControlMainThread:theArgend createCheckboxMainThread:set my handlerResult to {theCheckbox, theBottom + 18, theWidth}set theWidth to item 1 of item 2 of theFrameset theWidth to width of |size| of theFrameset theFrame to theCheckbox's frame()theCheckbox's setFrameSize:(theCheckbox's fittingSize())set isMain to NSThread's isMainThread() as booleanits setState:initialStateits setTitle:checkTitleits setButtonType:NSSwitchButtonset theFont to my fontOfControlSize:regular size boldType:falseset theCheckbox to NSButton's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, 18}}set {checkTitle, theLeft, theBottom, theWidth, initialState} to theArg as liston createCheckboxMainThread:theArgend createPopupMainThread:set my handlerResult to {thePopup, theBottom + 26}thePopup's selectItemWithTitle:defaultValuethePopup's addItemsWithTitles:entryListset thePopup to NSPopUpButton's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, 26}} pullsDown:falseset {entryList, theLeft, theBottom, theWidth, defaultValue} to theArg as liston createPopupMainThread:theArgend createSecureFieldMainThread:its setPlaceholderString:placeholderits (cell()'s setWraps:false)set theField to (NSSecureTextField's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, theTop - theBottom}})set theTop to theBottom + 22set {enteredText, placeholder, theLeft, theBottom, theWidth} to theArg as liston createSecureFieldMainThread:theArgend createFieldMainThread:set my handlerResult to {theField, theTop}if acceptsTabs then its setDelegate:meits setStringValue:enteredTextif extraHeight > 0 then its (cell()'s setWraps:true)its (cell()'s setPlaceholderString:placeholder)(its setBezeled:true)(its setEditable:true)tell theFieldset theField to (NSTextField's alloc()'s initWithFrame:{{theLeft, theBottom}, {theWidth, theTop - theBottom}})set theTop to theBottom + 22 + extraHeightset {enteredText, placeholder, theLeft, theBottom, theWidth, extraHeight, acceptsTabs} to theArg as liston createFieldMainThread:theArgend createLabelMainThread:set my handlerResult to {theLabel, theBottom + theHeight, newWidth}theLabel's setFrameOrigin:theOriginset theOrigin to {theLeft, theBottom}set theOrigin to {(theLeft + (maxWidth - newWidth) / 2), theBottom}set theOrigin to {theLeft + maxWidth - newWidth, theBottom}set {newWidth, theHeight} to item 2 of theFrameset {width:newWidth, height:theHeight} to theFrame's |size|set theFrame to theLabel's frame()theLabel's setFrameSize:(theLabel's fittingSize())its (cell()'s setWraps:wrapsBool)(its setDrawsBackground:false)(its setBordered:false)(its setSelectable:true)(its setEditable:false)(its setStringValue:labelString)its setPreferredMaxLayoutWidth:maxWidthits setFont:theFonttell theLabeltheLabel's setAlignment:NSLeftTextAlignmenttheLabel's setAlignment:NSCenterTextAlignmentelse if alignment = center aligned or alignment begins with "c" thentheLabel's setAlignment:NSRightTextAlignmentif alignment = right aligned or alignment begins with "r" thenset theLabel to (NSTextField's alloc()'s initWithFrame:{{theLeft, theBottom}, {maxWidth, 17}})set {labelString, theLeft, theBottom, maxWidth, alignment, wrapsBool, controlSize, boldType} to theArg as liston createLabelMainThread:theArgend showTheWindowAndWaitMainThread:theWindow's orderOut:meNSObject's cancelPreviousPerformRequestsWithTarget:(NSApp) selector:"abortModal" object:(missing value)if giveUp as integer > 0 and returnCode is not NSModalResponseAbort thenset my returnCode to NSApp's runModalForWindow:theWindowNSApp's performSelector:"abortModal" withObject:(missing value) afterDelay:giveUp inModes:{NSModalPanelRunLoopMode}if giveUp as integer > 0 thentheWindow's setTitle:windowTitletheWindow's orderFront:me -- must be visible or it will be centeredtheWindow's setFrame:windowFrame display:trueset item 1 of windowFrame to {item 1 of initPosition, theY - (item 2 of item 2 of windowFrame)}set origin of windowFrame to {item 1 of initPosition, theY - (height of |size| of windowFrame)}if class of windowFrame is record thenset windowFrame to theWindow's frame()set theY to screenHeight - (item 2 of initPosition)set {screenWidth, screenHeight} to item 2 of screenFrameset {width:screenWidth, height:screenHeight} to |size| of screenFrameif class of screenFrame is record thenset screenFrame to NSScreen's mainScreen()'s frame()theWindow's |center|()if initPosition = {} thenset initPosition to initPosition as listif defaultField is not missing value then theWindow's makeFirstResponder:defaultFieldset {theWindow, defaultField, giveUp, initPosition, windowTitle} to theArg as liston showTheWindowAndWaitMainThread:theArgend prepareEnhancedWindowMainThread:set my handlerResult to theWindowtheWindow's setAutorecalculatesKeyViewLoop:truethisContentView's addSubview:theAccessoryViewset theAccessoryView to NSView's alloc()'s initWithFrame:{{accViewSideInset, accViewYValue}, {theWidth, theHeight}}thisContentView's setSubviews:allButtonsset thisContentView to theWindow's contentView()theWindow's setLevel:NSModalPanelWindowLevelset theWindow to NSWindow's alloc()'s initWithContentRect:{{0, 0}, {windowWidth, theHeight + accViewYValue + accViewTopGap}} styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:trueif cancelLeftFlag and (item 1 of allButtons)'s tag() is NSModalResponseCancel then (item 1 of allButtons)'s setFrameOrigin:{buttonSideInset, buttonYValue}(aButton's setFrameOrigin:{buttonLeft, buttonYValue})set buttonLeft to buttonLeft - buttonWidthset buttonWidth to item 1 of item 2 of theFrameset buttonWidth to width of |size| of theFrameset theFrame to aButton's frame()repeat with aButton in (reverse of allButtons)set buttonLeft to windowWidth - buttonSideInsetset windowWidth to theWidth + accViewSideInset * 2set {windowTitle, theWidth, theHeight, controlsList, giveUp, defaultField, initPosition, cancelLeftFlag, allButtons} to theArg as liston prepareEnhancedWindowMainThread:theArgend displayEnhancedAlertMainThread:set my handlerResult to theAlertset my returnCode to theAlert's runModal()if giveUp > 0 then NSApp's performSelector:"abortModal" withObject:(missing value) afterDelay:giveUp inModes:{NSModalPanelRunLoopMode}its (|window|()'s setAutorecalculatesKeyViewLoop:true)its setAccessoryView:theAccessoryViewits setShowsSuppressionButton:showSuppression(its addButtonWithTitle:anEntry)repeat with anEntry in buttonsListits setInformativeText:theExplanationits setMessageText:mainTextits setAlertStyle:styleNumtell theAlertset theAlert to NSAlert's alloc()'s init()set buttonsList to reverse of buttonsListtheAccessoryView's setSubviews:controlsListset theAccessoryView to NSView's alloc()'s initWithFrame:{{0, 0}, {theWidth, theHeight}}set {mainText, theExplanation, styleNum, buttonsList, showSuppression, giveUp, theWidth, theHeight, controlsList} to theArg as liston displayEnhancedAlertMainThread:theArgend fontOfControlSize:boldType:return NSFont's systemFontOfSize:theFontSizereturn NSFont's boldSystemFontOfSize:theFontSizeif boldType thenset theFontSize to 16else if controlSize = large size thenset theFontSize to NSFont's systemFontSizeForControlSize:NSSmallControlSizeelse if controlSize = small size thenset theFontSize to NSFont's systemFontSizeForControlSize:NSMiniControlSizeelse if controlSize = mini size thenset theFontSize to NSFont's systemFontSizeForControlSize:NSRegularControlSizeif controlSize is regular size thenon fontOfControlSize:controlSize boldType:boldTypeend create image viewmy performSelectorOnMainThread:"createImageViewMainThread:" withObject:{posixPath, theLeft, theBottom, viewWidth, viewHeight, imageScale, imageAlignment} waitUntilDone:truemy createImageViewMainThread:{posixPath, theLeft, theBottom, viewWidth, viewHeight, imageScale, imageAlignment}on create image view posixPath left inset theLeft : 0 bottom theBottom view width viewWidth view height viewHeight scale image imageScale : scale down proportionally align image imageAlignment : center alignedend create rulemy performSelectorOnMainThread:"createRuleMainThread:" withObject:{theBottom, theLeft, theWidth} waitUntilDone:truemy createRuleMainThread:{theBottom, theLeft, theWidth}on create rule theBottom left inset theLeft : 0 rule width theWidthend create labeled matrixreturn {theMatrix, theLabel, theTop, matrixLeft}theLabel's setFrame:(current application's NSOffsetRect(theLabel's frame(), 0, theTop - theBottom - 19))set {theMatrix, theTop, theWidth} to create matrix listOfNames left inset (matrixLeft) bottom theBottom max width (theWidth - matrixLeft) arranged vertically isVertical initial choice defaultValueset {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 2) max width (matrixLeft - theLeft - 6) aligns right aligned without multilineset {theMatrix, theTop, theWidth} to create matrix listOfNames left inset matrixLeft bottom theBottom max width (theWidth - newWidth - 6) arranged vertically isVertical initial choice defaultValueset matrixLeft to (newWidth + 6 + theLeft)if matrixLeft ≤ theLeft thenon create labeled matrix listOfNames left inset theLeft : 0 bottom theBottom max width theWidth arranged vertically isVertical : true matrix left matrixLeft label text theLabel initial choice defaultValue : 1end create matrixmy performSelectorOnMainThread:"createMatrixMainThread:" withObject:{listOfNames, theLeft, theBottom, theWidth, isVertical, defaultValue} waitUntilDone:truemy createMatrixMainThread:{listOfNames, theLeft, theBottom, theWidth, isVertical, defaultValue}on create matrix listOfNames left inset theLeft : 0 bottom theBottom max width theWidth arranged vertically isVertical : true initial choice defaultValue : 1end create labeled path controlreturn {thePathControl, theLabel, theTop}set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theTop + 4) max width theWidth aligns left aligned without multilineset {thePathControl, theTop} to create path control thePath left inset theLeft bottom theBottom control width theWidth pops up popsUpBoolon create labeled path control thePath left inset theLeft : 0 bottom theBottom control width theWidth pops up popsUpBool : true label text theLabelend create path controlmy performSelectorOnMainThread:"createPathControlMainThread:" withObject:{thePath, theLeft, theBottom, theWidth, popsUpBool} waitUntilDone:truemy createPathControlMainThread:{thePath, theLeft, theBottom, theWidth, popsUpBool}on create path control thePath left inset theLeft : 0 bottom theBottom control width theWidth pops up popsUpBool : trueend create labeled checkboxreturn {theCheckbox, theLabel, theTop, checkboxLeft}set {theCheckbox, theTop, theWidth} to create checkbox checkTitle left inset checkboxLeft bottom theBottom max width (theWidth - checkboxLeft) initial state checkStateset {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 2) max width (checkboxLeft - theLeft - 6) aligns right aligned without multilineset {theCheckbox, theTop, theWidth} to create checkbox checkTitle left inset checkboxLeft bottom theBottom max width (theWidth - newWidth - 6) initial state checkStateset checkboxLeft to (newWidth + 6)set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 2) max width theWidth aligns left aligned without multilineif checkboxLeft ≤ theLeft thenon create labeled checkbox checkTitle left inset theLeft : 0 bottom theBottom max width theWidth label text theLabel checkbox left checkboxLeft initial state checkState : falseend create checkboxmy performSelectorOnMainThread:"createCheckboxMainThread:" withObject:{checkTitle, theLeft, theBottom, theWidth, initialState} waitUntilDone:truemy createCheckboxMainThread:{checkTitle, theLeft, theBottom, theWidth, initialState}on create checkbox checkTitle left inset theLeft : 0 bottom theBottom max width theWidth initial state initialState : falseend create labeled popupreturn {thePopup, theLabel, theTop, popupLeft}set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 6) max width (popupLeft - theLeft - 6) aligns right aligned without multilineset {thePopup, theTop} to create popup entryList left inset popupLeft bottom theBottom popup width popupWidth initial choice defaultValueset popupLeft to (newWidth + 6)set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 6) max width theWidth aligns left aligned without multilineif popupLeft ≤ theLeft thenon create labeled popup entryList left inset theLeft : 0 bottom theBottom popup width popupWidth max width theWidth label text theLabel popup left popupLeft initial choice defaultValue : 1end create popupmy performSelectorOnMainThread:"createPopupMainThread:" withObject:{entryList, theLeft, theBottom, theWidth, defaultValue} waitUntilDone:truemy createPopupMainThread:{entryList, theLeft, theBottom, theWidth, defaultValue}if class of defaultValue is integer then set defaultValue to item defaultValue of entryListon create popup entryList left inset theLeft : 0 bottom theBottom popup width theWidth initial choice defaultValue : 1end create side labeled fieldreturn {theField, theLabel, theTop, fieldLeft}set {theField, theTop} to create field enteredText placeholder text placeholder left inset fieldLeft bottom theBottom field width (theWidth - fieldLeft) extra height 0 accepts linebreak and tab acceptsTabsset {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 4) max width (fieldLeft - theLeft - 8) aligns right aligned without multilineset {theField, theTop} to create field enteredText placeholder text placeholder left inset fieldLeft bottom theBottom field width (theWidth - newWidth - 8) extra height 0 accepts linebreak and tab acceptsTabsset fieldLeft to (theLeft + newWidth + 8)set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theBottom + 4) max width theWidth aligns left aligned without multilineif fieldLeft ≤ theLeft thenon create side labeled field enteredText placeholder text placeholder : "" left inset theLeft : 0 bottom theBottom total width theWidth label text theLabel field left fieldLeft accepts linebreak and tab acceptsTabs : falseend create top labeled fieldreturn {theField, theLabel, theTop}set {theLabel, theTop, newWidth} to create label theLabel left inset theLeft bottom (theTop + 8) max width theWidth aligns left aligned without multilineset {theField, theTop} to create field enteredText placeholder text placeholder left inset theLeft bottom theBottom field width theWidth extra height extraHeight accepts linebreak and tab acceptsTabson create top labeled field enteredText placeholder text placeholder : "" left inset theLeft : 0 bottom theBottom field width theWidth extra height extraHeight : 0 label text theLabel accepts linebreak and tab acceptsTabs : falseend create secure fieldmy performSelectorOnMainThread:"createSecureFieldMainThread:" withObject:{enteredText, placeholder, theLeft, theBottom, theWidth} waitUntilDone:truemy createSecureFieldMainThread:{enteredText, placeholder, theLeft, theBottom, theWidth}on create secure field enteredText placeholder text placeholder : "" left inset theLeft : 0 bottom theBottom field width theWidthend create fieldmy performSelectorOnMainThread:"createFieldMainThread:" withObject:{enteredText, placeholder, theLeft, theBottom, theWidth, extraHeight, acceptsTabs} waitUntilDone:truemy createFieldMainThread:{enteredText, placeholder, theLeft, theBottom, theWidth, extraHeight, acceptsTabs}on create field enteredText placeholder text placeholder : "" left inset theLeft : 0 bottom theBottom field width theWidth extra height extraHeight : 0 accepts linebreak and tab acceptsTabs : falseend max depth for labelreturn theHeight + 1 -- allow fudgeset theHeight to item 2 of item 2 of theFrameset theHeight to height of |size| of theFrameif class of theFrame is record thenset theFrame to labelText's boundingRectWithSize:{maxWidth, 2000} options:NSStringDrawingUsesLineFragmentOrigin attributes:theAttsset labelText to NSString's stringWithString:labelTexton max depth for label labelText max width maxWidth control size controlSize : regular size bold type boldType : falseend max width for labelsreturn maxWidth + 4.5 -- allow for frame rectangle and fudgeif newWidth > maxWidth then set maxWidth to newWidthset newWidth to width of (theString's sizeWithAttributes:theAtts)set theString to (NSString's stringWithString:labelString)repeat with labelString in listOfLabelsset maxWidth to 0set theAtts to NSDictionary's dictionaryWithObject:theFont forKey:(NSFontAttributeName)set theFont to my fontOfControlSize:controlSize boldType:boldTypeon max width for labels listOfLabels control size controlSize : regular size bold type boldType : falseend create labelmy performSelectorOnMainThread:"createLabelMainThread:" withObject:{labelString, theLeft, theBottom, maxWidth, alignment, wrapsBool, controlSize, boldType} waitUntilDone:truemy createLabelMainThread:{labelString, theLeft, theBottom, maxWidth, alignment, wrapsBool, controlSize, boldType}on create label labelString left inset theLeft : 0 bottom theBottom max width maxWidth aligns alignment : left aligned multiline wrapsBool : true control size controlSize : regular size bold type boldType : falseend display enhanced alertreturn {buttonName, suppressedState, controlResults}set buttonName to item buttonNumber of (reverse of buttonsList)if buttonNumber = 0 thenset buttonNumber to returnCode mod 1000 + 1 -- where 1 = right-most buttonset suppressedState to theAlert's suppressionButton()'s state() as booleanset theAlert to handlerResultif giveUp > 0 and returnCode is not NSModalResponseAbort then NSObject's cancelPreviousPerformRequestsWithTarget:(NSApp) selector:"abortModal" object:(missing value)my performSelectorOnMainThread:"displayEnhancedAlertMainThread:" withObject:{mainText, theExplanation, styleNum, buttonsList, showSuppression, giveUp, theWidth, theHeight, controlsList} waitUntilDone:truemy displayEnhancedAlertMainThread:{mainText, theExplanation, styleNum, buttonsList, showSuppression, giveUp, theWidth, theHeight, controlsList}set styleNum to 1set styleNum to 0else if styleType = warning alert thenset styleNum to 2if styleType = critical alert thenon display enhanced alert mainText message theExplanation as styleType : informational alert buttons buttonsList suppression showSuppression : false giving up after giveUp : 0 acc view width theWidth acc view height theHeight acc view controls controlsListend create buttonsreturn handlerResultmy performSelectorOnMainThread:"createButtonsViewMainThread:" withObject:{buttonList, buttonKeysList, equalWidths, cancelIndex, okIndex} waitUntilDone:truemy createButtonsViewMainThread:{buttonList, buttonKeysList, equalWidths, cancelIndex, okIndex}on create buttons buttonList button keys buttonKeysList : {} equal widths equalWidths : (false) default button okIndex : 0 cancel button cancelIndex : 0end display enhanced windowreturn {buttonName, controlResults}set my returnCode to missing valueset end of controlResults to missing valueelse -- NSBoxset end of controlResults to aControl's image()'s |name|() as textelse if (aControl's isKindOfClass:(NSImageView)) as boolean thenset end of controlResults to aControl's selectedCell()'s title() as textelse if (aControl's isKindOfClass:(NSMatrix)) as boolean thenset end of controlResults to aControl's |URL|()'s |path|() as textelse if (aControl's isKindOfClass:(NSPathControl)) as boolean thenset end of controlResults to aControl's state() as booleanelse if (aControl's isKindOfClass:(NSButton)) as boolean thenset end of controlResults to aControl's titleOfSelectedItem() as textelse if (aControl's isKindOfClass:(NSPopUpButton)) as boolean then(aControl's setDelegate:(missing value))set end of controlResults to aControl's stringValue() as textif (aControl's isKindOfClass:(NSTextField)) as boolean thenrepeat with aControl in controlsListset controlResults to {}set buttonName to (item buttonNumber of allButtons)'s title() as textset buttonName to "Gave Up"if buttonNumber = NSModalResponseAbort then -- timed outif buttonNumber = NSModalResponseCancel then error number -128 -- designated Cancel button pressedset buttonNumber to returnCodeset handlerResult to missing valuemy performSelectorOnMainThread:"showTheWindowAndWaitMainThread:" withObject:{theWindow, defaultField, giveUp, initPosition, windowTitle} waitUntilDone:truemy performSelectorOnMainThread:"prepareEnhancedWindowMainThread:" withObject:{windowTitle, theWidth, theHeight, controlsList, giveUp, defaultField, initPosition, cancelLeftFlag, allButtons} waitUntilDone:truemy showTheWindowAndWaitMainThread:{theWindow, defaultField, giveUp, initPosition, windowTitle}set theWindow to handlerResultmy prepareEnhancedWindowMainThread:{windowTitle, theWidth, theHeight, controlsList, giveUp, defaultField, initPosition, cancelLeftFlag, allButtons}if NSThread's isMainThread() as boolean thenerror "User interaction disallowed" number theErrorif theError is not 0 thenset theError to current application's AEInteractWithUser(-1, missing value, missing value) -- -1 is kAEDefaultTimeouton display enhanced window windowTitle acc view width theWidth acc view height theHeight acc view controls controlsList giving up after giveUp : 0 active field defaultField : missing value initial position initPosition : {} align cancel button cancelLeftFlag : true buttons allButtonsproperty handlerResult : missing valueproperty returnCode : missing valueproperty minimumButtonWidth : 81property accViewTopGap : 20property accViewYValue : 50property accViewSideInset : 22property buttonYValue : 13property buttonSideInset : 16property NSSecureTextField : a reference to current application's NSSecureTextFieldproperty NSAttributedString : a reference to current application's NSAttributedStringproperty NSDictionary : a reference to current application's NSDictionaryproperty NSThread : a reference to current application's NSThreadproperty NSFontAttributeName : a reference to current application's NSFontAttributeNameproperty NSButton : a reference to current application's NSButtonproperty NSAlert : a reference to current application's NSAlertproperty NSScreen : a reference to current application's NSScreenproperty |NSURL| : a reference to current application's |NSURL|property NSTextField : a reference to current application's NSTextFieldproperty NSObject : a reference to current application's NSObjectproperty NSButtonCell : a reference to current application's NSButtonCellproperty NSWindow : a reference to current application's NSWindowproperty NSBox : a reference to current application's NSBoxproperty NSApp : a reference to current application's NSAppproperty NSView : a reference to current application's NSViewproperty NSModalPanelRunLoopMode : a reference to current application's NSModalPanelRunLoopModeproperty NSFont : a reference to current application's NSFontproperty NSPopUpButton : a reference to current application's NSPopUpButtonproperty NSPathControl : a reference to current application's NSPathControlproperty NSMatrix : a reference to current application's NSMatrixproperty NSImageView : a reference to current application's NSImageViewproperty NSImage : a reference to current application's NSImageproperty NSLeftTextAlignment : a reference to current application's NSLeftTextAlignmentproperty NSCenterTextAlignment : a reference to current application's NSCenterTextAlignmentproperty NSRightTextAlignment : a reference to current application's NSRightTextAlignmentproperty NSTitledWindowMask : a reference to 1property NSMiniControlSize : a reference to 2property NSLineBorder : a reference to 1property NSPathStylePopUp : a reference to 2property NSRegularControlSize : a reference to 0property NSNoTitle : a reference to 0property NSModalResponseAbort : a reference to -1001property NSPathStyleStandard : a reference to 0property NSBackingStoreBuffered : a reference to 2property NSRadioModeMatrix : a reference to 0property NSOnState : a reference to 1property NSMomentaryPushInButton : a reference to 7property NSRoundedBezelStyle : a reference to 1property NSRadioButton : a reference to 4property NSBoxSeparator : a reference to 2property NSModalResponseCancel : a reference to 0property NSSwitchButton : a reference to 3property NSModalPanelWindowLevel : a reference to 8property NSSmallControlSize : a reference to 1property NSNoImage : a reference to 0property NSStringDrawingUsesLineFragmentOrigin : a reference to 1property NSOffState : a reference to 0use framework "Carbon" -- AEInteractWithUser() is in Carbonend event recurrence fortheDict's setObject:recurrCount forKey:"occurrence_count"set recurrCount to recurrEnd's |occurrenceCount|()if recurrEndDate is not missing value then theDict's setObject:recurrEndDate forKey:"occurrence_end_date"set recurrEndDate to recurrEnd's |endDate|()if recurrEnd is not missing value thenset recurrEnd to theRule's |recurrenceEnd|()(theDict's setObject:(theRule's interval()) forKey:"occurrence_interval")(theDict's setObject:(item (theFreq + 1) of {"daily", "weekly", "monthly", "yearly"}) forKey:"occurrence_frequency")set theFreq to theRule's frequency() as integerset theRule to theEvent's |recurrenceRules|()'s firstObject()set theDict to (current application's NSMutableDictionary's dictionaryWithObjects:{theNull} forKeys:{"occurrence_end_date"})on event recurrence for event theEventend event attendees for(theArray's addObject:(theDict's |copy|()))(theDict's setObject:(item (theRole + 1) of {"unknown", "required", "optional", "chair", "nonparticipant"}) forKey:"attendee_role")set theRole to anAttendee's |participantRole|() as integer(theDict's setObject:(item (theType + 1) of {"unknown", "person", "room", "resource", "group"}) forKey:"attendee_type")set theType to anAttendee's |participantType|() as integer(theDict's setObject:(item (theStatus + 1) of {"unknown", "pending", "accepted", "declined", "tentative", "delegated", "completed", "in process"}) forKey:"attendee_status")set theStatus to anAttendee's |participantStatus|() as integerif theEmail is not missing value then (theDict's setObject:(theEmail's |resourceSpecifier|()) forKey:"attendee_email")set theEmail to anAttendee's |URL|()(theDict's setObject:(anAttendee's |name|()) forKey:"attendee_name")set theDict to (current application's NSMutableDictionary's dictionaryWithObjects:{theNull} forKeys:{"attendee_email"})repeat with anAttendee in theAttendeesset theArray to current application's NSMutableArray's array()set theAttendees to theEvent's attendees()if theEvent's hasAttendees() as boolean thenon event attendees for event theEventend event info fortheDict's setObject:(item (theResult + 1) of {"none", "confirmed", "tentative", "canceled"}) forKey:"event_status"theDict's setObject:"none" forKey:"event_status"if theResult is missing value thenset theResult to (theEvent's status())if theResult is not missing value then theDict's setObject:theResult forKey:"event_original_date"set theResult to (theEvent's |occurrenceDate|())if theResult is not missing value then theDict's setObject:theResult forKey:"event_organizer"set theResult to (theResult's |name|())if theResult is not missing value thenset theResult to (theEvent's organizer())theDict's setObject:(theEvent's |creationDate|()) forKey:"event_creation_date"theDict's setObject:(theEvent's |hasRecurrenceRules|()) forKey:"event_is_recurring"theDict's setObject:{} forKey:"event_attendees"theDict's setObject:(theEvent's attendees()'s valueForKey:"name") forKey:"event_attendees"if theAttendees as boolean thenset theAttendees to theEvent's |hasAttendees|()if theResult is not missing value then theDict's setObject:theResult forKey:"event_description"set theResult to (theEvent's notes())if theResult thenset theResult to (theEvent's |hasNotes|()) as booleanif theURL is not missing value then theDict's setObject:(theURL's |absoluteString|()) forKey:"event_url"set theURL to (theEvent's |URL|())if theResult is not missing value then theDict's setObject:theResult forKey:"event_location"set theResult to (theEvent's location())if tz is not missing value then theDict's setObject:(tz's |name|()) forKey:"event_time_zone"set tz to (theEvent's timeZone())theDict's setObject:(theEvent's |isAllDay|()) forKey:"all_day"theDict's setObject:(theEvent's |endDate|()) forKey:"event_end_date"theDict's setObject:(theEvent's |startDate|()) forKey:"event_start_date"theDict's setObject:(theEvent's |calendarItemExternalIdentifier|()) forKey:"event_external_ID"if theResult is not missing value then theDict's setObject:theResult forKey:"event_summary"set theResult to (theEvent's title())theDict's setObject:(item (theResult + 1) of {"local", "cloud", "Exchange", "subscription", "birthday"}) forKey:"calendar_type"set theResult to (theEvent's calendar()'s |type|()) as integertheDict's setObject:(theEvent's calendar()'s title()) forKey:"calendar_name"set theDict to current application's NSMutableDictionary's dictionaryWithObjects:{theNull, theNull, theNull, theNull, theNull, theNull, theNull} forKeys:{"event_summary", "event_time_zone", "event_location", "event_url", "event_description", "event_organizer", "event_original_date"}set theNull to current application's NSNull's |null|()on event info for event theEventend event identifier forreturn theEvent's |calendarItemExternalIdentifier|() as texton event identifier for event theEventend store eventif not theResult as boolean then error (theError's |localizedDescription|() as text)set {theResult, theError} to theStore's saveEvent:theEvent span:futureFlag commit:true |error|:(reference)on store event event theEvent event store theStore future events futureFlag : trueend stop recurrenceif (count of theRules) > 0 then theEvent's removeRecurrenceRule:(item 1 of theRules)set theRules to theEvent's |recurrenceRules|()if theEvent's hasRecurrenceRules() as boolean thenon stop recurrence event theEventend modify recurrencetheEvent's addRecurrenceRule:recurrRulestop recurrence event theEventset recurrRule to current application's EKRecurrenceRule's alloc()'s initRecurrenceWithFrequency:theFreq interval:interv |end|:recurrEndset recurrEnd to current application's EKRecurrenceEnd's recurrenceEndWithEndDate:endingDateset recurrEnd to current application's EKRecurrenceEnd's recurrenceEndWithOccurrenceCount:repeatCtif endingDate is missing value thenerror "Invalid frequency parameter"set theFreq to 3else if theFreq = do yearly thenset theFreq to 2else if theFreq = do monthly thenset theFreq to 1else if theFreq = do weekly thenset theFreq to 0if theFreq = do daily thenon modify recurrence event theEvent event frequency theFreq event interval interv repeats for repeatCt : missing value repeats until endingDate : missing valueend modify zoneelse -- assume it's already a time zoneset tz to current application's NSTimeZone's timeZoneWithName:tzif (current application's NSTimeZone's knownTimeZoneNames()'s containsObject:tz) as boolean thenif (tz's isKindOfClass:(current application's NSString)) as boolean thenset tz to (current application's NSArray's arrayWithObject:tz)'s |firstObject|()theEvent's setTimeZone:tzif tz is missing value thenon modify zone event theEvent time zone tzend modify eventreturn theEventif desc is not missing value then theEvent's setNotes:descif theLocation is not missing value then theEvent's setLocation:theLocationif allDay is not missing value then theEvent's setAllDay:allDayif endD is not missing value then theEvent's setEndDate:endDif startD is not missing value then theEvent's setStartDate:startDif theTitle is not missing value then theEvent's setTitle:theTitleif theCal is not missing value then theEvent's setCalendar:theCalon modify event event theEvent destination calendar theCal event summary theTitle : missing value starting date startD : missing value ending date endD : missing value runs all day allDay : missing value event location theLocation : missing value event description desc : missing valueend create eventreturn newEventif desc is not missing value then newEvent's setNotes:descif theLocation is not missing value then newEvent's setLocation:theLocationnewEvent's setAllDay:allDaynewEvent's setEndDate:endDnewEvent's setStartDate:startDnewEvent's setTitle:theTitlenewEvent's setCalendar:theCalset newEvent to current application's EKEvent's eventWithEventStore:theStoreon create event event store theStore destination calendar theCal event summary theTitle starting date startD ending date endD runs all day allDay : false event location theLocation : missing value event description desc : missing valueend remove eventif not theResult as boolean then error (theError's localizedDescription() as text)set {theResult, theError} to theStore's removeEvent:theEvent span:futureFlag commit:true |error|:(reference)on remove event event theEvent event store theStore future events futureFlag : trueend filter events by patternset theNSPredicate to current application's NSPredicate's predicateWithFormat_("location LIKE %@", theLocation)set theNSPredicate to current application's NSPredicate's predicateWithFormat_("location MATCHES %@", theLocation)if useRegex as boolean thenset theNSPredicate to current application's NSPredicate's predicateWithFormat_("hasNotes == %@ AND notes LIKE %@", true, desc)set theNSPredicate to current application's NSPredicate's predicateWithFormat_("hasNotes == %@ AND notes MATCHES %@", true, desc)set theEvents to (theEvents's filteredArrayUsingPredicate:theNSPredicate)set theNSPredicate to current application's NSPredicate's predicateWithFormat_("title LIKE %@", theTitle)set theNSPredicate to current application's NSPredicate's predicateWithFormat_("title MATCHES %@", theTitle)if regexFlag as boolean thenon filter events by pattern event list theEvents event summary theTitle : missing value event description desc : missing value event location theLocation : missing value using regex regexFlag : trueend filter eventsset theEvents to (theEvents's filteredArrayUsingPredicate:thePred)set thePred to current application's NSCompoundPredicate's andPredicateWithSubpredicates:predArrayelse if theCount > 1 thenset theEvents to (theEvents's filteredArrayUsingPredicate:(predArray's firstObject()))if theCount = 1 thenset theCount to count of predArraypredArray's addObject:(current application's NSPredicate's predicateWithFormat_("allDay == %@", allDay))if allDay is not missing value thenpredArray's addObject:(current application's NSPredicate's predicateWithFormat_("hasRecurrenceRules == %@", hasRecRules))if hasRecRules is not missing value thenpredArray's addObject:(current application's NSPredicate's predicateWithFormat_("hasAttendees == %@", hasA))if hasA is not missing value thenpredArray's addObject:(current application's NSPredicate's predicateWithFormat_("hasNotes == %@ AND notes ==[c] %@", true, desc))if desc is not missing value thenpredArray's addObject:(current application's NSPredicate's predicateWithFormat_("location ==[c] %@", theLocation))if theLocation is not missing value thenpredArray's addObject:(current application's NSPredicate's predicateWithFormat_("title ==[c] %@", theTitle))if theTitle is not missing value thenset predArray to current application's NSMutableArray's arrayWithCapacity:6if not (theEvents's isKindOfClass:(current application's NSArray)) as boolean then set theEvents to theEventsArrayset theEvents to theEventsArray's |firstObject|()set theEventsArray to current application's NSArray's arrayWithObject:theEventson filter events event list theEvents event summary theTitle : missing value event location theLocation : missing value event description desc : missing value has attendees hasA : missing value has recurrence hasRecRules : missing value runs all day allDay : missing valueend fetch eventsset theEvents to theStore's eventsMatchingPredicate:thePredicateset thePredicate to theStore's predicateForEventsWithStartDate:startDate endDate:endDate calendars:calListif not (calList's isKindOfClass:(current application's NSArray)) as boolean then set calList to calListArrayset calList to calListArray's |firstObject|()set calListArray to current application's NSArray's arrayWithObject:calListon fetch events starting date startDate ending date endDate searching cals calList event store theStoreend fetch events by UIDreturn theEvents as listset theEvents to theEvents's sortedArrayUsingSelector:"compareStartDateWithEvent:"set theEvents to (theStore's calendarItemsWithExternalIdentifier:calID)on fetch events by UID calID event store theStoreend fetch calendarsreturn (theCalendars's filteredArrayUsingPredicate:theNSPredicate) as listset theNSPredicate to current application's NSPredicate's predicateWithFormat_("title IN %@ AND type IN %@", listOfCalNames, listOfCalTypes)set theNSPredicate to current application's NSPredicate's predicateWithFormat_("type IN %@", listOfCalTypes)set item i of listOfCalTypes to calTypeset calType to item i of listOfCalTypesrepeat with i from 1 to count of listOfCalTypesset theNSPredicate to current application's NSPredicate's predicateWithFormat_("title IN %@", listOfCalNames)return theCalendars as listif listOfCalNames = {} thenif listOfCalTypes = {} thenon fetch calendars listOfCalNames as list cal type list listOfCalTypes as list : {} event store theStoreend fetch calendarreturn (theCalendars's filteredArrayUsingPredicate:theNSPredicate)'s firstObject()set theNSPredicate to current application's NSPredicate's predicateWithFormat_("title == %@ AND type IN %@", calName, {calType})set theCalendars to theStore's calendarsForEntityType:0error "Invalid cal type"set calType to 4else if calType = cal birthday thenset calType to 3else if calType = cal subscription thenset calType to 2else if calType = cal exchange thenset calType to 1else if calType = cal cloud thenset calType to 0if calType = cal local thenon fetch calendar calName cal type calType event store theStoreend fetch storereturn theEKEventStoretell pane id "com.apple.preference.security" to reveal anchor "Privacy"display dialog "Access must be given in System Preferences" & linefeed & "-> Security & Privacy first." buttons {"OK"} default button 1if authorizationStatus is not 3 thenset authorizationStatus to current application's EKEventStore's authorizationStatusForEntityType:0theEKEventStore's requestAccessToEntityType:0 completion:(missing value)set theEKEventStore to current application's EKEventStore's alloc()'s init()on fetch storeuse framework "EventKit"use AppleScript version "2.5" -- requires OS X 10.11 or higherend RBGtoHTMLreturn ("#" & the hex_value) as stringset the hex_value to (the hex_value & x & y) as stringset y to item (((this_value / 16 mod 1) * 16) + 1) of the hex_listset x to item ((this_value div 16) + 1) of the hex_listif this_value is 256 then set this_value to 255set this_value to (item i of the RGB_values) div 256repeat with i from 1 to the count of the RGB_valuesset the the hex_value to ""on RBGtoHTML(RGB_values)end display overlay textdo shell script commandStringset the commandSubstring to "-o" & space & opacityAsRealAsStringset the opacityAsRealAsString to (the backgroundOpacity * 0.01) as stringset backgroundOpacity to 0else if backgroundOpacity is less than 0 thenset backgroundOpacity to 100if backgroundOpacity is greater than 100 thenif backgroundOpacity is not missing value thenset backgroundOpacity to the opacity of advancedSettingsRecordset the commandSubstring to (("-x" & space & windowLeft) as string) & space & (("-y" & space & windowBottom) as string)copy backgroundPosition to {windowLeft, windowBottom}if backgroundPosition is not missing value thenset backgroundPosition to the background position of advancedSettingsRecordset the commandSubstring to (("-w" & space & windowWidth) as string) & space & (("-h" & space & windowHeight) as string)copy backgroundDimensions to {windowWidth, windowHeight}if backgroundDimensions is not missing value thenset backgroundDimensions to the background dimensions of advancedSettingsRecordset the commandString to commandString & space & "-b" & space & backgroundColorValueset backgroundColorValue to text 2 thru -1 of (my RBGtoHTML(backgroundColorValue))if the class of backgroundColorValue is list thenif backgroundColorValue is not missing value thenset backgroundColorValue to the background color of advancedSettingsRecordset the commandString to commandString & space & "-f" & space & fontColorValueset fontColorValue to text 2 thru -1 of (my RBGtoHTML(fontColorValue))if the class of fontColorValue is list thenif fontColorValue is not missing value thenset fontColorValue to the font color of advancedSettingsRecordtry -- will fail if the matching setting is not in the passed recordif advancedSettingsRecord is not missing value thenset the commandString to commandString & space & "-H"if gooseHonkValue is true thenif gooseHonkValue is not missing value thenset the commandString to commandString & space & commandSubstringset the commandSubstring to "-p" & space & durationValueset the durationValue to (durationValue as integer) as stringif durationValue is not missing value thenset the commandString to honkUtility & space & (quoted form of the (space & sourceText & space))set the honkUtility to the quoted form of the POSIX path of (path to resource "BigHonkingText")prevChar = "(" or prevChar = "[" or prevChar = "{" or ¬ prevChar = "<" or prevChar = 171 or ¬ prevChar = character id 12296 or prevChar = character id 12298 or ¬ (prevChar = gLeftQuote and theChar = singleQuote) or ¬ (prevChar = gLeftApostrophe and theChar = doubleQuote) or ¬ isWhiteSpace(prevChar)) then if theChar = singleQuote then set theChar to gLeftApostrophe else set theChar to gLeftQuote end if else if theChar = singleQuote then set theChar to gRightApostrophe else set theChar to gRightQuote end if end if set prevChar to theChar as string end if copy theChar to end of newString end repeat setString(newString as string) return getString() end smartenQuotes -- file path utilities on filename() return lastToken("/") end filename on dirPath() return beforeString(filename()) end dirPath on fileExtension() tell newString(filename()) return afterString(".") end tell end fileExtension on fileBasename() tell newString(filename()) return beforeString(".") end tell end fileBasename end script on display overlay text sourceText duration durationValue : 0 goose honk gooseHonkValue : false advanced settings advancedSettingsRecord : {}if (prevChar = 0 or ¬if (theChar = singleQuote or theChar = doubleQuote) thenset theChar to character i of theStringset prevChar to ""set s to theStringset n to number of characters of theStringset newString to {}on smartenQuotes()property doubleQuote : "\""property singleQuote : "'"property gRightQuote : character id 8221property gLeftQuote : character id 8220property gRightApostrophe : character id 8217property gLeftApostrophe : character id 8216end isWhiteSpacereturn c = space or c = tab or c = return or c = linefeedon isWhiteSpace(c)return -nif n < 0 thenon abs(n)end titlecase_pureASset firstChar to falseif not firstChar thenelse if a > 96 and a < 123 and firstChar thenif a > 64 and a < 91 and not firstChar thenset firstChar to trueif a is in {9, 11, 32, 34, 39, 160, 2018, 8220} thenset firstChar to true -- start with first charon titlecase_pureAS() --> stringend lowercase_pureASset newString to newString & character lc of lowersif contents of c = character lc of uppers thenset a to a + 32if a > 64 and a < 91 thenset ncl to number of characters of upperson lowercase_pureAS() --> stringend uppercase_pureASset theString to newStringset newString to newString & cif not found thenset newString to newString & character lc of uppersif contents of c = character lc of lowers thenrepeat with lc from 1 to nclif (not found) and (a > 128) thenset found to trueset newString to newString & (character id a)set a to a - 32if a > 96 and a < 123 thenset a to id of crepeat with c in characters of theStringset ncl to number of characters of lowersset newString to ""local newStringon uppercase_pureAS() --> stringproperty uppers : "ŒÆÁÀÂÄÃÅÉÈÊËÓÒÔÖÕÚÙÛÜÍÌÎÏÑÇØŸ∏ẞ"property lowers : "œæáàâäãåéèêëóòôöõúùûüíìîïñçøÿπß"end titlecaseset theString to (current application's NSString's stringWithString:theString)'s capitalizedString as itemon titlecase() --> stringend lowercaseset theString to (current application's NSString's stringWithString:theString)'s lowercaseString as itemon lowercase() --> stringend uppercaseset theString to (current application's NSString's stringWithString:theString)'s uppercaseString as itemon uppercase() --> stringend trimWhitespaceset theString to text 1 thru -2 of theStringrepeat while last character of theString = tab or last character of theString = space or last character of theString = lfset theString to text 2 thru -1 of theStringrepeat while character 1 of theString = tab or character 1 of theString = space or character 1 of theString = lfif length of theString > 1 thenreplaceString(twoSpaces, space)repeat while theString contains twoSpacesset twoSpaces to space & spacereplaceString(twoTabs, tab)repeat while theString contains twoTabsset twoTabs to tab & tabreplaceString(twoReturns, return)repeat while theString contains twoReturnsset twoReturns to return & returnset lf to character id 10on trimWhitespace() --> stringend afterTokenset aList to items (i + 1) thru n of theListrepeat with i from 1 to (n - 1)on afterToken(token, delim) --> string (only reads)end beforeTokenreturn convertListToString(aList, delim)set aList to items 1 thru (i - 1) of theListif item i of theList = token thenrepeat with i from 2 to non beforeToken(token, delim) --> string (only reads)end keepTokenRangeset theList to getTokenRange(startIndex, endIndex, delim)on keepTokenRange(startIndex, endIndex, delim) --> stringend deleteTokenRangesetTokens(theList, delim)set theList to (items 1 thru (startIndex - 1) of theList) & (items (endIndex + 1) thru n of theList)set theList to items 1 thru (startIndex - 1) of theListelse if endIndex = n thenset theList to items (endIndex + 1) thru n of theListif endIndex = n thenif endIndex < 0 then set endIndex to n + endIndex + 1if startIndex < 0 then set startIndex to n + startIndex + 1if startIndex > endIndex then error "startIndex > endIndex in deleteTokenRange"if abs(endIndex) > n or endIndex = 0 then error "Bad endIndex in deleteTokenRange"if abs(startIndex) > n or startIndex = 0 then error "Bad startIndex in deleteTokenRange"on deleteTokenRange(startIndex, endIndex, delim) --> stringend getTokenRangeif startIndex > endIndex then error "startIndex > endIndex in getTokenRange"if abs(endIndex) > n or endIndex = 0 then error "Bad endIndex in getTokenRange"if abs(startIndex) > n or startIndex = 0 then error "Bad startIndex in getTokenRange"set n to number of items of theListon getTokenRange(startIndex, endIndex, delim) --> list (only reads)end eachTokenContainingcopy theItem to end of newListif contents of theItem contains thisString thenrepeat with theItem in theListset theList to getTokens(delim)on eachTokenContaining(thisString, delim) --> list (only reads)end keepNthTokensetString(NthToken(n, delim))on keepNthToken(n, delim) --> stringend keepLastTokensetString(NthToken(-1, delim))on keepLastToken(delim) --> stringend keepFirstTokensetString(NthToken(1, delim))on keepFirstToken(delim) --> stringend deleteLastTokendeleteNthToken(-1, delim)on deleteLastToken(delim) --> stringend deleteFirstTokendeleteNthToken(1, delim)on deleteFirstToken(delim) --> stringend deleteNthTokenerror theMsg number theNumon error theMsg number theNumset theString to aList as stringset aList to (items 1 thru (n - 1) of aList) & (items (n + 1) thru m of aList)set aList to items 1 thru (m - 1) of aListelse if n = m thenset aList to items 2 thru m of aListif n < 1 then error "Cannot delete tokens before the first token"if n < 0 then set n to m + n + 1set m to number of items of aListset aList to getTokens(delim)if n = 0 then error "Cannot delete token zero"on deleteNthToken(n, delim) --> stringend NthTokenreturn item n of tif n > numItems then error "Cannot get delim " & n & ", only " & numItems & " of tokens"set numItems to number of items of tif t = {} then return ""set t to getTokens(delim)if n = 0 then error "Cannot get delim zero"on NthToken(n, delim) --> stringend lastTokenreturn NthToken(-1, delim)on lastToken(delim) --> stringend firstTokenreturn NthToken(1, delim)on firstToken(delim) --> string (only reads)end setTokensset theString to convertListToString(aList, delim)on setTokens(aList, delim) --> stringend getTokenson getTokens(delim) --> list (only reads)end convertListToStringset AppleScript's text item delimiters to oldSepset aString to aList as stringset AppleScript's text item delimiters to delimset oldSep to AppleScript's text item delimiterson convertListToString(aList, delim) --> string (only reads)end deleteCharactersset theString to a & bset b to ""set b to text (y + 1) thru -1 of theStringif y < length of theString thenset a to ""set a to text 1 thru (x - 1) of theStringif x > 1 thenon deleteCharacters(x, y) --> stringend keepBetweenset theString to betweenStrings(afterThis, beforeThis)on keepBetween(afterThis, beforeThis) --> stringend keepAfterset theString to afterString(afterStr)on keepAfter(afterStr) --> stringend keepBeforeset theString to beforeString(beforeStr)on keepBefore(beforeStr) --> stringend deleteBetweenIncludingset theString to {beforeString(afterThis), afterString(beforeThis)} as stringon deleteBetweenIncluding(afterThis, beforeThis) --> stringend deleteBetweenset theString to {beforeString(afterThis), afterThis, beforeThis, afterString(beforeThis)} as stringon deleteBetween(afterThis, beforeThis) --> stringend deleteAfterset theString to beforeString(afterStr) & afterStron deleteAfter(afterStr) --> stringend deleteBeforeset theString to beforeStr & afterString(beforeStr)on deleteBefore(beforeStr) --> stringend insertAftererror "Could not insert after missing string."set theString to {beforeString(afterStr), afterStr, thisStr, afterString(afterStr)} as stringif theString contains afterStr thenon insertAfter(afterStr, thisStr) --> stringend insertBeforeerror "Could not insert before missing string."set theString to {beforeString(beforeStr), thisStr, beforeStr, afterString(beforeStr)} as stringif theString contains beforeStr thenon insertBefore(beforeStr, thisStr) --> stringend replaceBetweenset theString to {t1, frontTag, newValue, theString} as stringdeleteBefore(rearTag)deleteString(frontTag)deleteBefore(frontTag)set t1 to beforeString(frontTag)on replaceBetween(frontTag, rearTag, newValue) --> stringend deleteStringset theString to beforeString(aString) & afterString(aString) as stringif foo ≠ 0 thenon deleteString(aString) --> stringend replaceStringsset AppleScript's text item delimiters to oldDelimset theString to theList as stringset AppleScript's text item delimiters to thatStrset theList to text items of theStringset AppleScript's text item delimiters to thisStrset oldDelim to AppleScript's text item delimiterson replaceStrings(thisStr, thatStr) --> stringreplaceStrings(thisStr, thatStr) -- expecting only a single replacement could be considered here, but we're not that subtle yeton replaceString(thisStr, thatStr) -- syntax forgivenness so you don't have to remember if there is or isn't an send replaceOneStringset theString to beforeString(thisStr) & thatStr & afterString(thisStr)on replaceOneString(thisStr, thatStr) --> stringend prependStringset theString to aString & theStringon prependString(aString) --> stringend appendStringset theString to theString & aStringon appendString(aString) --> stringend betweenStringsIncludingreturn (afterThis & betweenStrings(afterThis, beforeThis) & beforeThis) as stringon betweenStringsIncluding(afterThis, beforeThis) --> string (only reads)end betweenStringsreturn tempStringsetString(savedString)set tempString to theStringkeepBefore(beforeThis)keepAfter(afterThis)set savedString to theStringon betweenStrings(afterThis, beforeThis) --> string (only reads)return {before_str, aString, after_str}set after_str to text foo thru -1 of theStringset after_str to ""set before_str to text 1 thru (foo - 1) of theStringset before_str to ""else if foo = 1 thenreturn {theString, "", ""}on partition(aString)end afterStringreturn text foo thru -1 of theStringif foo > length of theString thencopy foo + (length of aString) to fooif foo = 0 thenon afterString(aString) --> string (only reads)end beforeStringreturn text 1 thru (foo - 1) of theStringif foo ≤ 1 thenon beforeString(aString) --> string (only reads)end containsStringreturn foo > 0set foo to offset of aString in theStringon containsString(aString)end subStringreturn text x thru y of theStringon subString(x, y) --> string (only reads)end setListset theString to convertListToString(aList, seperator)on setList(aList, seperator) --> stringend setStringset theString to aString as stringon setString(aString) --> stringend getStringon getString() --> string (only reads)end newStringanObject's setString(aString)copy me to anObjecton newString(aString) --> script object factory methodproperty theString : ""property parent : AppleScriptscript SmartStringend write to standard output_error("write to standard output", eText, eNumber, eFrom, eTo)asocStdout's writeData:(asocString's dataUsingEncoding:(current application's NSUTF8StringEncoding))set asocStdout to current application's NSFileHandle's fileHandleWithStandardOutput()if withLineEnding and not (asocString's hasSuffix:linefeed) then asocString's appendString:linefeedasocString's replaceOccurrencesOfString:(return) ¬withString:(linefeed) options:0 range:{location:0, |length|:asocString's |length|()}asocString's replaceOccurrencesOfString:(return & linefeed) ¬if useLinefeeds thenset asocString to _support's asNSMutableString(_support's asTextParameter(theText, ""))to write to standard output theText normalized line breaks useLinefeeds : (true) automatic line ending withLineEnding : (true)end read from standard input_error("read from standard input", eText, eNumber, eFrom, eTo)if asocString's hasSuffix:linefeed then set asocString to asocString's substringToIndex:((asocString's |length|()) - 1)if asocString is missing value then error "Input is not UTF8-encoded text." number -1700set asocString to current application's NSString's alloc()'s initWithData:asocData encoding:(current application's NSUTF8StringEncoding)set asocData to asocStdin's readDataToEndOfFile()if asocData's |length|() = 0 then return missing valueset asocData to asocStdin's availableData()write to standard output promptText without normalized line breaks and automatic line endingif isInteractive thenset asocStdin to current application's NSFileHandle's fileHandleWithStandardInput()to read from standard input with prompt promptText : (">> ") user interaction isInteractive : (false)end environment variablesreturn (current application's NSProcessInfo's processInfo()'s environment()) as anyto environment variablesend current working directory_error("current working directory", eText, eNumber, eFrom, eTo)return asocPath as text as POSIX fileif asocPath is missing value then error "Not available." number -1728set asocPath to current application's NSFileManager's defaultManager()'s currentDirectoryPath()to current working directoryend format command line help_error("format command line help", eText, eNumber, eFrom, eTo)return helpText & linefeedset helpText to helpText & LF2 & vtStyle's b & "DESCRIPTION" & vtStyle's n & LF2 & longDescriptionif longDescription is not "" thenif argumentsSection is not "" then set helpText to helpText & LF2 & argumentsSectionif optionsSection is not "" then set helpText to helpText & LF2 & optionsSection_support's throwInvalidParameterType(commandSynopses, "synopsis", list, "list of text")set helpText to helpText & LF2 & Indent1 & textRefrepeat with textRef in commandSynopsesset commandSynopses to {commandName & defaultOptionsSynopsis & defaultArgumentsSynopsis}if commandSynopses is {} thenset helpText to helpText & LF2 & vtStyle's b & "SYNOPSIS" & vtStyle's nset {defaultArgumentsSynopsis, argumentsSection} to _formatArguments(argumentDefinitions, vtStyle)set {defaultOptionsSynopsis, optionsSection} to _formatOptions(optionDefinitions, vtStyle, hasDefaultOptions)set helpText to helpText & " -- " & shortDescriptionif shortDescription is not "" thenset helpText to vtStyle's b & "NAME" & vtStyle's n & LF2 & Indent1 & commandNameset commandName to "COMMAND" -- fallback on the offchance the above should fail to get the script's file nameset commandName to item -1 of (split path (_ of (environment variables)))if commandName is "" then -- use the AppleScript shell script's own file name by defaultset vtStyle to {n:"", b:"", u:""}set vtStyle to {n:VT100(0), b:VT100(1), u:VT100(4)} -- normal, bold, underlineif _support's asBooleanParameter(isStyled, "terminal styles") thenset longDescription to _support's asTextParameter(longDescription, "documentation")set shortDescription to _support's asTextParameter(shortDescription, "summary")set commandSynopses to _support's asListParameter(commandSynopses, "")set commandName to _support's asTextParameter(commandName, "name")terminal styles isStyled : (true) ¬description longDescription : ("") ¬synopsis commandSynopses : {} ¬summary shortDescription : ("") ¬to format command line help name commandName : ("") ¬end parse command line arguments_error("parse command line arguments", eText, eNumber, eFrom, eTo)if eNumber = _ArgvUserError thenreturn asocParametersDict as any -- coerce the dictionary to an AS record and return it_parseArguments(argumentsList, argumentDefinitions, asocParametersDict)_addDefaultOptions(asocParametersDict, optionDefinitions)set {asocParametersDict, argumentsList} to _parseOptions(items of argv, optionDefinitions, hasDefaultOptions)set argumentDefinitions to _support's asListParameter(argumentDefinitions, "")set optionDefinitions to _support's asListParameter(optionDefinitions, "")set argv to _support's asListParameter(argv, "")default options hasDefaultOptions : (true)arguments argumentDefinitions : {} ¬options optionDefinitions : {} ¬to parse command line arguments argv ¬end _formatArgumentsreturn {" [--]" & argumentsSynopsis, argumentsSection}set argumentsSynopsis to argumentsSynopsis & space & valuePlaceholderif argumentDefinition's defaultValue is not NoValue then set valuePlaceholder to "[" & valuePlaceholder & "]"if valueDescription is not "" then set argumentsSection to argumentsSection & linefeed & Indent2 & valueDescriptionif isList then set valueDescription to valueDescription & "This argument can appear multiple times. "if argumentDefinition's defaultValue is not NoValue then set valueDescription to valueDescription & _formatDefaultValue(argumentDefinition)set argumentsSection to argumentsSection & LF2 & Indent1 & valuePlaceholderif isList then set valuePlaceholder to valuePlaceholder & " ..."if valuePlaceholder is "" then set valuePlaceholder to _defaultValuePlaceholder(argumentDefinition)_support's throwInvalidParameterType(argumentDefinitions, "arguments", record, "list of ‘command line argument definition’ records")set valueDescription to _normalizeTrailingSpace(argumentDefinition's valueDescription as text)set valuePlaceholder to argumentDefinition's valuePlaceholder as textset isList to argumentDefinition's isList as booleanset valueType to _asValueType(argumentDefinition's valueType)set argumentDefinition to (argumentRef as record) & {valueType:text, isList:false, defaultValue:NoValue, valuePlaceholder:"", valueDescription:""}repeat with argumentRef in argumentDefinitionsset argumentsSection to vtStyle's b & "ARGUMENTS" & vtStyle's nset argumentsSynopsis to ""if argumentDefinitions is {} then return {"", ""}to _formatArguments(argumentDefinitions, vtStyle)end _formatOptionsreturn {optionsSynopsis, optionsSection}if otherOptions is not "" then set optionsSynopsis to optionsSynopsis & otherOptionsif booleanOptions is not "" then set optionsSynopsis to optionsSynopsis & " [-" & booleanOptions & "]"if defaultOptions is not "" then set optionsSynopsis to optionsSynopsis & " [-" & defaultOptions & "]"set optionsSynopsis to ""set optionsSection to optionsSection & LF2 & Indent1 & "-v, --version" & linefeed & Indent2 & "Print version number and exit."set defaultOptions to defaultOptions & "v"if booleanOptions does not contain "v" thenset optionsSection to optionsSection & LF2 & Indent1 & "-h, --help" & linefeed & Indent2 & "Print this help and exit."set defaultOptions to "h" & defaultOptionsif booleanOptions does not contain "h" thenif valueDescription is not "" then set optionsSection to optionsSection & linefeed & Indent2 & valueDescriptionif isList then set valueDescription to valueDescription & "This option can appear multiple times. "if optionDefinition's defaultValue is not NoValue then set valueDescription to valueDescription & _formatDefaultValue(optionDefinition)if valueType's class is list then set valueDescription to valueDescription & _formatEnumeration(valueType)set optionsSection to optionsSection & space & valuePlaceholderif isOptional then set otherOptions to otherOptions & "]"set otherOptions to otherOptions & space & valuePlaceholderset valuePlaceholder to vtStyle's u & valuePlaceholder & vtStyle's nif valuePlaceholder is "" then set valuePlaceholder to _defaultValuePlaceholder(optionDefinition)set valuePlaceholder to valuePlaceholderset otherOptions to otherOptions & "-" & optionNameif isOptional then set otherOptions to otherOptions & "["set otherOptions to otherOptions & spaceset isOptional to optionDefinition's defaultValue is not NoValueset booleanOptions to booleanOptions & optionNameif valueType is boolean then -- group all boolean flags as "[-N…]"if longName is not "" then set optionsSection to optionsSection & ", --" & longNameset optionsSection to optionsSection & "-" & shortNameset optionName to shortNameset optionsSection to optionsSection & "--" & longNameset optionName to longNameif longName is "" then error "Invalid option definition (record must contain a ‘shortName’ and/or ‘longName’ property)." number -1703 from optionRefif shortName is "" thenset optionsSection to optionsSection & LF2 & Indent1_support's throwInvalidParameter(optionDefinitions, "options", list, "not a valid list of ‘command line option definition’ records: " & eText)set valueDescription to _normalizeTrailingSpace(optionDefinition's valueDescription as text)set valuePlaceholder to optionDefinition's valuePlaceholder as textset isList to optionDefinition's isList as booleanset valueType to _asValueType(optionDefinition's valueType)set longName to optionDefinition's longName as textset shortName to optionDefinition's shortName as textset optionDefinition to (optionRef as record) & {shortName:"", longName:"", valueType:text, isList:false, defaultValue:NoValue, valuePlaceholder:"", valueDescription:""}set optionsSection to vtStyle's b & "OPTIONS" & vtStyle's nset {defaultOptions, booleanOptions, otherOptions} to {"", "", ""}if optionDefinitions is {} and not hasDefaultOptions then return {"", ""}to _formatOptions(optionDefinitions, vtStyle, hasDefaultOptions)end _parseArgumentsif argumentsList is not {} then error "Too many arguments (expected " & length of argumentDefinitions & " but received " & argCount & ")." number _ArgvUserError(asocParametersDict's setObject:theValue forKey:(argumentDefinition's propertyName))set argumentsList to {}set end of theValue to _unpackValue(aRef's contents, argumentDefinition)repeat with aRef in argumentsListset theValue to {theValue}if i < length of argumentDefinitions then error "Invalid argument definition (only the last argument definition may contain an ‘isList:true’ property)." number -1703 from argRefif argumentDefinition's isList thenset argumentsList to rest of argumentsListset theValue to _unpackValue(first item of argumentsList, argumentDefinition)error "Missing " & _ordinalNumber(i) & " required argument (expected " & placeholderText & ")." number _ArgvUserErrorif placeholderText's length = 0 then set placeholderText to _defaultValuePlaceholder(argumentDefinition)set placeholderText to argumentDefinition's valuePlaceholderif theValue is NoValue then -- record doesn't have a defaultValue property, so user should've supplied argumentset theValue to argumentDefinition's defaultValueif argumentsList = {} thenif argumentDefinition's propertyName is "" then error "Invalid argument definition (record must contain a non-empty propertyName property)." number -1703 from argReferror "Invalid argument definition (a non-optional argument cannot follow an optional argument)." number -1703 from argRefelse if mustBeOptional and argumentDefinition's defaultValue is NoValue thenset mustBeOptional to trueif argumentDefinition's defaultValue is not NoValue thenset argumentDefinition to (argRef's contents as record) & {propertyName:"", valueType:text, isList:false, defaultValue:NoValue, valuePlaceholder:""}repeat with argRef in argumentDefinitionsset mustBeOptional to false -- repeat loop will throw invalid argument definition error if an optional argument definition is followed by a required argument definitionset argCount to argumentsList's lengthto _parseArguments(argumentsList, argumentDefinitions, asocParametersDict)end _normalizeTrailingSpaceif theText's length > 0 and theText's character -1 is not "" then set theText to theText & spaceignoring white space -- (hyphens, punctuation must already be considered)to _normalizeTrailingSpace(theText) -- append space to text only if necessaryend _ordinalNumberreturn (n as text) & "th"return (n as text) & item (n mod 10) of {"st", "nd", "rd"}if {n mod 10} is in {1, 2, 3} and {n mod 100} is not in {11, 12, 13} thento _ordinalNumber(n)end _addDefaultOptionsif (asocParametersDict's objectForKey:(propertyNameRef's contents)) is missing value then (asocParametersDict's setObject:false forKey:(propertyNameRef's contents))repeat with propertyNameRef in {"help", "version"}(asocParametersDict's setObject:defaultValue forKey:propertyName)if defaultValue is missing value then set defaultValue to current application's NSNull's |null|()error "Missing required option: " & optionName number _ArgvUserErrorif optionName is "--" then set optionName to "-" & rec's shortNameset optionName to "--" & rec's longNameset defaultValue to falseif rec's valueType is boolean thenif defaultValue is NoValue then -- record doesn't have a defaultValue propertyset defaultValue to rec's defaultValueif (asocParametersDict's objectForKey:propertyName) is missing value thenif propertyName is "" then set propertyName to rec's longNameset propertyName to rec's propertyNameset rec to (recRef as record) & {propertyName:"", longName:"", defaultValue:NoValue}repeat with recRef in optionDefinitionsto _addDefaultOptions(asocParametersDict, optionDefinitions)end _parseOptionsreturn {asocParametersDict, rawArguments}asocParametersDict's setObject:theValue forKey:propertyNameerror "Duplicate option: " & optionName number _ArgvUserErrorelse if (asocParametersDict's objectForKey:propertyName) is not missing value thenset theValue to theListtheList's addObject:theValueset theValue to current application's NSMutableArray's arrayWithObject:theValueif theList is missing value thenset theList to asocParametersDict's objectForKey:propertyNameif optionDefinition's isList then -- option can appear multiple times, so collect in a listset theValue to _unpackValue(first item of rawArguments, optionDefinition)if rawArguments is {} then error "Missing value for option: " & optionName number _ArgvUserErrorerror "Bad defaultValue for boolean option: " & optionName number -1700 from (a reference to defaultValue of optionDefinition)set theValue to not optionDefinition's defaultValueif optionDefinition's valueType is boolean thenset propertyName to optionDefinition's propertyNameset optionDefinition to optionDefinition as anyerror "Unknown option: " & optionName number _ArgvUserErrorset rawArguments to {}asocParametersDict's setValue:isVersion forKey:"version"asocParametersDict's setValue:isHelp forKey:"help"asocParametersDict's removeAllObjects()if isHelp or isVersion then -- ignore everything else and return a minimal record containing only `help` and `version` properties, one or both of which are true, so must be dealt with accordingly by `run` handler (i.e. format+log help text and return and/or return version number)set {isHelp, isVersion} to {{optionName} is in {"-h", "--help"}, {optionName} is in {"-v", "--version"}}if hasDefaultOptions thenif optionDefinition is missing value then -- check for default options (help/version), else raise errorelse -- not an option name, so anything left in rawArguments is positional argumentselse --remove the option name from stackset first item of rawArguments to "-" & first item of rawArgumentsif optionDefinition is not missing value and (optionDefinition as any)'s valueType is boolean thenset optionDefinition to optionDefinitionsByName's objectForKey:optionNameset first item of rawArguments to text 3 thru -1 of theArgif theArg's length > 2 then -- put "[-N…]VALUE" back on stack for laterset optionName to text 1 thru 2 of theArg -- get "-N"if theArg is "-" or theArg's character 2 is in "01234567890" then exit repeat -- it's a lone hyphen or a negative number (i.e. not an option), so treat it and rest of rawArguments as positional argumentselse if theArg starts with "-" then -- found "-N[N…][VALUE]" (N is a single-character short option name)else -- remove the option name from stackset first item of rawArguments to text (text item 2) thru -1 of theArgif (count theArg each text item) > 1 then -- put "VALUE" back on stack for laterset optionName to first text item of theArg -- get "--NAME"set rawArguments to rest of rawArgumentsif theArg is "--" then -- double-hypens terminates the option list, so anything left in rawArguments is positional argumentsif theArg starts with "--" then -- found "--[NAME[=VALUE]]" (NAME is a long option name)set theArg to first item of rawArgumentsrepeat until rawArguments is {}set AppleScript's text item delimiters to "=" -- note: a long option can use a space or '=' to separate its name and valueset asocParametersDict to current application's NSMutableDictionary's dictionary()set optionDefinitionsByName to _buildOptionsTable(optionDefinitions)to _parseOptions(rawArguments, optionDefinitions, hasDefaultOptions)end _buildOptionsTablereturn optionDefinitionsByNameif length of foundNames = nameCount then error "Invalid option definition (record must contain a non-empty ‘shortName’ and/or ‘longName’ property)." number -1703 from optionRef(optionDefinitionsByName's setObject:optionDefinition forKey:(namePrefix & theName))if charRef's contents is not in "abcdefghijklmnopqrstuvwxyz1234567890-" then error "Invalid option definition (long name can only contain A-Z, a-z, 0-9 or hyphen characters)." number -1703 from optionRefrepeat with charRef in theNameif theName's length = 0 or theName's character 1 is not in "abcdefghijklmnopqrstuvwxyz" or theName ends with "-" then error "Invalid option definition (long name must start with A-Z or a-z character)." number -1703 from optionRefelse -- validate long nameif (theName's length ≠ 1 or theName is not in "abcdefghijklmnopqrstuvwxyz") then error "Invalid option definition (short name must be a single A-Z or a-z character)." number -1703 from optionRefif namePrefix's length = 1 then -- validate short nameset end of foundNames to theNameif {theName} is in foundNames then error "Invalid option definition (found duplicate short/long name)." number -1703 from optionRefif theName is not "" thenerror "Invalid option definition (short/long name must be text)." number -1700 from optionRefset theName to theName as textset {theName, namePrefix} to aRefrepeat with aRef in {{optionDefinition's shortName, "-"}, {optionDefinition's longName, "--"}}set nameCount to length of foundNameserror "Invalid option definition (property name must be non-empty text)." number -1703 from optionRefif optionDefinition's propertyName is "" then error number -1700set propertyName to optionDefinition's propertyName as textset optionDefinition to (optionRef's contents as record) & {shortName:"", longName:"", propertyName:"", valueType:text, isList:false, defaultValue:false} -- this defaultValue is only used by boolean optsrepeat with optionRef in optionDefinitionsset optionDefinitionsByName to current application's NSMutableDictionary's dictionary()set foundNames to {}to _buildOptionsTable(optionDefinitions)end _formatEnumerationreturn "This must be: " & _joinText(enumList, ", ") & ". "if enumList's length > 1 then set enumList's item -1 to "or " & enumList's item -1set textRef's contents to "“" & (textRef's contents) & "”"repeat with textRef in enumListcopy valueType to enumListto _formatEnumeration(valueType)end _formatDefaultValuereturn "Default: “" & defaultText & "”. "set defaultText to "N"else if defaultValue is false thenset defaultText to "Y"else if defaultValue is true thenset defaultText to POSIX path of defaultValueelse if (count {defaultValue} each «class furl») ≠ 0 or (count {defaultValue} each alias) ≠ 0 thenset defaultText to (asocFormatter's stringFromNumber:defaultValue) as anyelse if (count {defaultValue} each integer) ≠ 0 or (count {defaultValue} each real) ≠ 0 thenset defaultText to defaultValueif (count {defaultValue} each text) ≠ 0 thenif (count {defaultValue} each list) ≠ 0 and length of defaultValue = 1 then set defaultValue to item 1 of defaultValueset defaultValue to defaultValue of definitionRecordto _formatDefaultValue(definitionRecord) -- formats default value for inclusion in OPTIONS/ARGUMENTS sectionend _defaultValuePlaceholderreturn "Y|N"else if valueType is boolean thenreturn "FILE"else if {valueType} is in {«class furl», alias, file, POSIX file} thenreturn "NUMBER"return "INTEGER"else if {valueType} is in {integer, real, number} thenreturn "TEXT"if valueType's class is list then return "OPTION" -- (valueType is list of allowed text values, i.e. an enumeration)to _defaultValuePlaceholder(definitionRecord) -- given an option/argument definition record, returns the appropriate default placeholderValue according to valueTypeend _unpackValueerror "Invalid option/argument definition (not an allowed type)." number -1703 from (a reference to valueType of definitionRecord) to typeerror "Not ‘yes’ or ‘no’ (Y|N): " & theValue number _ArgvUserErrorset theResult to falseelse if {theValue} is in {"false", "no", "f", "n", "0"} thenset theResult to trueif {theValue} is in {"true", "yes", "t", "y", "1"} thenelse if valueType is boolean then -- may be used by boolean argument definitions (boolean options don't take a value)error "File path doesn’t exist: " & theValue number _ArgvUserErroron error number -43 -- file not foundif valueType is alias then set theResult to theResult as aliasset theResult to ((current application's NSString's stringWithString:theValue)'s stringByStandardizingPath()) as text as POSIX fileset theValue to (current application's NSString's pathWithComponents:{basePath, theValue})if basePath is missing value then error "Can't expand relative file path (current working directory is unknown): " & theValue number _ArgvUserErrorset basePath to current application's NSFileManager's defaultManager()'s currentDirectoryPath()if theValue does not start with "/" and theValue does not start with "~" thenelse if {valueType} is in {«class furl», alias, file, POSIX file} then -- note: `file` is treated as synonym for `POSIX file` here, as actual 'file' object specifiers are both mostly pointless and much more problematic due to using HFS pathsset theResult to theResult as integerif theResult mod 1 ≠ 0 then error "Not a valid integer: " & theValue number _ArgvUserErrorif valueType is integer thenset theResult to asocResult as anyif asocResult is missing value then error "Not a valid number: " & theValue number _ArgvUserErrorset asocResult to asocFormatter's numberFromString:theValueasocFormatter's setLocale:(current application's NSLocale's systemLocale())set asocFormatter to current application's NSNumberFormatter's alloc()'s init()else if {valueType} is in {integer, real, number} then -- note: decimal numbers must be in canonical formset theResult to theValueif valueType is text thenelse -- valueType is a type name (text, integer, boolean, etc)set theResult to theValue -- note: the given value is returned as-is, so its case is not guaranteed to be same as in enumeration; client code should normalize value itself as necessaryerror "Not a valid option (" & _joinText(valueType, "/") & "): " & theValue number _ArgvUserErrorif {theValue} is not in valueType thenif valueType's class is list thenset valueType to _asValueType(definitionRecord's valueType)to _unpackValue(theValue, definitionRecord)end _asValueTypereturn valueTypeset valueType to valueType as classelse -- must be type nameerror "Not a list of text." number -1700 from valueType to listif valueType's length = 0 or valueType's length ≠ (count valueType each text) thenif (count {valueType} each list) = 1 then -- list of text = enumeration of allowed valuesto _asValueType(valueType)set theText to theList as textend VT100return (character id 27) & "[" & formatCode & "m"to VT100(formatCode)property Indent2 : " "property Indent1 : " "property LF2 : linefeed & linefeedscript NoValue -- unique constant used to indicate no defaultValue property was givenproperty _ArgvUserError : 10000 -- error code used to indicate the shell script's user supplied invalid command line options (errors due to bugs in invalid option/argument definitions supplied by shell script author use standard AS error codes); need to decide what's a sensible code to use and document it in SDEF (unfortunately, `on error number ...` blocks only accept literal integer (for pattern matching) or identifier (for assignment) and don't allow a command as parameter, so there's no way to supply library-defined error numbers as 'named constants' via library-defined commands, e.g. `on error number (command line user error)`, that return the appropriate number)end split path_error("split path", eText, eNumber, eFrom, eTo)_support's throwInvalidConstantParameter(matchFormat, "at")return (asocPath's pathComponents()) as listelse if splitPosition is all components thenreturn {(asocPath's stringByDeletingPathExtension()) as text, (asocPath's pathExtension()) as text}else if splitPosition is file extension thenreturn {(asocPath's stringByDeletingLastPathComponent()) as text, (asocPath's lastPathComponent()) as text}if splitPosition is last component thenset asocPath to current application's NSString's stringWithString:(_support's asPOSIXPathParameter(filePath, ""))to split path filePath at splitPosition : (last component)end join path_error("join path", eText, eNumber, eFrom, eTo)return asocPath as textif asocPath is missing value then _support's throwInvalidParameter(fileExtension, "using file extension", text, "Invalid file extension.")set asocPath to asocPath's stringByAppendingPathExtension:fileExtensionif fileExtension's length ≠ 0 thenset fileExtension to _support's asTextParameter(fileExtension, "using file extension")set asocPath to (current application's NSString's pathWithComponents:subPaths)_support's throwInvalidParameter(pathComponents, "", list, "Expected one or more text and/or file items.")set aRef's contents to _support's asPOSIXPathParameter(aRef's contents, "")repeat with aRef in subPathsif subPaths is {} then errorset subPaths to items of _support's asListParameter(pathComponents, "")to join path pathComponents using file extension fileExtension : ("")end normalize path_error("normalize path", eText, eNumber, filePath, eTo)return ((current application's NSString's stringWithString:filePath)'s stringByStandardizingPath()) as textreturn ((current application's NSString's stringWithString:filePath)'s stringByResolvingSymlinksInPath()) as textif _support's asBooleanParameter(expandingSymlink, "alias expansion") thenand filePath does not start with "/" then set filePath to join path {current working directory, filePath}if _support's asBooleanParameter(expandingRelative, "absolute expansion") ¬and filePath starts with "~" then set filePath to "./" & filePath -- Cocoa API *always* expands leading "~" character, which it really shouldn't as tilde expansion is a *nix shell-ism, not a POSIX path-ism, so prefix with "./" to prevent thatif not _support's asBooleanParameter(expandingTilde, "tilde expansion") ¬set filePath to _support's asPOSIXPathParameter(filePath, "")absolute expansion expandingRelative : (false) link expansion expandingSymlink : (false)to normalize path filePath tilde expansion expandingTilde : (false) ¬end convert path_error("convert path", eText, eNumber, eFrom, eTo)_support's throwInvalidConstantParameter(toFormat, "to")return (asocURL's absoluteString()) as textif asocURL is missing value then _support's throwInvalidParameter(filePath, "", text "Can’t convert to file URL.")set asocURL to current application's |NSURL|'s fileURLWithPath:posixPathelse if toFormat is file URL format thenreturn posixPath as POSIX file as textelse if toFormat is HFS path format thenreturn a reference to file (posixPath as POSIX file as text) of AppleScriptelse if toFormat is file specifier object then -- returns an _object specifier_ of type 'file'. Caution: unlike alias and «class furl» objects, this is not a true object but may be used by some applications; not to be confused with the deprecated `file specifier` type («class fss»), although it uses the same `file TEXT` constructor. Furthermore, it uses an HFS path string so suffers the same problems as HFS paths. Also, being a specifier, requires disambiguation when used [e.g.] in an `open` command otherwise command will be dispatched to it instead of target app, e.g. `tell app "TextEdit" to open {fileSpecifierObject}`. Horribly nasty, brittle, and confusing mis-feature, in other words, but supported (though not encouraged) as an option here for sake of compatibility as there's usually some scriptable app or other API in AS that will absolutely refuse to accept anything else.return posixPath as POSIX fileelse if toFormat is POSIX file object then -- returns object of type `«class furl»`return posixPath as POSIX file as aliaselse if toFormat is alias file object then -- returns object of type `alias`return posixPathif toFormat is POSIX path format thenif posixPath's length = 0 then _support's throwInvalidParameter(filePath, "", text, "Path can’t be empty.")_support's throwInvalidConstantParameter(fromFormat, "from")if asocURL is missing value or not asocURL's fileURL() then _support's throwInvalidParameter(filePath, "", text, "Not a file URL.")set asocURL to current application's |NSURL|'s URLWithString:filePathelse if fromFormat is file URL format thenset posixPath to POSIX path of (file filePath)else if fromFormat is HFS path format then -- caution: HFS path format is flawed and deprecated everywhere else in OS X (unlike POSIX path format, it can't distinguish between two volumes with the same name), but is still used by AS and a few older scriptable apps so must be supportedset posixPath to filePathif fromFormat is POSIX path format thenelse -- it's a text path in the user-specified format, so convert it to a standard POSIX pathset posixPath to _support's asPOSIXPathParameter(filePath, "")if (count {filePath} each text) = 0 then -- assume it's a file identifier object (alias, «class furl», etc)to convert path filePath from fromFormat : (POSIX path format) to toFormat : (POSIX path format) -- brings a modicum of sanity to the horrible mess that is AppleScript's file path formats and file identifier typesend write to file_error("write file", eText, eNumber, eFrom, eTo)write theData to fh as dataTypeset eof fh to 0 -- important: when overwriting an existing file, make sure its previous contents are erased firstset fh to open for access (posixPath as POSIX file) with write permissionerror (theError's localizedDescription() as text) number theError's code() from theFile to dataTypeif not didSucceed thenset {didSucceed, theError} to asocString's writeToFile:posixPath atomically:true encoding:textEncoding |error|:(specifier)set asocString to current application's NSString's stringWithString:(_support's asTextParameter(theData, "data"))if dataType is text and textEncoding is not primary encoding thento write to file theFile data theData as dataType : (text) using textEncoding : (UTF8 encoding)end read from file_error("read file", eText, eNumber, eFrom, eTo)close access fhset theResult to read fh as dataTypeset fh to open for access (posixPath as POSIX file)if asocString is missing value then error (theError's localizedDescription() as text) number theError's code() from theFile to dataTypeset {asocString, theError} to current application's NSString's stringWithContentsOfFile:posixPath encoding:textEncoding |error|:(specifier)set textEncoding to _NSStringEncodings's getEncoding(textEncoding)if dataType is text and textEncoding is not primary encoding then -- note: AS treats `text`, `string`, and `Unicode text` as synonyms when comparing for equality, which is a little bit problematic as StdAdds' `read` command treats `string` as 'primary encoding' and `Unicode text` as UTF16; passing `primary encoding` for `using` parameter provides an 'out'set dataType to _support's asTypeParameter(dataType, "as")set posixPath to _support's asPOSIXPathParameter(theFile, "")to read from file theFile as dataType : (text) using textEncoding : (UTF8 encoding)_support's throwInvalidConstantParameter(textEncoding, "using")on error number -1700 -- fall throughreturn textEncoding as integeron error number -1700 -- not a predefined constant, but hedge bets as it might be a raw NSStringEncoding numberif aRef's item 1 is textEncoding then return aRef's item 2set textEncoding to textEncoding as constant{WindowsCP1254 encoding, current application's NSWindowsCP1254StringEncoding}}{WindowsCP1253 encoding, current application's NSWindowsCP1253StringEncoding}, ¬{WindowsCP1252 encoding, current application's NSWindowsCP1252StringEncoding}, ¬{WindowsCP1251 encoding, current application's NSWindowsCP1251StringEncoding}, ¬{WindowsCP1250 encoding, current application's NSWindowsCP1250StringEncoding}, ¬{Symbol encoding, current application's NSSymbolStringEncoding}, ¬{ShiftJIS encoding, current application's NSShiftJISStringEncoding}, ¬{NonLossyASCII encoding, current application's NSNonLossyASCIIStringEncoding}, ¬{MacOSRoman encoding, current application's NSMacOSRomanStringEncoding}, ¬{JapaneseEUC encoding, current application's NSJapaneseEUCStringEncoding}, ¬{ISOLatin2 encoding, current application's NSISOLatin2StringEncoding}, ¬{ISOLatin1 encoding, current application's NSISOLatin1StringEncoding}, ¬{ISO2022JP encoding, current application's NSISO2022JPStringEncoding}, ¬{ASCII encoding, current application's NSASCIIStringEncoding}, ¬{UTF32LE encoding, current application's NSUTF32LittleEndianStringEncoding}, ¬{UTF32BE encoding, current application's NSUTF32BigEndianStringEncoding}, ¬{UTF32 encoding, current application's NSUTF32StringEncoding}, ¬{UTF16LE encoding, current application's NSUTF16LittleEndianStringEncoding}, ¬{UTF16BE encoding, current application's NSUTF16BigEndianStringEncoding}, ¬{UTF16 encoding, current application's NSUTF16StringEncoding}, ¬set _list to {¬ {UTF8 encoding, current application's NSUTF8StringEncoding}, ¬script _NSStringEncodings_support's throwCommandError("File", handlerName, eText, eNumber, eFrom, eTo)end reverse comparator_error("reverse comparator", eText, eNumber, eFrom, eTo)return -(continue compareKeys(leftKey, rightKey)) -- flip negative flag to positive and vice-versato compareKeys(leftKey, rightKey)property parent : comparatorObjectscript ReverseComparatorset comparatorObject to _support's asScriptParameter(comparatorObject, "for")set comparatorObject to default comparatorif comparatorObject is missing value thento reverse comparator for comparatorObject : (missing value)end list comparator_error("list comparator", eText, eNumber, eFrom, eTo)return MixedListComparatorset comparisonResult to (itemComparators's item i's itemComparator)'s compareKeys(leftKeyObject's getKey(i), rightKeyObject's getKey(i))repeat with i from 1 to itemComparators's lengthreturn item comparatorIndex of my _keys_set end of _keys_ to comparatorObject's makeKey(subItem)error "Can’t compare item " & (idx as integer) & " of sub-list as it only has " & sublist's length & " items." number -1728 from (a reference to item idx of sublist)set subItem to item idx of my _list_set {itemIndex:idx, itemComparator:comparatorObject} to item comparatorIndex of itemComparatorsrepeat while comparatorIndex > length of my _keys_to getKey(comparatorIndex)property _keys_ : {}script KeyObject -- lazily converts a single sublist's items into comparable keys, caching them for subsequent reusescript MixedListComparator -- compares sublists of same length and variable type_support's throwInvalidParameter(itemComparators, "for", {script, list}, "Not a comparator script object, list of comparator script objects, or list of item comparator records.")set item idx of itemComparators to {itemIndex:idx, itemComparator:item idx of itemComparators}repeat with idx from 1 to length of itemComparatorsset itemComparators to itemComparators's items -- duplicate list before modifying itelse if (count itemComparators each script) = itemComparators's length then -- list of script objects_support's throwInvalidParameter(aRef, "for", list, "Not a valid item comparator record.")if {eNum} is not in {-1700, -1728} then error eMsg number eNum(itemComparator of aRef) as script(itemIndex of aRef) as integerrepeat with aRef in itemComparators -- check list contains item comparator recordsif (count itemComparators each record) = itemComparators's length then -- list of recordsif (count {itemComparators} each record) = 1 then set itemComparators to {itemComparators}return UniformListComparatorreturn 0 -- both lists are identicalreturn 1 -- right sublist is shorter than left sublist, so comes firstelse if leftLength > rightLength thenreturn -1 -- left sublist is shorter than right sublist, so comes firstif leftLength < rightLength thenif comparisonResult ≠ 0 then return comparisonResultset comparisonResult to comparatorObject's compareKeys(leftKeyObject's getKey(i), rightKeyObject's getKey(i))repeat with i from 1 to commonLength -- iterate over item indexes common to both lists, comparing keysif rightLength < commonLength then set commonLength to rightLengthset commonLength to leftLengthset {leftLength, rightLength} to {leftKeyObject's _list_'s length, rightKeyObject's _list_'s length}to compareKeys(leftKeyObject, rightKeyObject)end getKeyreturn item itemIndex of my _keys_set end of _keys_ to comparatorObject's makeKey(item itemIndex of my _list_)repeat while itemIndex > length of my _keys_to getKey(itemIndex)property _keys_ : {} -- cached keysproperty _list_ : sublistscript KeyObjectto makeKey(sublist)script UniformListComparator -- compares sublists of same type and variable lengthset comparatorObject to _support's asScriptParameter(itemComparators, "for")if (count {itemComparators} each script) = 1 then -- compare all sublist items using same comparatorif itemComparators is missing value then set comparatorObject to default comparatorto list comparator for itemComparators : (missing value)end text comparator_error("text comparator", eText, eNumber, eFrom, eTo)_support's throwInvalidConstantParameter(orderingOption, "for")return CurrentConsiderationsComparatorelse if orderingOption is current ordering thenreturn ExactMatchTextComparatorscript ExactMatchTextComparatorelse if orderingOption is exact ordering thenreturn CaseInsensitiveTextComparatorreturn continue compareKeys(leftObject, rightObject)property parent : CurrentConsiderationsComparatorscript CaseInsensitiveTextComparatorif orderingOption is case insensitive ordering thenreturn anObject as text -- caution: some AS types - e.g. reals, lists - are subject to localization/TIDs issues when coercing to text, but there's a practical limit to how much AS insanity a library can protect user from without completely bogging down itselfscript CurrentConsiderationsComparatorto text comparator for orderingOption : (case insensitive ordering)end date comparatorreturn leftObject - rightObject -- as in NumericComparator, a simple subtraction operation produces a suitable resultreturn anObject as datescript DateComparatorto date comparatorend number comparatorreturn leftObject - rightObject -- note: since compareKeys' return value can be any -ve/0/+ve number, a single subtraction operation is sufficient for numbers and dates. (Caveat: this doesn't take into account minor differences due to real imprecision. Currently this doesn't matter as quicksort isn't stable anyway so makes no guarantees about the order of effectively-if-not-exactly-equal real numbers; however, if quicksort ever gets replaced with a stable sorting algorithm then this method will need revised to use Number library's `cmp` instead.)return anObject as numberto makeKey(anObject)script NumericComparatorto number comparatorend default comparatorend compareKeyselse if leftObject > rightObject thenif leftObject < rightObject thento compareKeys(leftObject, rightObject)end makeKeyerror "Invalid item type (default comparator expected " & _type & " but received " & (class of anObject) & ")." number -1700 from anObjectelse if (count {anObject} each _type) = 0 thenerror "Invalid item type (default comparator can only compare integer/real, text, or date types)." number -1700 from anObjectreturn anObjectset _type to aRef's contentsif (count {anObject} each (get aRef's contents)) > 0 thenrepeat with aRef in my _supportedTypesif _type is missing value thenon makeKey(anObject)property _type : missing valueproperty _supportedTypes : {number, text, date}script DefaultComparatorto default comparatorend sort list_error("sort list", eText, eNumber, eFrom, eTo)_sort(resultListObject, 1, resultListObject's _list_'s length, sortComparator, useQuickSort)set useQuickSort to (resultListObject's _list_'s length > _quicksortThreshold) and (disorderedCount / (resultListObject's _list_'s length)) > 0.01 -- if list is small or already 99% in-order then insertion sort is faster than quicksortif disorderedCount > 0 then -- some sorting requirederror eText number eNum from eFrom to eToset previousKey to currentKeyif sortComparator's compareKeys(previousKey, currentKey) > 0 then set disorderedCount to disorderedCount + 1set item i of resultListObject's _keys_ to currentKeyerror "Couldn’t makeKey for item " & i & ": " & eText number eNum from (a reference to item i of (get resultListObject's _list_)) to eToset currentKey to sortComparator's makeKey(item i of resultListObject's _keys_)repeat with i from 2 to resultListObject's _keys_'s lengthset item 1 of resultListObject's _keys_ to previousKeyerror "Couldn’t makeKey for item 1: " & eText number eNum from (a reference to item 1 of (get resultListObject's _list_)) to eToon error eText number eNum to eToset previousKey to sortComparator's makeKey(get item 1 of resultListObject's _keys_)set disorderedCount to 0 -- while generating keys also check if list is already almost/fully sorted and if it is use insertionsort/return as-isset sortComparator to _support's asScriptParameter(sortComparator, "using")set sortComparator to default comparatorif sortComparator is missing value thenif resultListObject's _list_'s length < 2 then return resultListObject's _list_property _list_ : items of theListproperty _keys_ : items of theList -- (replacing items in an existing list of the correct length is a little faster than appending items to a new empty list)to sort list theList using sortComparator : (missing value)end _sortset {item (j - 1) of resultListObject's _list_, item j of resultListObject's _list_} to {get item j of resultListObject's _list_, get item (j - 1) of resultListObject's _list_}set {item (j - 1) of resultListObject's _keys_, item j of resultListObject's _keys_} to {rightKey, leftKey}if sortComparator's compareKeys(leftKey, rightKey) ≤ 0 then exit repeat -- stop when leftKey≤rightKeyset {leftKey, rightKey} to {get item (j - 1) of resultListObject's _keys_, get item j of resultListObject's _keys_}repeat with j from i to startIndex by -1repeat with i from startIndex to endIndexon error number -2706 -- stack overflow, so fall-through to use non-recursive insertion sort (this should rarely happen in practice)_sort(resultListObject, leftIndex, endIndex, sortComparator, endIndex - leftIndex > _quicksortThreshold)_sort(resultListObject, startIndex, rightIndex, sortComparator, rightIndex - startIndex > _quicksortThreshold)set {leftIndex, rightIndex} to {leftIndex + 1, rightIndex - 1}set {item leftIndex of resultListObject's _list_, item rightIndex of resultListObject's _list_} to {get item rightIndex of resultListObject's _list_, get item leftIndex of resultListObject's _list_}set {item leftIndex of resultListObject's _keys_, item rightIndex of resultListObject's _keys_} to {get item rightIndex of resultListObject's _keys_, get item leftIndex of resultListObject's _keys_}if (not leftIndex > rightIndex) thenerror "Couldn’t compare object keys: " & eText number eNum from {item rightIndex of resultListObject's _keys_, pivotValue} to eToset rightIndex to rightIndex - 1repeat while sortComparator's compareKeys(item rightIndex of resultListObject's _keys_, pivotValue) as number > 0 -- while cmp returns 1;error "Couldn’t compare object keys: " & eText number eNum from {item leftIndex of resultListObject's _keys_, pivotValue} to eToset leftIndex to leftIndex + 1repeat while sortComparator's compareKeys(get item leftIndex of resultListObject's _keys_, pivotValue) as number < 0 -- while cmp returns -1; note that if compareKeys() returns a non-numeric value/no result, this will throw -1700/-2763 errorrepeat while leftIndex ≤ rightIndexset pivotValue to some item of items startIndex thru endIndex of resultListObject's _keys_set {leftIndex, rightIndex} to {startIndex, endIndex}if endIndex - startIndex < 1 then returnif useQuickSort then -- sort mostly uses quicksort, but falls through to insertionsort when sorting small number of items (<8), or when sorting a mostly-sorted list, or when quicksort recursion exceeds AS's stack depthto _sort(resultListObject, startIndex, endIndex, sortComparator, useQuickSort) -- performs in-place quicksort/insertionsortproperty _quicksortThreshold : 8 -- shorter ranges are sorted using insertion sort; longer ranges using quicksortend reduce list_errorWithPartialResult("reduce list", eText, eNumber, eFrom, eTo, theResult)from (a reference to item i of _support's asListParameter(theList, "")) to eToerror "Couldn’t reduce item " & i & ": " & eText number eNumber ¬set theResult to reduceObject's reduceItem(theResult, item i of listObject's _list_)repeat with i from 2 to length of listObject's _list_set theResult to item 1 of listObject's _list_set reduceObject to _support's asScriptParameter(reduceObject, "using")if length of listObject's _list_ = 0 then _support's throwInvalidParameter(theList, "", list, "List can’t be empty.")set theResult to missing valueto reduce list theList using reduceObjectend filter list_errorWithPartialResult("filter list", eText, eNumber, eFrom, eTo, ePartial)return resultListObject's _list_'s items 1 thru lastIndexif lastIndex = 0 then return {}error "Couldn’t filter item " & i & ": " & eText number eNumber ¬set ePartial to items 1 thru (lastIndex - 1) of resultListObject's _list_if lastIndex > 1 thenset item lastIndex of resultListObject's _list_ to theItemset lastIndex to lastIndex + 1if filterObject's filterItem(theItem) thenset theItem to item i of resultListObject's _list_repeat with i from 1 to length of resultListObject's _list_set lastIndex to 0to filter list theList using filterObjectend map list_errorWithPartialResult("map list", eText, eNumber, eFrom, eTo, ePartial)from (a reference to item i of _support's asListParameter(theList, "")) to eTo partial result ePartialerror "Couldn’t map item " & i & ": " & eText number eNumber ¬set ePartial to {}set ePartial to items 1 thru (i - 1) of resultListObject's _list_on error eText number eNumber to eToset item i of resultListObject's _list_ to mapObject's mapItem(item i of resultListObject's _list_)repeat with i from 1 to length of resultListObject's _list_ -- use counting loop rather than `repeat with aRef in theList` as the item's index is also used when constructing error messagesset mapObject to _support's asScriptParameter(mapObject, "using")to map list theList using mapObjectend find in list_error("find in list", eText, eNumber, eFrom, eTo)return listObject's _result__support's throwInvalidConstantParameter(findingOccurrences, "returning")repeat with i from length of listObject's _list_ to 1 by -1else if findingOccurrences is last occurrence thenelse if findingOccurrences is first occurrence thenif filterObject's filterItem(item i of listObject's _list_) thenset filterObject to _support's asScriptParameter(filterObject, "using")set end of listObject's _result_ to iif item i of listObject's _list_ is theItem thenrepeat with i from 1 to length of listObject's _list_if filterObject is missing value thenif findingOccurrences is all occurrences thenproperty _result_ : {}to find in list theList value theItem : (missing value) using filterObject : (missing value) returning findingOccurrences : (all occurrences)end unsort list_error("unsort list", eText, eNumber, eFrom, eTo)return resultListObject's _list_set {resultListObject's _list_'s item idx1, resultListObject's _list_'s item idx2} to {get resultListObject's _list_'s item idx2, get resultListObject's _list_'s item idx1}set idx2 to random number from 1 to lenrepeat with idx1 from 1 to lenset len to length of resultListObject's _list_property _list_ : items of _support's asListParameter(theList, "")script resultListObjectto unsort list theListend transpose list_error("transpose list", eText, eNumber, eFrom, eTo)return listObject's _resultList_repeat with j from 1 to resultListLengthset item i of item j of listObject's _resultList_ to item j of item i of listObject's _list_repeat with j from 1 to length of listObject's _list_'s item irepeat with i from 1 to resultSubListLengthif unevenOption is padding uneven lists thenset end of listObject's _resultList_ to (get resultSubList's items) -- shallow copyrepeat with i from 2 to resultListLengthset end of listObject's _resultList_ to resultSubListset resultSubList to _makeListObject(resultSubListLength, padValue)set resultSubListLength to length of listObject's _list_if resultListLength > 0 then_support's throwInvalidConstantParameter(unevenOption, "by")if aRef's length < resultListLength then set resultListLength to aRef's lengthelse if unevenOption is trimming uneven lists thenif aRef's length > resultListLength then set resultListLength to aRef's lengthelse if unevenOption is padding uneven lists thenif aRef's length ≠ resultListLength then _support's throwInvalidParameter(theList, "", list, "Sublists are not all same length.")if unevenOption is rejecting uneven lists thenset resultListLength to length of listObject's _list_'s item 1property _resultList_ : {}property _list_ : theList_support's throwInvalidParameter(theList, "", list, "Not a list of lists.")if (count {theList} each list) = 0 or (count theList each list) ≠ (count theList) thenif theList is {} then return {}to transpose list theList by unevenOption : (rejecting uneven lists) padding with padValue : (missing value)end slice list_error("slice list", eText, eNumber, eFrom, eTo)return items startIndex thru endIndex of theListor startIndex > theLength and endIndex > theLength then return {}return theList's items 1 thru endIndexif endIndex = 0 then _support's throwInvalidParameterIndex(endIndex, "to item")set endIndex to _support's asIntegerParameter(endIndex, "to item")error "Expected ‘from item’ and/or ‘to item’ parameter but received neither." number -1701return theList's items startIndex thru -1return theList's itemsif startIndex = 0 then _support's throwInvalidParameterIndex(startIndex, "from item")set startIndex to _support's asIntegerParameter(startIndex, "from item")set theLength to theList's lengthset theList to _support's asListParameter(theList, "")to slice list theList from item startIndex : (missing value) to item endIndex : (missing value)end remove duplicates from list_error("remove duplicates from list", eText, eNumber, eFrom, eTo)return listObject's _list_'s items 1 thru uset listObject's _list_'s item u to listObject's _list_'s item iset u to u + 1if i > listLength then return listObject's _list_'s items 1 thru urepeat while {listObject's _list_'s item i} is in listObject's _list_'s items 1 thru urepeat until i > listLengthif listLength = 0 then return {}set {i, u, listLength} to {2, 1, listObject's _list_'s length}property _list_ : _support's asListParameter(theList, "")'s itemsto remove duplicates from list theListend delete from list_error("delete from list", eText, eNumber, eFrom, eTo)return startList & endListset endList to listObject's _list_'s items (endIndex + 1) thru -1set endList to {}if endIndex = listLength thenset startList to listObject's _list_'s items 1 thru (startIndex - 1)set startList to {}if startIndex = listLength or endIndex = listLength then return {}if startIndex = 1 thenif startIndex > endIndex then return listObject's _list_'s items���%aͦ�k���P{���*X��Q��� 8Y����>���4Kk�� I u � � + N � �  & I � J f � � � � ' D j � � � %>p��%a��L��-w���&`�L���7|���`����d��9L����"=^��}��1f���8Ro���0Nf���/U~��/^���� 4 U r � � !!S!�!�!4"I"�"�"#1#@#[#�#�#�#�#�#8$�$�$s%�%�%�%0&]&y&�&'0'I''�'�'�'>(m(�(�(�( )S)h)�)�)*<*f*�*�*�*)+Z+y+�+,$,@,],�,�,-J-y-�-�-�-�- .U.�.�.�./Y/}/�/�0�0!1�1�1 292z2�23=3n3�3�3�3 4G4�4�4 5?5�5�5�56:6e6�6�6�6#7P7e7�7�7�78D8v8�8�89?9�9 :g:u:�:$;c;�;�;�;'<S<r<�<�<�<=)=9>p>�>�>�>K?k?�?�?@$@D@X@�@�@�@�@!A�A�A�A|B�B�B C+CgCDD2DYDpD�D�D�D EEE�E�E�E%F]F�F�F�F�FjG�G�G�G�GH1HFH�H�H�H�H�H$IMIeI�I�I�IJ7JQJ|J�J�J�JKLKgKxK�K�K�K/LWL|L�L�LWM�MNBN�N�N�NGOpO�O P]P�PROR�R�R&S�S&T^T�TUURUxU�U�U7VMVxV�V�V�V�VXDX^X�X�X�XYPYYY`YuY}Y�Y�Y�Y%ZmZ�Z�Z&[B[z[�[�[\A\o\�\�\�\D]c]�]�] ^H^p^�^�^ _<_g_�_�_�_```�`aZapa�a�ab(b�b�b#c�cdLd�d�d�d�d e1efe�e�e-fvfgag�g�g:hjh�h�h�h�hci�i?j`j�jk'khk�klEl�l�l.m�m�m�m5non�noCo�opQplp�p�pqQq�q�qr:rWrjr�r�r�r s7sfs�s�s�s�s�s t;tOt{t�t�t�t u?ucuv(vUv�v�v w w\w�w�w�wxOxnx�x�x�x$y]yvy�y�yzFzzz�z�z�z{5{r{�{�{�{|3|K|q|�|�|�|2}d}z}�}�}~9~f~�~�~�~B�����4�O�s���ÀӀ��.�D�S�������� ��=�T�}���Ƃ�4�X�h�����P�����ބ�X�����ȅ���9�n�������І ��_���‡���+�]�������H�v���ɉ�!�K�v���݊�?�c�����P�������.�T�x�������C�z����&�u���͏�D�f�������F�b���ߑ'�L�Ҕ#�N�u�����Q���–��/�J�w�����ٗ�?�x���ؘ�$�W���ԙ�V�q�����U�����ϛ���.�M�p�������F�Z���՝��3�G�x������D���Ο�:�m���ؠ�+�\�����ס��9�U�q����I��$���������V��������4�@�q�ۦ+�Q�v�ȧ<�s��&�[���ȩ����������5�p�Ԭ.�s����ˮ�Q���ԯ`���ް�U���ɱ��/�W���۲�F�}�ݳ�F�������ε�m���öA�y���ķ��D�q����/�o���عz������9�������S�s���� �s�����/�D�^�����ž� �"�2�H�X�x����F�q���������e��� ����D������E�z������O�������)�G�c����� �9�M���������?�b�����'�f�����+����� �I�h��������R��� �"�X������/�R����� �1�T������0�V���������8������R�l������/�����6����.�>�T�����"�V�y������B�p�����5�^�������"�G�z����_��������A�i����������8�V��������0�B�V�u���������g������C������������'�=�]�y������� �5������� �?�|����-�E�V�i��������!�3�N�f����������=�R�y������� �3�������w����A�j��� �e���J�{�������1�W�~��������@�a��������� �6�l������C�t����������%�7�g�v�������J�x�����#�����/�H�s���������� ��3�����������"�J�q������>�Y��������J��������7�H�����:�������.�W����� �E�b����� �:�u�������]�=L���7 ��"�3r������ -Be����S�� � � � � � + q � C � � � � �   $ < R  �   N Y � � � � �  "Hd����)Alz�����8p�����-k~����AQl�������z�i����2��$j���?���U� S{�2Q{��S���Nn���/n��# 9 � �  !%!]!�!�!E"�"�"#R#�#�#$:$M$�$�$�$�$*%A%b%�%�%&&N&�&(_(�(�(,)b)o)�)�);*x*�*+[+�+�+T,g, -/-.�.�.R/p/�/�/_0�0�01#1>1e1�1�1�1�12>2Z2~2�2�2�2�2�2�34>4n4�4B5c5�56�6&7�7�7G8�8�869�9�9Z:�:5;�;'<�<�<m=�=�=G>�>l?�?Q@�@�@ ATA�A�A�ABPB�B�B�B{C�CbD�DEhE�EFdF�F�FJG�G+HzH I�I�I>J�J�JK�K�K3L�L�L5M�M�MJN�N�N�N O@OWOyO�O/P�P�P:QsQ�QR�R�RSS�S�S!T�T�T0UlU�U;V�V�VWWW�WAX�X�Y8Z�Z�Z�[�[J\�\]S]�]^p^�^._l_�_`[`�`aGa�a bcb�b�bqc�c�d�de/eje�e�e�ef@f�f�f g�g+heh�hifi�i�i3jkj�jkk:k\kwk�k�k�klnl�l�l5m�m�mn(n:n[n�n�n�n�no*o������I���Z����b�ݒ�V���̓�=�v����$�]���˕ח��.�c����!�8�O�p����������+�A�h���f�{����C���ӡ�<�����ϣ�`�#�d�����i�ħ�R�}����)�^���ݪ�ȫ������3�W�{�s�&�O�G����Z�ڲ��"�� �̴(�^�S���r����C���"�������z�������L���_�}��� � �5�{������u���$�\���M��&�~�F�Z������+�?�W��������z�����9�v���`� ����X�q�������������Q�j���!�G�n�����2���1�����i���L���=�{������G���o�����%������z���$�����G�����t���N���?�e�w�����"�O��������� �C�X���'�m���k���������)���a�+���1���,���=���s��z�����9���7���7���@���E���@�m���f�������O���M���J�/���7�{��0�4�Ls��{2�8 � , � �  � � I��0y����]�7�n�*��K�z�:��\�'��P � #!�!�!D"�"#J#�#�#5$�$�$%h%�%&d&�&'Z'�'�':(�(�(,)x)�)�) *,*Y*|*�*@+e+�+#,E,V-�-�.�./]/�/�/)0O0z0�0'1�1^2�2/3�34g4�4V56O6�6.7�7f8�849�9�9O:�:{;�;+<C<�<[=�=�=G>�>?�?Y@�@�@kA�A�B�CpDEiEqF�FG�GbH8I�IJ?JOJiJ�J�J�JKJK�KCL�LM�MRN�N:OkO�O%PdP|P�P�PQ�Q!R�R$SVS�S�ST:T�T�T2UV�V!WRW�W#X�X�Y�YZ�Z�ZQ[�[�[0\w\�\.]<]M]p]�]�]�]�]^�^�^_�_�`QajaJb�b8czc�cId�de�e�f�g�g]h�h/i�i�i�ij9j�j�jk�kVlmm#mSm�mnWn�n�n-o}o�o.p�p�p2qaqxq�q�q3r�r�r�s�s+t�t$u�u vCv�v@w�w@x}x�x�x�xyy=y�y�y:z�zv{�{�{n| }�}~�~��Հ6�с.�˂����΃v� �j�����ˇ+������c���9�V����T���*��� �x��M���-�����&�S������l��r����M�[��r�"���%�S�����#�M��2�h�������B�Y���M�F�w���ޠ)��P���٢v�ѣ$�l�Ѥ-�^���G�ݦ)��������L����j����m�Y�����g�����p�P����������#�ȱ��Q���B���Ĵ/�ҵ�6�r����»Y�0�k����������� ������Q��� ����g��� ���S���*����&�3�B�X����t������ �7�����k�Text's length < (widthToAdd + padSize)set padText to padText & padTexset {theButtons, minWidth} to create buttons {theButtonsVisitLabel, theButtonsEmailLabel, theButtonOKLabel} button keys {"v", "e", ""} default button 3set theButtonsEmailLabel to localized string "Send E-Mail" from table "MacYTDL"set theButtonsVisitLabel to localized string "Visit Site" from table "MacYTDL"set accViewWidth to 300set about_diag_prompt to theButtonsAboutDiagLabelset theButtonsAboutDiagLabel to localized string "About MacYTDL" from table "MacYTDL"set about_text_2 to theButtonsAbout2Label & return & return & theButtonsAbout3Label & MacYTDL_date & ". " & theButtonsAbout4Labelset theButtonsAbout4Label to localized string "With thanks to Shane Stanley, Adam Albrec, kopurando, Michael Page, Tombs and all MacYTDL users." from table "MacYTDL"set theButtonsAbout3Label to localized string "Written by © Vincentius, " from table "MacYTDL"set theButtonsAbout2Label to localized string "Please post any questions or suggestions to github.com/section83/MacYTDL/issues" from table "MacYTDL"set about_text_1 to theButtonsAbout1Labelset theButtonsAbout1Label to (localized string "MacYTDL is a simple AppleScript program for downloading videos from various web sites. It uses the" from table "MacYTDL") & " " & DL_Use_YTDLP & " " & (localized string "Python script as the download engine." from table "MacYTDL")on show_about()end utilitiesmy show_about()else if utilities_button_number_returned is 3 then -- Aboutdisplay dialog theUtilitiesMYTDLUninstalledLabel buttons {theUtilitiesMYTDLUninstalledByeLabel} default button 1 with icon file MacYTDL_custom_icon_file_Trash giving up after 600set MacYTDL_custom_icon_file_Trash to (path_to_home_folder & ".Trash:MacYTDL.app:Contents:Resources:MacYTDL.icns") as stringset theUtilitiesMYTDLUninstalledByeLabel to localized string "Goodbye" from table "MacYTDL"set theUtilitiesMYTDLUninstalledLabel to localized string "MacYTDL is uninstalled. All components are in the Trash which you can empty when you wish. Cheers." from table "MacYTDL"tell current application to do shell script "mv " & quoted form of (macYTDL_defaults_preferences_file) & " ~/.trash/com.apple.script.id.MacYTDL.plist"if (the file macYTDL_defaults_preferences_file exists) thendo shell script "mv " & quoted form of (macYTDL_service_file) & " ~/.trash/Send-URL-To-MacYTDL.workflow"set macYTDL_defaults_preferences_file to (POSIX path of (path to home folder) & User_defaults_path)set User_defaults_path to "Library/Preferences/com.apple.script.id.MacYTDL.plist"do shell script "mv " & quoted form of (POSIX path of DTP_file) & " ~/.trash/DialogToolkitMacYTDL.scptd" -- Quoted form because of space in "Script Libraries" folder namedo shell script "mv " & POSIX path of MacYTDL_preferences_path & " ~/.trash/MacYTDL"do shell script "mv " & path_to_macytdl_file & " ~/.trash/MacYTDL.app" with administrator privilegesset path_to_macytdl_file to quoted form of (POSIX path of path_to_MacYTDL)do shell script "mv " & POSIX path of ffmpeg_file & " ~/.trash/ffmpeg" with administrator privilegesif ffmpeg_exists is true thendo shell script "mv " & POSIX path of ffprobe_file & " ~/.trash/ffprobe" with administrator privilegesif ffprobe_exists is true thendo shell script "mv " & POSIX path of ytdlp_file & " ~/.trash/yt-dlp" with administrator privilegesif ytdlp_exists is true thendo shell script "mv " & POSIX path of youtubedl_file & " ~/.trash/youtube-dl" with administrator privilegesif YTDL_exists is true thendo shell script "mv /usr/local/bin/AtomicParsley" & " ~/.trash/AtomicParsley" with administrator privilegesif remove_answ is theButtonNoLabel thenset remove_answ to button returned of really_remove_MacYTDLset really_remove_MacYTDL to display dialog theUtilitiesUninstallLabel buttons {theButtonYesLabel, theButtonNoLabel} with title diag_Title default button 2 with icon file MacYTDL_custom_icon_file giving up after 600set theUtilitiesUninstallLabel to localized string "Do you really want to remove MacYTDL ? Everything will be moved to the Trash." from table "MacYTDL"else if utilities_button_number_returned is 2 thendisplay dialog theUtilitiesDeleteLogsLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 100set theUtilitiesDeleteLogsLabel to localized string "All MacYTDL log files are now in the Trash." from table "MacYTDL"do shell script "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_response-[ABCDEabcde]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_response-[FGHIJKLMNfghijklmn]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_response-[OPQRSTUVWXYZopqrstuvwxyz]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_response-[1234567890#~!@$%^]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_response-*" & " ~/.trash/"do shell script "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_log-[ABCDEabcde]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_log-[FGHIJKLMNfghijklmn]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_log-[OPQRSTUVWXYZopqrstuvwxyz]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_log-[1234567890#~!@$%^]*" & " ~/.trash/" & " ; " & "mv " & POSIX path of MacYTDL_preferences_path & "youtube-dl_log-*" & " ~/.trash/"else if utilities_button_number_returned is 1 then -- Delete logsdisplay dialog theServiceRemovedLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 100set theServiceRemovedLabel to localized string "The MacYTDL Service has been removed." from table "MacYTDL"run_Utilities_handlers's remove_MacYTDLservice()set Service_file_plist to (macYTDL_service_file_nonPosix & ":Contents:info.plist")if reallyWantsAPRemoved is theButtonReturnLabel then main_dialog()set reallyWantsAPRemoved to button returned of (display dialog theAutoDLisOnLabel with title diag_Title buttons {theButtonReturnLabel, theButtonRemoveLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600)set theAutoDLisOnLabel to localized string "You have the Auto downloads setting on. You can cancel and return to Main dialog or remove the Service and turn off auto downloads." from table "MacYTDL"set theButtonRemoveLabel to localized string "Remove" from table "MacYTDL"if DL_auto is true thenelse if isServiceInstalled is "Yes" thendisplay dialog theServiceInstalledLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 100set theServiceInstalledLabel to localized string "The MacYTDL Service is installed." from table "MacYTDL"if utilities_Service_choice is true thenrun_Utilities_handlers's remove_MacYTDLatomic(path_to_MacYTDL, theButtonOKLabel, diag_Title, MacYTDL_custom_icon_file)else if Atomic_is_installed is true thenrun_Utilities_handlers's install_MacYTDLatomic(diag_Title, theButtonOKLabel, path_to_MacYTDL, usr_bin_folder)if reallyWantsAP is theButtonNoLabel then main_dialog()set reallyWantsAP to button returned of (display dialog theDontNeedAPTextLabel with title diag_Title buttons {theButtonNoLabel, theButtonYesLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600)set theDontNeedAPTextLabel to localized string "You are currently using yt-dlp and so there is no need for Atomic Parsley. Do you still wish to install Atomic Parsley ?" from table "MacYTDL"if Atomic_is_installed is false thenif utilities_Atomic_choice is true thenrun_Utilities_handlers's check_MacYTDL(downloadsFolder_Path, diag_Title, theButtonOKLabel, theButtonNoLabel, theButtonYesLabel, MacYTDL_version, MacYTDL_custom_icon_file)if utilities_MacYTDL_check_choice is true thenif Really_Return_To_Defaults is theButtonYesLabel thenset Really_Return_To_Defaults to button returned of (display dialog theReturnSettingsLabel with title diag_Title buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with icon file MacYTDL_custom_icon_file giving up after 600)set theReturnSettingsLabel to localized string "Do you really want to return to the default settings ?" from table "MacYTDL"if utilities_Return_Defaults_choice is true thenset value of property list item "Saved_Settings_Location" to DL_Saved_Settings_Locationset value of property list item "Name_Of_Settings_In_Use" to restored_settings_namedo shell script "cp -a " & restore_settings_file_name_posix & " " & MacYTDL_prefs_fileset restored_settings_name to text (last_colon_in_path + 2) thru last_stop_in_path of restore_settings_file_name_textset last_stop_in_path to last_offset(restore_settings_file_name_text, ".")set last_colon_in_path to last_offset(restore_settings_file_name_text, ":")if restore_or_giveup is theButtonNoLabel thenset restore_or_giveup to button returned of (display dialog theCannotRestoreLabel with title diag_Title buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with icon file MacYTDL_custom_icon_file giving up after 600)set theCannotRestoreLabel to localized string "Sorry, can't restore settings file to itself. Try again ?" from table "MacYTDL"if restore_settings_file_name_posix = quoted form of MacYTDL_prefs_file thenset restore_settings_file_name_posix to quoted form of (POSIX path of restore_settings_file_name) -- Need quoted posix form to pass to do shell scriptset restore_settings_file_name_text to restore_settings_file_name as textset restore_settings_file_name to choose file with prompt "Choose a settings file to restore:" default location DL_Saved_Settings_Location_Alias of type "plist"if utilities_Restore_Settings_choice is true thenset value of property list item "Saved_Settings_Location" to path_to_saved_settings_locationset path_to_saved_settings_location to text 1 thru last_colon_in_path of save_settings_file_name_textset last_colon_in_path to last_offset(save_settings_file_name_text, ":")do shell script "cp -a " & MacYTDL_prefs_file & " " & save_settings_file_name_posixset save_settings_file_name_posix to quoted form of (POSIX path of save_settings_file_name)set save_settings_file_name_posix to quoted form of ((POSIX path of save_settings_file_name) & ".plist") -- Need quoted posix form to pass to do shell scriptif text -5 thru -1 of save_settings_file_name_text is not "plist" thenset save_settings_file_name_text to save_settings_file_name as texton error number -128 -- If user cancels, go back to Main dialogset save_settings_file_name to (choose file name with prompt "Save MacYTDL Settings" & return & "Enter a file name and choose a location" default location DL_Saved_Settings_Location_Alias default name "Name for your saved settings")set DL_Saved_Settings_Location_Alias to DL_Saved_Settings_Location as aliasif utilities_Save_Settings_choice is true thenif alert_text_ytdl does not contain "is out of date" thenif choiceMainOrBrewYTDL is theButtonYesLabel thenset choiceMainOrBrewYTDL to button returned of (display dialog thePreferMainOrBrewYTDLPInstallTextLabel with title diag_Title buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with icon file MacYTDL_custom_icon_file giving up after 600)set thePreferMainOrBrewYTDLPInstallTextLabel to localized string "You currently have a Homebrew install of YT-DLP. Do you wish to switch to a MacYTDL install ?" from table "MacYTDL"if ytdlp_exists is false and homebrew_ytdlp_exists is true thencheck_ytdl(show_yt_dlp)if ytdlp_exists is false and homebrew_ytdlp_exists is false thenset user_wants_switch to "yt-dlp"set alert_text_ytdl to "Switching"if utilities_Switch_choice is true thenopen location "https://github.com/yt-dlp/yt-dlp"open location "https://github.com/ytdl-org/youtube-dl"if utilities_YTDL_webpage_choice is true thenrun_Utilities_handlers's install_ffmpeg_ffprobe(theButtonOKLabel, diag_Title, path_to_MacYTDL, usr_bin_folder, resourcesPath, MacYTDL_custom_icon_file, user_on_old_os, new_FFmpeg_arch)if switch_FFmpeg is theButtonYesLabel thenset switch_FFmpeg to button returned of (display dialog (theFFmpegSwitchLabel & " " & installed_FFmpeg_arch & theFFmpegToLabel & new_FFmpeg_arch & " ?") buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theFFmpegToLabel to localized string " to " from table "MacYTDL"set theFFmpegSwitchLabel to localized string "Switch FFmpeg and FFprobe from" from table "MacYTDL"if utilities_FFmpeg_switch_choice is true thendisplay dialog alert_text_ytdl & return with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600else if utilities_YTDL_check_choice is true and utilities_FFmpeg_check_choice is not true thendisplay dialog alert_text_ffmpeg & return & return with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600else if utilities_FFmpeg_check_choice is true and utilities_YTDL_check_choice is not true thendisplay dialog alert_text_ytdl & return & alert_text_ffmpeg with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600check_ffmpeg()set alert_text_ffmpeg to theFFmpegProbeInstalledAlertLabelset theFFmpegProbeInstalledAlertLabel to localized string "FFmpeg and FFprobe have been installed." from table "MacYTDL"if ffmpeg_version is "Not installed" thenif utilities_YTDL_check_choice is true and utilities_FFmpeg_check_choice is true thenset the position of the front Finder window to {100, 100} -- <= This DOES work but is ugly - it opens the window then moves it to a location which should not overlap Main Dialogopen (downloadsFolder_Path as POSIX file) -- <= Had to read prefs again to get this working - something to do with this path in Main Dialogcheck_download_folder(downloadsFolder_Path)if utilities_DL_folder_choice is true thenset the position of the front Finder window to {200, 200}open (MacYTDL_preferences_path as POSIX file)if utilities_log_folder_choice is true thenset utilities_log_folder_choice to item 14 of utilities_controls_results -- <= Open log folder choiceset utilities_DL_folder_choice to item 13 of utilities_controls_results -- <= Open download folder choiceset utilities_YTDL_check_choice to item 12 of utilities_controls_results -- <= Check YTDL/yt-dlp version choiceset utilities_YTDL_webpage_choice to item 11 of utilities_controls_results -- <= Show YTDL/yt-dlp web page choiceset utilities_Switch_choice to item 10 of utilities_controls_results -- <= Switch downloaders choiceset utilities_Restore_Settings_choice to item 9 of utilities_controls_results -- <= Restore saved settings choiceset utilities_Save_Settings_choice to item 8 of utilities_controls_results -- <= Save current settings choiceset utilities_Return_Defaults_choice to item 7 of utilities_controls_results -- <= Return to default settings choiceset utilities_MacYTDL_check_choice to item 6 of utilities_controls_results -- <= Check MacYTDL version choiceset utilities_FFmpeg_check_choice to item 5 of utilities_controls_results -- <= Check FFmpeg version choiceset utilities_FFmpeg_switch_choice to item 4 of utilities_controls_results -- <= Switch FFmpeg architectureset utilities_Atomic_choice to item 3 of utilities_controls_results -- <= Install Atomic Parsley choiceset utilities_Service_choice to item 2 of utilities_controls_results -- <= Install Service choiceif utilities_button_number_returned is 5 then -- Startset {utilities_button_returned, utilities_button_number_returned, utilities_controls_results, finalPosition} to display enhanced window diag_Title buttons theButtons acc view width minWidth acc view height theTop acc view controls utilities_allControls initial position window_Positionset utilities_allControls to {theUtilitiesRule, utilities_theCheckbox_Service_Install, utilities_theCheckbox_Atomic_Install, utilities_theCheckbox_SwitchFFmpeg, utilities_theCheckbox_FFmpeg_Check, utilities_theCheckbox_MacYTDL_Check, utilities_theCheckbox_Return_Defaults, utilities_theCheckbox_Save_Settings, utilities_theCheckbox_Restore_Settings, utilities_theCheckbox_Switch_Scripts, utilities_theCheckbox_YTDL_release, utilities_theCheckbox_YTDL_Check, utilities_theCheckbox_DL_Open, utilities_theCheckbox_Logs_Open, MacYTDL_icon, utilities_instruct, utilities_prompt}set {utilities_prompt, theTop} to create label utilities_diag_prompt left inset 0 bottom (theTop) max width minWidth aligns center aligned with bold typeset {utilities_instruct, theTop} to create label instructions_text left inset accViewInset + 5 bottom (theTop + 10) max width minWidth - 100 aligns left aligned with multilineset {utilities_theCheckbox_Logs_Open, theTop} to create checkbox theCheckBoxOpenLogFolderLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxOpenLogFolderLabel to localized string "Open log folder" from table "MacYTDL"set {utilities_theCheckbox_DL_Open, theTop} to create checkbox theCheckBoxOpenDLFolderLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxOpenDLFolderLabel to localized string "Open download folder" from table "MacYTDL"set {utilities_theCheckbox_YTDL_Check, theTop} to create label " " left inset accViewInset + 5 bottom (theTop - 17) max width minWidth - 100 aligns left aligned with multilineset {utilities_theCheckbox_YTDL_Check, theTop} to create checkbox theCheckBoxCheckYTDLversion left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxCheckYTDLversion to theCheckBoxCheckYTDLLabel & " " & "(" & theYTDLVersionInstalledlabel & ")"set theCheckBoxCheckYTDLLabel to (localized string "Check for" from table "MacYTDL") & " " & utilities_DL_Use_YTDLP & " " & (localized string "update" from table "MacYTDL")if ytdlp_exists is true and (DL_Use_YTDLP is "yt-dlp" or DL_Use_YTDLP is "yt-dlp-legacy") thenset {utilities_theCheckbox_YTDL_release, theTop} to create checkbox theCheckBoxOpenYTDLLabel left inset accViewInset bottom (theTop + 5) max width 200set theCheckBoxOpenYTDLLabel to (localized string "Open" from table "MacYTDL") & " " & utilities_DL_Use_YTDLP & " " & (localized string "web page" from table "MacYTDL")set utilities_DL_Use_YTDLP to "yt-dlp"set {utilities_theCheckbox_Switch_Scripts, theTop} to create label " " left inset accViewInset + 5 bottom (theTop - 17) max width minWidth - 100 aligns left aligned with multilineset utilities_DL_Use_YTDLP to "youtube-dl"set {utilities_theCheckbox_Switch_Scripts, theTop} to create checkbox theCheckBoxSwitchScriptsLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxSwitchScriptsLabel to localized string "Switch to yt-dlp" from table "MacYTDL"set {utilities_theCheckbox_Save_Settings, theTop} to create checkbox theCheckBoxSaveSettingsLabel left inset accViewInset bottom (theTop + 5) max width 200set theCheckBoxSaveSettingsLabel to localized string "Save current settings" from table "MacYTDL"set {utilities_theCheckbox_Restore_Settings, theTop} to create checkbox theCheckBoxRestoreSettingsLabel & " " & current_settings_installed left inset accViewInset bottom (theTop + 5) max width 200set theCheckBoxRestoreSettingsLabel to localized string "Restore settings" from table "MacYTDL"set {utilities_theCheckbox_Return_Defaults, theTop} to create checkbox theCheckBoxReturnDefaultsLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxReturnDefaultsLabel to localized string "Return to default settings" from table "MacYTDL"set {utilities_theCheckbox_MacYTDL_Check, theTop} to create checkbox theCheckBoxCheckMacYTDLLabel left inset accViewInset bottom (theTop + 5) max width 200set theCheckBoxCheckMacYTDLLabel to localized string "Check for MacYTDL update" from table "MacYTDL"set {utilities_theCheckbox_FFmpeg_Check, theTop} to create label " " left inset accViewInset + 5 bottom (theTop - 17) max width minWidth - 100 aligns left alignedset {utilities_theCheckbox_FFmpeg_Check, theTop} to create checkbox theCheckBoxCheckFFmpegversion left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxCheckFFmpegversion to theCheckBoxCheckFFmpegLabel & " " & "(" & FFMpeg_version_installed & ")"set theCheckBoxCheckFFmpegLabel to localized string "Check for FFmpeg update" from table "MacYTDL"if homebrew_ffmpeg_exists is false thenset {utilities_theCheckbox_SwitchFFmpeg, theTop} to create label " " left inset accViewInset + 5 bottom (theTop - 17) max width minWidth - 100 aligns left alignedset {utilities_theCheckbox_SwitchFFmpeg, theTop} to create checkbox theCheckBoxSwitchFFmpegLabel left inset accViewInset bottom (theTop + 5) max width 200set theCheckBoxSwitchFFmpegLabel to theCheckBoxSwitchFFmpegLabel2 & " " & new_FFmpeg_archset theCheckBoxSwitchFFmpegLabel2 to localized string "Switch FFmpeg to" from table "MacYTDL"if user_system_arch is "arm64" and homebrew_ffmpeg_exists is false thenset new_FFmpeg_arch to "Intel"set new_FFmpeg_arch to "ARM"set installed_FFmpeg_arch to "Intel"if ffmpeg_version_arch is "tessus" thenset installed_FFmpeg_arch to "ARM"set switch_FFmpeg to "No"set ffmpeg_version_arch to text item 4 of ffmpeg_version_longset {utilities_theCheckbox_Atomic_Install, theTop} to create checkbox theCheckBoxInstallAtomicLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxInstallAtomicLabel to localized string "Install Atomic Parsley" from table "MacYTDL"set {utilities_theCheckbox_Atomic_Install, theTop} to create checkbox theCheckBoxRemoveAtomicLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxRemoveAtomicLabel to localized string "Remove Atomic Parsley" from table "MacYTDL"if Atomic_is_installed is true thenset {utilities_theCheckbox_Service_Install, theTop} to create checkbox theCheckBoxInstallServiceLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxInstallServiceLabel to localized string "Install Service" from table "MacYTDL"set {utilities_theCheckbox_Service_Install, theTop} to create checkbox theCheckBoxRemoveServiceLabel left inset accViewInset bottom (theTop + 5) max width 250set theCheckBoxRemoveServiceLabel to localized string "Remove Service" from table "MacYTDL"set {theUtilitiesRule, theTop} to create rule 10 rule width accViewWidthif minWidth > accViewWidth then set accViewWidth to minWidthset {theButtons, minWidth} to create buttons {theButtonsDeleteLogsLabel, theButtonsUninstallLabel, theButtonsAboutLabel, theButtonCancelLabel, theButtonsStartLabel} button keys {"d", "U", "a", ".", ""} default button 5set theButtonsStartLabel to localized string "Start" from table "MacYTDL"set theButtonsAboutLabel to localized string "About MacYTDL" from table "MacYTDL"set theButtonsUninstallLabel to localized string "Uninstall" from table "MacYTDL"set theButtonsDeleteLogsLabel to localized string "Delete logs" from table "MacYTDL"set accViewInset to 75set accViewWidth to 600set utilities_diag_prompt to theDiagPromptLabelset theDiagPromptLabel to localized string "Utilities" from table "MacYTDL"set instructions_text to theInstructionsTextLabelset theInstructionsTextLabel to localized string "Choose the utility(ies) you would like to run then click 'Start'" from table "MacYTDL"set current_settings_installed to "(" & theCurrentInstalledLabel & " " & DL_Settings_In_Use & ")"set theCurrentInstalledLabel to localized string "Current:" from table "MacYTDL"set FFMpeg_version_installed to theVersionInstalledLabel & " v" & ffmpeg_versionset theYTDLVersionInstalledlabel to theVersionInstalledLabel & " v" & YTDL_versionset theVersionInstalledLabel to localized string "Installed:" from table "MacYTDL"if not (exists the file macYTDL_service_file) thenset services_Folder to (POSIX path of (path to home folder) & "/Library/Services/")set macYTDL_service_file_nonPosix to services_Folder_nonPosix & "Send-URL-To-MacYTDL.workflow"set services_Folder_nonPosix to (path_to_home_folder & "Library:Services:") as textset path_to_home_folder to (path to home folder)on utilities()end check_ffmpeg_armrun_Utilities_handlers's install_ffmpeg_ffprobe_arm(theButtonOKLabel, diag_Title, path_to_MacYTDL, usr_bin_folder, resourcesPath, MacYTDL_custom_icon_file, user_on_old_os)set ffmpeg_install_text to theFFmpegOutDatedTextLabel1 & ffmpeg_version & ". " & theFFmpegOutDatedTextLabel2 & release_build_version_FFmpeg & return & return & theFFmpegOutDatedTextLabel3if release_build_version_FFmpeg is not equal to ffmpeg_version or release_build_version_FFmpeg is not equal to ffprobe_version thenset release_build_version_FFmpeg to text item 2 of release_build_text_FFmpegset release_build_text_FFmpeg to paragraph 2 of text item 3 of FFmpeg_pageset AppleScript's text item delimiters to {"macOS (Apple Silicon/arm64)"}set ffmpeg_site to "https://ffmpeg.martin-riedl.de"on check_ffmpeg_arm()end check_ffmpeg_intelset alert_text_ffmpeg to "" & ffmpeg_versionset theFFmpegProbeAlertOutOfDateLabel to localized string "FFmpeg is out of date. Your current version is " from table "MacYTDL"set alert_text_ffmpeg to theFFmpegProbeAlertUpDatedLabel & ffmpeg_versionset theFFmpegProbeAlertUpDatedLabel to localized string "FFmpeg and FFprobe have been updated. Your new version is " from table "MacYTDL"run_Utilities_handlers's install_ffmpeg_ffprobe_intel(theButtonOKLabel, diag_Title, path_to_MacYTDL, usr_bin_folder, resourcesPath, MacYTDL_custom_icon_file, user_on_old_os)if ffmpeg_install_answ is theButtonYesLabel thenset ffmpeg_install_answ to button returned of (display dialog ffmpeg_install_text buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set ffmpeg_install_text to theFFmpegOutDatedTextLabel1 & ffmpeg_version & ". " & theFFmpegOutDatedTextLabel2 & ffmpeg_version_check & return & return & theFFmpegOutDatedTextLabel3set theFFmpegOutDatedTextLabel3 to localized string "Would you like to update it now ? If yes, this will also update FFprobe. Note: You may need to provide administrator credentials." from table "MacYTDL"set theFFmpegOutDatedTextLabel2 to localized string "The current version is " from table "MacYTDL"set theFFmpegOutDatedTextLabel1 to localized string "FFmpeg is out of date. You have version " from table "MacYTDL"if ffmpeg_version_check is not equal to ffmpeg_version or ffmpeg_version_check is not equal to ffprobe_version thenset ffmpeg_version_check to text ffmpeg_version_start thru ffmpeg_version_end of FFmpeg_pageset ffmpeg_version_end to (offset of "-tessus" in FFmpeg_page) - 1set ffmpeg_version_start to (offset of "version" in FFmpeg_page) + 8display dialog theFFmpegDownloadProblemLabel buttons {theButtonOKLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theFFmpegDownloadProblemLabel to localized string "There was a problem with accessing FFmpeg. Perhaps you are not connected to the internet or the server is currently not available. Try again later." from table "MacYTDL"if FFmpeg_page is "" thendisplay dialog theFFmpegCurlErrorLabel buttons {theButtonOKLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theFFmpegCurlErrorLabel to localized string "There was an error with looking for the FFmpeg web page. The error was: " & errmsg & ", and the URL that produced the error was: " & ffmpeg_site & ". Try again later and/or send a message to macytdl@gmail.com with the details." from table "MacYTDL"set FFmpeg_page to do shell script "curl " & ffmpeg_site & " | textutil -stdin -stdout -format html -convert txt -encoding UTF-8 "set ffmpeg_site to "https://evermeet.cx/pub/ffmpeg/"set alert_text_ffmpeg to theFFmpegAlertUpToDateLabel & ffmpeg_versionset theFFmpegAlertUpToDateLabel to localized string "FFmpeg and FFprobe are up to date. Your current version is " from table "MacYTDL"set ffprobe_version_long to do shell script ffprobe_file & " -version"on check_ffmpeg_intel()end check_ffmpegcheck_ffmpeg_arm()check_ffmpeg_intel()if user_system_arch is "Intel" thenon check_ffmpeg()end check_ytdlset alert_text_ytdl to show_yt_dlp & theYTDLOutOfDateLabel & YTDL_versionset theYTDLOutOfDateLabel to localized string " is out of date. Your current version is " from table "MacYTDL"set alert_text_ytdl to show_yt_dlp & theYTDLUpDatedLabel & YTDL_versionset theYTDLUpDatedLabel to localized string " has been updated. Your new version is " from table "MacYTDL"set YTDL_version to YTDL_version_checkdo shell script "chmod a+x /usr/local/bin/yt-dlp" with administrator privilegesdisplay dialog "There was an error in downloading the YT-DLP update. The error reported was " & errmsgif errmsg does not contain "User canceled" thendo shell script "curl -L " & YTDL_site_URL & "/download/" & YTDL_version_check & "/" & name_of_executable & " -o /usr/local/bin/yt-dlp" with administrator privilegesdo shell script "rm /usr/local/bin/yt-dlp" with administrator privilegesif homebrew_ytdlp_exists is true thendo shell script resourcesPath & "alerter -message " & installAlertMessage & " -title " & installAlertTitle & " -subtitle " & installAlertSubtitle & " -timeout 5 -sender com.apple.script.id.MacYTDL -actions " & installAlertActionLabel & " > /dev/null 2> /dev/null & "set installAlertSubtitle to quoted form of ((localized string "Download and install of " from table "MacYTDL") & show_yt_dlp)set installAlertMessage to quoted form of (localized string "started. Please wait." from table "MacYTDL")set installAlertTitle to quoted form of (localized string "MacYTDL installation:" from table "MacYTDL")set installAlertActionLabel to quoted form of "_"if YTDL_install_answ is theButtonYesLabel thenset YTDL_install_answ to button returned of (display dialog YTDL_update_text buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set YTDL_update_text to "A new version of " & show_yt_dlp & " is available. You have version " & installedYTDL_version & ". The current version is " & YTDL_version_check & return & return & "Would you like to download it now ?"set YTDL_update_text to "To switch to " & show_yt_dlp & " it will need to be installed. Would you like to download it now ?"if switch_flag is true thenif YTDL_version_check is not equal to installedYTDL_version or homebrew_ytdlp_exists is true thenset YTDL_version_check to text item 2 of version_paraset version_para to paragraph (numParas) of YTDL_releases_textset numParas to count paragraphs in YTDL_releases_textset YTDL_releases_text to text item 1 of YTDL_releases_pageset AppleScript's text item delimiters to "Latest"display dialog theYTDLPageErrorLabel buttons {theButtonOKLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theYTDLPageErrorLabel to theYTDLPageErrorLabel1 & show_yt_dlp & ". " & theYTDLPageErrorLabel2set theYTDLPageErrorLabel2 to localized string "Perhaps you are not connected to the internet or GitHub is currently not available." from table "MacYTDL"set theYTDLPageErrorLabel1 to localized string "There was a problem with looking for " from table "MacYTDL"if YTDL_releases_page is "" thenset alert_text_ytdl to theYTDLUpToDateLabel & installedYTDL_versionif alert_text_ytdl is "Switching" then set switch_flag to trueset switch_flag to falseset theYTDLUpToDateLabel to show_yt_dlp & theYTDLUpToDateLabelaset theYTDLUpToDateLabela to localized string " is up to date. Your current version is " from table "MacYTDL"set value of property list item "YTDL_YTDLP_version" to installedYTDL_versionif installedYTDL_version is not YTDL_version thenset installedYTDL_version to do shell script ytdlp_file & " --version"display dialog theYTDLCurlErrorLabel buttons {theButtonOKLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theYTDLCurlErrorLabel to theYTDLCurlErrorLabel1 & show_yt_dlp & theYTDLCurlErrorLabel2 & errmsg & theYTDLCurlErrorLabel3 & YTDL_site_URL & ". " & theYTDLCurlErrorLabel4set theYTDLCurlErrorLabel4 to localized string "Try again later and/or send a message to macytdl@gmail.com with the details." from table "MacYTDL"set theYTDLCurlErrorLabel3 to localized string ", and the URL that produced the error was: " from table "MacYTDL"set theYTDLCurlErrorLabel2 to localized string " web page. The error was: " from table "MacYTDL"set theYTDLCurlErrorLabel1 to localized string "There was an error with looking for the " from table "MacYTDL"set YTDL_releases_page to do shell script "curl " & YTDL_site_URL & " | textutil -stdin -stdout -format html -convert txt -encoding UTF-8 "set name_of_executable to "yt-dlp_macos_legacy"else if show_yt_dlp is "yt-dlp-legacy" thenset name_of_executable to "yt-dlp_macos"if show_yt_dlp is "yt-dlp" thenset YTDL_site_URL to "https://github.com/yt-dlp/yt-dlp/releases"on check_ytdl(show_yt_dlp)end set_settingsset value of property list item "Thumbnail_Embed" to falseif settings_thumb_embed_choice is false thenset theSTsEmbedFormatLabel to localized string "Sorry, to embed thumbnails, you need to specify audio only and use mp3 or m4a audio format." from table "MacYTDL"else if settings_thumb_embed_choice is true and DL_Use_YTDLP is "youtube-dl" and (settings_audio_only_choice is false or (settings_audio_codec_choice is not "mp3" and settings_audio_codec_choice is not "m4a")) thendisplay dialog theSTsEmbedFormatLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theSTsEmbedFormatLabel to localized string "Sorry, to embed thumbnails, you need to install Atomic Parsley. You can do that in Utilities." from table "MacYTDL"else if settings_thumb_embed_choice is true and Atomic_is_installed is false and DL_Use_YTDLP is "youtube-dl" thenset value of property list item "Thumbnail_Embed" to trueif settings_thumb_embed_choice is true and ((DL_Use_YTDLP is "yt-dlp") or (DL_Use_YTDLP is "youtube-dl" and Atomic_is_installed is true and settings_audio_only_choice is true and (settings_audio_codec_choice is "mp3" or settings_audio_codec_choice is "m4a"))) thenset value of property list item "SubTitles_Embedded" to settings_stembed_choicedisplay dialog theSTsEmbeddedFileformatLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theSTsEmbeddedFileformatLabel to localized string "Sorry, File format or Remux format must be mp4, mkv or webm for subtitles to be embedded." from table "MacYTDL"if settings_stembed_choice is true and (settings_format_choice is not "mp4" and settings_format_choice is not "mkv" and settings_format_choice is not "webm" and settings_remux_format_choice is not "webm" and settings_remux_format_choice is not "mkv" and settings_remux_format_choice is not "mp4") thendisplay dialog theSTsEmbeddedTogetherLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theSTsEmbeddedTogetherLabel to localized string "Sorry, you need to turn on subtitles if you want them embedded." from table "MacYTDL"if settings_subtitles_choice is false and settings_autoST_choice is false and settings_stembed_choice is true thenset value of property list item "Limit_Rate_Value" to settings_limit_rate_value_choiceset value of property list item "Limit_Rate" to settings_limit_rate_choiceif settings_limit_rate_choice is true and (settings_limit_rate_value_choice is "" or settings_limit_rate_value_choice is less than or equal to 0) thendisplay dialog theLimitRateInvalidLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theLimitRateInvalidLabel to localized string "Sorry, you need a positive real number to limit download speed." from table "MacYTDL"set settings_limit_rate_value_choice to settings_limit_rate_value_choice as realset value of property list item "DownloadFolder" to settings_folder_choiceset settings_folder_choice to text 1 thru offset_to_file_name of settings_folder_choiceset offset_to_file_name to last_offset(settings_folder_choice as text, "/")tell application "System Events" to set test_DL_folder to (get class of item (settings_folder_choice as text)) as textrepeat until test_DL_folder is "file" or test_DL_folder is "folder" or test_DL_folder is "disk" or test_DL_folder is "«class cfol»" or test_DL_folder is "alias"set test_DL_folder to ""set value of property list item "Custom_Settings" to settings_custom_settings_choiceset value of property list item "Use_Custom_Settings" to settings_use_custom_settings_choicedisplay dialog theMustProvideCustomSettingsLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theMustProvideCustomSettingsLabel to localized string "Sorry, you have not provided custom settings." from table "MacYTDL"if settings_use_custom_settings_choice is true and settings_custom_settings_choice is "" thenset value of property list item "Custom_Output_Template" to settings_custom_template_choiceset value of property list item "Use_Custom_Output_Template" to settings_use_custom_template_choiceset settings_custom_template_choice to settings_custom_template_choice & ".%(ext)s"if settings_custom_template_choice is not equal to "" and settings_custom_template_choice does not end with ".%(ext)s" thendisplay dialog theMustProvideCustomTemplateLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theMustProvideCustomTemplateLabel to localized string "Sorry, you have not provided a custom file name template." from table "MacYTDL"if settings_use_custom_template_choice is true and (settings_custom_template_choice is "" or settings_custom_template_choice is " ") thenset value of property list item "Cookies_Location" to settings_cookies_location_choiceset value of property list item "Use_Cookies" to settings_use_cookies_choicedisplay dialog theMustProvideProxyLocationLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theMustProvideProxyLocationLabel to localized string "Sorry, you need to give the location of your cookies file." from table "MacYTDL"if settings_use_cookies_choice is true and settings_cookies_location_choice is "/No Cookie File" thenset value of property list item "Use_Proxy" to settings_use_proxy_choiceset value of property list item "Proxy_URL" to settings_proxy_URL_choicedisplay dialog theMustProvideProxyURLLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theMustProvideProxyURLLabel to localized string "Sorry, you need a proxy URL to use a proxy for downloads." from table "MacYTDL"if settings_use_proxy_choice is true and settings_proxy_URL_choice is "" thendisplay dialog theNeedValidProtocolLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theNeedValidProtocolLabel to localized string "Sorry, you need a valid protocol for a proxy URL (http, https or socks)." from table "MacYTDL"if protocol_chosen is not "http:" and protocol_chosen is not "https" and protocol_chosen is not "socks" thenset protocol_chosen to text 1 thru 5 of settings_proxy_URL_choiceif settings_proxy_URL_choice is not "" thenset new_value to "Send-URL-To-MacYTDL"set value of property list item "Auto_Download" to falseelse if settings_auto_download_choice is false and isServiceInstalled is "Yes" thenif show_yt_dlp is "yt-dlp" or show_yt_dlp is "yt-dlp-legacy" thenrun_Utilities_handlers's install_MacYTDLservice(path_to_MacYTDL)if autoDLNeedService is theButtonsInstallLabel thenif autoDLNeedService is theButtonReturnLabel then main_dialog()set autoDLNeedService to button returned of (display dialog (theNeedServiceLabel & " ?") with title diag_Title buttons {theButtonReturnLabel, theButtonsInstallLabel, theButtonsSaveLabel} default button 2 with icon file MacYTDL_custom_icon_file giving up after 600)set theButtonsInstallLabel to localized string "Install" from table "MacYTDL"set theNeedServiceLabel to localized string "Sorry, to have automatic downloads, you need to install the MacYTDL Service. Discard settings changes and return to Main, install the Service and turn on auto downloads or save all but Auto-download changes" from table "MacYTDL"if isServiceInstalled is "No" thenset value of property list item "default" of property list item "NSMenuItem" of property list item 1 of property list items of contents to new_valuetell property list file Service_file_plistset new_value to "Download Video Now"if show_yt_dlp is "yt-dlp" or show_yt_dlp is "yt-dlp-legacy" then -- This might not work on macOS earlier than 10.15set value of property list item "Auto_Download" to settings_auto_download_choiceif isServiceInstalled is "Yes" thenif settings_auto_download_choice is true thenset isServiceInstalled to "Yes"if (exists the file macYTDL_service_file) thenset isServiceInstalled to "No"set Service_file_plist to (macYTDL_service_file & ":Contents:info.plist")set macYTDL_service_file to services_Folder & "Send-URL-To-MacYTDL.workflow"set services_Folder to ((path to home folder) & "Library:Services:") as textset value of property list item "Get_Formats_List" to settings_formats_list_choiceset value of property list item "Make_QuickTime_Compat" to settings_QT_Compat_choiceset value of property list item "Verbose" to settings_verbose_choiceset value of property list item "Thumbnail_Write" to settings_thumb_write_choiceset value of property list item "Subtitles_YTAuto" to settings_autoST_choiceset value of property list item "Subtitles_Language" to settings_subtitleslanguage_choiceset value of property list item "Subtitles_Format" to settings_subtitlesformat_choiceset value of property list item "SubTitles" to settings_subtitles_choiceset value of property list item "Add_TimeStamps" to settings_timestamps_choiceset value of property list item "Show_Settings_before_Download" to settings_show_settings_choiceset value of property list item "Remux_Format" to settings_remux_format_choiceset value of property list item "Over-writes allowed" to settings_forceOW_choiceset value of property list item "Keep_Remux_Original" to settings_original_choiceset value of property list item "FileFormat" to settings_format_choiceset value of property list item "Description" to settings_description_choiceset value of property list item "Auto_Check_YTDL_Update" to settings_YTDL_auto_choiceset value of property list item "Audio_Codec" to settings_audio_codec_choiceset value of property list item "Audio_Only" to settings_audio_only_choiceset value of property list item "Add_Metadata" to settings_metadata_choiceset settings_folder_choice to item 40 of settings_controls_results -- <= The download path choiceset settings_format_choice to item 38 of settings_controls_results -- <= File format choiceset settings_description_choice to item 36 of settings_controls_results -- <= Description choiceset settings_audio_codec_choice to item 34 of settings_controls_results -- <= Audio codec choiceset settings_forceOW_choice to item 33 of settings_controls_results -- <= Force overwrites choiceset settings_audio_only_choice to item 32 of settings_controls_results -- <= Audio only choiceset settings_YTDL_auto_choice to item 31 of settings_controls_results -- <= Auto check YTDL version on startup choiceset settings_subtitles_choice to item 30 of settings_controls_results -- <= Subtitles choiceset settings_stembed_choice to item 29 of settings_controls_results -- <= Embed subtitles choiceset settings_subtitleslanguage_choice to item 27 of settings_controls_results -- <= Subtitles language choiceset settings_subtitlesformat_choice to item 25 of settings_controls_results -- <= Subtitles format choiceset settings_autoST_choice to item 24 of settings_controls_results -- <= Auto-gen subtitles choiceset settings_thumb_write_choice to item 23 of settings_controls_results -- <= Write Thumbnails choiceset settings_thumb_embed_choice to item 22 of settings_controls_results -- <= Embed Thumbnails choiceset settings_verbose_choice to item 21 of settings_controls_results -- <= Verbose choiceset settings_timestamps_choice to item 20 of settings_controls_results -- <= Add timestamps choiceset settings_metadata_choice to item 19 of settings_controls_results -- <= Add metadata choiceset settings_formats_list_choice to item 18 of settings_controls_results -- <= Add metadata choiceset settings_remux_format_choice to item 16 of settings_controls_results -- <= Remux format choiceset settings_original_choice to item 15 of settings_controls_results -- <= Keep original after remux choiceset settings_limit_rate_value_choice to item 14 of settings_controls_results -- <= Limit rate value choiceset settings_limit_rate_choice to item 13 of settings_controls_results -- <= Limit rate choiceset settings_proxy_URL_choice to item 12 of settings_controls_results -- <= The proxy URLset settings_use_proxy_choice to item 11 of settings_controls_results -- <= Use proxy choiceset settings_cookies_location_choice to item 10 of settings_controls_results -- <= The proxy URLset settings_use_cookies_choice to item 9 of settings_controls_results -- <= Use proxy choiceset settings_custom_template_choice to item 8 of settings_controls_results -- <= The custom template to useset settings_use_custom_template_choice to item 7 of settings_controls_results -- <= Use custom template choiceset settings_custom_settings_choice to item 6 of settings_controls_results -- <= The custom settings to useset settings_use_custom_settings_choice to item 5 of settings_controls_results -- <= Use custom settings choiceset settings_QT_Compat_choice to item 4 of settings_controls_results -- <= Make download QT compatibleset settings_show_settings_choice to item 3 of settings_controls_results -- <= Show settings before download choiceset settings_auto_download_choice to item 2 of settings_controls_results -- <= Automatic download using Serviceif settings_button_number_returned is 2 then -- Save Settingsset {settings_button_returned, settings_button_number_returned, settings_controls_results, finalPosition} to display enhanced window diag_Title buttons theButtons acc view width calculatedAccViewWidth acc view height theTop acc view controls settings_allControls initial position window_Positionset calculatedAccViewWidth to (BoxCustSetLeftDist + 250)if (BoxCustSetLeftDist + 250) is greater than calculatedAccViewWidth thenset calculatedAccViewWidth to accViewWidthset calculatedAccViewWidth to (popupSTFormatLeftDist + 60)if (popupSTFormatLeftDist + 50) is greater than accViewWidth thenset settings_allControls to {theSettingsRule, settings_theCheckbox_Auto_Download, settings_theCheckbox_Show_Settings, settings_theCheckbox_QT_Compat, settings_theCheckbox_Use_CustomSettings, settings_theField_Custom_Settings, settings_theCheckbox_Use_CustomTemplate, settings_theField_Custom_Template, settings_theCheckBox_Use_Cookies, settings_theCookiesLocationPathControl, settings_theCheckBox_Use_Proxy, settings_theField_ProxyURL, settings_theCheckbox_Limit_Rate, settings_theField_LimitRateValue, settings_theCheckbox_Original, settings_thePopUp_RemuxFormat, settings_remuxlabel, settings_theCheckbox_Formats, settings_theCheckbox_Metadata, settings_theCheckbox_TimeStamps, settings_theCheckbox_Verbose, settings_theCheckbox_ThumbEmbed, settings_theCheckbox_ThumbWrite, settings_theCheckbox_AutoSubTitles, settings_thePopUp_SubTitlesFormat, settings_STFormatlabel, settings_theField_STLanguage, settings_language_label, settings_theCheckbox_STEmbed, settings_theCheckbox_SubTitles, settings_theCheckbox_Auto_YTDL_Check, settings_theCheckbox_AudioOnly, settings_theCheckbox_OverWrites, settings_thePopup_AudioCodec, settingsCodecLabel, settings_theCheckbox_Description, theSettingsAdminRule, settings_thePopUp_FileFormat, settings_formatlabel, settings_thePathControl, settings_pathLabel, MacYTDL_icon, settings_prompt, theSettingsSTEndRule}set {settings_prompt, theTop} to create label settings_diag_prompt left inset 0 bottom (theTop - 5) max width accViewWidth aligns center aligned with bold typeset {MacYTDL_icon, theTop} to create image view MacYTDL_custom_icon_file_posix left inset 0 bottom theTop - 50 view width 64 view height 64 scale image scale proportionallyset {settings_thePathControl, settings_pathLabel, theTop} to create labeled path control (POSIX path of downloadsFolder_Path) left inset 70 bottom (theTop + 8) control width 150 label text theLabelPathChangeDLFolderLabel with pops upset theLabelPathChangeDLFolderLabel to localized string "Change download folder:" from table "MacYTDL"set {settings_thePopUp_FileFormat, settings_formatlabel, theTop, popupLeft} to create labeled popup {theDefaultLabel, "mp4", "webm", "ogg", "3gp", "flv"} left inset 70 bottom (theTop + 3) popup width 90 max width 400 label text theLabeledPopUpFileFormatLabel popup left 70 initial choice DL_formatset theLabeledPopUpFileFormatLabel to localized string "File format:" from table "MacYTDL"set {settings_theCheckbox_Verbose, theTop} to create checkbox theCheckboxVerboseLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_verboseset theCheckboxVerboseLabel to localized string "Verbose logging" from table "MacYTDL"set {settings_theCheckbox_TimeStamps, theTop} to create checkbox theCheckboxTimeStampsLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_TimeStampsset theCheckboxTimeStampsLabel to localized string "Add timestamps to log" from table "MacYTDL"set {settings_theCheckbox_Auto_YTDL_Check, theTop} to create checkbox theCheckboxCheckYTDLOnStartLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_YTDL_auto_checkset theCheckboxCheckYTDLOnStartLabel to (localized string "Check" from table "MacYTDL") & " " & settings_DL_Use_YTDLP & " " & (localized string "version on startup" from table "MacYTDL")set settings_DL_Use_YTDLP to DL_Use_YTDLPset settings_DL_Use_YTDLP to "YT-DLP"if DL_Use_YTDLP is "yt-dlp-legacy" thenset {settings_theCheckbox_Show_Settings, theTop} to create checkbox theCheckboxShowSettingsLabel left inset 70 bottom (theTop + 3) max width 200 initial state DL_Show_Settingsset theCheckboxShowSettingsLabel to localized string "Show settings before download" from table "MacYTDL"set {settings_theCheckbox_Auto_Download, theTop} to create checkbox theCheckboxAutoDownloadLabel left inset 70 bottom (theTop + 1) max width 200 initial state DL_autoset theCheckboxAutoDownloadLabel to localized string "Automatic download" from table "MacYTDL"set {settings_theField_LimitRateValue, theTop} to create field DL_Limit_Rate_Value left inset (RateBoxLeftDist + 70) bottom (theTop - 20) field width 40set {settings_theCheckbox_Limit_Rate, theTop, RateBoxLeftDist} to create checkbox theCheckboxLimitRateLabel left inset 70 bottom (theTop + 3) max width 200 initial state DL_Limit_Rateset theCheckboxLimitRateLabel to localized string "Limit download speed (MB/sec)" from table "MacYTDL"set {theSettingsSTEndRule, theTop} to create rule (theTop + 1) left inset 70 rule width (accViewWidth - 70)set {settings_thePopUp_SubTitlesFormat, settings_STFormatlabel, theTop, popupSTFormatLeftDist} to create labeled popup {theBestLabel, "srt", "vtt", "ass", "lrc", "ttml", "dfxp", "srv3"} left inset (STCheckBoxWidth + 77) bottom (theTop - 23) popup width 65 max width 250 label text theLabeledPopUpSTsFormatLabel popup left (STCheckBoxWidth + 77) initial choice DL_subtitles_formatset theLabeledPopUpSTsFormatLabel to localized string "Subtitles format:" from table "MacYTDL"set {settings_theCheckbox_SubTitles, theTop, STCheckBoxWidth} to create checkbox theCheckboxDLSTsLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_subtitlesset theCheckboxDLSTsLabel to localized string "Download subtitles" from table "MacYTDL"set {settings_theField_STLanguage, settings_language_label, theTop, fieldSTLangLeft} to create side labeled field DL_STLanguage left inset 70 bottom (theTop + 3) total width 200 label text theLabeledFieldSTsLangLabel field left 0set theLabeledFieldSTsLangLabel to localized string "Subtitles language:" from table "MacYTDL"set {settings_theCheckbox_STEmbed, theTop} to create checkbox theCheckboxEmbedSTsLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_STEmbedset theCheckboxEmbedSTsLabel to localized string "Embed subtitles" from table "MacYTDL"set {settings_theCheckbox_AutoSubTitles, theTop} to create checkbox theCheckboxDLAutoSTsLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_YTAutoSTset theCheckboxDLAutoSTsLabel to localized string "Auto-generated subtitles" from table "MacYTDL"set {theSettingsAdminRule, theTop} to create rule (theTop + 1) left inset 70 rule width (accViewWidth - 70)set {settings_theCheckbox_Description, theTop} to create checkbox settings_theCheckbox_DescriptionLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_descriptionset settings_theCheckbox_DescriptionLabel to localized string "Download description" from table "MacYTDL"set {settings_theCheckbox_AudioOnly, theTop} to create checkbox theCheckboxAudioOnlyLabel left inset 70 bottom (theTop - 21) max width 250 initial state DL_audio_onlyset theCheckboxAudioOnlyLabel to localized string "Audio only" from table "MacYTDL"set {settings_thePopup_AudioCodec, settingsCodecLabel, theTop} to create labeled popup {theBestLabel, "aac", "flac", "mp3", "m4a", "opus", "vorbis", "wav"} left inset 220 bottom (theTop - 2) popup width 90 max width 200 label text theLabeledPopupCodecLabel popup left 220 initial choice DL_audio_codecset theLabeledPopupCodecLabel to localized string "Audio format:" from table "MacYTDL"set {settings_theCheckbox_OverWrites, theTop} to create checkbox theCheckboxForceOWLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_over_writesset theCheckboxForceOWLabel to localized string "Force overwrites" from table "MacYTDL"set {settings_theCheckbox_ThumbWrite, theTop} to create checkbox theCheckboxWriteThumbsLabel left inset 70 bottom (theTop - 18) max width 250 initial state DL_Thumbnail_Writeset theCheckboxWriteThumbsLabel to localized string "Write thumbnails" from table "MacYTDL"set {settings_theCheckbox_ThumbEmbed, theTop} to create checkbox theCheckboxEmbedThumbsLabel left inset 280 bottom (theTop + 1) max width 250 initial state DL_Thumbnail_Embedset theCheckboxEmbedThumbsLabel to localized string "Embed thumbnails" from table "MacYTDL"set {settings_theCheckbox_Metadata, theTop} to create checkbox theCheckboxMetadataLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_Add_Metadataset theCheckboxMetadataLabel to localized string "Add metadata" from table "MacYTDL"set {settings_theCheckbox_Formats, theTop} to create checkbox theCheckboxGetFormatsListLabel left inset 70 bottom (theTop + 3) max width 250 initial state DL_formats_listset theCheckboxGetFormatsListLabel to localized string "Get formats list" from table "MacYTDL"set {settings_thePopUp_RemuxFormat, settings_remuxlabel, theTop} to create labeled popup {theNoRemuxLabel, "mp4", "mkv", "flv", "webm", "avi", "ogg"} left inset 70 bottom (theTop + 3) popup width 100 max width 200 label text theLabeledPopupRemuxFormatLabel popup left 70 initial choice DL_Remux_formatset {settings_thePopUp_RemuxFormat, settings_remuxlabel, theTop} to create labeled popup {theNoRemuxLabel, "avi", "flv", "gif", "mkv", "mov", "mp4", "webm"} left inset 70 bottom (theTop + 3) popup width 100 max width 200 label text theLabeledPopupRemuxFormatLabel popup left 70 initial choice DL_Remux_formatset theLabeledPopupRemuxFormatLabel to localized string "Remux format:" from table "MacYTDL"set {settings_theCheckbox_Original, theTop} to create checkbox theCheckboxKeepOriginalLabel left inset 70 bottom (theTop + 3) max width 200 initial state DL_Remux_originalset theCheckboxKeepOriginalLabel to localized string "Keep original video and/or subtitles file" from table "MacYTDL"set {settings_theField_ProxyURL, theTop} to create field DL_Proxy_URL left inset (ProxyCheckBoxWidth + 70) bottom (theTop - 20) field width 250 placeholder text theFieldProxyURLPlaceholderLabelset theFieldProxyURLPlaceholderLabel to localized string "No URL set" from table "MacYTDL"set {settings_theCheckBox_Use_Proxy, theTop, ProxyCheckBoxWidth} to create checkbox theCheckboxUseProxyLabel left inset 70 bottom (theTop + 3) max width 100 initial state DL_Use_Proxyset theCheckboxUseProxyLabel to localized string "Use proxy" from table "MacYTDL"set {settings_theCheckBox_Use_Cookies, theTop} to create checkbox theCheckboxUseCookiesLabel left inset 70 bottom (theTop - 25) max width 150 initial state DL_Use_Cookiesset theCheckboxUseCookiesLabel to localized string "Use cookies" from table "MacYTDL"set {settings_theCookiesLocationPathControl, theTop} to create path control (POSIX path of DL_Cookies_Location) left inset 205 bottom (theTop + 1) control width 225 with pops upset {settings_theField_Custom_Template, theTop} to create field DL_Custom_Template left inset (CustTempPopLeftDist + 70) bottom (theTop - 20) field width 200 placeholder text theFieldCustomTemplateLabelset theFieldCustomTemplateLabel to localized string "Custom file name template" from table "MacYTDL"set {settings_theCheckbox_Use_CustomTemplate, theTop, CustTempPopLeftDist} to create checkbox theCheckBoxUseCustomTemplateLabel left inset 70 bottom (theTop + 3) max width 150 initial state DL_Use_Custom_Templateset theCheckBoxUseCustomTemplateLabel to localized string "Use custom template" from table "MacYTDL"set {settings_theField_Custom_Settings, theTop} to create field DL_Custom_Settings left inset (BoxCustSetLeftDist + 70) bottom (theTop - 20) field width 200 placeholder text theFieldCustomSettingsLabelset theFieldCustomSettingsLabel to localized string "Custom settings" from table "MacYTDL"set {settings_theCheckbox_Use_CustomSettings, theTop, BoxCustSetLeftDist} to create checkbox theCheckBoxUseCustomSettingsLabel left inset 70 bottom (theTop + 3) max width 150 initial state DL_Use_Custom_Settingsset theCheckBoxUseCustomSettingsLabel to localized string "Use custom settings" from table "MacYTDL"set {settings_theCheckbox_QT_Compat, theTop} to create checkbox theCheckboxQTCompatLabel left inset 70 bottom (theTop + 3) max width 200 initial state DL_QT_Compatset theCheckboxQTCompatLabel to localized string "QT compatible video" from table "MacYTDL"set {theSettingsRule, theTop} to create rule 3 rule width accViewWidthset {theButtons, minWidth} to create buttons {theButtonCancelLabel, theButtonsSaveLabel} button keys {".", ""} default button 2set theButtonsSaveLabel to localized string "Save Settings" from table "MacYTDL"set accViewInset to 0set settings_diag_prompt to theSettingsDiagPromptLabelset theSettingsDiagPromptLabel to localized string "Settings" from table "MacYTDL"on set_settings()end get_Date_Timereturn download_date_timeset download_date_time to the item_list as stringset AppleScript's text item delimiters to "_"set the item_list to every text item of download_date_timeset AppleScript's text item delimiters to {", ", " ", ":", ","}set download_date_time to (current date) as stringon get_Date_Time()end check_subtitles_download_availableset YTDL_subtitles to "--write-auto-sub --write-sub --sub-format " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --write-sub --sub-format ttml " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --write-sub --sub-format dfxp " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --write-sub --sub-format best " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --write-sub --convert-subs " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "if author_gen is true and auto_gen is true thenset YTDL_subtitles to "--write-auto-sub --sub-format " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --sub-format ttml " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --sub-format dfxp " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --sub-format best " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-auto-sub --convert-subs " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "if author_gen is false and auto_gen is true thenset YTDL_subtitles to "--write-sub --sub-format " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "set YTDL_subtitles to "--write-sub --sub-format ttml " & "--sub-lang " & DL_STLanguage & " "else if DL_subtitles_format is "ttml" thenset YTDL_subtitles to "--write-sub --sub-format dfxp " & "--sub-lang " & DL_STLanguage & " "else if DL_subtitles_format is "dfxp" thenset YTDL_subtitles to "--write-sub --sub-format best " & "--sub-lang " & DL_STLanguage & " "else if DL_subtitles_format is theBestLabel thenset YTDL_subtitles to "--write-sub --convert-subs " & DL_subtitles_format & " " & "--sub-lang " & DL_STLanguage & " "if subtitles_info does not contain DL_subtitles_format and DL_subtitles_format is not theBestLabel and DL_subtitles_format is not "ttml" and DL_subtitles_format is not "dfxp" thenif author_gen is true and auto_gen is false thenelse if subtitles_quit_or_continue is theButtonContinueLabel thenelse if dialog_2_text is "auto-generated " thenif dialog_2_text is "author-generated " thenif subtitles_quit_or_continue is theButtonContinueGoLabel thenset subtitles_quit_or_continue to button returned of (display dialog theSTLangNotAvailableLabel1 & "\"" & DL_STLanguage & "\". " & theSTLangNotAvailableLabel2 & return & return & theSTLangNotAvailableLabel3 buttons {theButtonReturnLabel, theButtonContinueGoLabel, theButtonContinueLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theSTLangNotAvailableLabel3 to theSTLangNotAvailableLabel3a & dialog_2_text & theSTLangNotAvailableLabel3bset theSTLangNotAvailableLabel3b to localized string "subtitles or download without subtitles." from table "MacYTDL"set theSTLangNotAvailableLabel3a to localized string "You cancel your download, download " from table "MacYTDL"set theSTLangNotAvailableLabel2 to localized string theSTLangNotAvailableLabel2a & " " & dialog_2_text & theSTLangNotAvailableLabel2bset theSTLangNotAvailableLabel2b to localized string "subtitles are available." from table "MacYTDL"set theSTLangNotAvailableLabel2a to localized string "But" from table "MacYTDL"set theSTLangNotAvailableLabel1 to localized string theSTLangNotAvailableLabel1a & " " & dialog_1_text & theSTLangNotAvailableLabel1b & " "set theSTLangNotAvailableLabel1b to localized string "subtitle file in your preferred language" from table "MacYTDL"set theSTLangNotAvailableLabel1a to localized string "There is no" from table "MacYTDL"if alt_lang_avail is "Y" thenset theButtonContinueGoLabel to localized string "Get auto" from table "MacYTDL"set dialog_3_text to auto_gen_subtitlesset dialog_2_text to "auto-generated "set dialog_1_text to "author-generated "if author_gen_subtitles does not contain (DL_STLanguage & " ") and auto_gen_subtitles contains (DL_STLanguage & " ") and auto_gen is false thenset alt_lang_avail to "Y"set theButtonContinueGoLabel to localized string "Get author" from table "MacYTDL"set dialog_3_text to author_gen_subtitlesset dialog_2_text to "author-generated "set dialog_1_text to "auto-generated "if author_gen_subtitles contains (DL_STLanguage & " ") and auto_gen_subtitles does not contain (DL_STLanguage & " ") and author_gen is false thenset author_gen_subtitles to text item 3 of check_subtitles_availableset auto_gen_subtitles to text item 2 of check_subtitles_availableset alt_lang_avail to "N"if (count of text items in check_subtitles_available) is 3 thenset AppleScript's text item delimiters to {"Available automatic captions for", "Available subtitles for"}set subtitles_quit_or_continue to button returned of (display dialog theSTLangNotAvailableLabel1 & "\"" & DL_STLanguage & "\". " & theSTLangNotAvailableLabel2 & return & return & show_languages_avail & return & return & theSTLangNotAvailableLabel3 buttons {theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theSTLangNotAvailableLabel3 to localized string "You can quit, cancel your download (then go to Settings to change language) or download anyway." from table "MacYTDL"set theSTLangNotAvailableLabel2 to localized string "These languages are available: " from table "MacYTDL"set theSTLangNotAvailableLabel1 to localized string "There is no subtitle file in your preferred language " from table "MacYTDL"if subtitles_info does not contain (DL_STLanguage & " ") thenset show_languages_avail to show_languages_avail & lang_code & ", "set lang_code to text item 1 of log_subtitle_paragraphset subtitles_info to subtitles_info & log_subtitle_paragraph & returnif log_subtitle_paragraph contains " " or character 3 of log_subtitle_paragraph is "-" thenrepeat with log_subtitle_paragraph in log_ST_paragraphsset AppleScript's text item delimiters to " "set show_languages_avail to ""set log_ST_paragraphs to paragraphs of check_subtitles_availableset subtitles_info to ""set auto_gen to trueset author_gen to falseelse if auto_subtitles_stop_or_continue is theButtonContinueGoAutoLabel thenset auto_subtitles_stop_or_continue to button returned of (display dialog theNoAutoYesAuthorLabel buttons {theButtonContinueGoAutoLabel, theButtonContinueLabel, theButtonReturnLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theButtonContinueGoAutoLabel to localized string "Get auto" from table "MacYTDL"set theNoAutoYesAuthorLabel to localized string "You have specified author-generated subtitles but only auto-generated are available. Do you want auto-generated subtitles, continue without subtitles or cancel this download and return to the Main dialog ?" from table "MacYTDL"else if auto_gen is false and author_gen is true and check_subtitles_available contains "Available automatic captions for" and check_subtitles_available does not contain "Available subtitles for" thenset theButtonContinueGoAuthorLabel to localized string "Get author" from table "MacYTDL"set theNoAutoYesAuthorLabel to localized string "You have specified auto-generated subtitles but only author generated are available. Do you want author generated subtitles, continue without subtitles or cancel this download and return to the Main dialog ?" from table "MacYTDL"if auto_gen is true and author_gen is false and check_subtitles_available does not contain "Available automatic captions for" and check_subtitles_available contains "Available subtitles for" thenelse if check_subtitles_available contains "Language formats" or check_subtitles_available contains "Language formats" or check_subtitles_available contains "Language Name" thenelse if subtitles_quit_or_continue is theButtonReturnLabel thenif subtitles_quit_or_continue is theButtonQuitLabel thenset subtitles_quit_or_continue to button returned of (display dialog theSTNotAvailableLabel1 & return & return & theSTNotAvailableLabel2 buttons {theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theSTNotAvailableLabel2 to localized string "You can quit, stop and return or download anyway." from table "MacYTDL"set theSTNotAvailableLabel1 to localized string "There is no subtitle file available for your video (although it might be embedded)." from table "MacYTDL"if check_subtitles_available does not contain "Language formats" and check_subtitles_available does not contain "Language formats" and check_subtitles_available does not contain "Language Name" thenset check_subtitles_available to do shell script shellPath & DL_Use_YTDLP & " --list-subs --ignore-errors " & URL_for_subtitles_testreturn YTDL_subtitleselse if auto_subtitles_stop_or_continue is theButtonContinueLabel thenset auto_gen to falseset author_gen to trueelse if auto_subtitles_stop_or_continue is theButtonContinueGoAuthorLabel thenif auto_subtitles_stop_or_continue is theButtonReturnLabel thenset auto_subtitles_stop_or_continue to button returned of (display dialog theAutoSTWillNotWorkLabel buttons {theButtonContinueGoAuthorLabel, theButtonContinueLabel, theButtonReturnLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theButtonContinueGoAuthorLabel to localized string "Try author" from table "MacYTDL"set theAutoSTWillNotWorkLabel to localized string "You have specified auto-generated subtitles but not from Youtube. It will not work. Do you want to try author generated subtitles, continue without subtitles or cancel this download and return to the Main dialog ?" from table "MacYTDL"if auto_gen is true and author_gen is false and URL_for_subtitles_test does not contain "YouTube" and URL_for_subtitles_test does not contain "YouTu.be" thenset URL_for_subtitles_test to URL_user_enteredset URL_for_subtitles_test to URL_user_entered_cleanif ABC_show_name is "" and SBS_show_name is "" thenset auto_gen to DL_YTAutoSTset author_gen to subtitles_choiceon check_subtitles_download_available(shellPath, diag_Title, subtitles_choice, URL_user_entered, theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel, MacYTDL_custom_icon_file, DL_Use_YTDLP)end set_File_Namesreturn URL_user_enteredset download_filename_new to run_Utilities_handlers's replace_chars(download_filename_new, ":", "_-")set YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-" & SBS_show_name_underscore & "-" & download_date_time & ".txt"set SBS_show_name_underscore to run_Utilities_handlers's replace_chars(SBS_show_name, " ", "_")set download_filename to SBS_show_nameset download_filename_new to run_Utilities_handlers's replace_chars(SBS_show_name, " ", "_")set YTDL_output_template to "-o '" & SBS_show_name & "-%(autonumber)s.%(ext)s'"set YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-" & SBS_show_name & "-" & download_date_time & ".txt"set URL_user_entered to run_Utilities_handlers's replace_chars(URL_user_entered, "https://www.sbs.com.au/ondemand/watch/", "https://www.sbs.com.au/api/v3/video_smil?id=")set download_filename to text 1 thru -1 of (do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & SBS_show_URLs & " " & YTDL_output_template)set download_filename_trimmed to download_filename_newif YTDL_simulate_log contains "ERROR: Unsupported URL: https://www.sbs.com.au/ondemand" thendisplay dialog (theSBSsimulateFailedLabel & return & return & errmsg) buttons {theButtonOKLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theSBSsimulateFailedLabel to localized string "Something went wrong trying to download from SBS. The error was: " from table "MacYTDL"if errmsg contains "ERROR: [ThePlatform]" or errmsg contains "HTTP Error 403: Forbidden" thenif number_ABC_SBS_episodes is 1 thenelse if SBS_show_name is not "" thenset YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-" & ABC_show_name_underscore & "-" & download_date_time & ".txt"set ABC_show_name_underscore to run_Utilities_handlers's replace_chars(ABC_show_name, " ", "_")set download_filename to text 1 thru -1 of (do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & ABC_show_URLs & " " & YTDL_output_template)set download_filename_trimmed to text 1 thru ((download_filename_new's length) - (offset of "." in (the reverse of every character of download_filename_new) as text)) of download_filename_newset download_filename to text 1 thru -1 of (do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & URL_user_entered & " " & YTDL_output_template)else if number_ABC_SBS_episodes is 1 thenset download_filename_trimmed to text 1 thru ((download_filename's length) - (offset of "." in (the reverse of every character of download_filename) as text)) of download_filenameset download_filename to last paragraph of (do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & URL_user_entered & " " & YTDL_output_template)if number_ABC_SBS_episodes is 0 thenelse if ABC_show_name is not "" thenset YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-Multiple_download_on-" & download_date_time & ".txt"set download_filename_new to "the multiple videos"else --<= This is a multiple file (iView and non-iView) download - don't distinguish between iView and others - covers warning and non-warning casesset download_filename_new to "the-error-download"else if YTDL_simulate_log contains "ERROR:" then --<= Single file download or playlist but simulate.txt contains ERROR (iView and non-iView) - need a generic file name for non-playlistsset download_filename_trimmed to download_filenameif text -1 thru -6 of YTDL_simulate_log contains "." thenset YTDL_simulate_log to paragraph (numParas - 1) of YTDL_simulate_logset numParas to count paragraphs in YTDL_simulate_logset YTDL_simulate_log to paragraph 1 of YTDL_simulate_logif YTDL_simulate_log contains "FutureWarning:" thenelse if YTDL_simulate_log contains "WARNING:" and YTDL_simulate_log does not contain "ERROR:" then --<= Single file download but simulate.txt contains WARNING(S) (iView and non-iView) - need to trim warning paras and ".mp4" from end of simulate log - but Futurewarning warnings have reverse layout in simulate logset download_filename_new to "the-playlist"set download_filename_new to run_Utilities_handlers's replace_chars(download_filename_new, " ", "_")set download_filename_new to playlist_Nameelse --<= Probably a Youtube playlist - but beware as there can be playlists on other sitesset YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-" & download_filename_trimmed & "-" & download_date_time & ".txt"set download_filename_new to run_Utilities_handlers's replace_chars(download_filename_only, " ", "_")set download_filename_trimmed to run_Utilities_handlers's replace_chars(download_filename_trimmed, " ", "_")set download_filename_trimmed to text 1 thru ((YTDL_simulate_log's length) - (offset of "." in (the reverse of every character of YTDL_simulate_log) as text)) of YTDL_simulate_logset download_filename_only to text 1 thru -2 of YTDL_simulate_logset download_filename_trimmed to text offsetOfLastSlash thru ((YTDL_simulate_log's length) - (offset of "." in (the reverse of every character of YTDL_simulate_log) as text)) of YTDL_simulate_logset download_filename_only to text offsetOfLastSlash thru -2 of YTDL_simulate_logset offsetOfLastSlash to last_offset(YTDL_simulate_log, "/") + 2if YTDL_simulate_log contains "/" thenif num_paragraphs_log is 2 then --<= A single file download (iView and non-iView) - need to trim ".mp4" from end of file (which is a single line containing one file name)if YTDL_simulate_log does not contain "WARNING:" and YTDL_simulate_log does not contain "ERROR:" then --<= A single file or playlist download non-error and non-warning (iView and non-iView)set download_filename to YTDL_simulate_logif number_of_URLs is 1 then -- Single file download or playlistif ABC_show_name is "" and SBS_show_name is "" then -- not an ABC or SBS show pageset number_of_URLs to number of text items in URL_user_enteredset num_paragraphs_log to count of paragraphs of YTDL_simulate_logon set_File_Names(shellPath, YTDL_simulate_log, URL_user_entered, ABC_show_name, SBS_show_name, DL_Use_YTDLP)end check_download_folderset quit_or_return to button returned of (display dialog theDownloadFolderMissingLabel buttons {theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theDownloadFolderMissingLabel to localized string "Your download folder is not available. You can make it available then click on Continue, return to set a new download folder or quit." from table "MacYTDL"if folder_chosen = downloadsFolder_Path thenon check_download_folder(folder_chosen)end check_cookies_fileelse if quit_or_return is theButtonQuitLabel thenset quit_or_return to button returned of (display dialog theCookiesFileMissingLabel buttons {theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theCookiesFileMissingLabel to localized string "Your cookies file is not available. You can make it available then click on Continue, return to set a new cookies location or quit." from table "MacYTDL"set cookies_Path_alias to cookies_Path_posix as aliasset cookies_Path_posix to (POSIX file DL_Cookies_Location)on check_cookies_file(DL_Cookies_Location)end download_videoif skip_Main_dialog is false thenset ABC_show_URLs to ""set SBS_show_URLs to ""set URL_user_entered to ""do shell script "osascript -s s " & myMonitorScriptAsString & " " & my_params & " " & " > /dev/null 2> /dev/null &"if branch_execution is "Quit" then quit_MacYTDL()if branch_execution is "Settings" then set_settings()set branch_execution to run_Utilities_handlers's show_settings(YTDL_subtitles, DL_Remux_original, DL_YTDL_auto_check, DL_STEmbed, DL_audio_only, YTDL_description, DL_Limit_Rate, DL_over_writes, DL_Thumbnail_Write, DL_verbose, DL_Thumbnail_Embed, DL_Add_Metadata, DL_Use_Proxy, DL_Use_Cookies, DL_Use_Custom_Template, DL_Use_Custom_Settings, remux_format_choice, DL_TimeStamps, DL_Use_YTDLP, YTDL_version, folder_chosen, theButtonQuitLabel, theButtonCancelLabel, theButtonDownloadLabel, DL_Show_Settings, MacYTDL_prefs_file, MacYTDL_custom_icon_file_posix, diag_Title)if DL_Show_Settings is true thenset my_params to quoted form of downloadsFolder_Path & " " & quoted form of MacYTDL_preferences_path & " " & YTDL_TimeStamps_quoted & " " & ytdl_settings & " " & URL_user_entered & " " & YTDL_log_file & " " & download_filename & " " & download_filename_new & " " & quoted form of MacYTDL_custom_icon_file_posix & " " & monitor_dialog_position & " " & YTDL_simulate_log & " " & diag_Title_quoted & " " & is_Livestream_Flag & " " & screen_width & " " & screen_height & " " & DL_Use_YTDLP & " " & quoted form of path_to_MacYTDLset YTDL_TimeStamps_quoted to quoted form of YTDL_TimeStampsset diag_Title_quoted to quoted form of diag_Titleset YTDL_simulate_log to quoted form of YTDL_simulate_logset YTDL_simulate_log to text 1 thru -2 of YTDL_simulate_logset YTDL_log_file to quoted form of YTDL_log_fileset download_filename_new to quoted form of download_filename_newset download_filename to quoted form of download_filenameset URL_user_entered to quoted form of URL_user_enteredif ABC_show_name is not "" or SBS_show_name is not "" thenset monitor_dialog_position to 1set monitor_dialog_position to ((count of paragraphs in monitor_dialogs_list) / 2) + 1set monitor_dialogs_list to do shell script "pgrep -f osascript"try -- In a try block to catch error of nil pids returnedset myMonitorScriptAsString to quoted form of ((POSIX path of path_to_MacYTDL) & "Contents/Resources/Scripts/Monitor.scpt")add_To_Batch(URL_user_entered, download_filename_new, YTDL_remux_format)if SBS_show_indicator is "Yes" thenset overwrite_continue_choice to button returned of (display dialog theShowExistsWarningTextLabel1 & " \"" & each_filename & "\" " & theShowExistsWarningTextLabel2 & return & return & theShowExistsWarningTextLabel3 buttons {theShowExistsButtonOverwriteLabel, theShowExistsButtonNewnameLabel, theButtonReturnLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theShowExistsWarningTextLabel3 to localized string "Do you want to continue anyway, download with a different name or stop and return to the main dialog ?" from table "MacYTDL"set theShowExistsWarningTextLabel2 to localized string "already exists." from table "MacYTDL"set theShowExistsWarningTextLabel1 to localized string "The file" from table "MacYTDL"repeat with each_filename in (get paragraphs of YTDL_simulate_log)set download_filename_new to SBS_show_nameelse if overwrite_continue_choice is theShowExistsButtonNewnameLabel thenif overwrite_continue_choice is theShowExistsButtonOverwriteLabel thenset overwrite_continue_choice to button returned of (display dialog theShowExistsLabel1 & " \"" & each_filename & "\" " & theShowExistsLabel2 & return & return & theShowExistsLabel3 buttons {theShowExistsButtonOverwriteLabel, theShowExistsButtonNewnameLabel, theButtonReturnLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theShowExistsButtonNewnameLabel to localized string "New name" from table "MacYTDL"set theShowExistsButtonOverwriteLabel to localized string "Overwrite" from table "MacYTDL"set theShowExistsLabel3 to localized string "Do you want to continue anyway, download with a different name or stop and return to the main dialog ?" from table "MacYTDL"set theShowExistsLabel2 to localized string "already exists." from table "MacYTDL"set theShowExistsLabel1 to localized string "A file for the SBS show" from table "MacYTDL"else if SBS_show_indicator is "Yes" thenset download_filename_new to ABC_show_nameif (count of paragraphs of download_filename_new_plain) is greater than 1 thenmy main_dialog()if DL_auto is false thenelse if overwrite_continue_choice is theButtonReturnLabel thenset ytdl_settings to quoted form of (" --ignore-errors --newline " & YTDL_subtitles & YTDL_STEmbed & YTDL_credentials & YTDL_format & YTDL_remux_format & YTDL_Remux_original & YTDL_description & YTDL_audio_only & YTDL_audio_codec & YTDL_over_writes & YTDL_metadata & YTDL_limit_rate_value & YTDL_verbose & YTDL_Use_Proxy & YTDL_Use_Cookies & YTDL_no_playlist & YTDL_no_part & YTDL_Custom_Settings & YTDL_output_template_new & " " & YTDL_QT_Compat & " " & YTDL_formats_to_download & " ")set download_filename_new to run_Utilities_handlers's replace_chars(download_filename_new, set_new_download_filename, set_new_download_filename & "-2")set set_new_download_filename to text 1 thru -5 of download_filename_newset YTDL_output_template_new to run_Utilities_handlers's replace_chars(YTDL_output_template, ".%(ext)s", "-2.%(ext)s")else if overwrite_continue_choice is theABCShowExistsButtonNewnameLabel thenset ytdl_settings to quoted form of (" --ignore-errors --newline " & YTDL_subtitles & YTDL_STEmbed & YTDL_credentials & YTDL_format & YTDL_remux_format & YTDL_Remux_original & YTDL_description & YTDL_audio_only & YTDL_audio_codec & YTDL_metadata & YTDL_limit_rate_value & YTDL_verbose & YTDL_Use_Proxy & YTDL_Use_Cookies & YTDL_no_playlist & YTDL_no_part & YTDL_Custom_Settings & YTDL_output_template & " " & YTDL_QT_Compat & " " & YTDL_formats_to_download & " ")do shell script "mv " & file_to_delete & " ~/.trash/"set file_to_delete to quoted form of (POSIX path of (downloadsFolder_Path & "/" & search_for_download))set search_for_download to search_for_download as textif overwrite_continue_choice is theABCShowExistsButtonOverwriteLabel thenset overwrite_continue_choice to button returned of (display dialog theABCShowExistsLabel1 & " \"" & each_filename & "\" " & theABCShowExistsLabel2 & return & return & theABCShowExistsLabel3 buttons {theABCShowExistsButtonOverwriteLabel, theABCShowExistsButtonNewnameLabel, theButtonReturnLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theABCShowExistsButtonNewnameLabel to localized string "New name" from table "MacYTDL"set theABCShowExistsButtonOverwriteLabel to localized string "Overwrite" from table "MacYTDL"set theABCShowExistsLabel3 to localized string "Do you want to continue anyway, download with a different name or stop and return to the main dialog ?" from table "MacYTDL"set theABCShowExistsLabel2 to localized string "already exists." from table "MacYTDL"set theABCShowExistsLabel1 to localized string "A file for the ABC show" from table "MacYTDL"if search_for_download is not {} thenset search_for_download to (name of files in downloadsFolder_Path_alias where name contains each_filename)if length_each_filename is not 0 thenset length_each_filename to count words of each_filenameset each_filename to text offset_to_file_name thru end of each_filenameset offset_to_file_name to last_offset(each_filename, "/") + 2if each_filename contains "/" thenset each_filename to each_filename as textrepeat with each_filename in (get paragraphs of download_filename_new_plain)set download_filename_new_plain to run_Utilities_handlers's replace_chars(download_filename_new, "_", " ")if ABC_show_indicator is "Yes" thenset search_for_download to {}set downloadsFolder_Path_alias to downloadsFolder_Path_posix as aliasset downloadsFolder_Path_posix to (POSIX file downloadsFolder_Path)if DL_over_writes is true thenset ytdl_settings to quoted form of (" --ignore-errors --newline " & YTDL_subtitles & YTDL_STEmbed & YTDL_credentials & YTDL_format & YTDL_remux_format & YTDL_Remux_original & YTDL_description & YTDL_audio_only & YTDL_audio_codec & YTDL_over_writes & YTDL_Thumbnail_Write & YTDL_Thumbnail_Embed & YTDL_metadata & YTDL_limit_rate_value & YTDL_verbose & YTDL_Use_Proxy & YTDL_Use_Cookies & YTDL_no_playlist & YTDL_no_part & YTDL_Custom_Settings & YTDL_output_template & " " & YTDL_QT_Compat & " " & YTDL_formats_to_download & " ")set YTDL_output_template to run_Utilities_handlers's replace_chars(YTDL_output_template, ".%(ext)s", "." & format_id_output_template & ".%(ext)s")if format_id_output_template is not "" thenset format_id_output_template to text item 3 of chosen_formats_list -- Contains "%(format_id)s" if user has asked to not merge but to download and retain each formatif YTDL_formats_to_download contains "," thenset YTDL_formats_to_download to " --format " & text item 2 of chosen_formats_listelse if branch_execution is "Download" thenif branch_execution is "Main" thenset format_id_output_template to ""set branch_execution to text item 1 of chosen_formats_listset chosen_formats_list to run_Utilities_handlers's get_formats_list(URL_user_entered, diag_Title, theButtonCancelLabel, theButtonDownloadLabel, X_position, screen_height, MacYTDL_custom_icon_file, MacYTDL_custom_icon_file_posix, theButtonReturnLabel, skip_Main_dialog, path_to_MacYTDL, DL_Use_YTDLP, shellPath, download_filename_formats, YTDL_credentials)set chosen_formats_list to ""set download_filename_formats to quoted form of download_filenameif DL_formats_list is true thenset YTDL_formats_to_download to ""set YTDL_subtitles to check_subtitles_download_available(shellPath, diag_Title, subtitles_choice, URL_user_entered, theButtonQuitLabel, theButtonReturnLabel, theButtonContinueLabel, MacYTDL_custom_icon_file, DL_Use_YTDLP)if subtitles_choice is true or DL_YTAutoST is true thenset URL_user_entered to set_File_Names(shellPath, YTDL_simulate_log, URL_user_entered, ABC_show_name, SBS_show_name, DL_Use_YTDLP)else if warning_quit_or_continue is theWarningButtonsMainLabel then -- <= Stop and return to Main dialogset_File_Names(shellPath, YTDL_simulate_log, URL_user_entered, ABC_show_name, SBS_show_name, DL_Use_YTDLP)if warning_quit_or_continue is theButtonContinueLabel then -- <= Ignore warning - try DL - get filename from last paragraph of simulate fileset warning_quit_or_continue to button returned of (display dialog theURLWarningTextLabel1 & return & return & URL_user_entered & return & return & theURLWarningTextLabel2 & return & return & simulate_warnings & return & return & theURLWarningTextLabel3 buttons {theWarningButtonsMainLabel, theButtonContinueLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theWarningButtonsMainLabel to localized string "Main" from table "MacYTDL"set theURLWarningTextLabel3 to (localized string "You can return to the main dialog or continue to see what happens." from table "MacYTDL")set theURLWarningTextLabel2 to localized string "The warning message(s) was: " from table "MacYTDL"set theURLWarningTextLabel1 to DL_Use_YTDLP & (localized string " has given a warning on the URL you entered:" from table "MacYTDL")if simulate_warnings is not "" thenif is_SBS_bug_page is false thenset simulate_warnings to simulate_warnings & return & aParaset simulate_warnings to aParaif simulate_warnings is "" thenif aPara contains "WARNING:" and aPara does not contain "Falling back on generic information" and aPara does not contain "Ignoring subtitle tracks found in the HLS manifest" and aPara does not contain "FutureWarning:" thenrepeat with aPara in (paragraphs of YTDL_simulate_log)set simulate_warnings to ""set theTooManyUELsLabel to localized string "Sorry, but MacYTDL cannot list formats for more than one SBS show. Would you like to cancel the download and return to the main dialog or skip the formats list and continue to download ?" from table "MacYTDL"set number_ABC_SBS_episodes to number of text items in SBS_show_URLsset URL_user_entered to SBS_show_URLsset SBS_show_indicator to "Yes"set branch_execution to run_Utilities_handlers's Get_SBS_Episodes(URL_user_entered, diag_Title, theButtonOKLabel, theButtonCancelLabel, theButtonDownloadLabel, X_position, screen_height, MacYTDL_custom_icon_file, MacYTDL_custom_icon_file_posix, theButtonReturnLabel, skip_Main_dialog, path_to_MacYTDL)set SBS_show_name to "This is a watcher URL"set URL_user_entered to ("https://www.sbs.com.au/ondemand/watch/" & check_URL_ID)else if is_ID is true and length_check_URL_ID is greater than 7 and URL_user_entered does not contain "watch" thenset YTDL_output_template to "-o '" & download_filename_new & ".%(ext)s'"if YTDL_remux_format contains "recode" then set YTDL_remux_format to ""set YTDL_log_file to MacYTDL_preferences_path & "youtube-dl_log-" & download_filename_new & "-" & download_date_time & ".txt"set download_date_time to get_Date_Time()set download_filename_new to run_Utilities_handlers's replace_chars(download_filename, " ", "_")set AppleScript's text item delimiters to {"title=\"", "\" copyright="}set download_filename to (text item 2 of SBS_workaround_page) & ".mp4"set AppleScript's text item delimiters to {"title=\"", "\" abstract="}if SBS_workaround_page contains "abstract" thenset SBS_workaround_page to do shell script "curl " & URL_user_enteredset number_ABC_SBS_episodes to 1set SBS_show_name to "This is a bug URL"set URL_user_entered to ("https://www.sbs.com.au/api/v3/video_smil?id=" & check_URL_ID)if is_SBS_bug_page is true thenset is_ID to falseon error errText number errNumset is_ID to trueset check_URL_number to check_URL_ID as numberset length_check_URL_ID to length of check_URL_IDset check_URL_ID to last word of URL_user_entereddo shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename " & YTDL_credentials & URL_user_entered & " " & YTDL_output_template & " > /dev/null" & " &> " & YTDL_simulate_fileset URL_user_entered to quoted form of ("https://www.sbs.com.au/ondemand/watch/" & SBS_movie_ID)set SBS_movie_ID to text 1 thru -2 of (last text item of URL_user_entered)else if URL_user_entered contains "/ondemand/movie/" thendisplay dialog theOnDemandURLProblemLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 100set theOnDemandURLProblemLabel to localized string "MacYTDL cannot download video from an SBS OnDemand \"Play\" or Search links. Navigate to a \"Show\" page and try again." from table "MacYTDL"if YTDL_simulate_log contains "?play=" or URL_user_entered contains "ondemand/search" thenset URL_user_entered to (text 1 thru -14 of URL_user_entered & "'")if URL_user_entered contains "?action=play" thenif YTDL_simulate_log contains "Unsupported URL: https://www.sbs.com.au/ondemand" or is_SBS_bug_page is true thenset DL_formats_list to falseelse if skip_or_return is theButtonContinueLabel thenset theTooManyUELsLabel to localized string "Sorry, but MacYTDL cannot list formats for more than one ABC show. Would you like to cancel the download and return to the main dialog or skip the formats list and continue to download ?" from table "MacYTDL"if number_ABC_SBS_episodes is greater than 1 and DL_formats_list is true thenset number_ABC_SBS_episodes to number of text items in ABC_show_URLsset URL_user_entered to ABC_show_URLsset ABC_show_indicator to "Yes"if branch_execution is "Main" then main_dialog()set branch_execution to run_Utilities_handlers's Get_ABC_Episodes(URL_user_entered, diag_Title, theButtonOKLabel, theButtonCancelLabel, theButtonDownloadLabel, X_position, screen_height, MacYTDL_custom_icon_file, MacYTDL_custom_icon_file_posix, theButtonReturnLabel, skip_Main_dialog, path_to_MacYTDL)set URL_user_entered_clean to (URL_user_entered_clean & "/")if last character of URL_user_entered_clean is not "/" thenif URL_user_entered_clean contains "iview.abc.net.au/show/" thenset SBS_show_indicator to "No"set ABC_show_indicator to "No"display dialog theURLErrorTextLabel1 buttons {theButtonOKLabel} with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theURLErrorTextLabel1 to localized string "There was an error with the URL you entered. The video might be DRM protected or it could be a network, VPN or macOS install issue. If the URL is correct, you may need to look more deeply into your network settings and macOS install." from table "MacYTDL"if YTDL_simulate_log contains "IOError: CRC check failed" thenset quit_or_return to button returned of (display dialog theURLErrorTextLabel1 & theURLErrorTextLabel4 & return & return & URL_user_entered & return & return & theURLErrorTextLabel2 & return & return & YTDL_simulate_log & return & theURLErrorTextLabel3 buttons {theButtonQuitLabel, theButtonOKLabel, theButtonDownloadLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theURLErrorTextLabel3 to localized string "Quit, OK to return or Download to try anyway." from table "MacYTDL"set quit_or_return to button returned of (display dialog theURLErrorTextLabel1 & " " & theURLErrorTextLabel4 & return & return & URL_user_entered & return & return & theURLErrorTextLabel2 & return & return & YTDL_simulate_log & return & theURLErrorTextLabel3 buttons {theButtonOKLabel, theButtonDownloadLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theURLErrorTextLabel3 to localized string "OK to give up or Download to try anyway." from table "MacYTDL"set theURLErrorTextLabel2 to localized string "The error message was: " from table "MacYTDL"set theURLErrorTextLabel1 to localized string "There was an error with the URL you entered" from table "MacYTDL"set theURLErrorTextLabel4 to ":"set theURLErrorTextLabel4 to localized string theURLErrorTextLabelString & " " & "'" & playlist_Name & "':"set theURLErrorTextLabelString to localized string "for the playlist" from table "MacYTDL"if playlist_Name is not "" thenset is_SBS_bug_page to trueelse if URL_user_entered_clean contains "https://www.sbs.com.au/ondemand/" and YTDL_simulate_log contains "HTTP Error 403: Forbidden" thenif URL_user_entered_clean contains "https://iview.abc.net.au/show" and YTDL_simulate_log contains "An extractor error has occurred" thenif YTDL_simulate_log contains "ERROR:" and YTDL_simulate_log does not contain "Unsupported URL: https://www.sbs.com.au/ondemand" and YTDL_simulate_log does not contain "Unsupported URL: https://iview.abc.net.au/show" thenset is_SBS_bug_page to falseset YTDL_simulate_log to run_Utilities_handlers's replace_chars(YTDL_simulate_log, "NA#", "") -- Removes placeholder when there is no is_live returned by simulateset YTDL_simulate_log to run_Utilities_handlers's replace_chars(YTDL_simulate_log, "False#", "")set YTDL_simulate_log to run_Utilities_handlers's replace_chars(YTDL_simulate_log, "True#", "")set remux_format_choice to "mp4"if YTDL_format_pref is "3gp" thenset remux_format_choice to DL_formatelse if quit_or_return is "Remux" thendo shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename " & YTDL_no_playlist & DL_Playlist_Items_Spec & YTDL_credentials & URL_user_entered_clean_quoted & " " & simulate_YTDL_output_template & " > /dev/null" & " &> " & YTDL_simulate_fileelse if quit_or_return is theButtonDownloadLabel thenset quit_or_return to button returned of (display dialog theFormatNotAvailLabel1 & return & theFormatNotAvailLabel2 buttons {theButtonReturnLabel, theFormatNotAvailButtonRemuxLabel, theButtonDownloadLabel} default button 3 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theFormatNotAvailButtonRemuxLabel to localized string "Remux" from table "MacYTDL"set theFormatNotAvailLabel2 to localized string "{Note: 3gp format is not available - a request for 3gp will be remuxed into mp4.}" from table "MacYTDL"set theFormatNotAvailLabel1 to localized string "Your preferred file format is not available. Would you like to cancel download and return, have your download remuxed into your preferred format or just download the best format available ?" from table "MacYTDL"if YTDL_simulate_log contains "requested format not available" thendisplay dialog theURLWarning10playLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theURLWarning10playLabel to localized string "This is a 10Play Show page from which MacYTDL cannot download videos. Try an individual episode." from table "MacYTDL"if YTDL_simulate_log contains "Unsupported URL: https://10play.com.au" thendisplay dialog theURLWarning9NowLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theURLWarning9NowLabel to localized string "This is a 9Now Show page from which MacYTDL cannot download videos. Try an individual episode." from table "MacYTDL"if YTDL_simulate_log contains "Unsupported URL: https://www.9now.com.au" thendisplay dialog theURLWarning7PlusLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theURLWarning7PlusLabel to localized string "This is a 7Plus Show page from which MacYTDL cannot download videos. Try an individual episode." from table "MacYTDL"if YTDL_simulate_log contains "Unsupported URL: https://7Plus.com.au" thenset YTDL_simulate_log to run_Utilities_handlers's replace_chars(YTDL_simulate_log, "NA-", "") -- Removes placeholder when there is no series name - put there by output template for ABC, ITV & 7Plusif YTDL_simulate_log contains "#NA-" and (URL_user_entered contains "ABC" or URL_user_entered contains "ITV" or URL_user_entered contains "7Plus") thendo shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & YTDL_no_playlist & DL_Playlist_Items_Spec & YTDL_format_pref & YTDL_credentials & YTDL_Use_Proxy & YTDL_Use_Cookies & simulate_YTDL_output_template & " " & URL_user_entered_clean_quoted & " 2>&1 &>" & YTDL_simulate_file & " ; exit 0"set YTDL_output_template to " -o '%(is_live)s#%(title)s.%(ext)s'"set quit_or_return to button returned of (display dialog theFileNameTooLongLabel buttons {theButtonReturnLabel, theButtonContinueLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theFileNameTooLongLabel to localized string "With your custom file name output template, the total length of the log file name is too long. Would you like to exclude your custom template then continue or return to Main ?" from table "MacYTDL"if (length of YTDL_simulate_log is greater than 195) and ((count of paragraphs in YTDL_simulate_log) is less than 3) thenset YTDL_no_part to "--no-part "set is_Livestream_Flag to "True"if YTDL_simulate_log contains "True#" thenif playlist_Name is "" thenset is_Livestream_Flag to "False"display dialog "Error in reading simulate file: " & YTDL_simulate_file & return & "The error reported was " & errmsgon error errmsgset YTDL_simulate_log to read POSIX file YTDL_simulate_file as «class utf8»do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; export LC_CTYPE=UTF-8 ; " & DL_Use_YTDLP & " --get-filename --ignore-errors " & YTDL_format_pref & DL_Playlist_Items_Spec & YTDL_credentials & YTDL_Use_Proxy & YTDL_Use_Cookies & YTDL_no_playlist & simulate_YTDL_output_template & " " & URL_user_entered_clean_quoted & " 2>&1 &>" & YTDL_simulate_file & " ; exit 0"set simulate_YTDL_output_template to run_Utilities_handlers's replace_chars(YTDL_output_template, " -o '%", " -o '%(is_live)s#%")set thePlaylistAndListLabel to localized string "Sorry, but MacYTDL cannot list formats for channels. Would you like to cancel the download and return to the main dialog or skip the formats list and continue to download ?" from table "MacYTDL"if is_channel is true and DL_formats_list is true thenset skip_or_return to button returned of (display dialog thePlaylistAndListLabel buttons {theButtonReturnLabel, theButtonContinueLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set thePlaylistAndListLabel to localized string "Sorry, but MacYTDL cannot list formats for playlists. Would you like to cancel the download and return to the main dialog or skip the formats list and continue to download ?" from table "MacYTDL"if playlist_Name is not "" and DL_formats_list is true thenif skip_or_return is theButtonReturnLabel thenset skip_or_return to button returned of (display dialog theTooManyUELsLabel buttons {theButtonReturnLabel, theButtonContinueLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theTooManyUELsLabel to localized string "Sorry, but MacYTDL cannot list formats for more than one URL. Would you like to cancel the download and return to the main dialog or skip the formats list and continue to download ?" from table "MacYTDL"if number_of_URLs is greater than 1 and DL_formats_list is true thenset theManyPlaylistItemsLabel2 to localized string " items in channel " from table "MacYTDL"set playlist_Number_Items to last text item of playlist_details as integerset AppleScript's text item delimiters to {" "}set playlist_Name to text item 2 of playlist_detailsset AppleScript's text item delimiters to {"[youtube:tab] Playlist ", " - Videos: Downloading ", " - Topic: Downloading "}set playlist_details to paragraph (x) of playlist_Simulateif (contents of paragraph x of playlist_Simulate contains " - Videos: Downloading ") or (contents of paragraph x of playlist_Simulate contains " - Topic: Downloading ") thenif DL_Use_Cookies is true and error_Message contains "channel does not exist" thenset theErrorWithPlaylistLabel1 to "There was an error with the channel. The error was: \""set playListAlertSubtitle to quoted form of (localized string "Now checking detail of channel. " from table "MacYTDL")if playlist_Name is "" and DL_Use_YTDLP is "yt-dlp" and is_channel is true thenset quit_or_return to button returned of (display dialog theManyPlaylistItemsLabel1 & playlist_Number_Items & theManyPlaylistItemsLabel2 & "\"" & playlist_Name & "\". " & theManyPlaylistItemsLabel3 buttons {theButtonReturnLabel, theButtonContinueLabel} default button 2 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theManyPlaylistItemsLabel3 to localized string "It will take a long time to download. Do you wish to continue or return to the Main dialog ?" from table "MacYTDL"set theManyPlaylistItemsLabel2 to localized string " items in playlist " from table "MacYTDL"set theManyPlaylistItemsLabel1 to localized string "There are " from table "MacYTDL"if alerterPiD is not "" then do shell script "kill " & alerterPiDif playlist_Number_Items is greater than 20 thenset playlist_Number_Items to text item 2 of PL_simulate_Paragraph as integerset AppleScript's text item delimiters to {": Downloading ", " items "}set PL_simulate_Paragraph to paragraph (x) of playlist_Simulateif contents of paragraph x of playlist_Simulate begins with "[youtube:tab] Playlist" thenrepeat with x from 1 to count paragraphs of playlist_Simulateset playlist_Number_Items to text item 3 of playlist_Simulate as integerset playlist_Number_Items to text item 4 of playlist_Simulate as integerif (URL_user_entered_clean contains "list=PL" or URL_user_entered_clean contains "list=OL") and (URL_user_entered_clean contains "watch?" or URL_user_entered_clean contains "//youtu.be/") thenset AppleScript's text item delimiters to {": Downloading ", " videos"}set playlist_Name to run_Utilities_handlers's replace_chars(playlist_Name, "/", "_")if playlist_Name contains "/" thenset playlist_Name to text item 2 of playlist_Simulateset AppleScript's text item delimiters to {"[download] Downloading playlist: ", return & "[youtube:tab] Playlist "}display dialog theErrorWithPlaylistLabel1 & error_Message & "\" " & theErrorWithPlaylistLabel2 buttons {theButtonReturnLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theErrorWithPlaylistLabel2 to "Check the URL and try again."set theErrorWithPlaylistLabel2 to "This may have been caused by a faulty cookies file. Check the file and try again."if DL_Use_Cookies is true and error_Message contains "playlist does not exist" thenset theErrorWithPlaylistLabel1 to "There was an error with the playlist. The error was: \""do shell script "kill " & alerterPiDon error error_Messageset playlist_Simulate to do shell script shellPath & "cd " & quoted form of downloadsFolder_Path & " ; " & DL_Use_YTDLP & " --flat-playlist " & DL_Playlist_Items_Spec & YTDL_Use_Cookies & URL_user_entered_clean_quotedset alerterPiD to do shell script quoted form of (resourcesPath & "alerter") & " -message " & playListAlertMessage & " -title " & playListAlertTitle & " -subtitle " & playListAlertSubtitle & " -sender com.apple.script.id.MacYTDL -actions " & playListAlertActionLabel & " -timeout 10 > /dev/null 2> /dev/null & echo $!"set playListAlertSubtitle to quoted form of (localized string "Now checking detail of playlist. " from table "MacYTDL")set playListAlertMessage to quoted form of (localized string " Please wait." from table "MacYTDL")set playListAlertTitle to quoted form of (localized string "MacYTDL" from table "MacYTDL")set playListAlertActionLabel to quoted form of "_"else if URL_user_entered_clean contains "playlist" or (URL_user_entered_clean contains "watch?" and URL_user_entered_clean contains "&list=") or (URL_user_entered_clean contains "?list=") thenset YTDL_no_playlist to "--no-playlist "if URL_user_entered_clean contains "&index=" and URL_user_entered_clean contains "youtu" thenset DL_Playlist_Items_Spec to ("--playlist-items " & text item (i + 1) of DL_Custom_Settings & " ")if text item (i) of DL_Custom_Settings is "-I" or text item (i) of DL_Custom_Settings is "--playlist-items" thenrepeat with i from 1 to num_custom_settings_itemsset num_custom_settings_items to count of text items in DL_Custom_Settingsif DL_Custom_Settings contains "playlist-items" or DL_Custom_Settings contains "-I" thenset alerterPiD to ""set DL_Playlist_Items_Spec to ""set playlist_Name to ""set YTDL_no_playlist to ""set URL_user_entered_clean_quoted to quoted form of URL_user_entered_cleanset URL_user_entered_clean_quoted to URL_user_entered_clean_quoted & current_URL & " "set current_URL to "'" & current_URL & "'"repeat with current_URL in text items of URL_user_entered_cleanset URL_user_entered_clean_quoted to ""if number_of_URLs is greater than 1 thenset number_of_URLs to number of text items in URL_user_entered_cleandisplay dialog theYTChannelLabel buttons {theButtonReturnLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600set theYTChannelLabel to localized string "The URL you entered looks like a YouTube channel. You are using youtube-dl for your download. Currently, MacYTDL cannot download channels with youtube-dl." from table "MacYTDL"set is_channel to trueif quit_or_return is theButtonReturnLabel thenset quit_or_return to button returned of (display dialog theYTChannelLabel buttons {theButtonReturnLabel, theButtonContinueLabel} default button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theYTChannelLabel to localized string "The URL you entered looks like a YouTube channel. Most channels have a great many videos, some have hundreds. It may take hours to check and download each video. Do you really wish to continue or return to the Main dialog ?" from table "MacYTDL"if URL_user_entered_clean contains "https://www.youtube.com/c/" or URL_user_entered_clean contains "https://www.youtube.com/channel/" or URL_user_entered_clean contains "https://www.youtube.com/user/" or URL_user_entered_clean contains "https://www.youtube.com/@" thenset is_channel to falseelse if URL_user_entered contains "7Plus" thenset YTDL_output_template to " -o '" & NineNow_show_new & "-%(title)s.%(ext)s'"set NineNow_show_new to run_Utilities_handlers's replace_chars(NineNow_show_old, "-", "_")set NineNow_show_old to text 1 thru end of item 4 of NineNow_URL_itemsset NineNow_URL_items to every text item of URL_user_entered_sans_qset URL_user_entered_sans_q to text 1 thru -2 of URL_user_enteredelse if URL_user_entered contains "9Now" thenset YTDL_output_template to " -o '%(series)s-%(season)s-%(title)s.%(ext)s'"else if URL_user_entered contains "ITV" thenset YTDL_output_template to " -o '%(series)s-%(title)s.%(ext)s'"if URL_user_entered contains "ABC" thenset YTDL_output_template to " -o '" & YTDL_Custom_Template & "'"if YTDL_Custom_Template is not "" thenset YTDL_output_template to " -o '%(title)s.%(ext)s'"display dialog theURLWarningSBSCategoryLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theURLWarningSBSCategoryLabel to localized string "This is an SBS OnDemand Category page from which MacYTDL cannot download videos. Try an individual show." from table "MacYTDL"if URL_user_entered is "'https://www.sbs.com.au/ondemand'" or URL_user_entered is "'https://www.sbs.com.au/ondemand/tv-shows'" or URL_user_entered contains "https://www.sbs.com.au/ondemand/collection" or URL_user_entered contains "-collection" or URL_user_entered contains "https://www.sbs.com.au/ondemand/sport" or URL_user_entered contains "https://www.sbs.com.au/ondemand/movies" or URL_user_entered contains "https://www.sbs.com.au/ondemand/live" or URL_user_entered contains "https://www.sbs.com.au/ondemand/fifa-world-cup-2022" or URL_user_entered contains "https://www.sbs.com.au/ondemand/favourites" thenif URL_user_entered contains "https://www.sbs.com.au/ondemand" thendisplay dialog theURLWarningiViewCategoryLabel with title diag_Title buttons {theButtonOKLabel} default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set theURLWarningiViewCategoryLabel to localized string "This is an iView page from which MacYTDL cannot download videos. Try an individual show." from table "MacYTDL"if URL_user_entered contains "https://iview.abc.net.au/category" or URL_user_entered contains "https://iview.abc.net.au/collection" or URL_user_entered is "'https://iview.abc.net.au/browse'" or URL_user_entered contains "https://iview.abc.net.au/channel" or URL_user_entered is "'https://iview.abc.net.au'" or URL_user_entered is "'https://iview.abc.net.au/'" thenset quit_or_return to button returned of (display dialog theURLTooShortLabel1 & " \"" & URL_user_entered & "\" " & theURLTooShortLabel2 buttons {theButtonQuitLabel, theButtonOKLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theURLTooShortLabel2 to localized string "is not valid. It should begin with the letters http. You need to paste a valid URL before selecting Download, Quit or OK to try again." from table "MacYTDL"set theURLTooShortLabel1 to localized string "The URL" from table "MacYTDL"if skip_Main_dialog is true thenset quit_or_return to button returned of (display dialog theURLNothttpLabel1 & " \"" & URL_user_entered & "\" " & theURLNothttpLabel2 buttons {theButtonQuitLabel, theButtonOKLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theURLNothttpLabel2 to localized string "is not valid. It should begin with the letters http. You need to paste a valid URL before selecting Download. Quit or OK to try again." from table "MacYTDL"set theURLNothttpLabel1 to localized string "The URL" from table "MacYTDL"if not test_URL is "http" thenset test_URL to text 2 thru 5 of URL_user_enteredif length of URL_user_entered is greater than 4 thenif quit_or_return is theButtonOKLabel thenset quit_or_return to button returned of (display dialog theURLBlankLabel buttons {theButtonQuitLabel, theButtonOKLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theURLBlankLabel to localized string "You need to paste a URL before selecting Download. Quit or OK to try again." from table "MacYTDL"if URL_user_entered is "" or URL_user_entered is "''" thenset URL_user_entered to quoted form of (text 2 thru -3 of URL_user_entered) -- Why not just remove the trailing slash ??if text -2 of URL_user_entered is "/" thenset URL_user_entered_clean to URL_user_entered_from_auto_downloadif URL_user_entered_from_auto_download is not "" thenon download_video(shellPath, path_to_MacYTDL, MacYTDL_custom_icon_file, MacYTDL_custom_icon_file_posix, screen_width, screen_height, YTDL_simulate_file, URL_user_entered, URL_user_entered_from_auto_download, folder_chosen, diag_Title, DL_batch_status, remux_format_choice, subtitles_choice, YTDL_credentials, YTDL_subtitles, YTDL_STEmbed, YTDL_format_pref, YTDL_format, YTDL_remux_format, YTDL_Remux_original, YTDL_description, YTDL_audio_only, YTDL_audio_codec, YTDL_over_writes, YTDL_Thumbnail_Write, YTDL_Thumbnail_Embed, YTDL_metadata, YTDL_limit_rate_value, YTDL_verbose, YTDL_TimeStamps, YTDL_Use_Proxy, YTDL_Use_Cookies, YTDL_Custom_Settings, YTDL_Custom_Template, YTDL_no_part, skip_Main_dialog, theButtonOKLabel, theButtonCancelLabel, theButtonDownloadLabel, theButtonReturnLabel, theButtonQuitLabel, theButtonContinueLabel, YTDL_QT_Compat, DL_Use_YTDLP)end main_dialogdownload_video(shellPath, path_to_MacYTDL, MacYTDL_custom_icon_file, MacYTDL_custom_icon_file_posix, screen_width, screen_height, YTDL_simulate_file, URL_user_entered, URL_user_entered_from_auto_download, folder_chosen, diag_Title, DL_batch_status, remux_format_choice, subtitles_choice, YTDL_credentials, YTDL_subtitles, YTDL_STEmbed, YTDL_format_pref, YTDL_format, YTDL_remux_format, YTDL_Remux_original, YTDL_description, YTDL_audio_only, YTDL_audio_codec, YTDL_over_writes, YTDL_Thumbnail_Write, YTDL_Thumbnail_Embed, YTDL_metadata, YTDL_limit_rate_value, YTDL_verbose, YTDL_TimeStamps, YTDL_Use_Proxy, YTDL_Use_Cookies, YTDL_Custom_Settings, YTDL_Custom_Template, YTDL_no_part, skip_Main_dialog, theButtonOKLabel, theButtonCancelLabel, theButtonDownloadLabel, theButtonReturnLabel, theButtonQuitLabel, theButtonContinueLabel, YTDL_QT_Compat, DL_Use_YTDLP)open_batch_processing(folder_chosen, remux_format_choice, subtitles_choice, YTDL_credentials, YTDL_subtitles, YTDL_STEmbed, YTDL_format, YTDL_remux_format, YTDL_Remux_original, YTDL_description, YTDL_audio_only, YTDL_audio_codec, YTDL_over_writes, YTDL_Thumbnail_Write, YTDL_Thumbnail_Embed, YTDL_metadata, YTDL_limit_rate_value, YTDL_verbose, YTDL_TimeStamps, YTDL_Use_Proxy, YTDL_Use_Cookies, YTDL_Custom_Settings, YTDL_Custom_Template, YTDL_no_part, YTDL_QT_Compat, DL_Use_YTDLP)if openBatch_chosen is true thenif button_number_returned is 5 then -- Continue to downloadset skip_Main_dialog to falseset downloadsFolder_Path to folder_chosenset URL_user_entered_from_auto_download to ""set folder_chosen to text 1 thru offset_to_file_name of folder_chosenset offset_to_file_name to last_offset(folder_chosen as text, "/")if test_DL_folder is "file" thentell application "System Events" to set test_DL_folder to (get class of item (folder_chosen as text)) as textif DL_Use_Cookies is true then check_cookies_file(DL_Cookies_Location)check_download_folder(folder_chosen)set YTDL_audio_codec to "--extract-audio --audio-format " & DL_audio_codec & " --audio-quality 0 "set YTDL_audio_only to "--format bestaudio "if YTDL_get_formats contains "audio only" and DL_audio_codec is theBestLabel thenset YTDL_get_formats to errStrset YTDL_get_formats to do shell script shellPath & DL_Use_YTDLP & " --list-formats --ignore-errors " & one_playlist_item & URL_user_entered & " 2>&1"set one_playlist_item to "--playlist-items 1 "if URL_user_entered_clean contains "playlist" or (URL_user_entered_clean contains "watch?" and URL_user_entered_clean contains "&list=") or (URL_user_entered_clean contains "?list=") thenset one_playlist_item to ""if DL_audio_only is true thenset YTDL_no_part to ""set YTDL_QT_Compat to ""set YTDL_QT_Compat to "--recode-video \"mp4\" --ppa \"VideoConvertor:-vcodec libx264 -acodec aac\" "if DL_QT_Compat is true thenset YTDL_Custom_Template to ""set YTDL_Custom_Template to DL_Custom_Templateif DL_Use_Custom_Template is true thenset YTDL_Custom_Settings to ""set YTDL_Custom_Settings to (DL_Custom_Settings & " ")if DL_Use_Custom_Settings is true thenset YTDL_Use_Cookies to ""set YTDL_Use_Cookies to ("--cookies " & DL_Cookies_Location & " ")if DL_Use_Cookies is true thenset YTDL_Use_Proxy to ""set YTDL_Use_Proxy to ("--proxy " & DL_Proxy_URL & " ")if DL_Use_Proxy is true thenset YTDL_metadata to ""set YTDL_metadata to "--add-metadata "if DL_Add_Metadata is true thenset YTDL_limit_rate_value to ""set YTDL_limit_rate_value to ("--limit-rate " & DL_Limit_Rate_Value & "m ")if DL_Limit_Rate is true thenget_YTDL_credentials()if credentials_choice is true thenset YTDL_credentials to ""set YTDL_TimeStamps to ""set YTDL_TimeStamps to resourcesPath & "ets"if DL_TimeStamps is true thenset YTDL_verbose to ""set YTDL_verbose to "--verbose "if DL_verbose is true thenset YTDL_Thumbnail_Write to ""set YTDL_Thumbnail_Write to "--write-thumbnail "if DL_Thumbnail_Write is true thenset YTDL_Thumbnail_Embed to ""set YTDL_Thumbnail_Embed to "--embed-thumbnail "if DL_Thumbnail_Embed is true thenset YTDL_format to ""set YTDL_format_pref to ""set YTDL_format_pref to "-f " & DL_format & " "set YTDL_format to "-f bestvideo[ext=" & DL_format & "]+bestaudio/best[ext=" & DL_format & "]/best "if DL_format is not theDefaultLabel thenset YTDL_Remux_original to ""set YTDL_Remux_original to "--keep-video "if DL_Remux_original is true thenset YTDL_remux_format to ""set YTDL_remux_format to "--recode-video " & remux_format_choice & " " & "--postprocessor-args \"-codec copy\" "set YTDL_remux_format to "--recode-video " & remux_format_choice & " " & "--postprocessor-args \"ffmpeg:-codec copy\" "if remux_format_choice is not theNoRemuxLabel thenset YTDL_STEmbed to ""set YTDL_STEmbed to "--embed-subs "if DL_STEmbed is true thenset YTDL_subtitles to ""set YTDL_over_writes to ""set YTDL_over_writes to "--force-overwrites "if DL_over_writes is true and DL_Use_YTDLP is "yt-dlp" thenset YTDL_audio_codec to ""set YTDL_audio_only to ""set YTDL_description to ""set YTDL_description to "--write-description "if description_choice is true thentell application "System Events" to open file MacYTDL_help_file_posixset MacYTDL_help_file_posix to POSIX path of MacYTDL_help_fileset MacYTDL_help_file to (path to resource "Help.pdf" in bundle path_to_MacYTDL_alias) as stringset path_to_MacYTDL_alias to path_to_MacYTDL as aliaselse if button_number_returned is 1 then -- Show Helputilities()else if button_number_returned is 2 then -- Show Utilitiesset_settings()if button_number_returned is 4 then -- Show Settingsset value of property list item "final_Position" to finalPositionif finalPosition is not equal to window_Position thenset value of property list item "Show_Settings_before_Download" to show_settings_choiceset DL_Show_Settings to show_settings_choiceif show_settings_choice is not equal to DL_Show_Settings thenset URL_user_entered to quoted form of URL_user_entered_clean -- Quoted form needed in case the URL contains ampersands etc - but really need to get quoted form of each URL when more than oneif text item -1 of URL_user_entered_clean is " " then set URL_user_entered_clean to text 1 thru -2 of URL_user_entered_cleanif URL_user_entered_clean is not "" and URL_user_entered_clean is not " " thenset URL_user_entered_clean to item 1 of controls_results -- Needed to refill the URL box on return from Settings, Help etc.set show_settings_choice to item 2 of controls_resultsset subtitles_choice to item 3 of controls_resultsset credentials_choice to item 4 of controls_resultsset description_choice to item 5 of controls_resultsset remux_format_choice to item 6 of controls_resultsset folder_chosen to item 8 of controls_resultsset DL_batch_status to item 9 of controls_resultsset openBatch_chosen to item 10 of controls_resultsif button_number_returned is 3 then -- Quitset {button_label_returned, button_number_returned, controls_results, finalPosition} to display enhanced window diag_Title acc view width (accViewWidth + add_extra_dialog_width) acc view height theTop acc view controls {theField, theCheckbox_Show_Settings, theCheckbox_SubTitles, theCheckbox_Credentials, theCheckbox_Description, main_thePopUp_FileFormat, main_formatlabel, thePathControl, theCheckbox_AddToBatch, theCheckbox_OpenBatch, pathLabel, diag_settings_prompt, theRule, MacYTDL_icon} buttons theButtons active field theField initial position window_Positionset {MacYTDL_icon, theTop} to create image view MacYTDL_custom_icon_file_posix left inset 0 bottom theTop - 60 view width 64 view height 64 scale image scale proportionallyset {diag_settings_prompt, theTop} to create label theDiagSettingsTextLabel left inset accViewInset bottom theTop + 8 max width accViewWidth control size regular size with bold typeset {theCheckbox_AddToBatch, theTop} to create checkbox theCheckbox_AddToBatchLabel left inset (accViewInset + 210) bottom (theTop + 5) max width 200 initial state DL_batch_statusset theCheckbox_AddToBatchLabel to localized string "Add URL to Batch" from table "MacYTDL"set add_extra_dialog_width to (theBatchLabelWidth - 158)if theBatchLabelWidth is greater than 158 thenset add_extra_dialog_width to 0set {theCheckbox_OpenBatch, theTop, theBatchLabelWidth} to create checkbox theCheckbox_OpenBatchLabel left inset (accViewInset + 210) bottom (theTop - 40) max width 200 without initial stateset theCheckbox_OpenBatchLabel to localized string "Open Batch functions" from table "MacYTDL"set {thePathControl, pathLabel, theTop} to create labeled path control (POSIX path of downloadsFolder_Path) left inset accViewInset bottom (theTop + 5) control width 190 label text thePathControlLabel with pops upset thePathControlLabel to localized string "Change download folder:" from table "MacYTDL"set {main_thePopUp_FileFormat, main_formatlabel, theTop, popupLeft} to create labeled popup {theNoRemuxLabel, "mp4", "mkv", "flv", "webm", "avi", "ogg"} left inset accViewInset - 5 bottom (theTop + 5) popup width 100 max width 200 label text theLabelledPopUpRemuxFileformat popup left accViewInset - 5 initial choice DL_Remux_formatset {main_thePopUp_FileFormat, main_formatlabel, theTop, popupLeft} to create labeled popup {theNoRemuxLabel, "mp4", "mkv", "flv", "webm", "mov", "avi", "ogg"} left inset accViewInset - 5 bottom (theTop + 5) popup width 100 max width 200 label text theLabelledPopUpRemuxFileformat popup left accViewInset - 5 initial choice DL_Remux_formatif DL_Use_YTDLP is "yt-dlp" thenset theLabelledPopUpRemuxFileformat to localized string "Remux file format:" from table "MacYTDL"set {theCheckbox_Description, theTop} to create checkbox theCheckbox_DescriptionLabel left inset accViewInset bottom (theTop + 5) max width 175 initial state DL_descriptionset theCheckbox_DescriptionLabel to localized string "Download description" from table "MacYTDL"set {theCheckbox_Credentials, theTop} to create checkbox theCheckbox_CredentialsLabel left inset accViewInset bottom (theTop + 5) max width 200 without initial stateset theCheckbox_CredentialsLabel to localized string "Credentials for download" from table "MacYTDL"set {theCheckbox_SubTitles, theTop} to create checkbox theCheckbox_SubTitlesLabel left inset accViewInset bottom (theTop + 15) max width 250 initial state DL_subtitlesset theCheckbox_SubTitlesLabel to localized string "Subtitles for this download" from table "MacYTDL"set {theCheckbox_Show_Settings, theTop} to create checkbox theCheckbox_Show_SettingsLabel left inset accViewInset + 50 bottom (theTop + 10) max width 250 initial state DL_Show_Settingsset theCheckbox_Show_SettingsLabel to localized string "Show settings before download" from table "MacYTDL"set {theRule, theTop} to create rule theTop + 18 rule width accViewWidthset {theField, theTop} to create field default_contents_text placeholder text theFieldLabel left inset accViewInset bottom 0 field width accViewWidth - accViewInset extra height 15set theFieldLabel to localized string "Paste URL here" from table "MacYTDL"set {theButtons, minWidth} to create buttons {theButtonsHelpLabel, theButtonsUtilitiesLabel, theButtonQuitLabel, theButtonsSettingsLabel, theButtonContinueLabel} button keys {"?", "u", "q", "s", ""} default button 5set theButtonsSettingsLabel to localized string "Settings" from table "MacYTDL"set theButtonsUtilitiesLabel to localized string "Utilities" from table "MacYTDL"set theButtonsHelpLabel to localized string "Help" from table "MacYTDL"set accViewInset to 80set accViewWidth to 450set theDiagSettingsTextLabel to localized string "One-time settings: Batches:" from table "MacYTDL"on error errNum -- Not called from Service, should always be error -2753 (variable not defined) - refill URL so it's shown in dialog - will be blank if user has not pasted a URLset called_video_URL to ""set default_contents_text to called_video_URLset default_contents_text to URL_user_entered_cleanif called_video_URL is "" thenset DL_batch_status to falseset DL_batch_status to trueif DL_batch_status is true thenif YTDL_version is "Not installed" thenset DL_audio_codec to localized string DL_audio_codec from table "MacYTDL"set DL_Remux_format to localized string DL_Remux_format from table "MacYTDL"set DL_subtitles_format to localized string DL_subtitles_format from table "MacYTDL"set DL_format to localized string DL_format from table "MacYTDL"run_Utilities_handlers's read_settings(MacYTDL_prefs_file)on main_dialog()main_dialog()set number_ABC_SBS_episodes to 0set SBS_show_name to ""set ABC_show_name to ""display dialog DL_Use_YTDLP & " " & alert_text_ytdl with title diag_Title buttons theButtonOKLabel default button 1 with icon file MacYTDL_custom_icon_file giving up after 600if alert_text_ytdl contains alert_text_ytdlLabel thenset alert_text_ytdlLabel to localized string "has been updated" from table "MacYTDL"display dialog alert_text_ytdlLabel with title diag_Title buttons theButtonOKLabel default button 1 with icon file MacYTDL_custom_icon_file giving up after 600set alert_text_ytdlLabel to localized string "Sorry, auto update cannot be used for Homebrew installs of YT-DLP." from table "MacYTDL"check_ytdl(DL_Use_YTDLP)if homebrew_ytdlp_exists is false thenelse if homebrew_ytdlp_exists is false thenset YTDL_version to do shell script youtubedl_file & " --version"if DL_Use_YTDLP is "youtube-dl" thenif DL_YTDL_auto_check is true thenset value of property list item "Use_ytdlp" to switched_show_yt_dlpset switched_show_yt_dlp to show_yt_dlpset switched_show_yt_dlp to "yt-dlp"set YTDL_version to do shell script ytdlp_file & " --version"if (ytdlp_exists is false and homebrew_ytdlp_exists is false) then check_ytdl(show_yt_dlp)if switch_or_quit is theButtonSwitchLabel thenset switch_or_quit to button returned of (display dialog warning_YTDL_not_working buttons {theButtonQuitLabel, theButtonSwitchLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theButtonSwitchLabel to localized string "Switch" from table "MacYTDL"set warning_YTDL_not_working to localized string "Sorry, \"youtube-dl\" does not work in macOS 12.3 and above. Would you like to switch to \"YT-DLP\" or Quit ?" from table "MacYTDL"if user_on_123 is true and DL_Use_YTDLP is "youtube-dl" thenrun_Utilities_handlers's update_MacYTDLservice(path_to_MacYTDL, MacYTDL_prefs_file, show_yt_dlp)run_Utilities_handlers's check_settings_current(MacYTDL_prefs_file, DL_Use_YTDLP, MacYTDL_preferences_path, youtubedl_file, ytdlp_file)set DL_Use_YTDLP to value of property list item "Use_ytdlp"set DL_YTDL_auto_check to value of property list item "Auto_Check_YTDL_Update"set YTDL_simulate_file to MacYTDL_preferences_path & "youtube-dl_simulate.txt"set Atomic_is_installed to trueif (exists file macYTDL_Atomic_file) thenset macYTDL_Atomic_file to ("usr:local:bin:AtomicParsley" as text)else if Install_FFprobe is theButtonNoLabel thenif Install_FFprobe is theButtonYesLabel thenset Install_FFprobe to button returned of (display dialog theInstallFFprobeTextLabel buttons {theButtonQuitLabel, theButtonYesLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theInstallFFprobeTextLabel to localized string "FFprobe is not installed. Would you like to install it now ? If not, MacYTDL can't run and will have to quit. Note: This download can take a while and you will probably need to provide administrator credentials." from table "MacYTDL"if ffprobe_exists is false and homebrew_ffprobe_exists is false thenelse if Install_FFmpeg is theButtonNoLabel thenif Install_FFmpeg is theButtonYesLabel thenset Install_FFmpeg to button returned of (display dialog theInstallFFmpegTextLabel buttons {theButtonQuitLabel, theButtonYesLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theInstallFFmpegTextLabel to localized string "FFmpeg is not installed. Would you like to install it now ? If not, MacYTDL can't run and will have to quit. Note: This download can take a while and you will probably need to provide administrator credentials." from table "MacYTDL"if ffmpeg_exists is false and homebrew_ffmpeg_exists is false thenrun_Utilities_handlers's check_DTP(DTP_file, path_to_MacYTDL)else if install_DTP is theButtonNoLabel thenif install_DTP is theButtonYesLabel thenset install_DTP to button returned of (display dialog theInstallDTPTextLabel buttons {theButtonNoLabel, theButtonYesLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theInstallDTPTextLabel to localized string "MacYTDL needs a code library installed in your Libraries folder. It cannot function without that library. Do you wish to continue ?" from table "MacYTDL"if DTP_exists is false thenset value of property list item "Use_ytdlp" to "yt-dlp"if (ytdlp_exists is true or homebrew_ytdlp_exists is true) and setting_yt_dlp is "youtube-dl" thenset value of property list item "Use_ytdlp" to "youtube-dl"set yt_install_answ to button returned of (display dialog theYTDLYTDLPIsInstalledtTextLabel & " ?" with title diag_Title buttons {theButtonNoLabel, theButtonYesLabel} default button 2 with icon file MacYTDL_custom_icon_file giving up after 600)set theYTDLYTDLPIsInstalledtTextLabel to localized string "You are currently set to download with YT-DLP but, it is not installed. This may have been set according to the version of macOS you are using or because there was a fault in downloading yt-dlp. You do have youtube-dl installed. Would you like to switch to YT-DLP" from table "MacYTDL"set switch_to to "yt-dlp"if ytdlp_exists is false and homebrew_ytdlp_exists is false and YTDL_exists is true and (setting_yt_dlp is "yt-dlp" or setting_yt_dlp is "yt-dlp-legacy") thenset value of property list item "YTDL_YTDLP_version" to YTDL_versionset value of property list item "Use_ytdlp" to ytdlp_install_show_yt_dlpset ytdlp_install_show_yt_dlp to show_yt_dlpset ytdlp_install_show_yt_dlp to "yt-dlp"if show_yt_dlp is "yt-dlp-legacy" thenif yt_install_answ is theButtonYesLabel thenset yt_install_answ to button returned of (display dialog theYTDLNotInstalledtTextLabel1 & return & return & theYTDLNotInstalledtTextLabel2 with title diag_Title buttons {theButtonQuitLabel, theButtonYesLabel} default button 2 cancel button 1 with icon file MacYTDL_custom_icon_file giving up after 600)set theYTDLNotInstalledtTextLabel2 to localized string "Note: This download can take a while and you will probably need to provide administrator credentials." from table "MacYTDL"set theYTDLNotInstalledtTextLabel1 to localized string "No downloader is installed. MacYTDL cannot download videos. By default it uses the YT-DLP downloader. Would you like to install YT-DLP now ?" from table "MacYTDL"if YTDL_exists is false and ytdlp_exists is false and homebrew_ytdlp_exists is false thenset setting_yt_dlp to value of property list item "Use_ytdlp"tell property list file MacYTDL_prefs_filerun_Utilities_handlers's check_settings(MacYTDL_prefs_file, old_version_prefs, diag_Title, theButtonNoLabel, theButtonYesLabel, MacYTDL_version, MacYTDL_date, MacYTDL_preferences_path, path_to_MacYTDL, X_position, Y_position, theBestLabel, theDefaultLabel, theNoRemuxLabel, resourcesPath, show_yt_dlp, YTDL_version)else if Install_Prefs is theButtonNoLabel thenif Install_Prefs is theButtonYesLabel thenset Install_Prefs to button returned of (display dialog theInstallPrefsTextLabel buttons {theButtonNoLabel, theButtonYesLabel} default button 2 cancel button 1 with title diag_Title with icon file MacYTDL_custom_icon_file giving up after 600)set theInstallPrefsTextLabel to localized string "The MacYTDL Preferences file is not present. To work, MacYTDL needs to create a file in your Preferences folder. Do you wish to continue ?" from table "MacYTDL"if prefs_exists is false thenquit_MacYTDL()run_Utilities_handlers's ask_user_install_service(path_to_MacYTDL, theButtonYesLabel, diag_Title, MacYTDL_custom_icon_file)set ffmpeg_version_long to do shell script ffmpeg_file & " -version"run_Utilities_handlers's install_ffmpeg_ffprobe(theButtonOKLabel, diag_Title, path_to_MacYTDL, usr_bin_folder, resourcesPath, MacYTDL_custom_icon_file, user_on_old_os, user_system_arch)run_Utilities_handlers's install_DTP(DTP_file, path_to_MacYTDL, resourcesPath)run_Utilities_handlers's set_preferences(old_version_prefs, diag_Title, theButtonNoLabel, theButtonYesLabel, MacYTDL_prefs_file, MacYTDL_version, MacYTDL_date, MacYTDL_preferences_path, path_to_MacYTDL, X_position, Y_position, theBestLabel, theDefaultLabel, theNoRemuxLabel, resourcesPath, show_yt_dlp, YTDL_version, MacYTDL_custom_icon_file)if word 2 of YTDL_ytdlp_version is "ytdl" thenset YTDL_version to word 1 of YTDL_ytdlp_versionset YTDL_ytdlp_version to run_Utilities_handlers's check_ytdl_installed(usr_bin_folder, diag_Title, youtubedl_file, ytdlp_file, theButtonQuitLabel, theButtonYesLabel, path_to_MacYTDL, theButtonOKLabel, resourcesPath, show_yt_dlp, MacYTDL_custom_icon_file)if components_install_answ is theButtonYesLabel thenset components_install_answ to button returned of (display dialog theComponentsNotInstalledtTextLabel1 & return & return & theComponentsNotInstalledtTextLabel2 with title diag_Title buttons {theButtonQuitLabel, theButtonYesLabel} default button 2 cancel button 1 with icon file MacYTDL_custom_icon_file giving up after 600)set theComponentsNotInstalledtTextLabel2 to localized string "Note: Some components will be downloaded which might take a while and you will need to provide administrator credentials." from table "MacYTDL"set theComponentsNotInstalledtTextLabel1 to localized string "It looks like you have not used MacYTDL before. A number of components must be installed for MacYTDL to run. There is more detail in the Help file. Would you like to install those components now ? Otherwise, Quit." from table "MacYTDL"if YTDL_exists is false and ytdlp_exists is false and DTP_exists is false and ffmpeg_exists is false and ffprobe_exists is false and prefs_exists is false and homebrew_ytdlp_exists is false and homebrew_ffmpeg_exists is false and homebrew_ffprobe_exists is false thenset ffprobe_version to text item 3 of ffprobe_version_longset ffprobe_version_long to do shell script shellPath & " ffprobe -version"if ffprobe_exists is true or homebrew_ffprobe_exists is true thenset ffmpeg_version to text item 3 of ffmpeg_version_longset AppleScript's text item delimiters to {"-", " "}set ffmpeg_version_long to do shell script shellPath & " ffmpeg -version"if ffmpeg_exists is true or homebrew_ffmpeg_exists is true thenset prefs_exists to falseset prefs_exists to trueif exists file MacYTDL_prefs_file thenset ffprobe_file to ("/opt/local/bin/ffprobe" as text)else if exists file macPorts_ffprobe_file thenset ffprobe_file to ("/opt/homebrew/bin/ffprobe" as text)else if exists file homebrew_ARM_ffprobe_file thenset ffprobe_exists to trueset homebrew_ffprobe_exists to falseset ffprobe_exists to falseset homebrew_ffprobe_exists to trueset its_type_ffmprobe to file type of disk item homebrew_Intel_ffprobe_fileif exists file ffprobe_file thenset ffmpeg_file to ("/opt/local/bin/ffmpeg" as text)else if exists file macPorts_ffmpeg_file thenset ffmpeg_file to ("/opt/homebrew/bin/ffmpeg" as text)else if exists file homebrew_ARM_ffmpeg_file thenset ffmpeg_exists to trueset homebrew_ffmpeg_exists to falseset ffmpeg_exists to falseset homebrew_ffmpeg_exists to trueif its_type_ffmpeg is "slnk" thenset its_type_ffmpeg to file type of disk item homebrew_Intel_ffmpeg_fileif exists file ffmpeg_file thenset DTP_exists to falseset DTP_exists to trueif exists file DTP_file thenset ytdlp_file to ("/opt/local/bin/yt-dlp" as text)else if exists file macPorts_ytdlp_file thenelse if exists file homebrew_ARM_ytdlp_file thenif size of ytdlp_path_alias is less than 9000 and its_type is not "slnk" thenset ytdlp_exists to trueset homebrew_ytdlp_exists to falseif size of ytdlp_path_alias is greater than 9000 thenset ytdlp_exists to falseset homebrew_ytdlp_exists to trueif its_type is "slnk" thenset its_type to file type of disk item homebrew_Intel_ytdlp_fileset ytdlp_path_alias to POSIX file ytdlp_file as aliasif exists file ytdlp_file thenset YTDL_exists to falseset YTDL_exists to trueif exists file youtubedl_file thenset run_Utilities_handlers to load script path_to_Utilitiesset path_to_Utilities to (path_to_MacYTDL & "Contents:Resources:Scripts:Utilities.scpt") as aliasset theNoRemuxLabel to localized string "No remux" from table "MacYTDL"set theDefaultLabel to localized string "Default" from table "MacYTDL"set theBestLabel to localized string "Best" from table "MacYTDL"set theButtonYesLabel to localized string "Yes" from table "MacYTDL"set theButtonNoLabel to localized string "No" from table "MacYTDL"set theButtonCancelLabel to localized string "Cancel" from table "MacYTDL"set theButtonContinueLabel to localized string "Continue" from table "MacYTDL"set theButtonReturnLabel to localized string "Return" from table "MacYTDL"set theButtonDownloadLabel to localized string "Download" from table "MacYTDL"set theButtonQuitLabel to localized string "Quit" from table "MacYTDL"set theButtonOKLabel to localized string "OK" from table "MacYTDL"set screen_height to item 4 of screen_size as integerset screen_width to item 3 of screen_size as integerset Y_position to item 2 of screen_size as integerset X_position to item 1 of screen_size as integerset screen_size to get_screensize()set batch_file to POSIX file (MacYTDL_preferences_path & batch_filename)set batch_filename to "BatchFile.txt" as stringset macPorts_ffprobe_file to ("/opt/local/bin/ffprobe" as text)set macPorts_ffmpeg_file to ("/opt/local/bin/ffmpeg" as text)set homebrew_Intel_ffprobe_file to ("usr:local:bin:ffprobe" as text)set homebrew_ARM_ffprobe_file to ("/opt/homebrew/bin/ffprobe" as text)set homebrew_Intel_ffmpeg_file to ("usr:local:bin:ffmpeg" as text)set homebrew_ARM_ffmpeg_file to ("/opt/homebrew/bin/ffmpeg" as text)set ffprobe_file to ("/usr/local/bin/ffprobe" as text)set ffmpeg_file to ("/usr/local/bin/ffmpeg" as text)set MacYTDL_prefs_file to MacYTDL_preferences_path & "MacYTDL.plist"set MacYTDL_preferences_path to (POSIX path of (path to home folder) & MacYTDL_preferences_folder)set MacYTDL_preferences_folder to "Library/Preferences/MacYTDL/"set DTP_file to libraries_folder & ":DialogToolkitMacYTDL.scptd"set libraries_folder to home_folder & "Library:Script Libraries"set home_folder to (path to home folder) as textset youtubedl_file to ("/usr/local/bin/youtube-dl" as text)set macPorts_ytdlp_file to ("/opt/local/bin/yt-dlp" as text)set homebrew_Intel_ytdlp_file to ("usr:local:bin:yt-dlp" as text)set homebrew_ARM_ytdlp_file to ("/opt/homebrew/bin/yt-dlp" as text)set ytdlp_file to ("/usr/local/bin/yt-dlp" as text)set usr_bin_folder to ("/usr/local/bin/" as text)set old_version_prefs to "No"set Atomic_is_installed to falseset ffmpeg_version to "Not installed"set ffprobe_version to "Not installed"set YTDL_version to "Not installed"set diag_Title to "MacYTDL, " & theVersionLabel & " " & MacYTDL_version & ", " & MacYTDL_dateset theVersionLabel to localized string "Version" from table "MacYTDL"set MacYTDL_custom_icon_file_posix to POSIX path of MacYTDL_custom_icon_fileset MacYTDL_custom_icon_file to (path to resource "macytdl.icns") as stringset shellPath to "PATH=$PATH:/bin:/sbin:/usr/bin:/usr/local/bin:/usr/sbin:~/opt/bin:~/opt/sbin:/opt/local/bin:/opt/local/sbin:/opt/homebrew/bin:" & quoted form of (POSIX path of (path_to_MacYTDL & "::")) & "; "if user_system_arch is not "arm64" then set user_system_arch to "Intel"set user_system_arch to (do shell script "arch")set user_on_old_os to falseset user_on_old_os to trueif user_os_version is less than "10.12.1" thenset user_on_123 to falseset user_on_123 to trueif user_os_version is greater than "12.2.1" thenset show_yt_dlp to "yt-dlp"set show_yt_dlp to "yt-dlp-legacy"if user_os_version is greater than "10.9.5" and user_os_version is less than "10.15" thenset user_os_version to system version of user_sysinfo as stringset user_sysinfo to system infoset alert_text_ytdl to "NotSwitching"set resourcesPath to POSIX path of (path_to_MacYTDL & "Contents:Resources:")set MacYTDL_date to MacYTDL_date_day & " " & thedateLabel & " " & MacYTDL_date_yearset thedateLabel to localized string MacYTDL_date_month from table "MacYTDL"set MacYTDL_date_year to word 3 of MacYTDL_dateset MacYTDL_date_month to word 2 of MacYTDL_dateset MacYTDL_date_day to word 1 of MacYTDL_dateset MacYTDL_date to text MacYTDL_date_position thru end of MacYTDL_copyrightset MacYTDL_date_position to (offset of "," in MacYTDL_copyright) + 2set MacYTDL_version to value of property list item "CFBundleShortVersionString" of contents of property list file bundle_fileset MacYTDL_copyright to value of property list item "NSHumanReadableCopyright" of contents of property list file bundle_fileset bundle_file to (path_to_MacYTDL & "contents:Info.plist") as stringset path_to_MacYTDL to path to me as textend called_by_serviceset called_video_URL to video_URLtell me to activateon called_by_service(video_URL)set URL_user_entered_clean to ""global URL_user_entered_cleanglobal run_Utilities_handlersglobal Y_positionglobal X_positionglobal window_Positionglobal theDefaultLabelglobal theNoRemuxLabelglobal theBestLabelglobal theButtonYesLabelglobal theButtonNoLabelglobal theButtonCancelLabelglobal theButtonReturnLabelglobal theButtonQuitLabelglobal theButtonOKLabelglobal theButtonDownloadLabelglobal theButtonContinueLabelglobal screen_heightglobal screen_widthglobal monitor_dialog_positionglobal called_video_URLglobal DTP_fileglobal ffmpeg_fileglobal ffprobe_fileglobal MacYTDL_dateglobal MacYTDL_copyrightglobal MacYTDL_versionglobal DL_formats_listglobal DL_QT_Compatglobal DL_Settings_In_Useglobal DL_Saved_Settings_Locationglobal DL_autoglobal DL_Custom_Settingsglobal DL_Use_Custom_Settingsglobal DL_TimeStampsglobal DL_Use_YTDLPglobal DL_Custom_Templateglobal DL_Use_Custom_Templateglobal DL_Proxy_URLglobal DL_Use_Proxyglobal DL_Cookies_Locationglobal DL_Use_Cookiesglobal DL_Show_Settingsglobal DL_Limit_Rate_Valueglobal DL_Limit_Rateglobal DL_batch_statusglobal DL_Add_Metadataglobal DL_Remux_originalglobal DL_Remux_formatglobal DL_STEmbedglobal DL_STLanguageglobal DL_formatglobal DL_descriptionglobal DL_verboseglobal DL_Thumbnail_Embedglobal DL_Thumbnail_Writeglobal DL_YTAutoSTglobal DL_subtitles_formatglobal DL_subtitlesglobal DL_over_writesglobal DL_YTDL_auto_checkglobal DL_audio_codecglobal DL_audio_onlyglobal YTDL_credentialsglobal resourcesPathglobal MacYTDL_preferences_pathglobal macYTDL_service_fileglobal MacYTDL_custom_icon_file_posixglobal MacYTDL_custom_icon_fileglobal MacYTDL_prefs_fileglobal batch_fileglobal old_version_prefsglobal YTDL_format_prefglobal YTDL_output_templateglobal number_ABC_SBS_episodesglobal playlist_Nameglobal SBS_show_nameglobal ABC_show_nameglobal SBS_show_URLsglobal ABC_show_URLsglobal URL_user_enteredglobal user_on_old_osglobal user_on_123global user_system_archglobal show_yt_dlpglobal homebrew_ffprobe_existsglobal homebrew_ffmpeg_existsglobal homebrew_ytdlp_existsglobal ffprobe_existsglobal ffmpeg_existsglobal ytdlp_existsglobal YTDL_existsglobal ytdlp_fileglobal youtubedl_fileglobal YTDL_simulate_fileglobal YTDL_log_fileglobal download_filename_newglobal download_filenameglobal macYTDL_Atomic_fileglobal Atomic_is_installedglobal downloadsFolder_Pathglobal shellPathglobal path_to_MacYTDLglobal alert_text_ffmpegglobal alert_text_ytdlglobal ffmpeg_versionglobal ffprobe_versionglobal ffmpeg_version_longglobal usr_bin_folderglobal YTDL_versionglobal diag_Titleglobal diag_promptuse script "DialogToolkitMacYTDL" -- Yosemite (10.10) or laterend roundThis(((n * x) + 0.5) div 1) / xset x to 10 ^ numDecimalson roundThis(n, numDecimals)end formatNumberreturn theResult as textset theResult to theFormatter's stringFromNumber:pNumbertheFormatter's setLocalizesFormat:falsetheFormatter's setFormat:pFormatStrset theFormatter to current application's NSNumberFormatter's new()on formatNumber(pNumber, pFormatStr)end convertBytesreturn fileSizeset fileSize to roundThis(fileSize, 3)set fileSize to my formatNumber(fileSize, "#,##0.000;0.000;(#,##0.000)") & " " & pUnitsStrif (pOutputType starts with "Str") thenset fileSize to pSizeBytes / convFactorset convFactor to 1024 ^ ((offset of pUnitsStr in converUnits) div 3 + 1)set converUnits to "KB MB GB TB"on convertBytes(pSizeBytes, pUnitsStr, pOutputType)set fileSize to my convertBytes(fileSizeBytes, "MB", "str")set fileSizeBytes to size of (get info for fileAlias)set fileAlias to item 1 of finderSelectionListtell application "Finder" to set finderSelectionList to selection as alias listuse framework "AppKit" -- this may not be requireduse framework "Foundation" -- this may not be requiredproperty ptyScriptAuthor : "JMichaelTX"property ptyScriptDate : "2017-12-23"property ptyScriptVer : "1.2" -- use byte conversion method by @NigelGarveyproperty ptyScriptName : "Convert Bytes to Specified Units"end convertBytesToStringreturn (theNSByteCountFormatter's stringFromByteCount:pSizeNum) as texttheNSByteCountFormatter's setAllowedUnits:nsUnitstheNSByteCountFormatter's setIncludesActualByteCount:pIncludeBytesBoolset nsUnits to a reference to 4 -- default to MBset nsUnits to a reference to 8else if (pNSUnitsStr = "GB") thenset nsUnits to a reference to 4else if (pNSUnitsStr = "MB") thenset nsUnits to a reference to 2if (pNSUnitsStr = "KB") thenon convertBytesToString(pSizeNum, pNSUnitsStr, pIncludeBytesBool)set fileSizeMBStr to my convertBytesToString(fileSizeNum, "MB", true)set fileSizeNum to size of oFileset oFile to info for filePathset filePath to POSIX path of (choose file)if (fileSizeNum is missing value) thenset fileSizeNum to missing valuetheNSByteCountFormatter's setAllowedUnits:NSByteCountFormatterUseKBset theNSByteCountFormatter to current application's NSByteCountFormatter's new()my formatAsBytes:123456789property NSByteCountFormatterUseKB : a reference to 2set theWeight to (mFormatter's stringFromKilograms:85) as textmFormatter's setUnitStyle:(current application's NSFormattingUnitStyleLong)set mFormatter to current application's NSMassFormatter's new()set end of thePhoneNumbers to {|phoneNumber|:thePhoneNumber}set wholeRange to (aMatch's rangeAtIndex:0) as record -- or aMatch's range() as recordset theMatches to theDetector's matchesInString:theNSStringSample options:0 range:{0, theNSStringSample's |length|()}set theDetector to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypePhoneNumber) |error|:(missing value)set item rangeIndex of parts to (theNSStringSample's substringWithRange:partRange) as textif partRange's |length| > 0 then ¬set thePhoneNumber to (theNSStringSample's substringWithRange:wholeRange) as textset theMatches to theRegEx's matchesInString:theNSStringSample options:0 range:{0, theNSStringSample's |length|()}set theNSStringSample to current application's NSString's stringWithString:theSample--> { -- {phoneNumber:"333-1234", parts:{"000", "333", "1234"}},thePhoneNumbersset end of thePhoneNumbers to {|phoneNumber|:thePhoneNumber, parts:parts}set item rangeIndex of parts to text ((partRange's location) + 1) thru ((partRange's location) + (partRange's |length|)) of theSampleif partRange's location is not NSNotFound then ¬set partRange to (aMatch's rangeAtIndex:rangeIndex) as recordrepeat with rangeIndex from 1 to numRanges - 1set parts to {"000", "000", "0000"}set numRanges to aMatch's numberOfRanges as integerset thePhoneNumber to text ((wholeRange's location) + 1) thru ((wholeRange's location) + (wholeRange's |length|)) of theSampleset wholeRange to (aMatch's rangeAtIndex:0) as recordset thePhoneNumbers to {}set theMatches to theRegEx's matchesInString:theSample options:0 range:[0, theSample's length]set theRegEx to NSRegularExpression's regularExpressionWithPattern:usPhoneNumberPattern options:NSRegularExpressionCaseInsensitive |error|:(missing value)set theSample to "333-1234, 250-888-8888, (123) 350-1234, (456)-350-1234"set usPhoneNumberPattern to "\\(?(\\d{3})?\\)?\\s*-?\\s*(\\d{3})\\s*-?\\s*(\\d{4})"property NSNotFound : a reference to 9.22337203685477E+18 + 5807 -- see http://latenightsw.com/high-sierra-applescriptobjc-bugs/property NSRegularExpressionCaseInsensitive : a reference to 1current application's NSPasteboard's generalPasteboard()'s pasteboardItems()'s firstObject()'s |types|() as list"inheritance path" buttons {"OK"} default button "OK" cancel button "OK" default answer (ClassPath of TheResult)"The arrow points to the class that is inheriting from its parent." with title ¬if (Successful of TheResult) thenset TheResult to GetInheritancePath(StartingClass as text)set StartingClass to text returned of result"The input is case sensitive." with title "Enter a class" buttons {"OK", "Cancel"} default button "OK" default answer """The class will be converted to an inheritance path" & return & ¬end GetInheritancePath& " occured getting the inheritance path." & return & return & errMsg with title "Error" buttons {"OK"} default button "OK"display dialog "Error " & (errNum as string) ¬set (Successful of ReturnObj) to trueset (ClassPath of ReturnObj) to ClassPathset CurrentClass to NextClassset ClassPath to ClassName & "-->" & ClassPathset ClassName to GetClassNameAsString(NextClass)set NextClass to CurrentClass's superclass()repeat until (GetClassNameAsString(CurrentClass) = "NSObject")set ClassPath to CurrentClassNamereturn ReturnObjset (Successful of ReturnObj) to false"\" does not appear to represent a valid class name." buttons {"OK"} default button "OK" with title "Error"display dialog "Invalid input. The entered text \"" & CurrentClassName & ¬display dialog "Invalid input. There were no letters found in the input, \"" & CurrentClassName & "\"" buttons {"OK"} default button "OK" with title "Error"else if (StringStatus = "NoLettersFound") thendisplay dialog "Invalid input. All the text in the input, \"" & CurrentClassName & ",\" was all lower case." buttons {"OK"} default button "OK" with title "Error"else if (StringStatus = "AllLowerCase") thendisplay dialog "Invalid input. All the text in the input, \"" & CurrentClassName & ",\" was all upper case." buttons {"OK"} default button "OK" with title "Error"if (StringStatus = "AllUpperCase") thenset StringStatus to GetStringState(CurrentClassName)display dialog "Invalid input. Only " & (length of CurrentClassName) & " character(s) was input" buttons {"OK"} default button "OK" with title "Error"else if ((length of CurrentClassName) < 4) thendisplay dialog "No characters were entered as input." buttons {"OK"} default button "OK" with title "Error"if (CurrentClassName = "") thenif (CurrentClass = missing value) thenset CurrentClass to current application's NSClassFromString(CurrentClassName)if (CurrentClassName = "NSObject") then return CurrentClassNamelocal TheClasslocal NextClasslocal ClassPathlocal CurrentClassproperty ClassPath : ""property Successful : falsescript ReturnObjon GetInheritancePath(CurrentClassName)end GetClassNameAsStringreturn (current application's NSStringFromClass(TheClass's |class|())) as texton GetClassNameAsString(TheClass)end GetStringStatereturn Stateif (not UpperCaseFound and LowercaseFound) then set State to "AllLowerCase"if (UpperCaseFound and not LowercaseFound) then set State to "AllUpperCase"if (not UpperCaseFound and not LowercaseFound) then set State to "NoLettersFound"if (UpperCaseFound and LowercaseFound) then set State to "MixedCase"set UpperCaseFound to ((id of "A") ≤ (id of TheCharacter)) and ((id of TheCharacter) ≤ (id of "Z"))if (not UpperCaseFound) thenset LowercaseFound to ((id of "a") ≤ (id of TheCharacter)) and ((id of TheCharacter) ≤ (id of "z"))if (not LowercaseFound) thenrepeat with TheCharacter in StringCharacterset StringCharacter to characters of TheStringset UpperCaseFound to falseset LowercaseFound to falseset TheString to TheString as texton GetStringState(TheString)use framework "Carbon"set the script_text to the script_text & "tell application \"Finder\"" & CRset the script_text to the script_text & "tell application \"System Events\"" & CRset the script_text to the script_text & "end tell" & CRset the script_text to the script_text & "tell application \"" & target_string & "\"" & CRset the replacement_string to "ApplicationName"set the script_text to the script_text & "end using terms from" & CRset the script_text to the script_text & tab & "-- insert actions here" & CRset the script_text to the script_text & "using terms from application \"" & target_string & "\"" & CRset the script_text to the script_text & "end considering" & target_string & CRset the script_text to the script_text & "end considering"set the script_text to the script_text & "considering" & space & the parameter_string & CRset the the chosen_parameters to (choose from list comparison_parameters with prompt "Pick the parameter(s) to use: (Command-key for multiple)" with multiple selections allowed)set the script_text to the script_text & "ignoring" & space & the parameter_string & CRset the parameter_string to the parameter_string & ", " & this_itemset the parameter_string to the parameter_string & " and " & this_itemelse if i is the parameter_count thenset the parameter_string to the parameter_string & this_itemset this_item to item i of chosen_parametersrepeat with i from 1 to the parameter_countset the parameter_string to ""set the parameter_string to the chosen_parameters as stringif the parameter_count is 1 thenset the parameter_count to the count of the chosen_parametersif the chosen_parameters is false then return "user cancelled"set the the chosen_parameters to (choose from list comparison_parameters with prompt "Pick the parameter(s) to ignore: (Command-key for multiple)" with multiple selections allowed)set the comparison_parameters to {"case", "diacriticals", "expansion", "hyphens", "punctuation", "white space"}set the script_text to the script_text & return & "repeat with i from 1 to number of items in " & the selected_text & returnset the replacement_string to "-- insert actions for: this_item"set the script_text to the script_text & tab & "else -- other list items" & returnset the script_text to the script_text & tab & "-- insert actions for: this_item" & returnset the script_text to the script_text & tab & "else if i is the item_count then -- last list item" & returnset the script_text to the script_text & tab & "if i is 1 -- first list item" & returnset the replacement_string to "-- insert actions for the first item"set the script_text to the script_text & tab & "if i is 1" & return2) A list of items, such as: {\"red\", \"blue\", \"yellow\"}" buttons {"Help", "OK"} default button 21) The name of a variable containing a list, such as: new_colors or newColorsset the replacement_string to "-- insert actions for the last item"set the script_text to the script_text & tab & "-- insert actions for the other items" & returnset the script_text to the script_text & tab & "else" & returnset the script_text to the script_text & tab & "if i is the item_count then" & returnset the script_text to the script_text & tab & "set this_item to item i of " & the selected_text & returnset the script_text to the script_text & "repeat with i from 1 to the item_count" & returnset the script_text to the script_text & return & "set the item_count to the number of items in " & the selected_text & returnset the replacement_string to "-- insert actions here for: this_file"set the script_text to the script_text & tab & "end if" & returnset the script_text to the script_text & tab & tab & target_string & returnset the script_text to the script_text & tab & "if visible of this_info is true and alias of this_info is false then" & returnset the script_text to the script_text & tab & "set this_info to info for this_file" & returnset the script_text to the script_text & tab & "set these_files to every file of folder this_folder" & returnset the script_text to the script_text & "set this_folder to (choose folder with prompt \"Pick the folder containing the files to process:\") as string" & returndisplay dialog error_message buttons {"OK"} default button 1set the script_text to the script_text & tab & "set this_file to (item i of these_files as alias)" & returnset the script_text to the script_text & "repeat with i from 1 to the count of these_files" & returnset the script_text to the script_text & tab & "set these_files to every file of folder this_folder whose name does not start with \".\" and (file type is \"TIFF\" or file type is \"JPEG\" or name extension is \"tiff\" or name extension is \"tif\" or name extension is \"jpeg\" or name extension is \"jpg\")" & returnset the script_text to the script_text & "tell application \"System Events\"" & returnset the script_text to the script_text & "set this_folder to (choose folder with prompt \"Pick the folder containing the images to process:\") as string" & returndisplay dialog error_message buttons {"OK"} default button 1 with icon 2set the replacement_string to "-- insert actions here for: this_item"set the script_text to the script_text & "end repeat"set the script_text to the script_text & tab & target_string & returnset the script_text to the script_text & tab & "set this_info to info for this_item" & returnset the script_text to the script_text & tab & "set this_item to (item i of these_items) as alias" & returnset the script_text to the script_text & "repeat with i from 1 to the count of these_items" & returnset the script_text to the script_text & "end tell" & returnset the script_text to the script_text & tab & "set these_items to the selection" & returnset the script_text to the script_text & "tell application \"Finder\"" & returnset the script_text to the script_text & tab & "scale this_image to size " & target_dimension & returnset the target_dimension to (this_value as string)if this_value is greater than or equal to 6 thendisplay dialog "Enter the desired dimension (in pixels) of the longest side of the image:" default answer ""set the script_text to the script_text & tab & "rotate this_image to angle 90" & returnset the script_text to the script_text & tab & "rotate this_image to angle -90" & return2) An alias reference to an image file, such as: alias \"Macintosh HD:Images:Picture.01.jpg\"" buttons {"Help", "OK"} default button 21) The name of a variable containing an alias reference to an image file, such as: this_image or thisImagedisplay dialog "Please select text in this script that is either:set the script_text to the script_text & "end tell--XXXX"set the script_text to the script_text & tab & "close this_image" & returnset the script_text to the script_text & tab & "save this_image in " & selected_text & returnset the script_text to the script_text & tab & "scale this_image by factor " & scale_factor & returnset the script_text to the script_text & tab & "set this_image to open " & selected_text & returnset the script_text to the script_text & "tell application \"Image Events\"" & returnset the script_text to "" & returnreturn "user cancelled"if the error_number is -128 thenset the scale_factor to (this_value * 0.01) as stringif this_value is greater than 0 thenset this_value to the text returned of the result as integerdisplay dialog "Enter the scale percentage:" default answer "100"set the script_text to the script_text & "end adding folder items to" & target_string & CRset the script_text to the script_text & "end adding folder items to" & CRset the script_text to the script_text & "on adding folder items to this_folder after receiving these_items" & CRset the script_text to the script_text & "end closing folder window for" & target_string & CRset the script_text to the script_text & "end closing folder window for" & CRset the script_text to the script_text & "on closing folder window for this_folder" & CRset the script_text to the script_text & "end moving folder window for" & target_string & CRset the script_text to the script_text & "end moving folder window for" & CRset the script_text to the script_text & "on moving folder window for this_folder from original_bounds" & CRset the script_text to the script_text & "end opening folder" & target_string & CRset the script_text to the script_text & "end opening folder" & CRset the script_text to the script_text & "on opening folder this_folder" & CRset the script_text to the script_text & "end removing folder items from" & target_string & CRset the script_text to the script_text & "end removing folder items from" & CRset the script_text to the script_text & "on removing folder items from this_folder after losing these_items" & CRset the script_text to the script_text & tab & "display dialog \"Error: \" & the error_number & \". \" & the error_message buttons {\"Cancel\"} default button 1" & CRset the script_text to the script_text & "end try" & the target_string & returnset the script_text to the script_text & "end try" & returnset the script_text to the script_text & tab & "display dialog \"Error: \" & the error_number & \". \" & the error_message buttons {\"OK\"} default button 1" & returnset the script_text to the script_text & "on error the error_message number the error_number" & returnset the script_text to the script_text & tab & the target_string & returnset the script_text to the script_text & "try" & returnset the script_text to the script_text & tab & "return the error_text" & CRset the script_text to the script_text & tab & "display dialog the error_text buttons {\"OK\"} default button 1" & CRset the script_text to the script_text & tab & "end if" & CRset the script_text to the script_text & tab & tab & "error number -128" & CRset the script_text to the script_text & tab & "else" & CRset the script_text to the script_text & tab & tab & "display dialog the error_text buttons {\"Cancel\"} default button 1" & CRset the script_text to the script_text & tab & tab & "set the error_text to \"Error: \" & the error_number & \". \" & the error_message" & CRset the script_text to the script_text & tab & "if the error_number is not -128 then" & CRset the script_text to the script_text & tab & "-- don't display error message if the user canceled a dialog within the [try] and [on error] lines above" & CRcheck syntax of the front documentset contents of selection to CR & the sub_routine & CRset selection to insertion point -1 of front documentif the contents of the front document does not contain "on write_error_log" thenend write_error_log"close access file the error_logwrite (this_error & return) to file the error_log starting at eofopen for access file the error_log with write permissionset the error_log to ((path to desktop) as text) & \"Script Error Log.txt\"set the sub_routine to "on write_error_log(this_error)set the script_text to the script_text & "end try" & the target_string & CRset the script_text to the script_text & "end try" & CRset the script_text to the script_text & tab & "my write_error_log(the error_text)" & CRset the script_text to the script_text & tab & "-- if the file \"Script Error Log.txt\" already exists, it will add one line to the log" & CRset the script_text to the script_text & tab & "-- the following line evokes the sub-routine to write the error into an error log created on the desktop" & CRset the script_text to the script_text & tab & "set the error_text to \"Error: \" & the error_number & \". \" & the error_message" & CRset the script_text to the script_text & "on error the error_message number the error_number" & CRset the script_text to the script_text & tab & the target_string & CRset the script_text to the script_text & "try" & CRset the script_text to "display dialog \"" & target_string & "\" buttons {\"Cancel\"} default button 1" & returnset the script_text to "display dialog \"" & target_string & "\" buttons {\"OK\"} default button 1" & returnset the script_text to "display dialog \"" & target_string & "\" buttons {\"\"} default button 1" & returnset the script_text to "display dialog \"" & target_string & "\" buttons {\"\", \"\"} default button 2" & returnset the script_text to the script_text & "display dialog \"" & target_string & "\" buttons {\"\", \"\"} default button 2" & returnset the script_text to "display dialog \"" & target_string & "\" buttons {\"\", \"\", \"\"} default button 3" & returnset the script_text to the script_text & "if the button returned of the result is \"\" then" & returnset the script_text to the script_text & "display dialog \"" & target_string & "\" buttons {\"Cancel\", \"\", \"\"} default button 3" & returnset the script_text to the script_text & "end if" & returnset the script_text to the script_text & tab & "-- action for 3rd button goes here" & returnset the script_text to the script_text & "else" & returnset the script_text to the script_text & tab & "-- action for 2nd button goes here" & returnset the script_text to the script_text & "else if the button_pressed is \"\" then" & returnset the script_text to the script_text & tab & "-- action for 1st button goes here" & returnset the script_text to the script_text & "if the button_pressed is \"\" then" & returnset the script_text to the script_text & "set the button_pressed to the button returned of the result" & returnset the script_text to the script_text & "display dialog \"" & target_string & "\" buttons {\"\", \"\", \"\"} default button 3" & returnset the script_text to "display dialog \"" & target_string & "\" default answer \"\" buttons {\"OK\"} default button 1" & returnset the script_text to the script_text & "display dialog \"" & target_string & "\" default answer \"\" buttons {\"\",\"\"} default button 1" & returnelse if the user_choice is "Stop" thenif the user_choice is "Help" thendisplay dialog "This script will delete the selected text." & return & return & "Do you want to continue?" buttons {"Help", "Continue", "Stop"} default button 3 with icon 2my replace_and_select(target_string, "")set the contents of selection to the script_textif my display_message() is false then return "user cancelled"set the script_text to the script_text & "copy the result as list to {text_returned, button_pressed}" & returnset the script_text to the script_text & "display dialog \"" & target_string & "\" default answer \"\" buttons {\"\",\"\",\"\"} default button 1" & returnset the target_string to "X-X-X"end eolset selection to insertion point (i)return (i - 1)set selection to insertion point iif this_char is carriage_return thenset this_char to character irepeat with i from y to 10000000set carriage_return to ASCII character 10copy the (character range of selection) to {x, y}on eol()end script_help«event helpsanc» this_anchor given «class sstr»:"Script Editor Help"tell application "EPSON ET-4750 Series"on script_help(this_anchor)end display_messagemy script_help("ScriptEditor001")if the button returned of the result is "Help" then{\"car\", \"book\", \"house\", \"tree\"}" buttons {"Help", "OK"} default button 2 with icon 2display dialog "This script creates a conditional statement for each item of a selected list. Please select text in this script that is a list of items, such as:on display_message()set the replacement_string to "-- item 1 action goes here"check syntax of front documentset the contents of the selection of the front document to return & return & script_textmy eol()set the script_text to the script_text & "else if " & condition_variable & space & chosen_operator & space & (item i of the list_items) & " then" & return & tab & "-- item " & (i as string) & " action goes here" & returnset the script_text to the script_text & "else if " & condition_variable & space & chosen_operator & space & (item i of the list_items) & " then" & return & tab & "-- item " & (i as string) & " action goes here" & return & "end if"else if i is the condition_count thenset the script_text to "if " & condition_variable & space & chosen_operator & space & (item i of the list_items) & " then " & return & tab & target_string & returnelse if i is 1 thenset the script_text to "if " & condition_variable & space & chosen_operator & space & (item i of the list_items) & " then " & return & tab & target_string & return & "end if"if the condition_count is 1 thenrepeat with i from 1 to the condition_countif the chosen_operator is "false" then return "user cancelled"set the chosen_operator to (choose from list operator_list with prompt "Choose the comparison to use:") as stringif the condition_variable is not "" then exit repeatset the condition_variable to the text returned of the resultdisplay dialog "Enter the name of the comparison variable:" & return & return & "ex: if this_item is \"Shoe\" then" & return & space default answer "this_item"return "script cancelled"my display_message()else -- errorset the condition_count to the count of the list_itemsset the list_items to every text item of the prep_dataset the prep_data to (characters 2 thru -2 of the selected_text) as stringif the selected_text begins with "{" and the selected_text ends with "}" thenset the selected_text to contents of selection of front documentset the operator_list to {"is", "is not", "begins with", "does not begin with", "ends with", "does not end with", "contains", "does not contain", "is in", "is not in", "is equal to", "is not equal to", "is greater than", "is greater than or equal to", "is not greater than or equal to", "is less than", "is less than or equal to", "is not less than or equal to", "comes after", "comes before"}set the script_text to the script_text & "end if" & CR --& target_stringset the script_text to the script_text & target_string & CR & ¬"else" & CR"-- insert if actions here" & CR & ¬set the script_text to the script_text & "If true then" & CR & ¬set the replacement_string to "-- insert else actions here"& "end if" & CR --& target_string& target_string & CR ¬set the script_text to the script_text & "else" & CR ¬set the replacement_string to "-- insert if actions here""end if" & CR"-- insert else actions here" & CR & ¬set the script_text to the script_text & "else" & CR & ¬set selection to {}set the replacement_string to "true"set the script_text to the script_text & "If " & target_string & " then" & CRset the script_text to the script_text & "end if" & CRset the script_text to the script_text & tab & target_string & CRset the script_text to the script_text & "If true then" & CRset the script_text to the script_text & "end ignoring" & target_string & CRset the script_text to the script_text & "end ignoring"set the script_text to the script_text & "ignoring application responses" & CRset the script_text to the script_text & "end timeout" & target_string & CRset the script_text to the script_text & "end timeout"set the script_text to the script_text & "with timeout of " & (time_amount as string) & " seconds" & CRif the error_number is -128 then return "user cancelled"on error number error_numberif the time_amount is greater than 0 then exit repeatset the time_amount to the text returned of the result as integerdisplay dialog "Enter the number of seconds before a timeout occurs:" default answer "180"end replace_and_selectset the contents of the selection to the replacement_stringset selection to characters this_offset thru (this_offset + (length of the target_string) - 1)if this_offset is not 0 thenset this_offset to the offset of the target_string in this_textset this_text to the contentson replace_and_select(target_string, replacement_string)my replace_and_select(target_string, replacement_string)check syntaxset contents of selection to script_textset the replacement_string to ""set the script_text to the script_text & "end transaction" & target_string & CRset the script_text to the script_text & tab & the selected_textif last character of selected_text is in {CR, NL} thenset the replacement_string to "-- insert actions here"set the script_text to the script_text & "end transaction"set the script_text to the script_text & tab & the selected_text & CRset the script_text to the script_text & "with transaction" & CRset the script_text to ""set the selected_text to the target_stringif the selected_text is "" thenset the contents of the selection of the front document to this_textdisplay dialog "Select some text before invoking this script command." with icon stop buttons "OK" default button 1set contents of selection to return & ¬if the last character of selected_text is in {CR, NL} thenif true thencharacters (BlockStartOffset + 2) through (BlockEndOffset - 1) of selected_text as text) & ¬set Newtext to ((characters 1 through (BlockStartOffset - 1) of selected_text as text) & ¬characters (BlockStartOffset + 2) through -3 of selected_text as textset Newtext to (characters 1 through (BlockStartOffset - 1) of selected_text as text) & ¬if BlockEnd thenset contents of selection to Newtextcharacters (BlockEndOffset + 2) through -1 of selected_text as textset Newtext to (characters 3 through (BlockEndOffset - 1) of selected_text as text) & ¬if BlockStart thenif BlockStartOffset is less than BlockEndOffset thenlog {BlockStartOffset, BlockEndOffset, SelectionLength}(offset of ")*" in (reverse of (characters of selected_text) as text))set BlockEndOffset to SelectionLength - ¬set SelectionLength to length of selected_textset contents of selection to characters 3 through -3 of selected_text as textset contents of selection to characters 4 through -4 of selected_text as textif BlockStart and BlockEnd thenif the selected_text is not "" thenset the selected_text to contents of selectionset the target_string to "--XXXX"set NL to ASCII character 10set CR to ASCII character 13"Otherwise, the inserted routine will be placed at the current cursor location.""If there is text selected in the front document, the inserted routine will be wrapped around the selected text. " & ¬"of the Script Editor application." & ¬property message_A : "These scripts will insert standard AppleScript routines into the front document " & ¬property carriage_return : return as textsay currentTimeoutput currentTimeset currentTime to ((currentDate's month) as text) & " " & ((currentDate's day) as text) & ", " & (currentHour as text) & ":" & ((currentMinutes) as text) & " " & amPM as textset currentHour to (currentHour - 12)if (currentHour > 12) thenset currentHour to 12if currentHour is equal to 0 thenset currentMinutes to ("0" & currentMinutes) as textif currentMinutes < 10 thenset amPM to "PM"if (currentHour ≥ 12 and currentHour < 24) thenset currentMinutes to currentDate's minutesset currentHour to (currentDate's hours)set amPM to "AM"set currentDate to current datesay unreadStringoutput unreadStringset unreadString to unreadCount & " unread messages" as stringset unreadString to unreadCount & " unread message" as stringif unreadCount is equal to 1 thenset unreadCount to unreadMailCount()set unreadString to ""end unreadMailCountreturn unreadCountset unreadCount to (unread count of inbox) + unreadCountset unreadCount to 0 as numberon unreadMailCount()make new attachment with properties {file name:screenshotPath} at after last paragraphtell contenttell newMessageset newMessage to make new outgoing message with properties {visible:true, subject:"VoiceOver Cursor Screenshot", content:"VoiceOver Cursor screenshot:" & return & return}display dialog "VoiceOver must be running with AppleScript support enabled"set screenshotPath to grab screenshottell vo cursorif isVoiceOverRunningWithAppleScript() thenset screenshotPath to ""end isVoiceOverRunningWithAppleScriptreturn isRunningWithAppleScriptset isRunningWithAppleScript to falseset x to bounds of vo cursortell application "VoiceOver"set isRunningWithAppleScript to trueif isVoiceOverRunning() thenon isVoiceOverRunningWithAppleScript()end isVoiceOverRunningreturn isRunningset isRunning to (name of processes) contains "VoiceOver"set isRunning to falseon isVoiceOverRunning()global screenshotPathdisplay dialog "Full name: " & theResultactivate meset theResult to value of text field "Full name:"click radio button "Password"tell tab group 1 of window "Users & Groups" of process "System Preferences"set current pane to pane "com.apple.preferences.users"keystroke "p" using {shift down, option down}key up {shift, option}key down {shift, option}key up shiftkey down shiftkeystroke "e" using option downkey up optionkeystroke "e"key down optiontell process "TextEdit"of every menu for every application currently running, to see results run it within AppleScript Editor."display dialog "The 'Probe Menu Bar' script was executed, it uses UI element scripting to return a list of every menuitemget every menu item of every menu of every menu item of every menu of every menu bar itemget every menu of every menu item of every menu of every menu bar itemget every menu item of every menu of every menu bar itemget every menu of every menu bar itemget every menu bar itemtell menu bar 1get every menu barget every processdisplay dialog "The 'Probe Window' script was executed, it uses UI element scripting to get information about the top window in the Finder, to see results run it within AppleScript Editor."get properties of every UI element whose class is not button and class is not static text and class is not scroll barget every UI element whose class is not button and class is not static text and class is not scroll barget every UI element of every scroll barget properties of every scroll barget every scroll barget every UI element of every static textget properties of every static textget every static textget every UI element of every buttonget properties of every buttonget every buttonget every UI elementdisplay dialog "Error: " & errMsgset value to 0.5set value to 0.8if value is 0.5 thentell slider 1 of window "Sound" of process "System Preferences"set current pane to pane "com.apple.preference.sound""To convert files in batch mode, open the appropriate script (/Library/Scripts/Printing Scripts) in ScriptEditor and save the script as an application. Then drag the files to be converted on to the new application." & ¬set message_A to "The Convert… scripts convert a file to PDF or PostSctript." & ¬display dialog message_A buttons {"OK"} default button 1 with icon note"A script can also be opened in Script Editor by holding down the Option Key while selecting that script in the Scripts menu.""To use these scripts as droplets, open the appropriate script (/Library/Scripts/Printing Scripts) in ScriptEditor and save the script as an application. Then drag the folder(s) on to the new application." & ¬carriage_return & carriage_return & ¬set message_A to "The Print… scripts print (in text) the contents of a folder." & ¬set carriage_return to return as textset terminalCommand to convertCommand & "-f " & "\"" & thePOSIXFileName & "\"" & " -o " & "\"" & newFileName & "\"" & " -j \"application/pdf\""set newFileName to thePOSIXFileName & ".pdf"set these_items to (choose file with prompt "Select a file to convert to PDF:" of type {"JPEG", "GIFf", "PICT", "TIFF", "TEXT", "RTF"}) as listend processFiledo shell script terminalCommandset terminalCommand to convertCommand & "-f " & "\"" & thePOSIXFileName & "\"" & " -o " & "\"" & newFileName & "\"" & " -j \"application/postscript\""set newFileName to thePOSIXFileName & ".ps"set convertCommand to "/System/Library/Printers/Libraries/./convert "set terminalCommand to ""on processFile(thePOSIXFileName)set theFilePath to (this_item as string)the name extension of the item_info is in the extension_list) then((the file type of the item_info is in the type_list) or ¬else if (alias of the item_info is false) and ¬if folder of the item_info is true thenset this_item to alias ((theFolder as text) & (item i of these_items))set these_items to list folder theFolder without invisiblesprocessFile(thePOSIXFilePath)set thePOSIXFilePath to POSIX path of theFilePath as stringset theFilePath to (item i of these_items as string)((the name extension of the item_info) is in the extension_list) then(the file type of the item_info is in the type_list) or ¬(alias of the item_info is false)) and ¬else if ((folder of the item_info is false) and ¬processFolder(this_item)set thesefiles to {}set these_items to (choose file with prompt "Select a file to convert to PostScript:" of type {"JPEG", "GIFf", "PICT", "TIFF", "TEXT", "RTF"}) as listproperty extension_list : {"jpg", "gif", "pct", "tif", "pdf", "rtf"}property type_list : {"JPEG", "GIFf", "PICT", "TIFF", "PDF", "TEXT"}set theShellScript to ("( echo " & printedPath & " && ls -R \"" & printedPath & "\" ) | lpr " as string)end processFolderError: " & ErrNmbr buttons {"OK"} with icon notedisplay dialog ErrMsg & "on error ErrMsg number ErrNmbrdo shell script theShellScriptset theShellScript to ("( echo " & printedPath & " && ls -l \"" & theFolder & "\" ) | lpr " as string)set AppleScript's text item delimiters to OldDelimsset printedPath to items 1 thru (x - 1) of newTextList as stringset x to the count of newTextListset newTextList to text items of theFolderset OldDelims to AppleScript's text item delimiterson processFolder(theFolder)processFolder(thePOSIXFilePath)set thePOSIXFilePath to POSIX path of pShortPath as stringset pShortPath to (item i of these_items as string)if folder of the item_info is true then --if the item is a folderset the item_info to info for this_itemset this_item to (item i of these_items)repeat with i from 1 to the count of these_itemsset the item_info to {}on open these_itemsproperty pShortPath : ""end userPicksFolderset these_items to (choose folder with prompt "Select a folder whose contents you wish to print:") as listset these_items to {}on userPicksFolder()open FSif MyPath is item 1 of FS thenset MyPath to path to meelse if the SelectionCount is 1 thenset FS to userPicksFolder()if SelectionCount is 0 thenset SelectionCount to number of FS -- countset FS to FinderSelectiontell application "Finder" to set FinderSelection to the selection as alias listdisplay dialog "Finished reactivating non-Apple fonts." buttons {"OK"} default button 1display dialog "Could not reactivate \"" & typefaceToReactivate & "\"" buttons {"OK"} default button 1set «class fben» of «class fbfc» typefaceToReactivate to trueif (offset of "*" in typefaceToReactivate) is 0 thenset typefaceToReactivate to (read savedList before lf)set savedList to open for access savedListSpecset savedListSpec to choose file with prompt "Open the file containing the list of deactivated fonts"set lf to (ASCII character 10)tell application "TextEdit" to activateset paragraph paraIndex to return & returnif success thenset characters to tab & psName & return & returnset font to psNamerepeat with psName in postScriptNamesset paraIndex to paraIndex + 1set characters to familyName & return & returnset size to 14set font to "LucidaGrande"tell paragraph paraIndextell the front document of application "TextEdit"set the end of postScriptNames to «class fbps» of anotherFaceif «class fbfn» of anotherFace is familyName thenset anotherFace to first item of selectedTypefacesset postScriptNames to {«class fbps» of thisFace}set selectedTypefaces to the rest of selectedTypefacesset familyName to «class fbfn» of thisFaceset thisFace to first item of selectedTypefacesrepeat while selectedTypefaces is not {}set paraIndex to 3set size to 18numFaces & " typefaces" & return & return & returnnumFamilies & " families " & ¬set paragraph 1 to "Font Samples - " & ¬make new document at the end of documents of itif wasTextEditRunning thenset numFaces to count selectedTypefacesset numFamilies to count selectedFamiliesset selectedTypefaces to «class selc»set selectedFamilies to «class fbff»set wasTextEditRunning to (name of processes) contains "TextEdit"set collectionName to "Italic"set styleName to "Italic"delete (every «class fbcl» whose every «class fbfc» is {})if button returned of confirmResult is "好" thenset confirmResult to display dialog "Are you sure you want to delete empty collections?" & return & "You can not undo this action." with icon cautiondisplay dialog "There are no empty collections." buttons {"OK"} default button 1if (every «class fbcl» whose every «class fbfc» is {}) is {} then«event fbokfbad» (every «class fbfc» whose «class fbcr» contains searchText) given «class fbto»:«class fbcl» collectionNameset collectionName to "Copyright - " & searchTextset searchText to text returned of resultif button returned of result is "好" thenset result to display dialog "Enter text to look for in font's copyright information:" default answer "Apple"set «class fbcc» to «class fbcl» collectionName«event fbokfbad» (every «class fbfc» whose «class fbft» is fontTypeName) given «class fbto»:«class fbcl» collectionNameset collectionName to "Font type - " & fontTypeNameset fontTypeName to item 1 of chooseResultset chooseResult to choose from list my sortList(uniqueTypes) with prompt "Please select a font type."set the end of uniqueTypes to thisTypeif thisType is not in uniqueTypes thenif thisName does not start with "." thenset thisType to item i of fontTypesset thisName to item i of fontNamesrepeat with i from 1 to count fontNamesset uniqueTypes to {}set fontTypes to «class fbft» of every «class fbfc»set fontNames to name of every «class fbfc»end sortListreturn sortList(lowHalf) & p & sortList(highHalf)set highHalf to highHalf & iset lowHalf to lowHalf & iif i comes before p thenrepeat with i in listToSortset highHalf to {}set lowHalf to {}set listToSort to the rest of listToSortset p to the first item of listToSortreturn reverse of listToSortif item 1 of listToSort comes before item 2 of listToSort thenelse if n is 2 thenreturn listToSortif n is less than 2 thenset n to count of listToSorton sortList(listToSort)«event fbokfbad» (every «class fbfc» whose «class fbsn» is styleName) given «class fbto»:«class fbcl» collectionNamemake new «class fbcl» with properties {name:collectionName}if not («class fbcl» collectionName exists) thenset collectionName to "Style - " & styleNameset styleName to item 1 of chooseResultif chooseResult is false thenset chooseResult to choose from list my sortList(uniqueStyles) with prompt "Please select a style name."set uniqueStyles to uniqueStyles & aStyleif aStyle is not in uniqueStyles thenrepeat with aStyle in styleNamesset uniqueStyles to {}set styleNames to «class fbsn» of every «class fbfc»tell application "Font Book"end ChooseFileFromFAScriptFolderreturn SelectedScriptscopy alias ((path to Folder Action scripts folder from user domain as Unicode text) & EachScript) to end of SelectedScriptselse if EachScript is in UserScripts thencopy alias ((path to Folder Action scripts folder from local domain as Unicode text) & EachScript) to end of SelectedScriptsif EachScript is in LibraryScripts thenset SelectedScripts to {}with multiple selections allowedset ChosenScripts to choose from list LibraryScripts & UserScripts with prompt ChooseScriptPrompt ¬if (count LibraryScripts) + (count UserScripts) is greater than 0 thenset UserScripts to {}set UserScripts to list folder (path to Folder Action scripts folder from user domain) without invisiblesset LibraryScripts to {}set LibraryScripts to list folder (path to Folder Action scripts folder from local domain) without invisiblesto ChooseFileFromFAScriptFolder()open the resultmy ChooseFileFromFAScriptFolder()display dialog ItemName & ErrorMsg with icon cautionwith properties {name:ItemName}at end of scripts ¬make new script ¬tell folder action FANameif FileTypeOfItem is "osas" or FileExtensionOfItem is "scpt" thenset ItemName to name of ItemInfoset FileExtensionOfItem to name extension of ItemInfoset FileTypeOfItem to file type of ItemInfoif not folder of ItemInfo thenset ItemInfo to info for EachItemrepeat with EachItem in DroppedItemswith properties {path:TargetFolder} -- name:FAName,at end of folder actions ¬make new folder action ¬if folder action FAName exists thenset FAName to name of alias TargetFolderset TargetFolder to the result as textchoose folder with prompt ChooseFolderPrompton open DroppedItemsproperty ErrorMsg : " is not a compiled script. (Ignored)."property ChooseFolderPrompt : "Select a folder to attach actions"property ChooseScriptPrompt : "Select compiled script file(s) containing folder actions"tell application "System Events" to set folder actions enabled to falsetell application "System Events" to set folder actions enabled to truedisplay dialog NoFoldersActionsExist with icon notedelete folder action FolderActionNameif (count of FAScripts) is (count of ChosenScripts) then ¬delete script ScriptName of folder action FolderActionNameset ScriptName to contents of EachScriptrepeat with EachScript in ChosenScriptsif class of ChosenScripts is boolean thenwith prompt ChooseScriptPrompt & EachFolder with multiple selections allowedset ChosenScripts to choose from list FAScripts ¬set FAScripts to name of every script of folder action FolderActionNameset FolderActionName to contents of EachFolderrepeat with EachFolder in ChosenFoldersif class of ChosenFolders is boolean thenwith prompt ChooseFolderPrompt with multiple selections allowedset ChosenFolders to choose from list FolderActionNames ¬if FolderActionNames is not {} thenset FolderActionNames to name of every folder actionproperty NoFoldersActionsExist : "There are no folder actions."property ChooseScriptPrompt : "Select script(s) to remove from "property ChooseFolderPrompt : "Select folder(s) to remove folder actions from "reveal the added_itemsopen this_folderif user_choice is "Yes" thendisplay dialog the alert_message buttons {"Yes", "No"} default button 2 with icon 1 giving up after dialog_timeoutset the alert_message to (the alert_message & return & return & "Would you like to view the added items?")set alert_message to alert_message & "been placed in folder " & «data utxt201C» & the folder_name & «data utxt201D» & "."set alert_message to alert_message & "One new item has "set alert_message to alert_message & (the item_count as text) & " new items have "if the item_count is greater than 1 thenset alert_message to ("Folder Actions Alert:" & return & return) as Unicode textset the folder_name to the name of this_folderend closing folder window forclose window of EachFolderrepeat with EachFolder in (get every folder of folder this_folder)on closing folder window for this_folderdo shell script ("pstopdf " & source_item & " -o " & target_path)set the target_path to the quoted form of the POSIX path of (((results_folder as string) & new_name) as string)set the source_item to the quoted form of the POSIX path of the source_fileproperty extension_list : {"eps", "ps"}property type_list : {"EPSF"}property newimage_extension : "pdf"property originals_foldername : "Original Files"property done_foldername : "PDF Files"property done_foldername : "Original Images"save this_image as JPEG in file target_path with iconproperty extension_list : {"tif", "tiff", "gif", "png", "pict", "pct"}property type_list : {"TIFF", "GIFf", "PNGf", "PICT"}property newimage_extension : "jpg"property done_foldername : "JPEG Images"save this_image as PNG in file target_path with iconproperty extension_list : {"tif", "tiff", "jpg", "jpeg", "gif", "pict", "pct"}property type_list : {"TIFF", "JPEG", "GIFf", "PICT"}property newimage_extension : "png"property done_foldername : "PNG Images"save this_image as TIFF in file target_path with iconset this_image to open file (source_file as string)set the target_path to ((results_folder as string) & new_name) as stringon process_item(source_file, new_name, results_folder)return the target_nameset the name of document file target_name of the target_folder to the new_nameset the new_name to (the trimmed_name & "." & (name_increment as string) & "." & target_extension) as stringif (exists document file target_name of target_folder) thenset target_name to (the trimmed_name & "." & target_extension) as stringset target_extension to new_extensionset target_extension to file_extensionset target_name to file_nameif the new_extension is "" thenon resolve_conflicts(this_item, target_folder, new_extension)process_item(source_file, new_name, results_folder)set the source_file to (move this_item to the originals_folder with replacing) as aliasset the new_name to my resolve_conflicts(this_item, results_folder, newimage_extension)my resolve_conflicts(this_item, originals_folder, "")set the originals_folder to folder originals_foldername of this_foldermake new folder at this_folder with properties {name:originals_foldername}if not (exists folder originals_foldername of this_folder) thenset the results_folder to (folder done_foldername of this_folder) as aliasproperty extension_list : {"jpg", "jpeg", "gif", "png", "pict", "pct"}property type_list : {"JPEG", "GIFf", "PNGf", "PICT"}property newimage_extension : "tif"property originals_foldername : "Original Images"property done_foldername : "TIFF Images"flip this_image with horizontalflip this_image with verticalproperty done_foldername : "Flipped Images"set the comment of this_item to the comment_string"CS: " & color_space"BD: " & bit_depth & the data_delimiter & ¬"R: " & (image_DPI as string) & the data_delimiter & ¬"H: " & (image_height as string) & the data_delimiter & ¬"W: " & (image_width as string) & the data_delimiter & ¬set the comment_string to ¬set the data_delimiter to ", "copy the dimensions of these_properties to {image_width, image_height}set the bit_depth to item i of the bit_depth_titlesif this_depth is item i of the bit_depths thenset this_depth to the bit depth of these_propertiescopy the resolution of these_properties to {image_DPI, y}set the color_space to item i of the color_space_titlesif this_space is item i of the color_spaces thenrepeat with i from 1 to the count of the color_spacesset this_space to the color space of these_propertiesset these_properties to the properties of this_imageset this_image to open file target_itemset the target_item to this_item as stringset the index of column (item i of the column_list) of list view options of container window of the target_folder to (i + 1)repeat with i from 1 to the count of the column_listset the column_list to {comment column, size column, modification date column, creation date column, kind column, label column, version column}set visible of every column of list view options of container window of the target_folder to trueset uses relative dates of list view options of container window of the target_folder to falseset the icon size of list view options of container window of the target_folder to large iconset the current view of container window of the target_folder to list viewset the target_folder to (make new folder at this_folder with properties {name:done_foldername})property bit_depth_titles : {"sixteen colors", "color", "four grays", "black & white", "thousands of colors", "grayscale", "256 grays", "four colors", "sixteen grays", "millions of colors", "best", "256 colors", "millions of colors plus"}property bit_depths : {sixteen colors, color, four grays, black & white, thousands of colors, grayscale, two hundred fifty six grays, four colors, sixteen grays, millions of colors, best, two hundred fifty six colors, millions of colors plus}property color_space_titles : {"Eight channel", "Eight color", "Five channel", "Five color", "Seven channel", "RGB", "Lab", "XYZ", "Six channel", "CMYK", "Six color", "Seven color", "Named", "Gray"}property color_spaces : {Eight channel, Eight color, Five channel, Five color, Seven channel, RGB, Lab, XYZ, Six channel, CMYK, Six color, Seven color, named, Gray}using terms from application "Image Events"property extension_list : {"jpg", "jpeg", "tif", "tiff", "gif", "pct", "pict", "psd", "png"}property type_list : {"JPEG", "TIFF", "GIFf", "PICT", "8BIM", "PNGf"}property done_foldername : "Processed Images"rotate this_image to angle 270.0end process_itemon error error_messageclose this_imagesave this_image with iconrotate this_image to angle 90.0set this_image to open file this_itemlaunch -- always use with Folder Actionswith timeout of 900 secondsset this_item to this_item as stringon process_item(this_item)end resolve_conflictsset the name_increment to the name_increment + 1set the name of document file file_name of the target_folder to the new_nameif not (exists document file new_name of the target_folder) thenset the new_name to (the trimmed_name & "." & (name_increment as string) & "." & file_extension) as stringset the name_increment to 1set the trimmed_name to text 1 thru -((length of file_extension) + 2) of the file_nameset the trimmed_name to the file_nameif the file_extension is "" thenset file_extension to the name extension of this_itemif (exists document file file_name of target_folder) thenset the file_name to the name of this_itemon resolve_conflicts(this_item, target_folder)display dialog error_message buttons {"Cancel"} default button 1 giving up after 120if the error_number is not -128 thenprocess_item(target_file)set the target_file to (move this_item to the target_folder with replacing) as aliasmy resolve_conflicts(this_item, target_folder)if (alias of the item_info is false and the file type of the item_info is in the type_list) or (the name extension of the item_info is in the extension_list) thenset the item_info to the info for this_itemset the target_folder to folder done_foldername of this_folderset current view of container window of this_folder to list viewmake new folder at this_folder with properties {name:done_foldername}if not (exists folder done_foldername of this_folder) thenproperty extension_list : {"jpg", "jpeg", "tif", "tiff", "png"}property type_list : {"JPEG", "TIFF", "PNGf"}property done_foldername : "Rotated Images"open information window of this_folderelse if the user_choice is "Open Comments" thenset comment of this_folder to ""if the user_choice is "Clear Comments" thenset the user_choice to the button returned of the resultdisplay dialog alert_message buttons {"Open Comments", "Clear Comments", "OK"} default button 3 giving up after dialog_timeoutif the alert_message is not "" thenset the alert_message to the comment of this_folderproperty dialog_timeout : 30 -- set the amount of time before dialogs auto-answer.set cmdLine to ("sips --embedProfile " & profPath & " " & filePath) as stringset profPath to quoted form of POSIX path of embedProfset embedProf to choose file with prompt "Choose profile to embed" default location POSIX file "/System/Library/ColorSync/Profiles"display dialog "Embed a profile into an image."set cmdLine to ("sips --extractProfile " & newFilePosixPath & " " & imageFilePosixPath) as stringset imageFilePosixPath to quoted form of POSIX path of thisFileset newFilePosixPath to quoted form of POSIX path of newFilePathmove item (newFilePath as alias) to trashset newFilePath to choose file name default name newProfileName with prompt "Save profile as..."set newProfileName to (internalName & ".icc") as stringset newProfileName to ((characters 1 through 251 of internalName) & ".icc") as stringif strCount > 251 thenset strCount to count characters of internalNamedisplay dialog "no profile in " & (thisFile as text) buttons {"OK"} default button 1if internalName is equal to "" thenset internalName to item 2 of (text items of infoString)set AppleScript's text item delimiters to ": "set originalDelimiters to AppleScript's text item delimitersset cmdLine to ("sips -g profile " & filePath) as stringset chosenFile to choose file with prompt "Choose an image"display dialog "Extract the embedded profile from an image."set cmdLine to ("sips --matchTo " & profPath & " " & filePath) as stringset profPath to quoted form of POSIX path of matchProfset matchProf to choose file with prompt "Choose destination space profile" default location POSIX file "/System/Library/ColorSync/Profiles"display dialog "Match an image to another color space."set cmdLine to ("sips --matchTo " & destProfPath & " " & filePath) as stringset cmdLine to ("sips --matchTo " & proofProfPath & " " & filePath) as stringset destProfPath to quoted form of POSIX path of destProfset proofProfPath to quoted form of POSIX path of proofProfset destProf to choose file with prompt "Choose a destination space profile" default location POSIX file "/System/Library/ColorSync/Profiles"set proofProf to choose file with prompt "Choose an intermediate space profile" default location POSIX file "/System/Library/ColorSync/Profiles"display dialog "Proof an image through one space into another space."set cmdLine to ("sips -d profile --deleteColorManagementProperties " & filePath) as stringset chosenFile to choose file with prompt "Choose an image " default location path to desktop folderdisplay dialog "Remove the embedded profile from an image."set newName to fileNameelse if theButton is "filename" thendo shell script cmdLineset cmdLine to ("sips -s description '" & newName & "' " & filePath) as stringset newName to text returned of (display dialog "Enter new profile description string" default answer descriptionString)if theButton is "other..." thenset theButton to button returned of (display dialog "filename: " & fileName & return & "description: " & descriptionString & return & return & "Change description string to match the filename?" buttons {"no", "other...", "filename"} default button 3)set descriptionString to xmlvalue(infoString, "description")if xmlvalue(infoString, "pcs") is not equal to "" thenset cmdLine to ("sips -g allxml " & filePath) as stringset filePath to quoted form of POSIX path of thisFiletell application "Finder" to set fileName to name of thisFileset chosenFile to choose file with prompt "Choose a profile" default location POSIX file "/Library/ColorSync/Profiles"display dialog "Change a profile's description string."set cmdLine to ("sips -s " & theTag & " " & theValue & " " & filePosixPath & " --out " & filePosixPathNew) as stringset filePosixPathNew to quoted form of (POSIX path of thisFile & " new") as stringset theValue to quoted form of "best"set theTag to quoted form of "quality"display dialog "Example only. Drag this application onto Script Editor to edit."set chosenFile to choose file with prompt "Choose a color profile" default location path to desktop folderdisplay dialog "Set image or profile properties."end xmlvaluereturn value of property list item theItem of newPlistItemset newPlistItem to make new property list item with data theStringon xmlvalue(theString, theItem)display dialog infoStringset infoString to do shell script cmdLineset cmdLine to ("sips -g all " & filePosixPath) as stringset filePosixPath to quoted form of POSIX path of thisFilerepeat with thisFile in (draggedItems as list)on open draggedItemsopen chosenFileset chosenFile to choose file with prompt "Choose an image or profile" default location path to desktop folderdisplay dialog "Show information for images or profiles."set newTask to make new inbox task with properties {name:"Add tracking number to package tracking application.", note:_combined, flagged:true, context:theContext}set theContext to (first flattened context where its name = "Computer")set _combined to "message://%3c" & msg's message id & "%3e" & return & return & _title & return & return & _notesset _notes to the content of msgset _sender to sender of msgset _title to subject of msgset theAttachmentCount to (count of mail attachments of msg)set msg to item counter of theMessagesrepeat with counter from 1 to theMailCountset theMailCount to (count of theMessages)my writeTextToFile(outFile, risContent)set risContent to format pubsList using "RIS.fmt"if pubsList is not {} thenset pubsList to publication items of group item groupNametell front library windowset outFile to ((path to desktop from user domain) as string) & "Bibliography.ris"set groupName to "My Papers" -- adopt to your needstell application "Bookends""Please select a single cell in the table that is not in a row or column header.""Please select a single cell in the table before running this script.""Please select a single cell in a table before running this script.""Please create or open a document before running this script."set alertString to (errorNumber as string) & space & "MISSING RESOURCE"show newEvent{summary:taskName, start date:startTime, end date:endTime}set newEvent to make new event with properties ¬tell defaultCalendarset defaultCalendar to first calendar whose uid is calendarIDset defaultCalendar to calendar 1if calendarID is "UseLastSelectedAsDefaultCalendar" then(do shell script "defaults read com.apple.iCal CalDefaultCalendar")set calendarID to ¬set the background color of cell cellID to {38390, 64038, 22477}set value of cell cellID to firstNameset firstName to word 1 of userNameset userName to long user name of (get system info)set seconds of endTime to 0set minutes of endTime to endMinuteset hours of endTime to endHourcopy sessionDate to endTimeset seconds of startTime to 0set minutes of startTime to startMinuteset hours of startTime to startHourcopy sessionDate to startTimeset endMinute to (word -1 of sessionTimeString) as integerset endHour to (word -2 of sessionTimeString) as integerset startMinute to (word -3 of sessionTimeString) as integerset startHour to (word -4 of sessionTimeString) as integerthe formatted value of cell 2 of column of cell cellIDset sessionTimeString to ¬set sessionDate to the value of cell 1 of column of cell cellIDset taskName to the formatted value of cell 1 of row of cell cellIDaddress of column of cell cellID is 1 then error number 1003if address of row of cell cellID is less than or equal to 2 or ¬set cellID to the name of item 1 of selection rangeerror number 1002if the (count of cells of selection range) is not 1 then ¬set the alignment of row 1 to centerset the value of cell 1 of column (i + 1) to thisHeaderTitleset the value of cell 1 of row (i + 1) to thisHeaderTitleset thisHeaderTitle to item i of the headerTitlesrepeat with i from 1 to the count of the headerTitles{row count:rowCount, column count:columnCount}make new table with properties ¬set thisTable to ¬if errorNumber is -128 then error number -128on error number errorNumberset rowCount to elementCount + 1set columnCount to elementCount + 1if the elementCount is greater than 0 thenset the elementCount to the text returned of the result as integerdisplay dialog dialogMessage default answer "3"set the dialogMessage to "Enter the number of rows to add:"set columnCount to (length of the headerTitles) + 1set the dialogMessage to "Enter the number of columns to add:"set rowCount to (length of the headerTitles) + 1if the userChoice is "Row Headers" then{"Cancel", "Row Headers", "Column Headers"}display dialog "Use the state names as column headers or row headers?" buttons ¬set the headerTitles to {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"}log ("SCRIPT ERROR: " & errorMessage)write thisData to the openTargetFile starting at eof --as «class PNGf»set the openTargetFile to open for access file targetFile with write permissiondisplay alert errorNumber message errorMessageif errorNumber is -1719 thenerror "There was a problem writing the image file."reveal document file targetImageFileHFSPathelse if userChoice is "Show Image File" thenusing application file id "com.apple.mail"open document file targetImageFileHFSPath ¬if userChoice is "Send Image" thenset userChoice to the button returned of the result{"Send Image", "Show Image File", "OK"} default button 3 with icon 1display dialog "The table image has been created." buttons ¬if writeResult is true thenset the writeResult to my writeToFile(imageData, targetImageFileHFSPath, false)set the imageData to get the clipboard as «class PNGf»set targetImageFileHFSPath to targetImageFileHFSPath & ".png"if targetImageFileHFSPath does not end with ".png" thenset targetImageFileHFSPath to targetImageFile as stringset the targetImageFile to (choose file name default name defaultName)set the defaultName to (tableName & space & "Selection" & ".png")set the defaultName to (tableName & ".png")set tableName to the nameset the selection range to thisRangetell application "System Events" to ¬set the selection range to the cell rangeset thisRange to the selection rangeif the userChoice is "Table" thenset the userChoice to the button returned of the result{"Cancel", "Range", "Table"} default button 3 with icon 1"Save the entire table, or just the selection range, as an image?" buttons ¬display dialog ¬set thisTable to the first table whose class of selection range is rangeset errorMessage to "Please select a table before running this script."set alertString to "SELECTION ERROR"set alertString to "MISSING RESOURCE"set the text color of selectionRange to intersectionTextColorset background color of selectionRange to intersectionBackgroundColorset the font size of thisRow to 15set the font name of thisRow to "Helvetica"set the text color of thisRow to textColorset the background color of thisRow to backgroundColorset thisRow to item i of theseRowsrepeat with i from 1 to the count of theseRowsset the font size of thisColumn to 15set the font name of thisColumn to "Helvetica"set the text color of thisColumn to textColorset the background color of thisColumn to backgroundColorset thisColumn to item i of theseColumnsrepeat with i from 1 to the count of theseColumnsset theseRows to the rows of selection rangeset theseColumns to the columns of selection rangeset the selectionRange to the selection rangetell selectedTableset the textColor to {65535, 65535, 65535}set the backgroundColor to {52428, 26214, 65535}set the intersectionTextColor to {0, 0, 0} -- blackset the intersectionBackgroundColor to {65535, 65535, 65535} -- whiteerror number 1001(the first table whose class of selection range is range)set the selectedTable to ¬tell active sheetend incrementTableNameIfNeededreturn the testTableNamethisTableName & thisDivider & (incrementor as string)set the testTableName to ¬set incrementor to incrementor + 1repeat until testTableName is not in theseTableNamesset incrementor to 0set the testTableName to the thisTableNameset the theseTableNames to the name of every tableon incrementTableNameIfNeeded(thisTableName, thisDivider)display alert alertString message errorMessage buttons {"Cancel"}if the errorNumber is not -128 thenset alertString to "EXECUTION ERROR"set errorMessage to "There are no people in the chosen Contacts group."set errorMessage to "There are no groups in your Contacts."set alertString to "MISSING CONTACTS RESOURCE"set errorMessage to "Please create or open a document before running this script."set alertString to "MISSING NUMBERS RESOURCE"return thisTablesort by column 1 direction ascendingset the value of the last cell to formulaStringset the formulaString to "=COUNTIF(" & rangeString & ", FALSE)"set the rangeString to (name of cell 2 & ":" & name of cell -2)tell row irepeat with i from 2 to the count of rowsset alignment to centerset the value of cell 1 to "MISSED"set width to 60tell last columnset format to checkboxtell range (rangeStart & ":" & rangeEnd)set the rangeEnd to the name of last cell of column -2set the rangeStart to the name of cell 2 of column 2set width to 36tell columns 2 thru -2set value of cell i to item (i - 1) of the fullNamesrepeat with i from 2 to peopleCount + 1set width to 128set the alignment to leftset value of cell i to item (i - 1) of the columnTitlesrepeat with i from 2 to dayCount + 1set the alignment to centerset the vertical alignment to centerset the alignment of every row to centerset the vertical alignment of every row to centerset the height of every row to 24tell thisTable{column count:dayCount + 2, row count:peopleCount + 1, name:tableName}set thisTable to make new table with properties ¬tell the active sheetset tableName to my incrementTableNameIfNeeded(tableName, "-")"-" & year of (the current date)) as string(text 1 thru 3 of (thisMonth as string) & ¬set the tableName to chosenGroup & space & ¬set the dayCount to the count of the columnTitlesset tempDate to tempDate + (1 * days)set the end of the columnTitles to the dayTitle(thisDay & "-" & (text 1 thru 1 of thisWeekday)) as stringset the dayTitle to ¬thisWeekday is not in {"Saturday", "Sunday"}) thenif includeWeekends is true or (includeWeekends is false and ¬set thisWeekday to the (weekday of tempDate) as stringset thisDay to day of tempDaterepeat until month of tempDate is not thisMonthset thisMonth to the month of tempDateset day of tempDate to 1set the columnTitles to {}set tempDate to the current datetell application id "com.apple.AddressBook" to quitif AddressBookWasOpen is false thenset the peopleCount to the count of the fullNames(last name of thisPerson) & ", " & (first name of thisPerson)set the end of the fullNames to ¬set thisPerson to item i of thesePeoplerepeat with i from 1 to the count of thesePeopleset the fullNames to {}if thesePeople is {} then error number 1002set thesePeople to every person of group chosenGroupset the chosenGroup to the chosenGroup as stringif the chosenGroup is false then error number -128with prompt "Pick the Contacts group to be used for the table:")(choose from list the AddressBookGroupNames ¬set the chosenGroup to ¬if the AddressBookGroupNames is {} then error number 1001set the AddressBookGroupNames to the name of every grouptell application id "com.apple.AddressBook"set AddressBookWasOpen to truetell application id "com.apple.AddressBook" to launchset AddressBookWasOpen to falseif application id "com.apple.AddressBook" is not running thenset includeWeekends to falseset includeWeekends to trueif the button returned of the result is "Include Weekends" then{"Cancel", "Omit Weekends", "Include Weekends"} default button 3"Should the table include Saturdays and Sundays?" buttons ¬return & return & ¬"the attendance of the people in a chosen Contacts group." & ¬display dialog "This script will create a new table for tracking " & ¬if not (exists document 1) then error number 1000tell application id "com.apple.iWork.Numbers"start front document from startingSlideset the transition properties of every slide to {transition effect:no transition effect, transition duration:0, transition delay:1, automatic transition:true}if newTime is ":00" then exit repeatset object text of the default title item to newTimeset newTime to newMinutes & ":" & newSecondsset newMinutes to amountInMinutesset newSeconds to "0" & newSecondsif length of newSeconds is 1 then((amountInSeconds as integer) - 1) as stringset newSeconds to ¬if newMinutes is "0" then set newMinutes to ""((amountInMinutes as integer) - 1) as stringset newMinutes to ¬set newMinutes to ""if amountInMinutes is "0" thenset newSeconds to "59"if amountInSeconds is "00" thenset amountInSeconds to second word of slideTextset amountInMinutes to first word of slideTextset amountInSeconds to first word of slideTextset amountInMinutes to "0"if slideText begins with ":" thenset slideText to object text of the default title itemtell the last slideduplicate (get current slide)set startingSlide to current slideend createScaledQRCodeImageObjectForStringset aTransform to current application's CGAffineTransform's CGAffineTransformMakeScale(xScale, yScale)set yScale to targetHeight / (baseImageSize's height())set xScale to targetWidth / (baseImageSize's width())set baseImageSize to baseImage's extent()'s |size|()on createScaledQRCodeImageObjectForString(thisString, targetWidth, targetHeight)end createFullSizeQRCodeImageObjectForStringreturn resultingImageObjectresultingImageObject's addRepresentation:imageRepresentationset resultingImageObject to current application's NSImage's alloc()'s initWithSize:(imageRepresentation's |size|())set imageRepresentation to current application's NSCIImageRep's imageRepWithCIImage:outputImageset outputImage to baseImage's imageByApplyingTransform:aTransformset aTransform to current application's CGAffineTransform's CGAffineTransformMakeScale(100.0, 100.0)set baseImage to anImageFilter's outputImage()anImageFilter's setValue:"L" forKey:"inputCorrectionLevel"anImageFilter's setValue:thisData forKey:"inputMessage"anImageFilter's setDefaults()set anImageFilter to current application's CIFilter's filterWithName:"CIQRCodeGenerator"set thisData to thisString's dataUsingEncoding:(current application's NSUTF8StringEncoding)set thisString to current application's NSString's stringWithString:thisStringon createFullSizeQRCodeImageObjectForString(thisString)display alert "Unable to Complete Request:" message errorMessage buttons {"Cancel"} default button 1tell application (POSIX path of (path to frontmost application))set theTask to (current application's NSTask's launchedTaskWithLaunchPath:cfgutil arguments:{(spokenErrorTitle & errorMessage)})set cfgutil to "/usr/bin/say"set spokenErrorTitle to "I was unable to complete your request: "say "Done!"(fileManager's trashItemAtURL:URLOfItemToTrash resultingItemURL:resultingURL |error|:(missing value))set URLOfItemToTrash to (current application's |NSURL|'s fileURLWithPath:thisPOSIXPath)set resultingURL to missing valueset thisPOSIXPath to current application's NSString's stringWithString:targetItemPOSIXPathset the position of thisImage to {(documentWidth - targetMinimumDimension) div 2, (documentHeight - targetMinimumDimension) div 2}set thisImage to make new image with properties {file:targetFile, width:targetMinimumDimension, height:targetMinimumDimension}tell current slideset documentHeight to the height of itset documentWidth to the width of itif not (exists document 1) thenset the targetFile to targetItemHFSPath as aliasmy writeNSImageObjectToFileAsJPEG(thisImageObject, targetItemPOSIXPath, false)set thisImageObject to my createFullSizeQRCodeImageObjectForString(clipboardText)set targetItemPOSIXPath to POSIX path of targetItemHFSPathset the targetItemHFSPath to (theURL as string) & (theUUID as string) & ".jpg"set theURL to (fileManager's URLsForDirectory:(current application's NSPicturesDirectory) inDomains:(current application's NSUserDomainMask))'s firstObject()set fileManager to current application's NSFileManager's defaultManager()set theUUID to current application's NSUUID's UUID()'s UUIDString()error "There is no text on the clipboard to convert into a QR code image."set clipboardText to (get the clipboard as «class utf8»)if (clipboard info for «class utf8») is not {} thenproperty targetMinimumDimension : 400use framework "CoreGraphics"display alert "ERROR" message errorMessageset presenter notes to (item i of translatedNotes)tell targetSlideset targetSlide to (first slide whose slide number is i)repeat with i from 1 to the count of translatedNotesdisplay alert "EXTRACTION ERROR" message errorMessagedisplay dialog "Notes extraction complete. Click “Continue” to switch to Keynote and replace the notes in the current document." buttons {"Cancel", "Continue"} default button 2 with icon 1display alert "INCORRECT PAGE" message "The current page was not generated by the translation script."set the end of translatedNotes to thisNote(do JavaScript "document.getElementById('txtarea" & (i as string) & "').value;" in current tab of window 1)set thisNote to ¬repeat with i from 1 to elementCountset translatedNotes to {}(do JavaScript "document.getElementsByTagName('textarea').length;" in current tab of window 1) as integerset elementCount to ¬if pageSource contains "Page Generated for Translation" thenset pageSource to source of current tab of window 1display dialog "This script will replace the presenter notes in the current Keynote document with the notes from this webpage." with icon 1if not (exists document 1) then error "There is no document open in Safari."if KeynoteStatus is false then "There is no document in Keynote."set KeynoteStatus to (exists document 1)end matchItemByIndexToCorrespondingListreturn item i of matchingListif item i of sourceList is itemToMatch thenrepeat with i from 1 to the count of sourceListif length of sourceList is equal to length of matchingList thenon matchItemByIndexToCorrespondingList(itemToMatch, sourceList, matchingList)return sourceTextset sourceText to the itemList as stringset AppleScript's text item delimiters to the replacementStringset the itemList to every text item of sourceTextset AppleScript's text item delimiters to the searchStringon replaceText(sourceText, searchString, replacementString)close access the openTargetFilewrite thisData to the openTargetFile starting at eof as «class utf8»if appendData is false then set eof of the openTargetFile to 0open for access file targetFile with write permissionset the openTargetFile to ¬set the targetFile to the targetFile as stringon writeToFile(thisData, targetFile, appendData)make new tab with properties {URL:GoogleTranslateURL}set thisWindow to make new document with properties {URL:thisURL}"/" & destinationLanguageID & "/""https://translate.google.com/#" & sourceLanguageID & ¬set GoogleTranslateURL to ¬set thisURL to the URL of disk item targetFileHFSPathif my writeToFile(HTMLOutline, targetFileHFSPath, false) is true thenset targetFileHFSPath to (temporaryFolder as string) & fileNameset temporaryFolder to (path to temporary items folder from user domain)set fileName to (do shell script "uuidgen") & ".html"linefeed & "" & linefeed & """ & linefeed & HTMLBody & ¬textarea {width:96%;}7f00ff00ff00ffff

    "property oneWindow : falseproperty factorySettings : {gridRows:2, gridCols:2, gridInnerMargin:0, edgeWindows:0, resizeWindows:1, moveWindows:1, ignoreInfoWindow:true, ignoreMinimizedWindow:true, activateFinder:true, alwaysOnTop:true, stackOffset:{22, 22}, stackMargin:{300, 300}, stackBounceOffset:{200, 0}}property userDefaults : "" -- set on app initproperty titleBarHeight : 22 -- or 16 for Special Info Window (see issue#3)property menuBarHeight : 22 -- system's top menu barproperty sidebarWidth : 120property gridWebView : missing valueproperty moveWindows : missing valueproperty resizeWindows : missing valueproperty edgeWindows : missing valueproperty gridInnerMargin : missing valueproperty gridCols : missing valueproperty gridRows : missing valueproperty myWindow : missing valuescript FinderWindowFunAppDelegateproperty NSScreen : class "NSScreen"set msg to pre & " 01 " & chanType & " 00 00 00 " & chanNumVal & " 00 00 00 00 " & valueset chanType to hex(96)set chanType to hex(95)set chanType to hex(94)if operation = "cue" or operation = "nocue" thenset msg to pre & " 00 " & chanType & " 00 00 00 " & chanNumVal & " 00 00 00 00 " & valueset chanType to hex(93)set chanType to hex(76)set chanType to hex(49)if chan = "ch" or chan = "st" thenif operation = "on" or operation = "off" thenset value to hex(0)set value to hex(1)if operation = "on" or operation = "cue" thenset operation to item 3 of splitTextset chanNumVal to hex(chanN * 2 + 62)if chan = "st" thendisplay dialog "Enter Channel Control String" default answer "" buttons {"Set", "Cancel"} cancel button "Cancel" default button "Set" with title "SCENE NUMBER"return 900set ping to (do shell script "ping -c 2 " & IP_address)set IP_address to "8.8.8.8"set the clipboard to (_links as string)set end of _links to _messageURLset _messageURL to "message://%3c" & _msg's message id & "%3e"repeat with _msg in _selset _links to {}set _sel to get selectionwindowSize's windowSize({xsize:1, ysize:0.5, xpos:0, ypos:0.5})sleeptell application "System Events"SetViewInfo {latitude:latitude of loc, longitude:longitude of loc, distance:(distance of loc) * 2, tilt:tilt of loc, azimuth:azimuth of loc} speed 1set loc to GetViewInfotell application "Google Earth Pro"display dialog "Hello!"to say_hello()-- A say_hello commandtell theRecord to make new reminder with properties {schedule:once, alarm:notification, due date:due_date}set due_date to due_date + 3600 * 24set due_date to current dateend fmGUI_CheckboxSettell application "htcLib" to fmGUI_CheckboxSet({objRef:objRefStr} & prefs)on fmGUI_CheckboxSet(prefs)end fmGUI_ManageSecurity_PrivSet_Update_AccessValueListerror "unable to fmGUI_ManageSecurity_PrivSet_Update_AccessValueList - " & errMsg number errNumclickObjectByCoords(noAccessCheckbox)else if vlPriv of oneVLRec is equal to "no access" thenclickObjectByCoords(viewCheckbox)else if vlPriv of oneVLRec is equal to "view only" thenclickObjectByCoords(modifyCheckbox)if vlPriv of oneVLRec is equal to "modifiable" thenif item 2 of oneVLInfo is not equal to vlPriv of oneVLRec thenset oneVLInfo to name of every static text of oneVLRowselect oneVLRowset oneVLRow to (first row of table 1 of scroll area 1 of window 1 whose name of static text 1 is vlName of oneVLRec)set oneVLRec to contents of oneVLRecrepeat with oneVLRec in vlPrivList of vlAccess of prefsfmGUI_CheckboxSet({objRef:allowCreate, objValue:allowCreate of vlAccess of prefs})set noAccessCheckbox to checkbox 4 of window 1set viewCheckbox to checkbox 3 of window 1set modifyCheckbox to checkbox 2 of window 1set allowCreate to checkbox "Allow creation of new value lists" of window 1windowWaitUntil_FrontIS({windowName:"Custom Value List Privileges"})if accessVL of prefs begins with "Custom privileges" thenfmGUI_Popup_SelectByCommand({objRef:valueListsPopup, objValue:accessVL of prefs, selectCommand:"contains", clickIfAlreadySet:true})if windowName is not windowNameEditPrivSet then error "do not have " & windowNameEditPrivSet & " window open" number -1024set valueListsPopup to pop up button "Value Lists:" of window 1set defaultPrefs to {accessVL:null, vlAccess:null}on fmGUI_ManageSecurity_PrivSet_Update_AccessValueList(prefs)fmGUI_ManageSecurity_PrivSet_Update_AccessValueList({accessVL:"Custom privileges...", vlAccess:{allowCreate:0, vlPrivList:{{vlName:"YesNo", vlPriv:"view only"}, {vlName:"CompleteInProgress", vlPriv:"modifiable"}, {vlName:"[Any New Value List]", vlPriv:"view only"}}}})print errMsgtell process frontApplicationset frontApplication to (get name of every process whose frontmost is true) as stringtell application "Typinator" to create from clipboardtell application "Typinator" to create from selectionif (menu item "Copy" of menu 1 of menu bar item "Edit" of menu bar 1) is enabled thentell (first process whose frontmost is true){name:"flake8 for " & thepath}make new results browser with data errorList with properties ¬copy {result_document:text document 1, result_kind:thekind, result_file:filepath, result_line:linenumber, message:themessage} to end of errorListset thekind to note_kindset thekind to error_kindelse if errorCode is in {"E", "F"} thenset thekind to warning_kindif errorCode is "W" thenset errorCode to character 2 of themessageset {filepath, linenumber, charoffset, themessage} to every text item in x as listrepeat with x in every paragraph of rset errorList to {}set r to do shell script flakePath & " --max-line-length=" & maxLength & " --max-complexity=" & maxComplexity & space & thepath & " --exit-zero"set thepath to quoted form of POSIX path of (sourceFile as alias)set sourceFile to file of text document 1save text document 1display dialog "Document '" & n & "' does not seem to be Python!"set thename to name of text document 1if source language of text document 1 is not "Python" thenif not (exists text document 1) thendisplay dialog "Could not find flake8 binary at '" & flakePath & "'"if not (exists (POSIX file flakePath as alias)) thenproperty flakePath : "/usr/local/bin/flake8"property maxComplexity : 12property maxLength : 256set rec to setKeyValue(rec, "d", 4)log getKeyValue(rec, "a")set rec to {a:1, b:2, c:3}end setKeyValueresult's setValue(rec, val)r & {|" & k & "|:v}on error number -10006rset r's |" & k & "| to von setValue(r, v)on setKeyValue(rec, k, val)end getKeyValueresult's getValue(rec)me"r's |" & k & "|on getValue(r)on getKeyValue(rec, k)if added is false then error "No linked images in this document"set added to trueadd download thisLink referrer this_URL without automaticif thisLink ends with ".jpg" or thisLink ends with ".JPG" or thisLink ends with ".jpeg" or thisLink ends with ".JPEG" or thisLink ends with ".gif" or thisLink ends with ".GIF" or thisLink ends with ".png" or thisLink ends with ".PNG" thenrepeat with thisLink in these_linksset these_links to get links of this_source base URL this_URLset this_URL to the URL of theWindowset this_source to the source of theWindowif not (exists think window 1) then error "No window is open."set added to falsewriteTextToFile(resultText, folderName & a & ".txt", true)set resultText to convertListToString(currList, LF)set currList to item a of all_url_listrepeat with a from 1 to length of all_url_listset TabInfo to (TabTitle & LF & TabURL & LF)else if browserName is "Google Chrome" thencopy url_list to the end of all_url_listset TabInfo to ("" & TabTitle & return & TabURL & return)set TabTitle to (name of t)repeat with t in (tabs of thisWind)local url_listrepeat with thisWind in (get windows)if browserName is "Safari" thenset folderName to item (getPositionOfItemInList(browserName, browser_list)) of paths_list%Ai�����#���:���Ia|�*V����,Rl��t� F����1w���?g�2f��� N � �  S � � * g � � B | � � K � � f��T��<t��+_w��9a��� ;m��Mj���%x��#Gu��Gs��-U�����0\��r����  ?Sy��?t����Di�k � � !!*!N!�!�!�!�!"""O"^"{"�"�"T#�#�#�#O$^${$�$%M%s%�%�%�%8&H&X&p&�&�&�&'/'n'�'�'�'�'3(z(�(�(�(�2B3�3�3�3 44F4[4u4�4�4�4�4'5g5r5�5�5�5�56+6M6s6�6�6�6�6�6�6�67!7Y7�7�7�7*8y8�8�8$9:9a9�9�9�9:(:J:�:�:;";>;a;�;#<r<�<�<"=2=I=�=�=�=->�>�>?4?�?�?K@�@�@�@�@A�A�A)B3BZBnB�B�B�B�BC$CxC�CDSD�D�DE2EaE|E�E�E�EF)F:FqF�F�F�F�F�F�FG!GLG^GpG�G�G�G�G�G HH'H>HUH�H�H�HI&I2IEIZI�I�I�I�I�IJ+JWJjJ�J�J�J�J�JK@KSKiK|K�K�K�K�KL%LQLdLwL�L�L�L�L"M5MJM]MsM�M�M�M�MNN0N]NpN�N�N�N�N�NO*O@OlOO�O�O�OPP@PSPP�P�P�P�P�P)QVQV}V�V�V�V�VW!WMW`WvW�W�W�W�W XX0X\XoX�X�X�X�XY,YXYkY�Y�Y�Y�YZ,Z?ZRZ~Z�Z�Z�Z�Z[<[O[|[�[�[�[�[�[ \7\J\v\�\�\�\�\�\]]1]D]p]�]�]�]�]^^C^V^l^�^�^�^�^_-_@_V_�_�_�_�_�_�_*`=`i`|`�`�`�`�`&a9aeaxa�a�a�a�a b bLb_bub�b�b�b�bccGcZcoc�c�c�c�cddDdWd�d�d�d�d�d�de!eNeae�e�e�e�e ff2fEfXf�f�f�f�fggAgTg�g�g�g�g�gh?hRh~h�h�h�h�hi;iNizi�i�i�i�i j8jKj^j�j�j�j�j�jk/k[knk�k�k�k�kl,lXlkl�l�l�l�l�l*m=mim|m�m�m�m�mn=nPn}n�n�n�n�n�n ooJo]opo�o�o�o�op.pApWp�p�p�p�pqq'q:qgqzq�q�q�q�q%r8rdrwr�r�r�r�r s6sIs\s�s�s�s�s�st/tBtot�t�t�t�tu,u?uku~u�u�u�u�uv?vRvv�v�v�v�v�v'w:wPwcw�w�w�w�w x xLx_xux�x�x�x�x y3y_yry�y�y�y�yz/z[znz�z�z�z�z�z{({T{g{�{�{�{�{|$|P|c|�|�|�|�|�|#}6}I}u}�}�}�}�}~2~E~q~�~�~�~�~/Bo�����-�@�l������Ԁ��&�9�L�x�������āׁ��)�<�i�|�����΂�� �9�L�y�������Ń���*�=�P�|�������˄�� �6�I�u�����ȅۅ��F�Y�������׆��*�V�i�����ԇ���&�9�e�x�����ʈ�� ��/�B�U�������Ӊ��?�R�e�x��������"�5�b�u�����Nj���F�Y�����ƌٌ��+�>�k�~�����э��#�9�e�x�������� �5�H�[�n����������+�>�k�~�����А���"�5�H�[�����Ǒڑ��-�Y�l�����’���'�S�f�y��������#�6�b�u�����ǔ��3�F�r�����ĕ��/�B�n�������Ӗ���>�Q�d�����ϗ��"�N�a����������#�6�b�u�����Ǚ���3�F�r�����Ě��0�C�Y�����ěכ��B�U�h�����Ӝ��%�Q�d�����ϝ��!�M�`�����̞ߞ��1�D�p�����Ÿ��-�@�l������Ѡ��#�O�b�����͡� ��K�^�����ʢݢ��0�C�p�����£գ��@�S������Ѥ��#�6�I�u�����ǥڥ��,�X�k�����֦���(�;�N�z�����̧ߧ ��J�]�����Ȩۨ��F�Y�l�����ة��+�X�k�����ת����<�O�{�����ͫ���2�E�q�����ì֬��B�U�������֭����"�5�a�t�����Ǯڮ��F�Y�����įׯ��,�X�k�����װ���)�<�h�{��������&�9�e�x�����ʲ�� �5�H�[�����Ƴٳ��D�W�����ôִ��B�U�������ӵ���>�Q�}�����ж��"�N�a�t�����Ʒ��2�E�r�����ĸ���B�U�������Թ��@�S������Ѻ���#�O�b�u�����ǻڻ��F�Y�����żؼ��C�V�i�����Խ���&�9�L�x�����˾޾ ��I�\�������ݿ��/�B�o����������,�?�R�~����������#�P�c�v��������� �3�_�r����������0�\�o����������,�?�l�����������=�P�|����������!�M�`�s����������1�D�p����������-�@�l����������*�=�i�|���������&�9�e�x���������"�5�H�[������������,�X�k�~���������)�<�h�{��������� ��L�_������������0�C�V�����������?�R�~����������#�6�c�v�����������G�Z������������+�W�j����������(�U�h�{���������&�9�L�_��������� ��/�[�n����������,�?�k�~���������+�>�Q�d�w���������"�5�a�t����������3�F�Y������������*�V�i�����������'�:�f�y��������� ��J�]�����������-�@�l�����������<�O�{��������� �8�K�^��������� ��H�[�n����������+�X�k����������,�?�k�~����������#�O�b�u��������� �3�`�s����������1�D�p�����������@�S�����������>�Q�d�w��������� ��J�]��������� ��I�\�����������E�X�k����������+�W�j�}���������'�:�f�y��������� ��J�]�p�����������B�U������������%�R�e�����������#�6�I�u����������3�F�r����������/�B�n�����������+�>�j�}���������)�<�h�{��������� �9�L�y��������� ��0�C�p������������(�T�g�z��������� �9�L�y�������������D�W�����������A�T������������=�P�}����������:�M�y��������� �6�I�u���������2Eq����.AT�����&Sfy���� 7Jv����5Ht����DW����BUh{����&9L_r����CV������& 9 e x � � � � �  / [ n � � � �  - Y l � � � � � ) < h { � � � �  9 L _ � � � � � )<h{����%8dw����!4`s����EX����(Tg����%Qd����#Ob���� L_r����1]p����.An�����%Re����"Na�����1]p����-@Sf����$Qd����"Ob����  3_r����/[n����  ? R ~ � � � � !#!O!b!�!�!�!�!�!"4"G"Z"�"�"�"�"##D#W#�#�#�#�#$$B$U$�$�$�$�$�$%>%Q%}%�%�%�%�%&!&M&`&�&�&�&�&�&'0'C'V'�'�'�'�'�'()(U(h({(�(�(�(�(�()2)_)r)�)�)�)�)*1*^*q*�*�*�*�*++B+U+�+�+�+�+,,&,S,f,�,�,�,�,-$-7-d-w-�-�-�-�-!.4.`.s.�.�.�.�./0/C/o/�/�/�/�/00@0S0�0�0�0�0�01=1P1|1�1�1�1�12;2N2z2�2�2�2�2 3313]3p3�3�3�3�34-4Z4m4�4�4�4�45+5>5Q5g5�5�5�5�5�56"6N6a6�6�6�6�6 77J7]7�7�7�7�7�78-8Y8l8�8�8�8�8�8+9>9Q9~9�9�9�9�9:=:P:|:�:�:�:�:;!;M;`;�;�;�;�;�;<0<C<o<�<�<�<�<=-=@=l==�=�=�=�=)><>i>|>�>�>�>�>?"?N?a?�?�?�?�? @ @M@`@�@�@�@�@�@A2A^AqA�A�A�A�AB0BCBoB�B�B�B�B�BC&C9CeCxC�C�C�C�C D5DHDuD�D�D�D�D�DE.EZEmE�E�E�E�E�EF>FQF}F�F�F�F�FG;GNG{G�G�G�G�G HHKH^HqH�H�H�H�HII(ITIgI�I�I�I�IJ&JRJeJ�J�J�J�J�J'K:KfKyK�K�K�K�K#L6LILuL�L�L�L�LM3MFMrM�M�M�M�MN0NCNoN�N�N�N�NOOBOUO�O�O�O�OPP&PRPeP�P�P�P�P�P QQHQ[Q�Q�Q�Q�Q�QR-RZRmR�R�R�R�R�R*S=SiS|S�S�S�S�S T TLT_T�T�T�T�T UU/U[UnU�U�U�U�UV,V?VkV~V�V�V�V�VW"WNWaW�W�W�W�W�WX2X^XqX�X�X�X�XY.YZYmY�Y�Y�Y�YZ+ZWZjZ�Z�Z�Z�Z[)[<[h[{[�[�[�[�[ \8\K\x\�\�\�\�\ ]]J]]]�]�]�]�] ^^H^[^n^�^�^�^�^_+_W_j_�_�_�_�_`(`U`h`�`�`�`�`a%a8adawa�a�a�a�abbGbZb�b�b�b�bcc+cWcjc}c�c�c�c�cd:dMdyd�d�d�d�d eeIe\e�e�e�e�e�ef0f]fpf�f�f�f�fg-g@glgg�g�g�g�g)h�Q�~�����Ц���;�N�z�����ͧ�� �9�L�y�����˨�� �6�I�u�����ǩک��F�Y�l�����ת���)�<�O�{�����ͫ�� ��L�_�r�����ݬ��/�B�o���������-�@�S�����������&�9�L�_�r�����ů���C�V�i�|�����ΰ���:�M�`�����̱߱ ��K�^�������ݲ��0�\�o�������Գ��&�S�f����������%�8�K�w�����ʵ�� �6�I�v�����ȶ۶��F�Y�o�������Է��@�S�������Ҹ��$�P�c����������"�5�b�u��������!�4�a�t�����ƻٻ��+�W�j�����ּ��(�;�N�z�����̽�� �8�K�w�����ɾ�� �6�I�v�����ɿ���4�G�s�����������D�W�����������A�T������������=�P�c����������!�M�`��������� ��0�\�o����������-�@�m����������,�?�l�����������$�7�c�v���������"�5�a�t����������3�F�r����������0�C�V�����������(�;�g�z���������%�8�d�w����������4�G�s�������������*�=�P�|��������� � �L�_�r�����������*�V�i�����������'�:�f�y���������$�7�c�v�����������-�Y�l����������)�<�i�|��������� � �L�_������������/�[�n����������-�@�l�����������?�R������������#�6�b�u����������3�F�r�����������C�V�����������@�S�f����������#�O�b����������!�M�`��������� ��K�^�q����������.�Z�m�����������+�>�j�}���������(�;�N�z��������� �8�K�w��������� �5�H�t�����������E�X������������+�X�k�����������)�<�R�~����������#�P�c����������� �3�_�r����������0�\�o������������'�S�f����������#�P�c����������� �3�F�r�������������)�<�i�|���������'�:�g�z���������%�8�d�w��������� �6�I�u����������4�G�s����������0�C�p����������.�A�T�������������%�8�d�w���������"�5�K�w��������� �5�H�t�����������G�Z������������*�=�i�|���������&�9�e�x��������� �6�I�u����������2�E�X�k����������)�V�i����������'�S�f����������� J]p����-@Sfy���� 7J]p����-Yl�����)<O{���� :My���� 7J]s����2Er����DW����� ) U h � � � � � ' : M y � � � �  8 K w � � � �   I \ r � � � �  1 D p � � � � @S�����$7cv����4Gs����,?k~����*=i|���� :My���� J]p����-Yl����)<h{����':gz����&9ex���� 5Ht����2Eq����.Am�����'Sf�����$7dw���� 5Ht����,Xk~����* = j } � � � � )!8k8~8�8�8�8�8)9<9h9{9�9�9�9�9 :9:L:_:r:�:�:�:�:;/;[;n;�;�;�;�;<,<X<k<�<�<�<�<=)=V=i=�=�=�=�=�=&>9>f>y>�>�>�>�> ??0?\?o?�?�?�?�?@.@Z@m@�@�@�@�@A+AWAjA�A�A�A�AB'BSBfB�B�B�B�BC#COCbCuC�C�C�C�CDDEDXD�D�D�D�DEECEVEiE�E�E�E�EF'FSFfF�F�F�F�F�F GG1G^GqG�G�G�G�GH/HBHUHhH~H�H�H�H�H(I;IgIzI�I�I�I�I J7JJJwJ�J�J�J�J KKHK[K�K�K�K�K�KL,L?LRL~L�L�L�L�LM"M5MaMtM�M�M�M�MNNFNYN�N�N�N�NOOBOUOhO�O�O�O�O�O(P;PhP{P�P�P�P�P QQKQ^Q�Q�Q�Q�QRRGRZR�R�R�R�RSSCSVS�S�S�S�S�ST'TSTfTyT�T�T�T�T$U7UdUwU�U�U�U�U#V6VIVvV�V�V�V�V�VW-WYWlWW�W�W�W�WX#XOXbX�X�X�X�X Y YLY_Y�Y�Y�Y�Y ZZIZ\Z�Z�Z�Z�Z�Z[,[?[k[~[�[�[�[�[\;\N\z\�\�\�\�\ ]7]J]w]�]�]�]�]^5^H^u^�^�^�^�^_2_E_q_�_�_�_�_``C`V`�`�`�`�`�`�` a:aMaya�a�a�a�a bb2b^bqb�b�b�b�bc/cBcUc�c�c�c�cdd&d9dedxd�d�d�d�d�de/eBene�e�e�e�ef-f@fmf�f�f�f�f�f+g>gjg}g�g�g�g�ghlQl}l�l�l�l�lm:mMmym�m�m�m�m nn1nDnqn�n�n�n�noo)oUoho�o�o�o�op&p9pepxp�p�p�p�p$q7qdqwq�q�q�q�qrrHr[rnr�r�r�r�rs+s>sjs}s�s�s�s�st;tNtzt�t�t�t�t u8uKuwu�u�u�u�u vvJv]v�v�v�v�vwwFwYwlw�w�w�w�wx*xVxix|x�x�x�x�xy!yNyay�y�y�y�y zzJz]zpz�z�z�z�z{{@{S{{�{�{�{�{|<|O|{|�|�|�|�|�| }3}`}s}�}�}�}�}~0~C~p~�~�~�~�~/BU������&�9�e�x�����ʀ�� �5�H�t�����Ɓ��1�D�p�����‚Ղ��A�T�������҃��� ��1�]�p�����܄��.�A�m�������҅���$�P�c�����Ά� � �M�`�s�����އ��0�\�o�����ۈ��-�@�l������щ���#�O�b�����͊�� ��K�^�����ʋ݋ ��H�[�n�����ڌ��,�?�k�~��������(�;�N�{�����͎�� �9�L�x�����ˏޏ��0�C�o���������,�?�|������=�a����Y�������;�e�������7���������ҕ��(�i����������d�����>���ۘ�8�n���ߙ�F������-�E�R�������?��������#�C�}��� �C�~�����Ğߞ�� �1�E�a�����џ��8�S�����:�Z�d�����*�N���Ӣ���7�\�٣�z�����ݤ��G�R�~���¥ݥ!�7�J�t����=�c�����]�����Ҩ�S�m���������(�?�_�����ŪѪԪ��M�V����#�\�����/�z�������Y��� �{��b�ϰK���E�Z�u��I�����Գ��D������G�`��������7�~�����ݶA�r���˷�1�����Ÿظ<�U���߹�D���ٺ�;�b������9�|���ȼ�)�M�{���Ž���A�L���Ӿ��0�Y���ݿ�D�����������&�A�Z���*�B�M�{����7�`���������*�������G�����A�b�����c��������)�i�������B�n������&�W�|��������.�^�����,�A�P�x�������&�c�{����������G�d�����������3�N������������@�j������� �\�{�������.�N�}��������>���4�R�v������T������� �G�l����������D�Y��������6�V�z���������-�R����������*�H�l���������"�]�~��������$�v��!�H�t��������$�2�g�������:�v������Z�����&�h�����I�c������>�y������&�-�W�z���������8�l������� �:�O������+����� �g������K������V�����T�������*�:�y������(�i�y�����*�^��������H�v���������#�D�h����������9�]����������C�m��������)�t����������n������9�[�n��������/�L�s����(�V�n������� ��7�k��������-�a����������/�������*�>�_�������;�b�|��������2�E�]�o������������� /U��?g���As�Q^�k��������% L { � � �  6 c ~ � � � � ( R t � & > U �  , F � Lcy��� $Kcw���:j��0{��"�����7Ur���&]� O��K^���-F�1u���Z�+Af����Z����g����*>d�� 8 � � �  !!,!_!�!�!"C"f"�"�"�"#A#q#�#�#G$u$�$�$�$%C%&G&y&�&�&�'�'�'((7(Q(k(�(�(�(�(�(�(�( )).)J)e)�)�)�)D**�*�*'+8+h+�+�+,9,�,�,�,-\-�-�-�- .O.�.�./=/n/�/�/10W0b0y0�0�0121U1t1�1�1�12O2�2�2�2 3C3v3�3�3.4I4t4�4�4�45H5r5�566[6{6�67[7�758_8{8�8S9�9:�:�:Y;m;�;<S<�<3=�=�=l>�>�>�>n?�?@6@E@V@�@�@�@ATA�A�A�AB=BNB�BC-CbC�C�CDCDoD�D�D�D2E�EF7FOFrF�F�F!GTGeGG�G�G�GHFHnHWIeI�I�I�I�I�IJGJ�J�J�K�K�KLCL�L�L�L M M2MBMSMoM�M�MNN1NKNkN�NOSOhO�O�O�O�OP'P8PNPlP|P�P�P�PQQ6Q�Q�Q�Q�Q�QR&RDR�R�R.S�TUGU�U�U�U�U;V\VsV�V�V.WtW�W XTX�X�XYMY}Y�Y�Y�YZ1ZCZ�Z�Z�Z�Z([[�[�[�[�[�\]:]f]�]�]�]�]"^�^�^�^_V_�_�_�_�_`'`L``�`�`�`�`a7a�a�a bPb�b�bccsc�cdYd�d�de@e�e�e�e1fhf�f g3gzg�g hdh�h�h�h�h6i�i�iHj�j�jk 2) and ((offset of "@" in aNoteAuthor) > fOff) and (lOff > (offset of "@" in aNoteAuthor)) then -- if Author field contains something plus an email addressset lOff to offset of ">" in aNoteAuthor -- and end charset fOff to offset of "<" in aNoteAuthor -- get position of email start charset aNoteAuthor to author of noteAttrs -- get author from meta dataset aNoteTitle to nname of noteAttrs -- get note title from meta dataset noteAttrs to getMeta2(noteHTMLfile) -- get Meta tags from the note html file 0.3.5repeat with noteHTMLfile in listNoteFiles -- examine each note in the current notebookset priorEnviron to item 2 of yy -- remember previous environment commentset expStamp to getDateSrch(item 1 of yy) -- get export date from previous index fileset priorExportDate to item 1 of yy -- remember export date as stringif length of (item 1 of yy) > 0 thenset yy to readIndex(POSIX file (outHTML & nbIndexFile), {"", " -->"}, 500) -- Get export date and environment comment from old index.htmlif not wasExported then -- if it wasn't just exported ...set priorExportDate to "" -- assume no prior export dateset priorEnviron to "" -- assume no prior "environment" comment existsset expStamp to current date -- assume this notebook was actually just exportedif (count of listNoteFiles) = 0 then return -- if no files, return 0.3.5return -- if no files found, return without building the notebook indextell application "System Events" to set listNoteFiles to ((every file of yy) whose (((kind is "HTML text") or (kind is "HTML document")) and (name ≠ nbIndexFile))) -- get every note html file 0.5.0set yy to alias (outHTML as POSIX file)set noteBookCell to " set yy to my repl(yy, ":", "%3A") -- handle filename with :set yy to my urlEncode(my repl(bookName, "/", "_")) & "/" & nbIndexFile -- index file for this notebookset bookFiles to 0 -- init count of attachmentsset bookNotes to 0 -- init count of notes in this notebookset tagRows to "" -- Building HTML for rows with Tag infoset htmlNotes to "" -- Building HTML for Notes listset bookCreate to initDate(2040, 1, 1) -- default book create date 0.4.2set bookMod to initDate(2000, 1, 1) -- default book mod date 0.4.2local ourTimer, bookNotes, bookFileslocal aNoteAuthor, aNoteExporter, fOff, lOff, sz, expStamp, priorEnviron, priorExportDatelocal aTageName, seenTag, parentCell, loopTag, spanTag, sNoteAttach, dirSizelocal aNoteMod, aNoteCreate, tagsComma, allTagNames, aNoteTagListlocal noteAttrs, noteHTMLfile, sNoteTitle, fileEnc, notelink, noteLinkFarlocal bookMod, bookCreate, htmlNotes, tagRows, yy, noteBookCell, pfile, listNoteFileson buildNoteIndex(bookName, outHTML, wasExported)end exportNotesreturn true -- return: aome notes exportedif oType = "HTML" then tell application "Evernote" to export selectedNotes to oFile format HTML -- or as HTMLif oType = "ENEX" then tell application "Evernote" to export selectedNotes to oFile format ENEX with tags -- export notes as enexif (count of selectedNotes) = 0 then return false -- If no notes to export, return empty listif logProgress then log oType & " note count for: " & bName & " is: " & (count of selectedNotes) & " with quoted notebook name"copy m to end of selectedNotes -- copy it to the result listif m is w then -- if note is in both listsset w to item j of b -- get note from search resultsrepeat with j from 1 to length of b -- with every note in search str resultsset m to item i of c -- get the note from the notebookrepeat with i from 1 to (length of c) -- with every note in notebookset c to every note in notebook bName -- get all notes in notebookset selectedNotes to {} -- init list of notes to exportset b to find notes SearchString -- search all of evernote with user-specified searchset selectedNotes to every note in notebook bName -- if not, export every note in notebookif SearchString = "" then -- did user specify a search string?if cu = 0 then return false -- if no changed notes in notebook, don't export ittell application "Evernote" to set cu to count of (every note in notebook bName whose modification date ≥ d) -- get count of updated notes in this notebookif logProgress then log "enexp: " & enexp & " local: " & dset d to d + offsetGMT -- adjust GMT export-date to local timetell d to set {its year, its month, its day, its time} to {0 + (text 1 thru 4 of enexp), 0 + (text 5 thru 6 of enexp), 0 + (text 7 thru 8 of enexp), (hours * (0 + (text 10 thru 11 of enexp))) + (minutes * (0 + (text 12 thru 13 of enexp))) + (0 + (text 14 thru 15 of enexp))} -- convert date string into type dateset d to current date -- init date objectif enexp ≠ "" then -- if only updated noteselse -- there is a " in the notebook name - no search allowedtell application "Evernote" to set selectedNotes to find notes srch -- get list of notes to exportif (count of someNotes) = 0 then return false -- If no new notes, don't export this notebookif logProgress then log oType & " note count for: " & bName & " is: " & (count of someNotes) & " with search: " & srch & datesrchtell application "Evernote" to set someNotes to find notes srch & datesrch -- any updated notes?set srch to "notebook:\"" & bName & "\" " & SearchString -- Build basic search string for EXPORTif (offset of "\"" in bName) = 0 then -- if normal notebook name (no " in it)if (length of enexp) > 0 then set datesrch to " updated:" & enexp -- Set export date clause for search stringif oType = "HTML" then set enexp to item 1 of readIndex(POSIX file (oFile & nbIndexFile), {""}, 500) -- get export from HTML commentif oType = "ENEX" then set enexp to item 1 of readIndex(POSIX file oFile, {" 0, "Some notebooks exported", "No notebooks exported") message ((countBooksAttempted as text) & " Notebooks consideredset timerAll to getFineTime() - timerAll -- elapsed seconds for runset progress total steps to 0 -- shut down the progress displayif (countENEXdone > 0) or (countHTMLdone > 0) then set x to managePlist(3) -- Update the Property List file with new Export Dateif (countHTMLdone > 0) or (not gotIndex) or alwaysBuildTopIndex then buildTopIndex() -- rebuild top index if missing or outdatedtell application "Finder" to set gotIndex to (exists (FolderHTML & myTopIndex)) -- does top index exist ?set progress completed steps to pcounter -- and ask Applescript to display itset pcounter to pcounter + 1 -- increment the progress display counterif expSome or alwaysBuildBookIndexes then buildNoteIndex(aBook, outHTML, expSome) -- build the index.html file for this notebookif expSome then set countHTMLdone to countHTMLdone + 1 -- count successful exportsset expSome to exportNotes(aBook, outHTML, "HTML") -- Try to export notebookset outHTML to (POSIX path of FolderHTML) & my repl(aBook, "/", "_") & "/" -- build HTML export folder pathset countHTMLtried to countHTMLtried + 1 -- count attemptsset progress additional description to "Exporting " & aBook & " as HTML" -- set progress display detailif ExportAsHTML then -- if HTML export was requestedif exportNotes(aBook, (POSIX path of FolderENEX) & my repl(aBook, "/", "_") & ".enex", "ENEX") then set countENEXdone to countENEXdone + 1 -- export as ENEX anc count successesset countENEXtried to countENEXtried + 1 -- count attemptsset progress additional description to "Exporting " & aBook & " as ENEX" -- set progress display detailif ExportAsENEX then -- if ENEX export was requestedrepeat with aBook in exportBooks -- repeat with each notebook nameset pcounter to 0set progress description to "Exporting notebooks"set progress total steps to (length of exportBooks) -- set up progress displayset ExportDate to current date -- Set date of main index rebuildset countBooksAttempted to length of exportBooks -- count of notebooks being attemptedset countHTMLdone to 0 -- init count of completed HTML exportsset countENEXdone to 0 -- init count of completed ENEX exportsset countHTMLtried to 0 -- init count of attempted HTML exportsset countENEXtried to 0 -- init count of attempted ENEX exportswith timeout of (TimeoutMinutes * 60) seconds -- run this code with a timeoutif not checkRunVol(FolderHTML, "HTML") then return -- check volume and folder; quit if not foundif ExportAsHTML thenif not checkRunVol(FolderENEX, "ENEX") then return -- check volume and folder; quit if not foundif ExportAsENEX thenif AllNotebooks then set exportBooks to getBooks() -- get sorted list of all notebooksset exportBooks to BooksSelected -- assume a user-selected listset timerAll to getFineTime() -- get time at start ot runif ("Export Now" = (button returned of (display dialog msg buttons {"Export now", "Change settings", "Cancel"} default button 1 cancel button 3 with title "Ready to Export" with icon note))) then exit repeatStart export now or change settings."" & SearchString, "All notes will be exported in each notebook") & "" & cond(length of SearchString > 0, "Only notes meeting this criteria will be exported:ENEX: " & cond(ExportAsENEX, POSIX path of FolderENEX, "(not to be exported)") & "HTML: " & cond(ExportAsHTML, POSIX path of FolderHTML, "(not to be exported)") & "set msg to "Will consider " & cond(AllNotebooks, "all notebooks", ("only " & (count of BooksSelected) & " selected notebooks")) & " for export toset plistPrompt to true -- If we loop in the repeat, let user update PListdelay 1 -- give it a secondif not managePlist(2) then return -- update PList; quit if user cancelsif plistPrompt then -- If PList is new or it's a second pass through this looprepeat -- Until user clicks Export Now or Cancelset plistPrompt to not managePlist(1) -- Get PList values (returns false if the PList file did not exist)activate frontProcess -- Switch back to our app so user sees the promptsdelay 5 -- give it a few seconds to crank upactivate application "Evernote" -- start evernote if not already runningif application "Evernote" is not running thenif logProgress then log "frontProcess: " & frontProcesstell application "System Events" to set frontProcess to the name of every process whose frontmost is true -- get our process nameset TimeoutMinutes to 30 -- Default timeoutset ExportDate to initDate(2000, 1, 1) -- No exports have been done yet 0.4.2set BooksSelected to {} -- List of notebooks to exportset ExportAsENEX to true -- Export notebooks in ENEX formatset ExportAsHTML to true -- Export notebooks in HTML formatset SearchString to "" -- assume no user-supplied search stringset AllNotebooks to true -- export all notebooks, not just someset FolderENEX to path to documents folder as text -- Path for ENEX exportsset FolderHTML to path to documents folder as text -- Path for HTML exportsset plExportTypeDesc to {"Export only in HTML format", "Export only in ENEX format", "Export in both HTML and ENEX formats"}if logProgress then log "Property List file: " & myPListFullPathset timerSub1 to 0set timerAll to 0global timerAll, timerSub1set nbIndexFile to "index.html" -- name of the notebook index page listing all notesset myTopIndex to "index.html" -- name of the top-level index page listing all notebooksset myTagFile to "entags.html" -- master tag list file for html export folderset myJSfile to "enscripts.js" -- JS file name for html export folderset myCSSfile to "enstyles.css" -- CSS file name for html export folderglobal frontProcess -- name of our processglobal ExportAsHTML, ExportAsENEX, TimeoutMinutes, BooksSelected, ExportDate -- Propertiesglobal FolderHTML, FolderENEX, AllNotebooks, SearchString -- Propertiesglobal nbIndexFile -- filename for notebook index pagesglobal myCSSfile, myJSfile, myTagFile, myTopIndex -- file names for top-level folderglobal plExportTypeDesc -- Descriptions for optionsset headerInfo to "" -- initially emptyglobal headerInfo -- system info to store as comment in index pagesset offsetGMT to time to GMT -- get offset to GMT in secondsglobal offsetGMT -- offset to GMT in secondsset parentTagHTML to {} -- corresponding list of parent tag HTMLset parentTagNames to {} -- list of tag names already looked upglobal parentTagNames, parentTagHTML -- cache of tag namesset myPListFullPath to POSIX path of ((path to preferences as text) & "com.lake91.nem.plist") -- Folder for preferencesglobal myPListFullPath -- PList full path + file nameset alwaysBuildBookIndexes to false -- force rebuild of notebook indexes USER SETTINGglobal alwaysBuildBookIndexesset alwaysBuildTopIndex to true -- force rebuild of top-level index USER SETTINGglobal alwaysBuildTopIndexset logProgress to false -- run Log commands for debugging USER SETTINGglobal logProgress -- switch to control Log statements for debuggingdisplay notification (the clipboard) with title "Clipboard Set"set the clipboard to "\"" & my encodePosixtoHFS(thePath) & "\" as alias"tell application "Finder" to set thePath to POSIX path of (selection as alias)set name of disk ORIG to theNameset ORIG to "Catalina HD"set theName to "Catalina-HD"if exists disk "Catalina HD" thenend list2stringset AppleScript's text item delimiters to theBackupset theBackup to AppleScript's text item delimiterson list2string(theList, theDelimiter)close access myFilewrite theBody to myFileset myFile to open for access (choose file name) with write permissionset the clipboard to theBodydisplay dialog theBodyset theBody to list2string(reminderCompleted, "set reminderCompleted to name of reminders whose completed is truedisplay dialog ("File could not be deleted") buttons {"OK"}delete currentFileif answer is equal to "Yes" thenset question to display dialog "Do you want to delete" & (POSIX path of currentFile) buttons {"Yes", "No", "Cancel"} default button 2repeat with currentFile in appexFilesset end of appexFiles to POSIX file (item i of thePrgs)repeat with i from 1 to count of thePrgsset appexFiles to {}set thePrgs to paragraphs of theListif button returned of result = "Cancel" then" & theList) buttons {"Select appex files", "Cancel"}display dialog ("The following .appex files were found:set theList to (do shell script "find /Applications -maxdepth 5 -type d -name '*.appex' | grep -Evw '(Books|Calendar|FaceTime|Home|iTunes|Mail|Messages|Notes|Photos|Reminders|Safari|VoiceMemos|Xcode).app' ")end logitdo shell script "echo \"" & log_string & "\" >> $HOME/Library/Logs/" & log_file & ".log"to logit(log_string)end loginitdo shell script "echo \"" & log_string & "\" > $HOME/Library/Logs/" & log_file & ".log"set editor_path to "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"set log_file to "TestDrive"to loginit(log_string)if not remindersOpen then quitdelete (every reminder whose completion date is less than monthAgo)tell list thisListrepeat with thisList in myListsset myLists to name of every listset monthAgo to (current date) - (30 * days)set remindersOpen to application "Reminders" is runningget the clipboardset the clipboard to name of i & ", " & URL of iset the bounds of the first window to {0, 0, 1024, 768}set theCopy to create formatted note from theURL name theName in (item 1 of theParents)return textFieldif backgroundColor is not missing value then textField's setBackgroundColor:backgroundColorif textColor is not missing value then textField's setTextColor:textColorif textFont is not missing value then textField's setFont:textFontif placeholder is not missing value then textField's setPlaceholderString:placeholderif bordered is not missing value then textField's setBordered:borderedif selectable is not missing value then textField's setSelectable:selectableif editable is not missing value then textField's setEditable:editabletextField's setFrame:{origin, dimensions}textField's sizeToFit()textField's setFrameOrigin:originif dimensions is in {{}, false, missing value} then -- size to fittextField's setBezelStyle:bezelStyle -- 0, 1, or enumtextField's setBezeled:trueif bezelStyle is not missing value thenset textField to theClass's textFieldWithString:stringValueset textField to theClass's labelWithString:stringValueif label is true thento makeTextField at origin given dimensions:dimensions : {100, 22}, stringValue:stringValue : missing value, label:label : false, secure:secure : false, editable:editable : missing value, selectable:selectable : missing value, bordered:bordered : missing value, bezelStyle:bezelStyle : missing value, placeholder:placeholder : missing value, textFont:textFont : missing value, textColor:textColor : missing value, backgroundColor:backgroundColor : missing valuedisplay notification "Music is " & (player state as text)set properties of text object in myTextLayer to {contents:"I'm some text", size:48, font:"Ariel"}set myTextLayer to make new art layer in myDoc with properties {kind:text layer}set myDoc to make new documentend addTextToEndOfDocinsert text postBody at end of text object of active documenton addTextToEndOfDoc(postBody)end addTextToFrontOfDocend tell --progend tell -- docinsert text preBody & return at beginning of text object of active documenton addTextToFrontOfDoc(preBody)end closeWordDocByNameclose document docName saving noclose document docName saving yesif savingBOOL is true thenon closeWordDocByName(docName, savingBOOL)end duplicateDocreturn name of active documentpaste object selectionon duplicateDoc()end saveWordDocsave as active document file name inputPathALon saveWordDoc(inputPathAL)end openInTeXShopset content of selection of thisDoc to (the clipboard)set thisDoc to the front documentcopy object selectionif selection type of selection is selection normal thenset myRange to create range start (start of content of text object of paragraph 1) end (end of content of text object of paragraph paraCount)set paraCount to count of paragraphsget RTF in clipboard of settingsget properties of settingson openInTeXShop()end GetParagraphreturn paragraphNumset paragraphNum to (count paragraphs in myRange)set myRange to create range myDoc start 0 end (start of content of text object of selection)set myDoc to active documenton GetParagraph()end texifyTablesend if -- if tableend if --tables existend repeat --table loopset content of selection to "\\tabucline[.1mm,black]1"insert rows selection position above number of rows 1select text object of (get cell from table thisTable row (2) column 1)set content of myRange to postTableContent & return & origContent\\end{table}"\\end{tabu}}set postTableContent to "\\tabucline[.4mm,black]1set myRange to create range active document start (start of content of content of text object of paragraph postParaNum of active document) end ((end of content of content of text object of paragraph postParaNum of active document))set postParaNum to (GetParagraph() of me) + 1 + 1 + 1select text object of (get cell from table thisTable row rowCount column columnCount)set content of myRange to origContent & return & preTableContent\\tabucline[.4mm,black]1"{\\extrarowsep=1mm \\begin{tabu}{" & colString & "}\\centering\\begin{table}set preTableContent to "set origContent to content of myRangeselect myRangeset myRange to create range active document start (start of content of content of text object of paragraph preParaNum of active document) end ((end of content of content of text object of paragraph preParaNum of active document) - 1)set preParaNum to (GetParagraph() of me)select text object of (get cell from table thisTable row 1 column 1)set colString to colList as stringset end of colList to "X[m]"set end of colList to "X[l]"if (count of colList) is less than 1 thenrepeat (columnCount) timesset colList to {}set thisTable to table tableStep of active documentrepeat with tableStep from 1 to count of tables of active documentif (count of tables of active document) is greater than 0 thenget content of text object of paragraph selParaset selPara to GetParagraph() of meend repeat -- table loopset columnIncr to columnIncr + 1set content of text object of (get cell from table thisTable row rowIncr column columnIncr) to cellContent & " &"set content of text object of (get cell from table thisTable row rowIncr column columnIncr) to cellContent & " \\\\"if last character of (cellContent) is not "\\" thenif columnIncr = columnCount thenif last character of (cellContent) is not "&" thenif (count of characters of cellContent) is greater than 0 thenset cellContent to item 1 of cellcontentListset AppleScript's text item delimiters to orig_delimsset cellItems to items of cellcontentListset cellcontentList to text items of cellContentset AppleScript's text item delimiters to ASCII character 13 -- (a carriage return)set orig_delims to AppleScript's text item delimitersset cellcontentList to {}set cellContent to (get content of text object of (get cell from table thisTable row rowIncr column columnIncr))repeat with columnIncr from 1 to columnCount --(get cells of row rowIncr of thisTable)set rowList to {}repeat with columnIncr from 1 to columnCountrepeat with rowIncr from 1 to rowCountset columnCount to number of columns of thisTableset rowCount to number of rows of thisTableset rowCount to (count of rows of text object of thisTable)set cellCount to (count of cells of text object of thisTable)set thisTable to table tableNum of active documentrepeat with tableNum from 1 to tableCountif tableCount is greater than or equal to 1 thenset tableCount to (count of tables of active document)on texifyTables()end texifyListsset style of paragraph format of selection to myStyleselect text object of paragraph paraStep of active documentset content of text object of paragraph paraStep of active document to tab & paraContentset myStyle to Word style "Normal" of active document -- replace "Normal" with name of your style in quotationsif styleName is "List Paragraph" thenset paraContent to content of text object of paragraph paraStep of active documentlog "Paragraph: " & paraStepset myInsert to insert text "\\end{enumerate}" & return at first word of paragraph (paraStep + 1) of active documentinsert text return & "\\end{enumerate}" at last word of paragraph (paraStep) of active documentinsert text "\\begin{enumerate}" & return at first word of paragraph (paraStep + 1) of active documentif list type of list format of text object of paragraph (paraStep + 1) of active document is list simple numbering theninsert text return & "\\begin{enumerate}" at the last word of paragraph (paraStep - 1) of active documentif list type of listFormatProps is list simple numbering thenlog "Reached end of document checking for list at paragraph nr. " & paraStepinsert text return & "\\end{itemize}" at last word of paragraph (paraStep) of active documentset lastItem to trueif list type of list format of text object of paragraph (paraStep + 1) of active document is list no numbering theninsert text "\\end{itemize}" & return at first word of paragraph (paraStep + 1) of active documentif list level number of list format of text object of paragraph (paraStep + 1) of active document is 1 thenif list level number of list format of text object of paragraph (paraStep) of active document is 2 theninsert text return & "\\begin{itemize}" at last word of paragraph (paraStep) of active documentif list level number of list format of text object of paragraph (paraStep + 1) of active document is 2 thenif list type of list format of text object of paragraph (paraStep + 1) of active document is list bullet thenset paraStep to paraStep + 1set paraCompensator to paraCompensator + 1insert text return & "\\begin{itemize}" at the last word of paragraph (paraStep - 1) of active documentif list type of list format of text object of paragraph (paraStep - 1) of active document is list no numbering theninsert text "\\item " at first word of paragraph paraStep of active documentif content of text object of paragraph paraStep of active document does not contain "\\item" thenif list type of listFormatProps is list bullet thenget list type of listFormatPropsif styleName is "List paragraph" thenset styleName to name local of style of text object of paragraph paraStep of active documentset listFormatProps to properties of list format of text object of paragraph paraStep of active documentset paraStep to paraStep + paraCompensatorrepeat with paraStep from 1 to count of paragraphs of active documentset paraCompensator to 0on texifyLists()set content of replacement of myFind to replacementText --\\emph{^&}set content of myFind to textToFindon findReplace(textToFind, replacementText)end texifyBoldItalicsQuotesset auto format as you type replace quotes of settings to wasSmartQuotesset content of replacement of myFind to "\\begin{quotation}^&\\end{quotation}"set style of myFind to "quotation"set style of replacement of myFind to "Bold Tagged"set bold of font object of replacement of myFind to falseset content of replacement of myFind to "\\textbf{^&}"set bold of font object of myFind to trueexecute find myFind replace replace allset style of replacement of myFind to "Italic Tagged"set italic of font object of replacement of myFind to falseset content of replacement of myFind to "\\emph{^&}"clear formatting replacement of myFindset content of myFind to ""set italic of font object of myFind to trueset style of myFind to "Normal"set wrap of myFind to find continueset forward of myFind to trueclear formatting of myFindexecute find find text "_" replace with "\\_" replace replace allexecute find find text "&" replace with "\\&" replace replace allclear formatting myFindtell myFindset myFind to find object of selectionset auto format as you type replace quotes of settings to curlyset wasSmartQuotes to auto format as you type replace quotes of settingsset curly to false -- change to true if curly quotes desiredset italic of font object of italic_Style to true{name local:"Italic Tagged", style type:style type character}set italic_Style to make new Word style at active document with properties ¬if stylesList does not contain "Italic Tagged" thenif stylesList does not contain "Bold Tagged" thenset stylesList to (get name local of Word styles of active document)on texifyBoldItalicsQuotes()end texifyWordset content of word word_num to newContent --("\\" & tex_style & "{" & word_content & "}")set style of word word_num to "Bold Tagged"set newContent to "\\" & tex_style & "{" & word_content & "}"set word_content to content of wordOnlyend ((end of content of wordRange) - 1)set wordOnly to set range wordRange start ((start of content of wordRange)) ¬if last character of (word_content as string) is (ASCII character 32) thenset wordRange to word word_numset bold of font object of bold_Style to true{name local:"Bold Tagged", style type:style type character}set bold_Style to make new Word style at active document with properties ¬on texifyWord(word_content, tex_style, word_num)end texifyHeadingset style of paragraph para_num to word_styleset content of text object of paragraph para_num to returnTextset returnText to "\\" & tex_style & "{" & para_Content & "}"set returnText to "\\" & tex_style & "{" & sedFix & "}" & "if last character of (para_Content as string) is (ASCII character 13) then')\\$//\""set sedFix to do shell script "echo " & para_Content & "| sed \"s/$(printf 'on texifyHeading(para_Content, word_style, tex_style, para_num)addTextToEndOfDoc(postBody)addTextToFrontOfDoc(preBody)\\end{document}"set postBody to "\\begin{document}\\usepackage{tabu}\\usepackage{fontspec}\\documentclass[10pt]{article}set preBody to "my texifyTables()my texifyLists()my findReplace("%", "\\%")my findReplace("_", "\\_")my findReplace("$", "\\$")my findReplace("&", "\\&")my texifyBoldItalicsQuotes()my texifyHeading(paraContent, wordTag, texTag, paraStep)if Word style paraStyle is Word style wordTag thentry --if (paraContent as string) does not contain "{" then set {wordTag, texTag} to {item 1 of item itemStep of sectionTags, item 2 of item itemStep of sectionTags}repeat with itemStep from 1 to (count of sectionTags)set paraContent to (get content of text object of paragraph paraStep)set paraStyle to (get style of paragraph paraStep)repeat with paraStep from 1 to paraCountset {xpath, xname, xext, xbodytext, paraCount, wordCount} to {(get default file path file path type documents path), name, (get name extension), (get contents of text object), get count of paragraphs, get count of words}set end of sectionStyles to item 1 of item itemStep of sectionTagsrepeat with itemStep from 1 to count of sectionTagsset sectionStyles to {}set stylesList to (get name local of Word styles)global stylesListset inlineTags to {{"Paragraph", "paragraph"}}set sectionTags to {{"Title", "title"}, {"Heading 1", "section"}, {"Heading 2", "subsection"}, {"Heading 3", "subsubsection"}}if (count of documents) is greater than or equal to 1 thenset myDup to my duplicateDoc()open_file_with_editor(postdir, filename, editor)write_post_file(postdir, filename, iso_datetime)create_post_file(postdir, filename)set filename to {iso_date & "-" & slug & ".md"} as textset iso_datetime to date_time_to_iso(dt, timezone)set iso_date to date_to_iso(dt)set slug to text returned of resultdisplay dialog "Input post slug :" default answer ""end open_file_with_editordo shell script {"'" & editor & "' '" & filepath_std & "'"} as textset filepath_std to replaceText(replaceText(filepath, ":", "/"), "Macintosh HD", "")on open_file_with_editor(postdir, filename, editor)end write_post_fileclose access fnwrite input_text to fnset eof of fn to 0set fn to open for access file filepath with write permissionset input_text to {"--- title: layout: post date: " & iso_datetime & " categories: [] tags: [] --- "} as textset filepath to {postdir & ":" & filename} as texton write_post_file(postdir, filename, iso_datetime)end create_post_filetell application "Finder" to make new file with properties {name:filename} at alias postdiron create_post_file(postdir, filename)end date_time_to_isoreturn y & "-" & m & "-" & d & "T" & h & ":" & min & ":" & s & timezoneon date_time_to_iso(dt, timezone)end date_to_isoset {year:y, month:m, day:d} to dton date_to_iso(dt)set dt to (current date)set editor to "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl"set postdir to "Macintosh HD:Users:kerotaa:Sites:kerotaa.github.com:_posts"set timezone to "+09:00"end areModifiersPressedreturn flags = modifierSumset modifierSum to modifierSum + modifiererror "areModifiersPressed(): Unknown modifier name: " & modifierNameset modifierName to modifierName as textrepeat with modifierName in modifiersListset modifierSum to 0set modifiersList to {modifiersList}if class of modifiersList is text thenon areModifiersPressed(modifiersList)say (keyCombo as text)if areModifiersPressed(keyCombo) thenrepeat with keyCombo in keyCombinationsset keyCombinations to {{"CapsLock", "Shift"}, {"Control"}, {"Option", "Command"}, {"Function"}}do script "npm start" in front windowdo script "cd /Users/daniel/Developer/main-projects/social-media/social-backend/" in front windowdo script "mongodump" in front windowdo script "cd " & myFoldername in front windowdo script "mkdir " & myFoldername in front windowdo script "cd /Users/daniel/Developer/mongo_backups" in front windowset myFoldername to "" & m & "_" & d & "_" & ydo script "docker start mongodb" in front windowopen "/Users/daniel/Developer/main-projects/social-media/social-frontend-plain/html"open "/Users/daniel/Developer/main-projects/social-media"tell application "Docker"open location item 1 of argvdo shell script "open -a Firefox " & (item 1 of argv)if (firefoxRunning() = false) thenend firefoxRunningtell application "System Events" to (name of processes) contains "firefox"on firefoxRunning(){(1st item of the result), (2nd item of the result), (3rd item of the result), (4th item of the result)}tell application "Google Chrome" to set the bounds of the front window to ¬tell application "Finder" to get the bounds of the window of the desktoptell application "Safari" to get URL of current tab of first windowtell application "Google Chrome" to get URL of active tab of first windowdo shell script "LANG=en_US.UTF-8 pbpaste -Prefer txt | /usr/local/bin/pandoc -f markdown-smart -t html | /usr/bin/textutil -inputencoding utf-8 -stdin -stdout -format html -convert rtf | /usr/bin/sed 's/fcharset0 Times-Roman/fcharset0 Arial/' | pbcopy ; osascript -l AppleScript -e 'tell application \"System Events\" to keystroke \"v\" using command down'"set master of slide 1 to master slide "Title & Bullets"tell slideshow 1tell application "Finder" to open folder the_folderset the_folder to POSIX file the_folderset the_folder to the_path & todays_folderif (bring_to_front is true) thenif (open_folder is true) thendo shell script touch_file_cmdset touch_file_cmd to "/usr/bin/touch " & quoted form of (the_path & todays_folder & "/" & item_name)if (touch_file is true) thendo shell script move_file_cmdset move_file_cmd to "/bin/test -d " & quoted form of (the_path & todays_folder) & " && /bin/mv -n " & quoted form of (the_path & item_name) & " " & quoted form of (the_path & todays_folder) & "/"do shell script make_folder_cmdset make_folder_cmd to "/bin/test -d " & quoted form of (the_path & todays_folder) & " || /bin/mkdir " & quoted form of (the_path & todays_folder)if (item_name is not equal to todays_folder) thenset item_name to the name of (info for this_item)display dialog item_kind & " or " & item_suffix & " is being ignored"if (item_kind is in ignore_kinds) or (item_suffix is in ignore_suffix) thenset item_suffix to getSuffix(this_item as text)set item_kind to the kind of (info for this_item) as stringset this_item to item i of added_itemsrepeat with i from 1 to number of items in added_itemsset todays_folder to do shell script of date_cmdset date_cmd to "date '" & date_fmt & "'"end getSuffixreturn theSuffixset theSuffix to last text item of myFileif myFile contains "." thentell application "Finder" to set myFile to name of myFileon getSuffix(myFile)end set_organized_folderset organized_folder to (choose folder)on set_organized_folder()tell application "Finder" to move the_files to organized_folderset_organized_folder()if (organized_folder is equal to "") thenon open of the_filesset touch_file to trueset touch_file to falseif the button returned of the result is "Don't Change Modification Date" thendisplay dialog "Do ya wanna to set the modification date to the time you downloaded these items?" buttons {"Change Modification Date", "Don't Change Modification Date"} default button 2set bring_to_front to trueset bring_to_front to falseif the button returned of the result is "Don't Activate" thendisplay dialog "Wanna make the Finder active when new items are added?" buttons {"Don't Activate", "Activate"} default button 2set open_folder to trueset open_folder to falseif the button returned of the result is "Don't Show" thendisplay dialog "Wanna show the folder when you're downloading new stuff?" buttons {"Don't Show", "Show"} default button 2property date_fmt : "+%Y-%m-%d" --property ignore_suffix : {"nzb", "torent"}property ignore_kinds : {"Safari download", "Finder Document"}property organized_folder : ""property bring_to_front : trueproperty time_fmt : 1property touch_file : falseproperty open_folder : trueselect current document variants nextVariantsdeselect current document variants currentVariantscopy nextVariant to the end of the |nextVariants|set nextVariant to variant after vrepeat with v in currentVariantsset nextVariants to {}select current document variant (first variant)if (count of currentVariants) is 0 thenset currentVariants to variants whose selected is trueuse application "Capture One 20"end RBG_to_HEXreturn (the hex_value)on RBG_to_HEX(RGB_values)display dialog "HEX colour value (" & formatedColor & ") has been copied to the clipboard." with icon 1 buttons {"Dismiss"} default button {"Dismiss"} giving up after 10set the clipboard to formatedColorset the formatedColor to my RBG_to_HEX(RGB16bit_list)set the RGB16bit_list to (choose color)make new action with properties {xml:" DisplayKind None HonourFailureSettings IncludeStdErr MacroActionType ExecuteAppleScript Path Text tell application \"Mail\" set selMessage to selection set thisMessage to item 1 of selMessage set mailbox of thisMessage to mailbox \"" & theMailbox & "\" of account \"" & theAccount & "\" display notification with title \"Message Moved to " & theAccount & " " & theMailbox & "\" end tell TimeOutAbortsMacro TrimResults TrimResultsNew UseText "}make new trigger with properties {xml:theXMLfortheTrigger}tell theMacroset theMacro to make new macro with properties {name:theMacroName}tell theMacroGroupset theMacroGroup to make new macro group with properties {name:theMacroGroupName, available application xml:" Targeting Included TargetingApps BundleIdentifier com.apple.mail Name Mail NewFile /System/Applications/Mail.app "}set theMacroGroup to macro group theMacroGroupNameif macro group theMacroGroupName exists thenset theMacroName to "Move to " & theAccount & " - " & theMailboxset theAccount to (name of eachAccount)set theMailbox to theMailboxrepeat with theMailbox in selectedMailboxesif (count of selectedMailboxes) > 0 thenset selectedMailboxes to choose from list theList with title ("Pick the desired mailboxes from " & accountName) with multiple selections allowedset the end of theList to (name of eachMailbox)repeat with eachMailbox in accountMailboxesset accountName to name of eachAccountrepeat with eachAccount in accountListset accountList to every account"4096ModifiersHotKeyMacroTriggerType46KeyCodePressedFireTypeset theXMLfortheTrigger to "set theMacroGroupName to "Mail Moves"set returnValue to ":mic.slash.fill:"set returnValue to ":mic.fill: | sfcolor=red"rotate this_file to angle 270do script "cd " & go2shellset go2shell to quoted form of go2shellset go2shell to do shell script "echo " & go2shell & " | sed -e 's/" & rmfile & "//g'"set rmfile to do shell script "basename " & go2shellif go2shell contains "." thenset go2shell to quoted form of POSIX path of go2shellset go2shell to selection as textend check_if_highestif the_item_ref as number > the_top then return falserepeat with the_item_ref in the_listto check_if_highest out of the_list above the_topmake new event with properties {summary:theSummary, start date:startDate, end date:endDate, allday event:true}set endDate to item 3 of aDataset startDate to item 2 of aDataset theSummary to item 1 of aDatarepeat with aData in theEvents6tell calendar "New York Elections"create calendar with name "New York Elections"if not (exists (calendar "New York Elections")) thenset end of theSummaryList to theSummaryset end of theEvents6 to theEventif theSummaryList does not contain theSummary thenset theSummary to item 1 of theEventset theEvent to item i of theEvents5repeat with i from 1 to count of items in theEvents5set theSummaryList to {}set theEvents6 to {}set endDate to item 1 of theEventset startDate to item 1 of theEventset end of theEvents5 to {theSummary, date startDate, date endDate}set endDate to theDateset startDate to theDateset theDate to replace_chars(theDate, "t", "")else if theDate contains "Sept" thenset end of theEvents5 to {theSummary, date theDate, date theDate}set theDate to word 1 of theDate & space & theNumber & space & word 3 of theDateset theNumber to theNumber & aCharacterif aCharacter is not "h" thenif aCharacter is not "t" thenset aCharacter to item i of theCharactersrepeat with i from 1 to count of theCharactersset theCharacters to characters of theDayset theDay to second word of theDateset theNumber to ""else if theDate contains "th" thenset end of theEvents5 to {theSummary, startDate, endDate}set endDate to date endDateset endDate to item 1 of theDate & space & item 3 of theDate & space & item 4 of theDateset startDate to date startDateset startDate to item 1 of theDate & " " & item 2 of theDate & " " & item 4 of theDateset theDate to words of theDateif theDate contains "–" thenset theEvent to item i of theEvents4repeat with i from 1 to count of theEvents4set the theEvents5 to {}set end of theEvents4 to {item 1 of theEvent & " 2022", item 2 of theEvent}set theEvent to item i of theEvents3repeat with i from 1 to count of theEvents3set theEvents4 to {}set end of theEvents3 to theEventif item 1 of theEvent does not contain "January 18" thenif theEvent is not equal to nextEvent thenset nextEvent to item (i + 1) of theEvents2set theEvent to item i of theEvents2repeat with i from 1 to count of theEvents2set theEvents3 to {}set end of theEvents2 to {theDate, theSummary}if theDate is not equal to theSummary thenset theSummary to item 2 of theEventset theDate to item 1 of theEventrepeat with theEvent in theEventsset theEvents2 to {}set end of theEvents to {theCell, item (j + 1) of theTable}if theCell contains theMonth thenif (count of theCell) < 13 thenif theCell is not missing value thenset theCell to item j of theTablerepeat with j from 1 to count of theTableset theMonth to item i of theMonthsrepeat with i from 1 to count theMonthsset theTable to value of cellstell document chosenDocumentset chosenDocument to item 1 of chosenDocumentset chosenDocument to choose from list listOfDocumentsset listOfDocuments to name of documentsset theDates to {}set theTable to {}set theMonths to {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"}end fmGUI_ManageSecurity_PrivSet_Update_AccessLayouterror "unable to fmGUI_ManageSecurity_PrivSet_Update_AccessLayout - " & errMsg number errNumclick layoutNoAccesselse if layoutAccess of oneLayoutRec is equal to "no access" thenclick layoutViewelse if layoutAccess of oneLayoutRec is equal to "view only" thenclick layoutModifyif layoutAccess of oneLayoutRec is equal to "modifiable" thenif item 3 of oneLayoutInfo is not equal to layoutAccess of oneLayoutRec thenclick recordNoAccesselse if dataAccess of oneLayoutRec is equal to "no access" thenclick recordViewelse if dataAccess of oneLayoutRec is equal to "view only" thenclick recordModifyif dataAccess of oneLayoutRec is equal to "modifiable" thenif item 4 of oneLayoutInfo is not equal to dataAccess of oneLayoutRec thenset oneLayoutInfo to name of every static text of oneLayoutRowselect oneLayoutRowset oneLayoutRow to (first row of table 1 of scroll area 1 of window 1 whose name of static text 1 is layoutName of oneLayoutRec)set oneLayoutRec to contents of oneLayoutRecrepeat with oneLayoutRec in layoutPrivList of layoutAccess of prefsfmGUI_CheckboxSet({objRef:allowCreate, objValue:allowCreate of layoutAccess of prefs})set recordNoAccess to a reference to checkbox 7 of window 1set recordView to a reference to checkbox 6 of window 1set recordModify to a reference to checkbox 5 of window 1set layoutNoAccess to a reference to checkbox 4 of window 1set layoutView to a reference to checkbox 3 of window 1set layoutModify to a reference to checkbox 2 of window 1set allowCreate to checkbox "Allow creation of new layouts" of window 1windowWaitUntil_FrontIS({windowName:"Custom Layout Privileges"})if accessLayout of prefs begins with "Custom privileges" thenfmGUI_Popup_SelectByCommand({objRef:layoutsPopup, objValue:accessLayout of prefs, accessLayout:null, layoutAccess:null})set layoutsPopup to pop up button "Layouts:" of window 1set defaultPrefs to {accessLayout:null, layoutAccess:null}on fmGUI_ManageSecurity_PrivSet_Update_AccessLayout(prefs)fmGUI_ManageSecurity_PrivSet_Update_AccessLayout({accessLayout:"Custom privileges...", layoutAccess:{allowCreate:1, layoutPrivList:{{layoutName:"ZZ_GLOBALS Basic", layoutAccess:"modifiable", dataAccess:"modifiable"}, {layoutName:"[Any New Layout]", layoutAccess:"modifiable", dataAccess:"modifiable"}}}})return "On AC Power!"tell application "Dropbox"else if battStatus starts with "Now drawing from 'AC Power'" thendo shell script "killall Dropbox"if percentBatteryLeft < 95 thenset percentBatteryLeft to text item 2 of battStatusset AppleScript's text item delimiters to {tab, "%"}if battStatus starts with "Now drawing from 'Battery Power" thenset battStatus to do shell script "pmset -g ps"click button "Done" of sheet 1click menu item "60 Hertz" of menu 1tell thePopupset thePopup to item 3 of thePopupsset thePopups to pop up buttons of sheet 1sheet 1click theButtonset theButton to button "Display Settings…"tell window "Displays" of process "System Preferences"delay 1.0 -- wait for pane to load. May not be long enough.set current pane to pane id "com.apple.preference.displays"on replaceText(this_text, search_string, replacement_string)save document 1 in file filenameset filename to ((path to desktop from user domain) as string) & ":Desktop:notes.md"set text of document 1 to theFormattedNotestell application "MacDown"set theFormattedNotes to theFormattedNotes & item a of theNotes & return & returnset theFormattedNotes to theFormattedNotes & " (slide" & a & ")" & returnset theFormattedNotes to theFormattedNotes & ", " & item a of theTitlesset theFormattedNotes to theFormattedNotes & item a of theSlidenrsset theFormattedNotes to theFormattedNotes & "##"set theFormattedNotes to "#" & thePresentationName & return & returnset item a of theTitles to my replaceText(item a of theTitles, ASCII character 10, " ")set item a of theNotes to my replaceText(item a of theNotes, ASCII character 10, "repeat with a from 1 to length of theNotesset theNotes to presenter notes of every slideset theTitles to object text of text item 2 of every slideset theSlidenrs to object text of text item 1 of every slidedisplay alert "Unable to proceed." message "Please open a presentation in Keynote."if (front document exists) = false thenend getSourcedo shell script "curl " & the quoted form of the theURL & " | " & theCommandset theURL to URL of active tab of window 1 as stringon getSource()getSource()open location "bear://x-callback-url/change-theme?theme=Solarized%20Dark"set theme "Alfred macOS Dark"tell application "Alfred 3"set color preset to "Solarized Dark"repeat with theSession in sessions of theTabrepeat with theTab in tabs of theWindowrepeat with theWindow in windowsdo shell script "cp ~/etc/ST3_pref_dark.json ~/Library/Application\\ Support/Sublime\\ Text\\ 3/Packages/User/Preferences.sublime-settings"set value of preference id "OFIColorPaletteIdentifier" to "builtin:OmniFocus Dark"set dark mode to trueset the clipboard to the_htmlset the_html to encode entities the_stringset the_string to the clipboard as Unicode textend changeDesktopPicturedisplay dialog result & aFilePath"ファイルが見つかりません。" & return & returnset desktop picture to POSIX file (aFilePath)on changeDesktopPicture(aFilePath)delay sleepIntervalchangeDesktopPicture(item curIdx of hoge)repeat with curIdx from 1 to length of hogeset hoge to splitText(":", fileList)set fileList to item 2 of argvset sleepInterval to item 1 of argvdocument file "index.html" of folder "Sites" of homeend deleteItemsInNSArrayreturn deletedCountset deletedCount to deletedCount + 1move record toDelete to trash group of theDatabaseif toDelete is not missing value thenset toDelete to get record with id (recordId as integer) in theDatabaseset deletedCount to 0on deleteItemsInNSArray(theDatabase, theArray)end flagItemsInNSArrayreturn flaggedCountset flaggedCount to flaggedCount + 1set state of flaggedItem to trueif flaggedItem is not missing value thenset flaggedItem to get record with id (recordId as integer) in theDatabaserepeat with recordId in (theArray as list)set flaggedCount to 0on flagItemsInNSArray(theDatabase, theArray)end removeFromNSArrayarray's removeObject:(val as integer)on removeFromNSArray(val, array)end getGroupChildrenAsMutableArrayreturn knownGroups(knownGroups's addObject:id of theItem as integer)repeat with theItem in (children of theGroup)if theGroup is not missing value thenset knownGroups to (its NSMutableArray's alloc())'s init()on getGroupChildrenAsMutableArray(theDatabase, theGroup)end getZettel:return {zettelId:theFinalDate, zettelName:theFinalName}set theFinalName to (theFinalDate & " " & theName) as stringset theFinalDate to (script "zettel"'s zettelFromDate:(current date))set theFinalName to theNameset theFinalDate to (theString's substringWithRange:matchRange) as textset matchRange to (theMatch's rangeAtIndex:0) as recordset theMatch to matches's first itemif (count of matches) > 0 thenset matches to regex's matchesInString:theString options:0 range:{0, theString's |length|()}set regex to cA's NSRegularExpression's regularExpressionWithPattern:regexString options:(cA's NSRegularExpressionCaseInsensitive) |error|:(missing value)set theString to (cA's NSString's stringWithString:theName)set cA to current applicationon getZettel:theNameproperty regexString : "^[[:digit:]]{14}"set name_record to split_name("Paul Revere")return {forename:first_name, surname:last_name}set autoload of eachCue to falseset thePath to POSIX path of ((path to me as text) & ":")display dialog "The path to me is: " & thePathset thePath to POSIX path of (path to me as text)processItems(the_NextItems)if the_NextItems is not {} thentell application "Finder" to set the_NextItems to get every item of folder a_Folderrepeat with a_Folder in the_Foldersset locked of an_Item to falseif last character of (an_Item as text) is not ":" thenset end of the_Files to an_Item as aliasset end of the_Folders to an_Item as aliasif folder of (info for an_Item) thenrepeat with an_Item in the_Itemsset the_NextItems to {}set the_Folders to {}set the_Files to {}on processItems(the_Items)display dialog "This recursively unlocks files and folders dropped" giving up after 3processItems(the_Droppings)on open the_Droppingsend convertFromDecimalreturn targetValueset aValue to theDivset targetValue to rem & targetValue as textset targetValue to c & targetValue as textset c to ASCII character (65 + rem - 10)if rem is greater than 9 thenset rem to round (preliminaryDiv - theDiv) * targetBaseset theDiv to round preliminaryDiv rounding downset preliminaryDiv to aValue / targetBaserepeat until theDiv is 0set targetValue to ""set theDiv to 1if aValue is not "" thenif targetBase > 36 then error "Invalid target base." number 1on convertFromDecimal(aValue, targetBase)log convertFromDecimal(1024, 36) -- Highest possible baselog convertFromDecimal(18, 8) -- Octallog convertFromDecimal(255, 16) -- Hexlog convertFromDecimal(127, 2) -- Binaryreturn the_datadelete the_result_setset the_data to values of every row of the_result_setset the_result_set to do query query_text results as none with prefetching results set query_text to "SELECT first_name, last_name FROM contact_table"display alert "Unset URL" message msg as warningset URL of _record to ""repeat with _record in (selected records)set will autosave of front document to trueset timestamp to timestamp + (forward_time * 60)set forward_time to 15if forward_time is missing value thenset forward_time to estimated minutes of thisItemset due date of thisItem to timestampset timestamp to due date of firstTaskset firstTask to value of first item of selected treestell content of front document window of front documentset will autosave of front document to falseproperty defaultStartTime : 15 --default time to use (in hours, 24-hr clock)return the output -- pass the result(s) to the next actionset the end of SkippedItems to TheName -- just the nameon error -- permissions, etcset the end of output to (result as alias) -- the new file aliasmove AnItem to the resultmake new folder at TheContainer with properties {name:TheDate}on error -- make a new folderget ("" & TheContainer & TheDate) as aliastry -- check if the target folder existsset TheDate to text 1 thru 10 of (creation date of AnItem as «class isot» as string) -- YYYY-MM-DDif TheClass is document file then try -- just documentsset {class:TheClass, name:TheName, name extension:TheExtension, container:TheContainer} to item AnItemelse -- move to the source folderset {class:TheClass, name:TheName, name extension:TheExtension} to item AnItemif TheContainer is not missing value then -- move to the specified foldertell application "Finder" to repeat with AnItem in the input -- step through each item in the inputset TheContainer to (choose folder with prompt "Where do you want to move the items?")TheContainer as aliasif TheContainer is not missing value then try -- check the destination pathset TheContainer to "" -- a Finder path to a destination folder, or missing value for the source folderset SkippedItems to {} -- this will be a list of skipped items (errors)log "app stopped"set app_stopped to truedo shell script ("kill -STOP " & the_pid)if the_pid is not "" and app_stopped is false thendo shell script ("kill -CONT " & the_pid)if the_pid is not "" and app_stopped is true thenif name of a is equal to app_name and frontApp ends with "Firefox.app:" thenset frontApp to (path to frontmost application as Unicode text)set a to first process whose frontmost is truelog the_pidset app_stopped to falseset the_pid to (do shell script "ps ax | grep " & (quoted form of app_name_with_app) & " | grep -v grep | grep -v CrashReporter | grep -v applescript | awk '{print $1}'")set app_name_with_app to "Firefox.app"set app_name to "Firefox"end listFolder:returningAs:else if returnType = "name" thenelse if returnType = "path" thenif returnType = "furl" thenset {theURLs, theError} to NSFileManager's defaultManager()'s contentsOfDirectoryAtURL:targetDir includingPropertiesForKeys:{} options:(NSDirectoryEnumerationSkipsHiddenFiles) |error|:(reference)on listFolder:targetDir returningAs:returnType -- "furl", "path", "name"set itemNameList to my listFolder:targetDir returningAs:"name"set itemPathList to my listFolder:targetDir returningAs:"path"set itemFurlList to my listFolder:targetDir returningAs:"furl"set targetDir to path to downloads folderset the theResult to (the theResult & char) as stringset the theResult to (the theResult & character x of the destination) as stringset x to the offset of char in the sourcerepeat with char in cmdset the theResult to ""set cmd to reverse of characters of cmd as textset the destination to "ɐqɔpǝɟƃɥıɾʞlɯuodbɹsʇnʌʍxʎz()][}{¡¿˙'"set the source to "abcdefghijklmnopqrstuvwxyz)([]{}!?.,"end explodeerror "Can't explode: " & eMsg number eNumreturn input --> listset input to text items of inputlocal delimiter, input, ASTIDon explode(delimiter, input)set end of printNameAarry to printerSingleNameset printerSingleName to first word of theItemrepeat with theItem in printNameLoopset printNameAarry to {}set printNameLoop to every paragraph of the (do shell script "lpstat -a")write uniqueText to openFile starting at eof as textset eof of openFile to 0set openFile to open for access file filePath with write permissionset text item delimiters to tidsset uniqueText to uniqueList as textset {tids, text item delimiters} to {text item delimiters, return}if thisParagraph is not in uniqueList then set end of uniqueList to thisParagraphset thisParagraph to item i of textListset theText to read file filePathset filePath to (path to desktop as text) & serialNumber & ".txt"do shell script "echo " & returnLineValue & " >> ~/desktop/" & serialNumber & ".txt"set returnLineValue to theCurrentValue & tab & serialNumber & tabrepeat with theCurrentValue in printingListdo shell script "touch ~/desktop/" & serialNumber & ".txt"set printingItem to every item of printingList as stringset printingList to every paragraph of the (do shell script "lpstat -W completed")set returnLineValue to {}set serialNumber to do shell script "system_profiler SPHardwareDataType | awk '/Serial/ {print $4}'"global serialNumberglobal printingListglobal returnLineValuedisplay alert "Printer Names:" message "Printer Count: " & (count of printNameAarry) buttons printNameAarryif (ButtonReturn is equal to otherAction) thenopen location "http://localhost:631/jobs?which_jobs=all"do shell script "cupsctl WebInterface=yes"if (ButtonReturn is equal to checkPrinter) thenset ButtonReturn to button returned of the resultdisplay alert "Publish4All" message "What do you want to check!" buttons {otherAction, checkPrinter}set otherAction to "Show All Printers"set checkPrinter to "Printing History"global ButtonReturnset exclusions to {"Script Editor", "Sublime Text", "Finder", "iTerm2"}return toggleDevice(getFirstMatchingDevice(AirPodsName))end toggleDevicereturn "Disconnecting " & (device's nameOrAddress as string)device's closeConnection()return "Connecting " & (device's nameOrAddress as string)device's openConnection()if not (device's isConnected as boolean) thenon toggleDevice(device)end getFirstMatchingDeviceif (device's nameOrAddress as string) contains deviceName then return devicerepeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)on getFirstMatchingDevice(deviceName)set AirPodsName to "AirPods2"modifyKeysLib's modifyOptionAndCmdKeys("swap")end fmGUI_Menu_OpenDBerror "Couldn't fmGUI_Menu_OpenDB - " & errMsg number errNumreturn windowWaitUntil({windowName:"Manage Database for"})fmGUI_ClickMenuItem({menuItemRef:openManageDBMenuItem})set openManageDBMenuItem to first menu item of menu 1 of menu item "Manage" of menu 1 of menu bar item "File" of menu bar 1 whose name starts with "Database"on fmGUI_Menu_OpenDB(prefs)fmGUI_Menu_OpenDB({})set MyAction to make new task with properties {name:"Inserted the record into the database", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Updated mysql_setup.sql", context:pContext, start date:dateToday}set MyAction to make new task with properties {name:"Copied mobi to Kindle Contect", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Synced to iPad", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Copied pdf in iTunes", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Copied epub in iTunes", context:tContext, start date:dateToday}set MyAction to make new task with properties {name:"Sync With Dropbox", context:pContext, start date:dateToday}set MyProject1 to make new project with properties {name:ebookName, context:pContext} at end of project of myFolderset tContext to first flattened context where its name = "iMac"set pContext to first flattened context where its name = "Computer"set ebookName to (text returned of result)display dialog "Name of the ebook" default answer ""tell application "Spotify" to playif runningApp is not {} thenset runningApp to processes whose bundle identifier is "com.spotify.client"script SpotifyPlayPausekeystroke addressdelay 4.2log run script p # equivalent to: do shell script "osascript -e 'run script \"'/Users/super/Desktop/important/SystemFiles/menubarx-new-and-focus.applescript'\"'"set address to value of every text field of focusedWindowset focusedWindow to value of attribute "AXFocusedWindow"delay 0.666 # wait to get hands off modifier keysset pathStr to "Macintosh HD:users:super:Desktop:important:SystemFiles:menubarx-new-and-focus.scpt"show nextif slide number of current slide is less than slide number of last slide thenclose with savingrepeat while performing ocrocrtell openPdfwith timeout of 5 * k_minutes secondsset openPdf to open curr_itemrepeat with curr_item in added_itemstell application "Nitro PDF Pro"property k_minutes : 60display alert (theFile as string)multiple selections allowed false ¬cancel button name "Nope, try again" ¬OK button name "Looks Good!" ¬default items "B" ¬with prompt "Prompt Text" ¬with title "List Title" ¬set chosenListItem to choose from list {"A", "B", "3"} ¬tell current application's NSMakeRect to NSMakeRect(x, y, width, height)set x to screenWidth - widthelse if x + width > screenWidth thenset screenWidth to width of |size| of mainScreenFrameset height to height of |size| of documentViewFrame + windowHeadHeightset width to width of |size| of documentViewFrameset windowHeadHeight to height of |size| of appWindowFrame - height of |size| of webViewFrameset y to y of origin of appWindowFrameset x to x of origin of appWindowFrameset mainScreenFrame to frame() of mainScreen of current application's NSScreenset documentViewFrame to frame() of documentView of frameView of mainFrame of webViewset webViewFrame to frame() of webViewset appWindowFrame to frame() of appWindowreturn defaultFrameif fullScreenMode thenon windowWillUseStandardFrame_defaultFrame_(appWindow, defaultFrame)set fullScreenMode to falseon windowDidExitFullScreen_(aNotification)set fullScreenMode to trueon windowWillEnterFullScreen_(aNotification)return 3078on window_willUseFullScreenPresentationOptions_(appWindow, proposedOptions)property fullScreenMode : falseproperty webView : missing valuescript WindowDelegateset _path to (path of public folder) as stringset value of attribute named "link" of style of paragraph 1 of note of duplicatedTask to "omnifocus:///task/" & id of _selset note of duplicatedTask to "testing"set duplicatedTask to make new task with properties {name:"Review: " & name of _sel, flagged:true} at end of tasks of channeldisplay alert "No channel specified."set channel to task ("Channel " & argv) of LandSon main(argv)tell O to openPerspective("Land & Sea")display notification "\"" & name of _sel & "\"" & " is not a project."set note of duplicatedTask to "omnifocus:///task/" & id of _seltell O to deferDaily(duplicatedTask)set duplicatedTask to make new task with properties {name:"Review: " & name of _sel, flagged:true} at end of tasks of LandSif class of _sel is project thenset LandS to findProject("Land & Sea") of Omain(argv)write text "cd " & q & "; clear"tell current session of last terminal windowon CD_to(q)set dir_path to quoted form of (POSIX path of (the target of the front window as alias))set R to choose from list my_list with prompt thePrompt with multiple selections allowedmy Simple_sort(the my_list)tell application "Contacts" to set my_list to name of every groupif application appName is running thenset appName to "Contacts"end openURLInSafariif exists (processes where name is "Safari Technology Preview") thenclose active tab of window 1on openURLInSafari()openURLInSafari()clean up window of desktop by kindset shows icon preview to falseset shows item info to trueset icon size to 48set arrangement to not arrangedtell iconViewOptionsset iconViewOptions to desktop's window's icon view optionsdisplay notification "An error occurred. " & errorMessagetell application "Finder" to eject (every disk whose ejectable is true and local volume is true)tell application "htcLib" to minNum(someList)tell application "htcLib" to clickAtCoords(xClick, yClick)on clickAtCoords(xClick, yClick)error "unable to clickObjectByCoords - " & errMsg number errNumreturn clickAtCoords(xClick, yClick)set yClick to yCoord + objOffsetset xClick to xCoord + objOffsetset objOffset to round (minNum({xSize, ySize}) / 2) rounding downset {xSize, ySize} to size of someObjectset {xCoord, yCoord} to position of someObjectset someObject to ensureObjectRef(someObject)clickObjectByCoords(privSetPrintCheckbox)set privSetPrintCheckbox to checkbox "Allow printing" of window 1return "done"return "started sharing"set cameras to (first window whose name does not contain " ")set bar to (second window whose name does not contain " ")set position of cameras to external_top_left_lowerset cameras to (second window whose name does not contain " ")set position of bar to external_top_left_lowerset bar to (first window whose name does not contain " ")tell application "System Events" to key code 76 -- returntell application "System Events" to key code 123 -- lefttell application "System Events" to key code 126 -- upperform action "AXRaise" of (first window whose name contains "Select")return "ended sharing"tell application "System Events" to keystroke "w" using {command down, shift down}trigger_action "{\"BTTPredefinedActionType\":175}" -- resize to right 2/3rdtrigger_action "{\"BTTPredefinedActionType\":47}" -- move to other monitorperform action "AXRaise" of (first window whose name is equal to "Zoom")trigger_action "{\"BTTPredefinedActionType\":108}" -- resize to left 1/3perform action "AXRaise" of (first window whose name contains "Meeting")tell application process theApptell application "System Events" to keystroke "s" using {command down, shift down}if shareStatus thenset shareStatus to falseset shareStatus to trueif ((currentName as string) contains "Sharing Frame Window") thenrepeat with currentName in theWindowListend subListsToOneListset theWindowList to newLset newL to newL & irepeat with i in xset newL to {}on subListsToOneList(x)set theWindowList to my subListsToOneList(myList) -- Flattening a list of listsset myList to name of windows of (processes whose name is "zoom.us") -- get a list of lists, each sublist contains namestell application theAppreturn "app isn't running"if application theApp is not running thenset external_top_left_lower to {582, -998}set external_top_left to {1290, -1000} -- top left -- rename these, set proper coordinates. maybe get from existing windows?set theApp to "zoom.us"end fmGUI_CustomFunctions_Saveerror "Custom Functions wasn't open - " & errMsgerror "Couldn't save Custom Functions - " & errMsg number errNumwindowWaitUntil({windowName:"Manage Custom Functions for", windowNameTest:"does not contain", whichWindow:"front"})if frontmostWindowName starts with "Manage Custom Functions for" thenon fmGUI_CustomFunctions_Save(prefs)fmGUI_CustomFunctions_Save({})frontmost_app()return "AppleScript Editor frontmost"if frontmost_app() is "AppleScript Editor" thenreturn item 1 of (get name of processes whose frontmost is true)tell application "iTunes" to activate # frontmost applicationtell track id 39328set played date to date "9/06/2008 16:31:18"tell track id 36954set played date to date "6/21/2008 13:12:09"tell track id 33485set played date to date "9/26/2008 01:56:03"tell track id 42910set played date to date "5/05/2008 05:41:06"tell track id 36701tell track id 36740set played date to date "7/11/2008 21:40:33"tell track id 40310tell track id 36779tell track id 34185set played date to date "10/29/2008 12:41:10"tell track id 39387set played date to date "5/01/2008 13:38:19"tell track id 42572set played date to date "10/28/2008 13:55:11"tell track id 37493set played date to date "7/30/2008 03:24:17"tell track id 38498set played date to date "8/14/2008 16:23:14"tell track id 40714set played date to date "10/01/2008 14:01:56"tell track id 40268tell track id 35361set played date to date "9/25/2008 19:16:55"tell track id 34448set played date to date "6/21/2008 09:11:19"tell track id 32783set played date to date "6/12/2008 15:22:36"tell track id 32551set played date to date "5/11/2008 19:08:46"tell track id 41933set played date to date "5/05/2008 04:55:33"tell track id 40176tell track id 33953set played date to date "9/13/2008 13:26:28"tell track id 42808set played date to date "10/29/2008 11:02:48"tell track id 38367tell track id 33763set played date to date "5/27/2008 16:30:44"tell track id 33119set played date to date "5/01/2008 14:44:11"tell track id 32789set played date to date "6/15/2008 12:18:14"tell track id 32887set played date to date "10/03/2008 01:45:03"tell track id 32943set played date to date "9/20/2008 14:51:58"tell track id 38476set played date to date "6/15/2008 23:01:47"tell track id 36720set played date to date "5/11/2008 04:28:35"tell track id 42966set played date to date "5/02/2008 12:12:08"tell track id 42611set played date to date "8/21/2008 19:27:39"tell track id 39844tell track id 34183set played date to date "6/15/2008 21:56:30"tell track id 36695set played date to date "5/15/2008 01:58:15"tell track id 37472tell track id 39287set played date to date "5/20/2008 17:07:54"tell track id 36008set played date to date "5/13/2008 15:49:48"tell track id 33773tell track id 40389set played date to date "5/13/2008 10:05:38"tell track id 37586set played date to date "10/03/2008 03:23:54"tell track id 38806set played date to date "6/21/2008 13:21:36"tell track id 38932set played date to date "5/14/2008 05:29:28"tell track id 41202set played date to date "6/11/2008 15:03:36"tell track id 36231set played date to date "8/04/2008 13:42:20"tell track id 35014tell track id 32344set played date to date "10/31/2008 08:41:03"tell track id 34944set played date to date "8/14/2008 18:05:22"tell track id 40596set played date to date "5/06/2008 06:26:18"tell track id 41030set played date to date "5/11/2008 13:49:40"tell track id 37395set played date to date "9/17/2008 21:13:41"tell track id 42816tell track id 40482set played date to date "6/10/2008 17:02:51"tell track id 31208tell track id 33429set played date to date "5/27/2008 12:50:56"tell track id 33107set played date to date "9/26/2008 14:50:47"tell track id 38875set played date to date "6/16/2008 02:09:51"tell track id 31404tell track id 42431set played date to date "5/01/2008 17:00:51"tell track id 43242set played date to date "10/25/2008 08:35:54"tell track id 31884set played date to date "5/13/2008 07:39:38"tell track id 36027tell track id 41017tell track id 36655tell track id 38213tell track id 42682tell track id 42858set played date to date "5/06/2008 03:23:27"tell track id 36690set played date to date "9/04/2008 19:27:09"tell track id 38024set played date to date "6/16/2008 06:37:28"tell track id 40178set played date to date "10/25/2008 08:48:22"tell track id 32583set played date to date "8/23/2008 13:24:03"tell track id 38838tell track id 42618set played date to date "5/11/2008 16:33:32"tell track id 32777set played date to date "9/25/2008 22:01:45"tell track id 34667set played date to date "6/02/2008 17:28:42"tell track id 33712set played date to date "6/03/2008 07:16:00"tell track id 42186set played date to date "9/25/2008 17:49:53"tell track id 38249set played date to date "5/27/2008 16:08:15"tell track id 34327set played date to date "5/11/2008 19:00:22"tell track id 32546tell track id 37357set played date to date "6/21/2008 15:51:24"tell track id 37794set played date to date "6/02/2008 16:30:34"tell track id 34446tell track id 37103set played date to date "5/05/2008 08:29:09"tell track id 31460tell track id 38161set played date to date "6/15/2008 15:50:39"tell track id 33644set played date to date "10/30/2008 08:59:33"tell track id 39082tell track id 40974set played date to date "10/03/2008 02:53:14"tell track id 38883set played date to date "10/24/2008 15:26:41"tell track id 41727set played date to date "5/01/2008 16:28:37"tell track id 42166set played date to date "10/25/2008 12:28:29"tell track id 42007set played date to date "8/14/2008 15:38:35"tell track id 34575set played date to date "7/10/2008 20:01:54"tell track id 34311tell track id 38935set played date to date "5/03/2008 10:12:18"tell track id 41304set played date to date "10/29/2008 09:32:41"tell track id 36902set played date to date "4/26/2008 06:45:18"tell track id 33962tell track id 35997set played date to date "10/30/2008 08:22:20"tell track id 34322tell track id 32526set played date to date "5/05/2008 08:51:58"tell track id 41960set played date to date "5/11/2008 19:26:02"tell track id 33489set played date to date "5/01/2008 22:30:08"tell track id 36648set played date to date "6/15/2008 20:47:43"tell track id 41088set played date to date "5/19/2008 15:24:25"tell track id 31320set played date to date "5/03/2008 12:36:58"tell track id 31420set played date to date "9/13/2008 13:15:00"tell track id 41251tell track id 42605tell track id 43052set played date to date "7/29/2008 21:19:46"tell track id 38449tell track id 37370set played date to date "8/25/2008 20:35:03"tell track id 34940set played date to date "5/10/2008 14:48:56"tell track id 34438set played date to date "5/01/2008 05:43:41"tell track id 41867set played date to date "6/10/2008 14:43:58"tell track id 34085set played date to date "10/01/2008 15:56:56"tell track id 38012tell track id 43141set played date to date "10/30/2008 09:03:40"tell track id 31612set played date to date "6/15/2008 20:40:51"tell track id 38954tell track id 42638tell track id 38771set played date to date "5/25/2008 11:58:52"tell track id 40545set played date to date "5/17/2008 08:52:43"tell track id 40227set played date to date "10/30/2008 06:21:45"tell track id 37211set played date to date "6/03/2008 15:51:32"tell track id 34911tell track id 34838set played date to date "7/19/2008 22:40:23"tell track id 33418set played date to date "6/01/2008 22:08:44"tell track id 40995set played date to date "9/25/2008 23:54:21"tell track id 37189set played date to date "8/08/2008 18:50:16"tell track id 37461set played date to date "11/03/2008 04:39:21"tell track id 39347set played date to date "10/09/2008 18:31:30"tell track id 31935tell track id 34235set played date to date "10/27/2008 09:02:29"tell track id 35622set played date to date "6/14/2008 05:44:55"tell track id 40273set played date to date "5/22/2008 02:52:16"tell track id 40156set played date to date "11/03/2008 03:06:58"tell track id 40027set played date to date "5/11/2008 04:51:37"tell track id 42948set played date to date "9/15/2008 18:02:07"tell track id 38707set played date to date "6/16/2008 07:16:39"tell track id 41730tell track id 33307set played date to date "10/29/2008 13:00:04"tell track id 31339set played date to date "5/26/2008 07:07:53"tell track id 40035set played date to date "6/07/2008 15:42:39"tell track id 37362tell track id 36401set played date to date "9/13/2008 12:57:29"tell track id 31732set played date to date "6/15/2008 15:54:49"tell track id 35234set played date to date "7/03/2008 21:41:14"tell track id 33906tell track id 36252set played date to date "10/01/2008 15:31:00"tell track id 41967set played date to date "5/06/2008 14:51:32"tell track id 37774set played date to date "5/14/2008 05:03:35"tell track id 31415tell track id 35252tell track id 42727set played date to date "11/03/2008 02:48:03"tell track id 43155set played date to date "10/29/2008 10:08:34"tell track id 37603set played date to date "4/26/2008 07:32:20"tell track id 32437set played date to date "10/03/2008 04:02:38"tell track id 31592set played date to date "5/13/2008 11:22:11"tell track id 31880tell track id 42118set played date to date "9/17/2008 16:21:14"tell track id 36201set played date to date "11/03/2008 03:53:04"tell track id 43177set played date to date "6/09/2008 10:11:01"tell track id 33957set played date to date "9/14/2008 03:20:59"tell track id 36135tell track id 35246set played date to date "5/13/2008 04:47:49"tell track id 34350set played date to date "10/25/2008 10:56:03"tell track id 38585tell track id 33310set played date to date "10/01/2008 12:05:41"tell track id 40604tell track id 34218tell track id 32646set played date to date "11/01/2008 07:40:27"tell track id 32010set played date to date "7/26/2008 18:13:29"tell track id 33970tell track id 36409set played date to date "6/06/2008 08:49:42"tell track id 40892set played date to date "7/10/2008 21:09:35"tell track id 36058set played date to date "5/02/2008 07:52:50"tell track id 32796set played date to date "9/13/2008 10:57:40"tell track id 33570set played date to date "8/05/2008 10:17:56"tell track id 34896set played date to date "9/04/2008 19:35:35"tell track id 40874tell track id 39265set played date to date "8/08/2008 22:10:18"tell track id 36015set played date to date "9/13/2008 12:13:42"tell track id 40018set played date to date "10/29/2008 13:11:09"tell track id 39725set played date to date "10/29/2008 06:14:13"tell track id 41291set played date to date "11/03/2008 03:27:28"tell track id 32014set played date to date "6/15/2008 16:28:05"tell track id 31393set played date to date "6/22/2008 09:17:55"tell track id 43122set played date to date "5/13/2008 07:48:09"tell track id 36713set played date to date "4/26/2008 08:36:42"tell track id 31239set played date to date "5/12/2008 17:45:22"tell track id 40609tell track id 33789set played date to date "10/09/2008 23:58:22"tell track id 41302set played date to date "10/27/2008 09:08:09"tell track id 42708tell track id 35373set played date to date "8/30/2008 20:51:55"tell track id 38242set played date to date "9/14/2008 04:05:36"tell track id 35242tell track id 37749set played date to date "9/25/2008 18:02:04"tell track id 36745set played date to date "10/02/2008 22:58:28"tell track id 41154set played date to date "10/09/2008 14:27:05"tell track id 37367tell track id 34816set played date to date "5/13/2008 15:09:12"tell track id 40881set played date to date "10/27/2008 08:04:08"tell track id 39718set played date to date "6/09/2008 07:46:49"tell track id 39933set played date to date "5/01/2008 15:23:41"tell track id 39147set played date to date "10/03/2008 08:09:51"tell track id 37188set played date to date "6/15/2008 18:41:11"tell track id 41971set played date to date "10/31/2008 08:44:22"tell track id 41137set played date to date "10/27/2008 07:31:09"tell track id 39711set played date to date "5/13/2008 14:55:29"tell track id 41987set played date to date "6/21/2008 14:06:25"tell track id 40158set played date to date "6/13/2008 19:35:30"tell track id 43428tell track id 32430tell track id 43065tell track id 36789tell track id 38904set played date to date "6/21/2008 16:12:15"tell track id 34419tell track id 34203tell track id 39335set played date to date "10/03/2008 05:55:13"tell track id 41158set played date to date "5/26/2008 16:02:53"tell track id 31459set played date to date "5/02/2008 00:52:04"tell track id 42140tell track id 43168set played date to date "7/09/2008 22:54:24"tell track id 33636tell track id 40387set played date to date "10/03/2008 08:56:42"tell track id 38886set played date to date "5/01/2008 18:41:35"tell track id 38582set played date to date "4/27/2008 09:15:23"tell track id 34699tell track id 34385tell track id 39930set played date to date "10/10/2008 01:49:22"tell track id 34312set played date to date "10/29/2008 13:30:33"tell track id 41214set played date to date "7/03/2008 20:40:56"tell track id 33321set played date to date "11/03/2008 03:23:34"tell track id 35059tell track id 33360set played date to date "5/03/2008 05:29:20"tell track id 34364tell track id 33309tell track id 38641set played date to date "5/10/2008 14:04:18"tell track id 31411set played date to date "11/01/2008 06:21:26"tell track id 31750tell track id 42466set played date to date "10/29/2008 13:39:16"tell track id 40900set played date to date "9/04/2008 21:56:09"tell track id 36227set played date to date "5/13/2008 15:25:27"tell track id 36637set played date to date "5/01/2008 22:57:57"tell track id 36676set played date to date "5/04/2008 05:05:30"tell track id 39110set played date to date "8/21/2008 14:41:31"tell track id 41845set played date to date "11/01/2008 17:50:05"tell track id 36037set played date to date "10/29/2008 09:13:40"tell track id 43335set played date to date "5/14/2008 12:05:04"tell track id 31443set played date to date "6/16/2008 08:11:10"tell track id 41942set played date to date "10/10/2008 01:44:37"tell track id 42810set played date to date "8/24/2008 02:57:01"tell track id 41165set played date to date "9/13/2008 10:20:19"tell track id 34939set played date to date "5/22/2008 03:55:18"tell track id 42594set played date to date "6/16/2008 02:22:17"tell track id 33576set played date to date "6/15/2008 20:50:39"tell track id 41721set played date to date "6/01/2008 19:59:45"tell track id 36241tell track id 33951set played date to date "6/14/2008 06:08:22"tell track id 31963set played date to date "6/16/2008 03:35:54"tell track id 33649set played date to date "9/15/2008 14:19:21"tell track id 42575tell track id 36756tell track id 34820set played date to date "5/13/2008 09:45:45"tell track id 39460set played date to date "5/17/2008 13:00:26"tell track id 34435set played date to date "10/02/2008 18:56:26"tell track id 31600set played date to date "5/06/2008 02:34:21"tell track id 40940set played date to date "5/01/2008 18:18:47"tell track id 34369set played date to date "6/21/2008 17:04:47"tell track id 31594set played date to date "4/28/2008 14:05:01"tell track id 37369set played date to date "10/03/2008 07:42:05"tell track id 32786set played date to date "5/24/2008 08:11:14"tell track id 41122set played date to date "9/19/2008 17:17:33"tell track id 41566set played date to date "5/06/2008 15:08:32"tell track id 41186set played date to date "7/29/2008 23:13:29"tell track id 38245set played date to date "5/13/2008 15:57:19"tell track id 37389tell track id 35130tell track id 34201tell track id 42999set played date to date "5/14/2008 10:30:01"tell track id 37378set played date to date "5/05/2008 05:36:55"tell track id 32923tell track id 34831set played date to date "5/12/2008 06:25:37"tell track id 36687tell track id 42150set played date to date "11/03/2008 03:47:29"tell track id 31737tell track id 41024set played date to date "6/16/2008 01:06:07"tell track id 41873set played date to date "10/27/2008 06:09:37"tell track id 35661set played date to date "11/01/2008 05:23:43"tell track id 36532set played date to date "10/29/2008 10:48:46"tell track id 34331set played date to date "7/24/2008 16:11:24"tell track id 32902set played date to date "10/09/2008 22:23:58"tell track id 33440set played date to date "9/13/2008 11:21:02"tell track id 39939tell track id 37098set played date to date "9/13/2008 13:22:29"tell track id 31191set played date to date "10/09/2008 16:06:17"tell track id 32293tell track id 42931set played date to date "5/12/2008 09:59:51"tell track id 34117set played date to date "9/06/2008 21:49:15"tell track id 37952set played date to date "5/11/2008 15:13:32"tell track id 34361set played date to date "5/13/2008 04:27:08"tell track id 40786set played date to date "6/07/2008 11:21:36"tell track id 42901set played date to date "5/12/2008 08:57:03"tell track id 34987set played date to date "7/30/2008 02:54:52"tell track id 37760set played date to date "5/10/2008 12:21:20"tell track id 33428set played date to date "9/13/2008 13:01:30"tell track id 42630set played date to date "5/01/2008 14:17:00"tell track id 32857set played date to date "8/26/2008 22:34:54"tell track id 35849tell track id 34553tell track id 35411set played date to date "5/10/2008 10:56:19"tell track id 39114set played date to date "9/17/2008 16:01:03"tell track id 41860set played date to date "10/02/2008 18:07:55"tell track id 42441set played date to date "10/27/2008 06:47:16"tell track id 34792tell track id 39340set played date to date "10/25/2008 12:01:17"tell track id 32915set played date to date "11/03/2008 04:57:25"tell track id 33592tell track id 36388set played date to date "5/04/2008 04:59:55"tell track id 41997set played date to date "5/03/2008 10:39:35"tell track id 40186set played date to date "6/09/2008 14:36:12"tell track id 41726set played date to date "5/12/2008 10:52:13"tell track id 36120set played date to date "11/01/2008 07:43:38"tell track id 34334tell track id 35190tell track id 37109set played date to date "6/06/2008 08:07:12"tell track id 43059set played date to date "11/03/2008 02:03:59"tell track id 40072set played date to date "6/15/2008 23:47:48"tell track id 33548tell track id 35282tell track id 40135set played date to date "5/11/2008 14:37:44"tell track id 38952set played date to date "6/15/2008 21:14:33"tell track id 41634set played date to date "6/21/2008 18:29:40"tell track id 34693tell track id 40458set played date to date "4/26/2008 07:03:18"tell track id 36753set played date to date "5/06/2008 11:15:46"tell track id 37809tell track id 33159tell track id 40264set played date to date "10/09/2008 23:14:50"tell track id 41366set played date to date "4/26/2008 07:23:28"tell track id 34032tell track id 42943set played date to date "10/01/2008 16:06:30"tell track id 40559set played date to date "8/23/2008 15:45:05"tell track id 41345set played date to date "10/26/2008 04:44:26"tell track id 43413set played date to date "5/12/2008 10:10:26"tell track id 36117tell track id 33490set played date to date "9/25/2008 22:15:15"tell track id 33329set played date to date "9/06/2008 17:52:14"tell track id 31312set played date to date "8/30/2008 20:44:09"tell track id 36766set played date to date "6/13/2008 21:14:05"tell track id 34698set played date to date "5/06/2008 09:06:08"tell track id 35205set played date to date "7/26/2008 22:41:22"set played count to 64tell track id 33180tell track id 35348tell track id 38837set played date to date "7/25/2008 18:33:05"tell track id 36303set played date to date "10/26/2008 03:36:09"tell track id 35363tell track id 32292set played date to date "6/07/2008 14:10:59"tell track id 34356set played date to date "10/04/2008 19:44:21"tell track id 35133tell track id 35794set played date to date "7/10/2008 19:21:54"tell track id 33306tell track id 41016tell track id 41093tell track id 35227set played date to date "10/29/2008 12:47:59"tell track id 34178set played date to date "6/03/2008 08:46:01"tell track id 42163set played date to date "5/15/2008 04:42:02"tell track id 36623set played date to date "10/27/2008 07:59:24"tell track id 39717set played date to date "6/02/2008 06:06:29"tell track id 33510tell track id 36741set played date to date "10/29/2008 08:57:46"tell track id 33249set played date to date "10/29/2008 14:13:31"tell track id 39719set played date to date "5/12/2008 06:15:57"tell track id 40164set played date to date "8/21/2008 18:23:57"tell track id 32548set played date to date "5/05/2008 07:34:03"tell track id 39953set played date to date "5/14/2008 06:32:42"tell track id 41627tell track id 38752set played date to date "5/17/2008 12:59:55"tell track id 34432tell track id 32476tell track id 40202set played date to date "6/21/2008 18:06:05"tell track id 39941set played date to date "5/13/2008 08:02:25"tell track id 34077set played date to date "9/13/2008 16:30:55"tell track id 33505set played date to date "8/26/2008 20:31:13"tell track id 33769set played date to date "4/28/2008 19:33:47"tell track id 40975set played date to date "9/11/2008 23:30:50"tell track id 34326set played date to date "5/03/2008 14:35:02"tell track id 31389set played date to date "8/26/2008 00:48:41"tell track id 34945set played date to date "9/04/2008 17:47:48"tell track id 41145set played date to date "10/04/2008 16:57:19"tell track id 41168set played date to date "6/15/2008 13:24:23"tell track id 38898set played date to date "5/12/2008 07:30:45"tell track id 38462set played date to date "8/19/2008 19:36:38"tell track id 37693set played date to date "11/01/2008 07:17:33"tell track id 31755set played date to date "5/23/2008 18:56:24"tell track id 31883set played date to date "10/29/2008 13:53:44"tell track id 40454set played date to date "8/07/2008 22:33:43"tell track id 42803tell track id 34063set played date to date "6/09/2008 07:26:00"tell track id 40948set played date to date "8/08/2008 16:36:57"tell track id 34371tell track id 39264tell track id 32647set played date to date "10/01/2008 11:22:20"tell track id 38966set played date to date "9/13/2008 13:04:28"tell track id 40597set played date to date "6/22/2008 10:25:17"tell track id 35022tell track id 43313set played date to date "6/12/2008 16:05:25"tell track id 33992set played date to date "10/29/2008 04:57:06"tell track id 32770set played date to date "7/25/2008 20:13:24"tell track id 34771set played date to date "11/03/2008 04:34:57"tell track id 32132set played date to date "6/01/2008 00:00:00"tell track id 41986set played date to date "5/26/2008 09:41:38"tell track id 42602set played date to date "11/01/2008 08:09:09"tell track id 38475set played date to date "6/10/2008 11:53:30"tell track id 32905set played date to date "6/16/2008 02:06:27"tell track id 43188set played date to date "8/23/2008 23:24:28"tell track id 40388set played date to date "6/21/2008 14:21:51"tell track id 42114set played date to date "8/21/2008 14:07:35"tell track id 33243set played date to date "6/22/2008 11:36:29"tell track id 34219tell track id 34186tell track id 36030set played date to date "10/01/2008 12:26:10"tell track id 42809set played date to date "7/24/2008 15:20:26"tell track id 39295tell track id 36792set played date to date "9/26/2008 13:58:57"tell track id 38688set played date to date "9/17/2008 18:30:27"tell track id 41369set played date to date "10/27/2008 05:09:52"tell track id 35755set played date to date "5/11/2008 04:19:41"tell track id 43154set played date to date "7/03/2008 19:46:06"tell track id 37585set played date to date "10/26/2008 02:43:28"tell track id 41174tell track id 42924set played date to date "9/04/2008 18:02:01"tell track id 38931set played date to date "8/23/2008 15:12:18"tell track id 33764set played date to date "6/15/2008 13:17:40"tell track id 36643set played date to date "10/27/2008 05:28:47"tell track id 35758tell track id 34815set played date to date "6/16/2008 00:38:08"tell track id 41027set played date to date "11/03/2008 02:25:35"tell track id 37604tell track id 41325set played date to date "6/11/2008 05:24:05"tell track id 35006set played date to date "6/13/2008 17:56:51"tell track id 38938set played date to date "10/01/2008 15:02:22"tell track id 33433set played date to date "11/03/2008 02:28:57"tell track id 32036set played date to date "5/14/2008 10:34:36"tell track id 34548set played date to date "9/13/2008 14:29:42"tell track id 36134set played date to date "11/01/2008 05:15:43"tell track id 40544tell track id 34210set played date to date "11/03/2008 05:14:53"tell track id 40220set played date to date "11/01/2008 14:51:55"tell track id 31414tell track id 37764set played date to date "8/07/2008 02:45:18"tell track id 41641tell track id 35612tell track id 35259set played date to date "10/09/2008 13:44:14"tell track id 33780set played date to date "5/03/2008 06:30:29"tell track id 31405set played date to date "10/09/2008 13:53:10"tell track id 41850set played date to date "5/02/2008 10:22:29"tell track id 32847set played date to date "5/13/2008 04:51:24"tell track id 33571set played date to date "10/09/2008 16:09:46"tell track id 33971tell track id 34200tell track id 36665tell track id 42783set played date to date "10/24/2008 15:58:21"tell track id 39314set played date to date "6/06/2008 09:12:10"tell track id 36737tell track id 42859set played date to date "10/09/2008 13:46:41"tell track id 41519set played date to date "5/02/2008 09:44:50"tell track id 35264tell track id 39098set played date to date "10/01/2008 11:50:32"tell track id 37775set played date to date "11/03/2008 05:22:48"tell track id 34445set played date to date "5/25/2008 14:25:15"tell track id 40829set played date to date "7/27/2008 16:11:49"tell track id 42004set played date to date "5/01/2008 17:37:45"tell track id 42909set played date to date "5/05/2008 03:23:00"tell track id 32848set played date to date "9/04/2008 17:57:20"tell track id 33643set played date to date "6/06/2008 09:15:39"tell track id 34377set played date to date "5/13/2008 06:30:43"tell track id 41129set played date to date "8/26/2008 07:02:09"tell track id 34227set played date to date "7/25/2008 22:34:35"tell track id 42210set played date to date "8/23/2008 19:25:50"tell track id 40549tell track id 42581set played date to date "6/21/2008 14:53:21"tell track id 41008set played date to date "5/12/2008 05:37:27"tell track id 34414set played date to date "9/04/2008 18:33:46"tell track id 33655set played date to date "5/02/2008 12:15:52"tell track id 38495set played date to date "6/16/2008 01:24:45"tell track id 31398set played date to date "6/16/2008 02:35:47"tell track id 32914set played date to date "11/01/2008 08:05:33"tell track id 40976tell track id 34819set played date to date "8/23/2008 17:12:18"tell track id 42713set played date to date "5/11/2008 15:53:18"tell track id 36444tell track id 36777tell track id 39275set played date to date "6/09/2008 15:13:16"tell track id 42895tell track id 42457set played date to date "5/13/2008 06:18:25"tell track id 31421set played date to date "5/10/2008 10:25:34"tell track id 35429set played date to date "11/01/2008 05:52:42"tell track id 31934set played date to date "5/15/2008 01:50:26"tell track id 38953set played date to date "9/26/2008 15:54:04"tell track id 40542set played date to date "6/16/2008 01:50:03"tell track id 42447set played date to date "5/02/2008 05:48:44"tell track id 41252set played date to date "5/11/2008 19:15:13"tell track id 38632set played date to date "9/13/2008 13:47:30"tell track id 34084set played date to date "5/13/2008 06:22:56"tell track id 36649tell track id 33956set played date to date "5/06/2008 01:02:23"tell track id 40226tell track id 33578tell track id 34236tell track id 38490set played date to date "6/21/2008 17:38:15"tell track id 41518tell track id 35281set played date to date "5/05/2008 06:41:52"tell track id 39108set played date to date "10/25/2008 08:30:46"tell track id 43051set played date to date "5/05/2008 02:25:46"tell track id 33549tell track id 32126tell track id 43320set played date to date "6/21/2008 09:48:34"tell track id 34594set played date to date "10/26/2008 03:05:10"tell track id 38897set played date to date "6/03/2008 14:52:06"tell track id 38642set played date to date "8/07/2008 22:45:02"tell track id 31964set played date to date "6/07/2008 10:34:10"tell track id 38951tell track id 35410set played date to date "8/26/2008 15:51:40"tell track id 31213set played date to date "9/11/2008 18:28:46"tell track id 36396set played date to date "4/26/2008 07:16:54"tell track id 32480set played date to date "5/13/2008 15:36:23"tell track id 36675set played date to date "8/24/2008 01:04:27"tell track id 35357set played date to date "6/15/2008 23:14:38"tell track id 34363set played date to date "6/10/2008 11:49:09"tell track id 41018tell track id 33795set played date to date "10/09/2008 19:32:58"tell track id 36862set played date to date "5/05/2008 09:39:22"tell track id 34572set played date to date "10/24/2008 17:01:20"tell track id 36036set played date to date "10/09/2008 20:03:52"tell track id 36604set played date to date "5/05/2008 05:48:06"tell track id 32889set played date to date "6/14/2008 15:50:35"tell track id 31322set played date to date "10/09/2008 19:09:26"tell track id 38520set played date to date "5/24/2008 11:53:45"tell track id 38972set played date to date "5/17/2008 08:32:23"tell track id 37417tell track id 37880set played date to date "5/02/2008 04:11:03"tell track id 37795set played date to date "10/29/2008 13:26:41"tell track id 41164set played date to date "5/03/2008 11:32:22"tell track id 40884set played date to date "11/01/2008 07:37:03"tell track id 37548set played date to date "10/30/2008 08:50:22"tell track id 35326set played date to date "10/25/2008 08:06:51"tell track id 33650set played date to date "7/27/2008 16:46:22"tell track id 40398set played date to date "10/09/2008 19:40:18"tell track id 34368tell track id 32477set played date to date "8/23/2008 16:56:25"tell track id 41565tell track id 33786tell track id 38486set played date to date "6/15/2008 16:33:59"tell track id 36970set played date to date "10/29/2008 09:59:56"tell track id 33453set played date to date "6/14/2008 06:38:17"tell track id 34082set played date to date "5/15/2008 05:46:54"tell track id 32580set played date to date "10/27/2008 07:26:51"tell track id 34795set played date to date "5/10/2008 09:48:39"tell track id 42133tell track id 33788set played date to date "10/29/2008 12:13:34"tell track id 34434set played date to date "9/17/2008 17:12:44"tell track id 34504tell track id 39334set played date to date "10/04/2008 18:25:41"tell track id 35374set played date to date "6/21/2008 18:59:08"tell track id 39944set played date to date "5/24/2008 08:21:11"set played count to 66tell track id 41632tell track id 42855set played date to date "9/15/2008 14:59:56"tell track id 36714set played date to date "8/04/2008 21:27:01"tell track id 37979set played date to date "6/21/2008 23:37:04"tell track id 34938set played date to date "6/02/2008 18:03:04"tell track id 40309set played date to date "6/10/2008 12:01:48"tell track id 39938set played date to date "6/02/2008 11:04:12"tell track id 33185set played date to date "5/21/2008 18:19:21"tell track id 33637set played date to date "5/06/2008 02:07:58"tell track id 36670set played date to date "10/30/2008 07:50:27"tell track id 32133set played date to date "8/14/2008 20:01:07"tell track id 42170set played date to date "6/21/2008 14:44:12"tell track id 36636set played date to date "5/02/2008 13:14:15"tell track id 41972set played date to date "9/25/2008 17:45:54"tell track id 38885set played date to date "5/10/2008 14:57:41"tell track id 42141tell track id 42919set played date to date "6/16/2008 05:24:19"tell track id 42906set played date to date "10/27/2008 07:35:08"tell track id 39712set played date to date "10/03/2008 09:00:42"tell track id 33545set played date to date "5/13/2008 05:59:42"tell track id 36123set played date to date "10/01/2008 11:38:01"tell track id 40608set played date to date "5/25/2008 00:56:31"tell track id 42123set played date to date "11/03/2008 04:52:53"tell track id 37261set played date to date "10/27/2008 09:03:12"tell track id 37293set played date to date "5/02/2008 12:46:54"tell track id 41998tell track id 36494set played date to date "5/17/2008 12:05:47"tell track id 42147set played date to date "6/14/2008 07:18:00"tell track id 32116set played date to date "5/23/2008 05:04:48"tell track id 41136set played date to date "9/13/2008 09:25:48"tell track id 42195set played date to date "6/07/2008 10:11:26"tell track id 43058set played date to date "5/03/2008 13:42:12"tell track id 34491set played date to date "5/02/2008 13:06:02"tell track id 36122tell track id 41015set played date to date "10/25/2008 13:00:34"tell track id 42122tell track id 40899set played date to date "6/15/2008 15:39:52"tell track id 36126set played date to date "5/13/2008 15:46:40"tell track id 40557set played date to date "4/26/2008 06:24:59"tell track id 31502set played date to date "10/03/2008 01:02:13"tell track id 43132set played date to date "5/25/2008 07:22:35"tell track id 35607tell track id 42059set played date to date "8/23/2008 15:04:06"tell track id 34509set played date to date "5/06/2008 09:52:49"tell track id 33181set played date to date "10/03/2008 06:25:21"tell track id 43124set played date to date "6/16/2008 00:46:26"tell track id 37782set played date to date "10/01/2008 16:18:39"tell track id 34511set played date to date "5/02/2008 09:08:22"tell track id 33541tell track id 43066tell track id 35368set played date to date "10/04/2008 18:35:19"tell track id 40263set played date to date "10/01/2008 12:30:11"tell track id 32540tell track id 34031set played date to date "9/14/2008 04:04:04"tell track id 34136set played date to date "10/27/2008 08:39:41"tell track id 39726set played date to date "5/15/2008 04:22:10"tell track id 41633set played date to date "6/12/2008 17:32:31"tell track id 42811tell track id 43057set played date to date "6/12/2008 06:02:43"tell track id 37786set played date to date "10/26/2008 04:48:14"tell track id 43414tell track id 32438set played date to date "6/16/2008 03:24:30"tell track id 39312tell track id 36765set played date to date "9/13/2008 11:04:41"tell track id 34355set played date to date "8/29/2008 16:08:18"tell track id 41468set played date to date "4/28/2008 13:36:58"tell track id 35236set played date to date "8/23/2008 23:28:47"tell track id 42915tell track id 37097set played date to date "7/03/2008 20:52:07"tell track id 38852set played date to date "5/23/2008 17:20:58"tell track id 33233tell track id 36746set played date to date "10/27/2008 06:15:19"tell track id 35662set played date to date "10/30/2008 08:55:07"set played count to 70tell track id 39341set played date to date "11/01/2008 17:39:47"tell track id 40163tell track id 34832set played date to date "9/06/2008 19:04:47"tell track id 34986set played date to date "10/28/2008 12:51:44"tell track id 34465set played date to date "8/29/2008 13:52:10"tell track id 36099set played date to date "10/09/2008 18:15:56"tell track id 32762set played date to date "10/31/2008 08:26:20"tell track id 36552set played date to date "6/01/2008 12:29:36"tell track id 32882set played date to date "5/14/2008 08:22:37"tell track id 35009tell track id 35129set played date to date "10/29/2008 07:04:50"tell track id 31196tell track id 35407set played date to date "5/15/2008 05:06:43"tell track id 40175set played date to date "10/01/2008 11:54:17"tell track id 34360set played date to date "8/08/2008 21:32:44"tell track id 41132set played date to date "10/31/2008 08:20:35"tell track id 34328set played date to date "5/15/2008 01:53:50"tell track id 31408tell track id 41856set played date to date "10/25/2008 10:00:38"tell track id 41650set played date to date "10/29/2008 09:09:47"tell track id 41173tell track id 36722set played date to date "10/04/2008 18:47:25"tell track id 31197set played date to date "6/09/2008 15:19:49"tell track id 39106set played date to date "11/01/2008 06:37:02"tell track id 39282tell track id 40383set played date to date "10/03/2008 06:53:13"tell track id 34299set played date to date "10/04/2008 20:44:55"tell track id 37720set played date to date "9/13/2008 16:12:25"set played count to 56tell track id 42583tell track id 35845set played date to date "9/26/2008 15:08:32"tell track id 31479set played date to date "5/10/2008 14:13:53"tell track id 39931set played date to date "10/25/2008 08:21:18"tell track id 40378set played date to date "5/02/2008 05:07:28"tell track id 36026set played date to date "10/03/2008 01:19:26"tell track id 35773set played date to date "10/28/2008 13:16:41"tell track id 34470set played date to date "9/14/2008 04:31:21"tell track id 41859set played date to date "9/17/2008 13:46:32"tell track id 40732tell track id 39678set played date to date "6/21/2008 15:27:32"tell track id 36686tell track id 40386set played date to date "6/15/2008 19:30:40"tell track id 38251set played date to date "6/01/2008 14:25:32"tell track id 39105set played date to date "9/26/2008 12:32:40"tell track id 42455set played date to date "8/25/2008 18:48:11"tell track id 42821set played date to date "6/15/2008 22:46:52"tell track id 31422set played date to date "5/02/2008 13:08:53"tell track id 38352tell track id 40402tell track id 43147set played date to date "6/06/2008 09:09:07"tell track id 38496set played date to date "11/03/2008 04:20:10"tell track id 39747tell track id 34237set played date to date "6/21/2008 12:46:58"tell track id 42161tell track id 35197tell track id 38374tell track id 42606set played date to date "5/02/2008 07:17:46"tell track id 36696set played date to date "7/22/2008 16:13:35"tell track id 31329tell track id 37368set played date to date "7/03/2008 18:04:52"tell track id 38673tell track id 38813set played date to date "11/03/2008 05:01:31"tell track id 37703tell track id 37063set played date to date "9/25/2008 22:05:53"tell track id 42823tell track id 38010tell track id 33437set played date to date "6/05/2008 00:31:30"tell track id 42207set played date to date "8/06/2008 02:20:10"tell track id 35057set played date to date "10/29/2008 13:43:08"tell track id 40219set played date to date "8/08/2008 13:25:05"tell track id 33648set played date to date "5/13/2008 13:10:41"tell track id 31453set played date to date "10/09/2008 16:49:24"tell track id 41125set played date to date "7/30/2008 01:56:50"tell track id 34485set played date to date "8/07/2008 17:00:14"tell track id 33638set played date to date "11/03/2008 04:44:19"tell track id 42914tell track id 39277tell track id 42672set played date to date "5/12/2008 11:01:39"tell track id 31417set played date to date "8/14/2008 15:45:22"tell track id 35291set played date to date "6/14/2008 07:32:29"tell track id 31237set played date to date "8/14/2008 16:16:22"tell track id 41659set played date to date "10/29/2008 11:32:32"tell track id 39722set played date to date "6/21/2008 11:44:19"tell track id 41976set played date to date "5/10/2008 09:10:20"tell track id 41965tell track id 33792set played date to date "8/23/2008 12:59:04"tell track id 41127set played date to date "6/01/2008 14:44:06"tell track id 32589set played date to date "5/02/2008 10:40:38"tell track id 36916set played date to date "5/11/2008 17:29:34"tell track id 34352set played date to date "8/26/2008 15:43:11"tell track id 31709tell track id 33105set played date to date "9/13/2008 09:16:55"tell track id 35241tell track id 34852set played date to date "6/14/2008 05:25:30"tell track id 42896set played date to date "5/06/2008 06:20:30"tell track id 39127set played date to date "10/29/2008 04:53:24"tell track id 32794tell track id 32367set played date to date "11/01/2008 06:08:41"tell track id 31200set played date to date "11/01/2008 05:11:10"tell track id 42971set played date to date "9/13/2008 10:12:11"tell track id 39676set played date to date "5/28/2008 23:23:09"tell track id 39202set played date to date "6/16/2008 04:57:58"tell track id 40276set played date to date "11/03/2008 05:45:46"tell track id 40543set played date to date "5/17/2008 08:07:58"set played count to 83tell track id 41622set played date to date "10/30/2008 08:35:43"tell track id 38359set played date to date "5/14/2008 05:22:13"tell track id 32532set played date to date "6/21/2008 13:25:25"tell track id 32297set played date to date "8/08/2008 22:26:35"tell track id 36909set played date to date "5/13/2008 07:28:48"tell track id 35995tell track id 34089set played date to date "10/29/2008 09:24:44"tell track id 40455tell track id 39099set played date to date "9/13/2008 15:31:58"tell track id 41046tell track id 32658set played date to date "6/14/2008 08:14:26"tell track id 41247set played date to date "5/02/2008 01:07:38"tell track id 33434set played date to date "10/29/2008 14:25:21"tell track id 39729set played date to date "10/10/2008 01:38:53"tell track id 41128set played date to date "6/10/2008 12:10:15"tell track id 39128set played date to date "6/02/2008 16:42:40"tell track id 36361set played date to date "8/25/2008 20:24:20"tell track id 42442set played date to date "5/02/2008 04:26:45"tell track id 33974set played date to date "11/01/2008 06:25:30"tell track id 34316set played date to date "10/30/2008 07:53:17"tell track id 32819set played date to date "4/29/2008 04:13:48"tell track id 34053set played date to date "9/17/2008 15:35:13"tell track id 31156set played date to date "10/29/2008 04:45:57"tell track id 32769set played date to date "10/27/2008 05:32:49"tell track id 35759tell track id 33955set played date to date "4/28/2008 10:19:35"tell track id 33304set played date to date "9/15/2008 17:07:53"tell track id 38930set played date to date "4/28/2008 13:49:04"tell track id 33178set played date to date "11/03/2008 03:02:46"tell track id 31388set played date to date "5/01/2008 05:35:30"tell track id 39851set played date to date "10/29/2008 11:47:54"tell track id 38697set played date to date "10/30/2008 08:40:21"tell track id 38482set played date to date "6/15/2008 22:03:57"tell track id 36624set played date to date "5/02/2008 00:02:38"tell track id 39137set played date to date "11/03/2008 05:53:35"tell track id 41175set played date to date "5/15/2008 05:02:19"tell track id 39245tell track id 43238tell track id 40932tell track id 35353set played date to date "5/03/2008 04:16:24"tell track id 36641set played date to date "5/11/2008 00:16:06"tell track id 38447tell track id 35285set played date to date "9/14/2008 04:11:33"tell track id 31134tell track id 32414set played date to date "7/21/2008 21:41:17"tell track id 36959set played date to date "5/01/2008 15:55:01"tell track id 38018set played date to date "10/29/2008 09:18:17"tell track id 32711set played date to date "9/12/2008 00:01:55"tell track id 38881set played date to date "6/15/2008 21:03:47"tell track id 35007set played date to date "5/13/2008 14:52:40"tell track id 33540set played date to date "8/23/2008 20:46:25"tell track id 43150set played date to date "10/25/2008 09:50:33"tell track id 34433tell track id 36791tell track id 42574tell track id 34211set played date to date "5/21/2008 17:14:50"tell track id 33198set played date to date "6/09/2008 07:08:55"tell track id 41957set played date to date "10/24/2008 17:16:13"tell track id 33709set played date to date "9/20/2008 16:30:28"tell track id 35315set played date to date "6/15/2008 17:27:32"tell track id 31458set played date to date "6/15/2008 16:20:21"tell track id 36032set played date to date "7/24/2008 17:15:25"tell track id 31757set played date to date "8/21/2008 19:07:58"tell track id 31403tell track id 42624set played date to date "5/13/2008 11:00:19"tell track id 33314set played date to date "10/29/2008 08:41:21"tell track id 42332set played date to date "9/25/2008 21:15:43"tell track id 42603set played date to date "10/27/2008 05:14:21"tell track id 35756tell track id 42936set played date to date "7/29/2008 23:19:18"set played count to 73tell track id 42159set played date to date "6/05/2008 13:27:35"tell track id 40171set played date to date "11/01/2008 07:33:13"tell track id 39596tell track id 34216set played date to date "6/05/2008 12:44:14"tell track id 42907set played date to date "11/03/2008 02:13:56"tell track id 39315set played date to date "11/03/2008 01:42:51"tell track id 41693set played date to date "10/29/2008 09:06:29"tell track id 39382tell track id 38643set played date to date "10/29/2008 13:05:21"tell track id 31734set played date to date "10/26/2008 03:20:37"tell track id 34325set played date to date "5/13/2008 14:11:13"tell track id 37796tell track id 36738set played date to date "7/10/2008 22:30:31"tell track id 36947set played date to date "6/06/2008 07:58:06"tell track id 40966set played date to date "5/02/2008 11:15:00"tell track id 40977set played date to date "10/26/2008 04:22:53"tell track id 32404set played date to date "9/13/2008 12:17:18"tell track id 31850set played date to date "5/12/2008 04:34:44"tell track id 32585set played date to date "8/21/2008 14:22:48"tell track id 36029set played date to date "11/03/2008 03:38:06"tell track id 43337set played date to date "9/14/2008 04:05:42"tell track id 31210set played date to date "6/16/2008 07:23:12"tell track id 31217tell track id 41011set played date to date "10/29/2008 10:17:14"tell track id 34671set played date to date "8/08/2008 22:30:04"tell track id 32547set played date to date "8/26/2008 18:23:48"tell track id 42716set played date to date "6/11/2008 04:26:43"tell track id 32849set played date to date "6/16/2008 05:43:33"tell track id 36688set played date to date "5/14/2008 03:12:08"tell track id 36699tell track id 36796set played date to date "10/26/2008 02:54:46"tell track id 33117set played date to date "8/05/2008 10:36:35"tell track id 34058set played date to date "8/08/2008 21:37:11"tell track id 41306set played date to date "8/06/2008 02:33:58"tell track id 38427set played date to date "5/15/2008 03:02:40"tell track id 33491tell track id 33110set played date to date "10/25/2008 10:31:03"tell track id 34394set played date to date "8/07/2008 16:29:24"tell track id 37012set played date to date "10/01/2008 11:11:29"tell track id 36674set played date to date "6/21/2008 09:55:55"tell track id 42256set played date to date "6/21/2008 15:22:48"tell track id 38587set played date to date "5/11/2008 15:00:43"tell track id 35851set played date to date "10/24/2008 18:10:23"tell track id 34505set played date to date "10/29/2008 06:40:23"tell track id 33263set played date to date "9/14/2008 04:06:45"tell track id 37033set played date to date "5/25/2008 14:06:29"tell track id 36553set played date to date "6/16/2008 08:41:50"tell track id 33462set played date to date "5/01/2008 05:51:58"tell track id 37391tell track id 35340set played date to date "11/03/2008 04:15:09"tell track id 43109set played date to date "5/13/2008 11:48:28"tell track id 31394set played date to date "6/12/2008 05:24:08"tell track id 38800set played date to date "9/15/2008 16:32:16"tell track id 41042set played date to date "6/16/2008 07:47:30"tell track id 36449set played date to date "11/03/2008 04:48:28"tell track id 36805set played date to date "5/03/2008 05:13:25"tell track id 35844tell track id 36681set played date to date "5/13/2008 13:39:16"tell track id 38013set played date to date "5/11/2008 18:17:01"tell track id 37355set played date to date "11/03/2008 01:35:19"tell track id 35258tell track id 34857set played date to date "6/15/2008 18:14:37"tell track id 40153set played date to date "9/17/2008 17:28:43"tell track id 33439set played date to date "8/30/2008 22:17:58"tell track id 35061tell track id 32761set played date to date "9/14/2008 04:32:05"tell track id 37060tell track id 38455set played date to date "10/10/2008 01:22:04"tell track id 38942set played date to date "10/26/2008 03:02:14"tell track id 33546set played date to date "10/29/2008 08:18:34"tell track id 33247tell track id 40789set played date to date "10/29/2008 04:05:49"tell track id 32795set played date to date "5/06/2008 00:47:23"tell track id 34062set played date to date "10/23/2008 16:35:38"tell track id 36039set played date to date "8/25/2008 23:44:37"tell track id 38887set played date to date "10/25/2008 11:27:52"tell track id 41513tell track id 42628set played date to date "5/12/2008 17:34:17"tell track id 33480set played date to date "9/26/2008 05:18:46"tell track id 41002set played date to date "5/28/2008 05:39:31"tell track id 37719tell track id 33312set played date to date "8/21/2008 21:24:40"tell track id 33889set played date to date "5/23/2008 13:13:12"tell track id 31259tell track id 35132set played date to date "5/31/2008 00:00:00"tell track id 35280tell track id 38423set played date to date "5/03/2008 05:54:28"tell track id 41949set played date to date "10/29/2008 12:37:34"tell track id 36729tell track id 35854set played date to date "5/12/2008 04:23:38"tell track id 39308set played date to date "5/05/2008 06:13:40"tell track id 41057set played date to date "6/02/2008 15:32:13"tell track id 37524set played date to date "6/15/2008 20:59:52"tell track id 40606tell track id 42945set played date to date "5/01/2008 21:13:39"tell track id 38709tell track id 31220tell track id 35367set played date to date "5/02/2008 01:34:01"tell track id 37401set played date to date "9/26/2008 16:02:10"tell track id 34054set played date to date "4/28/2008 17:31:44"tell track id 36118set played date to date "10/03/2008 02:45:05"tell track id 33289set played date to date "5/11/2008 14:18:53"tell track id 41945set played date to date "5/24/2008 12:38:03"tell track id 35421set played date to date "6/15/2008 17:52:37"tell track id 34416tell track id 42976set played date to date "8/23/2008 19:15:56"tell track id 42677set played date to date "10/03/2008 03:34:51"tell track id 43129set played date to date "8/26/2008 21:53:33"tell track id 32321tell track id 33577tell track id 41106set played date to date "11/03/2008 05:38:14"tell track id 43261set played date to date "6/16/2008 04:12:56"tell track id 32890tell track id 32651tell track id 33965set played date to date "6/15/2008 22:16:58"tell track id 35521set played date to date "6/22/2008 11:22:44"tell track id 36723set played date to date "6/15/2008 17:17:15"tell track id 31424tell track id 38166set played date to date "6/21/2008 13:15:52"tell track id 34439tell track id 41114set played date to date "6/22/2008 09:01:01"tell track id 43143tell track id 34097tell track id 34829tell track id 31310set played date to date "7/11/2008 20:17:38"tell track id 39890set played date to date "5/12/2008 11:07:03"tell track id 34037set played date to date "5/03/2008 06:59:52"tell track id 42565tell track id 41012set played date to date "6/10/2008 07:02:30"tell track id 37980set played date to date "9/13/2008 14:07:14"tell track id 42169set played date to date "5/14/2008 06:55:01"tell track id 40166set played date to date "6/10/2008 15:22:25"tell track id 38965set played date to date "9/17/2008 17:44:38"tell track id 36915set played date to date "10/27/2008 07:08:37"tell track id 34796set played date to date "5/14/2008 05:51:57"tell track id 34578tell track id 42448tell track id 31195set played date to date "10/03/2008 01:26:17"tell track id 31128set played date to date "10/25/2008 12:05:02"tell track id 41862set played date to date "5/13/2008 12:27:55"tell track id 37365tell track id 35138set played date to date "10/01/2008 14:54:55"tell track id 42227set played date to date "5/13/2008 13:03:03"tell track id 39952set played date to date "6/15/2008 20:45:00"tell track id 38634set played date to date "7/25/2008 20:41:20"tell track id 42219set played date to date "10/29/2008 08:22:52"tell track id 43120tell track id 32432set played date to date "9/15/2008 17:43:50"tell track id 34310set played date to date "10/09/2008 15:45:43"tell track id 32626set played date to date "6/21/2008 11:13:55"tell track id 31241set played date to date "8/26/2008 06:24:59"tell track id 38884set played date to date "10/26/2008 04:32:37"tell track id 43411set played date to date "11/01/2008 06:54:52"tell track id 37220set played date to date "6/11/2008 14:02:27"tell track id 42805tell track id 42053tell track id 34088set played date to date "10/01/2008 12:54:50"tell track id 40554tell track id 36783set played date to date "6/16/2008 01:13:36"tell track id 40184set played date to date "11/01/2008 06:45:04"tell track id 34472set played date to date "9/13/2008 14:31:27"tell track id 39130set played date to date "10/01/2008 13:15:05"tell track id 36669set played date to date "11/03/2008 02:31:46"tell track id 31771set played date to date "11/03/2008 03:56:47"tell track id 37665set played date to date "11/01/2008 05:36:13"tell track id 38958set played date to date "6/07/2008 15:09:41"tell track id 35013tell track id 36747set played date to date "7/30/2008 02:33:37"tell track id 42922set played date to date "9/17/2008 13:05:51"tell track id 36016tell track id 31478set played date to date "6/01/2008 22:01:43"tell track id 39115set played date to date "6/09/2008 10:21:15"tell track id 38906set played date to date "5/23/2008 20:13:21"tell track id 39951set played date to date "8/23/2008 13:29:17"tell track id 41394set played date to date "6/22/2008 08:53:44"tell track id 43296set played date to date "9/15/2008 17:35:17"tell track id 34389set played date to date "10/30/2008 09:18:02"tell track id 43091tell track id 37353set played date to date "5/13/2008 10:11:55"tell track id 43322set played date to date "8/08/2008 17:13:11"tell track id 39924set played date to date "7/26/2008 23:19:01"tell track id 34113set played date to date "5/02/2008 07:21:09"tell track id 41958set played date to date "5/05/2008 09:05:55"tell track id 31189set played date to date "10/29/2008 04:32:22"tell track id 32784set played date to date "5/14/2008 12:13:35"tell track id 33293set played date to date "9/17/2008 17:49:25"tell track id 40570set played date to date "9/25/2008 19:24:50"tell track id 43081tell track id 34833set played date to date "8/08/2008 23:11:41"tell track id 33504set played date to date "11/03/2008 02:59:16"tell track id 36523set played date to date "5/03/2008 06:43:50"tell track id 41032set played date to date "7/25/2008 23:04:30"tell track id 36233set played date to date "6/10/2008 14:48:11"tell track id 38665set played date to date "10/29/2008 11:07:23"tell track id 34402set played date to date "10/02/2008 17:52:11"tell track id 41567set played date to date "10/27/2008 06:18:35"tell track id 35663set played date to date "10/02/2008 21:04:12"tell track id 42920set played date to date "6/06/2008 08:01:04"tell track id 36069set played date to date "5/26/2008 14:35:43"tell track id 41700set played date to date "8/08/2008 21:10:13"tell track id 40985set played date to date "10/25/2008 12:21:59"tell track id 41043set played date to date "8/26/2008 06:30:03"tell track id 34765set played date to date "6/21/2008 15:14:09"tell track id 34374tell track id 37217tell track id 33676set played date to date "5/11/2008 14:46:41"tell track id 33175set played date to date "10/03/2008 04:16:44"tell track id 41167set played date to date "6/10/2008 16:49:23"tell track id 39945set played date to date "9/25/2008 23:59:58"tell track id 38879set played date to date "6/21/2008 17:52:54"tell track id 33547tell track id 41205tell track id 32136tell track id 42077set played date to date "6/09/2008 09:45:53"tell track id 41975set played date to date "10/27/2008 07:54:00"tell track id 39716set played date to date "10/29/2008 10:31:52"tell track id 40737set played date to date "10/10/2008 00:16:52"tell track id 40555set played date to date "7/10/2008 19:34:43"tell track id 31473set played date to date "10/01/2008 14:57:55"tell track id 41966set played date to date "6/21/2008 11:22:31"tell track id 36113set played date to date "10/31/2008 08:22:54"tell track id 39735tell track id 41630set played date to date "10/29/2008 08:13:38"tell track id 37773set played date to date "5/13/2008 11:52:18"tell track id 33106set played date to date "7/05/2008 20:15:27"tell track id 42744tell track id 36408set played date to date "7/27/2008 15:51:59"tell track id 41395set played date to date "10/29/2008 12:01:29"tell track id 35140set played date to date "9/12/2008 02:38:48"tell track id 42785set played date to date "10/02/2008 17:44:32"tell track id 42740tell track id 42942set played date to date "5/24/2008 17:16:44"tell track id 39100set played count to 29tell track id 36484set played date to date "6/22/2008 09:04:31"tell track id 40081set played date to date "5/25/2008 05:57:10"tell track id 39201set played date to date "9/06/2008 21:14:16"tell track id 41131tell track id 42655set played date to date "10/27/2008 07:14:07"tell track id 34797set played date to date "6/15/2008 21:34:14"tell track id 33645set played date to date "10/01/2008 13:57:58"tell track id 40950set played date to date "11/03/2008 05:41:48"tell track id 34102set played date to date "6/16/2008 08:52:22"tell track id 31227tell track id 33794set played date to date "7/27/2008 16:34:59"tell track id 40573set played date to date "11/03/2008 02:55:11"tell track id 32104tell track id 36739set played date to date "11/01/2008 06:59:42"tell track id 38362set played date to date "10/01/2008 13:50:28"tell track id 36865tell track id 39329set played date to date "9/13/2008 11:28:50"tell track id 38660tell track id 39276tell track id 40962set played date to date "6/16/2008 05:47:43"tell track id 40177set played date to date "5/11/2008 03:44:31"tell track id 43146set played date to date "10/29/2008 10:38:15"tell track id 34447set played date to date "11/03/2008 03:33:38"tell track id 31330tell track id 41058set played date to date "6/21/2008 11:50:03"tell track id 38770set played date to date "10/29/2008 07:07:44"tell track id 32097set played date to date "8/06/2008 02:30:19"tell track id 33452set played date to date "4/28/2008 04:37:21"tell track id 41701set played date to date "11/03/2008 04:11:06"tell track id 37212tell track id 43029set played date to date "6/16/2008 02:25:25"tell track id 38860set played date to date "11/01/2008 07:20:32"tell track id 38894set played date to date "5/06/2008 08:37:45"tell track id 39119tell track id 43142tell track id 36784tell track id 34823set played date to date "6/22/2008 10:53:42"tell track id 32643tell track id 41485set played date to date "6/10/2008 15:58:43"tell track id 32908set played date to date "10/29/2008 04:33:55"tell track id 32776tell track id 35360tell track id 41049tell track id 42792tell track id 32127set played date to date "6/15/2008 19:47:27"tell track id 39959set played date to date "5/12/2008 08:30:57"set played count to 32tell track id 38155tell track id 33943set played date to date "6/16/2008 06:49:08"tell track id 37373tell track id 40996set played date to date "5/11/2008 17:35:24"tell track id 41124set played date to date "10/29/2008 06:03:04"tell track id 40837set played date to date "5/11/2008 03:31:27"tell track id 43106set played date to date "11/03/2008 01:59:50"tell track id 41644tell track id 34234set played date to date "6/21/2008 17:00:38"tell track id 38934set played date to date "7/19/2008 21:26:20"tell track id 42160set played date to date "6/10/2008 16:52:46"tell track id 42224tell track id 42747set played date to date "10/29/2008 10:03:47"tell track id 42917tell track id 33315set played date to date "5/13/2008 11:57:04"tell track id 38968set played date to date "5/01/2008 20:11:19"tell track id 42815set played date to date "9/15/2008 15:50:53"tell track id 33503tell track id 38754set played date to date "6/21/2008 10:09:53"tell track id 36817tell track id 33967set played date to date "5/01/2008 02:42:59"tell track id 35785set played date to date "6/21/2008 11:09:00"tell track id 36704tell track id 42770set played date to date "11/01/2008 04:40:45"tell track id 33719set played date to date "5/15/2008 02:47:13"tell track id 31410tell track id 34229set played date to date "6/06/2008 20:37:35"tell track id 35316set played date to date "5/13/2008 11:29:15"tell track id 40265set played date to date "5/14/2008 06:51:34"tell track id 35240set played date to date "5/15/2008 05:17:31"tell track id 32934set played date to date "5/21/2008 17:38:21"tell track id 40057set played date to date "10/27/2008 08:29:32"tell track id 39723set played date to date "10/01/2008 11:25:37"tell track id 40456set played date to date "6/22/2008 11:28:45"tell track id 34215set played date to date "10/29/2008 08:49:06"tell track id 42937set played date to date "6/16/2008 04:31:50"tell track id 33771set played date to date "9/26/2008 13:44:04"tell track id 34324set played date to date "8/26/2008 05:17:16"tell track id 31340set played date to date "9/04/2008 16:30:49"tell track id 40172set played date to date "11/03/2008 05:49:55"tell track id 33723tell track id 43014set played date to date "5/14/2008 03:41:35"tell track id 33435set played date to date "6/16/2008 01:35:04"tell track id 34411set played date to date "11/03/2008 01:32:35"tell track id 41493set played date to date "6/15/2008 22:26:44"tell track id 39366set played date to date "6/11/2008 13:42:09"tell track id 33674set played date to date "10/29/2008 06:32:38"tell track id 39148set played date to date "10/25/2008 10:19:55"tell track id 31593tell track id 31216tell track id 41956tell track id 36768set played date to date "6/15/2008 21:27:36"tell track id 42898tell track id 42615tell track id 39677tell track id 40432set played date to date "11/01/2008 04:57:08"tell track id 31605set played date to date "5/15/2008 04:12:49"tell track id 41094set played date to date "10/29/2008 13:35:31"tell track id 42413set played date to date "10/25/2008 11:32:42"tell track id 32638set played date to date "10/03/2008 01:29:28"tell track id 31548set played date to date "6/15/2008 23:10:50"tell track id 32584tell track id 39278set played date to date "9/26/2008 14:17:03"tell track id 37799tell track id 35137set played date to date "5/10/2008 14:20:59"tell track id 43171tell track id 31211set played date to date "10/10/2008 00:24:05"tell track id 35519set played date to date "9/12/2008 01:06:56"tell track id 34666set played date to date "6/11/2008 09:25:42"tell track id 36689set played date to date "10/03/2008 09:40:10"tell track id 41148set played date to date "10/29/2008 06:23:50"tell track id 32645set played date to date "5/02/2008 09:16:42"tell track id 39249tell track id 31433set played date to date "5/24/2008 10:41:26"tell track id 41583set played date to date "5/05/2008 02:44:00"tell track id 40258set played date to date "6/16/2008 00:02:08"tell track id 35996set played date to date "6/21/2008 18:33:48"tell track id 40188tell track id 33187set played date to date "10/27/2008 05:36:25"tell track id 35760set played date to date "5/02/2008 10:49:23"tell track id 39932tell track id 33975set played date to date "10/29/2008 07:17:38"tell track id 42047set played date to date "11/03/2008 03:29:48"tell track id 37561set played date to date "5/13/2008 04:18:04"tell track id 40598tell track id 36780set played date to date "8/07/2008 22:30:30"tell track id 34953tell track id 33954set played date to date "6/15/2008 20:02:57"tell track id 34456tell track id 34858set played date to date "10/02/2008 22:20:29"tell track id 33539set played date to date "6/06/2008 08:09:42"tell track id 42578set played date to date "6/21/2008 11:31:06"tell track id 31454set played date to date "10/09/2008 23:02:38"tell track id 32582set played date to date "10/24/2008 19:15:49"tell track id 35635set played date to date "10/24/2008 15:41:30"tell track id 38690set played date to date "5/11/2008 19:41:36"tell track id 37825tell track id 42980set played date to date "9/11/2008 21:27:00"tell track id 38474set played date to date "6/15/2008 15:43:21"tell track id 32907tell track id 33762set played date to date "6/21/2008 16:09:32"tell track id 37772set played date to date "5/14/2008 03:21:33"tell track id 33640set played date to date "9/25/2008 21:02:35"tell track id 38243set played date to date "8/29/2008 13:44:42"tell track id 34423set played date to date "9/06/2008 16:57:08"tell track id 36700set played date to date "10/27/2008 04:15:36"tell track id 43417set played date to date "6/06/2008 17:29:26"tell track id 39250set played date to date "7/29/2008 18:38:23"tell track id 34429set played date to date "10/27/2008 08:22:04"tell track id 39721set played date to date "6/02/2008 18:20:16"tell track id 40724set played date to date "5/02/2008 10:09:55"tell track id 42927set played date to date "8/29/2008 14:24:53"tell track id 35613tell track id 35136set played date to date "6/15/2008 11:33:34"tell track id 42806set played date to date "5/11/2008 05:22:33"tell track id 43286set played date to date "5/11/2008 02:25:24"tell track id 43087set played date to date "5/16/2008 03:03:42"tell track id 35420tell track id 37351set played date to date "10/02/2008 23:32:11"tell track id 43125set played date to date "9/20/2008 14:37:23"tell track id 40537set played date to date "5/15/2008 04:46:59"tell track id 35279tell track id 32457set played date to date "4/26/2008 08:39:53"tell track id 32080set played date to date "8/05/2008 10:00:16"tell track id 42095set played date to date "9/20/2008 14:22:53"tell track id 43128set played date to date "5/01/2008 17:55:33"tell track id 38903tell track id 31561set played date to date "10/28/2008 14:30:28"tell track id 32324set played date to date "11/03/2008 02:39:41"tell track id 31915set played count to 28tell track id 36496set played date to date "5/03/2008 04:55:53"tell track id 32801set played date to date "10/26/2008 02:50:27"tell track id 34333tell track id 36764set played date to date "6/16/2008 07:55:52"tell track id 38957tell track id 34096tell track id 36735tell track id 42454set played date to date "8/14/2008 17:28:22"tell track id 35992set played date to date "6/22/2008 10:37:32"tell track id 43281set played date to date "10/26/2008 04:25:07"tell track id 38246tell track id 32656tell track id 32652set played date to date "11/03/2008 04:31:58"tell track id 34892set played date to date "5/13/2008 14:18:29"tell track id 38588set played date to date "5/27/2008 15:11:11"tell track id 40278tell track id 35255set played date to date "8/26/2008 20:27:50"tell track id 36957set played date to date "5/24/2008 08:51:21"tell track id 37366set played date to date "10/10/2008 00:38:08"tell track id 42562set played date to date "10/29/2008 06:48:58"tell track id 39345set played date to date "9/06/2008 19:30:38"tell track id 38901set played date to date "5/13/2008 07:51:47"tell track id 31451set played date to date "10/30/2008 09:22:53"tell track id 43260set played date to date "6/21/2008 19:15:07"tell track id 41121set played date to date "8/23/2008 16:04:32"set played count to 90tell track id 33179set played date to date "5/28/2008 04:12:02"tell track id 33121set played date to date "10/29/2008 05:44:38"tell track id 32826set played date to date "5/01/2008 04:42:07"tell track id 42132tell track id 35283set played date to date "10/01/2008 13:02:30"tell track id 41781set played date to date "6/15/2008 17:00:03"tell track id 41301set played date to date "7/22/2008 17:55:24"tell track id 40720tell track id 41001set played date to date "10/25/2008 08:24:52"tell track id 33887set played date to date "10/27/2008 08:51:29"tell track id 39724set played date to date "5/13/2008 05:10:45"tell track id 35850set played date to date "8/21/2008 16:20:44"tell track id 41150set played date to date "5/10/2008 11:00:24"tell track id 37392tell track id 43144tell track id 34202set played date to date "6/16/2008 00:24:05"tell track id 42218tell track id 37342set played date to date "6/14/2008 05:43:04"tell track id 33461tell track id 31481set played date to date "5/20/2008 06:05:24"tell track id 37343tell track id 36795set played date to date "10/24/2008 14:37:41"tell track id 34971set played date to date "6/01/2008 20:04:22"tell track id 39926set played date to date "5/26/2008 05:26:58"tell track id 37718tell track id 33950tell track id 35998set played date to date "5/01/2008 20:14:49"tell track id 39113set played date to date "6/13/2008 18:14:49"tell track id 42822set played date to date "7/27/2008 16:26:52"tell track id 41054set played date to date "6/15/2008 11:38:54"tell track id 40183set played date to date "10/24/2008 17:56:22"tell track id 40200set played date to date "6/21/2008 19:09:08"tell track id 34362set played date to date "8/26/2008 05:25:06"tell track id 34187tell track id 35131tell track id 32644set played date to date "9/13/2008 14:02:53"tell track id 40949set played date to date "8/23/2008 22:12:47"tell track id 35058set played date to date "5/11/2008 00:20:51"tell track id 40385set played date to date "5/20/2008 17:44:32"tell track id 38353set played date to date "6/16/2008 08:28:51"tell track id 36708set played date to date "5/10/2008 16:25:55"tell track id 33580set played date to date "5/01/2008 16:35:25"tell track id 40266set played date to date "5/28/2008 23:50:01"tell track id 33111set played date to date "10/30/2008 08:31:50"tell track id 38882set played date to date "5/01/2008 16:02:24"tell track id 33689set played date to date "6/21/2008 09:08:04"tell track id 35852tell track id 31820set played date to date "10/28/2008 13:34:14"tell track id 35423set played date to date "5/26/2008 04:42:03"tell track id 34393set played date to date "7/10/2008 20:13:44"tell track id 31463set played date to date "5/13/2008 10:17:42"tell track id 40565set played date to date "5/12/2008 10:14:06"tell track id 37469set played date to date "11/03/2008 05:26:02"tell track id 32040set played date to date "10/25/2008 11:46:28"tell track id 37354set played date to date "5/18/2008 05:07:28"tell track id 42165set played date to date "11/01/2008 06:49:17"tell track id 39146tell track id 38724tell track id 31483set played date to date "9/25/2008 19:41:16"tell track id 35292set played date to date "6/22/2008 11:07:32"tell track id 43090tell track id 32130set played date to date "10/02/2008 22:24:19"set played count to 57tell track id 35993set played date to date "8/25/2008 20:11:27"tell track id 41166set played date to date "6/16/2008 00:16:05"tell track id 38854set played date to date "4/28/2008 12:39:07"tell track id 39940set played date to date "8/25/2008 19:07:33"tell track id 33333set played date to date "9/25/2008 21:53:18"tell track id 37804set played date to date "5/12/2008 08:34:52"tell track id 41200set played date to date "6/22/2008 09:58:35"tell track id 42595set played date to date "5/15/2008 03:18:02"tell track id 41486set played date to date "5/05/2008 03:19:43"tell track id 33450set played date to date "9/06/2008 20:24:38"tell track id 34365set played date to date "7/11/2008 20:33:20"tell track id 40827set played date to date "10/29/2008 14:17:48"tell track id 36799set played date to date "10/03/2008 05:48:28"tell track id 35318set played date to date "9/13/2008 10:37:52"tell track id 34176set played date to date "5/15/2008 04:08:05"tell track id 40888set played date to date "9/13/2008 12:33:58"tell track id 40571set played date to date "10/01/2008 14:35:57"tell track id 41305set played date to date "10/03/2008 04:54:43"tell track id 40375tell track id 34818tell track id 35337set played date to date "6/16/2008 08:45:55"tell track id 41941set played date to date "6/21/2008 09:34:08"tell track id 34373tell track id 39327set played date to date "10/24/2008 19:42:50"tell track id 34506tell track id 32478set played date to date "5/06/2008 08:54:37"tell track id 38657set played date to date "10/29/2008 12:55:42"tell track id 31608set played date to date "8/05/2008 09:55:54"tell track id 32725set played date to date "5/06/2008 14:55:31"tell track id 38025set played date to date "6/16/2008 00:20:33"tell track id 33675tell track id 37887tell track id 33787set played date to date "10/10/2008 01:41:51"tell track id 41155set played date to date "10/29/2008 12:45:04"tell track id 37663set played date to date "5/12/2008 05:48:41"tell track id 33484tell track id 38836set played date to date "6/15/2008 17:11:36"tell track id 34598tell track id 41626set played date to date "6/11/2008 04:08:39"tell track id 40715set played date to date "5/06/2008 10:58:24"tell track id 41925tell track id 35356set played date to date "5/15/2008 04:33:09"tell track id 38658set played date to date "10/27/2008 08:16:55"tell track id 39720tell track id 39337set played date to date "10/28/2008 14:00:19"tell track id 41003tell track id 42564tell track id 42612set played date to date "6/21/2008 12:32:23"tell track id 38577tell track id 33793set played date to date "10/29/2008 04:49:33"tell track id 32775set played date to date "6/16/2008 04:15:34"tell track id 36668set played date to date "10/27/2008 08:49:31"tell track id 39728set played date to date "5/13/2008 10:53:11"tell track id 38907tell track id 38560set played date to date "5/01/2008 15:19:17"tell track id 42674tell track id 42096set played date to date "6/11/2008 03:00:01"tell track id 35004set played date to date "9/26/2008 03:16:36"tell track id 42440set played date to date "9/25/2008 19:11:40"tell track id 33166set played date to date "6/11/2008 15:06:05"tell track id 41638set played date to date "5/13/2008 09:57:57"tell track id 37396set played date to date "6/11/2008 14:18:26"tell track id 33791tell track id 42857set played date to date "8/08/2008 18:39:58"tell track id 36013set played date to date "10/25/2008 08:54:30"tell track id 40154set played date to date "10/01/2008 11:57:36"tell track id 32534set played date to date "11/01/2008 06:13:30"tell track id 33471set played date to date "5/02/2008 02:09:49"tell track id 39116set played date to date "6/22/2008 09:49:45"tell track id 43156set played date to date "10/25/2008 11:37:05"tell track id 38481set played date to date "10/25/2008 12:57:19"tell track id 36124set played date to date "10/29/2008 08:02:29"tell track id 33790set played date to date "6/15/2008 18:23:59"tell track id 41950set played date to date "5/01/2008 05:58:13"tell track id 38959set played date to date "5/06/2008 07:45:32"tell track id 40795tell track id 38019set played date to date "10/26/2008 04:38:19"tell track id 43412set played date to date "6/21/2008 17:56:55"tell track id 34917set played date to date "7/21/2008 19:33:38"tell track id 34309tell track id 34824set played date to date "10/01/2008 13:07:24"tell track id 36450tell track id 43148set played date to date "9/13/2008 13:55:56"tell track id 40607tell track id 38387set played date to date "5/26/2008 23:06:50"tell track id 42127set played date to date "5/05/2008 05:20:19"tell track id 39111set played date to date "10/09/2008 21:11:21"tell track id 42108set played date to date "11/03/2008 01:56:02"tell track id 37091set played date to date "9/13/2008 15:42:50"tell track id 41993tell track id 34507set played date to date "8/30/2008 19:43:33"tell track id 38735tell track id 35339set played date to date "6/14/2008 05:39:29"set played count to 55tell track id 34115set played date to date "10/29/2008 12:19:04"tell track id 40984set played date to date "9/26/2008 01:29:54"set played count to 77tell track id 37433set played date to date "5/03/2008 13:13:30"tell track id 32581set played date to date "5/13/2008 11:38:47"tell track id 35287set played date to date "8/30/2008 22:54:50"tell track id 31338set played date to date "10/26/2008 02:57:44"tell track id 36521set played date to date "5/15/2008 03:06:02"tell track id 38016set played date to date "11/03/2008 02:35:04"tell track id 41616set played date to date "6/21/2008 18:26:59"tell track id 36033set played date to date "11/03/2008 02:18:33"tell track id 43079set played date to date "9/26/2008 14:33:24"tell track id 31610set played date to date "7/30/2008 01:13:52"tell track id 31769set played date to date "6/16/2008 02:54:05"tell track id 33448set played date to date "10/29/2008 09:38:54"tell track id 32427set played date to date "5/05/2008 06:21:09"tell track id 33481tell track id 35351set played date to date "5/03/2008 07:02:33"tell track id 42571set played date to date "10/30/2008 08:27:40"tell track id 33302set played date to date "5/02/2008 13:48:16"tell track id 36280set played date to date "11/01/2008 07:29:13"tell track id 39534tell track id 35335tell track id 42566set played date to date "5/26/2008 19:58:46"tell track id 36306set played date to date "8/06/2008 02:42:03"tell track id 33200set played date to date "5/02/2008 13:36:20"tell track id 39949set played date to date "10/29/2008 12:06:25"tell track id 41475set played date to date "6/09/2008 10:19:04"tell track id 37374tell track id 42926set played date to date "5/12/2008 07:38:47"tell track id 42143set played date to date "5/06/2008 07:05:34"tell track id 33176set played date to date "5/26/2008 07:26:30"tell track id 42325set played date to date "7/21/2008 21:33:15"tell track id 37215set played date to date "5/13/2008 07:19:00"tell track id 41589set played date to date "6/15/2008 14:58:42"tell track id 39365set played date to date "6/03/2008 15:07:57"tell track id 41918tell track id 43145set played date to date "9/20/2008 16:21:40"tell track id 35331set played date to date "10/10/2008 01:55:27"tell track id 41467set played date to date "10/28/2008 13:47:19"tell track id 38880set played date to date "5/01/2008 18:50:38"set played count to 74tell track id 38020set played date to date "5/13/2008 13:35:34"tell track id 41964set played date to date "5/10/2008 14:53:35"tell track id 37398set played date to date "9/17/2008 21:06:58"tell track id 39877tell track id 38170set played date to date "5/25/2008 04:19:21"tell track id 42780set played date to date "5/13/2008 16:14:36"tell track id 42137set played date to date "7/22/2008 12:09:47"tell track id 38576set played date to date "5/17/2008 11:48:10"tell track id 38511set played date to date "6/07/2008 14:19:04"tell track id 35616tell track id 42458tell track id 38661set played date to date "8/08/2008 18:26:20"tell track id 41469tell track id 38652set played date to date "5/11/2008 17:56:05"tell track id 35994set played date to date "10/29/2008 04:59:00"tell track id 32771set played date to date "5/13/2008 05:31:13"tell track id 37363set played date to date "5/12/2008 06:11:46"tell track id 36002tell track id 35341tell track id 42663set played date to date "9/13/2008 12:31:04"tell track id 34395set played date to date "6/15/2008 11:43:40"tell track id 39942set played date to date "9/13/2008 09:46:48"tell track id 32300tell track id 36236set played date to date "9/25/2008 19:29:05"tell track id 34709set played date to date "9/25/2008 22:18:19"tell track id 41171set played date to date "9/04/2008 18:52:09"tell track id 33456set played date to date "10/25/2008 08:43:42"tell track id 36222set played date to date "6/03/2008 13:41:15"tell track id 41722set played date to date "10/25/2008 09:54:05"tell track id 34359set played date to date "8/23/2008 19:33:06"tell track id 33862set played date to date "8/14/2008 19:40:19"tell track id 35520set played date to date "8/23/2008 19:05:20"tell track id 34702set played date to date "5/06/2008 07:23:35"tell track id 40600set played date to date "7/03/2008 17:07:30"tell track id 42802tell track id 38710set played date to date "6/16/2008 05:02:31"tell track id 36710set played date to date "9/13/2008 16:08:27"tell track id 34308set played date to date "11/01/2008 07:57:10"tell track id 35379set played date to date "10/25/2008 10:15:06"tell track id 38015set played date to date "10/01/2008 12:09:53"tell track id 34697set played date to date "10/09/2008 23:46:34"tell track id 38680set played date to date "6/14/2008 05:53:16"tell track id 32938tell track id 42916set played date to date "10/29/2008 08:52:58"tell track id 34323set played date to date "6/22/2008 08:57:41"tell track id 31480set played date to date "9/26/2008 00:42:02"tell track id 42453tell track id 36794set played date to date "5/11/2008 04:31:23"tell track id 38440set played date to date "5/07/2008 04:56:51"tell track id 35798tell track id 36238set played date to date "8/21/2008 18:19:50"tell track id 31455set played date to date "10/28/2008 13:42:43"tell track id 33467set played date to date "11/03/2008 01:29:39"tell track id 34071set played date to date "9/13/2008 15:50:40"tell track id 37400set played date to date "10/01/2008 13:39:39"tell track id 39954set played date to date "5/14/2008 12:20:32"tell track id 32853set played date to date "9/26/2008 03:49:56"tell track id 41152set played date to date "7/11/2008 21:36:39"tell track id 41623set played date to date "5/12/2008 10:07:32"tell track id 34378set played date to date "7/27/2008 15:48:26"tell track id 42791set played date to date "6/15/2008 18:47:37"tell track id 35637set played date to date "5/11/2008 00:29:19"tell track id 43292set played date to date "9/20/2008 14:19:20"tell track id 36254tell track id 34191set played date to date "5/02/2008 13:19:52"tell track id 33552set played date to date "10/03/2008 08:28:01"tell track id 34189set played date to date "5/02/2008 10:36:17"tell track id 38566set played date to date "6/16/2008 04:51:05"tell track id 40165tell track id 38635set played date to date "9/13/2008 12:46:51"tell track id 40546tell track id 36211set played date to date "9/13/2008 15:29:07"tell track id 32299set played date to date "6/07/2008 12:56:03"tell track id 41479set played date to date "10/29/2008 10:24:45"tell track id 32005tell track id 34839set played date to date "4/28/2008 13:33:24"tell track id 36276set played date to date "8/05/2008 10:04:36"tell track id 38919tell track id 36785set played date to date "5/03/2008 07:35:49"tell track id 38005set played date to date "6/09/2008 07:50:00"tell track id 35999set played date to date "5/03/2008 13:18:14"tell track id 42099set played date to date "5/14/2008 02:39:00"tell track id 41120tell track id 35349set played date to date "7/30/2008 00:40:25"tell track id 41159set played date to date "5/06/2008 07:31:53"tell track id 42101tell track id 42076set played date to date "5/02/2008 06:14:38"tell track id 31733set played date to date "5/11/2008 05:15:35"tell track id 36731tell track id 40382set played date to date "5/13/2008 05:14:29"tell track id 38578set played date to date "9/12/2008 00:32:30"tell track id 43098set played date to date "10/26/2008 03:39:51"tell track id 38956set played date to date "9/13/2008 09:06:56"tell track id 40878set played date to date "10/26/2008 03:28:59"tell track id 36776tell track id 34206set played date to date "10/27/2008 07:47:41"tell track id 39715set played date to date "6/02/2008 10:56:40"tell track id 42902tell track id 34095set played date to date "5/13/2008 06:06:04"tell track id 36448tell track id 42807tell track id 34221set played date to date "6/21/2008 12:24:14"tell track id 40197set played date to date "5/01/2008 14:58:39"tell track id 42899tell track id 42814set played date to date "5/02/2008 01:14:04"tell track id 35278set played date to date "8/04/2008 18:59:26"tell track id 35275set played date to date "10/31/2008 08:48:38"tell track id 43110set played date to date "10/24/2008 16:20:12"tell track id 35220set played date to date "10/09/2008 20:09:03"tell track id 31885tell track id 34856set played date to date "10/26/2008 03:23:27"tell track id 34091set played date to date "9/13/2008 14:58:27"tell track id 42189set played date to date "5/11/2008 05:28:03"tell track id 32657set played date to date "10/30/2008 06:36:58"tell track id 33708set played date to date "5/13/2008 10:56:36"tell track id 38502set played date to date "5/10/2008 13:40:20"tell track id 42117set played date to date "4/27/2008 09:10:07"tell track id 42221set played date to date "9/11/2008 18:24:01"tell track id 38889set played date to date "10/29/2008 13:46:54"tell track id 32095set played date to date "5/11/2008 03:25:15"tell track id 43172tell track id 34704set played date to date "9/04/2008 18:07:21"tell track id 36175set played date to date "9/06/2008 21:32:35"tell track id 32827set played date to date "5/01/2008 13:19:57"tell track id 36818set played date to date "6/15/2008 15:10:59"tell track id 34375set played date to date "10/29/2008 11:35:51"tell track id 42450set played date to date "7/03/2008 20:36:06"set played count to 68tell track id 33238set played date to date "11/01/2008 06:04:14"tell track id 43169set played date to date "6/15/2008 20:10:04"tell track id 41499set played date to date "10/25/2008 11:20:45"tell track id 40198set played date to date "5/01/2008 14:54:06"tell track id 39943set played date to date "10/02/2008 20:04:27"tell track id 33516set played date to date "9/17/2008 15:42:26"tell track id 37262tell track id 42918tell track id 39336set played date to date "5/12/2008 05:45:33"tell track id 34972tell track id 36405set played date to date "5/02/2008 05:03:45"tell track id 42111tell track id 32642set played date to date "6/22/2008 09:40:55"tell track id 43104tell track id 36248set played date to date "8/25/2008 23:48:45"tell track id 39255set played date to date "5/13/2008 10:26:26"tell track id 38962set played date to date "10/10/2008 00:13:35"tell track id 36951set played date to date "5/02/2008 09:53:48"tell track id 38040set played date to date "10/09/2008 16:59:43"tell track id 38695set played date to date "5/24/2008 13:11:26"tell track id 38675set played date to date "8/12/2008 17:41:04"tell track id 39383set played date to date "5/03/2008 12:33:12"tell track id 37766tell track id 36759set played date to date "11/01/2008 18:04:47"tell track id 42104set played date to date "9/11/2008 22:26:51"tell track id 39680tell track id 40384set played date to date "4/28/2008 10:45:36"tell track id 36031set played date to date "10/27/2008 05:40:51"tell track id 35761tell track id 43134set played date to date "10/24/2008 17:04:54"tell track id 39305tell track id 34225set played date to date "10/09/2008 14:34:14"tell track id 34707set played date to date "5/05/2008 04:59:23"tell track id 36638set played date to date "5/13/2008 05:55:17"tell track id 34592set played date to date "4/28/2008 08:26:07"tell track id 40182tell track id 33661set played date to date "5/02/2008 01:04:06"tell track id 38940tell track id 33944set played date to date "7/22/2008 15:15:02"tell track id 31148tell track id 38839tell track id 38945set played date to date "8/21/2008 14:14:28"tell track id 33538set played date to date "6/22/2008 11:33:16"tell track id 38458set played date to date "10/27/2008 05:54:53"tell track id 35658set played date to date "6/11/2008 06:46:21"tell track id 40260tell track id 38753set played date to date "11/01/2008 08:00:29"tell track id 33039set played date to date "6/01/2008 18:52:38"tell track id 41362set played date to date "5/10/2008 12:28:02"tell track id 34118set played date to date "10/29/2008 13:23:40"tell track id 33303tell track id 34412set played date to date "10/04/2008 17:57:16"tell track id 43107set played date to date "10/28/2008 12:55:24"tell track id 34466set played date to date "10/04/2008 17:14:44"tell track id 35221set played date to date "10/01/2008 16:11:42"tell track id 32852set played date to date "9/17/2008 15:19:46"tell track id 42817set played date to date "5/15/2008 02:29:51"tell track id 34055tell track id 34092set played date to date "10/29/2008 09:36:23"tell track id 34067tell track id 39852set played date to date "11/03/2008 01:47:02"tell track id 43240set played date to date "10/03/2008 00:01:45"tell track id 38597set played date to date "6/07/2008 15:22:28"tell track id 40601set played date to date "5/25/2008 05:41:09"tell track id 37465set played date to date "9/19/2008 16:41:37"tell track id 42576set played date to date "6/21/2008 16:05:12"tell track id 40893set played date to date "6/15/2008 23:30:40"tell track id 31214set played date to date "11/03/2008 04:01:21"tell track id 39343set played date to date "6/03/2008 12:44:48"tell track id 33554set played date to date "9/12/2008 03:07:51"tell track id 35293set played date to date "5/12/2008 07:03:05"tell track id 39248set played date to date "8/08/2008 15:38:37"tell track id 41822tell track id 42155tell track id 37889set played date to date "5/11/2008 16:27:34"tell track id 37468set played date to date "6/15/2008 18:01:04"tell track id 41668tell track id 36255set played date to date "6/21/2008 13:45:33"tell track id 33239set played date to date "10/25/2008 08:50:56"tell track id 41177set played date to date "9/26/2008 17:47:30"tell track id 41698set played date to date "9/06/2008 21:20:55"tell track id 42586set played date to date "10/25/2008 09:46:29"tell track id 41955set played date to date "10/29/2008 11:20:28"tell track id 32946set played date to date "10/25/2008 11:41:42"tell track id 35516tell track id 38314set played date to date "10/09/2008 17:14:03"tell track id 43403tell track id 42622set played date to date "10/23/2008 16:31:43"tell track id 37187set played date to date "5/12/2008 09:41:37"tell track id 38631set played date to date "8/14/2008 18:57:40"tell track id 35317set played date to date "6/02/2008 15:46:44"tell track id 31965tell track id 34180set played date to date "7/09/2008 18:57:09"tell track id 39883set played date to date "8/08/2008 17:50:51"tell track id 41048set played date to date "5/13/2008 07:53:21"tell track id 39124set played date to date "9/14/2008 04:03:59"tell track id 39266set played date to date "6/16/2008 01:02:32"tell track id 43245set played date to date "6/11/2008 13:33:33"tell track id 42582set played date to date "5/04/2008 03:24:22"tell track id 32772set played date to date "10/29/2008 10:35:37"set played count to 60tell track id 42897tell track id 41014tell track id 34222set played date to date "8/26/2008 16:09:00"set played count to 85tell track id 36684tell track id 35343tell track id 40138set played date to date "5/14/2008 03:25:00"tell track id 41034set played date to date "9/17/2008 18:19:03"tell track id 38828set played date to date "10/30/2008 07:56:44"tell track id 41473set played date to date "10/31/2008 08:52:52"tell track id 31381set played date to date "5/01/2008 17:19:40"tell track id 36646set played date to date "9/04/2008 15:15:55"tell track id 37759set played date to date "7/25/2008 20:46:21"tell track id 33425set played date to date "6/05/2008 00:39:10"tell track id 38414tell track id 34194set played date to date "5/27/2008 13:05:04"tell track id 37602set played date to date "6/09/2008 09:02:43"tell track id 43236tell track id 38638set played date to date "6/10/2008 13:49:07"tell track id 39956set played date to date "10/28/2008 14:12:17"tell track id 36367set played date to date "5/04/2008 05:17:07"tell track id 39121set played date to date "10/03/2008 09:21:12"tell track id 34160set played date to date "7/03/2008 21:34:20"tell track id 31946set played date to date "5/26/2008 21:27:46"tell track id 36009set played date to date "6/12/2008 16:20:09"tell track id 33236set played date to date "7/03/2008 20:13:45"tell track id 33665set played date to date "10/30/2008 09:08:35"tell track id 37646set played date to date "8/26/2008 19:04:02"tell track id 41879set played date to date "7/20/2008 14:19:33"tell track id 42818tell track id 42860set played date to date "10/02/2008 17:20:55"tell track id 43054set played date to date "6/14/2008 07:35:00"tell track id 32301tell track id 36251set played date to date "5/24/2008 11:50:20"tell track id 40017set played date to date "6/16/2008 03:48:39"tell track id 36709set played date to date "5/05/2008 02:31:48"tell track id 32782set played date to date "5/02/2008 03:35:38"tell track id 38021set played date to date "6/10/2008 12:36:29"tell track id 41974set played date to date "5/11/2008 04:06:05"tell track id 40282set played date to date "6/15/2008 17:24:56"tell track id 42164set played date to date "10/25/2008 12:40:48"tell track id 34110tell track id 36771set played date to date "5/02/2008 05:21:02"tell track id 35289set played date to date "5/06/2008 02:11:41"tell track id 36715set played date to date "10/29/2008 08:37:51"tell track id 42934set played date to date "10/27/2008 06:23:33"tell track id 35664tell track id 41365set played date to date "10/03/2008 05:12:14"tell track id 42940set played date to date "6/14/2008 07:14:24"tell track id 41248set played date to date "9/15/2008 17:15:31"tell track id 41246set played date to date "5/28/2008 07:00:07"tell track id 37593set played date to date "10/27/2008 05:04:03"tell track id 35919tell track id 31226set played date to date "6/22/2008 10:10:57"tell track id 43135tell track id 32131set played date to date "10/31/2008 08:56:08"tell track id 43126set played date to date "11/03/2008 03:12:34"tell track id 40361set played date to date "5/02/2008 02:08:35"tell track id 37375set played date to date "10/25/2008 12:18:56"tell track id 38902set played date to date "10/29/2008 10:42:42"tell track id 31746set played date to date "6/03/2008 06:39:22"tell track id 39140tell track id 42664tell track id 42178tell track id 31596set played date to date "5/14/2008 05:47:43"tell track id 35003tell track id 33449set played date to date "7/21/2008 19:21:41"tell track id 33725set played date to date "11/03/2008 05:30:05"tell track id 32054tell track id 35254set played date to date "10/01/2008 15:35:12"tell track id 37393set played date to date "11/03/2008 05:34:22"tell track id 39326tell track id 41482set played date to date "6/21/2008 18:55:05"tell track id 42444tell track id 39101set played date to date "5/06/2008 02:31:40"tell track id 42097tell track id 31202set played date to date "4/26/2008 07:21:31"tell track id 42269set played date to date "5/26/2008 07:33:23"tell track id 33459set played date to date "5/15/2008 05:28:05"tell track id 35618tell track id 35195set played date to date "8/07/2008 02:41:01"tell track id 31383set played date to date "8/14/2008 14:41:23"tell track id 42786set played date to date "5/02/2008 06:18:48"tell track id 32929set played date to date "6/21/2008 10:16:05"tell track id 34599set played date to date "9/13/2008 10:15:53"tell track id 34372set played date to date "5/15/2008 05:41:54"tell track id 39925set played date to date "5/03/2008 07:51:17"tell track id 33457set played date to date "10/29/2008 13:14:11"tell track id 35598set played date to date "10/29/2008 11:14:33"tell track id 37297set played date to date "8/07/2008 20:07:04"tell track id 37588set played date to date "6/16/2008 01:38:12"tell track id 31601set played date to date "5/11/2008 15:35:20"tell track id 38565set played date to date "8/25/2008 22:42:10"tell track id 38421set played date to date "11/01/2008 04:36:07"tell track id 37218tell track id 34828set played date to date "10/28/2008 14:15:47"tell track id 41522set played date to date "9/26/2008 18:13:09"tell track id 31710tell track id 36748tell track id 32296set played date to date "10/01/2008 16:02:26"tell track id 37364set played date to date "4/26/2008 07:13:15"tell track id 37431set played date to date "5/14/2008 06:12:43"tell track id 41590set played date to date "10/29/2008 05:05:50"tell track id 39693tell track id 42933set played date to date "5/13/2008 08:07:50"tell track id 33945set played date to date "5/01/2008 16:52:36"tell track id 42443set played date to date "6/21/2008 11:19:39"tell track id 33282tell track id 41005set played date to date "10/01/2008 13:29:35"tell track id 34387tell track id 36235set played date to date "8/24/2008 03:00:18"tell track id 38916set played date to date "5/13/2008 07:44:38"tell track id 40936set played date to date "6/21/2008 14:32:09"tell track id 34453set played date to date "6/15/2008 17:55:25"tell track id 34691set played date to date "5/10/2008 14:30:26"tell track id 38646tell track id 31496set played date to date "5/02/2008 04:22:07"tell track id 39142set played date to date "10/28/2008 14:18:54"tell track id 37532set played date to date "9/15/2008 16:50:09"tell track id 32312set played date to date "10/01/2008 12:46:50"tell track id 32557set played date to date "6/05/2008 00:43:20"tell track id 41053set played date to date "5/12/2008 09:36:26"tell track id 39112set played date to date "11/01/2008 05:30:24"tell track id 37284set played date to date "10/24/2008 16:37:24"tell track id 31969set played date to date "10/03/2008 06:14:24"tell track id 38890set played date to date "8/26/2008 19:00:24"tell track id 41994set played date to date "6/21/2008 13:29:15"tell track id 40889tell track id 34094tell track id 42009set played date to date "9/04/2008 20:59:09"tell track id 36717set played date to date "6/02/2008 11:17:47"tell track id 36964set played date to date "6/15/2008 18:17:12"tell track id 38655tell track id 31484set played date to date "7/26/2008 21:50:37"tell track id 40636set played date to date "8/08/2008 20:14:11"tell track id 36800tell track id 36770set played date to date "9/13/2008 14:46:10"tell track id 40036set played date to date "6/09/2008 08:58:12"tell track id 40376set played date to date "5/02/2008 02:54:13"tell track id 43099set played date to date "9/06/2008 19:36:37"tell track id 32289set played date to date "9/14/2008 04:27:08"tell track id 37434set played date to date "5/02/2008 10:32:08"tell track id 42131set played date to date "10/26/2008 04:54:47"tell track id 43415set played date to date "5/03/2008 12:49:17"tell track id 31224set played date to date "9/11/2008 18:42:22"tell track id 41162tell track id 35354tell track id 42570set played date to date "10/31/2008 08:34:19"tell track id 36522set played date to date "5/12/2008 07:22:17"tell track id 35284set played date to date "8/26/2008 20:43:48"tell track id 40535set played date to date "10/01/2008 11:46:14"tell track id 33482tell track id 40943set played date to date "5/11/2008 04:59:40"tell track id 43119set played date to date "10/27/2008 06:41:32"tell track id 34791set played date to date "5/01/2008 13:14:10"tell track id 39937set played date to date "10/29/2008 12:23:53"tell track id 39533tell track id 31447set played date to date "10/29/2008 11:56:43"tell track id 35628set played date to date "6/16/2008 03:30:06"tell track id 41968set played date to date "8/25/2008 19:03:04"tell track id 38248set played date to date "4/26/2008 06:56:29"tell track id 39950set played date to date "7/05/2008 19:57:17"tell track id 37715set played date to date "10/09/2008 14:07:19"tell track id 41978set played date to date "11/01/2008 06:28:55"tell track id 36410set played date to date "6/22/2008 08:50:22"tell track id 43127set played date to date "6/16/2008 04:39:51"tell track id 38506set played date to date "10/27/2008 09:03:09"tell track id 37291set played date to date "5/02/2008 01:30:17"tell track id 41309set played date to date "5/11/2008 04:24:42"tell track id 34207set played date to date "9/17/2008 17:33:52"tell track id 33886tell track id 41723set played date to date "5/10/2008 12:55:39"tell track id 36000set played date to date "6/15/2008 18:52:16"tell track id 42110set played date to date "5/06/2008 00:55:09"tell track id 42491set played date to date "10/27/2008 08:58:04"tell track id 38591tell track id 32134set played date to date "5/02/2008 07:07:27"tell track id 36822set played date to date "10/27/2008 07:44:16"tell track id 39714tell track id 37099set played date to date "6/21/2008 14:18:02"tell track id 38944set played date to date "6/07/2008 13:00:06"tell track id 32927set played date to date "5/12/2008 06:00:12"tell track id 40160set played date to date "5/10/2008 13:02:13"tell track id 38035set played date to date "6/01/2008 23:54:34"tell track id 41480set played date to date "5/02/2008 04:06:48"tell track id 41944set played date to date "6/21/2008 10:24:48"tell track id 41249set played date to date "5/11/2008 02:37:01"tell track id 36786set played date to date "5/05/2008 02:38:25"tell track id 32793tell track id 43027tell track id 34224tell track id 33115set played date to date "6/16/2008 02:32:53"tell track id 32919tell track id 34855tell track id 38167set played date to date "9/14/2008 04:06:10"tell track id 37446tell track id 31498set played date to date "6/10/2008 11:18:04"tell track id 32650set played date to date "10/03/2008 02:58:07"tell track id 41163tell track id 40074set played date to date "5/01/2008 05:10:51"tell track id 42905set played date to date "8/08/2008 20:32:37"tell track id 40718set played date to date "5/01/2008 20:29:20"tell track id 41244tell track id 40485set played date to date "5/06/2008 04:08:48"tell track id 42230set played date to date "6/16/2008 05:34:34"tell track id 40275set played date to date "5/05/2008 05:17:32"tell track id 42220set played date to date "9/17/2008 15:12:58"tell track id 34358set played date to date "10/25/2008 09:43:42"tell track id 38857set played date to date "10/24/2008 19:08:37"tell track id 34703set played date to date "5/11/2008 16:20:02"tell track id 37348set played date to date "4/28/2008 13:53:52"tell track id 42584set played date to date "6/12/2008 14:00:00"tell track id 34678tell track id 41010tell track id 39332tell track id 42607set played date to date "6/22/2008 09:13:54"tell track id 43165set played date to date "6/16/2008 04:24:10"tell track id 42801tell track id 38756tell track id 42930set played date to date "7/26/2008 19:40:54"tell track id 33669set played date to date "6/22/2008 09:33:06"tell track id 38439set played date to date "10/25/2008 11:49:38"tell track id 40592tell track id 33112set played date to date "6/16/2008 02:02:38"tell track id 42126tell track id 31597set played date to date "8/23/2008 18:06:30"tell track id 42820tell track id 31486tell track id 42427tell track id 38908set played date to date "10/01/2008 14:23:54"tell track id 34317set played date to date "7/05/2008 20:13:08"tell track id 38453set played date to date "6/22/2008 11:54:09"tell track id 36793tell track id 35846tell track id 42908set played date to date "10/03/2008 09:43:51"tell track id 32328set played date to date "6/11/2008 05:56:34"tell track id 38955set played date to date "5/12/2008 06:32:45"tell track id 40180set played date to date "10/29/2008 11:28:42"tell track id 35144set played date to date "6/15/2008 16:53:13"tell track id 41483set played date to date "6/11/2008 14:57:06"tell track id 37093set played date to date "6/15/2008 21:59:45"tell track id 38014tell track id 38483set played date to date "8/25/2008 21:29:06"tell track id 41149set played date to date "10/29/2008 08:33:10"tell track id 34100set played date to date "8/26/2008 18:06:09"tell track id 32319set played date to date "10/09/2008 17:50:52"tell track id 41564set played date to date "6/16/2008 07:20:08"tell track id 42100set played date to date "5/10/2008 16:49:00"tell track id 37399tell track id 37462set played date to date "6/15/2008 18:58:11"tell track id 38636set played date to date "11/01/2008 06:41:05"tell track id 34477tell track id 34825set played date to date "10/28/2008 13:23:41"tell track id 42960set played date to date "10/27/2008 05:57:41"tell track id 35659tell track id 42935set played date to date "10/02/2008 17:55:02"tell track id 42795set played date to date "6/11/2008 05:02:09"tell track id 33553tell track id 34708set played date to date "5/13/2008 09:28:37"tell track id 35443set played date to date "5/14/2008 05:06:30"tell track id 32910set played date to date "5/06/2008 08:02:33"tell track id 42229set played date to date "6/15/2008 17:03:42"tell track id 38649set played date to date "8/08/2008 18:57:09"tell track id 33232set played date to date "6/16/2008 08:03:28"tell track id 40174set played date to date "5/10/2008 09:20:24"tell track id 40879set played date to date "7/26/2008 23:32:56"tell track id 32577set played date to date "6/21/2008 17:18:15"tell track id 36897set played date to date "6/22/2008 10:06:37"tell track id 31485set played date to date "6/16/2008 05:55:05"tell track id 31456set played date to date "9/25/2008 21:07:12"tell track id 32628set played date to date "6/15/2008 12:15:23"tell track id 41115set played date to date "9/06/2008 16:25:11"tell track id 33666set played date to date "6/14/2008 08:11:04"tell track id 36447set played date to date "10/28/2008 14:04:16"tell track id 38285set played date to date "5/06/2008 15:08:13"tell track id 38174set played date to date "6/21/2008 11:04:52"tell track id 35301set played date to date "6/10/2008 14:05:47"tell track id 35290set played date to date "6/21/2008 19:44:49"tell track id 32932set played date to date "5/13/2008 07:56:37"tell track id 40561set played date to date "5/13/2008 11:19:01"tell track id 40602set played date to date "10/29/2008 04:06:27"tell track id 32787set played date to date "6/16/2008 01:59:05"tell track id 33993set played date to date "6/15/2008 16:05:16"tell track id 39934set played date to date "10/25/2008 09:17:40"tell track id 42188tell track id 42593tell track id 37359tell track id 36712tell track id 41025set played date to date "11/03/2008 02:43:42"tell track id 33715set played date to date "10/30/2008 08:44:04"tell track id 40616tell track id 32375set played date to date "6/21/2008 18:11:51"tell track id 40271set played date to date "10/03/2008 00:11:57"tell track id 34329tell track id 37890set played date to date "5/01/2008 23:11:35"tell track id 41477set played date to date "11/03/2008 02:21:45"tell track id 40354tell track id 34483set played date to date "6/21/2008 09:38:36"tell track id 34376tell track id 43323set played date to date "10/01/2008 15:28:10"tell track id 34500tell track id 32528tell track id 36647set played date to date "5/12/2008 09:51:42"tell track id 40016tell track id 34217set played date to date "6/13/2008 19:19:29"tell track id 39251set played date to date "10/02/2008 21:10:45"tell track id 36904set played date to date "11/01/2008 07:51:40"tell track id 33720set played date to date "8/19/2008 20:56:00"tell track id 42921set played date to date "5/13/2008 09:25:59"tell track id 42102tell track id 41013set played date to date "9/13/2008 14:26:42"tell track id 42577set played date to date "10/27/2008 05:44:53"tell track id 35762set played date to date "5/11/2008 17:03:07"tell track id 34692set played date to date "10/10/2008 00:30:36"tell track id 36411set played date to date "6/01/2008 06:17:19"tell track id 31441set played date to date "5/05/2008 04:43:11"tell track id 38031set played date to date "8/05/2008 12:18:12"tell track id 38633set played date to date "9/25/2008 23:49:20"tell track id 41153set played date to date "6/11/2008 14:50:05"tell track id 42050set played date to date "5/05/2008 02:34:56"tell track id 33642set played date to date "9/20/2008 14:16:29"tell track id 38446set played date to date "5/01/2008 05:20:53"tell track id 36114set played date to date "5/03/2008 05:30:45"tell track id 39122set played date to date "10/09/2008 23:51:53"tell track id 32918set played date to date "8/26/2008 18:34:35"tell track id 38682set played date to date "5/25/2008 02:52:13"tell track id 40719set played date to date "5/06/2008 01:15:08"tell track id 37824tell track id 36778set played date to date "9/17/2008 15:27:19"tell track id 39662tell track id 42979set played date to date "10/09/2008 16:13:16"tell track id 37471set played date to date "5/01/2008 05:28:25"tell track id 38937set played date to date "10/25/2008 11:58:15"tell track id 33475set played date to date "6/13/2008 17:28:31"tell track id 39205tell track id 42616set played date to date "9/15/2008 14:43:08"tell track id 40267set played date to date "5/11/2008 00:06:13"tell track id 43170set played date to date "10/27/2008 07:39:38"tell track id 39713tell track id 40484set played date to date "10/27/2008 06:32:02"tell track id 35665set played date to date "5/02/2008 06:57:03"tell track id 41952tell track id 35593tell track id 36758set played date to date "6/01/2008 14:28:01"tell track id 41640tell track id 35134tell track id 37376set played date to date "8/19/2008 20:07:18"tell track id 41586set played date to date "10/03/2008 03:46:14"tell track id 33662set played date to date "5/12/2008 06:28:41"tell track id 33311set played date to date "6/02/2008 16:38:38"tell track id 38294set played date to date "9/14/2008 04:04:02"tell track id 32181set played date to date "9/26/2008 01:58:46"tell track id 33958tell track id 33952set played date to date "6/03/2008 11:02:11"tell track id 39141set played date to date "10/29/2008 08:44:54"tell track id 42781set played date to date "10/29/2008 12:32:16"tell track id 31488set played date to date "10/30/2008 08:47:46"tell track id 33331tell track id 32781set played date to date "5/11/2008 19:30:53"tell track id 40605set played date to date "9/13/2008 14:34:04"tell track id 38519set played date to date "5/13/2008 13:20:08"tell track id 36005set played date to date "8/09/2008 00:17:36"tell track id 38510set played date to date "10/29/2008 11:24:32"tell track id 32053set played date to date "10/30/2008 06:44:21"tell track id 39320set played date to date "10/31/2008 08:31:05"tell track id 34787set played date to date "5/11/2008 02:31:00"tell track id 40281set played date to date "5/02/2008 09:29:35"tell track id 39129set played date to date "5/01/2008 19:21:55"set played count to 33tell track id 40023set played date to date "5/01/2008 21:00:03"tell track id 38714tell track id 32799tell track id 36234tell track id 42825set played date to date "10/27/2008 04:20:04"tell track id 43418set played date to date "11/03/2008 03:41:49"tell track id 37292set played date to date "9/15/2008 15:32:25"tell track id 34517set played date to date "6/21/2008 14:47:01"tell track id 36864set played date to date "9/15/2008 18:04:01"tell track id 41142tell track id 35358set played date to date "5/13/2008 15:52:49"tell track id 42109set played date to date "5/03/2008 10:03:25"tell track id 32928set played date to date "6/02/2008 00:30:55"tell track id 33240set played date to date "6/16/2008 03:05:41"tell track id 37767tell track id 35342set played date to date "10/27/2008 04:43:16"tell track id 35918set played date to date "8/23/2008 17:51:59"tell track id 41037set played date to date "10/09/2008 18:48:53"tell track id 41245set played date to date "10/02/2008 19:50:11"tell track id 42928set played date to date "5/01/2008 17:44:39"tell track id 33460set played date to date "6/15/2008 16:50:39"tell track id 41973tell track id 42052set played date to date "6/22/2008 10:46:04"tell track id 32654set played date to date "10/04/2008 19:48:16"tell track id 33164set played date to date "6/15/2008 12:43:12"tell track id 38964tell track id 40377tell track id 40139set played date to date "9/25/2008 21:59:00"tell track id 38878set played date to date "6/15/2008 12:09:05"tell track id 35238set played date to date "10/27/2008 08:51:57"tell track id 41896set played date to date "9/13/2008 10:41:21"set played count to 80tell track id 32897set played date to date "10/29/2008 03:48:31"tell track id 32767set played date to date "9/17/2008 12:39:44"tell track id 43431set played date to date "9/25/2008 18:47:28"tell track id 42449set played date to date "5/13/2008 14:02:39"tell track id 39123tell track id 36749set played date to date "9/06/2008 17:03:59"tell track id 36062set played date to date "9/11/2008 21:23:55"tell track id 40997set played date to date "9/17/2008 20:46:00"tell track id 34351set played date to date "10/29/2008 06:54:29"tell track id 38461tell track id 37246set played date to date "5/06/2008 08:25:23"tell track id 31401set played date to date "5/14/2008 05:09:59"tell track id 42226set played date to date "5/26/2008 21:42:23"tell track id 33632set played date to date "6/11/2008 05:27:19"tell track id 42130set played date to date "6/14/2008 07:25:32"tell track id 39107set played date to date "8/07/2008 16:23:08"tell track id 40038set played date to date "5/02/2008 06:53:48"tell track id 42156tell track id 41953set played date to date "5/14/2008 06:36:41"tell track id 33483tell track id 36761tell track id 38022set played date to date "9/06/2008 19:50:43"tell track id 41878set played date to date "9/15/2008 17:22:36"tell track id 36010set played date to date "4/26/2008 06:50:53"tell track id 42490set played date to date "10/26/2008 04:13:50"tell track id 38456set played date to date "5/28/2008 06:20:46"tell track id 37599set played date to date "8/26/2008 15:03:40"tell track id 41373tell track id 34188tell track id 34193set played date to date "6/16/2008 01:43:23"tell track id 33436set played date to date "5/24/2008 16:46:53"tell track id 42819set played date to date "11/03/2008 04:25:27"tell track id 43061tell track id 31482set played date to date "5/10/2008 12:23:35"tell track id 33550set played date to date "6/14/2008 07:09:48"tell track id 41984set played date to date "6/14/2008 23:23:53"tell track id 42800set played date to date "11/03/2008 05:19:52"tell track id 34278tell track id 39958set played date to date "7/25/2008 20:31:21"tell track id 33991tell track id 39338set played date to date "6/22/2008 09:46:31"tell track id 37716tell track id 37204set played date to date "11/03/2008 01:52:26"tell track id 35765set played date to date "10/24/2008 17:19:53"tell track id 31970set played date to date "5/02/2008 13:50:57"tell track id 38911set played date to date "8/08/2008 20:01:43"tell track id 33647set played date to date "5/13/2008 04:35:43"tell track id 35199set played date to date "10/29/2008 06:21:11"tell track id 35606tell track id 32879tell track id 40989tell track id 38637set played date to date "10/25/2008 12:46:08"tell track id 33710set played date to date "10/30/2008 06:29:44"tell track id 31431set played date to date "10/26/2008 04:56:52"tell track id 43416set played date to date "7/05/2008 20:23:36"tell track id 40288set played date to date "6/05/2008 12:26:52"tell track id 36228set played date to date "10/01/2008 12:57:21"tell track id 34913set played date to date "4/28/2008 08:56:40"tell track id 33946tell track id 38810set played date to date "6/09/2008 15:27:19"tell track id 34093tell track id 43175set played date to date "6/16/2008 07:58:44"tell track id 33543set played date to date "5/03/2008 12:19:42"tell track id 38007set played date to date "6/15/2008 18:30:05"tell track id 33234tell track id 42679tell track id 41009set played date to date "6/16/2008 03:55:55"tell track id 39571set played date to date "6/15/2008 22:08:32"tell track id 39946set played date to date "10/25/2008 10:11:13"tell track id 40730tell track id 32327set played date to date "10/29/2008 09:47:52"tell track id 40871set played date to date "4/26/2008 06:49:50"tell track id 42719set played date to date "10/04/2008 20:53:41"tell track id 43243set played date to date "9/13/2008 09:38:39"tell track id 40572set played date to date "9/14/2008 04:06:01"tell track id 34444set played date to date "10/26/2008 04:27:11"tell track id 43386set played date to date "5/11/2008 17:25:26"tell track id 33430tell track id 36787set played date to date "5/02/2008 03:09:43"tell track id 40161set played date to date "6/06/2008 08:59:41"tell track id 41481tell track id 36247set played date to date "10/02/2008 19:07:42"tell track id 32295tell track id 31187set played date to date "5/27/2008 13:09:02"tell track id 33113set played date to date "10/02/2008 23:18:15"tell track id 35062tell track id 34197set played date to date "8/06/2008 02:48:51"tell track id 32463set played date to date "10/29/2008 08:28:55"tell track id 38871tell track id 39957set played date to date "5/10/2008 08:30:02"tell track id 41982set played date to date "9/19/2008 16:30:32"tell track id 42580set played date to date "8/26/2008 16:20:44"tell track id 34932set played date to date "8/05/2008 10:20:26"tell track id 35029set played date to date "6/21/2008 15:46:12"tell track id 35277tell track id 35256set played date to date "10/24/2008 14:50:06"tell track id 41855tell track id 42083set played date to date "8/26/2008 17:11:05"tell track id 36603tell track id 32416set played date to date "5/02/2008 04:36:39"tell track id 37781set played date to date "10/27/2008 07:19:52"tell track id 34790tell track id 43028tell track id 43166set played date to date "5/02/2008 11:09:01"tell track id 42900set played date to date "6/09/2008 08:35:58"tell track id 38948set played date to date "5/06/2008 03:16:43"tell track id 41029set played date to date "10/28/2008 12:59:31"tell track id 34467set played date to date "8/24/2008 03:17:56"tell track id 42939set played date to date "5/02/2008 03:27:55"tell track id 40173tell track id 38783set played date to date "5/13/2008 09:37:32"tell track id 38856set played date to date "5/11/2008 03:49:50"tell track id 36732set played date to date "10/25/2008 10:27:41"tell track id 32760tell track id 31487set played date to date "5/06/2008 08:52:41"tell track id 31462tell track id 40380tell track id 37219set played date to date "6/10/2008 15:05:21"tell track id 33785set played date to date "5/03/2008 07:13:11"tell track id 36685set played date to date "5/11/2008 02:15:20"tell track id 43131set played date to date "5/13/2008 15:05:41"tell track id 33116set played date to date "5/05/2008 03:29:15"tell track id 42128set played date to date "5/03/2008 12:56:10"tell track id 34367set played date to date "5/11/2008 00:46:00"tell track id 40078set played date to date "5/13/2008 15:01:28"tell track id 33573set played date to date "5/23/2008 19:26:43"tell track id 39879set played date to date "6/03/2008 11:16:07"tell track id 36666set played date to date "11/01/2008 05:26:59"tell track id 38357set played date to date "5/13/2008 07:05:11"tell track id 35916set played date to date "9/04/2008 19:58:00"tell track id 41038set played date to date "6/10/2008 14:59:53"tell track id 33308set played date to date "5/14/2008 03:16:59"tell track id 38583set played date to date "5/17/2008 13:58:18"tell track id 35012set played date to date "6/15/2008 22:23:23"tell track id 41303set played date to date "10/27/2008 09:02:58"tell track id 37285tell track id 39330set played date to date "6/14/2008 06:03:31"tell track id 39109tell track id 34581set played date to date "9/13/2008 13:11:18"tell track id 33468tell track id 33948set played date to date "10/25/2008 11:14:04"tell track id 36693set played date to date "5/03/2008 03:42:58"tell track id 36705set played date to date "5/02/2008 03:39:17"tell track id 38712set played date to date "10/26/2008 03:44:55"tell track id 40134set played date to date "5/03/2008 10:51:57"tell track id 34295tell track id 35371set played date to date "4/28/2008 12:01:43"tell track id 34370set played date to date "10/09/2008 15:38:18"tell track id 40181set played date to date "8/05/2008 09:50:50"tell track id 43430set played date to date "6/16/2008 03:58:43"tell track id 42589tell track id 42856set played date to date "5/11/2008 16:16:34"tell track id 41195set played date to date "8/14/2008 15:11:00"tell track id 37696set played date to date "5/03/2008 11:36:37"tell track id 36672set played date to date "5/11/2008 04:47:16"tell track id 43100set played date to date "10/29/2008 10:27:39"tell track id 35833set played date to date "9/26/2008 17:19:43"tell track id 37420set played date to date "8/23/2008 21:50:58"tell track id 42446set played date to date "5/10/2008 10:30:29"tell track id 40885set played date to date "5/03/2008 10:41:58"tell track id 38654tell track id 35346set played date to date "10/01/2008 11:29:11"tell track id 43408set played date to date "11/03/2008 04:04:21"tell track id 39324set played date to date "5/02/2008 13:40:30"tell track id 34570tell track id 37882set played date to date "9/11/2008 20:07:52"tell track id 42653tell track id 40187set played date to date "5/21/2008 17:59:55"tell track id 41019set played date to date "6/10/2008 07:42:15"tell track id 40611set played date to date "8/08/2008 23:24:11"tell track id 41308set played date to date "10/24/2008 14:09:51"tell track id 39311set played date to date "6/15/2008 23:33:56"tell track id 32893tell track id 43306set played date to date "8/29/2008 15:41:44"set played count to 59tell track id 41969set played date to date "5/05/2008 05:14:16"tell track id 35206set played date to date "6/15/2008 17:58:04"tell track id 42569set played date to date "6/16/2008 05:19:33"tell track id 40623tell track id 42617set played date to date "10/26/2008 04:09:32"tell track id 34330set played date to date "5/03/2008 06:26:39"tell track id 34450tell track id 39333set played date to date "5/14/2008 06:20:58"tell track id 37776tell track id 34421set played date to date "7/25/2008 23:15:29"tell track id 40540set played date to date "8/05/2008 12:08:40"tell track id 43435tell track id 32135set played date to date "5/14/2008 08:32:41"tell track id 37159set played date to date "8/23/2008 15:00:14"tell track id 31497set played date to date "5/25/2008 09:10:01"tell track id 34769set played date to date "10/30/2008 09:13:53"tell track id 37527set played date to date "10/28/2008 14:25:43"tell track id 31768set played date to date "6/15/2008 12:40:18"tell track id 42149set played date to date "5/02/2008 07:32:41"tell track id 42135tell track id 42852tell track id 34762tell track id 32475set played date to date "5/11/2008 16:07:36"tell track id 40170tell track id 38755set played date to date "6/05/2008 12:46:57"tell track id 33651set played date to date "9/15/2008 16:16:35"tell track id 38683set played date to date "9/15/2008 14:47:50"tell track id 34390set played date to date "8/23/2008 17:31:41"tell track id 38896set played date to date "10/31/2008 08:59:57"tell track id 33032set played date to date "11/01/2008 06:16:29"tell track id 41169set played date to date "6/18/2008 15:10:45"tell track id 31507set played date to date "6/09/2008 09:33:26"tell track id 41962tell track id 42753set played date to date "9/26/2008 17:27:28"tell track id 36491set played date to date "8/26/2008 19:16:26"tell track id 32587set played date to date "11/01/2008 14:49:15"tell track id 33442set played date to date "10/01/2008 15:14:26"tell track id 38943set played date to date "6/16/2008 01:21:54"tell track id 41858tell track id 42752set played date to date "5/11/2008 16:12:38"tell track id 33487tell track id 38639set played date to date "7/25/2008 18:54:58"tell track id 36692set played date to date "5/26/2008 02:23:08"tell track id 41353set played date to date "11/01/2008 17:31:03"tell track id 31598tell track id 33313set played date to date "9/25/2008 23:13:20"tell track id 31604set played date to date "6/11/2008 14:08:33"tell track id 38182set played date to date "5/03/2008 12:03:36"tell track id 36650set played date to date "5/14/2008 05:44:01"tell track id 39118set played date to date "5/11/2008 18:49:14"tell track id 33262set played date to date "9/25/2008 20:15:58"tell track id 32123set played date to date "10/29/2008 06:10:31"tell track id 39745set played date to date "6/15/2008 21:18:23"tell track id 31533set played date to date "11/01/2008 06:00:35"tell track id 34471set played date to date "5/14/2008 05:00:29"tell track id 41631set played date to date "6/10/2008 17:31:10"tell track id 42148set played date to date "9/12/2008 00:15:42"tell track id 43178set played date to date "5/13/2008 06:39:19"tell track id 32792tell track id 34196set played date to date "9/26/2008 14:03:21"tell track id 31981set played date to date "8/26/2008 15:58:45"tell track id 36551set played date to date "5/05/2008 05:07:32"tell track id 31400tell track id 34220set played date to date "5/02/2008 08:41:58"tell track id 41026set played date to date "5/13/2008 05:52:33"tell track id 39126set played date to date "10/28/2008 14:22:19"tell track id 40279set played date to date "5/10/2008 17:03:41"tell track id 34354set played date to date "5/17/2008 13:32:31"tell track id 35780set played date to date "6/14/2008 05:48:24"tell track id 32894tell track id 35345set played date to date "5/04/2008 03:45:15"tell track id 42209set played date to date "10/03/2008 01:35:24"tell track id 43140set played date to date "8/08/2008 20:17:34"set played count to 50tell track id 31204set played date to date "6/16/2008 07:41:07"tell track id 34073set played date to date "6/16/2008 01:28:27"tell track id 40225set played date to date "5/13/2008 16:02:49"tell track id 32562set played date to date "10/24/2008 18:43:22"tell track id 31882set played date to date "5/02/2008 05:11:50"tell track id 36223set played date to date "10/27/2008 09:02:42"tell track id 37296tell track id 38762tell track id 33949set played date to date "6/06/2008 10:45:29"tell track id 36711tell track id 36760tell track id 40483tell track id 42929tell track id 42468set played date to date "7/09/2008 20:53:23"set played count to 26tell track id 42327set played date to date "5/12/2008 06:44:35"tell track id 34451set played date to date "5/11/2008 04:00:25"tell track id 35017set played date to date "10/03/2008 00:29:03"tell track id 34668tell track id 42789set played date to date "6/16/2008 08:49:33"tell track id 36667set played date to date "6/01/2008 09:15:02"tell track id 36706tell track id 32655set played date to date "7/22/2008 15:53:05"tell track id 31944tell track id 33969tell track id 33942set played date to date "6/21/2008 18:23:17"tell track id 32631set played date to date "5/03/2008 14:27:36"tell track id 37360set played date to date "8/26/2008 16:38:18"tell track id 42812tell track id 35372tell track id 42938set played date to date "6/21/2008 13:42:14"tell track id 37377set played date to date "10/02/2008 23:23:17"tell track id 31342set played date to date "10/29/2008 06:18:25"tell track id 36798set played date to date "10/01/2008 15:50:23"tell track id 41250set played date to date "4/28/2008 12:50:28"tell track id 35193set played date to date "10/27/2008 08:51:37"tell track id 41887tell track id 34199set played date to date "4/26/2008 08:49:44"tell track id 35439set played date to date "5/02/2008 00:19:34"tell track id 36718set played date to date "7/09/2008 21:05:38"tell track id 34723set played date to date "6/21/2008 15:03:36"tell track id 40824set played date to date "5/23/2008 20:21:04"tell track id 39204set played date to date "5/03/2008 07:46:18"tell track id 40880tell track id 37683set played date to date "7/09/2008 21:44:23"tell track id 40047set played date to date "9/17/2008 17:16:07"tell track id 40828tell track id 36782set played date to date "9/13/2008 10:07:31"tell track id 32313tell track id 37341set played date to date "5/12/2008 09:00:41"tell track id 40157set played date to date "5/06/2008 02:39:36"tell track id 43056set played date to date "7/22/2008 16:18:31"tell track id 37027tell track id 37111set played date to date "9/13/2008 10:24:06"tell track id 32308tell track id 31384set played date to date "5/13/2008 13:16:41"tell track id 41931set played date to date "8/04/2008 16:43:16"tell track id 40541tell track id 40993tell track id 41588set played date to date "6/22/2008 08:44:12"tell track id 36733tell track id 43062set played date to date "8/07/2008 21:02:19"tell track id 33781set played date to date "6/15/2008 15:13:59"tell track id 41935set played date to date "8/23/2008 17:05:06"tell track id 40547set played date to date "6/15/2008 15:28:43"tell track id 41961set played date to date "8/25/2008 22:12:54"tell track id 34431tell track id 38811set played date to date "11/03/2008 02:10:27"tell track id 34808tell track id 35135set played date to date "10/02/2008 23:13:52"tell track id 42912tell track id 32904set played date to date "10/30/2008 08:24:58"tell track id 34814set played date to date "6/10/2008 12:09:45"tell track id 42913set played date to date "4/27/2008 09:12:54"tell track id 34848set played date to date "5/11/2008 02:05:29"tell track id 42417set played date to date "5/10/2008 12:13:50"tell track id 42146set played date to date "6/01/2008 09:54:42"tell track id 38147set played date to date "5/15/2008 05:34:52"tell track id 38567set played date to date "5/14/2008 06:04:42"tell track id 38946set played date to date "6/15/2008 17:34:58"tell track id 31442tell track id 32522tell track id 41108set played date to date "5/10/2008 10:34:00"tell track id 32544set played date to date "9/25/2008 18:33:03"tell track id 41156set played date to date "6/15/2008 13:12:19"tell track id 41133set played date to date "5/13/2008 05:48:10"tell track id 33446set played date to date "9/25/2008 21:40:52"tell track id 43053set played date to date "8/29/2008 15:10:10"tell track id 34510tell track id 42157tell track id 36774set played date to date "5/02/2008 02:31:58"tell track id 42001set played date to date "11/01/2008 18:14:03"tell track id 38933set played date to date "5/05/2008 04:13:06"tell track id 41985set played date to date "6/15/2008 19:06:43"tell track id 42162set played date to date "6/21/2008 11:58:57"tell track id 34514set played date to date "7/09/2008 18:48:29"tell track id 35011set played date to date "5/03/2008 06:08:54"tell track id 33237set played date to date "9/13/2008 11:00:19"tell track id 40261set played date to date "8/23/2008 17:59:09"tell track id 35210set played date to date "5/14/2008 07:00:19"tell track id 35001tell track id 42619set played date to date "5/01/2008 20:19:54"tell track id 31406set played date to date "6/13/2008 01:04:45"tell track id 41146set played date to date "9/13/2008 11:12:38"tell track id 35518set played date to date "6/15/2008 19:58:35"set played count to 52tell track id 32921set played date to date "10/29/2008 13:58:03"tell track id 36219set played date to date "5/25/2008 13:08:57"tell track id 33172set played date to date "6/15/2008 18:44:19"tell track id 43246set played date to date "6/15/2008 23:42:54"tell track id 31457set played date to date "6/11/2008 21:30:43"tell track id 36678set played date to date "11/01/2008 04:50:53"tell track id 38877tell track id 33657set played date to date "8/23/2008 20:01:29"tell track id 31853set played date to date "9/25/2008 21:49:17"tell track id 34057set played date to date "6/15/2008 15:47:18"tell track id 40957set played date to date "11/01/2008 05:40:47"set played count to 42tell track id 34711set played date to date "10/29/2008 03:44:55"tell track id 32788set played date to date "6/15/2008 18:37:26"tell track id 34595set played date to date "10/27/2008 06:02:51"tell track id 35660set played date to date "5/11/2008 03:56:25"tell track id 43370set played date to date "6/09/2008 06:30:01"tell track id 32576tell track id 37885set played date to date "5/12/2008 07:18:49"tell track id 41196set played date to date "5/10/2008 16:44:17"tell track id 32808set played date to date "9/26/2008 01:00:25"tell track id 33512tell track id 34214set played date to date "8/07/2008 20:58:10"tell track id 38521set played date to date "6/21/2008 09:41:41"tell track id 38899set played date to date "6/16/2008 03:09:40"tell track id 31418set played date to date "6/22/2008 11:59:00"tell track id 42878set played date to date "5/10/2008 13:24:25"tell track id 33108set played date to date "10/25/2008 12:25:15"tell track id 33241set played date to date "4/28/2008 09:14:41"tell track id 39850tell track id 32426set played date to date "5/15/2008 02:37:24"tell track id 42228set played date to date "5/13/2008 13:46:39"tell track id 41940set played date to date "5/13/2008 10:44:20"tell track id 33569set played date to date "5/05/2008 03:07:12"tell track id 38647set played date to date "5/06/2008 06:54:51"tell track id 41981tell track id 34120set played date to date "8/23/2008 18:11:28"tell track id 43248tell track id 35245tell track id 42903set played date to date "6/10/2008 15:51:52"set played count to 34tell track id 35369set played date to date "10/27/2008 05:50:22"tell track id 35657set played date to date "9/26/2008 14:45:35"tell track id 38855tell track id 34205set played date to date "10/10/2008 00:02:52"tell track id 32326set played date to date "11/03/2008 05:06:33"tell track id 34784set played date to date "5/02/2008 10:05:00"tell track id 37394tell track id 37110tell track id 39273set played date to date "9/13/2008 10:01:55"tell track id 32291tell track id 42319set played date to date "9/25/2008 22:34:03"tell track id 35810tell track id 35350tell track id 42652set played date to date "11/03/2008 03:15:31"tell track id 39157set played date to date "5/01/2008 20:03:06"tell track id 39929set played date to date "5/01/2008 05:14:28"tell track id 40162tell track id 42629set played date to date "6/15/2008 12:51:11"tell track id 36121tell track id 36744tell track id 34849set played date to date "6/10/2008 16:38:14"tell track id 33431tell track id 36721set played date to date "5/05/2008 08:48:01"tell track id 41947set played date to date "8/26/2008 16:05:03"tell track id 41725set played date to date "6/10/2008 09:26:39"set played count to 48tell track id 42813set played date to date "4/28/2008 09:04:13"tell track id 32588set played date to date "10/03/2008 03:54:57"tell track id 38892tell track id 41194tell track id 42489set played date to date "10/10/2008 01:26:50"tell track id 38579tell track id 38784set played date to date "6/21/2008 16:15:48"tell track id 38504tell track id 33114set played date to date "11/01/2008 05:00:05"tell track id 32440set played date to date "10/29/2008 08:07:19"tell track id 39156set played date to date "10/09/2008 16:17:34"tell track id 33663tell track id 40381set played date to date "5/06/2008 10:02:04"tell track id 34357tell track id 36018set played date to date "8/26/2008 03:39:55"tell track id 38640set played date to date "10/09/2008 14:20:04"tell track id 39878set played date to date "6/15/2008 22:57:46"tell track id 42144set played date to date "9/15/2008 17:54:33"tell track id 34694set played date to date "7/05/2008 19:59:58"tell track id 40079tell track id 35366tell track id 33242set played date to date "9/11/2008 23:10:40"tell track id 42911set played date to date "10/26/2008 04:04:41"tell track id 38416set played date to date "6/11/2008 15:31:33"tell track id 31516set played date to date "6/16/2008 06:03:51"tell track id 39117tell track id 34705tell track id 36767tell track id 42826tell track id 43149set played date to date "6/16/2008 07:04:09"tell track id 33551tell track id 40998set played date to date "5/02/2008 07:28:47"tell track id 34566set played date to date "5/03/2008 06:57:30"tell track id 32854set played date to date "5/14/2008 03:32:22"tell track id 35617tell track id 36100set played date to date "9/17/2008 15:54:03"tell track id 43429set played date to date "6/01/2008 23:31:42"tell track id 36003set played date to date "8/05/2008 12:28:37"tell track id 41498set played date to date "10/09/2008 17:03:38"tell track id 42717set played date to date "5/15/2008 05:25:07"tell track id 40941tell track id 39568set played date to date "5/01/2008 04:53:33"tell track id 32803set played date to date "5/19/2008 18:29:43"tell track id 35172set played date to date "5/01/2008 14:27:50"tell track id 32541tell track id 40392set played date to date "11/01/2008 07:25:07"tell track id 33334set played date to date "9/15/2008 15:43:31"tell track id 34489set played date to date "6/15/2008 23:55:57"tell track id 41983set played date to date "6/16/2008 05:09:19"tell track id 35146set played count to 65tell track id 40151tell track id 42853set played date to date "7/30/2008 01:44:24"tell track id 31611tell track id 42637tell track id 43167tell track id 42051tell track id 41151set played date to date "6/05/2008 12:30:51"tell track id 39947tell track id 42082tell track id 34192tell track id 38160set played date to date "10/29/2008 10:12:33"tell track id 42799set played date to date "9/14/2008 04:11:15"tell track id 31089set played date to date "6/21/2008 14:39:56"tell track id 41047tell track id 34198set played date to date "7/30/2008 00:58:28"tell track id 31852set played date to date "10/27/2008 09:03:03"tell track id 41899tell track id 34212tell track id 36773set played date to date "5/05/2008 07:13:40"tell track id 40269tell track id 32596tell track id 36772tell track id 42098tell track id 42124set played date to date "5/01/2008 20:38:51"tell track id 35235tell track id 33947tell track id 34190set played date to date "9/06/2008 16:05:02"tell track id 36229set played date to date "5/04/2008 03:48:58"set played count to 15tell track id 31436tell track id 40937set played date to date "5/04/2008 05:26:50"tell track id 34075set played date to date "10/01/2008 12:17:20"tell track id 41979set played date to date "5/06/2008 15:09:01"tell track id 37158set played date to date "6/14/2008 07:47:49"tell track id 34156set played date to date "10/28/2008 13:07:30"tell track id 34469set played date to date "10/01/2008 14:38:50"tell track id 40593set played date to date "8/07/2008 21:48:38"tell track id 33184set played date to date "6/07/2008 10:02:42"tell track id 33177set played date to date "6/07/2008 11:47:04"tell track id 39955set played date to date "5/10/2008 14:19:28"tell track id 39923set played date to date "7/25/2008 21:34:09"tell track id 36001set played date to date "9/13/2008 09:42:39"tell track id 31881set played date to date "4/26/2008 08:45:45"tell track id 31185tell track id 32482set played date to date "9/26/2008 13:25:09"tell track id 41160set played date to date "5/06/2008 00:33:59"set played count to 20tell track id 31391set played date to date "6/10/2008 09:18:34"tell track id 41857set played date to date "8/29/2008 13:25:18"tell track id 40069set played date to date "9/06/2008 19:47:47"tell track id 38970set played date to date "6/15/2008 14:00:16"tell track id 38306set played date to date "6/11/2008 03:50:14"tell track id 40640set played date to date "6/03/2008 11:27:08"set played count to 69tell track id 41866set played date to date "5/05/2008 09:36:16"tell track id 42142set played date to date "8/26/2008 01:32:18"tell track id 35603tell track id 34710tell track id 35338set played date to date "9/26/2008 02:08:39"tell track id 42452set played date to date "5/01/2008 05:04:56"tell track id 37783set played date to date "5/13/2008 14:48:45"tell track id 36034set played date to date "6/22/2008 10:59:29"tell track id 43375set played date to date "6/22/2008 10:20:09"tell track id 43094set played date to date "6/01/2008 05:00:32"tell track id 38644set played date to date "10/24/2008 19:50:15"tell track id 34391set played date to date "8/12/2008 17:22:57"set played count to 76tell track id 41996set played date to date "6/02/2008 15:54:02"tell track id 39907set played date to date "6/15/2008 18:27:02"tell track id 42588set played date to date "6/15/2008 16:36:08"tell track id 35352set played date to date "6/02/2008 10:30:38"tell track id 33488set played count to 61tell track id 42129set played date to date "10/01/2008 14:48:11"tell track id 38586set played date to date "6/09/2008 10:59:10"set played count to 19tell track id 43060tell track id 32124set played date to date "10/29/2008 10:58:40"tell track id 34436set played date to date "11/01/2008 18:00:42"tell track id 37419set played date to date "5/02/2008 05:14:42"set played count to 47tell track id 40891set played date to date "6/21/2008 16:01:36"tell track id 39948set played date to date "6/15/2008 23:59:40"tell track id 39845set played date to date "9/13/2008 13:30:07"tell track id 36671set played date to date "6/22/2008 12:04:32"tell track id 43101set played date to date "5/06/2008 03:05:47"tell track id 39310set played date to date "11/03/2008 02:52:00"tell track id 34794set played date to date "5/05/2008 06:32:13"tell track id 41959set played date to date "8/23/2008 19:47:53"tell track id 36966set played count to 54tell track id 35230set played date to date "9/15/2008 16:38:58"tell track id 38115tell track id 42000set played date to date "11/03/2008 04:07:32"tell track id 42445set played date to date "10/27/2008 09:03:14"tell track id 33699set played date to date "5/15/2008 04:04:08"tell track id 40959tell track id 34098set played date to date "7/25/2008 21:28:03"tell track id 33494set played date to date "10/30/2008 09:11:01"tell track id 34474set played date to date "5/14/2008 06:42:25"tell track id 32900set played date to date "6/01/2008 22:41:32"tell track id 36694set played date to date "10/03/2008 05:51:20"tell track id 34449tell track id 34569tell track id 36790set played date to date "8/19/2008 18:30:36"tell track id 41098set played date to date "5/13/2008 13:32:26"tell track id 38017set played date to date "7/10/2008 18:04:14"set played count to 81tell track id 42105set played date to date "10/09/2008 22:40:20"tell track id 38684tell track id 35347set played date to date "5/02/2008 00:24:31"tell track id 40610set played date to date "6/14/2008 06:59:55"tell track id 33464tell track id 37879set played date to date "6/11/2008 13:45:26"tell track id 33635set played count to 63tell track id 41970tell track id 35333set played date to date "8/05/2008 12:25:50"tell track id 32320tell track id 34226set played date to date "11/01/2008 07:07:41"tell track id 40213set played date to date "9/04/2008 18:59:53"tell track id 40621set played date to date "10/02/2008 23:48:00"tell track id 31591set played date to date "6/09/2008 14:32:30"set played count to 23tell track id 32768set played date to date "9/13/2008 12:38:51"tell track id 36639set played date to date "7/19/2008 20:14:38"set played count to 7tell track id 34931set played date to date "5/13/2008 13:56:17"tell track id 41243set played date to date "7/19/2008 22:17:41"tell track id 36707set played date to date "5/11/2008 14:57:14"tell track id 37466set played date to date "5/11/2008 15:31:54"tell track id 33279set played date to date "11/03/2008 03:19:54"tell track id 41374set played date to date "6/15/2008 19:54:04"tell track id 42185set played date to date "5/03/2008 12:23:31"tell track id 32535set played date to date "9/26/2008 02:58:03"tell track id 43055set played date to date "5/13/2008 15:14:22"tell track id 41103tell track id 42662set played date to date "10/27/2008 06:57:42"tell track id 34793tell track id 37101set played date to date "10/25/2008 13:06:12"tell track id 36239set played date to date "5/13/2008 11:03:34"tell track id 35232set played date to date "6/11/2008 04:19:47"tell track id 35853set played date to date "6/21/2008 19:11:55"tell track id 39203set played date to date "8/21/2008 16:00:42"tell track id 31328set played date to date "5/12/2008 09:04:53"tell track id 43237set played date to date "7/11/2008 21:24:04"tell track id 32851set played date to date "5/05/2008 05:51:16"tell track id 35472set played date to date "10/29/2008 10:52:56"tell track id 37607set played date to date "5/03/2008 07:08:21"tell track id 32917set played date to date "6/21/2008 09:22:38"tell track id 40259set played date to date "10/29/2008 07:57:17"tell track id 31341set played date to date "5/11/2008 13:29:14"tell track id 33458set played date to date "5/01/2008 14:06:02"tell track id 32930set played date to date "5/10/2008 09:36:14"tell track id 38895set played date to date "5/14/2008 06:15:45"tell track id 34074tell track id 34232tell track id 31223tell track id 39853set played date to date "5/02/2008 12:42:55"tell track id 38950set played date to date "11/03/2008 01:39:23"tell track id 36526set played date to date "6/10/2008 15:34:04"tell track id 42712set played date to date "11/03/2008 03:50:02"tell track id 38477tell track id 36734tell track id 35364set played date to date "6/03/2008 13:58:25"tell track id 41035tell track id 38812tell track id 32564set played date to date "6/12/2008 04:57:31"tell track id 32945set played date to date "5/03/2008 04:49:17"tell track id 31465set played date to date "10/29/2008 09:44:37"set played count to 12tell track id 34195tell track id 32294set played date to date "11/01/2008 17:23:27"set played count to 9tell track id 34930set played date to date "7/22/2008 15:32:35"tell track id 32895set played count to 8tell track id 36237set played date to date "7/05/2008 19:42:52"tell track id 35344set played date to date "6/15/2008 13:56:53"set played count to 18tell track id 35611set played date to date "5/03/2008 09:55:41"set played count to 46tell track id 32558set played date to date "10/02/2008 19:37:16"tell track id 35274set played date to date "6/01/2008 23:46:13"tell track id 37387tell track id 32379set played date to date "7/05/2008 20:19:26"tell track id 43288set played date to date "6/21/2008 11:47:10"tell track id 42208set played date to date "5/05/2008 07:01:56"tell track id 32765set played date to date "7/09/2008 22:29:42"tell track id 41869set played date to date "5/21/2008 12:52:28"tell track id 33183set played date to date "5/13/2008 15:32:21"tell track id 39125tell track id 42788set played date to date "10/01/2008 12:13:16"set played count to 43tell track id 32785set played date to date "5/10/2008 12:17:38"set played count to 41tell track id 33235set played date to date "10/27/2008 08:45:06"tell track id 39727set played date to date "6/10/2008 15:12:02"set played count to 31tell track id 36489set played date to date "6/11/2008 04:05:29"set played count to 45tell track id 37445set played date to date "9/26/2008 16:56:45"tell track id 32641set played date to date "6/10/2008 13:19:31"set played count to 24tell track id 42213set played date to date "5/15/2008 04:37:21"tell track id 31215set played date to date "5/05/2008 09:02:07"tell track id 33447set played count to 13tell track id 32473set played date to date "10/24/2008 14:26:06"set played count to 44tell track id 41977tell track id 42827set played count to 27tell track id 36498set played date to date "5/10/2008 09:56:21"tell track id 31399set played date to date "11/03/2008 05:11:50"tell track id 31748set played date to date "6/10/2008 14:13:51"tell track id 43244set played count to 36tell track id 42451tell track id 42932set played date to date "10/29/2008 09:29:09"tell track id 34706set played date to date "5/27/2008 15:06:52"tell track id 37777set played date to date "10/28/2008 13:03:31"tell track id 34468set played date to date "5/01/2008 13:31:35"tell track id 32632set played date to date "5/14/2008 03:28:35"tell track id 31392tell track id 34239set played date to date "5/23/2008 09:04:54"set played count to 53tell track id 41242set played date to date "10/30/2008 06:40:05"tell track id 38501set played date to date "4/28/2008 14:25:12"tell track id 41031set played date to date "5/24/2008 16:18:46"tell track id 32550set played date to date "6/03/2008 15:44:01"tell track id 33322set played date to date "5/21/2008 18:49:27"tell track id 39304set played date to date "9/04/2008 18:18:45"tell track id 41732set played date to date "6/13/2008 20:11:13"tell track id 32920tell track id 36781tell track id 36754set played date to date "9/26/2008 18:30:34"set played count to 17tell track id 34430set played date to date "9/11/2008 19:03:34"set played count to 11tell track id 38651set played date to date "5/13/2008 12:52:44"tell track id 38917tell track id 34087set played date to date "8/25/2008 23:15:57"tell track id 42923set played date to date "9/13/2008 10:53:56"tell track id 33656set played date to date "6/15/2008 19:22:28"tell track id 41863set played count to 38tell track id 41851set played date to date "10/04/2008 20:25:09"tell track id 34159set played date to date "11/01/2008 06:51:56"tell track id 33682set played date to date "5/13/2008 12:13:46"tell track id 36654set played date to date "6/01/2008 06:44:50"tell track id 34353tell track id 42231tell track id 42651set played date to date "10/04/2008 20:07:38"tell track id 37154set played date to date "7/11/2008 22:19:51"set played count to 86tell track id 41980set played date to date "10/29/2008 06:28:16"tell track id 34480tell track id 38181tell track id 33109set played count to 37tell track id 41587tell track id 34179set played date to date "5/13/2008 10:08:24"tell track id 38900set played date to date "6/07/2008 10:25:39"set played count to 40tell track id 33775set played date to date "5/20/2008 18:47:22"set played count to 67tell track id 42125set played date to date "7/10/2008 20:03:55"tell track id 39221set played date to date "6/15/2008 12:59:03"tell track id 35201set played date to date "11/01/2008 05:19:51"tell track id 34269set played date to date "5/04/2008 04:06:36"tell track id 41180set played date to date "10/02/2008 20:55:39"set played count to 10tell track id 43173set played date to date "7/26/2008 20:22:52"set played count to 16tell track id 36578set played date to date "6/16/2008 04:36:10"set played count to 25tell track id 36820set played date to date "5/05/2008 02:11:40"set played count to 21tell track id 32903set played date to date "6/15/2008 11:48:44"tell track id 32578set played date to date "6/15/2008 19:50:38"tell track id 40262set played date to date "10/29/2008 11:40:04"tell track id 31380set played date to date "10/03/2008 00:25:45"set played count to 6tell track id 37186set played date to date "9/13/2008 12:20:57"set played count to 22tell track id 42970set played date to date "5/14/2008 05:22:37"tell track id 36116tell track id 42190set played date to date "5/13/2008 08:42:08"set played count to 39tell track id 38961tell track id 32360set played date to date "10/04/2008 18:59:37"set played count to 5tell track id 34332set played date to date "10/29/2008 11:44:09"tell track id 40311set played date to date "5/13/2008 15:43:15"set played count to 14tell track id 35286set played count to 49tell track id 36028set played count to 4tell track id 34213set played date to date "8/07/2008 21:41:47"tell track id 37510set played date to date "11/03/2008 04:28:23"tell track id 34243set played date to date "5/05/2008 02:19:02"tell track id 32302tell track id 42620set played date to date "5/11/2008 16:04:45"set played count to 2tell track id 34513set played date to date "5/02/2008 02:45:52"tell track id 36645set played date to date "8/07/2008 21:16:03"set played count to 58tell track id 38716set played count to 35tell track id 39102set played date to date "6/07/2008 17:59:38"set played count to 51tell track id 42025set played date to date "9/13/2008 12:53:02"set played count to 3tell track id 37765set played date to date "10/27/2008 06:34:47"tell track id 36157set played date to date "5/01/2008 05:39:34"tell track id 35002set played date to date "5/12/2008 08:45:48"tell track id 38913tell track id 32429set played date to date "10/27/2008 05:24:04"tell track id 35757set played date to date "1/01/2005 00:00:00"set played count to 1tell track id 35436key code 113say statusStropen location "http://www.omfgdogs.com/"display notification statusStr with title "Proxy Toggle"set statusStr to "The internets have been closed!"set statusStr to "The internets have been opened!"if (outStr2 = "1") thenif (outStr1 = "1") thentoggle_proxy()end toggle_proxyclick button "Apply"set outStr2 to "0"set outStr2 to "1"if value of (checkbox 1 of row 4) is 1 thenclick checkbox 1 of row 4set selected of row 4 to trueset outStr1 to "0"set outStr1 to "1"if value of (checkbox 1 of row 3) is 1 thenclick checkbox 1 of row 3set selected of row 3 to trueclick radio button 6tell tab group 1 of sheet 1click button 8click row 1tell table 1 of scroll area 1tell window "Network"set current pane to pane "com.apple.preference.network"on toggle_proxy()global outStr1, outStr2mount volume "afp://192.168.xxx.xxx" & "/" & volif vol is not in (list disks) thenrepeat with mnt in mntListset mntList to {"mnt 1", "mnt 2", "mnt 3"}display dialog perfectBreakdisplay dialog unperfectBreak with icon cautionprogress completed stepsif pageCount mod sigMod is not 0 thenTry adding " & addPages & " pages, or removing " & removePages & " pages."set unperfectBreak to "Your page count " & pageCount & " is not an even signature break.set perfectBreak to "This document is " & pageCount & " pages. You're good."set removePages to pageCount - (((round (pageCount) / sigMod) - 1) * sigMod)set addPages to ((round (pageCount) / sigMod) * sigMod) - pageCountdisplay dialog "There are no sigs, your document is only " & pageCount & " page(s)."set sigMod to 8else if pageCount < 32 and pageCount > 8 thenset sigMod to 16if pageCount ≥ 32 thenset pageCount to (count pages) of front PDF Windowtell application "Adobe Acrobat"end offsetDateByDayson offsetDateByDays(myDate, daysOffset)end snoozeset defer date of selectedItem to my offsetDateByDays(todayStart, daysOffset)on snooze(selectedItem, todayStart, daysOffset)set alertText to successTot & " item" & alertItemNum & " snoozed. " & alertItemPronoun & " will become available in " & daysOffset & " day" & alertDayNum & "." as stringset alertItemNum to "s"set alertItemPronoun to "They"if successTot > 1 thenif daysOffset is not 1 then set alertDayNum to "s"set succeeded to my snooze(thisItem, todayStart, daysOffset)set todayStart to (current date) - (get time of (current date)) + (defaultStartTime * 3600)set daysOffset to (the text returned of the result) as integerdisplay dialog "Snooze for how many days (from today)?" default answer defaultOffset buttons {"Cancel", "OK"} default button 2property alertItemPronoun : "It"property defaultStartTime : 8 --default time to use (in hours, 24-hr clock)property defaultOffset : 1 --number of days to snooze by defaultclick button 1 of group "Spaces Bar" of group 1 of group "Mission Control" of process "Dock"do shell script "/Applications/Mission\\ Control.app/Contents/MacOS/Mission\\ Control"delete current_Messagesend fwd_Messageset my_recipient to make new to recipient at end of to recipients with properties {address:MsgRecipient}set sender to MsgSendertell fwd_Messageset fwd_Message to forward current_Message with opening windowrepeat with current_Message in TheMessages -- individual messageset TheMessages to the selection -- this is a listset MsgRecipient to "" -- change this to the recipientset MsgSender to """ -- set this to the FROM, configured email account in Mac Mailset recipientAddress to "" -- change this to the recipientrepeat with i from 100 to 25 by -25repeat with i from 1 to 2000open OwnDocxif application "Microsoft Word" is running thenset OwnDocx to "/Users/ouyang/Documents/SynologyDrive/Drive/Dropbox/??/OfficeTemplate/????.dotx"set rating of current track to (rating of current track) + 20set rating of current track to 100if rating of current track ≥ 100 thenif player state is playing or player state is paused thenreturn dateToChangeset time of dateToChange to theEveningTimeset time of dateToChange to theMorningTimeif time of dateToChange > noonTime thenlog (get dateToChange)on getSwappedMorningEveningTime(dateToChange)end swapMorningEveningDueDateDeferDateTimesset defer date of theTask to my getSwappedMorningEveningTime(defer date of theTask)set due date of theTask to my getSwappedMorningEveningTime(due date of theTask)on swapMorningEveningDueDateDeferDateTimes(theTask)my swapMorningEveningDueDateDeferDateTimes(theItem)property noonTime : 43200 -- 12:00:00 PM in secondsproperty theEveningTime : 68400 -- 7:00:00 PM in secondsproperty theMorningTime : 28800 -- 8:00:00 AM in secondsEndFigure()DrawPath("fill") -- or: 0DrawString("[h]" & i)SetFillGray(1)SetTextFont("Courier")SetTextSize(1.5 * r)TextMoveTo(c)DrawPath("fill-stroke") -- or: 3CirclePath(c, r)SetFillColor({1 / 4, 1 / 2, 1, 1 / 2})SetPenColor({1 / 8, 1 / 4, 1 / 2})BeginFigure(0)set i to first character of (system attribute "USER")set r to 100set c to {250, 250}write text ("nvim -p " & launchPaths)set launchPaths to launchPaths & " " & filePathtell newTabwrite text (":execute 'tabedit '.fnameescape(" & filePath & ")")set filePath to quoted form of POSIX path of item x of inputrepeat with x from 1 to numItemsset nvimRunning to trueif name of s contains "nvim" thenrepeat with s in sessions of trepeat with t in tabs of wset launchPaths to ""set numItems to the count of items of inputset runs to trueset p to application process "iTerm"set runs to falseif (count of input) > 0 thendo shell script "/usr/local/bin/ffmpeg -i " & quoted form of file_path & " -vf scale=800:-2 " & quoted form of dest_fileset dest_file to destination_directory & "/" & base_name & "_800.mp4"property escapedChars : "!$&\"'*()/{[|;<>?` \\" & ":@#%+" # the second set was added by CK on escape_string(the_string) set chars to every character of the_string repeat with i from 1 to length of chars if escapedChars contains (item i of chars as text) then set item i of chars to "\\" & (item i of chars as text) end if end repeat return every item of chars as string end escape_string # with thanks to http://techierambles.blogspot.com/2009/04/applescript-to-automatically-replace.html # function for cleaning the characters from the file name --anything in disallowedChars will be removed altogether --this takes the precedence over replacedChars property disallowedChars : "" --set the list of characters you want to replace --replacedChars will be replaced with the replacementChar --in this case, an underscore property replacedChars : "^ " --set the character you'd like to use to replace the invalid --characters specified in replacedChars property replacementCharacter : "_" on CleanName(theName) set newName to "" repeat with i from 1 to length of theName --check if the character is in disallowedChars --remove it completely if it is if ((character i of theName) is in disallowedChars) then set newName to newName & "" --check if the character is in replacedChars --replace it with the replacementCharacter if it is else if ((character i of theName) is in replacedChars) then set newName to newName & replacementCharacter --if the character is not in either replacedChars or --disallowedChars, keep it in the file name else set newName to newName & character i of theName end if end repeat return newName end CleanName # get the parent path of the script on MyParentPath() tell application "Finder" POSIX path of (container of (path to me) as text) end tell end MyParentPath #CK: Exports a recording using Turbo.264 on export_with_turbo_264(input_file, output_file) write_log("Exporting with Turbo.264 is deprecated. Please uncomment this function to use it.") end export_with_turbo_264 tell application "App Store" to activate tell application "System Events" tell process "App Store" -- click text field 1 of group 1 of splitter group 1 of window 1 tell window 1 click text field 1 of group 1 of splitter group 1 key code 48 -- set value of UI element 1 of group 1 of splitter group 1 to "boo" end tell -- properties of text field 1 of group 1 of splitter group 1 of window 1 end tell end tell on adding folder items to this_folder after receiving these_items tell application "Finder" if not (exists folder "converted" of this_folder) then make new folder at this_folder with properties {name:"converted"}end escape_pathreturn the_pathset the_path to path_components as stringset item counter of path_components to my escape_string(path_component)set path_component to item counter of path_componentsrepeat with counter from 1 to count path_componentsset path_components to every text item of the_pathon escape_path(the_path)end left_pad_numberreturn text -the_length thru -1 of ("00000000000" & the_number)on left_pad_number(the_number, the_length)end format_dateset d to left_pad_number(day of the_date, 2)set m to left_pad_number(month of the_date as integer, 2)set y to year of the_date as texton format_date(the_date)end file_matchesreturn the_matchset the_match to POSIX path of the first item of matches as stringif matches is not {} thenset matches to every file of disk item (the_path) whose name begins with the_filebaseset the_match to nullset the_path to POSIX path of the_pathset the_filebase to first item of text items of the_filename & "." as stringset the_filename to last item of text items of the_filename as stringset the_path to text items 1 through -2 of the_filename as stringon file_matches(the_filename)end file_existstell application "System Events" to set fileExists to exists disk item (the_filename)on file_exists(the_filename)end write_logwrite timestamp & the_log_message & character id 10 to the open_target_file starting at eof as «class utf8» # 10 = linefeedset the open_target_file to open for access POSIX path of LOG_FILENAME with write permissiontell (current date) to set timestamp to short date string & space & time string & ": "if LOG_FILENAME is not equal to "" thenon write_log(the_log_message)end update_plexset cmd to "curl \"" & PLEX_UPDATE_URL & "\""write_log("Updating plex ...")if PLEX_UPDATE_URL is not equal to "" thenon update_plex()end read_file_extensionreturn the_file_extensionset the_file_extension to text items -1 through -1 of the_filename as stringon read_file_extension(the_filename)end build_recording_namereturn filenameset filename to filename & " - " & recording_episodeif (recording_episode is not equal to "") thenset filename to filename & format_date(recording_date)set filename to filename & "S" & left_pad_number(recording_season_num, 2) & "E" & left_pad_number(recording_episode_num, 2)if recording_season_num is not equal to "" and recording_episode_num is not equal to "" and recording_season_num is greater than 0 thenset filename to program_title & " - "set recording_episode to my CleanName(episode of the_recording as text)set recording_date to (start time of the_recording) as dateon build_recording_name(the_recording)end build_recording_pathreturn directoryset directory to program_title & "/" & recording_yearset directory to program_title & "/Season " & recording_season_numset recording_year to year of (start time of the_recording as date)set program_title to my CleanName(title of the_recording as text)on build_recording_path(the_recording)end delete_recordingwrite_log("Recording deleted.")delete the_recordingwrite_log("Deleting recording...")if ENABLE_PROGRAM_DELETION thenon delete_recording(the_recording)end tag_metadatawrite_log("Finished tagging metadata.")write_log("ERROR: failed to run atomic parsley to set metadata on " & the_output_file)write_log("Successfully tagged metadata on " & the_output_file)set cmd to cmd & " --TVEpisodeNum \"" & recording_episode_num & "\""set cmd to cmd & " --TVEpisode \"" & recording_episode & "\""if recording_episode is not equal to "" thenset cmd to cmd & " --TVSeasonNum \"" & recording_season_num & "\""if recording_season_num is not equal to "" and recording_season_num is greater than 0 thenset cmd to ATOMIC_PARSLEY_CLI & " " & escape_path(the_output_file) & " --overWrite --artist \"" & program_title & "\" --title \"" & recording_episode & "\" --description \"" & recording_description & "\" --longdesc \"" & recording_description & "\" --comment \"" & recording_description & "\" --TVNetwork \"" & recording_station_name & "\" --TVShowName \"" & program_title & "\" --genre \"" & "TV Shows" & "\""set recording_station_name to station name of the_recordingset recording_description to description of the_recordingset recording_episode to episode of the_recordingset the_program to program program_titleset program_title to title of the_recordingset recording_episode_num to EPISODENUM of epg_infoset recording_season_num to SEASONID of epg_infoset epg_info to read_epg_info(the_recording)write_log("Tagging recording with metadata")on tag_metadata(the_recording, the_output_file)end read_epg_inforeturn value of property list item "epg info"tell property list file the_plistset the_plist to POSIX path of build_recording_path & "/" & the_filewrite_log("Found XML metadata in " & the_file)if the_file ends with ".eyetvp" thenrepeat with the_file in program_filesset program_files to list folder build_recording_path without invisiblesset build_recording_path to POSIX path of build_recording_pathset build_recording_path to text items 1 through -2 of recording_location as stringwrite_log("Reading XML metadata...")on read_epg_info(the_recording)end LoadPropertieswrite_log("PLEX_UPDATE_URL: " & PLEX_UPDATE_URL)write_log("ATOMIC_PARSLEY_CLI: " & ATOMIC_PARSLEY_CLI)if ENABLE_ATOMIC_PARSLEY thenwrite_log("ENABLE_ATOMIC_PARSLEY: " & ENABLE_ATOMIC_PARSLEY)write_log("HANDBRAKE_PARAMETERS: " & HANDBRAKE_PARAMETERS)write_log("HANDBRAKE_CLI: " & HANDBRAKE_CLI)write_log("TURBO_264_MAX_ATTEMPTS: " & TURBO_264_MAX_ATTEMPTS)write_log("TURBO_264_PRESET: " & TURBO_264_PRESET)write_log("ENABLE_TURBO_264: " & ENABLE_TURBO_264)write_log("TEST_MODE: " & TEST_MODE)write_log("SHELL_SCRIPT_SUFFIX" & SHELL_SCRIPT_SUFFIX)write_log("LOG_FILENAME: " & LOG_FILENAME)write_log("TEMP_PATH: " & TEMP_PATH)write_log("SOURCE_TYPE: " & SOURCE_TYPE)write_log("TARGET_TYPE: " & TARGET_TYPE)write_log("TARGET_PATH: " & TARGET_PATH)write_log("ENABLE_PROGRAM_DELETION: " & ENABLE_PROGRAM_DELETION)write_log("ENABLE_TRANSCODE: " & ENABLE_TRANSCODE)write_log("Properties:")write_log("---------------------------------------")write_log("")set TEST_MODE to value of property list item "TEST_MODE"if value of property list item "TEST_MODE" exists thenset SOURCE_TYPE to value of property list item "SOURCE_TYPE"if value of property list item "SOURCE_TYPE" exists thenset TARGET_TYPE to value of property list item "TARGET_TYPE"if value of property list item "TARGET_TYPE" exists thenset TARGET_PATH to value of property list item "TARGET_PATH"if value of property list item "TARGET_PATH" exists thenset TEMP_PATH to value of property list item "TEMP_PATH"if value of property list item "TEMP_PATH" exists thenset PLEX_UPDATE_URL to value of property list item "PLEX_UPDATE_URL"if value of property list item "PLEX_UPDATE_URL" exists thenset ATOMIC_PARSLEY_CLI to value of property list item "ATOMIC_PARSLEY_CLI"if value of property list item "ATOMIC_PARSLEY_CLI" exists thenset ENABLE_ATOMIC_PARSLEY to value of property list item "ENABLE_ATOMIC_PARSLEY"if value of property list item "ENABLE_ATOMIC_PARSLEY" exists thenset HANDBRAKE_PARAMETERS to value of property list item "HANDBRAKE_PARAMETERS"if value of property list item "HANDBRAKE_PARAMETERS" exists thenset HANDBRAKE_CLI to value of property list item "HANDBRAKE_CLI"if value of property list item "HANDBRAKE_CLI" exists thenset TURBO_264_MAX_ATTEMPTS to value of property list item "TURBO_264_MAX_ATTEMPTS"if value of property list item "TURBO_264_MAX_ATTEMPTS" exists thenset TURBO_264_PRESET to value of property list item "TURBO_264_PRESET"if value of property list item "TURBO_264_PRESET" exists thenset ENABLE_TURBO_264 to value of property list item "ENABLE_TURBO_264"if value of property list item "ENABLE_TURBO_264" exists thenset ENABLE_PROGRAM_DELETION to value of property list item "ENABLE_PROGRAM_DELETION"if value of property list item "ENABLE_PROGRAM_DELETION" exists thenset ENABLE_TRANSCODE to value of property list item "ENABLE_TRANSCODE"if value of property list item "ENABLE_TRANSCODE" exists thenset LOG_FILENAME to value of property list item "LOG_FILENAME"if value of property list item "LOG_FILENAME" exists thentell property list file thePListPathif my file_exists(thePListPath) thenset thePListPath to MyParentPath() & "Export To Plex.plist"on LoadProperties()end export_with_handbrakewrite_log("ERROR: failed to export with Handbrake!")write_log("Exporting with Handbrake completed.")write_log(cmd)set cmd to HANDBRAKE_CLI & " -i " & escape_path(input_file) & " -o " & escape_path(output_file) & HANDBRAKE_PARAMETERS & SHELL_SCRIPT_SUFFIXwrite_log("Exporting with HandBrake...")on export_with_handbrake(input_file, output_file)end export_recordingwrite_log("ERROR: The export was not successful! " & temp_file)write_log("Finished post-processing file " & temp_file)update_plex()write_log("ERROR: Could not create the directory " & output_directory)write_log("ERROR: Could not transfer the file using command: " & file_move_command)delete_recording(the_recording)do shell script file_move_commandwrite_log(file_move_command)do shell script "mkdir -p " & escape_path(output_directory)write_log("Transferring the file to the Plex directory.")if export_success thenset file_move_command to "cp " & escape_path(input_file) & " " & escape_path(output_directory) & "/" & escape_path(output_filename)set output_filename to build_recording_name(the_recording) & "." & read_file_extension(input_file)set temp_file to input_filewrite_log("Transcoding is disabled.")set file_move_command to "mv -f " & escape_path(temp_file) & " " & escape_path(output_directory) & "/"set export_success to truetag_metadata(the_recording, temp_file)write_log("Export complete. Post-processing the file " & temp_file)set temp_file to the_match as textif the_match is not null thenset the_match to file_matches(temp_file)export_with_handbrake(input_file, temp_file)export_with_turbo_264(input_file, temp_file)if ENABLE_TURBO_264 thenwrite_log("Temp file location is " & temp_file)set temp_file to my TEMP_PATH & "/" & build_recording_name(the_recording) & "." & TARGET_TYPE as stringset export_success to falseif ENABLE_TRANSCODE thenset output_directory to TARGET_PATH & "/" & my build_recording_path(the_recording)set input_file to recording_path & "." & SOURCE_TYPE as stringset recording_path to POSIX path of recording_pathset recording_path to text items 1 through -2 of recording_location as stringwrite_log("Exporting the recording " & recording_location)F�|� �t>��M�ͱ69R��X�Ћҿ�D���YL�@O4l���x�9�m��Jz��T�g��������?���?����˿�����׿�����ۯ��_���o���_���ۯ�������W)Mӥ��|ESe}�����(��@�|�U�}U�� ����S�V�����v��_1�v�8����Na��O����U�kS{�c鿾��1���|#�f� f]����:�U�kB�j��k�A��͝��o�>r�ݖ���t���k�hS�ОQ> �^Yr�2�����|�DŽ:S?+�����t���'/����R��.���tx�����P�g"s=���~t�`��l.)�l�������K�)�>���sM˷;����8w3�Rf���ey�ܽ�!�����Kd,�7_�k���U�=���k������~���ڼ�d��]�Z��~p���[u��3����E�ĺ���.�Z��U���7���i�����l�^���'�-(�R��«�޹3�?�w�E��� ���� ?a����o�e k��� ?�3K(�j��]�9.w¬Ų��ԥ�݋Ep�CK�x�ҷ���H������)�mɳ�|�Xzk��B��Vqe�q>K2� n�\�j5��M���e=Com�~b������}Q W��n�Ͼu�֗��>ܚ�o�;������D��^��7��Z� ��ݭ���������� ��?��X۞fܶ��ڙ/��i�λ>{��$��"~�Q�ܿӭӐ�ϚF���z}�B�Z��&V�o���5��.a����d_�0������B��yh�+�f���|f��[����oӨ�b}/0T��EOh�<�Ԏ>_t������t��`��w�3W9���Y'�S� �p���?���B��/W�p©�cK���Y&�@S�?�E��(;(��?���K�1�O%|�+�l�}%O�c=�� �,���?�������D(�6/���� )=!\�g��u���#�@�\ŷ�g��c�s/XX?��(d?~��q �ʁ�W�.NȲ�D��ftVXo��Y2X��ؕ9�<��k`�T &2� <���0���)�f�M|sZ@(P�vL��~+��(:<�������m�TV|lڨ�bDk��[ӳ[B�\�����}�<��(�~e��Hp[F����Q��8T�A����qq5s����;�* �};���2���J�m\�z�N�E�l�q�q�����M|�sy�h��χ5͋����1S��0*'#�� �q�c 3�&@� `ٹFc~5{@X�S��Lmߴ1���"����M��ȱ�B4��#q���m`�>+��hC�r�G(�=�7��ʗ�U^!Ʈ;�����q��˺MmT��Lc *1�q8@ ܲ>� h��G��+��1��U �J����$X�@��S0���!�ڃ��|��˞�2�qv���.�����6͓�#����W0c� Y� ��o��R�у�����hafj��-/�v����N��� `��H^�O�P$q��?\�I�� s|�䮟��"-\u~;�ZQư�̩ ��t� 0"b���k�-�;����$���%��"���~�A����v`��빳��`�Ǒ}5�ȁI6����&��7�.���_�A�Ԉ�оkȁ�}#>[6?K�M��?��&)�H��� Z��6��ތ�d��S�*�Y��&o�a��,1r�{4�Qu+5ӑGQH�����^��B�8 J-���@�K�3��~c���:� ��I=^N6�L"l�3}��fQI;� 9�����|9^��k��À��u� ��$x"��C �Do����)P�wpٟE!}ɩ X�!��:��'��%���x*�l0��,�M��J}����� ���MJ���$���� r|���<���? ��d��԰c�6m_p��\8�>2k�u��[��h�'�ե �`����(�=���i��ݟ�!Θ=S�q���H���v��X9�D�&�;�TY����<�A +K�T���`��OZp*� ��e�\X}�i��Jvn�'���eD����� �ٯF,����YhQ>Sqd�N.z"O6�dg�瑉�q֣$���C0x��y ��;��U�K���p-�d���H�ّ |i�a��+�5�F�؊-喌�벖�=�Ɵ��jZp�%Q)�l� ���[.p�/eIO> x�Y��iV(c�d &��őXpd����)�[9,N�� S���H"����A��,��I�)��ٺ���`�2�����E�Ĝ����]y}� o*l�.�Ɇ��[E�p->-����Lݻ�>�=ܡ�Ӫf��|�X�I��/Gt���›��d �Xr���ϐw>Y���S\ ,�h��I�6�B��No�XݷC�w����}h�ƿ��AR"�(oG�E�N���k�P�f��)2c٘� /�@]`�8s���S0|3��+�����q:MpX,���FaEs�I���F��w�h�,����)�~�?�\1̽n� x�d����h��~�cW]�i=/��۝f{�Y�f���e�ܩQWp���3�v��R�4`k/SZ;�q�E{s>�8���`e��-�*��Ț�R����k����F^�s�����*�K��bU����R�"��Aq���81�x��tW9�>�'IvU]��@2h�-�ɛ�$�Sj%��x�������UV�e�"K�Wcr���C��=bUk`��Ra.$(���w�0g92��H�~uq��Dn ���R*!�4�V��p�!YO=Л�J��B}�0)�̔j0�qT��������E& �-�U͗��D���0�'�2��y7�s�VU\1��P���Z��0��r^���R*���,##+��|��,��p l�*� m��X�)�s� �,�ܔ��W��Q8w�J�!�-oQ��rU_��)��Yh�E�4e�3�RǢ���mS���a���T��I��(�`@�y�)v�7ƀe:<�&\u %u�_�;`�����$ h&�5�.���Ha���W��� �F1e�H���b��� � j�9S���6% �S���j#��h����j&���6}.T����k��o�S̘��ų�����)�\������qTU���z ��� ��]���s!��Z^.�k��+_� G���,��:�{�/�*@�K�+6�z�p��Cz��q���#T�&8�6�����H��Ts�,&���aU�Īd;�0�ޟ��-�N�� e�ϫ�֑W�� �&31���@�qH���E�� �If��-tO�����FvV�{��1��:2���?"g�U~#É\�C=�,ek�j��t��[v5�#��jI0��z���)p�~�A�q���� ��<^��z{*�iT":x��0��,z�@M������!��R�4W���Z�R�'0�����1���Dt��>���z�(���͉�hioY��#�>�[ʯ}=�UAEz)�N�!ȹ��J�7��q����/�>.�G��eV<��uؖ���htxl=f � GF��)�wJj���N����"�#KC����ڭ�ညsY�*7a*��l>H��e�!W��RjE+���%[� lu p5�Rb�(�捻U�Qm�6�_Ǽ��zGH]x{�-�y�z�������9��X�)�k%�$�X^�\�g =HW�e�� ��e1jQT��$�����xՁCS��uGȝqǧ"�g�&%��>Q��YV���6�l7��^�� ��&��� /���$5j��� ��Ƀ��qS���w=�&7~�y�0s6�@�;Ŋ�����6��Y��.�Y�������A�o��I��4Nq���\`Y�J/�*���F9���`��u��nqQbݍ*$�_�A��P'W,��ɷ���O���m���*��lwS��T�C�������ئ��;u�\.�5���_ ���)ےSﲳ^A���ĤM�l�[�'��x��=U���d$������{��A���UK:ǚڔ�"�޳��`h�NI��=��3�JSIӼH�����fw��O���L�� f�e���Xo-^�PN׫ q��"�o̥sJ}q^��NF���I~�I�4�D? H��L����� ��a�IٕJI;@ҌƠ��q�ָ��V����z��/���q�k�L�߅��vD�5rD��e{c;3���G���`�l~���9k���d�V�ߴ"��Y� k<�q�8�j*3�J{�Q����n��q��pIu_T��Ò"��}�����KIA~��>-@sk���g�(Y�H���{J-��԰�>8R�'@�M�m�E�n��L��,[ ����W�#�f�����]0�4+4e�L���F-sN�$�4���A�0\�0���;�`�ɡ\1G��#U�0���"�\AwH�]!�k��؟���{^4��C��,�����[�F7�����(K����B*v:`�91�ѥR=�aP[�f]�(Z�.'&j8��DR-�:^�<�8�S��1�'���d��_6 G>F��ɫE^ �YZaȞ]��ЬBF��2q�A����4���<�� ��T)?NI?FS8bnQF0#Jw����#�A�>�ƌ�ɡIe�nh�;��yBS�l@��n��e��&�×Ye�<;���@yt(������Q�i ��HB`�������ܑ��0�����2j=0�*wg�0��#+s�)<ş���5@O�0�;2��=4we��� Su�z-N���g캛����]�Ƒp`�.0�)��l#�sڧU� ��~���>"���AW��|{���Z�T9���NKG7�u��:��u%:�����2~�9�Yd�-��H$kj��:~^���qS�BoFE S�'�R����m�V�����M3� �ŒΌ�Tגv}|�^p7_]:���3��V�.���%�n\-O!�9q�x�8韑��Pϕ�@%��J�ʥ���!��Ga�j:Ы��<���C~���(��EZ�N�{�T�g��据�FL%s}� Ȋ��E��;��M�;d��������= +Ate+�o0�QW>�-���S����~0 ����W3�p�+�4k)(��+��w����a�A�'�4�u�Y�n_�T��,/���|�Շ{�P߾'��.��)~i�S}קU�`M�X�iSi�R��az�g��V�C��a�lym]�l�//�PY#��$k�� ��Ӵ �L7E3�r���~�uɭi�R �G�s�9�P4�Y�ը���h��Zx���$с}?�jr��Y&2~U�����|5pz��}"%�괃j����*�lo�dՀ�݌>�L��[J�ZF����k.�Bú>LWC��@<�+�9�ߕ�gI� @�]�-_�I������ �~H����� � a�Eg�����[��ө�2~���%(�]L��yj$6W2}�|-4[��� _m��л�� =�]�P�-��EI����¤�n�~�󳛸;�>��q�>��2{��#W' F� �yl�R��S���V�+����׷Dji����Ꞇ"5~?nC#�Su�Raw��%^3��8����~C���)�w_����U�x� ���X���w+,��YJ�E'-F�tR��LV>P���“��6}�崒���X������-v(��@T���`���n}Ve@}�Ơd�à2��u,��V�kdpFῩߢ�ᥤ�����f}狴�by�q�j�|�v�WcTg�X�򽱾ʉ$�g_m�Õ��� �QÈ1�4s�{1���a�>��'�y}���\�H� �h}?Մg�Oϸv�}��I�a���c�a��D19�0�3��x�g��Y6p:v�£���2�+��7j����t>lxW���$����� J��Y�p�<`���I��7R���<t��4 � � � �  g � � � > � �  g � � M � � b~�x}��3HOS��3{����v��5f���F��]s�Z��/u���&]��J�� /O_p��&W��Q`r����+ ` � � � !E!f!�!�! "J"�"�#�#/$v$�$ %S%�%�%�%k&�&�&0'A'�'�'t(�(�()Q)b)s)�)�)&*�*�*+c+�+�+3,�,�,,-]-�-�-�-H.�.�.�.�./�/0:0E0Q0f0�0�0+1�12r2�2T3�3:4�45�5 6e6�6S7`7�7�7�7�78;8X8u8}8�8�8�8�8�8*9�9�9�9�9:=:E:O:�:�:�:�:�:;<�<�<�<�<�<,=5=A=R=c=�=�=�=>P>�>�>�?@?@N@p@�@�@A8AhA�A�A�A�A�A BBUB�B�B�B3CWC�C�CDpD~D�D�D�D EEE�E�E�E�E$FiF�F�F�F0G{G�G�G(HnH�H�H5I�IJ[J�J;K�K LsL�LGM�MNxN�N OFO�O�O�O:PxP�P�Pb~b�b�b1ckczc�c�c�cdJd�d�d�d�dEe�e�e�e�efMf�f�f�f�f�f gZgkgxg�g�g�ghUh�h�i�ij0jUj{j�j�j�j�j/k�k�k�k�k�k�k�klGl�l�l mHmnm�m�m�m)n;n�n�n�n�noko�o�o�oGp�p�p�p qq"qIqhq�q�q�q r*r_rVs�s�sBtKtZtwt�u�uv�v�v�v�v�v�v:wRwjw�w�w�wx�x�xQybypy�y�y�y@zdz�z�z�z;{W{d{�{�{�{!|K|r|�|�|�|}4}�{��k�Ӈ�!����5�S�u�����(�q�ό���5�c��������=�[��������"�G�m�����E�l�������H�q�����Ƒ��8�^�x���ܒ��a����~�ǔq����9����� �G���ӗ����R�n���ڙ�B�q�����̚Қ��͛��:�d�����7�v���Ɲ�%�.�f�����ʞ��r�}���������ՠ�&�O�v���ȡ��=�w�����Ң���K�p���ͣ�:�Y�y���٤�)�D�P������6�X�����զ��&�M��������.����������/�L�]�u�����ʩ� �1�P������5�R�e�~�����ë���*�H�p�����t�������1�`�}�������:�k�ڱ����-���ݳu���д�p�� �+�E�i���������9�]�����޷ ���Z�|���(�O�f����������'�>�L�m�������Ȼ�����D�S�c�y�������ݼ���4�D�R�^�����½ѽ���2�H�`������ �:�U�b���������Ϳ���+�M�]�r�{�����������=�a����������I�U��������3�A�N�`�f�n������������� ��'�/�;�J�p�w���������������������1�9�O�^�������?�s���������3�<�Z�g���������4�=�c�v����������2�=�N�x������������%�/�8�C�Z�j�~������������(�D�b�����������&�;�H�V�y�����������/�=�c�����������&�5�K�V�[������������������&�B�_�m������������������/�G�d�m�z���������������=�d�v������I�s������������&�M�n�������7�`�;�f����]�������z����9�o���'�����*�6�Z���i������T��� �j�������;�q���&�T�������"�w���F����������3�[�}��������� �4�������C�m�������*�N�r��������T�t�<�c�������p�������M�^�p�������%�5�J�������)�_����������Q������,�C�h���F�m��������(�H�x��������%�F�������*�n�������s����M��������N�u��������0�g������:�o�����U�k�~�����E�S�x��� �#�O�����;�[�s��������+�;�a����������C���������'�i������� /{����j���"^����?a������ !(6JV��Y���3K[~� G � �  ]  E � � 3 � �  U � � W��U}����Nv��c�� O���!L���X�����!Y��&j���2Z���'��0c���#4Sx��� ,Or�����!Cg~����.��;]�� ? Y � � !/!R!�!�!K"m"�"#,#[#{#�#3$d$�$�$�$%F%X%�%&&�&�&�&'K'i'�'�'�'�' (u(�(b*|*�*�*�*�*�*2+U+v+�+�+9,~,�,-I-�-�-M.�.//Z/�/�/ 0E0{0�0�0�0X1t1�152�2 3t3�3�3�3+4]4~4�4�4�45,5`5�5�56b6�67%7Q7�7#8@8q8�8*9\9�9:;;/;d;�;�;�;<I<�<�<�<>>>j>z>�>�>i?�?�?�?@D@q@�@AXAeAqA�A�A�A$BfB�B�B�BCQC�C�C�C�C4DQDoD�D�DEOEvE�E�EF"FEF�F�F�FG#G4GIGgG{G�G�G?HrH�H�HIIRI�I�I:J�J�J.K�K�KL�L�L�LNMhM�M;NsN�N�N*O�O�O]P�P"QoQR�R6S�S�S�S(T�T,U�U6V�VWJW�W�W"XmX�XYfY�Y�Y ZQZ�Z�Z�Z[[�[N\n\�\�\]0]u]�]A^�^_@_�_�_`7`R`q`�`�`�`a=ava�a�a%bob�b�b�b�b c@c}c�c�cAd�d�d�dYe�e�effLf�fgJg�ghBhQh�h�h)i�i�i�iej k�k�k�lXm�m�mQn�no#omopop�p�p�p@q�q�qrr�r�r�r�s�s8t�tuRu�u�uvdv�v�v�w�wxOx�x�x�x1y�y�yz�z{x{�{|�|�|�|.}@}�}�}�}~~~��€�Q���ǁU��� �q���ƄE������������o�d�O� ��P�r�����ݎ�2�b�x���Ə��K�_�������֐��-�P���Α��#�N�s����� �%�G�[�}���N�|�������(�6�l������M�i������"�g����9�n��� �>�_�����ܙ �4�J���ښ�;���՛��:�~�ٜ�s�������!�D���۞�(�D�e�t�����ӟ��%�2�D�_�d�������Šܠ �N����P�v���ߢQ��� �G���,�j���ܥ�M�����ۦ���'�A�^�x�����ͧ��0���(�C����E�b���֪��M�m�����@�e����.�N�y�����3�s�����G�p�����S������'�c����R�n���ݴ(�������@�e���7�X���ż�0�����Ž�%�F���ƾ�{���ؿ�_�����6�}���7������l����������.�O����������&�G�j���������'�C�a��������� �.�Q�|���f������V����� �F������o�����)�Z������������C�]�����,�������P�}������B�v������D�x����O�{�����#�O�|����C�z���4�q�$�u����������4�X�|������B�\�s����������1�P�������(��5�K�c����������!�Q����������4�W�~������� �U�������C�r�������w�����-�]�������h������� �-�Q���������'�T������,�o�����&�U�������'����K�w�����'�~��������(�|�����g�����]�x�����K���A�Z�l��������<�n�����M����)���^���I�������(�=�i���.�e�����#�c�|�����������A�U����������C�[�������/�c�u��������� ��=�j�������Ajy�� !8Np���� ;v����(Sh��)��0>T{��>n���=]{����Kr}� # 9 G X � l � � � �  � � � � P���7v�� 1[2n��� Fj��� 5x���� (c���!7W���K|��<Ldn.^���d�����?ap�����'EZv�����8~���*Fg����� & 3 < M ^ ~ � � � � � !!#!8!�!�!�!�!�!�!"G"`"}"�"g����"�"�"@#_##�#s$~$<&L'{'�'%*s+�+�+,3,g,�2�203N3m3�3�3�34G4y4�4�4�4 5*5H5k5�5�5�5606R6x6�6�6�67*7Q7p7�7�7�7�7$8D8i8�8�8�8�89#9E9j9�9�9�9�9 :,:U:�:�:�:;>;];�;�;�;�;�;<8<[<x<�<�<�<=:=`=�=�=�=�=>?>\>y>�>�>�>�>?1?X?v?�?�?�?�?@.@M@l@�@�@�@�@A/ALAnA�A�A�A�AB>B`BB�B�B�BC)COC�C�D�D�D EDEmE�E�E FF$FMF0GGG�G#H@HeHH�H�H�H�H"K5K9KzK�K�KXLjL�L�L�L�LMAM�M�M,N^N�N�NOpO�O�O�O�OPdP�PQ,QNQ�Q�Q�Q=RiR�R�R�R�R�RSOSmS|S�S�STJT�T�T�TU-UYUoU�U�U�UhV|V�V�VW3W]W�W�W XRX�X�X�X�X YY1YDY`YxY�Y�Y�Y�Y�YLZcZ�Z�Z�Z�Z/[?[R[�[�[�[�[�[�[)\K\X\�\�\�\�\ ]B]�]�] ^8^g^�^�^�^_A_�_�_�_&`n`�`�`�` aba�a�a�a�aHbWbkb�bc0cLc�c�c�cd8dJd�d�d�d�d�dCe]ene�e�ef@fef�f�f�f#gUgmg�g�g�g�g h8hph�h�h ii0iDiki�i�ijFjPjdj�j�j�j�j�jk)k_k�k�k&l2lKl�l�l�l�l�l�l m"m�m�m�m�m�m#n=n]n�n�n�n�n;oQowo�o�o'p1pOpcpyp�p�p�pqq(q8qYq�q�q�q rHr�r�r�r�rsLs�stit�t�t$unu�u�u�uGv�v�v�vwvw�w�wx$xQx�x�xyCySysy�y�y@zpz�z�z�z:{J{[{�{�{�{|*|J|p|�|�|�|�|}�}�}�}&~k~{~�~�~�~�~�~?a����#�J�q���ɀ��5�Y�k����Á���[����ӂ�e�s�������������*�8�E�q�}�����ȄՄ��-�i�x���…υ���,�8��������+�E�_�p���������)�=�L�|���ψ����0�P�q�܉ �;�{���Ȋ����Ë����������K�����͎��'�C�k�����m����W������M������%������=�R�����#���ɕ��V�_���–��V�������.�d���˜�8�]���ә� �9�t����+�y����.�Y���Ӝ�}��t������;�[�w�����ß��+�M�n�����>���١��<����}���ӣ�(�\�r������� �6�`�����ܥ��,�?�����٦��#�5�P�s�����ԧ� �<���2�:�[�d�w���� �U�5�X�r�|��������A�Y�y���̬%�c�����f���®���]�p�˯ׯ� �%�:�Q�q���°�j�{�������ıS���۲��-�Z���2�~��������� �*�[�������� �I�a������ �]��O�����ݸ�� �%�A�P�y���ҹ�L�~�˺޺D�n�Ż׻ �*�J���μ��B�]�y������1�B�P�����Ǿ۾�#�2�t���Կ��o������0�M�t�������F�x�����"�8����������.�l��������2�O���������6�H�i�t��� �!�5���$�E���������)�k�����S������N������q�{��������<�a�f�o����������8�n������5�b������������0�W��������-�X�d��� �8�l���������������3�=�[�����������Y�����������d�s����(�;�p��������A�p��������>�l���e����������[�����c�����1�Y�����%�H�m�����3�k����������P�������!�S�f�z���S��������� �:�i����7�T�t�Z������*�L�v�������.�J�m���������5�k�����������'�W�����I��������)�T�m�~����I�����*�z����������� �"�=�^�x����������7�D�O�n�x��������5������� ��B���������.�X�w���/�S�|������� �3�>�K�x������?�N�e��������F�y������*�_����������?�p������J�W�p����������*�q���������1�F�W�u�����.c�Qf���0\p���G|��� .Pj��,;Vr���,;W��7Gn����,;L_����  ; [ � � � � �   ; [ � � � � �  4 N ` | � � $ M � �  C { � �  Mg���'dy����Np����6Hq�����!c�?X{��?h��Ab���,Ne��*s����(iu�����M�� #^��S����Ym}� G���4n��� < � �  !0!@!a!�! "C"r"�"�"�"Q#�#�#�#p$�$�$�$%8%V%}%�%�%&&/&n&�&�&�&'6'E'}'�'�' (-(](�(�(�()J)V)e))�)�)***-*`*~*�*H+n+�+�+�+ ,,K,},�,�,�,�,�,�,*-6-B-R-�-�-�-�-�-.'.9.�./k/�/�/00,0K0v0�0�0�0�01+1F1k1�1�122'262O2]2~2�24"4c4x4�4�4�4�4�455'575G5�5�5�566M6`6�6B7o7�7\8}8�8�8y9�9�9,:_:g:z:�:�:D;V;e;{;�;�;�;�; <<=<J<o<�<5=b=l=z=�=�=�=`>�>�>�>�>?-?L?c?r?�?�?�?@@$@H@�@�@�@3AgA�A�AGB�B�B�E�E~G�G�GHOH^H�HIEI^I�IHJ�J�JKtK�KLoL�LM;M�M�M�MNZNuN�NCO�O�O"P@PRPP�P�P�P�PBQ^Q�Q�Q�Q(RIRR�R�R�R�RS#SeS�S�ST�TUfU�U�U�UVeV�V�V�VW&W_W�W�W�W XHXjX�X�XY&YfY�Y�Y�Y�Y�Y ZZ_Z�Z�ZF[|[�[�[�[2\�\�\�\�\-]�]�]�]W^r^�^�^_i_�_�_�_I`�`�`�`.aea�a�a�a�a4bNbnb�b�b�bc1c\c�c�c�cd"dBd]d�d�dSe�e�e�e6f`f�f�f�fgUg_gwg�g1hOhth�h�hii�i1jYj�j�j�j�j�jk3kQk{k�k�kJljl�l�l�l�lmm"m@mNm\mqm�m�m�m�mn%n>nbn�n�n�n�n oEoyo�o�o�o�op[p�p�p�p qHq�q�q r/rJrcr�r�rs's�s�st&t\t�t�tu:uhu�u�u�u vMv�v�v�vwdw�w�w�w�wx!xox�x�x�x�x y6yJyhy�y�y�y�y�yzAzVz�z�z{5{w{�{|&|�|�|^}�}�}�}~\~q~�~�~>��� �S�Z�w�����؀���<���Ӂ�6�v�����-�M�s�����׃��"�C�h�����΄ӄ��3�L�����ͅ.�i����$������'�F�c�~������J�������#�E����L�ʋ��3���A�\�����ɍ�G������ �3����=�o����E�^�u���đ֑����=�y���ܒ�C������ � �K�q����"�\����q�����Ζ��f��������&�J���Ę�L���ܙ�#�H�g���$�D�Y�u���̛ߛ��3�Q���˜ߜ�� �'�?�X�x��������^���ڞ��,�?���ן�^�����P���ơ���0�����ע���=�S�d�����<�W�w�����Ф��3�^�������c�����Ϧ8���ڧg����/�c����s�����5���۫��9�j�{�������¬�� �U�����ڭ�.�N�[�����*�;�X�~���̯���N�c�����ɰް��f�ձ��]�s���ٲ���(�<�R������"�Y�r�����˴��5�J����y�ܶ�its month, its day, its time} to {0 + (text 1 thru 4 of enexp), 0 + (text 5 thru 6 of enexp), 0 if not (the folder "Temp Export Folder" exists) thenif (the folder "Temp Export Folder" exists) then set FolderLoc to (the folder "Temp Export Folder")register as application growlName all notifications allNotificationsList default notifications enabledNotificationsList icon of application appNameset enabledNotificationsList to {"Success Notification", "Failure Notification"}set allNotificationsList to {"Success Notification", "Failure Notification"}set isRunning to trueif appIsRunning("GrowlHelperApp") thenset processnames to name of every processproperty successCount : "0"property appName : "Day One"property growlName : "MailToDayOne"set position to {300, 150}set position to {40, 120}display notification theDescription with title theTitleend conditionsmake new document window with properties {perspective name:perName} at end of document windowsset perspective name of document window 1 to perNameif visible of front document window is true thenon conditions(perName)end open_perspectivemy conditions("Someday")my conditions("Available")if (nTotalAvailable) > 0 thenset nTotalAvailable to count (every available task of every flattened context)my conditions("Flagged")if (nFlagged) > 0 thenset nFlagged to count (every available task of every flattened context whose flagged is true)my conditions("Forecast")if (nDue) > 0 thenset nDue to count (every available task of every flattened context whose due date is not greater than currDate)set currDate to (current date) - (time of (current date)) + (24 * hours - 1)my conditions("Inbox")if (count (every inbox task)) > 0 thenon open_perspective()open_perspective()do shell script "pwd"set end of senderNames to value of first cell of row rowAddresstell sheet sheetIndexset rowAddress to address of row of item 1 of cellHitset sheetIndex to sheetNumberset cellHit to (every cell whose value is email)if (every cell whose value is email) is not {} thenrepeat with email in emailsset end of emails to address of senderrepeat with sender in sendersopen replyMessageset the content of replyMessage to "Hello World
    This is a plain text test



    " & OldContentlog ("PLAIN TEXT!")set the content of replyMessage to "Thank you " & "br>


    " & OldContentlog ("HTML!")if has html of replyMessage thenset replyMessage to reply to replyToMessage without opening windowtell app "Numbers"set end of senders to sender of replyToMessageset OldContent to content of replyToMessageset replyToMessage to message messageCounterrepeat with messageCounter from 1 to count of messages in currentMailFoldertell currentMailFolderset currentMailFolder to folder of (get selection)set senderNames to {}set cellHit to {}set emails to {}set senders to {}return theDataURIset theDataURI to my getDataURIForImage:theSymbolset theSymbol to my imageWithSymbol:"doc.text.below.ecg" ofSize:128end imageWithSymbol:ofSize:return theSymbol's imageWithSymbolConfiguration:configset theSymbol to my (NSImage's imageWithSystemSymbolName:theSymbolName accessibilityDescription:(missing value))set config to my (NSImageSymbolConfiguration's configurationWithPointSize:theImageSize weight:(my NSFontWeightRegular))on imageWithSymbol:theSymbolName ofSize:theImageSizeend getDataURIForImage:return "data:" & "image/png" & ";base64," & (thePNGData's base64EncodedStringWithOptions:0) as textset thePNGData to theBitmap's representationUsingType:(my NSJPEGFileType) |properties|:(missing value)set theBitmap to my (NSBitmapImageRep's imageRepWithData:(theTIFFData))set theTIFFData to theNSImage's TIFFRepresentation()on getDataURIForImage:theNSImagedo shell script "xterm -e bash -c '" & winetricks & cmd & ";echo \"Winetricks has finished (status: $?). Press to return key to exit.\";read'"if not cmd is "false" thenset cmd to first text item of ((choose from list (every paragraph of (do shell script winetricks & cmd & " list;:")) with title cmd) as text)if cmd is "false" then error number -128set cmd to (choose from list (every paragraph of (do shell script winetricks & "list;:")) with title "Winetricks") as textproperty winetricks : "export PATH=" & PREFIX & ":$PATH;export WINEPREFIX=" & WINEPREFIX & ";winetricks "property WINEPREFIX : "$HOME/.wine"property PREFIX : "/usr/local/bin"do shell script "growlnotify -a Alfred"return execute_javascript(browser, jquery, whatsapp, conversation_title, message)repeat with browser in browsersset browsers to {"Google Chrome", "Google Chrome Canary"}set message to rest_arguments as stringcopy item i of arguments to the end of rest_argumentsrepeat with i from 2 to length of argumentsset rest_arguments to {}set conversation_title to first item of argumentsclose access whatsapp_fileset whatsapp to (read whatsapp_file)open for access whatsapp_fileclose access jquery_fileset jquery to (read jquery_file)open for access jquery_fileset whatsapp_file to (POSIX file (javascript_folder & "js/whatsapp.js"))set jquery_file to (POSIX file (javascript_folder & "js/jquery.min.js"))set javascript_folder to POSIX path of ((the path to me as text) & "::")on run(arguments)end execute_javascriptif msgs is not "" then return msgsset msgs to execute t javascript "msgs"execute t javascript whatsappexecute t javascript jqueryexecute t javascript ("var message = \"" & message & "\";")execute t javascript ("var conversation_title = \"" & conversation_title & "\";")if URL of t starts with "https://web.whatsapp.com/" thentell application browserif not app_is_running thenset app_is_running to is_running(browser)on execute_javascript(browser, jquery, whatsapp, conversation_title, message)tell application "System Events" to (name of processes) contains app_nameon is_running(app_name)do shell script "~/Development/bash/commands/bin/pushover -m \"" & message & "\" -t \"LaunchBar\" -d \"Air\""set newTarget to theFolder & fileNameset fileName to text (1 - (offset of "/" in reversed)) thru -1 of theTargetset reversed to reverse of characters of theTarget as stringset theFolder to the POSIX path of (choose folder with prompt "lead me to your files")set versionLength to 2 -- How many digits for versioning? v1 / v01end getMessagePartsreturn messagePartsset lastWasText to trueset the end of messageParts to stringArgset item (count of messageParts) of messageParts to newLastset newLast to my join(linefeed, {lastText, stringArg}) as stringset lastText to item (count of messageParts) of messageParts as stringif lastWasText thenset getAttachment to trueif stringArg is equal to "--attachment" thenset the end of messageParts to POSIX file stringArgif getAttachment thenset stringArg to anArg as stringrepeat with anArg in argsset lastWasText to falseset getAttachment to falseset messageParts to {}on getMessageParts(args)end getMyPhoneNumberreturn myphoneerror "You must add the line:" & linefeed & "export MYPHONE=##########" & linefeed & "to your .bashrc file."if myphone is equal to "" thenset myphone to (do shell script ". ~/.bashrc && echo $MYPHONE")on getMyPhoneNumber()return joinedStringset joinedString to myList as textset AppleScript's text item delimiters to myDelimiteron join(myDelimiter, myList)return "Message sent"return my join(linefeed, errors)set the beginning of errors to (count of errors) & " of " & (count of messageParts) & " message parts failed to send with the following error(s):"if (count of errors) is greater than 0 thenset the end of errors to errmsgsend messagePart to iMessageRecipientsend messagePart to smsRecipientrepeat with messagePart in messagePartsset iMessageRecipient to participant phoneNumber of account id iMessageTypeset iMessageType to (id of 1st account whose service type = iMessage)set smsRecipient to participant phoneNumber of account id smsMessageTypeset smsMessageType to id of 1st account whose service type = SMSset messageParts to my getMessageParts(argv)set messageParts to my getMessageParts((items 3 thru (count of argv) of argv))set messageParts to {defaultMessage}if (count of argv) is equal to 2 thenset phoneNumber to item 2 of argvreturn "ERROR: --to requires an argument"if (count of argv) is less than 2 thenif (item 1 of argv) is equal to "--to" thenset argv to {"--to", phoneNumber, defaultMessage, "--attachment", "/Users/robleach/Pictures/Icons/rob_face.jpg"}set phoneNumber to my getMyPhoneNumber()if (count of argv) is equal to 0 thenset errors to {}set defaultMessage to "applescript test"return do shell script "php -r 'print rawurlencode($argv[2]);' '' " & quoted form of theTextend copyHTMLTextToHTMLPasteboarddo shell script "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -e " & quoted form of theScript & " '' " & quoted form of theHTMLStrp.setString_forType_(ARGV[1].to_ns,OSX::NSHTMLPboardType);p.setString_forType_(ARGV[1].to_ns,OSX::NSStringPboardType);p.declareTypes_owner_([OSX::NSHTMLPboardType,OSX::NSStringPboardType],nil);p = OSX::NSPasteboard.generalPasteboard();set theScript to "require 'osx/cocoa';on copyHTMLTextToHTMLPasteboard(theHTMLStr)end htmlspecialcharsreturn do shell script "php -r 'print htmlspecialchars($argv[2]);' '' " & quoted form of theTexton htmlspecialchars(theText)return workDataset AppleScript's text item delimiters to OriginalDelimitersset workData to workData as Unicode textset AppleScript's text item delimiters to inNew as Unicode textset workData to text items of inTextset AppleScript's text item delimiters to inOld as Unicode textset OriginalDelimiters to AppleScript's text item delimitersset inText to inText as Unicode texton replaceText(inText, inOld, inNew)end getNoteLinkrepeat 120 timesreturn theNotelinkif theNotelink is not missing value thenset theNotelink to note link of theNoteon getNoteLink(theNote)display alert "copy done"my copyHTMLTextToHTMLPasteboard(childLinkHTML)set childLinkHTML to ""if button_pressed is "選択しているノートが親" thenset notebook1 to notebook "209.マンダラート"set theNote to create note with html tmplate title theNoteTitle notebook theNoteBookNameset tmplate to my replaceText(tmplate, "<>", prentLinkHTML)set prentLinkHTML to ""set theNotelink to my getNoteLink(theNote)set theNote to item 1 of theSelectiondisplay alert "ノートを選択して実行して下さい"if 0 is (count of theSelection) thenset tmplate to my replaceText(tmplate, "<>", "")if button_pressed is "新規作成" thenset tmplate to my replaceText(tmplate, "<>", my htmlspecialchars(theNoteTitle))set tmplate to htmlTemplateset theNoteTitle to text_returneddisplay alert "テーマを入力して下さい"if text_returned is "" thenif button_pressed is "cancel" thencopy the result as list to {button_pressed, text_returned}display dialog "マンダラートのテーマを入力して下さい" default answer "" buttons {"Cancel", "選択しているノートが親", "新規作成"} default button 3make notebook with properties {name:theNoteBookName}if (not (notebook named theNoteBookName exists)) then<td width='200' height='100' style='text-align:center;background-color:#fff; font-weight:bold; font-size:140%;'><<title>></td><td width='200' height='16' style='text-align:left;background-color:#cbdffa;'><<parentLink>></td><td width='200' height='100' style='text-align:center;background-color:#fff;'></td><td width='200' height='16' style='text-align:left;background-color:#cbdffa;'></td><table border='1' cellspacing='0'><div><title><<title>>property htmlTemplate : "property theNoteBookName : "209.マンダラート" -- 保存するノートブック名set days_old to file_age_in_seconds div daysset file_age_in_seconds to (current date) - file_creation_dateset file_creation_date to creation date of file_propertiesset file_properties to info for the_fileset the_file to choose file-- Some statements here...if i = 5 then error number -128do shell script "ping -o -t 5 www.google.com"set label index to 2tell (every file of folder folder_path whose creation date < expiration_date)display dialog "Files in folder \"" & folder_name & "\" that were created before " & short_date & " will be deleted."set short_date to short date string of expiration_datetell application "Finder" to set folder_name to name of folder folder_pathset expiration_date to (current date) - (weeks_old * weeks)set weeks_old to (text returned of dialog_reply) as integerset dialog_reply to display dialog "Delete files that are how many weeks old?" default answer "5"if weeks_old < 1 thenset folder_path to folder_path as textset folder_path to choose folder with prompt "Pick a folder to clean:"if not folder_exists thenset folder_exists to folder folder_path existsproperty weeks_old : 0property folder_path : ""closetell current tab of window 1tell application "Dash" to launchtell application "Sublime Text" to launchtell application "Terminal" to launchtell application "Mail" to launchtell application "Safari" to launchclick menu item "Choose Folder..." of m2name of every menu item of m2set m2 to menu 1 of menu item "Move" of m1name of every menu item of m1set m1 to menu "Message" of menu bar 1tell process "Microsoft Outlook"return "error?"if result thenset result to run script (POSIX file "/Users/IceHe/Documents/AppleScript/Lib/set_flag.applescript") with parameters {flag}end fmGUI_ManageSecurity_GotoTabtell application "htcLib" to fmGUI_ManageSecurity_GotoTab(prefs)on fmGUI_ManageSecurity_GotoTab(prefs)error "Couldn't go to Accounts tab - " & errMsg number errNumfmGUI_ManageSecurity_GotoTab({tabName:"Accounts"} & prefs)fmGUI_ManageSecurity_GoToTab_Accounts({fullAccessAccountName:"admin", fullAccessPassword:""})deconsolidate record theRecordon error errMsg--you may omit the errMsgkey code 15 using command downset the clipboard to bodytext as stringset bodytext to the clipboardkey code 8 using command downkey code 0 using command downtell w1set w1 to the name of first application process whose frontmost is truedisplay notification "starting eqMac2…" with title "eqMac2 Helper"tell application "eqMac2" to quittell application "Spotify" to pausedisplay notification "restarting eqMac2…" with title "eqMac2 Helper"if application "eqMac2" is running thenif current_track is track_name thendelay (track_duration - seconds_played)display notification "is now playing on Spotify" with title track_name subtitle track_artistif notifications thenset seconds_played to round (player position / 1) rounding downset track_duration to round ((duration of current track) / 1000) rounding upif not player state is playing thentell application "eqMac2" to activateif not application "eqMac2" is running thendisplay notification "Notifications: " & notifications & "\nInterruptions: " & interrupts with title "Now starting eqMac Helper..." subtitle "github.com/chad-cros/eqMac2-Helper"set interrupts to answer is {"Yes"}set answer to choose from list {"Yes", "No"} with prompt "Interrupt mid song?" default items {"Yes"}set notifications to answer is {"Yes"}set answer to choose from list {"Yes", "No"} with prompt "Turn on notifications?" default items {"No"}if a_stat is equal to "enable" thenclick checkbox "Share my photos" of group 1 of group 1 of window 1if a_stat is equal to "disable" thenif value of checkbox "Share my photos" of group 1 of group 1 of window 1 is equal to 1 thenclick button "Sharing" of tool bar 1 of window 1click menu item 3 of menu "iPhoto" of menu bar 1tell process "iPhoto"tell application "iPhoto" to activateif do_work is equal to "yes" thenset do_work to "yes"if start_iphoto is equal to "yes" thenif not appIsRunning("iPhoto") thenset do_work to "no"set start_iphoto to (item 2 of argv)set a_stat to (item 1 of argv)end tell -- Evernotedisplay dialog msgStr with title (name of me)log msgStrset msgStr to "••• NO Notes were found with the Delimiters •••"notebook nbNametitle titleNote ¬create note with html newNoteHTML ¬set titleNote to nbName & ": Weekly Summary " & date string of (current date)log newNoteHTMLset newNoteHTML to newNoteHTML & linefeed & ""if (numNotesWithDelim > 0) thenlog "end of repeat"end if -- Delimited Text was found& "
    " & textToAddToNote & "
    ""

    " & "Text From: " & noteHTMLLink & " (Updated: " & noteUpdated & ")
    " & linefeed ¬set newNoteHTML to newNoteHTML & linefeed & ¬log textToAddToNoteset textToAddToNote to foundItems as textset AppleScript's text item delimiters to ("" & linefeed & "
    ")set noteUpdated to date string of noteUpdatedset noteUpdated to (modification date of oNote)set noteHTMLLink to "" & noteTitle & ""set noteLink to note link of oNoteset noteTitle to title of oNoteset numNotesWithDelim to numNotesWithDelim + 1if ((count of foundItems) > 0) then ##CHG: Add IFset end of foundItems to item iItem of parsedListif (textStr ≠ "") and (textStr ≠ return) and (textStr ≠ linefeed) thenset textStr to text of item iItem of parsedListrepeat with iItem from 2 to (count of parsedList) by 2set foundItems to {}set parsedList to text items of noteTextset AppleScript's text item delimiters to {beginDelim, endDelim}set noteText to do shell script "echo " & quoted form of noteHTML & space & "| textutil -format html -convert txt -stdin -stdout"set noteHTML to HTML content of oNoteset numNotesWithDelim to 0set noteList to every note of notebook nbNameset newNoteHTML to "
    " & linefeed & linefeed -- & "

    "property endDelim : "!!!"property beginDelim : "***"property nbName : "TestExtractText"display dialog "There was an error cding to the finder window." buttons {"OK"}write text "cd " & theDir & " && clear"display dialog "There was an error creating a new tab in iTerm." buttons {"OK"}set theDir to quoted form of POSIX path of theDir as stringon CD_to(theDir, newWindow)set newWindow to true -- create window for any other files/foldersCD_to(thePath, newWindow)set thePath to (characters 1 thru -(x) of thePath) as stringset x to the offset of ":" in (the reverse of every character of thePath) as stringif not (thePath ends with ":") thenset thePath to thePath as stringrepeat with thePath in theListset newWindow to falseCD_to(currFolder, false)set currFolder to (path to desktop folder as string)set currFolder to (folder of the front window as string)set the clipboard to (pageTitle & "\n" & pageURL) as textset pageURL to URLset pageTitle to nametell first document of application "Safari"update every item with necessitydisplay dialog theString & theAnswerset theString to "3+2+1="set theAnswer to (theAnswer + 1)set theAnswer to (theFirstNumber + theSecondNumber)set the theSecondNumber to 2set theFirstNumber to 3set pages per document to 1set page width to 8set page height to 11[/applescript]key up controlkeystroke (ASCII character 29)key down control[applescript]end checkValuereturn value is not in {{}, "", missing value}to checkValue(value)end buttonPressed:if timer is not missing value then -- reset for next timeset button to alert's runModal()if timer is not missing value then current application's NSRunLoop's mainRunLoop's addTimer:timer forMode:(current application's NSModalPanelRunLoopMode) -- start iton buttonPressed:timerend updateCountdown:current application's NSApp's abortModal()set countdown to missing valueset timerField to missing valueset timer to missing valuetimer's invalidate()if countdown ≤ 0 then -- stop and reset for next timeto updateCountdown:timerend setupTimer:timerField's setStringValue:(countdown as text)set countdown to (giveUpTime as integer)tell (current application's NSTimer's timerWithTimeInterval:1 target:me selector:"updateCountdown:" userInfo:(missing value) repeats:true)timerField's setToolTip:"Time Remaining"timerField's setAlignment:(current application's NSCenterTextAlignment) -- not quite right in Big SurtimerField's setSelectable:falsetimerField's setEditable:falsetimerField's setFont:(current application's NSFont's fontWithName:"Menlo Bold" |size|:14) -- mono-spacedtimerField's setDrawsBackground:falsetimerField's setBordered:falseset timerField to current application's NSTextField's alloc's initWithFrame:[[0, 0], [40, 20]]if class of giveUpTime is not in {integer, real} or giveUpTime < 1 then return missing valueto setupTimer:giveUpTimeend no_op_on no_op_(sender) -- dummy action method to group radio buttonsbutton's setToolTip:(label)button's setTitle:labelset label to text 1 thru -2 of label -- strip the returnbutton's setState:(current application's NSOnState) -- NSControlStateValueOnif label ends with return then # set/checkbutton's setLineBreakMode:(current application's NSLineBreakByTruncatingMiddle)button's setAction:"no_op:"button's setButtonType:(current application's NSRadioButton)set button to current application's NSButton's alloc's init()set button to current application's NSButton's checkboxWithTitle:"" target:me action:"no_op:"set button to current application's NSButton's radioButtonWithTitle:"" target:me action:"no_op:"if (system attribute "sys2") ≥ 12 then -- use newer APIto makeButton(radio, label)end buttonAccessory:width:radio:(mainView's addSubview:it)(its setFrame:{{0, height - anItem * 26}, {width - 15, 25}})tell my makeButton(radio, label)set end of itemList to labelif label is not "" and label is not in itemList thenset label to (item anItem of input) as textrepeat with anItem from 1 to (count input)set itemList to {}set its titlePosition to 0set mainView to ittell (current application's NSBox's alloc's initWithFrame:{{0, 0}, {width, (height + 11)}})set height to (count input) * 26set input to input as listif not checkValue(input) then return missing value -- no button itemson buttonAccessory:input width:width radio:radioend comboAccessory:width:set end of comboList to anItem(its addItemWithObjectValue:anItem)if anItem is not "" and anItem is not in comboList thenif anItem ends with return then set anItem to text 1 thru -2 of anItemrepeat with anItem in (input as list) -- populate combo box menuset comboList to {}set its placeholderString to "Enter text or select a menu item" -- arbitraryits setLineBreakMode:(current application's NSLineBreakByTruncatingMiddle)set its numberOfVisibleItems to 10 -- arbitraryset its completes to true -- matches an item while manually enteringset its hasVerticalScroller to truetell (current application's NSComboBox's alloc's initWithFrame:{{0, 0}, {width, 26}})if not checkValue(input) then return my textAccessory:input width:width secure:false -- no itemson comboAccessory:input width:widthend textAccessory:width:secure:alert's setAccessoryView:itits setFrameSize:[width, last item of last item of (its frame as list)] -- restore widthits setFrameSize:(its (cell's cellSizeForBounds:[[0, 0], [width, 150]])) -- auto-size for contentits setStringValue:inputits setFont:(current application's NSFont's fontWithName:"Menlo" |size|:13) -- monospacedif input ends with return then set input to text 1 thru -2 of inputset input to input as textset its placeholderString to "Enter text" -- arbitrarytell fieldset field to (current application's NSTextField's alloc's initWithFrame:{{0, 0}, {width, 40}})set field to (current application's NSSecureTextField's alloc's initWithFrame:{{0, 0}, {width, 40}})if secure thenon textAccessory:input width:width secure:secureend adjustTimerFieldalert's |window|'s contentView's addSubview:timerFieldtimerField's setFrameOrigin:{(first item of spacing) + padding, (second item of spacing) - 18}set spacing to first item of ((first item of alert's |window|'s contentView's subviews)'s frame as list)alert's layout() # get new layoutif (system attribute "sys1") > 10 then set padding to 2 -- Big Sur +set padding to 13if timerField is missing value then returnon adjustTimerField()end setAccessory:using:addedWidth:return accessorymy adjustTimerField()set accessory to missing valueset accessory to my buttonAccessory:input width:width radio:trueelse if theType is "radiobutton" thenset accessory to my buttonAccessory:input width:width radio:falseelse if theType is "checkbox" thenset accessory to my comboAccessory:input width:widthelse if theType is "combobox" thenset accessory to my textAccessory:input width:width secure:trueelse if theType is "securefield" thenset accessory to my textAccessory:input width:width secure:falseif theType is "textfield" thenset width to accessoryWidth(addedWidth)to setAccessory:theType using:input addedWidth:addedWidthend accessoryWidthreturn width - 125 + addedWidthset width to first item of last item of (alert's |window|'s frame()) as listalert's layout()if addedWidth < 0 then set addedWidth to -addedWidthif class of addedWidth is not in {integer, real} then set addedWidth to 0on accessoryWidth(addedWidth)end setIcon:if iconImage is not missing value then set alert's icon to iconImageif not iconImage's isValid as boolean then set iconImage to missing valueset iconImage to current application's NSImage's alloc's initByReferencingFile:(iconType as text)else -- from a file - ASObjC doesn't like a bad initWithContentsOfFile, so this handles errors betterset iconImage to current application's NSImage's alloc's initByReferencingFile:(SYS_RESOURCES & "Alert" & iconType & "Icon.icns")else if iconType is in {"Note", "Stop"} then -- system iconalert's setAlertStyle:(current application's NSInformationalAlertStyle)else if iconType is in {"informational", "warning"} thenalert's setAlertStyle:(current application's NSCriticalAlertStyle)if iconType is "critical" thenset iconImage to missing valueto setIcon:iconTypeend setButtons:return buttonListalert's |window|'s setInitialFirstResponder:theButtonset theButton to (alert's addButtonWithTitle:okButton)set end of buttonList to okButtonif buttonList is {} then -- make sure there is at least oneset theButton to (alert's addButtonWithTitle:anItem)set end of buttonList to anItemif anItem is not in buttonList then -- filter for duplicatesset anItem to anItem as textrepeat with anItem in reverse of (buttons as list) -- arrange the same order as the listset buttonList to {}to setButtons:buttonsend performAlert:set my response to {button:button, answer:answer}set answer to accessory's stringValue as textelse -- textFieldsset answer to answer as record(answer's setValue:(anItem's state) forKey:(anItem's title)) -- full button title is key namerepeat with anItem in accessory's contentView()'s subviewsset answer to current application's NSMutableDictionary's alloc's init()if accessory is not (missing value) then if (accessoryType of arguments) is in {"checkbox", "radiobutton"} then -- check/radio buttonsif button is cancelButton then set accessory to missing value -- skip itset answer to missing valueset button to item (button - 999) of buttonList -- index using button numberset button to "gave up"if button < 0 thenset button to my buttonPressed:timer -- do itset accessory to my setAccessory:(accessoryType of arguments) using:(input of arguments) addedWidth:(addedWidth of arguments)set timer to my setupTimer:(giveUpTime of arguments)set buttonList to my setButtons:(buttons of arguments)if checkValue(icon of arguments) then my setIcon:((icon of arguments) as text) -- default if blankif checkValue(info of arguments) then alert's setInformativeText:((info of arguments) as text)set |font| of (fifth item of alert's |window|'s contentView's subviews) to messageFontset messageFont to current application's NSFont's systemFontOfSize:0.25if (alert's messageText) as text is "" then -- can't be nil, so just make it really smallalert's setMessageText:((message of arguments) as text)if checkValue(title of arguments) then alert's |window|'s setTitle:((title of arguments) as text)set alert to current application's NSAlert's alloc's init()set arguments to arguments & {title:""} & {message:"Alert"} & {info:""} & {icon:""} & {buttons:{}} & {giveUpTime:0} & {accessoryType:""} & {input:""} & {addedWidth:0}set arguments to arguments as record -- merged with default options:to performAlert:argumentslog "Error " & errnum & " from showAlert handler:" & return & errmessdisplay alert "Error " & errnum & " from showAlert handler:" message errmesson error errmess number errnum -- there are a few ways to deal with a cancel, pick onereturn responseif button of response is cancelButton then error number -128my performSelectorOnMainThread:"performAlert:" withObject:arguments waitUntilDone:truemy performAlert:argumentsto showAlert given arguments:argumentsshowAlert given arguments:{addedWidth:50, title:"This is a test", giveUpTime:15, message:"", input:{"Testing" & return, "Whatever" & return, "A really, really, long label to see how really, really, long labels appear"}, info:"This is a more complex NSAlert example using all arguments.", accessoryType:"checkbox", buttons:{"Cancel", "Wait...", "What?", "OK"}, icon:"stop"} -- everythingshowAlert given arguments:{info:"This is a simple NSAlert example."} -- simple/defaultsset loremText to "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vestibulum venenatis velit, non commodo diam pretium sed. Etiam viverra erat a lacus molestie id euismod magna lacinia. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum ac augue magna, eu pharetra leo. Donec tortor tortor, tristique in ornare nec, feugiat vel justo. Nunc iaculis interdum pellentesque. Quisque vel rutrum nibh. Phasellus malesuada ipsum quis diam ullamcorper rutrum. Nullam tincidunt porta ante, in aliquet odio molestie eget. Donec mollis, nibh euismod pulvinar fermentum, magna nunc consectetur risus, id dictum odio leo non velit. Vestibulum vitae nunc pulvinar augue commodo sollicitudin."on run -- examplesproperty response : missing value -- this will be the button and accessory results from the alertproperty countdown : missing value -- this will be the remaining time before alert is dismissedproperty timerField : missing value -- this will be a countdown textFieldproperty alert : missing value -- this will be the alertproperty okButton : "OK" -- a name for the OK buttonproperty cancelButton : "Cancel" -- a name for the cancel buttonproperty SYS_RESOURCES : "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/"use framework "Appkit"use AppleScript version "2.4" -- Yosemite 10.10 and laterset visible of every process to trueend getNowTimereturn nowPositionSeclog "iTunes has finished playing(Can't get now time)"if nowPositionSec = missing value thenset nowPositionSec to player positionon getNowTime()end getTimeSizereturn (min * 60) + secset sec to item 2 of timeSize_lset min to item 1 of timeSize_lreturn (hur * 60 * 60) + (min * 60) + secset sec to item 3 of timeSize_lset min to item 2 of timeSize_lset hur to item 1 of timeSize_lset timeSize_l to text items of timeSizedisplay notification "再生を見失いました" & return & "Scriptを終了します" with title "goNextEpisode"log "iTunes has finished playing(Can't get size time)"set timeSize to time of current track as texton getTimeSize()end monitoringdelay waitlog "Waiting. Next check after " & wait & "s"display notification "次のEpisodeです" with title "goNextEpisode"display notification "最後の再生でした Scriptを終了します" & return & "Have a nice day!" with title "goNextEpisode"else if (timeSize - nowTime) < 1 thenset wait to 1else if (timeSize - nowTime) > 1 thenset wait to 59else if (timeSize - nowTime) > 60 thenset wait to 179if (timeSize - nowTime) > 180 thenset nowTime to getNowTime()set timeSize to getTimeSize()log "Strat monitoring"on monitoring()monitoring() of medisplay notification "再生中のTV Showを検出" & return & "再生位置の監視を開始します" with title "goNextEpisode"if videoKind = TV show thenset videoKind to video kind of current trackset videoKind to ""delay 20log "Waiting play TV Show...(Play check after 20s)"error "unable to fmGUI_CustomMenus_Open - " & errMsg number errNumwindowWaitUntil_FrontIS({windowName:"Manage Custom Menus"})fmGUI_ClickMenuItem({menuItemRef:manageMenusMenuItem})set manageMenusMenuItem to first menu item of menu 1 of menu item "Manage" of menu 1 of menu bar item "File" of menu bar 1 whose name starts with "Custom Menus"if fmGUI_NameOfFrontmostWindow() starts with "Manage Custom Menus" thensay input using voiceset voice to the result as stringchoose from list {"Alex", "Daniel", "Ewa", "Samantha", "Serena", "Thomas", "Zosia", "Bad News", "Good News", "Pipe Organ"} with prompt "Choose voice:" without multiple selections allowed and empty selection allowedrepeat with arg in argvset day of _oldDate to ((_oldDate's day) + 1)return (do shell script "/bin/echo " & quoted form of str & " | perl -MURI::Escape -lne 'print uri_unescape($_)'")return (do shell script "/bin/echo " & quoted form of str & " | perl -MURI::Escape -lne 'print uri_escape($_)'")end deinterlaceListerror "Can't deinterlaceList: " & eMsg number eNumreturn {k's l1, k's l2}set k's l2's end to k's l's item (i + 1)set k's l1's end to k's l's item irepeat with i from 1 to count of k's l by 2if (count k's l) mod 2 is not 0 then error "list is not an even length."property l2 : {}property l1 : {}property l : lstscript kif lst's class is not list then error "not a list." number -1704local lston deinterlaceList(lst)end write_jsonclose access the file_write json to file_set eof of file_ to 0set the file_ to open for access file path_ with write permissionset json to json & lset l to "{" & return & tab & "\"" & (item 1 of kv) & "\": \"" & (item 2 of kv) & "\"," set json to json & l else if i > 1 and i < (count k_v) then set l to return & tab & "\"" & (item 1 of kv) & "\": \"" & (item 2 of kv) & "\"," set json to json & l else if i = (count k_v) then set l to return & tab & "\"" & (item 1 of kv) & "\": \"" & (item 2 of kv) & "\"" & return & "}"set kv to (item i of k_v)repeat with i from 1 to count k_vset json to ""on write_json(k_v, path_)end list2recordset rec to rec & rset r to run script rset r to "set rec to {_" & _key & ":" & _val & "}"else if val_type = "integer" or "number" thenset r to "set rec to {_" & _key & ":\"" & _val & "\"}"if val_type = "string" or "text" thenset _val to item i of _valsset _key to item i of _keysrepeat with i from 1 to count of _keysset rec to {}if (count _keys) = (count _vals) thenset _vals to item 2 of split_listset _keys to item 1 of split_listset split_list to my deinterlaceList(_list)on list2record(_list, val_type)end read_jsonreturn recset rec to my list2record(cleanList, "string")if {json_l's item i} is not in itemsToDelete then set cleanList's end to json_l's item irepeat with i from 1 to count json_lset itemsToDelete to {"", " ", " ", " ", " ", " ", " ", " "}set json_l to text items of json_set {astid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {return & linefeed, return, linefeed, tab, character id 8233, character id 8232, ":", "\"", ",", "{", "}"}}close access file_set json_ to (read file_)set the file_ to open for access file json_if path_ = true thenon read_json(json_, path_)end mdfindreturn my q_split(output, return)set output to do shell script "mdfind \"" & query & "\""on mdfind(query)end get_homereturn _homeif my q_is_empty(_home) then return missing valueon get_home()end get_storagereturn _storageif my q_is_empty(_storage) then return missing valueon get_storage()end get_cacheif my q_is_empty(_cache) then return missing valueif my q_is_empty(_bundle) then return missing valueon get_cache()end init_pathsdo shell script "mkdir " & (quoted form of _storage)if not my q_folder_exists(_storage) thendo shell script "mkdir " & (quoted form of _cache)if not my q_folder_exists(_cache) thenset _storage to (_home) & "Library/Application Support/Alfred 2/Workflow Data/" & (_bundle) & "/"set _cache to (_home) & "Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/" & (_bundle) & "/"set _bundle to my get_bundle()set _home to POSIX path of (path to "cusr" as text)on init_paths()end get_bundlereturn _bundleset _bundle to value of property list item "bundleid" as texttell property list file _infoPlistif my q_file_exists(_infoPlist) thenset _path to my get_path()on get_bundle()end get_pathif my q_is_empty(_path) then return missing valueset _path to (text items 1 thru -3 of (POSIX path of (path to me)) as string) & "/"on get_path()set outputFile to targetDir & cleanName & ".pdf"save front document in POSIX file outputFileset outputFile to targetDir & cleanName & ".eps"set canvas of front window to cvsset cleanName to replace_string(currentName, " ", "_") of meset currentName to name of cvs as textrepeat with cvs in canvases of front documentset area type of current export settings to all graphicsopen sourceFiletell application "OmniGraffle"set targetDir to fullpath((get (item 2 of argv) as string))set sourceFile to fullpath((get (item 1 of argv) as string))end fullpathreturn (POSIX path of (cwd & location))set cwd to POSIX path of ((container of (path to me)) as alias)on fullpath(location)end replace_stringset AppleScript's text item delimiters to replacementset textItems to every text item of inputon replace_string(input, search, replacement)else if button_pressed is "Cancel" thenset theList to (get selection)if button_pressed is "Selection" thenset button_pressed to button returned of resultdefault button "Selection"buttons {"Cancel", "All", "Selection"} ¬display dialog "Export selected people or all" ¬set outputFileName to choose file name with prompt "Save address book group export as text:" default name defNameset filePath to (path to desktop folder as string) & "dictionaries.txt"make new folder at myFolderPathset myFolderPath to (path to documents folder as string) & "test_folder"set AppleScript's progress completed steps to (AppleScript's progress completed steps) + 1set location of photo to items 1 thru 2 of thisItemset thisItem to my binarySearch(gpxFile, date of photo)repeat with photo in photosset AppleScript's progress completed steps to 0set AppleScript's progress total steps to count of photosset AppleScript's progress description to "Geotagging photos"set gpxFile to (choose file with prompt "Select a GPX file" of type {"com.apple.dt.document.gpx"}) as stringset photos to (get the selection)end binarySearchreturn {latitude, longitude, altitude}set altitude to my parseDecimal(value of XML element "ele" as text)set longitude to my parseDecimal(value of XML attribute "lon" as text)set latitude to my parseDecimal(value of XML attribute "lat" as text)tell XML element startIndex of segset startIndex to midpoint + 1set endIndex to midpointif photoTime ≤ midpointTime thenset midpointTime to my iso8601(value of XML element "time" of item midpoint of trks)set midpoint to startIndex + (endIndex - startIndex) div 2repeat until startIndex = endIndexset endIndex to count of trksset trks to every XML element of segif photoTime < lastRecordedTime thenset lastRecordedTime to my iso8601((value of XML element "time" of last XML element of seg) as string)repeat with seg in (every XML element whose name = "trkseg")tell application "System Events" to tell XML element "trk" of XML element "gpx" of XML file xmlFilePathon binarySearch(xmlFilePath, photoTime)end parseDecimalreturn decimalResultset decimalResult to (text item 1 of decimalString & my decimalSeparator & text item 2 of decimalString) as realon parseDecimal(decimalString)end iso8601return resultDate + (my timeOffset) * minutesset the seconds of resultDate to (text 18 thru 19 of dateString)set the minutes of resultDate to (text 15 thru 16 of dateString)set the hours of resultDate to (text 12 thru 13 of dateString)set the day of resultDate to (text 9 thru 10 of dateString)set the month of resultDate to (text 6 thru 7 of dateString)set the year of resultDate to (text 1 thru 4 of dateString)on iso8601(dateString)set decimalSeparator to text 2 thru 2 of (0.0 as text)set timeOffset to hoursOffset * 60 + minutesOffsetset minutesOffset to (text 1 thru 1 of tzString) & (text 4 thru 5 of tzString) as numberset hoursOffset to (text 1 thru 3 of tzString) as numberset tzString to do shell script "date '+%z'"end makeTabtell application "System Events" to keystroke "t" using {command down}on makeTab()do script "ssh root@" & new_cap_HOST & " tcpdump -U -i " & new_cap_INT & " -s 0 -w - > /tmp/" & capturefile in tab 1 of front windowdo script "wireshark -k -i /tmp/" & capturefile & "&" in tab 1 of front windowdo script "mkfifo /tmp/" & capturefile & "&" in tab 1 of front windowmy makeTab()set capturefile to new_cap_INT & "-" & text 1 thru 15 of get_dateset new_cap_INT to text item 4 of cap_URLset new_cap_HOST to text item 3 of cap_URLset cap_URL to this_URLset get_date to do shell script "date +%Y%m%d-%H%M%S"end removeItemFromListif oneItem is not removeItem of prefs then copy oneItem to end of newListrepeat with oneItem in someList of prefsset defaultPrefs to {someList:null, removeItem:null}on removeItemFromList(prefs)removeItemFromList({someList:{"a", "c", "d", "c", "b", "d"}, removeItem:"c"})system attribute "USER"end fmGUI_ManageDataSources_Deleteerror "Couldn't ensure existence of data source '" & dataSourceName & "' - " & errMsg number errNumreturn "Do NOT Exist: " & dataSourceNameon error -- DOES NOT exist:return "Deleted: " & dataSourceNameclickObjectByCoords(deleteButton)set deleteButton to first button of window 1 whose name starts with "Delete"select (first row of (table 1 of scroll area 1 of window 1) whose name of static text 1 is dataSourceName)try -- it DOES exist, so delete it:set defaultPrefs to {dataSourceName:null}on fmGUI_ManageDataSources_Delete(prefs)fmGUI_ManageDataSources_Delete({dataSourceName:"SomeFakeFile"})open location "https://m2-staging.happysocks.com/"if the result = "complete" then exit repeatdo JavaScript "document.readyState"tell document 1 to repeatend fmGUI_ManageSecurity_AccessRecord_OpenCalcerror "unable to fmGUI_ManageSecurity_AccessRecord_OpenCalc - " & errMsg number errNumreturn windowWaitUntil({windowName:"Custom Record Privileges", windowNameTest:"is not"})click menu item 2 of menu 1 of pop up button buttonNum of window 1click pop up button buttonNum of window 1set buttonNum to 5else if calcFor is equal to "field" thenset buttonNum to 3else if calcFor is equal to "delete" thenset buttonNum to 2else if calcFor is equal to "create" thenset buttonNum to 1else if calcFor is equal to "edit" thenset buttonNum to 4else if calcFor is equal to "view" thenset buttonNum to calcForif class of calcFor is equal to class of 1 thenset calcFor to calcFor of prefsset defaultPrefs to {calcFor:null}on fmGUI_ManageSecurity_AccessRecord_OpenCalc(prefs)fmGUI_ManageSecurity_AccessRecord_OpenCalc({calcFor:"field"})end qppreturn quoted form of (POSIX path of (aPath as text))on qpp(aPath)qpp(path to desktop folder)return not is_visibleset is_visible to visible of window 1 of application app_nameend convertToUpperCaseset item K of chrs to character olc of UPPERCASEset olc to offset of (item K of chrs) in lowercaseon convertToUpperCase(theString)return convertToUpperCase(exampleString)set exampleString to "abc"logger's infof("The project: {} is now registered", projectPath)configUser's setValue(projectPathsKey, projectList)set end of projectList to projectPathif projectList is missing value then set projectList to {}set projectList to configUser's getList(projectPathsKey)configUser's setValue(projectKey, projectPath)set projectPath to textUtil's replace(result, "/scripts/register-project.applescript", "")set posixPath to POSIX path of (path to me)logger's infof("The project: {} is already registered", projectKey)if configUser's hasValue(projectKey) thenset logger to std's import("logger")'s new("register-project")set projectPathsKey to "AppleScript Projects Path"set projectKey to "Project template-applescript-project"set shuffle enabled to falseend digitLenStringset output to "0" & outputrepeat while (count of output) < lengthset output to inputString as stringon digitLenString(inputString, length)end resortDigitsset errInputString to inputStringon error errMSGset output to output & (minNum as string)repeat with i from 1 to countMinset countMin to countMin + 1else if anNum = minNum thenif anNum > minNum thenif anNum < minNum then set minNum to anNumset countMin to 0set minNum to 10set workingNumbers to leftOversset output to output & (maxNum as string)repeat with i from 1 to countMaxset countMax to countMax + 1else if anNum = maxNum thenset leftOvers to leftOvers & ancharif anNum < maxNum thenif anNum > maxNum then set maxNum to anNumset anNum to anchar as integerrepeat with anchar in workingNumbersset leftOvers to ""set countMax to 0set maxNum to 0repeat while ((count of workingNumbers) > 0)if dirFlag thenset workingNumbers to inputStringif direction > 0 then set dirFlag to trueif direction then set dirFlag to trueset dirFlag to falseon resortDigits(inputString, direction)end KaprekarStepset output to digitLenString(((topNum - botNum) as string), stringLength)set botNum to (resortDigits(inputString, -1) as integer)set topNum to (resortDigits(inputString, 1) as integer)set stringLength to count of inputStringon KaprekarStep(inputString)end KaprekarRepreturn {oldResult, resultList}set oldResult to newResultset newResult to KaprekarStep(oldResult)set resultList to resultList & oldResultrepeat while resultList does not contain oldResultset oldResult to inputStringon KaprekarRep(inputString)end KaprekarRun{someString, LastResult, countResults, FoundIndex, RevFoundIndex, resultList}set RevFoundIndex to countResults - FoundIndex + 1if LastResult = (anResult as string) then set FoundIndex to indexERset indexER to indexER + 1repeat with anResult in resultListset FoundIndex to 0set indexER to 0set countResults to count of resultListset {LastResult, resultList} to KaprekarRep(someString)on KaprekarRun(someString)end KaprekarRandSamplesset iString to digitLenString(randomNumber, maxDigit)set sampleList to sampleList & randomNumberrepeat while sampleList contains randomNumberset randomNumber to (random number from 1 to (10 ^ maxDigit as integer))repeat with i from 1 to maxSamplesset randomNumber to 0set sampleList to {}on KaprekarRandSamples(maxDigit, maxSamples)end KaprekarSeqentialset output to output & {KaprekarRun(iString) & "\n"}set iString to digitLenString(i, maxDigit)repeat with i from startNum to StopNumon KaprekarSeqential(maxDigit, startNum, StopNum)end KaprekarMinimizedreturn {visitedPointList, "\n", minimizedStatsList}set minimizedStatsList to minimizedStatsList & {{startingNumber, BeginLoopNum, (count of minStepList), x, y, z, minStepList, deliminator}}set visitedPointList to visitedPointList & anStepelse if visitedPointList does not contain anStep thenset minStepList to minStepList & anStepif visitedPointList does not contain anStep then set visitedPointList to visitedPointList & anStepset nowCount to nowCount - 1if nowCount > 0 thenrepeat with anStep in StepListset nowCount to yset minStepList to {}set {startingNumber, BeginLoopNum, x, y, z, StepList, deliminator} to anStatrepeat with anStat in statsListset minimizedStatsList to {}set visitedPointList to {}on KaprekarMinimized(statsList){KaprekarMinimized(KaprekarSeqential(2, 0, 5)), errMSG, errInputString}property errMSG : ""property errInputString : ""openInIterm(theFolder)write text "cd " & quoted form of POSIX path of theFoldertell the first terminalset wasRunning to isRunning("iTerm")on openInIterm(theFolder)end trim_lineset this_text to characters 1 thru -(x + 1) of this_text as stringrepeat while this_text ends with the trim_charsif the trim_indicator is in {1, 2} thenset this_text to characters (x + 1) thru -1 of this_text as stringrepeat while this_text begins with the trim_charsif the trim_indicator is in {0, 2} thenset x to the length of the trim_charson trim_line(this_text, trim_chars, trim_indicator)log this_nodeon error err_str number err_numberset this_node to trim_line(this_line, test_str, 0)set this_line to paragraph i of the_content as stringif test_str is equal to "RESULT:" thenlog test_strset test_str to (characters 1 thru 7 of paragraph i of the_content) as stringset n to (count of every paragraph of the_content)set the_content to (contents of window 1) as stringdo script with command "which node | /usr/bin/awk '{ print " & "\"RESULT:\"" & " $1}'"if not (exists window 1) thenset this_node to ""load script "/Users/scott/github/iconify/ai-scripts/_string.scpt"log name of t_text as textset name of t_text to tset y to y + 24set text font of text range of t_text to adihausset size of text range of t_text to 16set t_text to make new text frame with properties {contents: t, position: { x, y }}set t to item a of values_listrepeat with a from 1 to length of values_listset y to -160set x to 80set adihaus to text font "Adihaus-Regular"set c to cell j of selectiongetArtistResultListFeedback(query as text)end getArtistResultListFeedbackreturn getResultListFeedback() of configaddNoResultsItem(query, "song") of configif config's resultListIsEmpty() thenaddResult({uid:("song-" & songId), valid:"yes", title:songName, subtitle:artist of theSong, icon:songArtworkPath}) of configset songArtworkPath to getSongArtworkPath(theSong) of configset songName to name of theSongset songId to (get database ID of theSong)if config's resultListIsFull() then exit repeatrepeat with theSong in artistSongsset artistSongs to getArtistSongs(artistName) of configrepeat with artistName in theArtistsset theArtists to getResultsFromQuery(query, "artist") of configset query to trimWhitespace(query) of configglobal configon getArtistResultListFeedback(query)set tags of theRecord to (parents of theRecord) & theTagsset theTags to text items of theTagset theTag to display name editor "Add Tags" info "Tags (separated by semicolons):"set logger to std's import("logger")'s new("idler")end idleInSecondsresult as realdo shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'"on idleInSeconds()end isIdleisIdleFor(awayThresholdSeconds)on isIdle()end isIdleForidleInSeconds() is greater than thresholdon isIdleFor(threshold)property awayThresholdSeconds : pAwayThresholdSecondsscript IdlerInstanceon new(pAwayThresholdSeconds)log sut's idleInSeconds()log sut's isIdle() -- truelog sut's isIdle() -- still falselog sut's isIdle() -- falselog sut's isIdleFor(1)set sut to new(sutThreshold)set sutThreshold to 2Manual: Idle in secondsManual: Is IdleManual: Idle for secondsset thisCaseId to "idler-spotCheck"tell i term application "System Events" to keystroke return using {command down}tell i term application "System Events" to keystroke "[" using {command down}tell i term application "System Events" to keystroke "d" using {shift down, command down}tell i term application "System Events" to keystroke "bash"tell i term application "System Events" to keystroke returntell i term application "System Events" to keystroke "ssh oka@host"tell i term application "System Events" to keystroke "d" using {command down}write text "bash"write text "ssh oka@host"set s to (launch session "Default session")set number of rows to 30set number of columns to 100set t to (make new terminal)set finalPositionY to (item 2 of desiredPosition) * (screenHeight - dockHeight)click button "Call" of window 1 of application process "FaceTime"repeat until (button "Call" of window 1 of application process "FaceTime" exists)do shell script "open facetime://" & quoted form of phone_numset phone_num to text returned of (display dialog "Input a phone number to call:" default answer "")set recurrence of e to recurrence of sourceEventlog "Adding recurrence to " & uid of sourceEventif recurrence of sourceEvent is not missing value thenset e to make new event with properties {summary:"", start date:start date of sourceEvent, end date:end date of sourceEvent, allday event:allday event of sourceEvent, excluded dates:excluded dates of sourceEvent, description:upToDateDesc}delete deleteEventlog "deleting stale copy of " & deleteEventif deleteEvent is not missing value thenif needsUpdate = true or previouslyCopied = false thenlog uid of sourceEvent & " is not related to " & uid of copiedEventlog uid of sourceEvent & "has not changed"set needsUpdate to trueset deleteEvent to copiedEventlog uid of sourceEvent & "has changed"if upToDateDesc ≠ copiedDesc thenset previouslyCopied to truelog uid of sourceEvent & "was previously copied"if myOffset ≠ 0 thenset myOffset to (offset of (uid of sourceEvent as text) in copiedDesc)set copiedDesc to description of copiedEventrepeat with copiedEvent in targetEventListset targetEventList to every eventtell calendar myTargetCalset upToDateDesc to sourceEtag & ":" & uid of sourceEventset sourceEtag to first item of splitText(shellOut, space) of meset shellOut to do shell script hashString & "| shasum -a 256"set hashString to "printf '%s%s%s%s' " & "'" & (start date of sourceEvent) & "'" & space & "'" & (end date of sourceEvent) & "'" & space & "'" & (allday event of sourceEvent) & "'" & space & "'" & (recurrence of sourceEvent) & "'"set deleteEvent to missing valueset previouslyCopied to falseset needsUpdate to falseset sourceProperties to properties of sourceEventrepeat with sourceEvent in (events of calendar mySourceCal where (its start date ≥ windowStart) and (its start date ≤ windowEnd))set windowStart to (current date) - (1 * weeks)set windowEnd to (current date) + (4 * weeks)set myTargetCal to "anothercal"set mySourceCal to "cloudcal"open SourceFolderif application "Visual Studio Code" is running thenset SourceFolder to "/Users/ouyang/Documents/gblog/source"if image_path is not "no disk file" then set suppress printing to 1end pathAction:display dialog "Path Control was double-clicked:" & return & (sender's clickedPathItem's title) as text buttons {"OK"} default button 1on pathAction:senderend makePathControlif editable is not false then its setEditable:trueits setDoubleAction:(action as text)its setURL:pathURLif allowedTypes is not (missing value) then set its allowedTypes to (allowedTypes as list)its setPathStyle:(current application's NSPathStyleStandard) -- 0its setPathStyle:(current application's NSPathStylePopUp) -- 2 (not editable)if popup is true thentell (current application's NSPathControl's alloc's initWithFrame:{origin, {width, 25}})if class of pathURL is not current application's NSURL then set pathURL to current application's NSURL's fileURLWithPath:(POSIX path of (pathURL as text))if pathURL is (missing value) then set pathURL to (path to desktop folder)on makePathControl at origin given width:width : 200, pathURL:pathURL : missing value, placeholder:placeholder : missing value, popup:popup : false, allowedTypes:allowedTypes : missing value, editable:editable : true, backgroundColor:backgroundColor : missing value, action:action : "pathAction:", target:target : missing valueuse AppleScript version "2.5" -- Sierra (10.12) or latermove cue id (uniqueID of eachCue) of parent of eachCue to end of groupCueif contents of eachCue is not parentOfGroup then -- Avoids a potential selection errorset parentOfGroup to parent of groupCueset q color of groupCue to groupColorset q name of groupCue to groupNameif (count theSelection) is 1 then -- if only one cue was selected, name the group after itset groupColor to q color of last item of theSelectionset groupName to q display name of last item of theSelectionif (count theSelection) is 0 then returndisplay notification "" with title "Se ha concluido con exito la conversión"set AppleScript's text item delimiters to delimitadorTextodisplay dialog "Un error ha ocurrido en: " & rutaArchivo & ": " & n & eset resultado to do shell script "textutil -convert txt -output " & archivoSalida & " " & rutaArchivoset archivoSalida to quoted form of (directorioDestino & nombreArchivo & ".txt")set the nombreArchivo to (text item 1 of text items of (get name of esteDocumento))set the rutaArchivo to the quoted form of the POSIX path of esteDocumentoset esteDocumento to contents of unDocumentorepeat with unDocumento in archivosDocset directorioDestino to (POSIX path of directorioDestino)set archivosDoc to (every document file of folder directorioOrigen whose (name extension is in {"doc", "docx", "html", "rft"})) as alias listset directorioDestino to choose folder with prompt "Elija la carpeta donde se guardarán los archivos txt" default location (path to desktop folder)set directorioOrigen to choose folder with prompt "Elija la carpeta que contiene los archivos de origen" default location (path to desktop folder)set {delimitadorTexto, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "."}set countTotal to plutil's new(countTotalName)plutil's createNewPList(countTotalName)if not plutil's plistExists(countTotalName) thenset countTotalName to "counter-total"set countKeys to plutil's new(countKeysName)plutil's createNewPList(countKeysName)if not plutil's plistExists(countKeysName) thenset countKeysName to "counter-all-keys"set countDaily to plutil's new(countDailyName)plutil's createNewPList(countDailyName)if not plutil's plistExists(countDailyName) thenset countDailyName to "counter-daily"set logger to std's import("logger")'s new("counter")end _stripExtensionscriptNameif scriptName ends with ".applescript" then set scriptName to text 1 thru ((length of scriptName) - (length of ".applescript")) of scriptNameon _stripExtension(scriptName)end _formatDate"20" & last word of dateString & "/" & first word of dateString & "/" & second word of dateStringon _formatDate(dateString)end totalScriptRunTodaytotalToday(keyToday)on totalScriptRunToday(scriptName as text)end hasScriptRunTodaytotalToday(keyToday) is greater than 0set keyToday to format {"Running: [{}.applescript]", my _stripExtension(scriptName)}on hasScriptRunToday(scriptName as text)end hasNotRunTodayhasRunToday(theKey) is falseon hasNotRunToday(theKey as text)end hasRunTodaytotalToday(theKey) is greater than 0on hasRunToday(theKey as text)end hasRuntotalAll(theKey) is greater than 0on hasRun(theKey)end clearRunon clearRun(theKey)countDaily's setValue(keyToday, 0)countTotal's setValue(theKey, 0)on clear(theKey)end isNthRuntotalCount mod nth is 0if the totalCount is missing value then return falseset totalCount to countTotal's getInt(theKey)assertThat of std given condition:nth is greater than 0, messageOnFail:format {"The nth:{} must be a positive integer", nth}on isNthRun(theKey as text, nth as integer)end totalAllset theCount to countTotal's getInt(theKey)on totalAll(theKey)countDaily's setValue(keyToday, keyTodayCount)set keyTodayCount to keyTodayCount + 1if keyTodayCount is missing value then set keyTodayCount to 0set keyTodayCount to countDaily's getInt(keyToday)countTotal's setValue(theKey, keyCount)set keyCount to keyCount + 1if keyCount is missing value then set keyCount to 0set keyCount to countTotal's getInt(theKey)on increment(theKey)end totalTodaytheCountif theCount is missing value then return 0set theCount to countDaily's getInt(keyToday)set keyToday to format {"{}-{}", {theKey, todayDate}}set todayDate to _formatDate(short date string of (current date))on totalToday(theKey)logger's infof("hasNotRunToday: {}", hasNotRunToday(sutKey))logger's infof("hasRunToday: {}", hasRunToday(sutKey))logger's infof("totalToday: {}", totalToday(sutKey))logger's infof("totalAll: {}", totalAll(sutKey))logger's debugf("Test Key: {}", sutKey)clear(thisCaseId)increment(thisCaseId)set sutKey to thisCaseIdIncrementTotalset thisCaseId to "counter-spotCheck"global countDaily, countKeys, countTotalkeystroke (key code 125)key up {command}key down {command}tell application "Finder" to make new folder with properties {name:"Temp Export From Evernote"}type "PDF"set ExportFolder to ((path to desktop folder) & "Temp Export From Evernote:") as stringset note_found to find notes "intitle:\"" & note_name & "\""on run {note_name, enex_path}error "Unable to fmGUI_PopupSet ( couldn't select '" & objValue of prefs & "' in popup ) - " & errMsg number errNumreturn fmGUI_Popup_SelectByCommand(prefs & {selectCommand:"contains"})set defaultPrefs to {objRef:null, objValue:null}fmGUI_PopupSet({objRef:popUpButtonRef, objValue:"Minimum"})set popUpButtonRef to pop up button "Available menu commands:" of window 1return run script (POSIX file "/Users/IceHe/Documents/AppleScript/Stat/stat_month.applescript") with parameters {current date}set var1 to the folders of (startup disk)or (bankruptcies = 0 and debt > 1000 and will_give_up_first_born)or (bankruptcies = 0 and credit_rating > 500 and debt < 10000)) ¬((bankruptcies = 0 and credit_rating > 700 and debt < 20000) ¬age ≥ 18 and ¬set is_applicant_approved to ¬display dialog "I'm out of here..." giving up after 5display dialog "What's next?" buttons {"Cancel", "Go", "Run"}quit application "Microsoft Word"tell application "iCal" to delete (every todo of (every calendar) whose completion date < (current date))do shell script cliclick & " rc:" & x & "," & y & " m:" & Storage # AXShowMenu workaround (right click then move mouse to OG location)set y to item 2 of pset x to item 1 of pset p to position of menu bar item (iconIndex) of mset m to value of attribute "AXParent" of focusedWindow # menu holding "pop over"s and "menu bar item"delay 0.333keystroke "x" using {option down}set iconIndex to 1set Storage to do shell script "/opt/homebrew/bin/cliclick p"set cliclick to "/opt/homebrew/bin/cliclick"end addrowset note of newtopic to notelinkset newtopic to (make with properties {topic:notename} new row at end of document 1)on addrow(notename, notelink)set dialogtext to "ノートはありません"repeat with var_note in sarchnoteif not (sarchnote = {}) thenset sarchnote to find notes sarchwordset sarchword to sarchnotebook & sarchtag & sarchtextset sarchnotebook to "notebook:\"" & selectedNotebooks & "\" "set sarchnotebook to ""if selectedNotebooks is "" thenset sarchtag to "tag:\"" & selectedTags & "\" "set sarchtag to ""if selectedTags is "" thenset sarchtext to text returned of (display dialog "検索ワードをどうぞ!" default answer "")set selectedTags to ""if selectedTags = false then set selectedTags to ""set selectedTags to choose from list TagNames with prompt "タグを選択して下さい"set TagNames to getTagNames()if button_returned is "タグを選択する" thendisplay dialog "タグを選択しますか?" buttons {"タグを選択する", "キーワードの入力へ"} default button 1if selectedNotebooks = false then set sarchnotebook to ""set selectedNotebooks to choose from list notebookNames with prompt "ノートブックを選択して下さい" default items firstNotebookName -- with multiple selections allowed 複数ノートブックの選択を可能にするset firstNotebookName to item 1 of notebookNamesset notebookNames to getNotebookNames()my addrow(linename, linkname)set linkname to (get note link of var_note)set linename to (get title of var_note)repeat with var_note in (get selection) -- 選択しているノートif button_returned is "取り込む" thendisplay dialog "選択したノートを取り込ますか?" buttons {"取り込む", "検索する"} default button 1set sortedList to paragraphs of strset str to do shell script "echo " & quoted form of str & " | sort -f"set str to aList as stringon sortList(aList) --アルファベット順にリストを整形end getTagNamesset nameList to name of tagson getTagNames() -- タグリストを取得end getNotebookNamesreturn sortList(nameList)set nameList to name of notebookson getNotebookNames() -- ノートブックリストを取得end countWordsreturn this_countset this_count to this_count + (my countWords(children of this_child))set this_count to this_count + (word count of this_child)repeat with this_child in these_childsset this_count to 0local this_child, this_counton countWords(these_childs)display alert "DEVONthink" message (this_words as string) & " words."set this_words to my countWords(this_selection)do shell script "echo Disconnected!"set sidecarToggle to ((checkbox 1 of window "Control Center") whose title contains "Disconnect")if cb contains "Disconnect" thenrepeat with cb in ccCheckboxesdo shell script "echo Connected to " & iPadCheckboxesclick deviceToggleset deviceToggle to checkbox iPadCheckboxes of scroll area 1 of window "Control Center"if iPadCheckboxes contains deviceName thenset iPadCheckboxes to title of item -1 of (every checkbox of scroll area 1 of window "Control Center")click sidecarToggleset sidecarToggle to checkbox "Connect to Sidecar" of window "Control Center"if ccCheckboxes contains "Connect to Sidecar" thenset ccCheckboxes to title of (every checkbox of window "Control Center")click menu bar item "Control Center" of menu bar 1tell its application process "ControlCenter"set sysVer to system version of (system info)set deviceName to "Felipe Coury’s iPad"end element_endreturn ""on element_end(the_name)end element_beginningreturn "<" & the_name & ">"on element_beginning(the_name)end element_with_attributeset xml_text to xml_text & ">" & the_content & "" --end of xml textset xml_text to "<" & the_name & " " & attribute_text --beginning of xml textif attribute is not the last item in the_attributes then set attribute_text to attribute_text & " " --append a space after each key value pair, unless its at the endset attribute_text to attribute_text & (the_key & "=" & "\"" & the_value & "\"")set the_value to (second item in attribute)set the_key to first item in attributeset attribute to item i of the_attributesrepeat with i from 1 to (length of the_attributes)set attribute_text to ""on element_with_attribute(the_name, the_content, the_attributes)end elementreturn xml_textset xml_text to xml_text & "/>" --end of xml textelse --no contentset xml_text to xml_text & ">" & content & "" --end of xml textif (length of the_content > 0) then --has contentset xml_text to "<" & the_nameon element(the_name, content)end headerreturn ""on header()do script " "tell application "Terminal"do shell script "pushd ~/Downloads; rm PagerDuty+Outgoing+Numbers.vcf; popd"do shell script "pushd ~/Downloads; curl -O https://s3.amazonaws.com/pdpartner/PagerDuty+Outgoing+Numbers.vcf; open PagerDuty+Outgoing+Numbers.vcf; popd"tell application "System Events" to key code 125 -- down arrowset theURL to URL of front document as stringset the end of niceURL to theName & theSeparator & theURLrepeat with i in theAliasset theAlias to (make alias at aliasHub to theSelection) as listset aliasHub to (path to home folder from user domain as text) & "alias"tell application "System Events" to click (every button whose value of attribute "AXDescription" is "add desktop") of group 1 of process "Dock"end checkPortreturn checkResultset checkResult to check()tell PortCheckerend systemVersionreturn {major:major, minor:minor, revision:revision, versionString:versionString}set versionString to (major as text) & "." & (minor as text) & "." & (revision as text)set major to (major2 & major1 as text) as integerset major2 to hex mod 16 as textset major1 to hex mod 16 as textset minor to hex mod 16set hex to hex div 16set revision to hex mod 16set hex to system attribute "sysv"on systemVersion()errorMessageset errorMessage to "readFile(\"" & filePath & "\", " & (contentClass as text) & "): " & ¬return fileContentserror "Error while trying to read file: " & errorMessage number errorNumberclose access file filePathset fileContents to read file filePath as contentClasserror "Could not open file: " & errorMessage number errorNumberopen for access file filePathtell application "System Events" to if (exists file filePath) is false then error "File not found."set contentClass to «class utf8»if contentClass is missing value or contentClass is in {false, 0, "", "utf8", "utf-8"} thenon readFile(filePath, contentClass)tell application "System Events" to delete file strokeFilePathif strokeToolPID is not false then do shell script "/bin/kill " & (strokeToolPID as text)end checkResultif timeTaken is greater than or equal to theTimeout then exit repeatset timeTaken to timeTaken + 0.1set strokeResult to trueif strokeOutput contains "Open TCP Port" or strokeOutput contains "Open UDP Port" thenset strokeOutput to readFile(strokeFilePath, text)set strokeResult to falseset timeTaken to 0.0on checkResult()end strokeset strokeToolPID to falseset strokeToolPID to pid as integerset pid to do shell script quotedStrokeToolPath & " " & quoted form of networkAddress & " " & quoted form of (portNumber as text) & " " & quoted form of (portNumber as text) & " > " & quotedStrokeFilePath & " 2>&1 & echo $!"set quotedStrokeFilePath to quoted form of (POSIX path of strokeFilePath)set strokeFilePath to temporaryPath()if quotedStrokeToolPath is false then error "Path to stroke tool not set. Did you first call init()?"on stroke()return strokeResultcleanUp()set strokeResult to checkResult()stroke()set quotedStrokeToolPath to quoted form of "/Applications/Utilities/Network Utility.app/Contents/Resources/stroke"set quotedStrokeToolPath to quoted form of "/System/Library/CoreServices/Applications/Network Utility.app/Contents/Resources/stroke"if major of sv ≥ 10 and minor of sv ≥ 9 thenset sv to systemVersion()property strokeFilePath : falseproperty strokeToolPID : falseproperty quotedStrokeToolPath : falseproperty theTimeout : aTimeoutproperty networkAddress : anAddressproperty portNumber : aPortscript PortCheckeron checkPort(aPort, anAddress, aTimeout)log checkPort(80, "google.com", 3)log checkPort(80, "swscan.apple.com", 3)log checkPort(80, "www.apple.com", 3)click menu item "上一曲" of menu 1 of menu bar item "控制" of menu bar 1return "❗️🔀"return "🔀"if not shuffle_mode thenset the shuffle enabled to not shuffle_modeset shuffle_mode to shuffle enabledset_volume(current_volume) # after pause restore volumetell application "iTunes" to pauserepeat with i from get_volume() to 0 by -1set state to "playing"if is_playing(iTunes_state()) thenon run args # fadeout volume to 0, pause and then restore volume (not play)end is_playingreturn (state is "playing") or ("kPSP" is in state)on is_playing(state) #set newRec's cite key to newRec's generated cite keyset newRec to first item of (import from eachFileAlias)repeat with eachFile in myBibsauto file justImportedset justImported's cite key to justImported's generated cite keyif value of field "year" of justImported is "" then set value of field "year" of justImported to "9999"if value of field "title" of justImported is "" then set value of field "title" of justImported to "00Fixme"if value of field "author" of justImported is "" then set value of field "author" of justImported to "00Fixme"set justImported to first item of (import with eachFileAlias)set eachFileAlias to eachFile as aliasrepeat with eachFile in myPDFstell application "Finder" to set myBibs to every file of folder "Path:To:Folder to import from" whose name extension is "bib"tell application "Finder" to set myPDFs to every file of folder "Path:To:Folder to import from" whose name extension is "pdf"tell BibDesk to set theDoc to get first documentuse BibDesk : application "BibDesk"use Finder : application "Finder"log "Unsupported type: " & theTypeplay thePlaylistset thePlaylist to getPlaylist(theId) of configelse if theType ends with "playlist" thenplay theSongset theSong to getSong(theId) of configif theType is "song" thenset theId to id of typeAndIdset theType to type of typeAndIdset typeAndId to parseResultQuery(query as text) of configEOFset the clipboard "tagname & ' | ' & input1 & ' | ' & input2 & ' | ' dateStamp"set dateStamp to do shell script "/bin/date +%Y%m%d-%H:%M"set tagname to resulted of (choose from list {"Start", "End"} default items {"Start"} with title "?Select Tags")set input2 to text returned of (display dialog "Task" default answer "" buttons {"OK", "Cancel"} default button "OK" with title "Task")set input1 to text returned of (display dialog "Customer" default answer "" buttons {"OK", "Cancel"} default button "OK" with title "Customer")set the clipboard to rssURLset rssURL to "https://api.prprpr.me/weibo/rss/" & result as stringdo shell script "echo " & theURL & "|egrep -o '[0-9]+'"else if theURL contains "weibo.com/u/" thenset rssURL to "https://rss.lilydjwg.me/zhihuzhuanlan/" & result as stringdo shell script "echo " & theURL & "|egrep -o '[a-z0-9]+$'"else if theURL contains "zhuanlan.zhihu.com" thenset rssURL to "https://api.prprpr.me/bilibili2rss/bangumi/" & result as stringdo shell script "echo " & theURL & "|egrep -o '[0-9]{4}'"else if theURL contains "bangumi.bilibili.com" thenset rssURL to "https://api.prprpr.me/bilibili2rss/user/" & result as stringdo shell script "echo " & theURL & "|egrep -o '[0-9]{6,9}'"if theURL contains "space.bilibili.com" thenif useGrowl and GrowlRunning thenend getEffectiveStartDatereturn {startAncestor, effectiveStartDate}return my getEffectiveStartDate(parent task of thisItem, effectiveStartDate)return {thisItem, effectiveStartDate}else if defer date of thisItem is greater than effectiveStartDate thenset effectiveStartDate to defer date of thisItemif effectiveStartDate is missing value thenif defer date of thisItem is not missing value thenon getEffectiveStartDate(thisItem, effectiveStartDate)end getEffectiveDueDatereturn {dueAncestor, effectiveDueDate}return my getEffectiveDueDate(parent task of thisItem, effectiveDueDate)return {thisItem, effectiveDueDate}if parent task of thisItem is missing value thenelse if due date of thisItem is less than effectiveDueDate thenset effectiveDueDate to due date of thisItemif effectiveDueDate is missing value thenif due date of thisItem is not missing value thenon getEffectiveDueDate(thisItem, effectiveDueDate)end deferset test to my offsetDateByDays(todayStart, daysOffset)if defer date of selectedItem is missing value thenelse if snoozeUnscheduledItems thenmy notifyWithSticky("Error", "Possible Due Date Mismatch", alertText)"» has an earlier effective due date inherited from «" & (name of contents of dueAncestor) & ¬if modifyDueDate and warnOnDateMismatch thenif realDueDate is not effectiveDueDate then --alert if there's a different effective dateset due date of selectedItem to my offsetDateByDays(realDueDate, daysOffset)if modifyDueDate thenif (realDueDate is not missing value) then --There's a preexisting due datemy notifyWithSticky("Error", "Possible Start Date Mismatch", alertText)"». The latter has not been changed.""» has a later effective start date inherited from «" & (name of contents of dueAncestor) & ¬set alertText to "«" & (name of contents of selectedItem) & ¬if realStartDate is not effectiveStartDate thenif warnOnDateMismatch thenset defer date of selectedItem to my offsetDateByDays(realStartDate, daysOffset)if (realStartDate is not missing value) then --There's a preexisting start dateif modifyStartDate thenset {dueAncestor, effectiveDueDate} to my getEffectiveDueDate(selectedItem, due date of selectedItem)set realDueDate to due date of selectedItemset {startAncestor, effectiveStartDate} to my getEffectiveStartDate(selectedItem, defer date of selectedItem)set realStartDate to defer date of selectedItemon defer(selectedItem, daysOffset, modifyStartDate, modifyDueDate, todayStart)set alertText to successTot & " item" & alertItemNum & " deferred " & daysOffset & " day" & alertDayNum & ". (" & changeScope & ")" as stringset succeeded to my defer(thisItem, daysOffset, modifyStartDate, modifyDueDate, todayStart)set modifyDueDate to falseelse if changeScope is "Start Only" thenset modifyStartDate to falseelse if changeScope is "Due Only" thenset modifyDueDate to trueset modifyStartDate to trueif changeScope is "Start and Due" thenif changeScope is "Cancel" then returnset changeScope to button returned of changeScopeQuerydefault button 3 with icon caution giving up after 60set changeScopeQuery to display dialog "Modify start and due dates?" buttons {"Cancel", "Due Only", "Start and Due"} ¬if promptForChangeScope thendisplay dialog "Defer for how many days (from existing)?" default answer defaultOffset buttons {"Cancel", "OK"} default button 2property changeScope : "Start and Due" --options: "Start and Due", "Due Only", "Start Only"property promptForChangeScope : falseproperty warnOnDateMismatch : true --if True, warns you if there's a mismatch between a deferred item's actual and effective Due date. An effective due date is set by a parent task or project.property defaultOffset : 1 --number of days to defer by defaultproperty snoozeUnscheduledItems : true --if True, when deferring Start AND Due dates, will set start date to given # of days in the futureset the bounds of the first window to safariBoundsset item 4 of safariBounds to intHeightset item 3 of safariBounds to intWidthset item 4 of safariBounds to ((item 4 of monitors) - intHeight)set item 3 of safariBounds to item 3 of monitorsset monitors to the bounds of window of desktopdisplay alert "Too many monitors" message "I can only handle 2 monitors and you have more than that. Sorry"if (count every desktop) > 2 thenset safariBounds to {0, 0, 0, 0}set intHeight to 900set intWidth to 1440end textsBetweenerror "textsBetween: " & eMsg number eNumset buffer to text (bOffset + bLength) thru -1 of bufferset end of matches to matchset match to text 1 thru (bOffset - 1) of bufferset match to ""if bOffset is 1 thenif bOffset is 0 thenset bOffset to offset of b in bufferset buffer to text (aOffset + aLength) thru -1 of bufferif aOffset is 0 thenset aOffset to offset of a in bufferset matches to {}set buffer to strset bLength to length of bset aLength to length of aon textsBetween(str, a, b)textsBetween(" 100000)tell table "donors"tell database "Campaign"close without savingsave in (filepath & ".csv") as CSV file formattell workbook 1open theDocumentset filepath to characters 1 thru -6 of (theDocument as text) as textset theDocument to choose file with prompt "Please choose " & fileType & " files:" of type {fileType}set fileType to "XLSX" as textlog "Skiën ⛷ kost veel €"tell application "Firefox" to set winTitle to name of first window whose miniaturizable is equal to true # first non-pip windowset process to std's import("process")set logger to std's import("logger")'s new("last-pass")end _getPasswordthePasswordkb's pressCommandShiftKey(tab)set the clipboard to originalClipboardset thePassword to the clipboardrepeat until thePassword is not ""set thePassword to ""click menu item "Copy Password" of menu 1 of menu bar item "Vault" of menu bar 1repeat until (the clipboard) is ""set originalClipboard to the clipboardon _getPassword()end _clearSearchif value of searchField is not "" then set value of searchField to ""on _clearSearch()end _searchselect row 2 of outline 1 of scroll area 2 of splitter group 1 of group 1 of splitter group 1 of window 1set value of searchField to distinctiveSearchKeyset searchField to text area 1 of scroll area 1 of splitter group 1 of group 1 of splitter group 1 of window 1if (count of windows) is 0 then returnif running of application "LastPass" is false then returnon _search(distinctiveSearchKey)end waitToUnlockreturn (exec of retry on Unlock by 0.5 for 200) is "unlocked"do shell script "afplay /System/Library/Sounds/Purr.aiff"logger's debug("Waiting for unlock...")tell application "System Events" to tell process "coreautha" to set frontmost to trueif unlockState is "unlocked" then return truereturn unlockState is "unlocked"set unlockState to exec of retry on Unlock by 0.5 for 120click button "UNLOCK" of window "App Lock Window"logger's debug("Clicking unlock...")do shell script "afplay /System/Library/Sounds/Purr.aiff" -- should be after the click but it takes a bit of time.if unlockState is "locked" thenif (count of windows) is not 0 then set frontmost to truereturn "unlocked"do shell script "afplay ~/applescript/sounds/Beer\\ Opening.aiff > /dev/null 2>&1 &"if exists (button "ADD ITEM" of group 1 of splitter group 1 of group 1 of splitter group 1 of window 1) thenscript Unlockif unlockState is missing value then return falselogger's debugf("unlockState: {}", unlockState)set unlockState to exec of retry on UnlockOrPasswordOrTouch by 0.5 for 120logger's debug("Waiting for unlock or password for 60s...")if exists (button "Use Password..." of window 1) then return "touch"tell application "System Events" to tell process "coreautha"if exists (button "UNLOCK" of window "App Lock Window") then return "locked"if exists (button "LastPass Enterprise" of splitter group 1 of window 1) then return "unlocked" -- TODO: Would fail for personal version.tell application "System Events" to tell process "LastPass" -- to updateactivate application "LastPass" -- issue where window isactivate application "LastPass"if running of application "LastPass" is false thenscript UnlockOrPasswordOrTouchlastPassProcess's terminate()set lastPassProcess to std's import("process")'s new("LastPass")tell application "System Events" to tell process "LastPass"if running of application "LastPass" is true thenon waitToUnlock()exec of retry on result for 5if thePassword is not missing value and thePassword is not "" then return thePasswordset thePassword to _getPassword()_search(credKey)_clearSearch()script GetPasswordScripton getPassword(credKey)script LastPassInstancelogger's info("Did not unlock")logger's infof("Password: {}", sut's getPassword("Dodoot."))if result is true thensut's waitToUnlock()global std, retry, kb, processend fmhash":=" & searchReplaceText(value, searchList, replaceList) & ":>"return "<:" & my searchReplaceText(name, searchList, replaceList) & ¬set replaceList to ["/:", "/=", "/>", "/<"]set searchList to [":", "=", ">", "<"]on fmhash(name, value)set clipTextFormatted to read file temp_path as «class XMCF»else if outputFormat is "custom_function" thenelse if outputFormat is "field" thenelse if outputFormat is "table" thenelse if outputFormat is "script_step" thenif outputFormat is "script" thenwrite clipText to temp_refon convertClip(clipText, outputFormat)end getTableNamesmyTableListcopy name of table tblLoop to end of myTableListrepeat with tblLoop from 1 to mytblcountdisplay dialog "There are no FileMaker 7 databases open!" buttons "Ok" with icon stop giving up after 5if mytblcount = 0 thencopy number of tables to mytblcountset myTableList to {}on getTableNames()end getScriptNamesmyScriptNameset myScriptName to ""set myScriptName to the name of FileMaker script 1 of database myDBif myScriptCount = 1 thenmyScriptListset myScriptList to myScriptList & myScriptItem & tabset myScriptItem to the name of FileMaker script ID (item i of myScriptIdList) of database myDBrepeat with i from 1 to the count of myScriptIdListset myScriptIdList to the ID of every FileMaker scriptif myScriptCount > 1 thenset myScriptCount to the count of every FileMaker scriptset myScriptIdList to {}set myScriptList to {}set myDB to theDatabaseset myTblNum to 1on getScriptNames(theDatabase)end getOpenDatabases_file_listcopy name of database _file_cur to end of _file_listrepeat with _file_cur from 1 to _file_countdisplay dialog "There are no FileMaker databases open!" buttons "Ok" with icon stop giving up after 5if _file_count = 0 thencopy number of databases to _file_countset _file_list to {}on getOpenDatabases()end splitFieldNamereturn _field_itemsdisplay dialog "Error: Please specify the table within this field name: " & fullyQualifiedFieldNameif (count of _field_items) < 2 thenset _field_items to fullyQualifiedFieldName's text itemsset AppleScript's text item delimiters to "::"to splitFieldName(fullyQualifiedFieldName)end performScriptdo script callbackScriptNameif callbackScriptName is not "" thenset field _result_field to _resulttell table _result_tableset _result_field to item 2 of _result_field_itemsset _result_table to item 1 of _result_field_itemsset _result_field_items to my splitFieldName(resultFieldNameFull)if resultFieldNameFull is not "" then"Partial Result: " & _partial) as text"Expected Type: " & _to & return & ¬"Object: " & _object & return & ¬set _result to ("Error " & _errorNumber & ": " & _errorText & return & ¬on error _errorText number _errorNumber from _object partial result _partial to _todo script scriptNameset _result to ""tell database databaseNameon performScript(databaseName, scriptName, resultFieldNameFull, callbackScriptName)end setFieldset field fieldName to theValuetell table (tableName as text)tell database (databaseName as text)on setField(databaseName, tableName, fieldName, theValue)end getFieldValuesfield (fieldName as text) of table (tableName as text)tell database (theDatabase as text)on getFieldValues(theDatabase, tableName, fieldName)end promptForDatabaseset _db_selected to choose from list dbList with prompt "Select database:"on promptForDatabase(dbList)---------------------------------------------click radio button "Scaled" of tab group 1 of window 1tell application "PyCharm" to tell application "System Events" to tell process "SystemUIServer"set visible to falseif visible thenperform action "AXPress" of (menu item "下一首" of menu "播放控制" of menu bar 1)tell process "QQMusic"return getImageAnimals("/Users/exampleUser/Documents/animals.png")end getImageAnimalsreturn text 1 thru -3 of theAnimalsset theAnimals to (theAnimals & label's identifier as text) & ", "repeat with label in (observation's labels())set theAnimals to ""set theRequest to current application's VNRecognizeAnimalsRequest's alloc()'s init()on getImageAnimals(imagePath)create note title theTitle with html theSource notebook "First Notebook"set theTitle to subject of theSelectionset theSource to getHtmlBody(theSource, msgContentType) of meif msgContentType starts with "multipart/alternative;" thenset msgContentType to content of header "content-type" of theSelectionset theSource to source of theSelectionset theSelection to first item of theSelectionend getHtmlBodyreturn theSourceset theSource to characters from beginning to (theOffset + (length of endHTML)) of theSource as stringset theOffset to offset of endHTML in theSourceset endHTML to ""set theSource to characters from theOffset to end of theSource as stringset theOffset to offset of " 0 thenset secs to 5on run args # restore from 0 to current volumeend is_pausedreturn (state is "paused") or ("kPSp" is in state)on is_paused(state)end iTunes_statetell application "iTunes" to return (get player state as string)on iTunes_state() #{playing, paused, stopped}end decodeTextreturn the character_list as stringset the end of the character_list to this_charset the temp_char to ""set the end of the character_list to my decodeChars(("%" & temp_char & this_char) as string)else if flag_B is true thenset flag_B to trueset the temp_char to this_charelse if flag_A is true thenset flag_A to trueif this_char is "%" thenset the character_list to {}set temp_char to ""set flag_B to falseset flag_A to falseon decodeText(this_text)end decodeCharsreturn (ASCII character ASCII_num)set the ASCII_num to (multiplier_amt * 16) + remainder_amtset the remainder_amt to the remainder_char as integerset the remainder_amt to the offset of the remainder_char in the hex_listif the remainder_char is in "ABCDEF" thenset the multiplier_amt to the multiplier_char as integerset the multiplier_amt to the offset of the multiplier_char in the hex_listif the multiplier_char is in "ABCDEF" thenset the hex_list to "123456789ABCDEF"copy these_chars to {indentifying_char, multiplier_char, remainder_char}on decodeChars(these_chars)key code 53 -- esc key to dispel drop-down menukeystroke query_textrepeat until ((the target of front Finder window as alias) as text) is (((the POSIX file search_path) as alias) as text)open ((POSIX file search_path) as alias)repeat until (target of front Finder window) is computer containeropen computer containerif no_search_path thenset the query_text to decodeText(query_text)set no_search_path to trueset no_search_path to falseset the query_text to (text from (x + 1) to -1 of the query_text)set the search_path to decodeText(search_path)set the search_path to (text 12 thru (x - 1) of the query_text)set x to the offset of "&" in the query_textif (text 1 thru 11 of the query_text) is "searchpath:" thenset the query_text to (text 11 thru -1 of this_URL)if (text 1 thru 10 of this_URL) is "spotlight:" thenplay document 1step forward document 1 by 150--Tells QuickTime to step forward by 150 frames (typically 5 seconds)end getTopLevelmy getTopLevel(parent of theCue)return theCueif q type of (parent of theCue) is "cue list" thenon getTopLevel(theCue)set selected to currentCueset cue target of goToCue to currentTopLevelmove cue id (uniqueID of goToCue) of parent of goToCue to end of lastCueBeforeMarkerset goToCue to last item of (selected as list)make type "goTo"set q name of newCue to (do shell script "echo " & sectionName & " | tr [:lower:] [:upper:]")set q color of newCue to userColormake type "memo"set selected to lastCueBeforeMarkerset sectionName to text returned of (display dialog "What title would you like to use for this section?" with title "Section Name" default answer "")set lastCueBeforeMarker to my getTopLevel(cue before currentTopLevel)set currentTopLevel to my getTopLevel(currentCue)set currentCue to last item of (selected as list)set userColor to "coral"userColorend fmGUI_ManageSecurity_PrivSet_OpenForEditerror "unable to fmGUI_ManageSecurity_PrivSet_OpenForEdit - " & errMsg number errNumreturn windowWaitUntil({windowName:"Edit Privilege Set"})fmGUI_ManageSecurity_PrivSet_Select(prefs)set defaultPrefs to {privSetName:null, fullAccessAccountName:null, fullAccessPassword:null}on fmGUI_ManageSecurity_PrivSet_OpenForEdit(prefs)fmGUI_ManageSecurity_PrivSet_OpenForEdit({privSetName:"[Full Access]", fullAccessAccountName:"admin", fullAccessPassword:""})set text of selection to theTextset theText to "<" & tagName & theClass & ">" & theText & ""set theClass to " class=\"" & className & "\""set className to item 2 of theSplitset tagName to item 1 of theSplitset theSplit to splitText(tagName, ".")if theOffset > 0 thenset theOffset to offset of "." in tagNameset theClass to ""set tagName to text returned of (display dialog "tag: " buttons {"Cancel", "Set"} with title "OK" cancel button "Cancel" default button "Set" default answer "")set theText to contents of selectionclose document 1 saving noexport document 1 in (file filePath) using settings preset "720p"stopdelay recordingTimedo shell script "python -c 'import time,Quartz; time.sleep(1); Quartz.NSEvent.mouseLocation(); Quartz.CGDisplayMoveCursorToPoint(0, (" & (_width / 2 as string) & "," & (_height / 2 as string) & "));mouse_location = Quartz.NSEvent.mouseLocation(); [ time.sleep(0.05) or Quartz.CGEventPost(Quartz.kCGHIDEventTap, Quartz.CGEventCreateMouseEvent(None, mouse_action, mouse_location, Quartz.kCGMouseButtonLeft)) for mouse_action in [ Quartz.kCGEventLeftMouseDown, Quartz.kCGEventLeftMouseUp, Quartz.kCGEventLeftMouseDown, Quartz.kCGEventLeftMouseUp ] ]'"tell newScreenRecordingtell process "QuickTime Player"set newScreenRecording to new screen recordingset _height to item 4 of _bset _width to item 3 of _bset _b to bounds of window of desktopdisplay notification filePathset filePath to (path to desktop as string) & "my recording at " & dateString & ".mov"set dateString to replace_chars((date string of (current date) as string) & " " & (time string of (current date) as string), ":", ".")set recordingTime to 10set new_event to make new event at calendar id 13 with properties { subject:"Test Event", content:"This is an event created to test AppleScript", all day event:true, start time:date (date string of ((current date) + 1 * days))}tell application "Microsoft Entourage"end myHandleron myHandler()set x to myHandler() of meset x to my myHandler()click radio button "Individual Slides" of radio group 1 of sheet 1 of window 1 --replace to suit your needsclick (checkbox 1 of sheet 1 of window 1)if value of (checkbox 1 of sheet 1 of window 1) is 0 thendisplay dialog "Script B says hi!"continue say_hello()do shell script shell_scriptset shell_script to "export PATH=" & pandoc_path & ":$PATH ; cd " & quoted form of file_container & " ; " & pandoc_path & "/pandoc" & " -f " & input_format & " -t " & output_format & space & more_options & " -o " & quoted form of new_file_path & space & quoted form of file_pathset new_file_path to file_container & "/" & file_name & "-output" & output_extensionset output_extension to "-zimwiki.txt"if output_format is "zimwiki" thenset output_extension to "-xwiki.txt"if output_format is "xwiki" thenset output_extension to ".textile"if output_format is "textile" thenset output_extension to ".texi"if output_format is "texinfo" thenset output_extension to "-tei.xml"if output_format is "tei" thenset output_extension to "-slidy.html"if output_format is "slidy" thenset output_extension to "-slideous.html"if output_format is "slideous" thenset output_extension to "-s5.html"if output_format is "s5" thenset output_extension to ".rtf"if output_format is "rtf" thenset output_extension to ".rst"if output_format is "rst" thenset output_extension to "-revealjs.html"if output_format is "revealjs" thenset output_extension to ".pptx"if output_format is "pptx" thenset output_extension to ".txt"if output_format is "plain" thenset output_extension to ".org"if output_format is "org" thenset output_extension to ".opml"if output_format is "opml" thenset output_extension to ".xml"if output_format is "opendocument" thenset output_extension to ".odt"if output_format is "odt" thenset output_extension to ".hs"if output_format is "native" thenset output_extension to ".muse"if output_format is "muse" thenset output_extension to ".ms"if output_format is "ms" thenset output_extension to "-mediawiki.txt"if output_format is "mediawiki" thenset output_extension to "-markua.md"if output_format is "markua" thenset output_extension to "-strict.md"if output_format is "markdown_strict" thenset output_extension to "-phpextra.md"if output_format is "markdown_phpextra" thenset output_extension to "-mmd.md"if output_format is "markdown_mmd" thenset output_extension to "-github.md"if output_format is "markdown_github" thenset output_extension to ".md"if output_format is "markdown" thenset output_extension to ".man"if output_format is "man" thenset output_extension to ".tex"if output_format is "latex" thenset output_extension to ".json"if output_format is "json" thenset output_extension to "-jira.txt"if output_format is "jira" thenset output_extension to "-jats_publishing.xml"if output_format is "jats_publishing" thenset output_extension to "-jats_articleauthoring.xml"if output_format is "jats_articleauthoring" thenset output_extension to "-jats_archiving.xml"if output_format is "jats_archiving" thenset output_extension to ".icml"if output_format is "icml" thenset output_extension to ".html"if output_format is "html5" thenset output_extension to "-html4.html"if output_format is "html4" thenset output_extension to "-haddock.hs"if output_format is "haddock" thenset output_extension to "-gfm.md"if output_format is "gfm" thenset output_extension to ".fb2"if output_format is "fb2" thenset output_extension to ".epub"if output_format is "epub3" thenset output_extension to "-epub2.epub"if output_format is "epub2" thenset output_extension to "-dzslides.html"if output_format is "dzslides" thenset output_extension to "-dokuwiki.txt"if output_format is "dokuwiki" thenset output_extension to ".docx"if output_format is "docx" thenset output_extension to "-docbook5.xml"if output_format is "docbook5" thenset output_extension to "-docbook4.xml"if output_format is "docbook4" thenset output_extension to "-csl.json"if output_format is "csljson" thenset output_extension to "-context.tex"if output_format is "context" thenset output_extension to "-commonmark_x.md"if output_format is "commonmark_x" thenset output_extension to "-commonmark.md"if output_format is "commonmark" thenset output_extension to "-biblatex.bib"if output_format is "biblatex" thenset output_extension to ".bib"if output_format is "bibtex" thenset output_extension to "-beamer.tex"if output_format is "beamer" thenset output_extension to "-asciidoc.txt"if output_format is "asciidoc" thenset output_format to item o of output_format_wordsrepeat with o from 1 to the count of output_format_wordsset file_name to the name of file_infoset file_container to POSIX path of (container of i)set file_path to POSIX path of iif the folder of file_info is false thenset the file_info to info for irepeat with i in dropped_filesset more_options to text returned of optionsDialogResultif button returned of optionsDialogResult is "OK" thenset optionsDialogResult to display dialog "Input format: " & input_format & return & return & "Output format(s): " & output_format_list & return & return & "If you would like to add more command-line options, add them carefully in the field below, for example:" & return & return & "Some reader options:" & return & "--indented-code-classes=CLASSES --default-image-extension=EXTENSION --metadata=KEY[:VAL] --preserve-tabs --tab-stop=NUMBER --track-changes=accept|reject|all --extract-media=DIR --shift-heading-level-by=X, where X=NUMBER-1" & return & return & "Some writer options:" & return & "--data-dir=DIRECTORY --defaults=FILE --standalone --wrap=auto|none|preserve --columns=NUMBER --toc (requires --standalone) --toc-depth=NUMBER --no-highlight --highlight-style=STYLE --resource-path=SEARCHPATH --template=FILE|URL --variable=KEY[:VAL]" & return & return & "Some options affecting specific writers:" & return & "--ascii -atx-headers --reference-links --reference-location=block|section|document --number-sections --number-offset=NUMBER[,NUMBER,...] --top-level-division=default|section|chapter|part --listings --incremental --slide-level=NUMBER --section-divs --email-obfuscation=none|javascript|references --id-prefix=STRING --css=URL --reference-doc=FILE --epub-cover-image=FILE --epub-metadata=FILE --epub-embed-font=FILE --epub-chapter-level=NUMBER --pdf-engine=pdflatex|lualatex|xelatex --pdf-engine-opt=STRING --bibliography=FILE --citeproc|--natbib|--biblatex --csl=FILE" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" default answer "--standalone" with title "Pandoc: Specify other options"set output_format_list to outputDialogResult as textset text item delimiters to ", "if (first item of output_format_words) is in outputFormats thenset output_format_words to words of (outputDialogResult as text)set text item delimiters to spaceset outputDialogResult to {choose from list outputFormats with title "Pandoc: Specify output format(s)" with prompt "Input format is " & input_format & ". What output format(s) do you want? (Note that markdown_github is deprecated in favor of gfm for GitHub-Flavored Markdown.)" default items "html5" with multiple selections allowed}set outputFormats to {"asciidoc", "beamer", "bibtex", "biblatex", "commonmark", "commonmark_x", "context", "csljson", "docbook4", "docbook5", "docx", "dokuwiki", "dzslides", "epub2", "epub3", "fb2", "gfm", "haddock", "html4", "html5", "icml", "ipynb", "jats_archiving", "jats_articleauthoring", "jats_publishing", "jira", "json", "latex", "man", "markdown", "markdown_github", "markdown_mmd", "markdown_phpextra", "markdown_strict", "markua", "mediawiki", "ms", "muse", "native", "odt", "opendocument", "opml", "org", "plain", "pdf", "pptx", "revealjs", "rst", "rtf", "s5", "slideous", "slidy", "tei", "texinfo", "textile", "xwiki", "zimwiki"}if input_format is in inputFormats thenset input_format to inputDialogResult as stringset inputDialogResult to {choose from list inputFormats with title "Pandoc: Specify input format" with prompt "What is the format of the file(s) to be converted? (Note that markdown_github is deprecated in favor of gfm for GitHub-Flavored Markdown.)" default items "html"}set inputFormats to {"bibtex", "biblatex", "commonmark", "commonmark_x", "creole", "csljson", "csv", "docbook", "docx", "dokuwiki", "endnotexml", "epub", "fb2", "gfm", "haddock", "html", "ipynb", "jats", "jira", "json", "latex", "man", "markdown", "markdown_github", "markdown_mmd", "markdown_phpextra", "markdown_strict", "mediawiki", "muse", "native", "odt", "opml", "org", "ris", "rst", "rtf", "t2t", "textile", "tikiwiki", "twiki", "vimwiki"}open resultchoose file with prompt "Which file(s) would you like to convert using Pandoc? If you select multiple files, all must have the same format." with multiple selections allowedproperty pandoc_path : "/usr/local/bin" -- The folder containing pandocproperty pandoc_version : "2.18"property script_version : "3.3"property script_title : "AppleScript droplet for pandoc file conversion"return "(Safari URL not available)"return "(Safari is not running)"return URL of front document end hashFunctionreturn _hash mod initSize + 1set _hash to _hash + charrepeat with char in (id of _key as list)set _hash to count _key -- Credits to Shane Stanly here, supports single character keys now.on hashFunction(_key)end countreturn my sizeon countend setValuesif (count _values) = (count my valueList) then set my valueList to _valueson setValues(_values)end valuesreturn my valueListon values()end valueExistsreturn my valueList contains _valueon valueExists(_value)end setKeysif (count _keys) = (count my keyList) thenset _keys to every text of _keyson setKeys(_keys)return my keyListon keys()end keyExistsreturn my keyList contains _keyon keyExists(_key)return item node of my valueListon valueForKey(_key)end setValueforKeyset end of item x of my hashList to my sizeset end of my keyList to _keyset end of my valueList to _valueset my size to (my size) + 1set item node of my valueList to _valueif id of item node of my keyList = id of _key thenset x to hashFunction(_key)on setValueforKey(_key, _value)end initWithKeysAndValuesset end of item hashFunction(item x of my keyList) of my hashList to xrepeat with x from 1 to my sizeset my size to count my keyListset my valueList to _valuesset my keyList to _keyson initWithKeysAndValues(_keys, _values)set my valueList to {}set my keyList to {}set end of my hashList to {}repeat initSize timesset initSize to getPrimeSize()set my hashList to {}set my size to 0end getPrimeSizereturn initSizereturn nextPrime as integerif initSize < nextPrime thenrepeat with nextPrime in my PrimesToMillionon getPrimeSize()end newInstanceproperty valueList : missing valueproperty keyList : missing valueproperty hashList : missing valueproperty size : missing valueproperty parent : hashTablescript hashTableInstanceon newInstance()write nodeDisplay & (ASCII character 10) as text to fileIDset nodeDisplay to nodeDisplay & (id of item node of my keyList) & ", " as textrepeat with node in item x of my hashListset nodeDisplay to (the count of item x of my hashList) & ": " as textif nodeCount > 0 thenset nodeCount to the count of item x of my hashListrepeat with x from 1 to the count of my hashListset eof of fileID to 0set fileID to open for access POSIX file (POSIX path of (the path to the desktop) & "Remove Duplicate Messages Hash Table Node Listing.txt" as text) with write permissionon debug()property initSize : 1000script hashTableend SetMailShowDuplicatesSettingreturn (GetMailShowDuplicatesSetting() is shouldShowDuplicates)do shell script commandset command to "defaults write com.apple.mail " & keyName & " -bool false"my LogEntry("Hiding duplicate messages in Mail.")set command to "defaults write com.apple.mail " & keyName & " -bool true"my LogEntry("Showing duplicate messages in Mail.")if shouldShowDuplicates thenset success to false -- default: failureon SetMailShowDuplicatesSetting(shouldShowDuplicates)end GetMailShowDuplicatesSettingreturn (output is "1")set output to do shell script commandset output to "0" -- default: not setset command to "defaults read com.apple.mail " & keyNameset keyName to "AlwaysShowDuplicates" -- older than Yosemiteset keyName to "_AlwaysShowDuplicates" -- Yosemite or laterif osVersion ≥ 101000 thenset osVersion to GetOSVersion()on GetMailShowDuplicatesSetting()end GetOSVersionreturn versionValue as numberset versionValue to versionValue + tempset temp to ((item i of v) as integer) * (100 ^ (3 - i)) as integerrepeat with i from 1 to number of items of vset versionValue to 0set AppleScript's text item delimiters to saveDelimset v to the text items of osVersionset saveDelim to AppleScript's text item delimitersset osVersion to osVersion as stringset osVersion to do shell script "sw_vers -productVersion"on GetOSVersion()end GetUserArchiveDuplicateMessagesChoicemy LogEntry("User chose not to archive any duplicate messages.")else if choice is "Discard All" thenmy LogEntry("User chose to archive all duplicate messages.")if choice is "Archive All" then"Click \"Archive All\" to archive all duplicate messages before removal. Click \"Discard All\" to remove duplicate messages without archiving them." as critical buttons {"Discard All", "Archive All"} default button "Archive All" giving up after pDialogTimeoutset dResult to display alert "Archive Action" message "Save duplicate messages to the archive folder on your desktop before they are removed from Apple Mail?" & return & return & ¬on GetUserArchiveDuplicateMessagesChoice()end GetUserRemoveDuplicateMessagesChoicereturn "ask"my LogEntry("User wishes to choose whether to remove each encountered duplicate message interactively.")else if choice is "Ask Me" thenmy LogEntry("User chose not to remove any duplicate messages.")else if choice is "Leave In Place" thenmy LogEntry("User chose to remove all duplicate messages.")if choice is "Remove All" thenset choice to dResult's button returned"Click \"Remove All\" to remove all duplicate messages. Click \"Ask Me\" to have the script ask you what to do for each duplicate message. Click \"Leave In Place\" to leave duplicate messages in place." as critical buttons {"Remove All", "Leave In Place", "Ask Me"} default button "Ask Me" giving up after pDialogTimeoutset dResult to display alert "Remove Action" message "Remove duplicate messages from Apple Mail?" & return & return & ¬on GetUserRemoveDuplicateMessagesChoice()end DisplayAbout"This script is provided with source code so that you may edit the script as you see fit. Read the included instructions for more information." as informational buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit""If a message's Subject, From, and Date headers match another message in the selection and the Message-ID header is either empty or matches the other message, the script considers the message to be a duplicate and removes the duplicate message from Mail, optionally saving the message as an archive to a file first. During this process, matching messages that have a larger total Attachment size are preferred." & return & return & ¬"• Attachments" & return & return & ¬"• Message ID" & return & ¬"• Date" & return & ¬"• From" & return & ¬"• Subject" & return & ¬& "The script determines whether a message is a duplicate of another message by examining these message properties:" & return & return & ¬display alert pScriptname message "This script removes duplicate messages from the current selection in Apple Mail." & return & return ¬on DisplayAbout()end ViewingLogreturn (pid is not "")set pid to do shell script commandset command to "ps | grep -v grep | grep 'tail -f' | grep " & the quoted form of pLogFileName & " | awk '{print $1}'"on ViewingLog()end ViewLogset newTab to do script terminalCommandset terminalCommand to ("tail -f " & the quoted form of (logFile's POSIX path))set logFile to (logFolder & pLogFileName as text)if alreadyViewing is not true thenset alreadyViewing to ViewingLog()on ViewLog()end SplitFilenameFromExtensionreturn {filename, fileExtension}set filename to item 1 of itemListif i is not numItems then set filename to filename & "."set filename to filename & item i of itemListrepeat with i from 1 to (numItems - 1)if numItems is greater than 2 thenset fileExtension to item (numItems) of itemListset numItems to the count of items in itemListset AppleScript's text item delimiters to saveDelimsset itemList to (every text item of filename)set saveDelims to AppleScript's text item delimiterson SplitFilenameFromExtension(filename)end MakeFilenameUniquereturn newNameset unique to not (my FileExists(parentFolder & newName))set newName to trimmedBaseFilename & "-" & counter & "." & fileExtension as textset trimmedBaseFilename to characters 1 through ((count of baseFilename) - ((count of (counter as text)) + 1)) of baseFilenamerepeat until uniqueset counter to 1if not unique thenset unique to not (my FileExists(parentFolder & newName as text))set {baseFilename, fileExtension} to my SplitFilenameFromExtension(newName)set newName to inNameon MakeFilenameUnique(parentFolder, inName)end CreateFolderreturn folderPath as textwith properties {name:folderName}at (parentFolder as alias) ¬set folderPath to make new folder ¬if (not my FileExists(folderPath)) thenset folderPath to (parentFolder & folderName & ":" as text)set parentFolder to (parentFolder & ":" as text)if the last character of (parentFolder as text) is not ":" thenon CreateFolder(parentFolder, folderName)end FileExistsreturn doesExistset doesExist to trueset anAlias to (someFile as alias)set doesExist to falseon FileExists(someFile)end TrimStringToLengthreturn (characters 1 through maxLength of someText) as textif the (count of someText) ≤ maxLength thenon TrimStringToLength(someText, maxLength)end FixFilenameset someText to textItems as Unicode textset textItems to text items of someTexton FixFilename(someText)end ListToStringif i < the (count of someList) then set someText to someText & ", "set someText to someText & nextItemset nextItem to item i of someListrepeat with i from 1 to the count of someListif (count of someList) > 0 thenset someText to ""on ListToString(someList)end SumListOfNumbersset totalSize to totalSize + nextNumberrepeat with nextNumber in numberListon SumListOfNumbers(numberList)end FormatDateTimereturn (yy & "/" & mm & "/" & dd & " " & hh as text)set hh to time string of theDateset yy to text -1 through -4 of ((year of theDate) as text)("0" & 1 + (theDate - tempDate + 1314864) div 2629728)set mm to text -2 thru -1 of ¬set the month of tempDate to Januarycopy theDate to tempDateset dd to text -2 thru -1 of ("0" & theDate's day)set theDate to theDate as dateon FormatDateTime(theDate)end LogEntryclose access logRefwrite FormatDateTime(current date) & ": " & someText & (ASCII character 10) starting at eof to logRefif logRef ≠ 0 thenset logRef to open for access (file logFile) with write permissionset logFile to (logFolder as text) & pLogFileNameif not pLogging then returnon LogEntry(someText)end SaveMessageclose access fileIDwrite msgSource to fileIDset fileID to open for access file outFile with write permissionmy LogEntry("Archiving message " & msgID & " in file: " & outFilename)set outFile to (archiveFolder & outFilename) as textset outFilename to my MakeFilenameUnique(archiveFolder, outFilename)set outFilename to my FixFilename(outFilename & ".eml")set outFilename to my TrimStringToLength(msgSubject, 255 - 4) -- max filename length is 255 characters minus 4 characters for filename extensionif msgSubject is "" then set msgSubject to "Untitled"on SaveMessage(msgID, msgSubject, msgSource)end GetMessageDetailsreturn {appleid:thisMessageID, messageid:thisMessageMID, subject:thisMessageSubject, sender:thisMessageSender, datesent:thisMessageSentDate, mailbox:thisMessageMailbox, account:thisMessageAccount, source:thisMessageSource, attachmentnames:thisMessageAttachmentNames, attachmentcount:thisMessageAttachmentCount, attachmentsize:thisMessageAttachmentTotalSize}if pDebug then my LogEntry("DEBUG: ERROR: Could not get attachment sizes for next message: [" & thisMessageID & "] \"" & thisMessageSubject & "\" due to error: " & errMessage & " (" & errNumber & ")")set thisMessageAttachmentTotalSize to 0tell application "Mail" to set thisMessageAttachmentTotalSize to my SumListOfNumbers(the file size of every mail attachment of thisMessage)if pDebug then my LogEntry("DEBUG: ERROR: Could not get attachment count for next message: [" & thisMessageID & "] \"" & thisMessageSubject & "\" due to error: " & errMessage & " (" & errNumber & ")")set thisMessageAttachmentCount to 0tell application "Mail" to set thisMessageAttachmentCount to the count of the mail attachments of thisMessageif pDebug then my LogEntry("DEBUG: ERROR: Could not get attachment names for next message: [" & thisMessageID & "] \"" & thisMessageSubject & "\" due to error: " & errMessage & " (" & errNumber & ")")set thisMessageAttachmentNames to ""tell application "Mail" to set thisMessageAttachmentNames to my ListToString(the name of every mail attachment of thisMessage)set thisMessageSource to thisMessage's source as rich textset thisMessageAccount to "On My Mac" -- "On My Mac" messages have no associated accountset thisMessageAccount to the name of the account of (thisMessage's mailbox)set thisMessageMailbox to the name of thisMessage's mailboxset thisMessageSentDate to thisMessage's date sentset thisMessageSender to thisMessage's senderset thisMessageSubject to thisMessage's subjectset thisMessageMID to thisMessage's message idset thisMessageID to thisMessage's idon GetMessageDetails(thisMessage)end ProcessMessagereturn userRequestedAbortif pDebug then LogEntry("DEBUG: no potential duplicates found in encountered message list")my LogEntry(" NOTICE: Since you specified that you want duplicate messages left in place, the script will NOT remove duplicate message " & clunkerID & ".")my LogEntry(" NOTICE: Since pDebug property is set to true, I will NOT remove duplicate message " & clunkerID & ".")set removedMessagesCount to removedMessagesCount + 1set the end of removedMessages to clunkerIDif messageMovedToTrash thenmy LogEntry("ERROR: Could not remove duplicate message " & clunkerID & " due to an error: " & errorMessage & " (" & errorNumber & "). Giving up.")tell application "Mail" to move clunker to mailbox "Deleted Messages"if not messageMovedToTrash thenmy LogEntry("ERROR: Could not remove duplicate message " & clunkerID & " due to an error: " & errorMessage & " (" & errorNumber & "). I will try an alternative method.")set messageMovedToTrash to truemy LogEntry("Message was removed.")tell application "Mail" to move clunker to mailbox "Trash" of account clunkerAccountset messageMovedToTrash to falsemy LogEntry("Removing duplicate message " & clunkerID & ".")if (not pDebug) thenif (shouldRemove) thenset shouldRemove to removeDuplicatesmy LogEntry(" User interactively chose to retain duplicate message " & clunkerID & ".")my LogEntry(" User interactively chose to remove duplicate message " & clunkerID & ".")if shouldRemove thenmy LogEntry(" User interactively chose to quit processing messages.")set shouldRemove to (userChoice is "Remove")set userRequestedAbort to (userChoice is "Quit")set userChoice to dResult's button returnedset dResult to display alert "Duplicate Message Encountered" message alertMessage as critical buttons {"Quit", "Remove", "Leave In Place"} default button "Leave In Place" giving up after pDialogTimeout"Would you like to remove this duplicate message now?""• Attachments: " & clunkerAttachmentPhrase & return & return & ¬"• Sent: " & clunkerSentDate & return & ¬"• From: " & clunkerSender & return & ¬"• Subject: " & clunkerSubject & return & ¬"• Mailbox: " & clunkerMailbox & " (Account: " & clunkerAccount & ")" & return & ¬"• Message-ID: " & clunkerMID & return & ¬"REMOVING Message " & clunkerID & ":" & return & ¬"• Attachments: " & keeperAttachmentPhrase & return & return & ¬"• Sent: " & keeperSentDate & return & ¬"• From: " & keeperSender & return & ¬"• Subject: " & keeperSubject & return & ¬"• Mailbox: " & keeperMailbox & " (Account: " & keeperAccount & ")" & return & ¬"• Message-ID: " & keeperMID & return & ¬"Keeping Message " & keeperID & ":" & return & ¬set alertMessage to "Message " & clunkerID & " matches previously encountered message:" & return & return & ¬set clunkerAttachmentPhrase to "(" & clunkerAttachmentCount & ") " & clunkerAttachmentNames & " (" & clunkerAttachmentTotalSize & " bytes)"set clunkerAttachmentPhrase to "none"set keeperAttachmentPhrase to "(" & keeperAttachmentCount & ") " & keeperAttachmentNames & " (" & keeperAttachmentTotalSize & " bytes)"set keeperAttachmentPhrase to "none"if (removeDuplicates is "ask") thenset shouldRemove to falseset archivedMessagesCount to archivedMessagesCount + 1my SaveMessage(clunkerID, clunkerSubject, clunkerSource)if (archiveDuplicates) thenmy LogEntry(" Attachments: (" & clunkerAttachmentCount & ") " & clunkerAttachmentNames & " (" & clunkerAttachmentTotalSize & " bytes)")if clunkerAttachmentCount = 0 thenmy LogEntry(" Sent: " & clunkerSentDate)my LogEntry(" From: " & clunkerSender)my LogEntry(" Subject: " & clunkerSubject)my LogEntry(" Mailbox: " & clunkerMailbox & " (Account: " & clunkerAccount & ")")my LogEntry(" Message-ID: " & clunkerMID)my LogEntry(" DELETING Message " & clunkerID & ":")my LogEntry(" Attachments: (" & keeperAttachmentCount & ") " & keeperAttachmentNames & " (" & keeperAttachmentTotalSize & " bytes)")if keeperAttachmentCount = 0 thenmy LogEntry(" Sent: " & keeperSentDate)my LogEntry(" From: " & keeperSender)my LogEntry(" Subject: " & keeperSubject)my LogEntry(" Mailbox: " & keeperMailbox & " (Account: " & keeperAccount & ")")my LogEntry(" Message-ID: " & keeperMID)my LogEntry(" Keeping Message " & keeperID & ":")set clunkerAttachmentTotalSize to selectedAttachmentTotalSizeset clunkerAttachmentCount to selectedAttachmentCountset clunkerAttachmentNames to selectedAttachmentNamesset clunkerSource to selectedSourceset clunkerAccount to selectedAccountset clunkerMailbox to selectedMailboxset clunkerSentDate to selectedSentDateset clunkerSender to selectedSenderset clunkerSubject to selectedSubjectset clunkerMID to selectedMIDset clunkerID to selectedIDset clunker to selectedMessageset keeperAttachmentTotalSize to nextAttachmentTotalSizeset keeperAttachmentCount to nextAttachmentCountset keeperAttachmentNames to nextAttachmentNamesset keeperSource to nextSourceset keeperAccount to nextAccountset keeperMailbox to nextMailboxset keeperSentDate to nextSentDateset keeperSender to nextSenderset keeperSubject to nextSubjectset keeperMID to nextMIDset keeperID to nextIDset keeper to nextMessageencounteredMessages's setValueforKey(hashString, {{object:selectedMessage, appleid:selectedID, messageid:selectedMID, subject:selectedSubject, sender:selectedSender, sentdate:selectedSentDate, mailbox:selectedMailbox, account:selectedAccount}})LogEntry(" Adding this message to encountered messages list")set clunkerAttachmentTotalSize to nextAttachmentTotalSizeset clunkerAttachmentCount to nextAttachmentCountset clunkerAttachmentNames to nextAttachmentNamesset clunkerSource to nextSourceset clunkerAccount to nextAccountset clunkerMailbox to nextMailboxset clunkerSentDate to nextSentDateset clunkerSender to nextSenderset clunkerSubject to nextSubjectset clunkerMID to nextMIDset clunkerID to nextIDset clunker to nextMessageset keeperAttachmentTotalSize to selectedAttachmentTotalSizeset keeperAttachmentCount to selectedAttachmentCountset keeperAttachmentNames to selectedAttachmentNamesset keeperSource to selectedSourceset keeperAccount to selectedAccountset keeperMailbox to selectedMailboxset keeperSentDate to selectedSentDateset keeperSender to selectedSenderset keeperSubject to selectedSubjectset keeperMID to selectedMIDset keeperID to selectedIDset keeper to selectedMessagemy LogEntry(" Keeping this message and removing message " & nextID & " instead.")my LogEntry(" This message has a larger attachment size than matching message " & nextID & " (" & selectedAttachmentTotalSize & " bytes > " & nextAttachmentTotalSize & " bytes).")if selectedAttachmentTotalSize > nextAttachmentTotalSize thenset duplicateMessagesCount to duplicateMessagesCount + 1my LogEntry(" This is a duplicate message (Message-ID header is empty or matches previously encountered message " & nextID & ").")if (selectedMID is "") or (selectedMID is nextMID) thenif nextID is not in removedMessages thenmy LogEntry(" Attachments: (" & nextAttachmentCount & ") " & nextAttachmentNames & " (" & nextAttachmentTotalSize & " bytes)")if nextAttachmentCount = 0 thenmy LogEntry(" Subject: " & nextSubject)my LogEntry(" From: " & nextSender)my LogEntry(" Sent: " & nextSentDate)my LogEntry(" Mailbox: " & nextMailbox & " (Account: " & nextAccount & ")")my LogEntry(" Message-ID: " & nextMID)my LogEntry(" Next Message " & nextID & ":")set nextAttachmentTotalSize to the attachmentsize of the nextMessageDetailsset nextAttachmentCount to the attachmentcount of the nextMessageDetailsset nextAttachmentNames to the attachmentnames of nextMessageDetailsset nextAccount to the account of nextMessageDetailsset nextMailbox to the mailbox of nextMessageDetailsset nextSource to the source of nextMessageDetailsset nextSentDate to the datesent of nextMessageDetailsset nextSender to the sender of nextMessageDetailsset nextSubject to the subject of nextMessageDetailsset nextMID to the messageid of nextMessageDetailsset nextID to the appleid of nextMessageDetailsset nextMessageDetails to my GetMessageDetails(nextMessage)set nextMessage to nextPotential's objectrepeat with nextPotential in potentialMatchesif pDebug then LogEntry(" DEBUG: comparing with " & the numPotentialMatches & " matching encountered messages")if numPotentialMatches > 0 thenset numPotentialMatches to the count of potentialMatchesif pDebug then my LogEntry(" DEBUG: potential duplicates: " & the (count of potentialMatches))set potentialMatches to encounteredMessages's valueForKey(hashString)if pDebug then my LogEntry(" DEBUG: we've encountered a message with this hash before")if encounteredMessages's keyExists(hashString) thenset potentialMatches to {}if pDebug then my LogEntry(" DEBUG: selected message hash: " & hashString)set hashString to (selectedSubject & " " & selectedSender & " " & FormatDateTime(selectedSentDate)) as textmy LogEntry(" Attachments: (" & selectedAttachmentCount & ") " & selectedAttachmentNames & " (" & selectedAttachmentTotalSize & " bytes)")my LogEntry(" Attachments: none")if selectedAttachmentCount = 0 thenmy LogEntry(" Sent: " & selectedSentDate)my LogEntry(" From: " & selectedSender)my LogEntry(" Subject: " & selectedSubject)my LogEntry(" Mailbox: " & selectedMailbox & " (Account: " & selectedAccount & ")")my LogEntry(" Message-ID: " & selectedMID)my LogEntry(" Selected Message " & selectedID & ":")set selectedAttachmentTotalSize to the attachmentsize of the selectedMessageDetailsset selectedAttachmentCount to the attachmentcount of the selectedMessageDetailsset selectedAttachmentNames to the attachmentnames of selectedMessageDetailsset selectedSource to the source of selectedMessageDetailsset selectedAccount to the account of selectedMessageDetailsset selectedMailbox to the mailbox of selectedMessageDetailsset selectedSentDate to the datesent of selectedMessageDetailsset selectedSender to the sender of selectedMessageDetailsset selectedSubject to the subject of selectedMessageDetailsset selectedMID to the messageid of selectedMessageDetailsset selectedID to the appleid of selectedMessageDetailsset selectedMessageDetails to my GetMessageDetails(selectedMessage)tell application "Mail" to my LogEntry("Examining " & selectedIndex & " of " & selectedCount & ": [" & the id of the selectedMessage & "] \"" & the subject of the selectedMessage & "\".")set clunkerAttachmentTotalSize to missing valueset clunkerAttachmentNames to missing valueset clunkerAccount to missing valueset clunkerSource to missing valueset clunkerMailbox to missing valueset clunkerSentDate to missing valueset clunkerSender to missing valueset clunkerSubject to missing valueset clunkerMID to missing valueset clunkerID to missing valueset clunker to missing valueset keeperAttachmentTotalSize to missing valueset keeperAttachmentNames to missing valueset keeperAccount to missing valueset keeperSource to missing valueset keeperMailbox to missing valueset keeperSentDate to missing valueset keeperSender to missing valueset keeperSubject to missing valueset keeperMID to missing valueset keeperID to missing valueset keeper to missing valueset userRequestedAbort to falseon ProcessMessage(selectedMessage, selectedIndex, selectedCount)my LogEntry("Finished. Goodbye.")tell application "Mail" to set message viewer 1's selected messages to {}my LogEntry("No messages were selected, or an error occurred. Aborting script.")display alert alertTitle message alertMsg as informational buttons {"Continue"} default button 1 giving up after pAlertTimeoutmy LogEntry("No duplicate messages were found or removed.")set alertMsg to "No duplicate messages were found or removed."my LogEntry("No duplicate messages were removed.")set alertMsg to alertMsg & ("No duplicate messages were removed. " as string)my LogEntry("No removed duplicate messages were archived.")set alertMsg to alertMsg & ("No removed duplicate messages were archived.")my LogEntry("All removed duplicate messages are now archived here: " & archiveFolder's POSIX path)set alertMsg to alertMsg & ("All duplicate messages that were removed are now archived here:" & return & return & archiveFolder's POSIX path as string)if (archiveDuplicates is true) thenmy LogEntry(removedMessagesCount & " duplicate messages were removed.")set alertMsg to alertMsg & (removedMessagesCount & " duplicate messages were removed. " as string)if removedMessagesCount is greater than 0 thenmy LogEntry(duplicateMessagesCount & " duplicate messages were found.")set alertMsg to (duplicateMessagesCount & " duplicate messages were found. " as string)if duplicateMessagesCount is greater than 0 thenset alertTitle to "Final Report"set duplicatesAreShown to SetMailShowDuplicatesSetting(false)my LogEntry("Re-configuring Mail to hide duplicate messages (the default factory configuration).")tell application "Mail" to set include when getting new mail of nextAccount to truemy LogEntry(displayMessage)set displayMessage to "Re-enabling automatic checking for these Mail accounts: " & accountDisplayListif automaticCheckingDisabled thenmy LogEntry("Time elapsed: " & endTime - startTime & " seconds.")set endTime to the current dateencounteredMessages's debug()if pDebug thenmy LogEntry("Aborting processing as requested by user after message " & m & " of " & selectedMessageCount)if userRequestedAbort thenset userRequestedAbort to my ProcessMessage(nextMessage, m, selectedMessageCount)set nextMessage to (a reference to selectedMessages's item m)repeat with m from 1 to the selectedMessageCountset startTime to the current datedisplay alert "Cannot Disable Automatic Mail Checking" message alertMsg as informational buttons {"Understood"} default button "Understood"set alertMsg to "When Mail is configured to automatically check for new messages, certain Mail operations (such as mail rule processing, importing mailboxes, and asking if attachments should be downloaded when new messages arrive) may cause Mail to stop responding to script commands while processing large numbers of messages. " & return & return & "Due to a bug in this version of macOS, this script cannot ask Mail to temporarily disable this property while the script runs. Here is the error message generated by Mail: " & return & return & errorMessage & "(" & errorNumber & ")"set automaticCheckingDisabled to truetell application "Mail" to set include when getting new mail of every account to falsemy LogEntry("Disabling automatic mail checking for these Mail accounts: " & accountDisplayList)display alert "Disabling Automatic Mail Checking" message alertMsg as informational buttons {"Continue"} default button "Continue" giving up after pAlertTimeoutset alertMsg to "Mail is configured to automatically check for new messages for these accounts: " & accountDisplayList & return & return & "Certain Mail operations (such as importing mailboxes, and asking if attachments should be downloaded when new messages arrive) may cause Mail to stop responding to script commands while processing large numbers of messages. " & return & return & "In order to minimize such potential interruptions, this property is being temporarily disabled for these accounts, and will be re-enabled once the script is finished processing messages."set accountDisplayList to text 1 through ((count of accountDisplayList) - 2) of accountDisplayList -- remove trailing comma and spaceset accountDisplayList to accountDisplayList & (accountName & ", ") as texttell application "Mail" to set accountName to the name of nextAccountrepeat with nextAccount in enabledAccountsset accountDisplayList to ""if (count of enabledAccounts) is greater than 0 thentell application "Mail" to set enabledAccounts to every account whose enabled is true and include when getting new mail is truemy LogEntry("Duplicate messages are already shown in Mail.")set duplicatesAreShown to SetMailShowDuplicatesSetting(true)my LogEntry("Temporarily configuring Mail to show duplicate messages.")if not duplicatesWereShown thenset duplicatesWereShown to my GetMailShowDuplicatesSetting()my LogEntry("Hash tables tables are initialized.")set archivedMessages to hashTable's newInstance()'s init()set hashTable's initSize to 1000 as integerset encounteredMessages to hashTable's newInstance()'s init()set hashTable's initSize to (selectedMessageCount * 2) as integerif (selectedMessageCount * 2 > 1000) thenmy LogEntry("Preparing encountered message and archived message hash tables...")set archiveDuplicates to my GetUserArchiveDuplicateMessagesChoice()set removeDuplicates to my GetUserRemoveDuplicateMessagesChoice()my LogEntry("Processing " & selectedMessageCount & " messages.")if gotSelectedMessages thendisplay alert "Could Not Get Selected Messages" message ("The script could not obtain a list of selected messages from Apple Mail." & return & return & "Error Message: \"" & errorMessage & "\" (" & errorNumber & ")" as text) as critical buttons {"Quit"} default button "Quit"my LogEntry("Could not get selected messages. Error Message: \"" & errorMessage & "\" (" & errorNumber & ")")set gotSelectedMessages to truedisplay alert "Select Messages First" message (selectedMessageCountPhrase & " The script will now abort." & return & return & "If you want to select all messages, choose Edit > Select All from the Mail menu bar before running this script." as text) as critical buttons {"Quit"} default button "Quit"if selectedMessageCount < 2 thenmy LogEntry(selectedMessageCountPhrase)set selectedMessageCountPhrase to selectedMessageCount & " messages are selected."set selectedMessageCountPhrase to selectedMessageCount & " message is selected."else if selectedMessageCount < 2 thenset selectedMessageCountPhrase to "No messages are selected."if selectedMessageCount is 0 thenset selectedMessageCount to count of selectedMessagestell application "Mail" to set selectedMessages to the selectionset gotSelectedMessages to falsemy LogEntry("Getting selected messages from Mail...")if pLogging and pShowLogInTerminal then ViewLog()my DisplayAbout()my LogEntry("Archive folder: " & POSIX path of archiveFolder)my LogEntry("Base folder: " & POSIX path of baseFolder)my LogEntry("Starting up...")set archiveFolder to my CreateFolder(baseFolder, pArchiveFoldername)set baseFolder to my CreateFolder(desktopFolder, pBaseFoldername)set archiveFolder to (baseFolder & pArchiveFoldername & ":" as text) -- have to add : path delimiter manually to textual pathset logFolder to baseFolderset baseFolder to (desktopFolder & pBaseFoldername & ":" as text) -- have to add : path delimiter manually to textual pathset desktopFolder to the path to the desktop from the user domain as text -- path to alias already has ending : path delimiterset duplicatesAreShown to falseset automaticCheckingDisabled to falseset archivedMessagesCount to 0set removedMessagesCount to 0set duplicateMessagesCount to 0set removedMessages to {}set archivedMessages to {}set encounteredMessages to {}set selectedMessages to {}set enabledAccounts to {}global duplicatesAreShownglobal duplicatesWereShownglobal automaticCheckingDisabledglobal archivedMessagesCount -- archived message counterglobal removedMessagesCount -- removed message counterglobal duplicateMessagesCount -- duplicate message counterglobal removedMessages -- a list of removed message IDsglobal archivedMessages -- a list of archived messagesglobal encounteredMessages -- a list of encountered messagesglobal selectedMessages -- a list of selected messages in Mailglobal enabledAccounts -- list of all enabled Mail accounts whose "include when automatically checking for new messages" property is enabledglobal archiveFolder -- computed at run time with base folder path and pArchiveFoldernameglobal logFolder -- computed at run time with base folder pathglobal baseFolder -- computed at runtime with desktop path and pBaseFoldernameglobal archiveDuplicates -- archive duplicate messages? specified at runtime by user (values: true, false)global removeDuplicates -- remove duplicate messages? specified at runtime by user (values: true, false, or "ask")property pArchiveFoldername : "Archived Duplicates"property pLogFileName : (pScriptname & ".log" as text)property pBaseFoldername : pScriptnameproperty pScriptname : "Remove Duplicate Messages"property pDialogTimeout : 30 -- number of seconds to give up on interactive dialogs after no response from userproperty pAlertTimeout : 15 -- number of seconds to give up on alerts after no response from userproperty pShowLogInTerminal : true -- show log in terminal window?property pLogging : true -- generate a log file?property pDebug : falsewrite text "$CD_CMD"tell lset l to (launch session "Default Session")set c to (make new terminal)get cset c to (current terminal)end make_group_logend log_errorlog_ref's log_error(the_text)on log_error(the_text)log_ref's log_message(the_text)log_ref's log_important(the_text)repeat with log_ref in log_objectsproperty class : "group log"script GroupLogon make_group_log(log_objects)rotate this_file to angle 90if image_width > image_height thenset image_height to the height of this_itemset image_width to the width of this_itemtell current session of window 1 to write text "cd \"" & (POSIX path of (this_folder as string)) & "\";ls -lh"set this_folder to the sel as aliasif (theType as text) = "«class cfol»" thentell application "System Events" to set theType to (get class of item (sel as text))if not sel = {} thenset sel to (get selection)set theURL to findAndReplaceInText(theURL, "x-apple-reminder://", "x-apple-reminderkit://REMCDReminder/") of meset theURL to the id of theReminder as textset theReminder to the first reminder whose name starts with lookupKey --is theReminderNameset lookupKey to characters 1 through 5 of theReminderName as stringset theReminderName to value of text field 1 of uiElementget properties of uiElementif isFocused thenif not (error_number is equal to -1708 or error_number is equal to -1719) thenset isFocused to value of attribute "AXFocused" of text field 1 of uiElementget properties of text field 1 of uiElementget UI elements of uiElement -- button 1, text field 1set uiElement to UI element 1 of theRowrepeat with theRow in rows of outline 1 of scroll area 1 of UI element 3 of splitter group 1 of theWindowset isFocused to falseset theWindow to 1st window of remindersset reminders to application process "Reminders"to findAndReplaceInText(theText, theSearchString, theReplacementString)end bonjourLookuptell bonjourLookup to return lookup()error "trim: " & eMsg number eNumlog "trim: " & eMsg & " (" & (eNum as text) & ")"return text (start_WhiteSpaceEnd + 1) thru (end_WhiteSpaceStart - 1) of aTextelse if start_WhiteSpaceEnd is not false and end_WhiteSpaceStart is not false thenreturn text 1 thru (end_WhiteSpaceStart - 1) of aTextelse if start_WhiteSpaceEnd is false and end_WhiteSpaceStart is not false thenreturn text (start_WhiteSpaceEnd + 1) thru -1 of aTextelse if start_WhiteSpaceEnd is not false and end_WhiteSpaceStart is false thenif start_WhiteSpaceEnd is false and end_WhiteSpaceStart is false thenset end_WhiteSpaceStart to iif start_WhiteSpaceEnd is not false and i ≤ (start_WhiteSpaceEnd + 1) then exit repeatset i to count of characters in aTextset end_WhiteSpaceStart to falseset start_WhiteSpaceEnd to iif (ASCII number (character i of aText)) > 32 and (ASCII number (character i of aText)) is not 202 thenrepeat with i from 1 to count of characters in aTextset start_WhiteSpaceEnd to falseif length of aText is 0 then return ""if class of aText is not text then error "Wrong type."on trim(aText)end runLookupScripton error _eMsg number _eNumreturn lookupResultset lookupResult to do shell script shellScriptset shellScript to joinList(shellScript, ASCII character 10)set end of shellScript to "kill -HUP $mDNSpid"set end of shellScript to "sleep " & (scanTime as text)set end of shellScript to "mDNSpid=$!"set end of shellScript to "/usr/bin/dns-sd -L " & quoted form of computerName & " _" & serviceType & "._tcp local &"set shellScript to {"#!/bin/bash"}on runLookupScript()end addressAndPortFromLookupResultreturn {theAddress, thePort}if character -1 of theAddress is "." then set theAddress to text 1 thru -2 of theAddressset thePort to trim(thePort)set theAddress to trim(theAddress)set thePort to text item 1 of thePortset theAddress to text item 1 of theAddressset thePort to text item 2 of theAddressset theAddress to text item 2 of lookupResultset text item delimiters to "can be reached at"if lookupResult does not contain "can be reached at" then return {false, false}on addressAndPortFromLookupResult()return addressAndPortFromLookupResult()set lookupResult to runLookupScript()on lookup()property lookupResult : ""property scanTime : aScanTimeproperty computerName : aNameproperty serviceType : aServiceTypescript bonjourLookupon bonjourLookup(aServiceType, aName, aScanTime)log bonjourLookup("ssh", "Mac002", 1.0)log bonjourLookup("afpovertcp", "Mac001", 1.0)click button 1 of group 1 of group 1 of toolbar 1repeat until exists toolbar 1tell window windowNametell tab group 1 of group 1 of window windowNamerepeat until exists group 1 of window windowNametell tab group 1 of window windowNamerepeat until exists tab group 1 of window windowNamewith timeout of MAX_TIMEOUT secondsset MAX_TIMEOUT to 5set windowName to "ASUS PB278 (1)"reveal anchor "displaysDisplayTab" of current paneif SE_Logging then set end of setting_list to {SettingID:21, SettingName:"Maximum Level in Progress Bar", SettingHelp:helpmaxProgressLevel, SettingValue:(a reference to maxProgressLevel), UserSet:true, SettingClass:"Integer", SettingLimited:"Min_Max", SettingLimit_L:{1, 10}}set end of setting_list to {SettingID:17, SettingName:"Enable Results in Dialog", SettingHelp:"", SettingValue:(a reference to enableResultsByDialog), UserSet:true, SettingClass:"Boolean"}set end of setting_list to {SettingID:15, SettingName:"Maximum Search Level", SettingHelp:helpmaxSearchlevel, SettingValue:(a reference to maxSearchlevel), UserSet:true, SettingClass:"Integer", SettingLimited:"Min", SettingLimit_L:{2}}set end of setting_list to {SettingID:14, SettingName:"Highest Debug Level in Result File", SettingHelp:"", SettingValue:(a reference to ResultsFileMaxDebug), UserSet:true, SettingClass:"Integer", SettingLimited:"Min_Max", SettingLimit_L:{1, 6}}set end of setting_list to {SettingID:13, SettingName:"Debug Level", SettingHelp:helpdebugLogLevel, SettingValue:(a reference to debugLogLevel), UserSet:true, SettingClass:"Integer", SettingLimited:"Min_Max", SettingLimit_L:{0, 6}}set end of setting_list to {SettingID:12, SettingName:"Do Not Search below Projects", SettingHelp:helpStopSearchAtProject, SettingValue:(a reference to StopSearchAtProject), UserSet:true, SettingClass:"Boolean"}set end of setting_list to {SettingID:11, SettingName:"Collections not searched", SettingHelp:"", SettingValue:(a reference to ExcludedSubCollectionNames), UserSet:true, SettingClass:"List_Text", SettingLimited:"List&Free", SettingLimit_L:nameUserCollections}set end of setting_list to {SettingID:9, SettingName:"Search COP Trash", SettingHelp:helpSearchTrash, SettingValue:(a reference to SearchTrash), UserSet:true, SettingClass:"Boolean"}set end of setting_list to {SettingID:8, SettingName:"Search All Images", SettingValue:false, UserSet:false}set end of setting_list to {SettingID:7, SettingName:"Search Recent Captures", SettingValue:SearchRecentCaptures, UserSet:false}set end of setting_list to {SettingID:5, SettingName:"Search Referenced Files", SettingHelp:SearchDiskFileSystem, SettingValue:(a reference to SearchDiskFileSystem), UserSet:true, SettingClass:"Boolean"}set end of setting_list to {SettingID:4, SettingName:"Search Managed Files", SettingHelp:"", SettingValue:false, UserSet:false}set end of setting_list to {SettingID:3, SettingName:"Collection", SettingValue:(kindSelectedCollection_s & " " & nameSelectedCollection & " with " & countSelectedVariants & " selected variants"), UserSet:false}set end of setting_list to {SettingID:2, SettingName:"Document", SettingValue:(COPDocKind_s & " " & COPDocName), UserSet:false}set end of setting_list to {SettingID:1, SettingName:"Parent", SettingValue:parent_name, UserSet:false}set nameUserCollections to nameUserCollections & (get name of every collection)if selectedCollectionIsUser then tell application "Capture One 11" to tell selectedCollectionRef to ¬set nameUserCollections to {nameSelectedCollection} & (get items bottomUserCollectionIndex thru topUserCollectionIndex of namesTopCollections)set helpStopSearchAtProject to "do not search Albums within a Project"set helpSearchTrash to "search CaptureOne Trash"set helpSearchDiskFileSystem to "search the OSX filesystem"set helpmaxProgressLevel to "lowest subcollection level reported in the progess bar"set end of basic_setting_list to {SettingName:(get kindSelectedCollection_s & " \"" & nameSelectedCollection & "\" with " & countSelectedVariants & " selected variants")}set end of basic_setting_list to {SettingName:(get copVersion & " in " & COPDocKind_s & " \"" & COPDocName & "\"")}global SE_Logging, SE_Parent, enableResultsFile, enableResultsByDialog, enableResultsByClipboard, enableNotifications, ResultMethod, Result_DocNameglobal SearchDiskFileSystem, SearchRecentImports, SearchRecentCaptures, SearchTrash, ExcludedSubCollectionNames, StopSearchAtProject, maxSearchlevelglobal parent_name, Script_Title, enableFastGUI, debugLogLevel, ResultsFileMaxDebug, maxProgressLevel, countSelectedVariantsset selectedVariantsIDList to {}set selectedVariantsNameList to {}set selectedVariantsList to {}global selectedVariantsList, selectedVariantsNameList, selectedVariantsIDList, enableNotificationsreturn found_pathsset found_paths to found_paths & (thisCollName & ">>" & item p_counter of resultPaths)repeat with p_counter from 1 to countResultPathsif countResultPaths > 0 thenloq_Results2(3, false, ("Result of search in " & searchCollName & " (" & searchCollKind_s & ") is: " & resultPaths))set countResultPaths to count of resultPathsset resultPaths to my search_collection(searchColl, nextSearchLevel, searchCollName, searchCollKind_s) -- the searchloq_Results2(4, false, ("Starting search in " & searchCollName & " (" & searchCollKind_s & ") "))loq_Results2(4, false, ("Verified sub-Collection " & c_Counter & " of " & thisCollKind & " " & thisCollName))loq_Results2(3, false, ("Top Level Collection number:" & CollNum & " replaces Sub collection " & c_Counter & " of " & thisCollKind & " " & thisCollName))set searchColl to selectedCollectionReferror "Unexpected collection index when checking collection integrity: " & CollNumloqqed_Error_Halt3(false, "Unexpected collection index when checking collection integrity: " & CollNum)loq_Results2(4, false, ("*****" & CO11_errtxt & "; number " & CO11_errnbr))if selectedCollectionIndex ≠ CollNum thenif CollNum ≠ c_Counter thenloqqed_Error_Halt3(true, "Unexpected error when checking collection integrity")loq_Results2(0, false, ("*****" & CO11_errtxt & "; number " & CO11_errnbr))set CollNum to (get last word of item 2 of splitstringtolist(CO11_errtxt, "of")) as integerif CO11_errnbr = -1728 thenloq_Results2(4, false, ("***Error Message " & CO11_errtxt & "; number " & CO11_errnbr & " Collection: " & c_Counter & " of " & thisCollKind & " " & thisCollName))on error CO11_errtxt number CO11_errnbr|| of {searchColl} -- generate an error to capture error text containing the collection referenceif (searchCollName = nameSelectedCollection) and (searchCollKind_s = kindSelectedCollection_s) thenif selectedCollectionIsUser thenset searchCollKind_s to convertKind(get item c_Counter of kindsSubcollsthisColl_p)set searchCollName to item c_Counter of namesSubcollsthisCollset searchColl to item c_Counter of listSubcollsthisCollrepeat with c_Counter from 1 to countSubcollsthisCollloq_Results2(5, false, ("Searching Collections in " & thisCollKind & " " & thisCollName & " at level " & searchLevel & " found " & countSubcollsthisColl & " collections"))(not (StopSearchAtProject and thisCollKind = "project")) thenif (nextSearchLevel ≤ maxSearchlevel) and ¬loq_Results2(debugLogLevel, false, ("In " & thisCollKind & " " & thisCollName & " at level " & searchLevel & " found " & countImages & " images ," & countVariants & " variants ," & countSubcollsthisColl & " collections"))set countVariants to count of every variantset countImages to count of every imageif debugLogLevel ≥ 5 thenif countSubcollsthisColl > 0 then set {namesSubcollsthisColl, kindsSubcollsthisColl_p} to {name, kind} of every collectiontell me to set countSubcollsthisColl to count of listSubcollsthisCollset listSubcollsthisColl to every collectiontell application "Capture One 11" to tell document COPDocName to tell thisCollectionif {"album", "smart album"} does not contain thisCollKind then -- albums and smart albums don't contain collectionsset kindsSubcollsthisColl_p to {}set namesSubcollsthisColl to {}set countSubcollsthisColl to 0loq_Results2(4, false, ("Found " & searchVariantIDhits & " hits in " & thisCollKind & " " & thisCollName))if enableNotifications or (debugLogLevel ≥ 2) then display notification searchedVariantName & " found in: " & thisCollKind & " '" & thisCollName & "'"set found_paths to found_paths & (thisCollName & "(" & thisCollKind & ")")if searchVariantIDhits > 0 thenset searchVariantIDhits to get count of (get every variant whose id is searchedVariantID)tell application "Capture One 11" to tell document COPDocName to tell thisCollection to ¬if SE_Logging and (searchLevel ≤ maxProgressLevel) then set progress additional description to thisCollKind & " " & thisCollNameif ExcludedSubCollectionNames contains thisCollName then return found_pathsset found_paths to {} -- initialise the listglobal selectedCollectionRef, selectedCollectionIndex, kindSelectedCollection_s, nameSelectedCollection, selectedCollectionAtTopEnd, selectedCollectionIsUserglobal debugLogLevel, SE_Logging, maxSearchlevel, searchedVariantID, searchedVariantName, COPDocName, StopSearchAtProject, ExcludedSubCollectionNames, maxProgressLevel, enableNotificationson search_collection(thisCollection, searchLevel, thisCollName, thisCollKind)loq_Results2(0, true, (return & "*** Done on " & date_string & " *** " & countProcessedVariants & " of " & countFoundVariants & " variants found" & return & return))loq_Results2(1, false, (return & "SetupTime: " & elapsedTime1s & "sec Process time: " & elapsedTime2s & "sec per Variant: " & searchTimePerVariantDisplay & "sec"))set searchTimePerVariant to get ((Mark3 - Mark2) / countSelectedVariants) -- update the property to provide a time estimate for the next runif countSelectedVariants > 0 thenset countProcessedVariants to countProcessedVariants + 1if enableNotifications then display notification searchedVariantName & " was not found"loq_Results2((return & searchedVariantName & " was not found"), false, 0)set countFoundVariants to countFoundVariants + 1loq_Results2(0, false, (return & searchedVariantName & " was found in:" & return & foundPaths))if isFound thenmy loqqed_Error_Halt3(true, "No Top Level Collections to Search")if enableNotifications then display notification "No Top Level Collections to Search"if not search_executed then -- there are no top level collections to search - don't keep searchingloq_Results2(3, false, ("Reject: " & topCollKind_s & " " & topCollName))set pathSeparator to return -- after the first path is added the separator become the newline character /rset foundPaths to foundPaths & pathSeparator & item p_counter of resultPathsrepeat with p_counter from 1 to count of resultPathsset isFound to trueif resultCount > 0 thenloq_Results2(3, false, ("Result of search in " & topCollName & " (" & topCollKind_s & ") is: " & resultPaths))set resultCount to count of resultPathsset resultPaths to my search_collection(thisTopCollection, nextSearchLevel, topCollName, topCollKind_s) -- The searchloq_Results2(3, false, ("Search: " & topCollKind_s & " " & topCollName))set search_executed to true(ExcludedTopCollectionKinds does not contain topCollKind_s) thenif (ExcludedTopCollectionNames does not contain topCollName) and ¬set topCollKind_s to convertKind(item c_Counter of kindsTopCollections_p)set topCollName to item c_Counter of namesTopCollectionsset thisTopCollection to item c_Counter of everyTopCollectionrepeat with c_Counter from 1 to max_search_coll_indexset searchLevel to 0set pathSeparator to ""set foundPaths to ""set isFound to falseloq_Results2(2, false, (return & "Searching for " & searchedVariantName))set progress description to "Searching for Variant " & searchedVariantNameset progress completed steps to v_Counterset searchedVariantID to item v_Counter of selectedVariantsIDListset searchedVariantName to item v_Counter of selectedVariantsNameListset thisVariant to item v_Counter of selectedVariantsListrepeat with v_Counter from 1 to countSelectedVariantsset progress description to "Searching for Variants ..."set progress total steps to countSelectedVariantsif SE_Logging thenset search_executed to falseset countProcessedVariants to 0set countFoundVariants to 0loq_Results2(4, false, (selectedVariantsNameList))set selectedVariantsList to (get selected variants)set selectedVariantsIDList to get id of variants whose selected is trueset selectedVariantsNameList to get name of variants whose selected is trueif SE_Logging then set progress description to "Setting up"display dialog "Are you sure you want to search for " & countSelectedVariants & " variants? " with icon cautionelse if (searchTimePerVariant = 0) and (countSelectedVariants > WarnMaxVariants) thendisplay dialog "Are you sure you want to search for " & countSelectedVariants & " variants? Estimated time: " & estimatedDuration & " seconds" with icon cautionif (estimatedDuration > WarnSearchTime) thenset estimatedDuration to countSelectedVariants * searchTimePerVariantset max_search_coll_index to countTopCollectionsset max_search_coll_index to countTopCollections - 1if selectedCollectionMirroredAtTopLast thenset max_search_coll_index to topUserCollectionIndexif not SearchDiskFileSystem thenif not SearchTrash then set ExcludedTopCollectionNames to ExcludedTopCollectionNames & "Trash"if not SearchRecentCaptures then set ExcludedTopCollectionNames to ExcludedTopCollectionNames & "Recent Captures"if not SearchRecentImports then set ExcludedTopCollectionNames to ExcludedTopCollectionNames & "Recent Imports"set ExcludedTopCollectionKinds to {"catalog folder"}set ExcludedTopCollectionKinds to {""}if SearchDiskFileSystem thenset ExcludedTopCollectionNames to {"In Catalog", "Catalog", "All Images"}my loqqed_Error_Halt3(true, "No images selected")display alert "No images selected - select one or more images"if countSelectedVariants = 0 thenloq_Results2(3, false, ("In this window " & countSelectedVariants & " Selected Variants"))tell application "Capture One 11" to set countSelectedVariants to get count of selected variantsvalidateCOPdoc3({"catalog", "session"})loq_Results2(0, false, ("Started from: " & parent_name & " Action: Find collections where variants are located"))set SearchRecentImports to false -- doesn't work in CO 11 (true/false)set StopSearchAtProject to false -- (true/false)set ExcludedSubCollectionNames to {} -- The collections in this list will not be searchedset SearchTrash to false -- untested probably safe (true/false)set SearchRecentCaptures to false -- (true/false)set SearchDiskFileSystem to false -- untested probably safe (true/false)set WarnSearchTime to 30 -- 1...n (seconds) If you make this large you will get no warning when the script may lock up CO for a long timeset WarnMaxVariants to 6 -- 1...n (number of variants) If you make this large you will get no warning when the script may lock up CO for a long timeproperty searchTimePerVariant : 0 -- The search time in seconds. The value from the previous run is usedset maxSearchlevel to 100 -- Reduce if you only want to search top level collections or if you start getting stack overflow messages Range 1....... Verified to 100set maxProgressLevel to 3 -- Levels shown in Script Editor's progress bar 1...6set ResultsFileMaxDebug to 3 -- 1...6set enableNotifications to false -- (true/false)set enableResultsByClipboard to true -- (true/false)set enableResultsFile to true -- Enables Results in Textedit file (true/false)set debugLogLevel to 0 -- 1...6 Set to 1 to allow changing other settings. Increasing Values result in increasing amounts of debug data that takes longer to reportdisplay dialog "An error has occured! [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopdisplay dialog "Finished with no apparent errors!" & return & "Output stored in /tmp/uid_match_results_for_" & myUniqname buttons {"Exit"} default button 1 with icon notedo shell script "sh -c " & quoted form of myCmd with administrator privilegesdisplay dialog "After you authenticate, this command may take a few minutes. Please be patient..." with icon cautionset myCmd to cmndA & "; " & cmndB & " > /tmp/uid_match_results_for_" & myUniqnameset cmndB to "/usr/bin/find / -xdev -user " & tmp_Uid & " -exec chown " & myUniqname & " {} \\; -print"set cmndA to "sudo /usr/bin/niutil -createprop . /users/" & myUniqname & " uid " & afsUIDdisplay dialog "This uid [" & afsUID & "] already exists locally!" buttons {"Exit"} default button 1 with icon stopdo shell script "nidump passwd . | cut -d: -f3 | grep " & afsUIDdisplay dialog "Not an integer! [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopif errnum = -128 thenset afsUID to the text returned of the result as integerdisplay dialog "Enter AFS UID: Current ID [" & tmp_Uid & "]" default answer "1000000" with icon notedisplay dialog "Error! Is OpenAFS installed? [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopelse if errnum = -128 thendisplay dialog "Error! User not discovered. [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopif errnum = 1 thendisplay dialog "remote uid: " & afsUID with icon noteset afsUID to do shell script "pts examine " & myUniqname & " -noauth | grep id | cut -d: -f3 | cut -d\\ -f2 | cut -d, -f1"do shell script "pts examine " & myUniqname & " -noauth"if button returned of the result = "afs tools" thendisplay dialog "Choose method of external uid discovery:" buttons {"afs tools", "by hand", "Cancel"} default button 2 with icon notedisplay dialog "Error! [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopset tmp_Uid to do shell script "id -u " & myUniqnamedisplay dialog "Error! No such user! [" & errnum & "]" buttons {"Exit"} default button 1 with icon stopset tmp_niDump to do shell script "/usr/bin/nidump passwd . | grep " & myUniqnameset myUniqname to the text returned of the resultdisplay dialog "Enter the username of local user to change: " default answer "uniqname" with icon noteelse if button returned of the result = "by hand" thenif myUniqname = false thenset myUniqname to choose from list pickListset pickList to text items of userListset userList to do shell script "nidump passwd . | cut -d: -f1"if button returned of the result = "from list" thendisplay dialog "Method of user name selection?" buttons {"from list", "by hand", "Cancel"} default button 1 with icon noteset currentUser to do shell script "whoami" as stringmy browserMinimized()end browserMinimizedif theWindow is minimized thenon browserMinimized()battery mode trueclick item 1 of btnsif count of btns > 0set btns to (every button whose description is equal to "Search")tell group 4 of toolbar 1 of window 1display notification theDescription with title scriptSuiteName subtitle theTitleon notify(theTitle, theDescription)end removeSuffixesset name of aTask to newNameset newName to text 1 thru -(1 + (length of missingNADelimiter)) of newNameelse if (newName ends with missingNADelimiter) thenif (newName is missingNADelimiter) thenset newName to text 1 thru -(1 + (length of missingNASuffix)) of newNameif (newName is missingNASuffix) thenset newName to name of aTaskset theTasks to every flattened task of theDocument whose name ends with missingNASuffixon removeSuffixes(theDocument)end accumulateMissingNAsTasksset accum to my accumulateMissingNAsTask(aTask, false, accum)repeat with aTask in theTaskson accumulateMissingNAsTasks(theTasks, accum)end accumulateMissingNAsTaskreturn my accumulateMissingNAsTasks(incompleteChildTasks, accum)set name to (name & missingNADelimiter & missingNASuffix)if (name does not end with missingNASuffix) thenset end of accum to nameif ((count incompleteChildTasks) is 0) thenset incompleteChildTasks to every task whose completed is falseif (completed or not isAProjectOrSubprojectTask) then return accumset isAProjectOrSubprojectTask to isProjectRoot or (count of (get tasks)) > 0tell theTaskon accumulateMissingNAsTask(theTask, isProjectRoot, accum)end accumulateMissingNAsProjectsreturn accumlog "skipped"set accum to my accumulateMissingNAsTask(theRootTask, true, accum)set theRootTask to root task of aProjectif (class of projectContainer is not folder or (class of projectContainer is folder and projectContainer is not hidden)) thenset projectContainer to container of aProjectlog "Checking project: " & (name of aProject)repeat with aProject in theProjectson accumulateMissingNAsProjects(theProjects, accum)end accumulateMissingNAsset accum to my accumulateMissingNAsProjects(theProjects, accum)set theProjects to every flattened project of theContainer whose status is active and singleton action holder is falseset theProjects to every flattened project of theContainer whose status is activeusing terms from application "OmniFocus"log theContaineron accumulateMissingNAs(theContainer, accum)set search term to "(missing next action)"display alert "The missing actions cannot be revealed without having the Search field in the toolbar." message "To add the Search field, control-click on the toolbar, choose “Customize Toolbar…”, and drag the Search field onto the toolbar. Re-run this script to reveal the missing actions." buttons {"OK"}if (currentSearchTerm is missing value) thenset currentSearchTerm to search termset selected task state filter identifier of content to "incomplete"set selected of every descendant tree of sidebar to noset selected sidebar tab to projects tabtell aWindowset aWindow to make new document window at before first document windowif (button returned of alertResult is "Reveal") thenlog "Expected user cancelled error but got " & errNumif (errNum ≠ -128) thenon error errNumset alertResult to display alert titleText message msg & "Mark the " & pluralizedItems & " as completed, or add actions as needed and re-run this script to remove the “" & missingNASuffix & "” suffix." buttons {"OK", "Reveal"} default button 2 cancel button 1set alertResult to {button returned:""}set msg to "These active projects or action groups do not have next actions:" & lackingListingDelim & lackingListing & returnset lackingListing to (lackingNextActions as text)set AppleScript's text item delimiters to lackingListingDelimset msg to "There are " & (count of lackingNextActions) & " active projects or action groups without next actions. " as textelse if ((count of lackingNextActions) > 10) thenset pluralizedItems to "item"set msg to "There is no next action for “" & item 1 of lackingNextActions & "“. "set titleText to "An active project or action group is missing a next action. You can reveal it if you want to correct this."if ((count of lackingNextActions) is 1) thenset pluralizedItems to "items"set titleText to "Some active projects or action groups are missing next actions. You can reveal them if you want to correct this."my notify("Congratulations!", msg)set msg to "Next actions are identified for all active projects and action groups."set msg to "Next actions are identified for all active projects, action groups, and single action lists."if shouldCheckSingleActionLists thenif (lackingNextActions is {}) thendisplay dialog "Error: " & errNum & return & errTextset will autosave to trueset lackingNextActions to my accumulateMissingNAs(it, {})my removeSuffixes(it)set will autosave to falseproperty scriptSuiteName : "Curt’s Scripts"property missingNADelimiter : " "property missingNASuffix : "(missing next action)"property lackingListingDelim : (return & " • ")property shouldCheckSingleActionLists : falseset dt to std's import("date-time")set logger to std's import("logger")'s new("redis")set REDIS_CLI to do shell script "plutil -extract \"Redis CLI\" raw ~/applescript-core/config-system.plist"assertMissingValue(sut's getValue("spot-array-one-time-set"), "missing value expected after timeout elapsed")assertMissingValue(sut's getValue("spot-array-string"), "missing value expected after timeout elapsed")assertMissingValue(sut's getValue("spot-array2"), "missing value expected after timeout elapsed")assertMissingValue(sut's getValue("spot-array"), "missing value expected after timeout elapsed")newScenario("Expiring List")assertMissingValue(sut's getValue("spot-string"), "missing value expected after timeout elapsed")newScenario("getValue with expiry")delay UT_REDIS_TIMEOUTlogger's infof("Delaying by {} to force timeout", UT_REDIS_TIMEOUT)assertTrue(sut's hasValue("spot-bool"), "Value found")assertFalse(sut's hasValue(missing value), "Missing value")assertEqual(1, sut's getInt("spot-bool"), "Update bool to integer")assertFalse(sut's getBool("spot-false"), "Verify False")assertTrue(sut's getBool("spot-true"), "Verify True")assertFalse(sut's getBool("spot-none"), "Missing Value is False")newMethod("getBool")assertEqual(0, sut's removeElement("spot-array-string", "Good Putin"), "Remove inexistent element")assertEqual(1, sut's removeElement("spot-array-string", "one"), "Successful removal")assertEqual(1, sut's removeElement("spot-array-string", "two"), "Successful removal")assertEqual(0, sut's removeElement("spot-array-string", missing value), "Missing value element")assertEqual(0, sut's removeElement(missing value, "two"), "Missing value list")assertEqual({"1", "2", "3"}, sut's getList("spot-array"), "Append Int")assertEqual({"3"}, sut's getList("spot-array2"), "First element")assertEqual("2", last item of arrayValue, "Get array element last")assertEqual("1", first item of arrayValue, "Get array element first")assertEqual("Multi word key", sut's getValue("spot text"), "Spaced Key")assertEqual(missing value, sut's getValue(missing value), "missing value key")sut's setValue("spot text", "Multi word key")sut's setValue("spot-true", true)sut's setValue("spot-false", false)sut's setValue("spot-array-one-time-set", {1, 2, 3})sut's deleteKey("spot-false")sut's deleteKey("spot-true")set sut to new(UT_REDIS_TIMEOUT)set UT_REDIS_TIMEOUT to 2end _splitByLine_split(csv, SEP, "string")set command to "echo " & theQuote & theString & theQuote & " | awk 'NF {$1=$1;print $0}' | paste -s -d" & SEP & " - | sed 's/" & SEP & "[[:space:]]*/" & SEP & "/g' | sed 's/[[:space:]]*" & SEP & "/" & SEP & "/g' | sed 's/^" & SEP & "//' | sed 's/" & SEP & SEP & "//g' | sed 's/" & SEP & "$//'" -- failed when using escaped/non escaped plus instead of asterisk.if theString contains SEP or theString contains "\"" then error "Sorry but you can't have " & SEP & " or double quote in the text :("return _split(theString, CR, "string") -- assuming this is shell command result, we have to split by CR.if theString contains (CR) thenon _splitByLine(theString as text)else if plistType is "string" thenelse if plistType is "bool" thenelse if plistType is "float" thenif plistType is "integer" thenon _split(theString, theDelimiter, plistType)set myHour to myHour - tzOffset -- Local Timezone adjustmentset tzOffset to do shell script "date +'%z' | cut -c 2,3"on _convertType(textValue, plistType)set expireListShellCommand to format {"{} EXPIRE {} {}", {REDIS_CLI, quotedPlistKey, timeoutSeconds}}do shell script appendCommandset appendCommand to format {"{} RPUSH {} {}", {REDIS_CLI, quotedPlistKey, nextElement}}if class of nextElement is text then set nextElement to quoted form of nextElementend getValueAsDatereturn dt's fromZuluDateText(plistValue)set plistValue to getValue(plistKey)on getValueAsDate(plistKey)return (do shell script removeShellCommand) is 1set removeShellCommand to format {"{} DEL {}", {REDIS_CLI, quotedPlistKey}}(do shell script deleteElementCommand) as integerset deleteElementCommand to format {"{} LREM {} 1 {}", {REDIS_CLI, quotedPlistKey, quotedValue}}if targetElement is not missing value then set quotedValue to _quoteValue(targetElement)set quotedValue to targetElementif targetElement is missing value then return 0if plistKey is missing value then return 0do shell script expireListShellCommandset expireListShellCommand to format {"{} EXPIRE {} {}", {REDIS_CLI, escapedAndQuotedPlistKey, timeoutSeconds}}if my timeoutSeconds is not 0 thenset appendShellCommand to format {"{} RPUSH {} {}", {REDIS_CLI, escapedAndQuotedPlistKey, quotedValue}}return (do shell script countShellCommand) as integer is greater than 0set countShellCommand to format {"{} LLEN {}", {REDIS_CLI, quotedPlistKey}}if dataType is equal to "list" thenif dataType is "none" then return falseset getTypeShellCommand to format {"{} TYPE {}", {REDIS_CLI, quotedPlistKey}}on hasValue(plistKey)set getValueShellCommand to format {"{} get {}", {REDIS_CLI, quotedPlistKey}}if dataType is "list" thenif dataType is "none" then return missing valueset getTypeShellCommand to format {"{} type {}", {REDIS_CLI, quotedPlistKey}}_splitByLine(csv)set getTsvCommand to format {"{} LRANGE {} 0 -1", {REDIS_CLI, quotedEspacedPlistKey}}return getString(plistKey) as realreturn getString(plistKey) as integerreturn getString(plistKey) is equal to "true"set getStringShellCommand to format {"{} GET {}", {REDIS_CLI, quotedPlistKey}}set setValueShellCommand to format {"{} SET {} {} {}", {REDIS_CLI, quotedPlistKey, shellValue, timeoutParam}}set timeoutParam to format {" EX {}", timeoutSeconds}if timeoutSeconds is greater than 0 thenset timeoutParam to ""property timeoutSeconds : pTimeoutSecondsscript RedisInstanceon new(pTimeoutSeconds)set appMenu to new("app-menu-items")set appKiller to new("app-killer")set sessionPlist to new("app-killer")set sessionPlist to new("session")log sut's getString("DB_NAME")set sut to new("config-bss")new("godly")log spotPList's hasValue(plistKey)log spotPList's hasValue("missing")log spotPList's getValue("missing")log spotPList's getValue(plistKey)spotPList's setValue(plistKey, 1)set plistKey to "spot1"set spotPList to new(plistName)logger's infof("Result: {}", sut's getValueAsDate(keyName))sut's setValue(keyName, current date)set keyName to "spot-zulu-date"set sut to new(2)Manual: Zulu Dateset thisCaseId to "redis-spotCheck"global REDIS_CLI, CRglobal std, dtdo shell script "defaults write com.apple.NetworkBrowser EnableODiskBrowsing -true false & killall Finder"else if discoRemoto = "Recuperar Disco Remoto" thendo shell script "defaults write com.apple.NetworkBrowser EnableODiskBrowsing -bool false & killall Finder"if discoRemoto = "Remover Disco Remoto" thenset discoRemoto to (choose from list listaOpciones default items {} with prompt "Selecciona una acción") as stringset listaOpciones to {"Remover Disco Remoto", "Recuperar disco remoto"}end fmGUI_ManageDataSources_Opentell application "htcLib" to fmGUI_ManageDataSources_Open(prefs)on fmGUI_ManageDataSources_Open(prefs)end fmGUI_ManageDataSources_EnsureExistserror "Couldn't fmGUI_ManageDataSources_EnsureExists for '" & dataSourceName & "' - " & errMsg number errNumreturn "Existed: " & dataSourceNameelse -- already existed:return "Added: " & dataSourceNamewindowWaitUntil_FrontIS({windowName:"Manage External Data Sources"})set okButton to first button of window 1 whose name starts with "OK"set value of text area 1 of scroll area 1 of group 1 of window 1 to dataSourcePathset value of text field 1 of window 1 to dataSourceNamewindowWaitUntil_FrontIS({windowName:"Edit Data Source"})clickObjectByCoords(newButton)set newButton to first button of window 1 whose name starts with "New"if not dataSourceExists thenset dataSourceExists to exists (first row of (table 1 of scroll area 1 of window 1) whose name of static text 1 is dataSourceName)fmGUI_ManageDataSources_Open({})if dataSourcePath is null then set dataSourcePath to "file:" & dataSourceNameset dataSourcePath to dataSourcePath of prefsset dataSourceName to dataSourceName of prefsset defaultPrefs to {dataSourceName:null, dataSourcePath:null}on fmGUI_ManageDataSources_EnsureExists(prefs)fmGUI_ManageDataSources_EnsureExists({dataSourceName:"a01_PERSON"})get the_datedisplay dialog "Re-enter date:" buttons {"OK"} default button 1 with icon cautionif the_date comes after (current date) thenset the_date to date user_dateset user_date to text returned of resultdisplay dialog "Enter date:" default answer "" repeatclick text field 1 of group 2 of group 1 of group 1 of group 1 of group 2 of group 1tell group 1 of group 1 of group 1 of group 1 of group 1 of group 1tell process "Podcasts"export front document to file targetFileHFSPath as Microsoft Wordset the targetFileHFSPath to (defaultDestination as string) & exportFileExtensionset the defaultDestination to choose file name with prompt "Save the document as:"property exportFileExtension : ".doc" --docxset my IS_SPOT to scriptName is equal to "calendar-event.applescript"set scriptName to get name of (path to me)set sb to std's import("string-builder")set logger to std's import("logger")'s new("calendar-event")end extractMeetingPasswordon extractMeetingPassword(meetingStaticText)end extractMeetingIdon extractMeetingId(meetingStaticText)CalendarEventInstanceend try -- when endTime is not availableset its endTime to date (my referenceDate & " " & endTimePart)set its endTime to date endTimePartset endTimePart to regex's firstMatchInString("(?<=ends at )\\d{1,2}:\\d{2}(?::\\d{2})? [AP]M", meetingDescription)end try -- when startTime is not availableset its startTime to date (my referenceDate & " " & startTimePart)set its startTime to date startTimePartif my referenceDate is missing value thenset startTimePart to regex's firstMatchInString("(?<=at )\\d{1,2}:\\d{2}(?::\\d{2})? [AP]M", meetingDescription)set its actioned to meetingDescription does not end with "Needs action"set its meetingPassword to my extractMeetingPassword(meetingStaticText)set its meetingId to my extractMeetingId(meetingStaticText)set its organizer to regex's firstMatchInString(".*(?= \\(organizer\\))", eventOrganizer)set its title to regex's firstMatchInString("^.*?(?=\\. Starts on | at)", meetingDescription)tell CalendarEventInstanceset CalendarEventInstance's passcode to regex's firstMatchInString("(?<=Passcode: )\\d+", CalendarEventInstance's body)if CalendarEventInstance's body is not missing value thenset CalendarEventInstance's body to value of first static text of group 1 of splitter group 1 of window "Calendar" whose value of attribute "AXPlaceholderValue" is "Add Notes"set eventOrganizer to get value of text field 1 of nextStaticTextrepeat with nextStaticText in static texts of attendeesButtonif attendeesButton is not missing value thenset attendeesButton to first button of pop over 1 of window "Calendar" whose description is "Edit Attendees"if attendeesButton is missing value thenset attendeesButton to first button of group 1 of splitter group 1 of window "Calendar" whose description is "Edit Attendees"set attendeesButton to missing valueset eventOrganizer to missing valueend toJsonStringjsonBuilder's toString()jsonBuilder's append("}")jsonBuilder's append("\"" & nextValue & "\"")jsonBuilder's append(nextValue)set jsonBuilder to sb's new("{") repeat with i from 1 to count of attributeNames if i is not 1 then jsonBuilder's append(", ") set nextName to item i of attributeNames set nextValue to item i of attributeValues set end of nameValueList to nextName set end of nameValueList to nextValue jsonBuilder's append("\"" & nextName & "\": ") if nextValue is missing value then jsonBuilder's append("null") else if {integer, real, boolean} contains class of nextValue thenset nameValueList to {}set attributeValues to {my title, my organizer, my startTime, my endTime, my meetingId, my meetingPassword, my passcode, my active, my actioned}set attributeNames to listUtil's _split("title, organizer, startTime, endTime, meetingId, meetingPassword, passcode, active, actioned", ", ")on toJsonString()", {my title, my organizer, my startTime, my endTime, my meetingId, my meetingPassword, my passcode})Passcode: {}Meeting Password: {}Meeting ID: {}End: {}Start: {}Organizer: {}textUtil's formatNext("Title: {}end isOnlinemeetingId is not missing valueon isOnline()property actioned : trueproperty active : falseproperty eventUi : meetingStaticTextproperty organizer : missing valueproperty endTime : missing valueproperty passcode : missing valueproperty meetingPassword : missing valueproperty meetingId : missing valuescript CalendarEventInstanceset meetingDescription to description of meetingStaticTextset meetingDescription to |description| of meetingStaticTextif my IS_SPOT thentell application "System Events" to tell process "Calendar"on new(meetingStaticText)script CalendarEventLibrarylogger's infof("JSON String: {}", sut's toJsonString())set sut to calendarEventLib's new({|description|:"Spot Meeting. Starts on Apr 9"})set calendarEventLib to new()Manual: Find a suitable calendar event for testing.To JSON Stringset IS_SPOT to trueset thisCaseId to "calendar-event-spotCheck"property IS_SPOT : false -- global initially, breaks when ran as dependency.property referenceDate : missing valueglobal std, regex, textUtil, listUtil, sbclose access fpwrite (locationsList as text) to fp as textset fp to open for access locationsFile with write permissionset locationsFile to POSIX file "/Users/companjenba/locations.txt"log "no location"log this_locationcopy this_location to the end of locationsListRefset this_location to location of this_eventif (exists location of this_event) thenrepeat with this_event in every calendar event of this_calendarset locationsListRef to a reference to locationsListset this_calendar to default calendar of this_accountset this_inbox to inboxset this_account to default accountset locationsList to {}click menu item "Close Tab" of file_menuclick menu item "New Tab" of file_menurepeat 250 timesset file_menu to menu "File" of menu bar 1else if the ret is "Cancel" thenopen location "http://www.jorudan.co.jp/"else if the ret is "Jorudan" thenopen location "https://www.ibm.com/"if the ret is "IBM" thencopy the result as list to {ret}display dialog "ページを選択" buttons {"IBM", "Jorudan", "Cancel"} default button 3 with icon noteset addr to "https://docs.google.com/presentation/u/0/"set theString to current application's NSString's stringWithString:sourceTexttell application "Finder" to open scriptPathif scriptPath ≠ "" thenset scriptPath to scriptPath as POSIX fileset scriptPath to my SearchandReplace(_xml's |path|, "~", (POSIX path of (path to home folder)) as text)if _xml's |path| starts with "~" thentell newScriptset newScript to make new document with properties {source text:(_xml's |Text|), debugger enabled:true}if _xml's UseText thenset _xml to value of (make property list item with properties {text:_xml})set _xml to a's xmlset a to item 1 of selif (count of items of sel) > 1 then error "Multiple actions selected, please select one"if class of item 1 of sel ≠ action then error "Action is not selected, please select a script action"set end of mysteryEmails to sourceEmailif sourceEmail is not in combinedReferenceSheets thenrepeat with sourceEmail in sourceEmailsset combinedReferenceSheets to combinedReferenceSheets & referenceSheetrepeat with referenceSheet in referenceSheetsset referenceSheets's item sheetNumber to value of cellsset the value of row emailRowNumber's last cell to truetell sheet documentSheetNumberif (sourceEmail as string) is equal to (email as string) thenset emailRowNumber to emailRowNumber + 1repeat with email in columnNumberset emailRowNumber to 0repeat with columnNumber in sheetNumberset documentSheetNumber to documentSheetNumber + 1repeat with sheetNumber in listOfAllEmailsset documentSheetNumber to 0repeat with sourceEmail in listOfSourceEmailsset the format of the cells to checkbox # Set the format of the rightmost column to checkboxrepeat with rowCounter from 2 to count of columnset the value of row 1's last cell to columnName # Set the title of the new column headersadd column after the last column # Add Column to the right side of sheets 1 to 4set listOfAllEmails's item sheetNumber's item (columnNumber - 6) to the value of the cellstell column columnNumberrepeat with columnNumber from 7 to 9 # Get all the emails from the target Numbers documenttell sheet sheetNumberrepeat with sheetNumber from 1 to 4set the end of listOfSourceEmails to the value of the cell rowNumberrepeat with rowNumber from 2 to the count of the rowstell column columnLetterset columnLetter to input's text returnedset input to display dialog "What is the column letter of the email address or Student ID#?" default answer ""set combinedReferenceSheets to {}set mysteryEmails to {}set listOfSourceEmails to {}set listOfAllEmails to {{{}, {}, {}}, {{}, {}, {}}, {{}, {}, {}}, {{}, {}, {}}}end selected_indexreturn item 1 of tmp_listset tmp_list to every text item of selected_itemon selected_index(selected_item)end selected_item_indexesreturn selected_indexesset the end of selected_indexes to selected_index(selected_item) of merepeat with selected_item in selected_itemsset selected_indexes to {}if selected_items = false then return 0set selected_items to choose from list target_list with prompt dialog_message with multiple selections allowedset dialog_message to "リストを作る項目を選択してください (Cmd + クリック で複数選択)"on selected_item_indexes(target_list)end replace_html_entityreturn target_textset target_text to replace_string_action(target_text, "\"", """)set target_text to replace_string_action(target_text, ">", ">")set target_text to replace_string_action(target_text, "<", "<")set target_text to replace_string_action(target_text, "&", "&")on replace_html_entity(target_text)end replace_string_actionreturn the target_textset AppleScript's text item delimiters to orig_delimiterset target_text to tmp_list as stringset AppleScript's text item delimiters to after_stringset tmp_list to every text item of target_textset AppleScript's text item delimiters to before_stringset orig_delimiter to AppleScript's text item delimiterson replace_string_action(target_text, before_string, after_string)end process_bundle_idreturn a_processset a_process to contents of first item of a_processif a_process = {} thenset a_process to every process whose bundle identifier is equal to bundle_idon process_bundle_id(bundle_id)end make_hateb_urlreturn hatenaBURLset hatenaBURL to ""on make_hateb_url(target_url)end make_tweetbuzz_urlreturn tweetBuzzURLset tweetBuzzURL to ""on make_tweetbuzz_url(target_url)end insert_marseditset selected text in document 1 to insert_text as textset the end of insert_text to {""}"
  • " & encoded_title & "" & make_tweetbuzz_url(site_url) of me & make_hateb_url(site_url) of me & "
  • " & returnset the end of insert_text to ¬set encoded_title to replace_html_entity(site_title) of meset site_url to url_key of site_infoset site_title to title_key of site_infoset site_info to (item select_index) of site_infosrepeat with select_index in select_indexesset insert_text to {"
    ", "") & "
    " & cond(checkbox, "
    " & cinstruct & "
     
    " & cright & "
    " & cleft & "
    return "
    on pageHead(cleft, cright, cinstruct, checkbox)end dateCellreturn "
    set {year:yy, month:mm, day:dd, hours:hh, minutes:r, seconds:s} to (dt - offsetGMT) -- for javascript to convertset {year:y, month:m, day:d} to dt -- for short, local date that will visible in celllocal y, m, d, yy, mm, dd, hh, s, ron dateCell(dt)end fmtTagreturn "" & repl(textHT(tn), " ", " ") & " "on fmtTag(tn)end item_positionif (item i of theList) is (item 1 of myitem) then return irepeat with i from 1 to the count of theListif myitem = false then return 0on item_position(myitem, theList)return timeScript's getFineTime()end getFineTimereturn current application's CFAbsoluteTimeGetCurrent()script timeScript -- encase the asobjc call in a script objecton getFineTime()return sortScript's sortListOfStrings(sourceList)end sortListOfStringsreturn (sortedItems as list)set the sortedItems to CocoaArray's sortedArrayUsingSelector:"localizedStandardCompare:"set the CocoaArray to current application's NSArray's arrayWithArray:sourceListscript sortScript -- encase the asobjc call in a script objecton sortListOfStrings(sourceList)end getBooksreturn sortListOfStrings(listBooks) -- sort the list and return itcopy (name of iBook) to end of listBooks -- add notebook name to listrepeat with iBook in every notebook -- for every notebook ...set listBooks to {} -- init the list of book nameslocal listBookson getBooks()end managePlistset value of property list item plExportDate to ExportDateif opt = 3 then -- Option 3: Update only the ExportDate propertyif logProgress then log "Successfully set all properties"set value of property list item plPropDate to current dateset value of property list item plBooksSelected to BooksSelectedset value of property list item plTimeoutMinutes to TimeoutMinutesset value of property list item plExportAsENEX to ExportAsENEXset value of property list item plExportAsHTML to ExportAsHTMLset value of property list item plSearchString to SearchStringset value of property list item plAllNotebooks to AllNotebooksset value of property list item plFolderENEX to FolderENEXset value of property list item plFolderHTML to FolderHTMLexit repeat -- if integer was valid, break out of the Repeat loopif TimeoutMinutes < 1 thenif msgPart = "" thenif logProgress then log "TimeoutMinutes: " & TimeoutMinutesset TimeoutMinutes to (text returned of resp) -- leave bad timeout value in placeif logProgress then log "Convert to integer failed."Timeout value must be a positive integer." -- set error messageset msgPart to "on error -- not a valid integerif logProgress then log "Convert to integer worked: " & TimeoutMinutesset TimeoutMinutes to (text returned of resp) as integerif logProgress then log "About to convert to integer."try -- see if text entered is a valid integerset resp to display dialog ("Enter export timeout in minutes. " & msgPart) default answer (TimeoutMinutes as text) with title "Specify Timeout" with icon noterepeat -- loop to prompt for Timeout value and validate itset msgPart to "" -- clear error message fragmentset SearchString to (text returned of resp) as text -- save user inputset resp to display dialog "Enter Evernote search terms to restrict notes that will be exported. Do not use 'notebook:', 'any:', or 'updated:' terms. Leave blank to export all notes in each notebook." default answer SearchString with title "Optional search terms" with icon noteif logProgress then log "BooksSelected: " & BooksSelectedif BooksSelected = false then return myResp -- if user cancelled, return to caller w 'false'set BooksSelected to choose from list bookNames with title "Choose Notebooks to export" with prompt "Use command key (⌘) to select several or all" default items BooksSelected with multiple selections allowedif logProgress then log "Count of Notebooks in Evernote: " & (count of bookNames)set bookNames to getBooks() -- get sorted notebook namesif not AllNotebooks then -- if only selected notebooksif logProgress then log "AllNotebooks: " & AllNotebooksset AllNotebooks to ((item 1 of buts) = (button returned of chc))set chc to display dialog "Export all notebooks or only selected ones?" buttons buts default button cond(AllNotebooks, 1, 2) cancel button 3 with icon noteset buts to {"All notebooks", "Only selected notebooks", "Cancel"}activate frontProcess -- switch back from Finder to scriptif logProgress then log "FolderENEX: " & FolderENEXtell application "Finder" to set FolderENEX to (choose folder with prompt "Select or create folder for ENEX exports" default location alias FolderENEX) as text -- prompt for folderif checkPropVol(FolderENEX, "ENEX") then set FolderENEX to path to documents folder as textif ExportAsENEX then -- if exporting as ENEXif logProgress then log "FolderHTML: " & FolderHTMLtell application "Finder" to set FolderHTML to (choose folder with prompt "Select or create folder for HTML exports" default location alias FolderHTML) as text -- prompt for folderif checkPropVol(FolderHTML, "HTML") then set FolderHTML to path to documents folder as textif ExportAsHTML then -- If exporting as HTMLif logProgress then log "ExportAsHTML: " & ExportAsHTML & " ExportAsENEX: " & ExportAsENEXset ExportAsENEX to item exopt of {false, true, true} -- Set ENEX export flagset ExportAsHTML to item exopt of {true, false, true} -- Set HTML export flagif exopt = 0 then return myResp -- quit if user cancelledif logProgress then log "Export option: " & exoptset exopt to item_position(choose from list plExportTypeDesc with title "Choose export types" with prompt "Which format(s) should be exported?" default items {item exopt of plExportTypeDesc}, plExportTypeDesc)if (not (ExportAsHTML and ExportAsENEX)) then set exopt to cond(not ExportAsHTML, 2, 1) -- if not HTML, then ENEX onlyset exopt to 3 -- assume both formatstell application "System Events" to set frontProcess to the name of every process whose frontmost is trueset myResp to false -- assume update has failedif opt = 2 then -- Option 2: Prompt for updates to Property List itemsreturn foundPList -- Tell caller if PList alreay existedset TimeoutMinutes to value of property list item plTimeoutMinutesset ExportDate to value of property list item plExportDateset BooksSelected to value of property list item plBooksSelected as listset ExportAsENEX to value of property list item plExportAsENEXset ExportAsHTML to value of property list item plExportAsHTMLset SearchString to value of property list item plSearchStringset AllNotebooks to value of property list item plAllNotebooksset FolderENEX to value of property list item plFolderENEXset FolderHTML to value of property list item plFolderHTMLtell property list file myPListFullPathmake new property list item at end with properties {kind:number, name:plTimeoutMinutes, value:TimeoutMinutes}make new property list item at end with properties {kind:date, name:plExportDate, value:ExportDate}make new property list item at end with properties {kind:date, name:plPropDate, value:(current date)}make new property list item at end with properties {kind:list, name:plBooksSelected, value:BooksSelected}make new property list item at end with properties {kind:boolean, name:plExportAsENEX, value:ExportAsENEX}make new property list item at end with properties {kind:boolean, name:plExportAsHTML, value:ExportAsHTML}make new property list item at end with properties {kind:string, name:plSearchString, value:SearchString}make new property list item at end with properties {kind:boolean, name:plAllNotebooks, value:AllNotebooks}make new property list item at end with properties {kind:string, name:plFolderENEX, value:FolderENEX}make new property list item at end with properties {kind:string, name:plFolderHTML, value:FolderHTML}set thePropertyListFile to make new property list file with properties {contents:theParentDictionary, name:myPListFullPath}if not foundPList then -- If it doesn't exist, create one with default valuestell application "Finder" to set foundPList to (exists myPListFullPath as POSIX file) -- Does PList exist?if opt = 1 then -- Option 1: create default PList if necessary and then load Plist values into Global variablesset plTimeoutMinutes to "TimeoutMinutes" -- export timeout in minutesset plExportDate to "ExportDate" -- date export last completedset plPropDate to "PropDate" -- date this Property List last updatedset plBooksSelected to "BooksSelected" -- names of notebooks to exportset plExportAsENEX to "ExportAsENEX" -- Export as ENEX?set plExportAsHTML to "ExportAsHTML" -- Export as HTML?set plSearchString to "SearchString" -- user's filter for notesset plAllNotebooks to "AllNotebooks" -- Export all notebooks, not just someset plFolderENEX to "FolderENEX" -- Folder for ENEX exportsset plFolderHTML to "FolderHTML" -- Folder for HTML exportslocal msgPart, resplocal thePropertyListFile, myResp, exopt, buts, chc, bookNameslocal plExportDate, plTimeoutMinutes, foundPList, theParentDictionarylocal plExportAsHTML, plExportAsENEX, plBooksSelected, plPropDatelocal plFolderHTML, plFolderENEX, plAllNotebooks, plSearchStringon managePlist(opt)end makeSizeOldset strSize to ((s / (1000 ^ 3)) as integer as text) & " GB"set strSize to ((s / (1000 ^ 2)) as integer as text) & " MB"set strSize to ((s / 1000) as integer as text) & " KB"set strSize to (s as integer as text) & " B  "on makeSizeOld(s)end makeSizereturn strSizeset strSize to (text 1 thru -2 of strSize) & "." & (text -1 thru -1 of strSize) & " GB"set strSize to ((s / (1000 ^ 3 / 10)) as integer as text)set strSize to (text 1 thru -2 of strSize) & "." & (text -1 thru -1 of strSize) & " MB"set strSize to ((s / (100000)) as integer as text)else if (s / (1000 ^ 2)) < 1000 thenset strSize to (text 1 thru -2 of strSize) & "." & (text -1 thru -1 of strSize) & " KB"set strSize to ((s / 100) as integer as text)else if (s / 1000) < 1000 thenset strSize to "0." & ((s / 100) as integer as text) & " KB"if s < 1000 then -- Build a formatted text showing total sizelocal strSizeon makeSize(s)end fmtSizereturn " on fmtSize(s)end writeIndexclose access file theAliaswrite theText to theOpenedFile as «class utf8»set eof of theOpenedFile to 0set theOpenedFile to open for access theAlias as «class furl» with write permissionset theAlias to thePath as POSIX file as «class furl»on writeIndex(thePath, theText)return dateScript's getDateSrch(x)end getDateSrchreturn d -- return date in our time zoneset d to d + theOffset -- adjust GMT time string to local timetell d to set {its year, its month, its day, its time} to {0 + (text 1 thru 4 of x), 0 + (text 5 thru 6 of x), 0 + (text 7 thru 8 of x), (hours * (0 + (text 10 thru 11 of x))) + (minutes * (0 + (text 12 thru 13 of x))) + (0 + (text 14 thru 15 of x))} -- convert date string to date objectset d to current date -- create a date variable 0.4.2set theOffset to tz's secondsFromGMTForDate:theDateset tz to current application's NSTimeZone's localTimeZone()set theDate to df's dateFromString:xdf's setDateFormat:"yyyyMMdd'T'HHmmssX" -- Pattern dateif x = "" then return initDate(2000, 1, 1) -- 0.4.2local df, theDate, tz, theOffset, dscript dateScripton getDateSrch(x)end initDatereturn mdtell md to set {its year, its month, its day, its time} to {yr, mo, dy, hours * 12}set md to current datelocal mdon initDate(yr, mo, dy) -- 0.4.2end getDateMetaset d to d + (hours * (text 22 thru 23 of x)) + (0 + (text 24 thru 25 of x)) * (cond((text 21 thru 21 of x) = "-", -1, 1)) + (time to GMT)tell d to set {its year, its month, its day, its time} to {0 + (text 1 thru 4 of x), 0 + (text 6 thru 7 of x), 0 + (text 9 thru 10 of x), (hours * (0 + (text 12 thru 13 of x))) + (minutes * (0 + (text 15 thru 16 of x))) + (0 + (text 18 thru 19 of x))} --if x = "" then return dset d to initDate(2000, 1, 1) -- 0.4.2local don getDateMeta(x)end tzonereturn lzer(offsetGMT div hours) & ":" & lzer(offsetGMT mod hours / minutes as integer)on tzone()end lzerreturn "-" & (text -1 thru -2 of ("000" & ((-numb) as text)))return (text -1 thru -2 of ("000" & (numb as text)))if numb ≥ 0 thenon lzer(numb)end fmtLongDatereturn (y as text) & "-" & lzer(m as number) & "-" & lzer(d as text) & " " & lzer(h as text) & ":" & lzer(r as text)set {year:y, month:m, day:d, hours:h, minutes:r} to inpDateon fmtLongDate(inpDate)end repllocal theTextItemson repl(theText, theSearchString, theReplacementString)end textHTreturn jset j to repl(j, ">", ">")set j to repl(j, "<", "<")set j to repl(j, "'", "'")set j to repl(j, "\"", """)set j to repl(inString, "&", "&") -- must be first to avoid double-encoding of ampersandslocal jon textHT(inString)return xmlScript's parseNote(xmlData)end parseNoteif (length of t) > 0 then set exporter of resp to (item 1 of t) -- copy EN Version if it's thereset t to ((theXMLDoc's nodesForXPath:"//meta[@name='exporter-version']/@content" |error|:(missing value))'s valueForKey:"stringValue") as listif (length of t) > 0 then set tags of resp to (item 1 of t) -- copy Tag Names if it's thereset t to ((theXMLDoc's nodesForXPath:"//meta[@name='keywords']/@content" |error|:(missing value))'s valueForKey:"stringValue") as listif (length of t) > 0 then set updated of resp to (item 1 of t) -- copy Modification Date if it's thereset t to ((theXMLDoc's nodesForXPath:"//meta[@name='updated']/@content" |error|:(missing value))'s valueForKey:"stringValue") as listif (length of t) > 0 then set author of resp to (item 1 of t) -- copy Author Name if it's thereset t to ((theXMLDoc's nodesForXPath:"//meta[@name='author']/@content" |error|:(missing value))'s valueForKey:"stringValue") as listif (length of t) > 0 then set created of resp to (item 1 of t) -- copy Creation Date if it's thereset t to ((theXMLDoc's nodesForXPath:"//meta[@name='created']/@content" |error|:(missing value))'s valueForKey:"stringValue") as listif (length of t) > 0 then set nname of resp to (item 1 of t) -- copy Note Title if it's thereset t to ((theXMLDoc's nodesForXPath:"/head/title" |error|:(missing value))'s valueForKey:"stringValue") as listif theXMLDoc ≠ missing value then -- if valid xml was foundset {theXMLDoc, theError} to current application's NSXMLDocument's alloc()'s initWithXMLString:xmlData options:0 |error|:(reference) -- parse the xml dataset resp to {nname:"", author:"", created:"", tags:"", updated:"", exporter:""} -- init returned valuelocal theXMLDoc, theError, t, respscript xmlScript -- encase the asobjc call in a script objecton parseNote(xmlData)end getMeta2return respset resp to parseNote(theXMLdata) -- parse the xml dataset ourTimer to getFineTime() -- timer for startset theXMLdata to " " & (item 1 of readIndex(infile, {""}, {""}, 2000)) & "" -- get html head tags from note html filelocal theXMLdata, ourTimer, respon getMeta2(infile)end getMetareturn resp -- return record with meta info to callerset timerSub1 to timerSub1 + (getFineTime() - ourTimer) -- accumulate time for this subroutineset nname of resp to (value of XML element "title") as text -- get note title from title tagif nm is "keywords" then set tags of resp to cnif nm is "author" then set author of resp to cnif nm is "updated" then set updated of resp to cnif nm is "created" then set created of resp to cnif nm is "exporter-version" then set exporter of resp to cn -- extract based on name ....set cn to value of XML attribute "content" of thismeta -- and the content attributeset nm to value of XML attribute "name" of thismeta -- get the name attributeif exists (XML attribute "name" of thismeta) then -- if there'a a 'name' attributeset thismeta to item t of metas -- get this meta tagrepeat with t from 1 to (length of metas) -- look at each meta tag in turnset metas to every XML element whose name = "meta" -- get all meta tagstell XML element "head" -- look within the head tagtell (make new XML data with properties {text:hd}) -- pass the note html to the xml scannerset resp to {nname:"", author:"", created:"", tags:{""}, updated:"", exporter:""} -- init returned valueset hd to "" & (item 1 of readIndex(ifile, {""}, {""}, 2000)) & ""set ourTimer to getFineTime() -- init sub timerlocal resp, XMLAppData, t, nm, cn, metason getMeta(ifile)end buildTopIndexmy writeCSS() -- write CSS file if it's not already theremy writeJS() -- write javascript file if it's not already theremy writeIndex((POSIX path of FolderHTML) & myTagFile, tagOutput) -- write all-tag page" & tagHTML & "" & pageHead("All Tags", "All Notebooks", "Click headings to sort. This page was built " & fmtLongDate(buildDate) & " " & tzone() & ".", true) & "if length of tagHTML > 0 then set tagOutput to "
     
    " & pageHead("All Tags", "All Notebooks", "No tags were found in any of the exported notebooks.", false) & "All Tagsset tagOutput to "my writeIndex((POSIX path of FolderHTML) & myTopIndex, htmlBooks) -- write top-level index page for all notebooks" & bookHTML & "
    " & my textHT(bookName) & "" & ((y as text) & "-" & lzer(m as number) & "-" & lzer(d as text)) & "" & makeSize(s) & "
    FilesSizeExportedModifiedCreatedNotesNotebook Name
    " & pageHead("All Exported Notebooks", "All Tags", "Click headings to sort. This page was built " & fmtLongDate(buildDate) & " " & tzone() & ".
    Totals: " & totBooks & " notebooks, " & totNotes & " notes, " & makeSize(totSize) & " size, " & totFiles & " files (attachments)", true) & "All Notebooks" & getSysInfo("") & " set htmlBooks to "end repeat -- all notebook index pages have now been readset progress completed steps to pcounterset pcounter to pcounter + 1set totFiles to totFiles + (0 + (item 5 of bookdata))set totSize to totSize + (0 + (item 4 of bookdata))set totNotes to totNotes + (0 + (item 3 of bookdata))set tagHTML to tagHTML & item 2 of bookdata -- and the tag dataset bookHTML to bookHTML & " " & item 1 of bookdata -- keep the link dataset bookdata to readIndex(pf, {" ", "data-notes='", "data-foldersize='", "data-files='"}, {"bookindex -->", "", "'", "'", "'"}, 0) -- read the index.html page in the subfolderif exi then -- if index.html exists in this folderset exi to falseset pf to alias pfset exi to truetell application "System Events" to set pf to ((path of fol) & nbIndexFile)set progress additional description to "Processing " & pftell application "System Events" to set pf to name of fol -- 0.3.5repeat with fol in folderList -- for every subfolderset pcounter to 0 -- counter for progress displayset progress description to "Building top-level index"set progress completed steps to 0 -- set progress counter to zeroset progress total steps to totBooks -- set up progress displayset totFiles to 0set totSize to 0set totNotes to 0 -- init totalsset totBooks to count of folderListset buildDate to current date -- date & time these index pages are builtset tagHTML to "" -- init table body html for list of tagsset bookHTML to "" -- init table body html for list of notebooksif logProgress then log "Folders being indexed"tell application "System Events" to set folderList to every folder of alias FolderHTML -- 0.3.5local totNotes, totSize, totFiles, totBookslocal bookdata, pcounter, htmlBooks, tagOutput, exilocal bookHTML, tagHTML, buildDate, folderList, fol, pfon buildTopIndex()end buildNoteIndexmy writeIndex(outHTML & nbIndexFile, htmlNotes) -- write the index.html for this notebook

    " & tagRows & "" & htmlNotes & "
    TagsAuthorFilesSizeModifiedCreatedNote Title
    " & pageHead("Notebook: " & my textHT(bookName), "All Notebooks  All Tags", "Click headings to sort. This notebook was exported from Evernote " & my fmtLongDate(expStamp) & " " & tzone() & "
    Totals: " & bookNotes & " notes, " & makeSize(dirSize) & " size, " & bookFiles & " files (attachments)", true) & "" & bookName & "" & noteBookRow & "bookindex -->" & getSysInfo(priorEnviron) & "set htmlNotes to "if priorExportDate ≠ "" then set ENdate to priorExportDate -- use prior export date if book wasn't just exportedset ENdate to (y1 as text) & lzer(m1 as number) & lzer(d1 as text) & "T" & lzer(h1 as text) & lzer(r1 as text) & lzer(s1 as text) & "Z" -- build export date to embed as comment in notebook index pageset {year:y1, month:m1, day:d1, hours:h1, minutes:r1, seconds:s1} to ((expStamp - offsetGMT) as date)set sortTags to "hideNBnames('nbname'); sortTable('tagTable',0,0);" -- for onload attribute" & tagRows & "
    NotebookParentsNoteNoteTag Name
    set tagRows to "
    Tags in this Notebook
    if (length of tagRows) > 0 thenset sortTags to "" -- assume no tag table to sort (fragment for the body onload attribute)" & dateCell(bookCreate) & dateCell(bookMod) & dateCell(expStamp) & fmtSize(dirSize) & "
    " & noteBookCell & " set noteBookRow to " set yy to count of listNoteFiles -- count of notes in this notebooktell application "System Events" to set dirSize to size of yy -- get size of notebook 0.3.5end repeat -- End of processing for notes in current notebook" & aNoteAuthor & " " & notelink & my dateCell(aNoteCreate) & my dateCell(aNoteMod) & fmtSize(sz) & " set htmlNotes to htmlNotes & " set bookNotes to bookNotes + 1 -- count notes in this notebookset bookFiles to bookFiles + aNoteAttach -- count attachments in this notebookset aNoteAttach to count of aNoteAttach -- count attachmentsset aNoteAttach to every file of folder resourceFolder -- get list of attachmentsset sz to sz + (size of folder resourceFolder) -- add size of resources folderset resourceFolder to (POSIX path of noteHTMLfile) & ".resources"tell application "System Events" -- 0.3.5try -- handle error if no resources folder existsset aNoteAttach to {} -- assume no attachments for this noteset sz to size of (get info for noteHTMLfile) -- size of note html file 0.3.5" & noteBookCell & " " & notelink & noteLinkFar & " set tagRows to tagRows & " set allTagNames to allTagNames & spanTag -- add to cell for tag table detail rowset spanTag to my fmtTag(aTagName) -- format the Tag Nameset parentCell to (item seenTag of parentTagHTML) -- get parent hierarchy dataelse -- get tag parent string from previously cached listcopy (aTagName) to end of parentTagNames -- and this tagcopy parentCell to end of parentTagHTML -- cache this parent tag infoset loopTag to parent of loopTagset parentCell to my fmtTag(name of loopTag) & parentCell -- pre-pend parent tagrepeat while (parent of loopTag) is not missing valueset loopTag to tag aTagNameset parentCell to "" -- init hierarchy of tag namesif seenTag = 0 then -- have not seen this tag beforeset seenTag to my item_position({aTagName}, parentTagNames) -- seen tag before?repeat with aTagName in aNoteTagList -- process each tagset allTagNames to "" -- initialize a string of tag names for the note detail lineset aNoteTagList to every text item of tagsCommaelse -- process the tags assigned to this noteset allTagNames to " " -- placeholder for table cellif tagsComma = "" then -- if no tagsset tagsComma to (tags of noteAttrs) as text -- comma separated list of tags from note html meta tagsif aNoteCreate < bookCreate then set bookCreate to aNoteCreate -- and earliest created note in notebookif aNoteMod > bookMod then set bookMod to aNoteMod -- track most recently changed note in notebookset aNoteCreate to getDateMeta(created of noteAttrs) -- get note create date (as class date)set aNoteMod to getDateMeta(updated of noteAttrs) -- get note update date (as class date)set noteLinkFar to " set notelink to " set fileEnc to my repl(fileEnc, "/", "%3A") -- handle filename with : which evernote saves as /set fileEnc to my urlEncode(name of noteHTMLfile) -- get current note file name (no path)set aNoteExporter to exporter of noteAttrs -- evernote versionset aNoteAuthor to " set aNoteAuthor to " ��nU�M��U���j���� 6���.��]��6`��� U���H���[q�� G f �  \ { � � 2 m � � ) C � � L � � � =~���c�� ;Yb|�Z���_��>����!Cm��� -Cd���)���,b���U~���!s���,>n������)t��_����1c�����!4p�� \��� !�!"0"V"�"#j#�#.$z$%m%�%2&b&�&�&�&&'<'�'�'�' (Z(v(�(�(�()�)�)�)�)*5+l+�+/,h,�,�,�,�-�-�-.2.[.t.�.�2+3@3g3�3�3c4�45o5�5�56K6�7�78"8�8�8+9Z9u9�9.:C:n:�:�:�:2;w;�;�;�;�;<C<k<�<�< =^=q=�=>>1>Q>f>�>�>�>�>?q?�?�?@X@g@�@�@�@�ABCBgB~B�B�B�B�B CYC�C�C�CD;DoD�D�DE\E�E�E�E?FyF�F�F�F�F)G:GUG�G�G�G�G�G'H9HbH�H�H�H�H�HII2IzI�IJJBJiJ�J�J�J2KfK�K�K�K1LVLxL�L�L�L�LM.MjM�M�M�M�M�M[N�N�N�NOYO�O�O�O�O�OP+PMPsP�P�P�PQ8Q]Q�Q�Q�Q�Q R7RTRiR�R�R�RS3ScS�S�S�S&TZTkT�T�T�T�TUm�m�m9n�n�n�nono�opp%pdpupqq(qYqlqyq�q�qrWrur�r�r�s�s�s�s$t�t�tEuuu v=v�v�v�v$w�w�wx*x�x�x�xdy�y�y'zSzlz�z�z�z{{z{|1|[|�|�|�|N}t}�}*~J~q~�~:Rh������ �m���Ё �V�o������j�~������ �0�Y���DŽԄ� �E�Z���Dž �o��O�V�i�y���ч݇�B�e�����ψ���-�I�����Ӊ���"�0�A�|�������ъ �;�i�����׋�� �I���̌��:�f�y�������ˍ���1�A�i�����Žێ��4�g�����֏���.�V������#�O������ �;�l���ƒ�;�R�p�~�����K�����Ŕ�%�{�ڕ�e���ؖ�9��� �=�u���W�˙֙����(�<�K�Z�k����������*�J�b���ɛ��1�W���]�y���ԝ���+�9�]�������Ҟ�����&�9�F���ܟ(�o���ܠ���:�J�\��������U�p��������C�l���ˣ �M�������4�C�a�����ϥܥ�8����%�a�u���ԧ��;�_���Ө"�I�p���Щ� ��+�a����� �h���������/�U�e�s�������%�B�v���Ϯ,�>�N�m��������$�������İ����2�����±ױ���R���ó���*�V�������)�k��������F�u�������c���Ϸ#�Ҹ��.�O���ӹ���5������:�~���û� �*�C�Y�p�������Լ��!�@�n���ʽ�(����ʾ��+�c���̿�:�n������@�q������/�?�T�q������6�S�q���������$�:�T�}����+�?�K����������3�B�\�y�����������#�@�f�������������(�?�d��������#�@�V������&�A������`�����"�4������K�k������(�t����� �M�������)�z�����<�y�������&�S��������� �3�i��������=�n��������U�p����������>�o���������O�g�������Y������8�p�������4�`������2�H�]�������-�k��������3�g�������#�4�R�~����������8�`�������������������������4����� �!�A�R�t���������3�A�N��������+�k������J���4�L�q�������!�E�V�n�������%�T�z����������Y�q�������D�u��������%�O�����C��������[���������:������� �;�����[������D�����������E�����.�L����5�_�o������^���R�����������6�n�������(�j����������(�C�������>�R�����������:�S�|�����"?Xu����� +C]w����J�w�;�N�j���� : d } � � � �  2 � � � " h  ? T � � � �  ] � s��!Kw�����+c�,d�n��Uq��q�>����3U���P[q~���� ,^s����(;Wk��������"5S����2H`m������!K[����L���  Q u � � � � !R!g!x!�!�!�! ""Q"�"�"�"�"##"#5#e#�#�#�#$7$F$Y$m$�$�$�$�$�$�$�$ %0%z%�%�%�%�%�%m&w&�&�&�&�&�&'0'E'R'k''�'�'�'�' (5(g(�(�(�(�(�()7)F)p)�)*5*�*�*�*F+O+W+u+�+�+,F,[,,�,�,$-�-�-�->.m.�.v/�/�/�/"0A0V0q0�0�0�0�0.1=1g1x1�1�1�1�1 2/2[2�2�23.3:3d3�3�3�34?4w4�4�4 55,5=5N5]5�5�5�56)6m6�67 717K7`7r7�7�7�7�7*8�8�8�8 9&9b9v9�9�9�9 :+:P:u:�:�:�: ;-;^;�;�;$<=<r<�<�<�<'=E=d=�=s>�>?�?�?�?6@c@�@�@�@ACA�A�A�ABIB]B�B�B�BCZCoC�C�C�C�CD@DnD�D�D�DEE0ERE�E�E�E�E�E%FRFF�F�F�FGGG�G�G�G�GHH4HTH�H�H�H�HIIRIgI�I�I�I�I)JVJ�J�J�J K1KNK�K�K�K�K�KL&L7LGLUL_L�L�L�LMM@M^MvM�M�M�MN6N]N�N�N�NO9O\O�O�O�O'P�P�P�P�PQQ6QiQ~Q�Q�Q�QRCR�R�R�RSOStS�S�S"TAT|T�T�T�T�TULUnU�U�U�UV VKV�V�V�V,WNW�W�WXXsX�X�X�X�XGY�Y�Y�YZIZ�Z�Z�Z�Z�Z�Z [E[�[�[�[C\8a^bwb�becc�c�c�c�c(d_d�d�deTe�ef>f^f�f$g�g�ggh�hi@idj�j�k�k�kl(l|l�l�lm/m�m�mnCnLn{n�n�n�n�no7ofo�o�o�opp&pOp�p�p�p qudu�u�u�uvvEvyv�v�v�vwQw_wtw�w�w�wUxqx�x�xByYy�y�yyz�z�z�z�z {,{L{e{�{�{�{�{||?|R|j|�|�|�|}]}�}�}~�~�~ 9��-�@���I�� ��d�������6�V�w��������8�g���Ԅ�2�V���������#�Q���Ȇ��q���͇��=�|�Lj&��P�c���Ԋ�I�����֋��*�h�����ʌ��!�D�Y�~���̍ލ �A�Z�����Ԏ�!�M�z�����ӏ��%�>�L�j���Ӑ� �6�P�p������d�{�Ȓ�f���ɓד�� �[���̔��6�^�u��������8�r������t�����*�T���͘*�Q�u���%�T���њ*�Q�x�������&��������G�}���˝ݝ��#�?�m���Ȟ���W������ �-�G�j�������Π��6�F�R�����4�C�N�[�n�����֢����0�i�������%�D�R�����Ф!�p�������̥�M�y�����`���ʧ��@�n���̨��� �$�D�S�l���٩��4�L�^�p�����/�D�W�s����P�q���ìڬ��I�e�t�����խ� �-�9�_�i������� � �a�p���ȯ��H�c�|�ɰ�6�C�g���±��*�P���˲����̳=���� �:�Q�������j�����I�h�����÷�a�X�»��3�U������|����N��5�O�f�{�������1�j�������/�V�o���:�j������I�����#�l��������?�^�o�������d�s�������%�N���������8�N�w������4�K�j�������������8�T���� �8�U�j�����}���������P������������;�\�}����������������h����������� ��2�^�s����������@�x��������}�����n�����p���?����Q�q�������P�p���������9�h�������'�H�h����� �0�|������(�F�W�f�v�����^���������"�B����2�[���������"�O�[�v��������?�t��������:�s��������2�J�g������� ��?�X�l�������2�D�������%���������J�����O�e��:�b������2�S������������^������� �c�������R�����������[�������/�a�v��� �'�o������������� �1�e������C�E�`���������v��������#�@�j����� �1�E�k������N�����!�G��������F�e�����������F�V�g����J�i�v���9�Y�g��������]�������5f��� :R}��� R��DZt���x���&Yn���J����,Ul����  @����� " = f � � �  = � �  / O i �  E f � � � � I��z��!@���R������%A^� p���U�e�-ey -@Sr������/EZt�����Ads��� D~��<{���$M|����D�� 0!R!u!"D"�"#Q#�#�#�#$5$l$�$�$ %%�%�%�%�&d'�':(�(�(0)b)�)�)*7*M*d*s*�* +�+�+y,�,�,x-�-�-.G.�.�.�.�. /^/w/�/�/0T0�0�0�071o1�1�12<2w2�2�2�243O3�3�3�334N4�4�45,5J5d5�5�5�5�5�56-6J6`6}6�6�6�6�6�687�7�7828A8�8 9W9s9�9�9�9�9,:F:`:�:�: ;;};<N<�<�<�<=.=Z=�=�=�>?f?�?�?�?�?@I@c@}@�@�@�@�@AiA�AuBGC�C�CD�D�D�D�E�E�E�E�E�E�E F-F�F�F�F�F�F+GKGuG�G�G�G&H:HdH�H�H I7IvI�I�IJJ,J�J�JKKgK�K�K�KL:LRLzL�L�L�L.MKMsM�M�M$NLNlN�N�N�N�NO`O}O�OP!PAPRP�P�P�P�PQ)QoQ�Q�Q:RiR�R�R�RSRS�S�S�S�ST$T`T�T�T�T_U�U�U�UV V5V�V�V�V�V�V#W7WLWdWvW�W3XgX�X�X�X�XwY�Y�Y�YZBZTZ�Z�Z*[P[p[�[�[�[\,\Z\�\�\�\�\].]>]L]Y]�]�]�]�]�]^O^u^�^�^�^�^ _'_I_�_�_�_�_`b`t`�`�`�` a>aTaka�a�a�a:bTbob�b�b�bc1c[c�c d-d_d�d�d8eee�e�ef�f�f�f?glg�g h�h�h�h.i[ini�ij#j�j�j�jSk�k�klLl�l�l�lhm�m�mn=n�n�n�nio�o(pUphp�pq�q�qPr}r�r$sQsds�s tt�t�tJuwu�u�u)v�Q������������"�O�b�օ����ӆ�G�t�����*�=���ʈ݈C�p����/�B�ʊ�� �����̋N�{�����"�5������^����� �9�L����l������J�]���*�’�}�����*�W�j�ޔ ������ѕR�����2�E�˗�� �����?�l����$�7���������ÛD�q��� �6�I�ѝ�����ƞٞ>�k���"���͠�J�w����4�G�Ȣ���s�����)�V�i�Ϥ�������ͥ1�^�q�צ����ħקU�����0�]�p�٩������F�s�߫ ���̬Q�~���*���خI�v�ۯ����հ�N�{�����+�>�IJ��q����>�Q�������ŵصE�r����G�Z������h��� �6���ʹݹ\����@�S�ɻ��y���-�Z�m���z��� �9�L������g������F�Y���&�9�������p����@�S�����������7�d�w� �6�I������������G�t����0�C����������8�e�x����#�������R�����L�_���)�������o������C�V����r�����0�]�p��� �������J�w�����%�8�������Q�~����>�������X������� �3�������a������G�Z����+�������g������E������q������G�Z������������7�d�w���$�7�������]������;�N��� ������5�b�u�����������K�x�����������?�l�����%�������S����� �6�I������_�����+�X�k�����������9�f�y��G�������x�����-�Z�m��� ��������U������;�N����������d�����#�P�c������������.�[�n��������Q~�>�� ���#Pc�� w��@m�.A���N{��% 8 � �  � � � _ � � 1 ^ � �  � � � /\o�)<��m��>��z��DW����:gz4G���^�.A���}�DW���o�GZ�%������Er��, ? � � l!�!�!"="P"�"###�#�#�#d$�$�$%A%T%�%�%&�&�&�&9'f'y'�'(1(�(�(�(v)�)�)*H*[*�*�*+�+�+�+1,^,q,�,�,--�-�-).V.�.�./�/�/�/60c0v0�01%1�1�1X2�2�2 3M3`3�3 44�4�4�4[5�5�56&6�6�6�6y7�78E8�8�8 9l9�9,:Y:l:�:;;�;�;<K<^<�<�<=}=�=:>g>z>�>(?�?�?�?k@�@�@ AMA`A�ABB�B�B�B5CbC�CD.D�D�D�DeE�E�EFLF_F�F�FG�G�G6HcHvH�HI)I�I�I�IWJ�J�JK?KRK�KLLuL�L�L*MWMjM�M�M N�N�N�N1O^OqOP4PGP�P�P�PJQwQR.RAR�R�R�RmS�S�STCTVT�TU�U�U�U7VdVwV W:WMW�W�W�W]X�X�X Y7YJY�Y�YZrZ�Z![N[a[�[#\6\�\�\]s]�]^5^�^�^�^t_�_7`d`w`a>aQa�a�ab�b�b�b>ckc~c�cd(d�d�d�dne�efHf[f�fg)g�g�g�ggh�h�h&iSifi�i%j8j�j�jTk�kl5lHl�l�lmwm�m�mnHn[n�no�o�o�o�o�op>pUptp�p�p�pqqxq�qr:r[r�r�r�r s-sJs�s�s�s%t7tNttt�t�t�tu5u`u{u�u�u�u�u?v`v�v�v�vw>wqw�w�w�w$xRx{x�x�xYy�y�y�y�i�����A�P�a�z���֙�W�h�y���ؚ!�4�G�x�ě�����(�~������&�2�C�����Ş۞��#�P�}���ן�1�^�������?�l���ơ� �M�z���Ԣ�.�[�������<�k���"�T�z�����N�X�h�x�������צ��(�U�g�����ӧ��$�Q�c�����Ϩ�� �M�a�������ǩ+�X�|�����ܪ�W�{�������#�=�n�w������o���֭��$�s�Ȯݮ� �)�I���� �2�N�i�հ�������1�o�x�����ʲ��[�g���س�4�j�����Դ� �/�a���ٵ�U�set UserAgent to " --user-agent \"CertunaScript/0.1\""set AuthString to " -H \"Authorization: Discogs token=" & Token & "\""set AdditionalFilters to "&type=master&format_exact=Single\""set baseURL to "\"https://api.discogs.com/database/search?"set Token to "please_insert_your_own_API_key_here"to QueryDiscogs(ArtistSong, nthItem)to replaceText(find, replace, subject)end ExtractStringreturn ExtractedValueset ExtractedValue to text item 1 of SecondChunkset text item delimiters to RightEdgeset SecondChunk to text item (1 + nthValue) of AllTextset text item delimiters to LeftEdgeto ExtractString(AllText, LeftEdge, RightEdge, nthValue)click menu item "Enter Full Screen" of menu 1 of menu bar item "View" of menu bar 1activate application "Firefox"lookup_timesset my_list to my_list & my_list -- Double the size of the listset end of lookup_times to round (((AMTime) - t) * 1000)get middle item of my_listrepeat 16 timesset lookup_times to {}set my_list to {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}on runerror "ERROR: unParseChars() handler: " & errMsg number errNumreturn unparsedTextset the unparsedText to thisList as stringset AppleScript's text item delimiters to the {newDelim as string}unParseChars({"one", "two", "three"}, "-")make new reminder in list reminderList with properties {name:subjMsg, body:"From: " & fromMsg & formatBody & "message://%3c" & msgID & "%3e", due date:((current date) + interval)}set formatBody to paragraph 1 of msgBody & return & paragraph 2 of msgBody & return & paragraph 3 of msgBodyset msgBody to content of iset msgID to message id of iset subjMsg to (subject of i as string)set fromMsg to (sender of i as string)repeat with i in the items of theMessagesif (theMessages = {} or the class of item 1 of theMessages is not message) then display alert "No message selected"set theMessages to the selectionset reminderList to "Reminders"set interval to 5 * hoursset formatBody to ""set theMessages to {}do shell script "/usr/local/bin/growlnotify -m 'Error quitting " & this_process & "'"do shell script "/usr/local/bin/growlnotify -m 'Quitting " & this_process & "'"tell application this_process to quitif this_process is not in white_list thenset this_process to item i of the process_listrepeat with i from 1 to (number of items in process_list)set white_list to {"Finder", "Adium", "iTunes", "Transmission", "HardwareGrowler", "AppleScript Editor"}tell application "System Events" to set the visible of every process to trueend convertmove file exportFileName to folder dirName with replacingclose docexport doc to file exportFileName as exportFormatif appName is "Pages" thenclose access (open for access exportFileName)set exportFileName to (dirName & docName & "." & exportExtension) as textset docName to name of docset doc to open fullPathset fullPath to (dirName & fileName)on convert(dirName, fileName, appName, exportFormat, exportExtension)convert(fDir, fName, "Pages", Microsoft Word, ".docx")using terms from application "Pages"if fExt is "pages" thenset fDir to folder of theFile as textset fName to name of theFile as textset fExt to name extension of theFile as texttell application "Finder" to set theFiles to every file in the entire contents of folder inputFolderon run inputFolderend countNucleotidesreturn (statsstr)set statsstr to statsstr & " - " & gapCount & "if gapCount > 0 thenset statsstr to statsstr & " N " & nCount & "if nCount > 0 thenset statsstr to statsstr & " W " & wCount & "if wCount > 0 thenset statsstr to statsstr & " S " & sCount & "if sCount > 0 thenset statsstr to statsstr & " M " & mCount & "if mCount > 0 thenset statsstr to statsstr & " K " & kCount & "if kCount > 0 thenset statsstr to statsstr & " Y " & yCount & "if yCount > 0 thenset statsstr to statsstr & " R " & rCount & "if rCount > 0 thenset statsstr to statsstr & " V " & vCount & "if vCount > 0 thenset statsstr to statsstr & " H " & hCount & "if hCount > 0 thenset statsstr to statsstr & " D " & dCount & "if dCount > 0 thenset statsstr to statsstr & " B " & bCount & "if bCount > 0 thenC " & cCount & "G " & gCount & "T " & tCount & "A " & aCount & "Breakdown:Ambiguous Nucleotides: " & (ambigTotal as string) & "Discrete Nucleotides: " & (realTotal as string) & "Alignment length: " & (alnTotal as string) & "set statsstr to "Sequence length: " & (seqTotal as string) & "set ambigTotal to seqTotal - realTotalset realTotal to aCount + tCount + gCount + cCountset alnTotal to seqTotal + gapCountset seqTotal to aCount + tCount + gCount + cCount + bCount + dCount + hCount + vCount + rCount + yCount + kCount + mCount + sCount + wCount + nCountset gapCount to (count dnaStr's text items) - 1set nCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "N"set wCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "W"set sCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "S"set mCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "M"set kCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "K"set yCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "Y"set rCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "R"set vCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "V"set hCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "H"set dCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "D"set bCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "B"set cCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "C"set gCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "G"set tCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "T"set aCount to (count dnaStr's text items) - 1set AppleScript's text item delimiters to "A"on countNucleotides(dnaStr)display alert "" & msgtell application _appnameset msg to countNucleotides(input as string)set _appname to name of first process whose frontmost is trueend contains_Lista contains bon contains_List(a, b)end equals_toreturn a = bon equals_to(a, b)run script (scriptdirectory & "SMB_Connect.scpt" as POSIX file) with parameters {shareList, serverList}run script (scriptdirectory & "VPNConnect.scpt" as POSIX file) with parameters VPNnameif currentWifi is not wifiname thenset currentWifi to do shell script "networksetup -getairportnetwork " & wifiDeviceName & " | awk '{print $4}'"set wifiDeviceName to do shell script "networksetup -listallhardwareports | awk '/Hardware Port: Wi-Fi/{getline;print $2}'"set scriptdirectory to (parentDir & "AppleScript/")set parentDir to POSIX path of resulttell application "Finder" to get folder of (folder of (path to me)) as aliason run {wifiname, VPNname, shareList, serverList}end getOutputNumberreturn outputNumberset outputNumber to item 1 of nameAsList & item 2 of nameAsList as numberset nameAsList to util's splitString(items 1 thru 2 of fileName, "")on getOutputNumber(theFile)end getOutputNamereturn outputListset outputList to items 4 thru -1 of nameAsList as stringset nameAsList to util's splitString(item 1 of nameWithoutExtension, "")set nameWithoutExtension to util's splitString(fileName, ".")set fileName to name of theFileon getOutputName(theFile)end checkForFilesdelete eachItemif name of eachItem is not (subFileName) thenrepeat with eachItem in startingFolderContentsif (count of startingFolderContents) is not 1 thenset startingFolderContents to (entire contents of folder saveLocationAlias)on checkForFiles(saveLocation, subFileName)delete cue id groupCueAlreadyID of parent of groupCueAlready -- of cue list mainCueListif groupCueAlready is not "" thenset groupCueAlreadyID to uniqueID of groupCueAlreadyset groupCueAlready to (first cue whose q name is "Line Check")set groupCueAlready to ""on checkForCues()end correctOutputNamereturn outputNamereturn newOutputNameset newOutputName to util's findAndReplaceInText(outputName, "Pros", "Proz")if outputName contains "Pros" thenon correctOutputName(outputName)end checkDigitsreturn numset num to text -howLong thru -1 of ("00" & num)on checkDigits(num, howLong)collapse groupCueset pre wait of thisCue to (previousDuration + previousPreWait + userDelay)set previousPreWait to pre wait of previousCueset previousDuration to duration of previousCueif eachOutputNumber is not 1 thenset previousCue to cue before thisCuesetLevel thisCue row 0 column eachColumn db "-inf"setLevel thisCue row 0 column eachColumn db userLevelsetGang thisCue row 0 column eachColumn gang eachGangsetGang thisCue row 0 column eachColumn gang ""setLevel thisCue row 1 column eachColumn db 0setLevel thisCue row 0 column eachColumn db subLevelif item eachOutputNumber of theChannels contains "Sub" thenset eachGang to getGang thisCue row 0 column eachColumnif eachColumn is eachOutputNumber thenrepeat with eachColumn from 1 to outputCountmove cue id thisCueID of parent of thisCue to end of groupCueset thisCueID to uniqueID of thisCueset q name of thisCue to eachOutputNameset file target of thisCue to eachOutput as alias -- add the file to the cueset thisCue to last item of (selected as list) -- give the cue a variablemake type "Audio" -- make cueset eachOutputNumber to my getOutputNumber(eachOutput)set eachOutputName to my getOutputName(eachOutput)if q number of eachOutput is not subFileName thenrepeat with eachOutput in util's sortList(allTheFiles)set allTheFiles to (entire contents of folder saveLocationAlias)set saveLocationAlias to POSIX file saveLocation as aliasset mode of groupCue to timelineset q name of groupCue to "Line Check"set playback position of mainCueList to titleCueset titleCue to (first cue whose q name is rigCheckTitleCue)set current cue list to mainCueListif rigCheckTitleCue is not "" thenset mainCueList to (first cue list whose q name is mainCueListName)set name of newFile to newFileNameset newFile to duplicate file (POSIX file (saveLocation & subFileName) as alias)set newFileName to (checkDigits(eachOutput, 2) & " " & (item eachOutput of theChannels) as string) & fileTypesay (eachOutputToSay) using "Daniel" saving to (POSIX file saveLocation & checkDigits(eachOutput, 2) & " " & (item eachOutput of theChannels) as string) & fileTypeif eachOutputToSay does not contain "Sub" thenset eachOutputToSay to correctOutputName(item eachOutput of theChannels)repeat with eachOutput from 1 to outputCountset outputCount to count of theChannelsset theChannels to util's splitString(userChannels, ", ")checkForFiles(saveLocation, subFileName)checkForCues()set current cue list to first cue list whose q name is mainCueListNameset saveLocation to (POSIX path of qlabParentPath & "Soundcheck/Line Checks/")set qlabParentPath to (container of qlabPathAlias) as aliasset qlabPathAlias to POSIX file qlabPath as aliasset qlabPath to pathset subLevel to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Line checks: sub level")set userLevel to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Line checks: output level")set userChannels to notes of (first cue of (first cue list whose q name is variableCueListName) whose q name is "Output channel names")set userDelay to 0.5userDelayset subFileName to "Sub v2.wav"subFileNameset mainCueListName to "Main Cue list"mainCueListNameset rigCheckTitleCue to " RIG CHECK" -- Leave blank to use the current positionrigCheckTitleCueset fileType to ".wav"fileTyperun script tplink_script with parameters {state}set tplink_script to (path to scripts folder as text) & "TPLink Plug Control For DVU.scpt" as aliasset tplink_light to "1"set state to "1"else if button returned of b is "On" thenset tplink_light to "0"set state to "0"if button returned of b is "Off" thenset b to display dialog "TP-Link Conference Light Control" buttons {"On", "Off"} default button "Off" with title "TP-Link Conference Light"else if tplink_light is "1" thenset b to display dialog "TP-Link Conference Light Control" buttons {"On", "Off"} default button "On" with title "TP-Link Conference Light"if tplink_light is "0" or tplink_light is "" thenproperty tplink_light : ""global kasacontrolset kasacontrol to (path to scripts folder as text) & "TPLink Plug Control For DVU.scpt" as aliaserror number -1728display dialog "bailing out..."else if button returned of result is "Cancel" thentell application "Strongbox-AutofillSafari" to if it is running then quitset pClipboard to emptyClipset infoClipboard to emptyCliptell application "System Events" to tell process "Safari" to keystroke tabPromptelse if button returned of result is "Both" thentell application "MacPassAutofill-Prompt" to if it is running then quitset the clipboard to pClipboardmenu_click({"Safari", "Edit", "Paste"})set the clipboard to infoClipboardmenu_click({"Safari", "Edit", "Select All"})set pClipboard to the clipboardmenu_click({"Strongbox", "Item", "Copy Password"})set the clipboard to emptyClipset infoClipboard to the clipboardmenu_click({"Strongbox", "Item", "Copy Username"})if button returned of result is "Username" thendisplay alert "AutoFill" message "Choose entry or create new then select - Options:Both fills Username and password on current page -- Username will just fill UN and PW is in the clipboard for 10 secs." buttons {"Both", "Username", "Cancel"} default button "Both"tell application "System Events" to tell process "Strongbox" to keystroke returnmenu_click({"Strongbox", "Edit", "Paste"})menu_click({"Strongbox", "Edit", "Select All"})tell application "Strongbox" to activateset the clipboard to sendURL as stringset sendURL to theStringif the theString does not contain "." thenrepeat with theString in myArrayset myArray to my theSplit(myTestString, "/")set myTestString to theURLset emptyClip to ""start current screen savererror "Can't urlEncode: " & eMsg number eNumon urlEncode(str)open location "sticky-notifications://note?title=OmniFocus&message=" & ti & taskLinkurlEncode(taskLink)urlEncode(ti)set taskLink to " omnifocus:///task/" & taskIDset taskID to idset ti to nametell singleTaskrepeat with singleTask in theTaskscreate note title aTitle with text aDescription notebook "Test" tags theTagsif aCompletedOn is "" thenset theTags to splitString(aLists, ",")set {aTitle, aCreatedBy, aAssignedto, aCreatedOn, aDueDate, aImportance, aRepeat, aLists, aDescription, aCompletedOn, aComments, aTimeEstimate, aTimeElapsed} to aTodorepeat with aTodo in theListset theList to rest of csvToList(theCsv, {}, {trimming:true})set theCsv to (read theFile as «class utf8»)set theFile to (choose file with prompt "Select a file to read:")log delimiterend getTextItemsset textItems to textItems & text items i thru j of txtif (j > tiCount) then set j to tiCountset j to i + 3999repeat with i from 1 to tiCount by 4000set tiCount to (count txt's text items)on getTextItems(txt, delim)return o's recordListif (o's currentRecord is not {}) then set end of o's recordList to o's currentRecordset quoteInProgress to trueset a to i - 1else if (quoteInProgress) thenif (((j > 1) and ((j < possibleFieldCount) or (i is qdtiCount))) or ((j is 1) and (i is 1)) or ((count trim(thisField, true)) > 0)) then set end of o's currentRecord to trim(thisField, trimming)if ((j < possibleFieldCount) or ((count thisField) > 0)) then set end of o's currentRecord to trim(thisField, trimming)set thisField to end of theseFieldsset o's currentRecord to {}set end of o's recordList to o's currentRecordif ((k > 1) or (j > 1) or (i is 1) or ((count trim(thisField, true)) > 0)) then set end of o's currentRecord to trim(thisField, trimming)set thisField to item k of theseFieldsrepeat with k from 1 to (count theseFields) - 1set theseFields to thisField's paragraphsif ((count thisField each paragraph) > 1) thenset thisField to item j of o's possibleFieldsset o's possibleFields to getTextItems(thisBit, separator)set end of o's currentRecord to item (i - 1) of o's qdtielse if (i > 1) thenset end of o's currentRecord to thisField as stringset thisField to thisField's text itemsset AppleScript's text item delimiters to "\"\""set thisField to (items a thru (i - 1) of o's qdti) as stringif (quoteInProgress) thenif ((count thisBit) > 0) or (i is qdtiCount) thenset thisBit to item i of o's qdtirepeat with i from 1 to qdtiCount by 2 -- Parse odd-numbered items only.set quoteInProgress to falseset qdtiCount to (count o's qdti)property recordList : {}property possibleFields : missing valueproperty currentRecord : {}property qdti : getTextItems(csvText, "\"")script o -- Lists for fast access.do script "cd " & current_path in newTabkeystroke "f" using {command down, control down}set current settings of newTab to tempset font size of temp to fontsizeset temp to current settings of newTabset newTab to do scriptset fontsize to 32set current_path to POSIX path of ((path to me as text) & "::")set for_ to for_ & locListset locList to "Nothing found" & return & returnset locList to locList & location of thisItem & name of thisItem & return & returnrepeat with thisItem in t_fndif t_fnd is not equal to {} thenset locList to ""set for_ to for_ & "In: " & name of thisDatabase & returnset t_fnd to (contents of thisDatabase whose name is i_fileName)repeat with thisDatabase in allDatabasesset the clipboard to theClipboardcopyLinkToEvernote(pageTitle, pageURL)tell application "Evernote" to activatedisplay alert "Evernote and Safari Required" message "You have to launch Evernote and Safari before executing script"if not (exists application process "Evernote") or not (exists application process "Safari") thenend copyLinkToEvernoteclick button "OK" of sheet 1 of wif exists sheet 1 of w thenset the clipboard to theURL as textkeystroke (ASCII character 28) using shift downrepeat length of theTitle timestell process "Evernote"set the clipboard to theTitle as texton copyLinkToEvernote(theTitle, theURL)open theFile as aliastell application "PDFpenPro"set theFile to alias (POSIX file filePath)on run filePathset properties to {alignment:justified, font:"Times", size:12, color:{5000, 5000, 5000}, background:{65535, 65535, 65535}}set played date to date "11/13/2008 21:33:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:America:America_ The Complete Greatest Hits:18 Right Before Your Eyes.mp3" thentell track id 32572set played date to date "11/13/2008 12:01:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Good Time:01 Good Time.mp3" thentell track id 32374set played date to date "11/12/2008 03:00:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Judy Collins:In My Life:11 In My LIfe (LP Version).mp3" thentell track id 37477set played date to date "11/12/2008 00:44:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alison Krauss & Union Station:New Favorite:03 The Lucky One.m4a" thentell track id 32509set played date to date "11/13/2008 17:36:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Edie Brickell & New Bohemians:Shooting Rubberbands At The Stars:10 Now.mp3" thenset played date to date "11/13/2008 15:43:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:38 Special:Tour De Force:01 If I'd Been the One.mp3" thenset played date to date "11/07/2008 01:05:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sheena Easton:Greatest Hits - Sheena Easton:09 Almost Over You.mp3" thentell track id 41172set played date to date "11/14/2008 02:24:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Olivia Newton-John:Back To Basics_ The Essential Collection:09 A Little More Love.mp3" thentell track id 39452set played date to date "11/14/2008 20:47:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Steely Dan:A Decade of Steely Dan (Remastered):06 Hey Nineteen.mp3" thentell track id 41494set played date to date "11/13/2008 16:04:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Paul Simon:Still Crazy After All These Years:01 Still Crazy After All These Years.mp3" thentell track id 39642set played date to date "11/11/2008 00:03:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Oleta Adams:Circle of One:01 Rhythm of Life.m4a" thentell track id 39435set played date to date "11/11/2008 23:29:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barbra Streisand:The Essential Barbra Streisand:20 You Don't Bring Me Flowers.mp3" thentell track id 32971set played date to date "11/14/2008 11:48:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter, Paul & Mary:The Best of Peter, Paul & Mary:03 Lemon Tree.m4a" thenset played date to date "11/14/2008 12:25:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dierks Bentley:Dierks Bentley:07 Is Anybody Loving You These Days.m4a" thentell track id 35037set played date to date "11/14/2008 00:33:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kool & The Gang:Celebration_ The Best Of Kool & The Gang:08 Cherish.mp3" thentell track id 37823set played date to date "11/11/2008 22:50:57"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Terry Jacks:Singles:01 Seasons in the Sun.mp3" thentell track id 41853set played date to date "11/13/2008 22:00:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Bill Withers:Bill Withers' Greatest Hits:04 Lovely Day.mp3" thentell track id 33250set played date to date "11/10/2008 22:17:05"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Firefall:Firefall_ Greatest Hits:03 You Are The Woman.mp3" thentell track id 35626set played date to date "11/13/2008 12:34:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:14 Wanted.m4a" thentell track id 32407set played date to date "11/11/2008 23:07:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Patti LaBelle:The Essential Patti Labelle:10 Somebody Loves You Baby (You Know Who It Is).mp3" thentell track id 39555set played date to date "11/14/2008 01:21:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Ronnie Milsap:The Essential Ronnie Milsap:25 What a Difference You've Made in My Life.mp3" thenset played date to date "11/02/2008 23:35:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Alan Parsons Project:Ultimate The Alan Parsons Project:18 Old And Wise.mp3" thentell track id 41937set played date to date "11/02/2008 23:56:31"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fleetwood Mac:Greatest Hits_ Fleetwood Mac:06 Gypsy.mp3" thenset played date to date "11/13/2008 14:21:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Boz Scaggs:Silk Degrees:09 Lido Shuffle.mp3" thenset played date to date "11/13/2008 14:17:25"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Justin Moore:Justin Moore:01 Back That Thing Up.mp3" thentell track id 37490set played date to date "11/13/2008 10:33:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:02 The Man That Came Between Us (Was.m4a" thentell track id 32186set played date to date "11/13/2008 12:37:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:15 I Don't Even Know Your Name.m4a" thentell track id 32408set played date to date "11/10/2008 23:28:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:2-12 Sing.mp3" thenset played date to date "11/13/2008 10:23:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Neville:The Tattooed Heart:10 Use Me.m4a" thentell track id 32160set played date to date "11/13/2008 10:56:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:09 Mission From Hank.m4a" thentell track id 32193set played date to date "11/13/2008 18:37:18"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Emily West:Emily West:01 Rocks In Your Shoes.mp3" thentell track id 35388set played date to date "11/12/2008 00:54:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Lovers Rock:07 The Sweetest Gift.mp3" thentell track id 40688set played date to date "11/14/2008 02:13:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Don McLean:Tapestry:01 Castles in the Air.mp3" thentell track id 35119set played date to date "11/14/2008 02:16:38"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Helen Reddy:The Woman I Am_ The Definitive Collection:01 I Don't Know How to Love Him.mp3" thentell track id 36278set played date to date "11/14/2008 02:01:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fleetwood Mac:Greatest Hits_ Fleetwood Mac:09 Dreams.mp3" thentell track id 35668set played date to date "11/03/2008 01:08:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alex de Grassi:Deep at Night:02 Deep at Night.m4a" thenset played date to date "11/13/2008 18:07:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lynyrd Skynyrd:The Essential Lynyrd Skynyrd:1-11 Comin' Home [Original Version][.m4a" thentell track id 38319set played date to date "11/07/2008 00:58:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Boyz II Men:Evolution:01 Doin' Just Fine.mp3" thentell track id 33713set played date to date "11/13/2008 15:02:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Cyndi Lauper:The Essential Cyndi Lauper:05 Time After Time.mp3" thentell track id 34648set played date to date "11/11/2008 23:26:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Rolling Stones:Sticky Fingers:03 Wild Horses.mp3" thentell track id 42609set played date to date "11/03/2008 00:59:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Edie Brickell & New Bohemians:Shooting Rubberbands At The Stars:06 Circle.mp3" thenset played date to date "11/13/2008 21:48:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lionel Richie:Back to Front:01 Do It To Me.mp3" thentell track id 38091set played date to date "11/14/2008 11:34:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Maxwell:Now:03 Lifetime.mp3" thentell track id 38525set played date to date "11/13/2008 16:01:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Hootie and The Blowfish:The Best of Hootie and The Blowfish:02 Only Wanna Be with You.mp3" thentell track id 36374set played date to date "11/13/2008 11:28:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:AC-DC:The Razors Edge:04 The Razor's Edge.mp3" thentell track id 32232set played date to date "11/10/2008 21:20:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:America:America_ The Complete Greatest Hits:11 Lonely People.mp3" thentell track id 32565set played date to date "11/14/2008 00:52:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Firefall:Firefall:06 Cinderella.mp3" thentell track id 35625set played date to date "11/12/2008 00:32:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Firefall:Rhino Hi-Five_ Firefall - EP:03 Strange Way.mp3" thentell track id 35630set played date to date "11/13/2008 21:26:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Bee Gees:Horizontal:28 Words.mp3" thentell track id 33064set played date to date "11/14/2008 20:52:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barbra Streisand:The Essential Barbra Streisand:31 Send in the Clowns.mp3" thentell track id 32982set played date to date "11/13/2008 17:56:22"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Eagles:Their Greatest Hits (1971-1975):01 Take It Easy.m4a" thentell track id 42254set played date to date "11/13/2008 19:38:57"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Diamond Life:09 Why Can't We Live Together.mp3" thentell track id 40672set played date to date "11/10/2008 21:35:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dr. Hook:Dr. Hook Greatest Hits:13 Sharing the Night Together.mp3" thentell track id 35203set played date to date "11/12/2008 03:03:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Norah Jones:Come Away with Me:05 Come Away With Me.mp3" thentell track id 39430set played date to date "11/14/2008 02:36:24"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Don Henley:The End Of The Innocence:05 New York Minute.mp3" thentell track id 35116set played date to date "11/14/2008 02:09:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dionne Warwick:Greatest Hits Dionne Warwick 1979-1990:01 That's What Friends Are For.mp3" thenset played date to date "11/14/2008 00:11:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Al Jarreau:Jarreau:01 Mornin'.mp3" thentell track id 32342set played date to date "11/14/2008 00:02:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Wilson Phillips:Shadows And Light:03 You Won't See Me Cry.mp3" thentell track id 44288set played date to date "11/10/2008 21:03:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Whitney Houston:I'm Your Baby Tonight:03 All the Man That I Need.mp3" thentell track id 44193set played date to date "11/13/2008 19:28:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Big Band Era- Vol. 7:7-02 Maria Elena.m4a" thentell track id 43394set played date to date "11/14/2008 12:57:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Michael Montgomery:John Michael Montgomery:03 I Can Love You Like That.mp3" thenset played date to date "11/13/2008 15:53:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Emmy Rossum:Inside Out:03 Stay.mp3" thentell track id 35391set played date to date "11/13/2008 10:50:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:07 The Call Of The Wild.m4a" thentell track id 32191set played date to date "11/14/2008 21:03:22"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Little River Band:First Under The Wire:04 Cool Change.mp3" thentell track id 38141set played date to date "11/11/2008 18:49:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dr. Hook:Dr. Hook Greatest Hits:06 A Little Bit More.mp3" thentell track id 35202set played date to date "11/12/2008 00:19:46"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rupert Holmes:Greatest Hits_ Rupert Holmes:04 Escape (The Pina Colada Song).m4a" thentell track id 40633set played date to date "11/13/2008 16:22:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Blue Oyster Cult:A Long Day's Night:02 Burning For You.mp3" thenset played date to date "11/14/2008 01:31:08"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Denver:Definitive All-Time Greatest Hits:09 Back Home Again.mp3" thentell track id 37172set played date to date "11/12/2008 00:46:49"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:2-04 Please Mr. Postman.mp3" thenset played date to date "11/13/2008 13:59:46"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Lines:Living Out Loud:07 You Can't Hide Beautiful.m4a" thentell track id 32152set played date to date "11/07/2008 00:24:18"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Confidential:09 Jump on It.mp3" thentell track id 39835set played date to date "11/13/2008 15:57:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Rascals:The Young Rascals:08 Mustang Sally.mp3" thenset played date to date "11/13/2008 22:37:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Jason Mraz:Mr. A-Z:01 Life Is Wonderful.mp3" thentell track id 36600set played date to date "11/11/2008 10:52:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alicia Keys:The Diary of Alicia Keys:07 Diary.mp3" thentell track id 32495set played date to date "11/13/2008 22:50:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Edie Brickell & New Bohemians:Shooting Rubberbands At The Stars:05 Love Like We Do.mp3" thenset played date to date "11/11/2008 23:58:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Basia:Time and Tide:10 Miles Away.mp3" thentell track id 33017set played date to date "11/13/2008 15:50:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Rolling Stones:Out of Our Heads:07 (I Can't Get No) Satisfaction.mp3" thenset played date to date "11/10/2008 20:51:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Air Supply:Ultimate Air Supply:02 All Out of Love.mp3" thenset played date to date "11/14/2008 12:47:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Cranberries:Everybody Else Is Doing It, So Why Can't We:06 Not Sorry.mp3" thentell track id 42180set played date to date "11/13/2008 10:42:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:05 I Was Born With A Broken Heart.m4a" thentell track id 32189set played date to date "11/03/2008 01:03:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Neil Diamond:Moods:06 Play Me.mp3" thenset played date to date "11/02/2008 23:22:18"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kansas:Point of Know Return:07 Dust in the Wind.mp3" thentell track id 37508set played date to date "11/12/2008 01:04:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:1-12 For All We Know.mp3" thentell track id 42112set played date to date "11/12/2008 00:08:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Larry Graham:The Best Of Larry Graham:02 One in a Million You.mp3" thentell track id 37875set played date to date "11/10/2008 22:28:32"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Linda Ronstadt:Cry Like A Rainstorm - Howl Like The Wind:03 All My Life.mp3" thentell track id 38045set played date to date "11/14/2008 20:55:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sheena Easton:The World of Sheena Easton_ The Singles Collection:03 For Your Eyes Only.mp3" thenset played date to date "11/14/2008 12:13:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Guess Who:So Long, Bannatyne:10 Sour Suite.mp3" thentell track id 42313set played date to date "11/14/2008 01:36:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rickie Lee Jones:Pirates:01 We Belong Together.mp3" thentell track id 40334set played date to date "11/12/2008 00:04:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Caravan of Dreams:07 City of Lights.mp3" thentell track id 39833set played date to date "11/14/2008 20:37:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Windham Hill Records Sampler '86:03 Engravings.m4a" thentell track id 44062set played date to date "11/13/2008 14:42:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Danity Kane:Welcome to the Dollhouse:02 Bad Girl.mp3" thenset played date to date "11/11/2008 22:26:53"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Confidential:04 She's in Love.mp3" thentell track id 39834set played date to date "11/10/2008 21:54:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rickie Lee Jones:Rickie Lee Jones:05 Easy Money.m4a" thentell track id 40340set played date to date "11/11/2008 22:39:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Coldplay:Viva La Vida:03 Lost.mp3" thentell track id 34557set played date to date "11/07/2008 01:12:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Playin' Favorites:04 Mister Magic.mp3" thentell track id 39846set played date to date "11/12/2008 00:58:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alexa Wilkinson:Lions:01 Hitchcock In the Afternoon.mp3" thentell track id 32449set played date to date "11/11/2008 18:58:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Perfect Moment:03 Midnight in Manhattan.mp3" thentell track id 39842set played date to date "11/14/2008 11:46:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fourplay:Fourplay:08 Midnight Stroll.mp3" thentell track id 35745set played date to date "11/13/2008 13:40:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Andrews Sisters:Andrews Sisters Singles:I Want To Be With You Always.m4a" thentell track id 41954set played date to date "11/11/2008 23:02:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Eric Carmen:The Best of Eric Carmen:06 Make Me Lose Control.m4a" thentell track id 35444set played date to date "11/14/2008 00:58:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Vanessa Williams:The Sweetest Days:04 The Sweetest Days.mp3" thentell track id 43349set played date to date "11/13/2008 15:15:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris Rea:The Best of Chris Rea:01 Josephine.mp3" thentell track id 34427set played date to date "11/13/2008 13:01:05"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:03 Who's Cheatin' Who.m4a" thentell track id 32377set played date to date "11/11/2008 22:35:24"if loc = "Macintosh HD:Users:paul:Public:Music:Library:George Winston:Summer:01 Living in the Country.m4a" thentell track id 35972set played date to date "11/14/2008 03:31:38"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Anita Baker:Rapture:03 Caught up in the Rapture.mp3" thentell track id 32709set played date to date "11/13/2008 16:59:51"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Huey Lewis & The News:Greatest Hits_ Huey Lewis & The News:07 If This Is It (2006 Digital Remas.mp3" thentell track id 36386set played date to date "11/13/2008 14:34:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:ZZ Top:Tres Hombres:08 La Grange.mp3" thentell track id 44383set played date to date "11/13/2008 12:11:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:06 Chasin' That Neon Rainbow.m4a" thentell track id 32399set played date to date "11/11/2008 22:58:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Celine Dion:Taking Chances:02 Alone.mp3" thentell track id 34241set played date to date "11/14/2008 03:04:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Hollies:The Hollies' Greatest Hits (Remastered):07 He Ain't Heavy, He's My Brother.mp3" thenset played date to date "11/03/2008 01:35:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Joanna:This Crazy Life:11 Your Obsession.mp3" thentell track id 37044set played date to date "11/10/2008 23:58:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barbra Streisand:The Essential Barbra Streisand:26 Memory.mp3" thentell track id 32977set played date to date "11/14/2008 12:09:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Forrest Gump Soundtrack:2-15 Against The Wind.m4a" thentell track id 43547set played date to date "11/12/2008 01:01:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Johnny Rivers:Secret Agent Man_ The Ultimate Johnny Rivers Anthology 1964-2006:09 Poor Side Of Town.mp3" thentell track id 37323set played date to date "11/13/2008 20:02:11"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Hollies:Super Hits_ The Hollies:03 The Air That I Breathe.mp3" thentell track id 42322set played date to date "11/12/2008 00:27:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sounds Orchestral:Cast Your Fate To The Wind:02 Cast Your Fate To The Wind.mp3" thentell track id 41307set played date to date "11/13/2008 22:07:35"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kenny Rogers:Number Ones:16 Don't Fall In Love With a Dreamer.mp3" thenset played date to date "11/13/2008 15:26:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Santana:Santana's Greatest Hits:06 Black Magic Woman.m4a" thentell track id 40843set played date to date "11/10/2008 23:21:22"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Lennon:Lennon Legend:13 Woman.mp3" thentell track id 37233set played date to date "11/13/2008 16:08:25"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aerosmith:Toys in the Attic:04 Walk This Way.mp3" thenset played date to date "11/11/2008 18:46:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rick Springfield:Success Hasn't Spoiled Me Yet:03 What Kind of Fool Am I.mp3" thentell track id 40323set played date to date "11/10/2008 23:14:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Matt Bianco:Whose Side Are You On:04 Half a Minute.mp3" thentell track id 38503set played date to date "11/14/2008 12:28:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Craig Morgan:Little Bit of Life:01 Little Bit Of Life.mp3" thenset played date to date "11/14/2008 03:26:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lobo:The Best Of Lobo:10 How Can I Tell Her.mp3" thentell track id 38168set played date to date "11/14/2008 20:42:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rod Stewart:Vagabond Heart:03 Broken Arrow.mp3" thentell track id 40490set played date to date "11/13/2008 13:14:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:13 When Somebody Love You.m4a" thentell track id 32387set played date to date "11/13/2008 15:06:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Cat Stevens:Greatest Hits_ Cat Stevens:04 Hard Headed Woman.m4a" thenset played date to date "11/11/2008 23:20:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Miracles:All Time Greatest Hits:12 The Tracks of My Tears.mp3" thenset played date to date "11/14/2008 10:44:30"set played count to 62if loc = "Macintosh HD:Users:paul:Public:Music:Library:Darryl Worley:Have You Forgotten_:01 Have You Forgotten_.m4a" thentell track id 34721set played date to date "11/12/2008 01:24:24"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Boney James:Backbone:05 Blue.m4a" thentell track id 33605set played date to date "11/13/2008 18:20:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:3 Doors Down:The Better Life:01 Kryptonite.mp3" thentell track id 32100set played date to date "11/03/2008 00:05:31"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Billy Ocean:Billy Ocean Greatest Hits:04 There'll Be Sad Songs (To Make You Cry).mp3" thenset played date to date "11/03/2008 00:09:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dido:Life for Rent:03 Life for Rent.mp3" thentell track id 35026set played date to date "11/14/2008 01:13:07"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Emmy Rossum:Inside Out:07 Don't Stop Now.mp3" thentell track id 35395set played date to date "11/13/2008 12:21:38"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:09 Livin' on Love.m4a" thentell track id 32402set played date to date "11/13/2008 11:12:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:14 That's as Close as I'll Get to Lo.m4a" thentell track id 32198set played date to date "11/13/2008 21:56:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Feist:The Reminder:13 How My Heart Behaves.mp3" thentell track id 35585set played date to date "11/13/2008 13:44:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Urban Cowboy:07 Could I Have This Dance.mp3" thentell track id 44030set played date to date "11/11/2008 23:54:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Seals & Crofts:Summer Breeze:04 Summer Breeze.mp3" thenset played date to date "11/10/2008 20:59:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Bellamy Brothers:Bellamy Brothers Greatest Hits, Vol. 1:01 Let Your Love Flow.mp3" thentell track id 42090set played date to date "11/13/2008 10:30:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:01 You've Got to Stand for Something.m4a" thentell track id 32185set played date to date "11/13/2008 13:30:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:When Somebody Loves You:10 Maybe I Should Stay Here.m4a" thentell track id 32425set played date to date "11/13/2008 21:36:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Captain & Tennille:Ultimate Collection_ The Complete Hits:02 The Way I Want To Touch You.mp3" thentell track id 33987set played date to date "11/11/2008 23:43:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Nightnoise:Shadow of Time:08 This Just In.m4a" thentell track id 39410set played date to date "11/10/2008 21:28:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Confidential:11 Endless Journey.mp3" thentell track id 39837set played date to date "11/13/2008 14:30:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sally Anthony:Goodbye:03 So Long.mp3" thentell track id 40713set played date to date "11/14/2008 02:05:22"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Denver:Definitive All-Time Greatest Hits:16 Like a Sad Song.mp3" thentell track id 37176set played date to date "11/13/2008 13:04:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:06 Right On The Money.m4a" thentell track id 32380set played date to date "11/14/2008 12:53:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Ramsey Lewis:The In Crowd:01 The 'In' Crowd.mp3" thentell track id 40199set played date to date "11/12/2008 01:18:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dave Koz:Lucky Man:02 You Make Me Smile.mp3" thentell track id 34805set played date to date "11/11/2008 22:22:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Divine:Fairy Tales:04 Lately.mp3" thentell track id 35073set played date to date "11/13/2008 14:10:55"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Monkees:The Best of the Monkees:20 Daydream Believer.mp3" thentell track id 42456set played date to date "11/02/2008 23:39:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Earth, Wind & Fire:Earth Wind & Fire_ Greatest Hits:16 After the Love Has Gone.mp3" thenset played date to date "11/13/2008 13:08:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:09 Pop A Top.m4a" thentell track id 32383set played date to date "11/13/2008 21:15:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barbra Streisand:The Essential Barbra Streisand:08 He Touched Me.mp3" thentell track id 32959set played date to date "11/13/2008 21:29:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Luther Vandross:Busy Body:06 How Many Times Can We Say Goodbye.mp3" thentell track id 38239set played date to date "11/13/2008 23:55:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Lovers Rock:03 King of Sorrow.mp3" thentell track id 40684set played date to date "11/13/2008 11:24:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:AC-DC:The Razors Edge:01 Thunderstruck.mp3" thentell track id 32231set played date to date "11/13/2008 13:26:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:When Somebody Loves You:07 Life or Love.m4a" thentell track id 32422set played date to date "11/13/2008 15:30:51"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Christopher Cross:Christopher Cross:08 Sailing.m4a" thentell track id 34464set played date to date "11/13/2008 19:33:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Earth, Wind & Fire:Earth Wind & Fire_ Greatest Hits:12 Reasons.mp3" thentell track id 35237set played date to date "11/13/2008 22:40:25"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Singers & Songwriters Volume 1:1-11 Everybody's Talkin'.m4a" thentell track id 43763set played date to date "11/10/2008 23:00:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rod Stewart:The Very Best of Rod Stewart:03 Have I Told You Lately.mp3" thenset played date to date "11/13/2008 17:11:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rufus Featuring Chaka Khan:The Very Best Of Rufus Featuring Chaka K:02 Tell Me Something Good.mp3" thentell track id 40629set played date to date "11/14/2008 11:41:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Robert Plant:Pictures At Eleven:01 Burning Down One Side.mp3" thentell track id 40424set played date to date "11/13/2008 18:30:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Vanessa Carlton:Heroes and Thieves:01 Nolita Fairytale.mp3" thentell track id 43319set played date to date "11/14/2008 12:31:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Nat King Cole:Nat King Cole Singles:You're The Cream In My Coffee.m4a" thentell track id 39172set played date to date "11/03/2008 00:00:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris Isaak:Best Of Chris Isaak:03 Wicked Game.mp3" thentell track id 34413set played date to date "11/14/2008 02:21:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Bon Jovi:Lost Highway:03 (You Want To) Make A Memory.mp3" thentell track id 33588set played date to date "11/12/2008 00:37:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Henry Mancini:Ultimate Pink Panther:01 The Pink Panther Theme.mp3" thentell track id 36284set played date to date "11/14/2008 00:39:58"if loc = "Macintosh HD:Users:paul:Public:Music:Library:James Taylor:James Taylor_ Greatest Hits:10 Mexico.mp3" thenset played date to date "11/13/2008 19:45:51"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Four Tops:The Four Tops 50th Anniversary Anthology:32 Ain't No Woman (Like the One I've Got).mp3" thentell track id 42274set played date to date "11/14/2008 00:06:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Stacie Orrico:Stacie Orrico:08 Strong Enough.mp3" thentell track id 41354set played date to date "11/13/2008 13:24:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:When Somebody Loves You:04 www.memory.m4a" thentell track id 32419set played date to date "11/02/2008 22:59:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fourplay:Yes, Please:06 Save Some Love For Me.mp3" thentell track id 35768set played date to date "11/06/2008 21:10:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Sensational 70s (Original Artist Re-Recording):04 On and On.mp3" thentell track id 43734set played date to date "11/11/2008 18:53:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Enya:Shepherd Moons:05 Angeles.mp3" thentell track id 35428set played date to date "11/13/2008 16:29:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sara Evans:Real Fine Place:08 The Secrets That We Keep.m4a" thentell track id 40894set played date to date "11/13/2008 14:47:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Michael Tomlinson:Face Up in the Rain:02 Safe at Home.m4a" thentell track id 38731set played date to date "11/12/2008 01:11:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Windham Hill Records Sampler '96:09 If You Believe.m4a" thentell track id 44126set played date to date "11/14/2008 01:53:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dana Glover:Testimony:09 Falling Into Love.mp3" thentell track id 34682set played date to date "11/13/2008 13:52:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Trick Pony:Trick Pony:05 More Like Me.m4a" thentell track id 43176set played date to date "11/10/2008 21:44:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Michael Buble:Call Me Irresponsible:09 Everything.mp3" thentell track id 38619set played date to date "11/12/2008 01:08:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Plumb:Beautiful Lumps of Coal:08 Nice, Naive & Beautiful.mp3" thentell track id 40101set played date to date "11/13/2008 22:10:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Mary Wells:My Guy:04 My Guy.mp3" thenset played date to date "11/13/2008 17:50:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Moody Blues:Long Distance Voyager:01 The Voice.mp3" thentell track id 42463set played date to date "11/14/2008 20:33:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Windham Hill Records Sampler '82:09 Clockwork.m4a" thentell track id 44051set played date to date "11/14/2008 21:10:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Herb Alpert:Colors:05 Think About It.m4a" thentell track id 36289set played date to date "11/10/2008 23:35:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris de Burgh:Into the Light:04 The Lady in Red.mp3" thenset played date to date "11/13/2008 16:18:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Seal:Best 1991 - 2004:02 Kiss From A Rose (Album Version).mp3" thentell track id 41022set played date to date "11/14/2008 01:17:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Steely Dan:A Decade of Steely Dan (Remastered):09 Rikki Don't Lose that Number.mp3" thentell track id 41497set played date to date "11/13/2008 13:47:31"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Ashton Shepherd:Sounds So Good:02 Sounds So Good.mp3" thentell track id 32839set played date to date "11/13/2008 14:54:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Harry Chapin:Heads & Tales:06 Taxi (LP Version).mp3" thentell track id 36249set played date to date "11/10/2008 21:13:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:KT Tunstall:Eye To The Telescope:03 Under the Weather.mp3" thentell track id 37859set played date to date "11/13/2008 13:21:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:When Somebody Loves You:02 When Somebody Loves You.m4a" thentell track id 32417set played date to date "11/03/2008 00:51:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Al Jarreau:Breakin' Away:09 Teach Me Tonight.mp3" thentell track id 32341set played date to date "11/13/2008 11:40:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:Stars & Stripes:05 If Her Lovin' Don't Kill Me.m4a" thentell track id 32178set played date to date "11/14/2008 10:48:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rascal Flatts:Rascal Flatts:01 Prayin' For Daylight.mp3" thentell track id 40211set played date to date "11/02/2008 23:14:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Spyro Gyra:Got the Magic:01 Silk & Satin.m4a" thentell track id 41328set played date to date "11/12/2008 00:12:57"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Patti LaBelle:Anthology:13 If You Only Knew.mp3" thentell track id 39547set played date to date "11/13/2008 17:21:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Reo Speedwagon:The Hits_ Reo Speedwagon:14 Ridin' The Storm Out.m4a" thenset played date to date "11/14/2008 11:37:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Steve Azar:Waitin' on Joe:07 One Good Reason Why.m4a" thentell track id 41514set played date to date "11/14/2008 12:16:18"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Norah Jones:Come Away with Me:07 Turn Me On.mp3" thentell track id 39431set played date to date "11/13/2008 12:17:49"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:08 Don't Rock The Jukebox.m4a" thentell track id 32401set played date to date "11/13/2008 22:33:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Waite:The Complete John Waite, Volume One_ Falling Backwards:10 Missing You.mp3" thentell track id 37309set played date to date "11/14/2008 21:06:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Marvin Gaye & Tammi Terrell:United:05 Your Precious Love.mp3" thentell track id 38473set played date to date "11/13/2008 12:08:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:05 Tall, Tall Trees.m4a" thentell track id 32398set played date to date "11/03/2008 00:43:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Love Deluxe:06 Cherish the Day.mp3" thentell track id 40678set played date to date "11/14/2008 11:22:58"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Boney James:Ride:03 R.P.M..m4a" thentell track id 33630set played date to date "11/13/2008 21:23:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Love Deluxe:01 No Ordinary Love.mp3" thentell track id 40673set played date to date "11/14/2008 11:09:58"if loc = "Macintosh HD:Users:paul:Public:Music:Library:State Radio:Us Against the Crown:10 Gunship Politico.mp3" thenset played date to date "11/13/2008 12:40:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:16 Dallas.m4a" thentell track id 32409set played date to date "11/14/2008 00:48:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Lennon:Lennon Legend:15 Watching the Wheels.mp3" thentell track id 37235set played date to date "11/13/2008 15:23:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Trick Pony:On A Mission:01 On a Mission.m4a" thentell track id 43160set played date to date "11/13/2008 23:59:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Neil Diamond:Sweet Caroline:13 Sweet Caroline.mp3" thentell track id 39316set played date to date "11/14/2008 11:13:46"if loc = "Macintosh HD:Users:paul:Public:Music:Library:John Mellencamp:Scarecrow:01 Rain on the Scarecrow.mp3" thentell track id 37273set played date to date "11/10/2008 22:42:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Edie Brickell & New Bohemians:Shooting Rubberbands At The Stars:09 Nothing.mp3" thenset played date to date "11/14/2008 12:19:07"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kiss:Dressed To Kill:10 Rock And Roll All Nite.mp3" thentell track id 37820set played date to date "11/14/2008 01:45:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Big Band Era- Vol. 7:7-03 Sentimental Journey.m4a" thentell track id 43395set played date to date "11/13/2008 19:58:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Hall & Oates:Abandoned Luncheonette:04 She's Gone.mp3" thenset played date to date "11/13/2008 10:59:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:10 You Are the Woman.m4a" thentell track id 32194set played date to date "11/13/2008 23:47:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:Confidential:10 Stormfront.mp3" thentell track id 39836set played date to date "11/13/2008 22:03:49"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Starland Vocal Band:Starland Vocal Band:08 Afternoon Delight.mp3" thentell track id 41409set played date to date "11/14/2008 11:57:46"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Gloria Estefan:Greatest Hits - Gloria Estefan:05 Rhythm Is Gonna Get You.mp3" thenset played date to date "11/13/2008 16:36:55"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Blood, Sweat and Tears:Greatest Hits_ Blood, Sweat and Tears:01 You've Made Me So Very Happy.m4a" thentell track id 33507set played date to date "11/13/2008 10:39:38"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:04 There Ain't Nothin' Wrong With th.m4a" thentell track id 32188set played date to date "11/14/2008 01:03:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:George Michael:Twenty Five:16 Careless Whisper.mp3" thentell track id 35957set played date to date "11/07/2008 00:36:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Richard Marx:Richard Marx - Greatest Hits:16 Right Here Waiting.mp3" thentell track id 40300set played date to date "11/11/2008 23:50:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fourplay:Elixir:08 The Closer I Get To You.mp3" thentell track id 35742set played date to date "11/02/2008 23:03:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Nickel Creek:Nickel Creek:05 Reasons Why.m4a" thentell track id 39370set played date to date "11/11/2008 23:12:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris Rea:The Best of Chris Rea:13 Fool (If You Think It's Over).mp3" thenset played date to date "11/14/2008 20:27:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Johnny Rivers:Secret Agent Man_ The Ultimate Johnny Rivers Anthology 1964-2006:12 Summer Rain.mp3" thentell track id 37326set played date to date "11/13/2008 18:34:18"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alabama:Greatest Hits, Vol. 3_ Alabama:04 When We Make Love.m4a" thentell track id 32353set played date to date "11/13/2008 16:55:59"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:The Best Of Smooth Jazz, Vol. 1:13 Nothin' But Love.m4a" thentell track id 43860set played date to date "11/10/2008 22:32:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:James Taylor:James Taylor_ Greatest Hits, Vol. 2:04 Up On The Roof.mp3" thentell track id 36557set played date to date "11/13/2008 16:47:36"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Pat Benatar:Greatest Hits_ Pat Benatar:01 Heartbreaker.m4a" thentell track id 39519set played date to date "11/14/2008 00:37:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:2-05 I Need To Be In Love.mp3" thentell track id 42119set played date to date "11/13/2008 21:09:36"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barry Manilow:Ultimate Manilow:01 Mandy.mp3" thentell track id 32996set played date to date "11/13/2008 17:03:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The J. Geils Band:Best of the J. Geils Band:04 Love Stinks.mp3" thentell track id 42342set played date to date "11/14/2008 00:22:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Big Band Era- Vol. 7:7-06 I'll Never Smile Again.m4a" thentell track id 43398set played date to date "11/14/2008 02:40:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Seals & Crofts:I'll Play for You:01 I'll Play for You.mp3" thenset played date to date "11/14/2008 01:26:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:The Very Best Of Smooth Jazz Guitar:04 Promenade.m4a" thentell track id 44007set played date to date "11/14/2008 01:42:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Phil Collins:Serious Hits ... Live!:04 One More Night.m4a" thentell track id 39912set played date to date "11/14/2008 11:26:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Huey Lewis & The News:Greatest Hits_ Huey Lewis & The News:04 Jacob's Ladder (2006 Digital Rema.mp3" thentell track id 36383set played date to date "11/13/2008 19:42:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Carl Anderson:Carl Anderson:01 Friends and Lovers.mp3" thentell track id 34008set played date to date "11/13/2008 14:38:31"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Faith Hill:Take Me As I Am:04 Piece Of My Heart.m4a" thentell track id 35553set played date to date "11/13/2008 21:41:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alicia Keys:Songs In a Minor:06 Rock Wit U.mp3" thentell track id 32479set played date to date "11/10/2008 21:57:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Neil Diamond:Moods:01 Song Sung Blue.mp3" thenset played date to date "11/13/2008 17:40:55"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris Rea:Auberge:02 Gone Fishing.m4a" thenset played date to date "11/14/2008 03:14:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Windham Hill Records Sampler '86:01 Welcoming.m4a" thentell track id 44060set played date to date "11/14/2008 00:55:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Jennifer Warnes:The Best of Jennifer Warnes:01 Right Time Of The Night.mp3" thenset played date to date "11/13/2008 12:57:02"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:01 Little Bitty.m4a" thenset played date to date "11/14/2008 03:08:24"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Crystal Gayle:Crystal Gayle_ The Hits:15 Half The Way.mp3" thentell track id 34644set played date to date "11/13/2008 21:51:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Captain & Tennille:Ultimate Collection_ The Complete Hits:07 Muskrat Love.mp3" thenset played date to date "11/06/2008 21:15:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Robin Thicke:The Evolution Of Robin Thicke:08 Teach U a Lesson.mp3" thentell track id 40446set played date to date "11/14/2008 11:18:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Pink Floyd:The Wall:2-09 Run Like Hell.m4a" thenset played date to date "11/11/2008 10:43:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:She & Him:Volume One:02 Why Do You Let Me Stay Here.mp3" thenset played date to date "11/13/2008 18:13:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Brad Paisley:Mud on the Tires:12 Make a Mistake.m4a" thentell track id 33736set played date to date "11/10/2008 21:09:51"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Harry Chapin:Sequel:01 Sequel.m4a" thentell track id 36250set played date to date "11/13/2008 12:54:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:20 I'd Love You All Over Again.m4a" thentell track id 32413set played date to date "11/13/2008 17:16:04"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Brooks & Dunn:Red Dirt Road:13 Red Dirt Road.m4a" thentell track id 33841set played date to date "11/11/2008 23:45:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Hamilton, Joe Frank & Reynolds:Greatest Hits_ Hamilton, Joe Frank & Reynolds:01 Don't Pull Your Love.mp3" thentell track id 36232set played date to date "11/10/2008 22:37:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Anita Baker:Rapture:01 Sweet Love.mp3" thentell track id 32707set played date to date "11/13/2008 19:20:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Phoebe Snow:Never Letting Go:04 Something So Right.mp3" thenset played date to date "11/13/2008 22:23:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Vanessa Williams:The Right Stuff:03 Dreamin'.mp3" thentell track id 43348set played date to date "11/13/2008 12:05:32"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:02 Gone Country.m4a" thentell track id 32395set played date to date "11/02/2008 23:30:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Brad Paisley:Part II:05 Two People Fell in Love.m4a" thentell track id 33746set played date to date "11/13/2008 14:27:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Eric Clapton:Journeyman:11 Lead Me On.m4a" thentell track id 35459set played date to date "11/13/2008 13:18:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:16 Drive (For Daddy Gene).m4a" thentell track id 32390set played date to date "11/07/2008 00:28:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sheriff:Sheriff:04 When I'm with You.mp3" thenset played date to date "11/13/2008 22:47:25"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lobo:The Best Of Lobo:06 I'd Love You to Want Me.mp3" thenset played date to date "11/11/2008 22:31:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fleetwood Mac:Greatest Hits_ Fleetwood Mac:16 No Questions Asked.mp3" thentell track id 35672set played date to date "11/10/2008 21:50:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Richard Elliot:Jumpin' Off:07 In the Groove.mp3" thenset played date to date "11/14/2008 11:28:36"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Christmas Is Coming:09 Soon It Will Be Christmas Day.m4a" thenset played date to date "11/13/2008 21:12:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:England Dan & John Ford Coley:Nights Are Forever:06 Nights Are Forever Without You.mp3" thenset played date to date "11/11/2008 00:08:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Elton John:Madman Across the Water:02 Levon.mp3" thenset played date to date "11/12/2008 01:14:12"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Edie Brickell & New Bohemians:Shooting Rubberbands At The Stars:11 Keep Coming Back.mp3" thenset played date to date "11/13/2008 15:35:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Seals & Crofts:Diamond Girl:01 Diamond Girl.mp3" thentell track id 41023set played date to date "11/13/2008 18:01:30"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chris Rea:Auberge:08 Every Second Counts.m4a" thentell track id 34422set played date to date "11/12/2008 01:21:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:1-07 Bless The Beasts And Children.mp3" thentell track id 42107set played date to date "11/10/2008 21:40:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Michael Bolton:The One Thing:01 Said I Loved You...But I Lied.mp3" thentell track id 38603set played date to date "11/13/2008 11:15:49"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:15 How's The Radio Know.m4a" thentell track id 32199set played date to date "11/14/2008 00:19:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Oleta Adams:Circle of One:02 Get Here.m4a" thentell track id 39436set played date to date "11/10/2008 22:47:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Anita Baker:The Songstress:01 Angel.mp3" thentell track id 32716set played date to date "11/07/2008 00:45:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Steely Dan:A Decade of Steely Dan (Remastered):07 Do It Again.mp3" thentell track id 41495set played date to date "11/11/2008 22:42:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Doors:The Soft Parade:02 Touch Me.mp3" thentell track id 42237set played date to date "11/13/2008 11:02:57"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:11 Cold Chill.m4a" thentell track id 32195set played date to date "11/14/2008 20:58:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dave Mason:Let It Flow:02 We Just Disagree.mp3" thentell track id 34821set played date to date "11/13/2008 14:14:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lynyrd Skynyrd:The Essential Lynyrd Skynyrd:1-02 I Ain't the One.m4a" thentell track id 38310set played date to date "11/13/2008 19:25:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Barbra Streisand:The Essential Barbra Streisand:32 Somewhere.mp3" thentell track id 32983set played date to date "11/10/2008 20:55:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Toni Braxton:Secrets:04 Un-Break My Heart.mp3" thentell track id 42991set played date to date "11/13/2008 12:31:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:13 Home.m4a" thentell track id 32406set played date to date "11/14/2008 00:15:08"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Natalie Cole:Snowfall on the Sahara:10 Since You Asked.m4a" thenset played date to date "11/06/2008 17:43:34"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Perry Como:Como Singles:Magic Moment.m4a" thentell track id 39760set played date to date "11/12/2008 20:06:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chicago:The Very Best of Chicago - Only the Begi:1-12 - Just You 'N' Me.mp3" thentell track id 34291set played date to date "11/10/2008 22:21:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Waiting To Exhale Soundtrack:02 Why Does It Hurt So Bad.mp3" thentell track id 44032set played date to date "11/12/2008 00:51:51"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Patti LaBelle:The Essential Patti Labelle:02 Love, Need and Want You.mp3" thentell track id 39553set played date to date "11/13/2008 13:10:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Greatest Hits Volume II_ Alan Jackson:12 www.memory.m4a" thentell track id 32386set played date to date "11/02/2008 23:08:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Windham Hill Records Sampler '89:04 Usually_Always.m4a" thentell track id 44085set played date to date "11/14/2008 11:53:49"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Paul Simon:Negotiations and Love Songs 1971-1986:05 Loves Me Like a Rock.mp3" thentell track id 39637set played date to date "11/10/2008 22:14:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Luther Vandross:Never Too Much:07 A House Is Not a Home.mp3" thentell track id 38252set played date to date "11/02/2008 23:18:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Clint Black:Greatest Hits II_ Clint Black:07 When I Said I Do.m4a" thenset played date to date "11/13/2008 11:06:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:12 All I Have To Offer You Is Me.m4a" thentell track id 32196set played date to date "11/13/2008 10:36:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:03 Many, Many, Many Beers Ago.m4a" thentell track id 32187set played date to date "11/13/2008 17:52:50"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Big Band Era- Vol. 7:7-08 Traumere.m4a" thentell track id 43400set played date to date "11/13/2008 12:47:33"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:18 Someday.m4a" thentell track id 32411set played date to date "11/14/2008 11:00:08"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kate Voegele:Don't Look Away:05 One Way or Another.mp3" thentell track id 37523set played date to date "11/13/2008 10:14:11"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Phenomenon Soundtrack:03 Crazy Love.mp3" thentell track id 43684set played date to date "11/13/2008 15:10:42"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Trace Adkins:Songs About Me:08 Baby I'm Home.m4a" thentell track id 43097set played date to date "11/13/2008 16:44:08"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Three Dog Night:Three Dog Night - The Complete Hit Singles:15 Pieces Of April.mp3" thenset played date to date "11/13/2008 10:18:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Neville:The Tattooed Heart:01 Can't Stop My Heart from Loving You (The Rain Song).mp3" thentell track id 32159set played date to date "11/13/2008 10:53:28"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:08 She Feels Like A Brand New Man To.m4a" thentell track id 32192set played date to date "11/07/2008 01:02:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Basia:London Warsaw New York:04 Baby You're Mine.mp3" thentell track id 33009set played date to date "11/12/2008 00:15:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Marvin Gaye & Tammi Terrell:United:13 Ain't Nothing Like The Real Thing.mp3" thenset played date to date "11/13/2008 14:57:56"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Lee Brice:Picture Of Me:02 She Ain't Right.mp3" thentell track id 37927set played date to date "11/11/2008 22:47:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Peter White:By Candlelight:08 No Woman No Cry.mp3" thentell track id 39829set played date to date "11/02/2008 23:26:06"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Feist:The Reminder:03 My Moon My Man.mp3" thentell track id 35575set played date to date "11/10/2008 21:46:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Marvin Gaye & Tammi Terrell:United:01 Ain't No Mountain High Enough.mp3" thentell track id 38471set played date to date "11/13/2008 11:55:39"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:Drive:04 Work in Progress.m4a" thentell track id 32364set played date to date "11/13/2008 12:14:58"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:07 I'll Try.m4a" thentell track id 32400set played date to date "11/13/2008 11:09:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:13 Country Boy's Tool Box.m4a" thentell track id 32197set played date to date "11/14/2008 03:00:00"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:The Very Best Of Smooth Jazz Guitar:05 Playing for Time.m4a" thentell track id 44008set played date to date "11/13/2008 10:46:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Tippin:The Essential Aaron Tippin:06 Working Man's Ph.D..m4a" thentell track id 32190set played date to date "11/14/2008 11:03:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Clay Walker:Rumor Has It:18 Then What.m4a" thentell track id 34498set played date to date "11/14/2008 01:57:05"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Enya:Watermark:10 The Longships.mp3" thentell track id 35441set played date to date "11/13/2008 17:26:11"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Michael Tomlinson:Face Up in the Rain:01 Gettin' Gone.m4a" thentell track id 38730set played date to date "11/11/2008 22:55:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Dana Glover:Testimony:04 Cherish.mp3" thentell track id 34680set played date to date "11/07/2008 01:09:17"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Helen Reddy:The Woman I Am_ The Definitive Collection:15 Somewhere in the Night.mp3" thentell track id 36282set played date to date "11/14/2008 10:56:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Kate Voegele:Don't Look Away:03 Only Fooling Myself.mp3" thentell track id 37521set played date to date "11/13/2008 23:50:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Sade:Love Deluxe:04 Like a Tattoo.mp3" thentell track id 40676set played date to date "11/13/2008 11:50:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alabama:Greatest Hits, Vol. 3_ Alabama:01 Give Me One More Shot [#].m4a" thentell track id 32350set played date to date "11/02/2008 23:45:45"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Teddy Pendergrass:Love Language:05 Hold Me.mp3" thentell track id 41790set played date to date "11/13/2008 17:30:08"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Josh Turner:Your Man:05 Loretta Lynn's Lincoln.m4a" thenset played date to date "11/13/2008 15:39:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Toby Keith:Unleashed:09 Ain't It Just Like You.m4a" thentell track id 42951set played date to date "11/13/2008 22:17:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Mamas & the Papas:The Mamas & The Papas Greatest Hits:03 Monday, Monday.mp3" thentell track id 42426set played date to date "11/13/2008 19:54:32"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Chicago:The Very Best of Chicago - Only the Begi:2-15 What Kind Of Man Would I Be_.mp3" thentell track id 34313set played date to date "11/13/2008 18:41:10"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Eric Clapton:The Best Of Eric Clapton 20th Century Masters The Millennium Collection:07 Lay Down Sally.mp3" thentell track id 35468set played date to date "11/13/2008 22:29:16"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Fiona Apple:Tidal:05 Slow Like Honey.mp3" thenset played date to date "11/14/2008 12:21:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Drifters:The Drifters All Time Greatest Hits:10 Save The Last Dance For Me.mp3" thentell track id 42251set played date to date "11/13/2008 12:44:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:17 Here In The Real World.m4a" thentell track id 32410set played date to date "11/14/2008 01:07:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Neil Diamond:Stones:01 I Am...I Said.mp3" thenset played date to date "11/07/2008 00:32:19"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Rod Stewart:The Very Best of Rod Stewart:16 Forever Young.mp3" thentell track id 40487set played date to date "11/13/2008 18:12:23"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Phil Collins:Face Value:06 Hand in Hand.m4a" thentell track id 39901set played date to date "11/13/2008 11:35:03"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Acoustic Alchemy:Against The Grain:08 Papillon.mp3" thentell track id 32238set played date to date "11/11/2008 00:15:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Billy Preston:20th Century Masters_ The Millennium Collection_ Best Of Billy Preston:10 With You I'm Born Again.mp3" thentell track id 33288set played date to date "11/13/2008 20:06:09"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Commodores:The Commodores Anthology:21 Sail On.mp3" thentell track id 42168set played date to date "11/10/2008 23:10:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Toni Braxton:Toni Braxton:02 Breathe Again.mp3" thentell track id 43000set played date to date "11/14/2008 02:29:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Anita Baker:Compositions:01 Talk to Me.mp3" thentell track id 32695set played date to date "11/13/2008 18:24:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Jennifer Love Hewitt:Jennifer Love Hewitt:03 (Our Love) Don't Throw It All Away.mp3" thenset played date to date "11/13/2008 22:14:25"if loc = "Macintosh HD:Users:paul:Public:Music:Library:April Wine:The Nature of the Beast:04 Just Between You and Me.mp3" thentell track id 32780set played date to date "11/10/2008 23:24:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:10cc:Deceptive Bends:02 The Things We Do For Love.mp3" thentell track id 32090set played date to date "11/13/2008 14:04:14"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Shania Twain:Up! (Red Album):03 She's Just Not a Pretty Face.m4a" thenset played date to date "11/14/2008 10:52:40"if loc = "Macintosh HD:Users:paul:Public:Music:Library:James Ingram:Forever More (Love Songs, Hits & Duets):08 Just Once.mp3" thentell track id 36535set played date to date "11/13/2008 10:27:43"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Aaron Neville:Warm Your Heart:02 Everybody Plays the Fool.mp3" thentell track id 32161set played date to date "11/13/2008 16:25:48"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Manfred Mann's Earth Band:The Best of Manfred Mann's Earth Band:07 Quinn The Eskimo.mp3" thentell track id 38376set played date to date "11/14/2008 00:27:29"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Elvin Bishop:Struttin' My Stuff:05 Fooled Around And Fell In Love.m4a" thenset played date to date "11/12/2008 00:35:13"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:2-10 We've Only Just Begun.mp3" thenset played date to date "11/10/2008 21:32:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Celine Dion:The Colour of My Love:08 When I Fall in Love.m4a" thentell track id 34249set played date to date "11/13/2008 12:27:44"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Alan Jackson:The Greatest Hits Collection_ Alan Jacks:11 Love's Got a Hold on You.m4a" thenset played date to date "11/10/2008 22:25:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Firefall:Firefall_ Greatest Hits:06 Just Remember I Love You.mp3" thentell track id 35627set played date to date "11/10/2008 23:31:31"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Pussycat Dolls:Doll Domination:16 I'm Done.mp3" thenset played date to date "11/10/2008 23:54:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Enya:The Memory of Trees:02 Anywhere Is.mp3" thentell track id 35431set played date to date "11/14/2008 12:42:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Carolina Rain:Weather the Storm:02 Get Outta My Way.mp3" thentell track id 34132set played date to date "11/11/2008 23:34:35"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Eric Carmen:In the Can:08 All By Myself.mp3" thenset played date to date "11/13/2008 16:33:26"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Grover Washington & Bill Withers:Love's Greatest Hits:06 Just The Two Of Us.m4a" thentell track id 36200set played date to date "11/03/2008 00:47:21"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Gregory Abbott:Shake You Down:03 Shake You Down.mp3" thentell track id 36187set played date to date "11/13/2008 13:54:37"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Don Gibson:Don Gibson_ All Time Greatest Hits:01 Oh Lonesome Me.mp3" thentell track id 35107set played date to date "11/13/2008 13:38:01"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Amy Grant:Greatest Hits - Amy Grant:04 House of Love.mp3" thentell track id 32636set played date to date "11/07/2008 00:39:27"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Climax:Climax:06 Precious And Few.m4a" thentell track id 34499set played date to date "11/12/2008 00:24:15"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Diane Schuur:The Best of Diane Schuur:02 Try A Little Tenderness.m4a" thenset played date to date "11/13/2008 19:50:11"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Restless Heart:Wheels:03 I'll Still Be Loving You.mp3" thenset played date to date "11/14/2008 01:48:41"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Various Artists:Singers & Songwriters Volume 2:2-02 Longer.m4a" thentell track id 43766set played date to date "11/10/2008 22:56:20"if loc = "Macintosh HD:Users:paul:Public:Music:Library:Steely Dan:A Decade of Steely Dan (Remastered):01 FM.mp3" thentell track id 41490set played date to date "11/14/2008 00:44:54"if loc = "Macintosh HD:Users:paul:Public:Music:Library:U2:The Joshua Tree:03 With or Without You.mp3" thenset played date to date "11/12/2008 00:40:52"if loc = "Macintosh HD:Users:paul:Public:Music:Library:The Carpenters:Yesterday Once More-Greatest Hits 1969-1:1-09 There's A Kind Of Hush.mp3" thenset loc to location as stringset low_date to date "1/1/1990 00:00:00"display alert "ERROR: " & errMsg giving up after 6set position to {x_origin, y_origin}set y_origin to round ((screen_height - window_height) / 2) rounding as taught in schoolset x_origin to round ((screen_width - window_width) / 2) rounding as taught in schoolset window_height to item 2 of window_sizeset window_width to item 1 of window_sizeset window_size to sizeset window_prop to propertiesdisplay alert "Full Screen Mode is Active" giving up after 6if value of attribute "AXFullScreen" thenif front window exists thentell process the_frontmostset the_frontmost to name of first item of (processes whose frontmost is true)set screen_height to item 4 of screen_sizeset screen_width to item 3 of screen_sizeset screen_size to bounds of window of desktopreturn batteryLevelTextkey code 53 -- esc keyset batteryLevelText to title of batteryLevelMenuItemtell batteryLevelMenuItemset batteryLevelMenuItem to (menu item 3 of menu 1)tell deviceMenuItemset deviceMenuItem to (menu item deviceName of menu 1)tell bluetoothMenuset bluetoothMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth")set deviceName to "Patrick Wu's AirPods"end MakeBarsset OutputBar to OutputBar & my CWhite & "]"repeat PercentageLeft timesset OutputBar to OutputBar & my SeparatorColor & "|" & my FreeColorset OutputBar to OutputBar & "❙"repeat PercentageFull timesset OutputBar to "[" & my UsedColorset PercentageLeft to 10 - PercentageFullon MakeBars(PercentageFull)end removetextset orig to theTextItems as stringset theTextItems to text items of origset AppleScript's text item delimiters to texttoremoveon removetext(orig, texttoremove)return origset orig to text 1 thru -2 of origrepeat until orig does not end with " "set orig to text 2 thru -1 of origrepeat until orig does not start with " "on trim(orig)end cutforwardset orig to origset orig to text item 1 of origset AppleScript's text item delimiters to pontoif orig contains ponto thenon cutforward(orig, ponto)set msg to msg1 & return & msg2set msg1 to characters 1 thru -4 of msg1 as stringset msg2 to FBold & "OS:" & text item 2 of msgset msg1 to text item 1 of msgset AppleScript's text item delimiters to "OS:"if NumberOfChars > 450 thenset NumberOfChars to count characters of msgrepeat until msg does not end with "•"set msg to text 1 thru -2 of msgrepeat until msg does not end with " "set msg to msg & FBold & "Script: " & FBold & scriptname & " " & CurrentVersion & ItemDelimiterif ViewScriptVersion thenset msg to msg & FBold & "Client: " & FBold & ClientName & " " & ClientVersion & ItemDelimiterif ViewClient thenset msg to msg & FBold & "Up: " & FBold & uptime & ItemDelimiterset uptime to temp1 & " " & temp2set temp2 to text items 2 thru end of uptimeset temp1 to text item 1 of uptimeif uptime contains " " thenset uptime to do shell script "uptime | awk '{sub(/.*up[ ]+/,\"\",$0) ; sub(/,[ ]+[0-9]+ user.*/,\"\",$0);sub(/,/,\"\",$0) ;print $0}'"if ViewUptime thenset msg to msg & " (" & KernelTag & ")"if ViewKernelTag thenset msg to msg & FBold & "Kernel: " & FBold & KernelVersionset KernelTag to text item 4 of KernelInfo as stringset KernelVersion to text items 1 thru 2 of KernelInfo as stringset KernelInfo to (do shell script "uname -a | awk {'print $1,$3,$14'} | awk -F':' {'print $1,$2'} | awk -F'/' {'print $1'}")if ViewKernel thenset msg to msg & OSXArchset OSXArch to "i386"set OSXArch to "x64"if (do shell script "uname -m") is "x86_64" thenif ViewOSXArch thenset msg to msg & OSXBuildset OSXBuild to "[" & item 3 of OSXInfo & "] "if ViewOSXBuild thenset msg to msg & FBold & "OS: " & FBold & OSName & " " & item 2 of OSXInfo & " "set OSName to "macOS"set OSName to "Mac OS X"if majorversion = 10 and minorversion < 12 thenset minorversion to text item 2 of OSVersionset majorversion to text item 1 of OSVersionset OSVersion to item 2 of OSXInfoset OSXInfo to the paragraphs of (do shell script "sw_vers | awk -F\"\\t\" '/BuildVersion:|ProductVersion|ProductName/ {print $2}'")if ViewOSXVersion thenset msg to msgset msg to msg & FBold & "Power: " & FBold & BatteryCapacity & TimeLeft & ItemDelimiterset TimeLeft to space & "[" & text item 3 of PowerInfo & "]"set TimeLeft to ""else if TimeLeft is "0:00" thenset TimeLeft to space & "[-:--]"if TimeLeft contains "(no" thenset TimeLeft to text item 3 of PowerInfoset BatteryCapacity to BatteryCapacity & " (Not charging)"set BatteryCapacity to CRed & BatteryCapacity & CWhiteelse if BatteryStatus is "discharging" thenset BatteryCapacity to CGreen & BatteryCapacity & CWhiteif BatteryStatus is "charging" thenset BatteryStatus to text item 2 of PowerInfoset BatteryCapacity to text item 1 of PowerInfoset PowerInfo to do shell script "pmset -g ps | head -n2 | tail -n1 | awk {'print $3,$4,$5'}"set PowerInfo to do shell script "pmset -g ps | head -n2 | tail -n1 | awk {'print $2,$3,$4'}"if ViewPower thenset msg to msg & FBold & "Audio: " & FBold & AudioCard & ItemDelimiterset AudioCard to "Unknown"set AudioCard to "AppleHDA"else if AudioCard contains "AppleHDA" thenset AudioCard to "VoodooHDA"if AudioCard contains "VoodooHDA" thenset AudioCard to do shell script "kextstat | grep HDA"if ViewAudio thenset msg to msg & ResolutionsGPU2set ResolutionsGPU2 to ""set ResolutionsGPU2 to ResolutionMonitor4 & " & " & ResolutionMonitor5 & " & " & ResolutionMonitor6set ResolutionMonitor6 to item 6 of GPU2else if ScreensGPU2 is 3 thenset ResolutionsGPU2 to ResolutionMonitor4 & " & " & ResolutionMonitor5set ResolutionMonitor5 to item 5 of GPU2else if ScreensGPU2 is 2 thenset ResolutionsGPU2 to ResolutionMonitor4set ResolutionMonitor4 to item 4 of GPU2if ScreensGPU2 is 1 thenset msg to msg & ResolutionsGPU1set msg to msg & ResolutionsGPU1 & " & "if ScreensGPU1 is not 0 and ScreensGPU2 is not 0 thenset ResolutionsGPU1 to ""set ResolutionsGPU1 to ResolutionMonitor1 & " & " & ResolutionMonitor2 & " & " & ResolutionMonitor3set ResolutionMonitor3 to item 6 of GPU1else if ScreensGPU1 is 3 thenset ResolutionsGPU1 to ResolutionMonitor1 & " & " & ResolutionMonitor2set ResolutionMonitor2 to item 5 of GPU1else if ScreensGPU1 is 2 thenset ResolutionsGPU1 to ResolutionMonitor1set ResolutionMonitor1 to item 4 of GPU1if ScreensGPU1 is 1 thenset msg to msg & FBold & "Res: " & FBoldif ViewResolutions thenset msg to msg & FBold & "GPU: " & FBold & VideoCard & " "set VideoCard to "2x" & VideoCard1 & VideoMemory1if VideoCard1 is equal to VideoCard2 thenset VideoCard to VideoCard1 & VideoMemory1 & " & " & VideoCard2 & VideoMemory2set ActiveGPU to 2set VideoCard to CGrey & VideoCard1 & VideoMemory1 & CWhite & " & " & VideoCard2 & VideoMemory2else if ScreensGPU1 is 0 thenset VideoCard to VideoCard1 & VideoMemory1 & " & " & CGrey & VideoCard2 & VideoMemory2 & CWhiteif ScreensGPU2 is 0 thenset ActiveGPU to 1set NrOfScreens to ScreensGPU1 + ScreensGPU2set ScreensGPU2 to ((count of items of GPU2) - 3)set VideoMemory2 to " [" & item 3 of GPU2 & "]"set VideoMemory2 to " [" & item 3 of GPU2 & VideoCardBus2 & "]"set VideoCardBus2 to ", " & item 2 of GPU2set VideoCard2 to item 1 of GPU2set GPU2 to items GPUtwo thru (count of items of SPGraphicsInfo) of SPGraphicsInfoset GPU1 to items 1 thru (GPUtwo - 1) of SPGraphicsInfoset VideoCard to VideoCard1 & VideoMemory1set ScreensGPU2 to 0set ScreensGPU1 to ((count of items of GPU1) - 3)set VideoMemory1 to " [" & item 3 of GPU1 & "]"set VideoMemory1 to " [" & item 3 of GPU1 & VideoCardBus1 & "]"if ViewGFXBus thenset VideoCardBus1 to ", " & item 2 of GPU1set VideoCard1 to item 1 of GPU1set GPU1 to items 1 thru (count of items of SPGraphicsInfo) of SPGraphicsInfoif GPUtwo is 0 thenset GPUtwo to GPUItemLoopset GPUone to GPUItemLoopif GPUone is 0 thenif i contains "AMD" or i contains "ATI" or i contains "NVIDIA" or i contains "INTEL" thenset GPUItemLoop to GPUItemLoop + 1repeat with i in SPGraphicsInfoset ActiveGPU to 0set GPUItemLoop to 0set GPUtwo to 0set GPUone to 0set GPU2 to {}set GPU1 to {}set SPGraphicsInfo to the paragraphs of (do shell script "system_profiler SPDisplaysDataType | awk -F: ' /Chipset|Bus|Resolution|VRAM/ {print $NF}' | sed 's/^.//g' | awk -F' @' '{print $1}'") as listset msg to msg & " " & OutputBarset OutputBar to MakeBars(UsedHDDBar)set msg to msg & FBold & "SSD: " & FBold & (UsedSpace) & UsedSpaceUnit & "/" & TotalSpace & TotalSpaceUnitset msg to msg & FBold & "HDD: " & FBold & (UsedSpace) & UsedSpaceUnit & "/" & TotalSpace & TotalSpaceUnitif isSSD is "No" thenset UsedHDDBar to round (((UsedSpaceBar) / TotalSpaceBar) * 100) / 10 as integerset diskTotals to do shell script "diskutil info " & the quoted form of volume & " | awk '/Total Space|Volume Free Space/' | awk -F':' {'print $2'} | tr -d ' ' | awk -F'(' {'print $2'} | awk -F'B' {'print $1'}"set diskTotals to do shell script "diskutil info " & the quoted form of volume & " | awk '/Container Total Space|Container Free Space/' | awk -F':' {'print $2'} | tr -d ' ' | awk -F'(' {'print $2'} | awk -F'B' {'print $1'}"if testforcontainer contains "Container" thenset testforcontainer to do shell script "diskutil info " & the quoted form of volumeset UsedSpaceUnit to "GB"set UsedSpaceUnit to "TB"set UsedSpace to roundThis(UsedSpace / 1000, 1)set UsedSpaceBar to UsedSpaceif UsedSpace ≥ 1000 thenset TotalSpaceUnit to "GB"set TotalSpaceUnit to "TB"set TotalSpace to roundThis(TotalSpace / 1000, 1)set TotalSpaceBar to TotalSpaceif TotalSpace ≥ 1000 thenset UsedSpace to TotalSpace - FreeSpaceset FreeSpace to FreeSpace + FreeSpaceDset TotalSpace to TotalSpace + TotalSpaceDset FreeSpaceD to roundThis((the second paragraph of diskTotals as integer) / 1.0E+9, 1)set TotalSpaceD to roundThis((the first paragraph of diskTotals as integer) / 1.0E+9, 1)set diskTotals to do shell script "diskutil info " & the quoted form of volume & " | awk '/Total Size|Volume Free Space/' | awk -F':' {'print $2'} | tr -d ' ' | awk -F'(' {'print $2'} | awk -F'B' {'print $1'}"repeat with volume in volumesListif {allVolumesList's item i} is not in DisksToDelete then set volumesList's end to allVolumesList's item irepeat with i from 1 to count allVolumesListset volumesList to {}set DisksToDelete to {"VM", "Preboot", "Update", "home", "mnt1"}set FreeSpace to ""set TotalSpace to ""return "/debug Error returning Hard Disk space values, please contact the author @ xeon4d@gmail.com"if (count of allVolumesList) is less than 1 thenset allVolumesList to (name of every disk whose local volume is true and ejectable is false and format is Mac OS Extended format or format is NFS format) as listset isSSD to do shell script "diskutil info /dev/rdisk0 | grep 'Solid State' | awk {'print $(NF)'}"if ViewDisk thenset msg to msg & " " & MakeBars(UsedMemoryBar)if ViewBars thenset msg to msg & FBold & "RAM: " & FBold & UsedMemory & UsedMemoryUnit & "/" & TotalMemory & TotalMemoryUnitset UsedMemoryUnit to "MB"set UsedMemoryUnit to "GB"set UsedMemory to roundThis((UsedMemory / 1024), 2)if UsedMemory ≥ 1024 thenset TotalMemoryUnit to "MB"set TotalMemoryUnit to "GB"set TotalMemory to roundThis((TotalMemory / 1024), 2)if TotalMemory ≥ 1024 thenset UsedMemoryBar to round ((UsedMemory / TotalMemory) * 100) / 10 as integerset UsedMemory to (TotalMemory - (the (last word of (do shell script "vm_stat | grep free")) * 4096) / (1048576) as integer)set TotalMemory to (round (do shell script "sysctl -n hw.memsize") / 1048576)if ViewRam thenset msg to msg & ItemDelimiterset msg to msg & FBold & " L2: " & FBold & (cpucache / 1048576 as integer) & "MB"set cpucache to do shell script "sysctl -n hw.l2cachesize"set msg to msg & FBold & " L3: " & FBold & (cpucache / 1048576 as integer) & "MB"set cpucache to do shell script "sysctl -n hw.l3cachesize"if CPUModel contains "Core(TM) i" thenif ViewCPUCache thenset msg to msg & "]"set msg to msg & "" & "/Octa"if corecheck is 8 thenset msg to msg & "" & "/Hexa"if corecheck is 6 thenset msg to msg & "" & "/Quad"if corecheck is "4" thenset msg to msg & "/Dual"if corecheck is "2" thenset msg to msg & "" & "/64-bit"if extfeatures contains "EM64T" thenset msg to msg & "" & "/VMX"if extfeatures contains "VMX" thenset msg to msg & "" & "HT"if features contains "HT" thenset msg to msg & " ["set extfeatures to do shell script "sysctl -n machdep.cpu.extfeatures"set features to do shell script "sysctl -n machdep.cpu.features"set corecheck to do shell script "sysctl -n machdep.cpu.core_count"if ViewCPUCapabilities thenset msg to msg & " @ " & "" & (CPUFrequency * 1000 as integer) & "MHz"set msg to msg & " @ " & "" & roundThis(CPUFrequency, 2) & "GHz"if CPUFrequency ≥ 0.99 thenset CPUFrequency to ((CPU speed of (system info)) / 1000) as realif ViewCurrentCPUSpeed thenset msg to msg & FBold & "CPU: 2x " & FBold & CPUModelFixedset msg to msg & FBold & "CPU: " & FBold & CPUModelFixedif NRofCPUs is "1" thenset CPUModelFixed to "Intel Core 2" & CPUModelFixedset CPUModelFixed to my removetext(CPUModelFixed, "Intel ")set CPUModelFixed to my removetext(CPUModelFixed, "Core2")if CPUModelFixed contains "Core2" thenset CPUModelFixed to my cutforward(CPUModelFixed, "@")set CPUModelFixed to my removetext(CPUModelFixed, " ")set CPUModelFixed to my removetext(CPUModelFixed, "GHz")set CPUModelFixed to my removetext(CPUModelFixed, " CPU")set CPUModelFixed to my removetext(CPUModelFixed, "Processor")set CPUModelFixed to my removetext(CPUModelFixed, "(TM)")set CPUModelFixed to my removetext(CPUModel, "(R)")set CPUModel to do shell script "sysctl -n machdep.cpu.brand_string"set NRofCPUs to do shell script "sysctl -n hw.packages"set msg to msg & FBold & "Mac: " & FBold & machineName & ItemDelimiterset machineName to "Unknown"if machineName is "" thenset machineName to text item 1 of machineName & "\"" & text item 2 of machineNameset AppleScript's text item delimiters to "-inch"if machineName contains "-inch" thenif machineName is not "" thenset machineName to ""set machineName to do shell script "defaults read " & plistpathset machineName to AppleResponse's text item 1set AppleScript's text item delimiters to ""set AppleResponse to AppleResponse's text item 2set AppleScript's text item delimiters to ""set AppleResponse to do shell script "curl https://support-sp.apple.com/sp/product\\?cc\\=" & SNIdentifier & "\\&land\\=en_US"set AppleResponse to do shell script "curl https://support-sp.apple.com/sp/product?cc=G8WN&land=en_US"if isMonterey is false thenset SNIdentifier to do shell script "system_profiler SPHardwareDataType | grep Serial | awk -F\\: {'print $2'} | awk '{ print substr( $0, length($0) - 3, length($0) ) }'"else if SNLength is 13 thenset SNIdentifier to do shell script "system_profiler SPHardwareDataType | grep Serial | awk -F\\: {'print $2'} | awk '{ print substr( $0, length($0) - 2, length($0) ) }'"if SNLength is 12 thenset SNLength to count characters of (do shell script "system_profiler SPHardwareDataType | grep Serial | awk -F\\: {'print $2'}")if ViewMac thenset isMonterey to falseset isMonterey to trueif montereytest contains "12." thenset montereytest to do shell script "sw_vers | grep ProductVersion | awk -F':' {'print $2'}"set msg to """/echo Coded by " & ScriptAuthor & " - " & ScriptAuthorHomepage & NewLine"/echo Homepage: " & ScriptHomepage & NewLine & ¬"/echo " & FBold & scriptname & " " & CurrentVersion & FBold & " - " & ScriptDescription & NewLine & ¬if cmd is "about" then"/echo The 'version' label outputs the current version and some information to the current channel/private conversation.""/echo The 'simple' label makes the script output without any formatting (colors, bold, etc...); " & NewLine & ¬"/echo There are also some special labels: 'about' shows some info about the script; " & NewLine & ¬"/echo Possible labels:" & NewLine & "/echo mac, cpu, speed, cap, cache, fsb, temp, ram, bar, mem, hd, gpu, res, audio, power, osx, osxbuild, osxarch, kernel, kerneltag, uptime, client." & NewLine & ¬"/echo If run without arguments, it'll show a predefined set of system details that can be customized by typing '/" & scriptname & " options'" & NewLine & ¬"/echo " & FBold & "Usage:" & FBold & " /" & scriptname & " [labels] [simple]" & NewLine & ¬set msg to ¬if cmd is "help" thenreturn "/echo The script " & FBold & "will remove" & FBold & " the formatting from the output."do shell script "defaults write xeon3d.si Simple True"else if Simple is "False" thenreturn "/echo The script " & FBold & "won't remove" & FBold & " the formatting from the output."do shell script "defaults write xeon3d.si Simple False"if Simple is "True" thenif cmd is "simple toggle" thenreturn "/echo The final delimiter is now being HIDDEN!"do shell script "defaults write xeon3d.si HideLastDelimiter True"return "/echo The final delimiter is now being SHOWN!"do shell script "defaults write xeon3d.si HideLastDelimiter False"if cmd is "HideLastDelimiter toggle" thenset msg to "/echo The last dot (delimiter) is currently " & FBold & "BEING" & FBold & " shown. To change this type '/" & scriptname & " HideLastDelimiter toggle'"else if HideLastDelimiter is "False" thenset msg to "/echo The last dot (delimiter) is currently " & FBold & "NOT" & FBold & " being shown. To change this type '/" & scriptname & " HideLastDelimiter toggle'"if HideLastDelimiter is "True" thenif cmd is "HideLastDelimiter" then"/echo • Simple - Defines if the formatting is removed from the output of the script." & FBold & " - Current Status: " & FBold & CRed & Simple & NewLine"/echo • HideLastDelimiter - Defines if the script should hide the final delimiter (as there are no more fields after." & FBold & " - Current Status: " & FBold & CRed & HideLastDelimiter & NewLine & ¬"/echo To change an option type '/" & scriptname & " " & theColumns & ""set theString to (theString & ""set theString to theString & ""set theColumns to theColumns & ""repeat with i from 1 to length of theDaysset theColumns to "" --the blank column for the Weekset theStart to date "Monday, March 31, 2014 at 12:00:00 AM" -- Monday of the week courses startset theDays to "mwf" -- Tuesday and Thursdayset color of frame to bcolornameset color to colornameset height of bounds to hoydeset width of bounds to breddeset top of bounds to toppset left of bounds to lefset bcolorname to (item 11 of res) as textset colorname to (item 9 of res) as textset hoyde to (item 4 of res) as textset bredde to (item 3 of res) as textset topp to (item 2 of res) as textset lef to (item 1 of res) as textset res to controlsResultsset {buttonName, controlsResults} to display enhanced window "cmd + M replacement by EMN" acc view width accViewWidth acc view height theTop acc view controls {theLeft, theRight, theTopp, theHeight, leftLabel, topLabel, widthLabel, heightLabel, colorPopup, popupLabel, bcolorPopup, bpopupLabel, bwidth} buttons theButtons active field theLeft with align cancel buttonset {bcolorPopup, bpopupLabel} to create labeled popup stylelist left inset 0 bottom 30 popup width 100 max width 200 label text "Border" popup left 70 initial choice bcolorset {colorPopup, popupLabel} to create labeled popup stylelist left inset 0 bottom 60 popup width 100 max width 200 label text "Box Color" popup left 70 initial choice fargeset {heightLabel} to create label "Height" bottom 110 max width accViewWidth control size regular sizeset {widthLabel} to create label "Width" bottom 140 max width accViewWidth control size regular sizeset {topLabel} to create label "Top" bottom 170 max width accViewWidth control size regular sizeset {leftLabel} to create label "Left" bottom 200 max width accViewWidth control size regular sizeset {bwidth} to create field bwidth placeholder text "Border" bottom 0 left inset 71 field width 80set {theHeight} to create field hoyde placeholder text "Height" bottom 110 left inset 70 field width 150set {theTopp} to create field bredde placeholder text "Width" bottom 140 left inset 70 field width 150set {theRight} to create field topp placeholder text "Right" bottom 170 left inset 70 field width 150set {theLeft} to create field venstre placeholder text "Left" bottom 200 left inset 70 field width 150set {theButtons, minWidth} to create buttons {"Cancel", "OK"} default button 2 cancel button 1set theTop to 220set accViewWidth to 210set bcolor to name of bcolorset farge to name of fargeset hoyde to hoyde as textset topp to topp as textset venstre to venstre as textset bredde to bredde as textset controlLeft to 44set bwidth to width of frameset bcolor to color of frameset farge to colorset hoyde to height of boundsset bredde to width of boundsset topp to top of boundsset venstre to left of boundstell current box of document 1 of application "QuarkXPress 2018"set stylelist to stylelist & ["Svart", "Magenta", "Cyan", "Gul"]if first character of navn is ":" thenset navn to name of item i of a as stringif (count of a) > 14 thenset stylelist to stylelist & bset b to name of item i of arepeat with i from 1 to count of aif (count of a) < 15 thenset stylelist to ["None"]set a to color specs of document 1 as listuse script "Dialog Toolkit Plus" version "1.1.2"return "Not Playing"do JavaScript "document.getElementById(\"movie_player\").playVideo();"do JavaScript "document.getElementById(\"movie_player\").pauseVideo();"if status is 1 thenset status to (do JavaScript "document.getElementById(\"movie_player\").getPlayerState();")log "CONTROLLING " & logurlset logurl to URLset controlTabURL to the first item of listOfYoutubeTabsreturn dateRecordset dateRecord to {d1:d1, d2:d2}set d2 to (d2) --NSDate 01-05-xxxxset d1 to (d1) --NSDate 01-04-xxxxset d2 to d2 - (1 * days) --Correct lastDay value date 31-04-xxxxset d2 to my makeASDateFrom:(d2) --date 01-05-xxxxset d1 to my makeASDateFrom:(d1) --date 01-04-xxxxif ASdate is true thenset ASdate to true -- If true NSDate will be converted to ASDateset d2 to (item 2 of firstLastDates) --NSDate 31-04-xxxxset d1 to (item 1 of firstLastDates) --NSDate 01-04-xxxxend firstLastMonthselectedreturn {(firstDay), (lastDay)}set lastDay to endDateset firstDay to lastMonthset endDate to startDate's dateByAddingTimeInterval:(monthLength - 0)set {success, startDate, monthLength} to currentCalendar's rangeOfUnit:monthUnit startDate:(reference) interval:(reference) forDate:lastMonthset lastMonth to currentCalendar's dateByAddingUnit:monthUnit value:0 toDate:(nsdateselected) options:0set currentCalendar to current application's NSCalendar's currentCalendar()set monthUnit to current application's NSCalendarUnitMonthon firstLastMonthselected(nsdateselected)set firstLastDates to firstLastMonthselected(selected_month_date)end stringToDatereturn "Sorry but that's not a valid date"set d to (item 1 of m)'s |date|()if (count m) > 0 thenset m to its ((NSDataDetector's dataDetectorWithTypes:(its NSTextCheckingTypeDate) |error|:(missing value))'s matchesInString:thisString options:0 range:{0, length of thisString})on stringToDate(thisString) --set selected_month_date to my stringToDate(("1 " & selected_month))on monthsAgo(m)set selected_month to choose from list monthList with prompt "Selecteer de betreffende maand: " OK button name "Ga door" cancel button name "Annuleren"set monthList to {monthsAgo(0), monthsAgo(1), monthsAgo(2), monthsAgo(3), monthsAgo(4), monthsAgo(5), monthsAgo(6)}set VPNservice to the service VPNnamerepeat with VPNname in VPNservicesset VPNservices to the name of every service whose (kind is greater than 11 and kind is less than 16) and connected of current configuration is truedo shell script "screencapture -is ~/Desktop/" & timeFormatted & ".png"do shell script "defaults write com.apple.screencapture name " & timeFormatted & "&& killall SystemUIServer"if application "Google Chrome" is not running thenclick menu item PROFILE of menu 1 of menu bar item "People" of menu bar 1set PROFILE to "YOURPROFILEHERE"tell application id "com.runningwithcrayons.Alfred-3" to search "SelectedText"do shell script "sips -s format jpeg -s formatOptions 70 " & thePathShellreturn projectTextdo shell script "echo '' > " & notesDirectory & quoted form of projectText & ".md"do shell script "echo " & (quoted form of ("[[" & projectText & "]]")) & " >> " & (quoted form of projectsFilePath)set projectText to newCode & " | " & projectNameset projectName to "%filltext:name=field 1%"set newCode to currentYear & "-" & numberStringset numberString to "0001"set numberString to text ((length of newNumber) - 3) thru (length of newNumber) of newNumberset newNumber to "0000" & ((existingCode as number) + 1) as stringif existingYear = currentYear thenset currentYear to year of (current date) as stringset existingYear to "1900"set existingCode to last text item of dateCodeset existingYear to text 3 thru 6 of (first text item of dateCode)set dateCode to first text item of projectsListset AppleScript's text item delimiters to " | "if projectsList is not equal to "" thenset projectsList to last item of (read projectsFilePath using delimiter linefeed)set projectsFilePath to (the POSIX path of (notesDirectory & projectsFileName))do shell script "echo '' > " & quoted form of (the POSIX path of (notesDirectory & projectsFileName))if exists (notesDirectory & projectsFileName) as POSIX file thenset projectsFileName to "project-codes.md"set notesDirectory to "/Users/joebuhlig/notes.joebuhlig/notes/"error "Couldn't open Manage Data Sources - " & errMsg number errNumclick (first menu item of menu 1 of menu item "Manage" of menu 1 of menu bar item "File" of menu bar 1 whose name starts with "External Data Source")if fmGUI_NameOfFrontmostWindow() does not start with "Manage External Data Sources" thenperform action 1 of button 1 of group 1 of window 1 of theProcessclick menu bar item 2 of menu bar 1 of theProcessset theProcess to first application process whose name is "ControlCenter"get name of first person whose (email_address is in (value of every email))tell application "Address Book"end nameAndSuffixFromFileNamereturn {theName, suffix}if suffix contains " " or theName is "" or suffix is "" thenset suffix to text item -1 of fileNameset theName to (text items 1 thru -2 of fileName) as textif fileName contains "." thenset suffix to ""set theName to fileNameon nameAndSuffixFromFileName(fileName)log nameAndSuffixFromFileName("archive.tar.gz")log nameAndSuffixFromFileName(".DS_Store")log nameAndSuffixFromFileName("Librarian.nib")set visible of application process app_name to falseif visible of process app_name is true thenend stripMarkFromTagListreturn newTagListset the end of newTagList to tagNameset the end of newTagList to ((characters 1 through -3 of tagName) as text)if (last character of tagName) is "•" thenrepeat with tagName in (tagNamesList)set newTagList to {}on stripMarkFromTagList(tagNamesList)end updateTagDisplayListset (item theDisplayTagId of tagDisplayList) to (item theDisplayTagId of tagDisplayList) & " •"if (last character of (item theDisplayTagId of tagDisplayList)) is not " •" then -- if the tag doesn't already have a mark then add oneif ((name of theTag as text) = (theActualTag as text)) thenlog (get theActualTag) & " : " & (get name of theTag)set theActualTag to item theDisplayTagId of gTagListset theDisplayTag to item theDisplayTagId of tagDisplayListrepeat with theDisplayTagId from 1 to (length of tagDisplayList)repeat with theTag in (tags of theTask)on updateTagDisplayList(tagDisplayList, theTask)end getTagdisplay dialog msgset msg to (theTagName & " is not a tag in your Omnifocus document. Please fix the script configuration.")return theTagname of theTagset theTag to the first flattened tag of front document where its name = theTagNameon getTag(theTagName)end getTagsFromTagNamesreturn TheTagsset TheTags to TheTags & {(my getTag(theTagName))}repeat with theTagName in tagNamesset TheTags to {}on getTagsFromTagNames(tagNames)end pickTagsFromListset tagNames to tagListset tagNames to dialogResultset dialogResult to (choose from list tagDisplayList with prompt "Pick one or more tags to toggle" with title "Toggle Omnifocus Tag" with multiple selections allowed)on pickTagsFromList(tagDisplayList)end pickOneTagFromListmy getTag(tagName)set tagName to item 1 of tagListset tagName to item 1 of dialogResultif dialogResult is false thenset dialogResult to (choose from list tagList with prompt "Pick a tag to toggle" with title "Toggle Omnifocus Tag")if length of tagList is greater than 1 thenset tagList to gTagListglobal gTagListon pickOneTagFromList()end toggleTagadd theTag to tags of theTaskremove theTag from tags of theTaskif (id of theItem) = (id of theTag) thenrepeat with theItem in tags of theTaskon toggleTag(theTask, theTag)end toggleMultipleTagsmy toggleTag(theTask, theTag)repeat with theTag in TheTagson toggleMultipleTags(theTask, TheTags)my toggleMultipleTags(theTask, tagsToToggle)set TheTags to tags of theTasklog (get theTask)set tagsToToggle to my getTagsFromTagNames(tagsNames)log (get tagsNames)set tagsNames to my stripMarkFromTagList(tagsNames)if tagsNames is missing value -- if the user cancel the pick listset tagsNames to my pickTagsFromList(tagDisplayList)my updateTagDisplayList(tagDisplayList, theTask)log ("task name: " & name of theTask)repeat with theTask in theTasksSelectedlog (get "gTagList" & gTagList)log ("tagDisplayList" & (get tagDisplayList))copy gTagList to tagDisplayList -- need to do a deep copy hereset gTagList to {"Wait For","Today", "Tomorrow", "This week","Someday","This month","Weekend"}keystroke theCharrepeat with theChar in (every character of dt)set dt to (short date string of (get current date))return defaultMeetingreturn fallbackMeetingif fallbackMeeting is not "" thencopy s to fallbackMeetingif (fallbackMeeting is "" and now is less than startTime) thenif (now is greater than or equal to startTimeWithMargin and now is less than endTime) thenset s to subject of item i of calendarEventsset startTimeWithMargin to startTime - startTimeMarginset endTime to end time of item i of calendarEventsset startTime to start time of item i of calendarEventsset item j of calendarEvents to tempset item i of calendarEvents to item j of calendarEventsset temp to item i of calendarEventsif start time of item j of calendarEvents < start time of item i of calendarEvents thenrepeat with j from i + 1 to count of calendarEventsrepeat with i from 1 to (count of calendarEvents)set calendarEvents to (every calendar event whose start time is greater than or equal to today and start time is less than tomorrow)tell (calendar id CalID)set CalID to item i of calendarIdrepeat with i from 1 to number of items in calendarIdset calendarEvents to {}set calendarId to calendarId & (id of every calendar whose name is calendarName)set calendarName to item i of calendarNamesrepeat with i from 1 to number of items in calendarNamesset fallbackMeeting to ""set calendarId to {}set calendarNames to every text item of calendarsif calendars contains ", " thenset delims to AppleScript's text item delimitersset tomorrow to today + (1 * days)copy now to todayset defaultMeeting to "Untitled Meeting"set startTimeMargin to (5 * minutes)set calendars to "Calendar"set _path to (path of library folder of system domain) as stringclick menu item "Selected sound output device" of menu 1 of thePopUpset thePopUp to pop up button 1click radio button "Sound Effects"tell tab group 1 of window "Sound"repeat until exists tab group 1 of window "Sound"set PLIST_EXISTS_CACHE to redisLib's new(1 * minutes)set redisLib to std's import("redis")return actualResultPLIST_EXISTS_CACHE's setValue(keyName, actualResult)set actualResult to continue plistExists(plistName)if PLIST_EXISTS_CACHE's getBool(keyName) is false thenset keyName to "plistExists-" & plistNameon plistExists(plistName)script PlutilExistsCachedInstanceglobal PLIST_EXISTS_CACHEglobal std, redismake new folder at p with properties {name:dateStamp &"-【"& input1 &"】"&input2}if input1 is not "" and input2 is not "" thenset input2 to text returned of (display dialog "任务名称" default answer "" buttons {"OK", "Cancel"} default button "OK" with title "任务名称")set input1 to text returned of (display dialog "服务主体" default answer "" buttons {"OK", "Cancel"} default button "OK" with title "服务主体")end fmGUI_ManageScripts_FmScript_SaveAndExiterror "Couldn't fmGUI_ManageScripts_FmScript_SaveAndExit - " & errMsg number errNumreturn fmGUI_ClickMenuItem({menuItemRef:closeScriptMenuItem})if needsSave then fmGUI_ClickMenuItem({menuItemRef:saveScriptMenuItem})set closeScriptMenuItem to menu item "Close Tab" of menu "View" of menu bar 1set needsSave to enabled of saveScriptMenuItemset saveScriptMenuItem to menu item "Save Script" of menu "Scripts" of menu bar 1on fmGUI_ManageScripts_FmScript_SaveAndExit(prefs)fmGUI_ManageScripts_FmScript_SaveAndExit({})path to temporary items from user domaindisplay alert "DEVONthink Pro" & space & error_number message error_message as warningopen window for record (item 1 of theResults)display notification "Pfad nicht in offenen Datenbanken enthalten!" with title "Lookup DEVONthink"if theResults = {} thenset theResults to theResults & thisDatabasesResultsset thisDatabasesResults to lookup records with path thePath in thisDatabaserepeat with thisDatabase in theDatabasesset theDatabases to databasesset thePath to characters (offset of "/" in thisLine) thru -1 in thisLine as stringif thisLine contains theFileName thenrepeat with thisLine in theLinesset theLines to paragraphs of convertedOutputset convertedOutput to (do shell script "iconv -t UTF8-MAC <<<$" & quoted form of theOpenFiles)set theOpenFiles to (do shell script "lsof -p " & PID)display alert "System Events" & space & error_number message error_message as warningset PID to unix idif theFileName starts with "* " then set theFileName to characters 3 thru -1 in theFileName as stringset theFileName to value of attribute "AXTitle" & ".pdf"tell application process "PDF Expert"tell application "System Events" to keystroke "t" using command downif System's checkIfRunning("Terminal") thenset System to load script (POSIX path of ((path to scripts folder as text) & "main.scpt"))do shell script "pbpaste | textutil -convert txt -stdin -stdout -encoding 30 | pbcopy"set the clipboard to ffcontset ffcont to ffcont as Unicode textset ffcont to read ffileset ffile to (choose file with prompt "Get contents from…" of type {"txt", "md", "markdown", "rtf"})set value of text field 1 of window "Window ofset front most to truetell application process "QQ"tell application "QQ"end is_iTunesRunningtell application id "sevs" to return (exists (some process whose name is "iTunes"))to is_iTunesRunning()tell application "iTunes" to updateAllPodcastsif not is_iTunesRunning() then returnend revealXcodeDocumentset theFile to ((thePath as text) as POSIX file)on revealXcodeDocument()revealXcodeDocument()tell application frontappset data of _art to _dataset _data to data of _artif downloaded of _art thenrepeat with _art in artworks of _trackrepeat with _track in _tracksdisplay alert "Nothing selected!" as warning giving up after 5if _tracks is {} thenset _tracks to selection as listsquare_root(49)end square_rootreturn (the_number ^ 0.5)on square_root(the_number)"line1" & return & "line2"end make_DayOnedo shell script new_DayOneset new_DayOne to new_DayOne & " new"if note_Lat > 0 and note_Long > 0 then set new_DayOne to new_DayOne & " --coordinate " & note_Lat & " " & note_Longset new_DayOne to "echo " & (quoted form of note_Text) & " | '/usr/local/bin/dayone2' -d=\"" & note_Date & "\" -j=\"" & destinationJournal & "\""if dayHeader is true then set note_Text to ("# " & noteName & return & return & note_Text)on make_DayOne(noteName, note_Date, note_Text, noteLink, noteLat, noteLong)end add_Tagsreturn note_Text & "" & noteTagsTextif noteNotebook is not "" then set noteTagsText to "Notebook: #" & noteNotebook & "set noteTagsText to noteTagsText & "#" & (name of item i of noteTags) & " "repeat with i from 1 to count of noteTagsif noteTags is not {} thenset noteTagsText to ""on add_Tags(note_Text, noteTags, noteNotebook)end convert_Datereturn date_Stringset date_String to (m & "/" & d & "/" & y & " " & t) as stringset t to (time string of noteCreated)set y to (year of noteCreated)set d to (day of noteCreated)set m to ((month of noteCreated) * 1)on convert_Date(noteCreated)end convert_Markdownset shell_Text to "echo " & (quoted form of noteHTML) & " | /usr/local/bin/pandoc -s -f html -t markdown_github"on convert_Markdown(noteHTML)end convert_Plaintextreturn note_Textset note_Text to do shell script shell_Textset shell_Text to "echo " & (quoted form of noteHTML) & " | textutil -stdin -convert txt -stdout"on convert_Plaintext(noteHTML)end getEvernote_Infoset noteLink to (note link of item 1 of theNotes)set noteNotebook to (name of notebook of item 1 of theNotes)set note_Long to (longitude of item 1 of theNotes)set note_Lat to (latitude of item 1 of theNotes)set noteHTML to (HTML content of item 1 of theNotes)set noteENML to (ENML content of item 1 of theNotes)set noteAltitude to (altitude of item 1 of theNotes)set noteAttachments to {attachments of item 1 of theNotes}set noteTags to (tags of item 1 of theNotes)set noteModified to (modification date of item 1 of theNotes)set noteCreated to (creation date of item 1 of theNotes)set noteSource to (source URL of item 1 of theNotes)set noteName to (title of item 1 of theNotes)set noteID to (local id of item 1 of theNotes)on getEvernote_Info(theNotes)my make_DayOne(noteName, note_Date, note_Text, noteLink, noteTags, note_Lat, note_Long)set note_Text to my add_Tags(note_Text, noteTags, noteNotebook)if addNotebookTags is true thenset note_Date to my convert_Date(noteCreated)set note_Text to my convert_Plaintext(noteHTML)set note_Text to my convert_Markdown(noteHTML)if convertMarkdown is true thenmy getEvernote_Info(selected_Item)repeat with selected_Item in selected_Itemsset selected_Items to selectionproperty note_Long : 0property note_Lat : 0property noteNotebook : ""property note_Date : ""property noteLink : ""property noteCreated : ""property addNotebookTags : trueproperty destinationJournal : "Evernote"property convertMarkdown : falseproperty dayHeader : trueset osc output enabled of overrides to falseset the_domain to text (the_offset + 1) thru -1 of the_email_addressset the_offset to offset of "@" in the_email_addressset theURL to "https://whoplus.microsoft.com/Search?searchText=" & theSearch & "&searchType=people"set theSearch to (the clipboard)property dayToDeferTo : Friday -- set to null to not find next day to defer todisplay dialog the_namerepeat with the_name in name_listset name_list to {"Ben", "Jen", "Sten"}set contents of selection of front document to resultTextset resultText to template_fill of me into templateText under selectionTextif templateText is not false thenset templateText to template_content of me to styleNameset styleName to item 1 of the resultchoose from list styleList with title "选择所选文字外套样式" with prompt "选择一项" default items {"bg_blue"} OK button name "确定" cancel button name "取消"set selectionText to selection_text of me into thisDocumentText under selectionRangeset selectionRange to range of selection of front documentset thisDocumentText to contents of front documentset styleList to {¬ "underlined_red", ¬ "bg_blue", ¬ "bg_orange", ¬ "bg_purple"}end selection_textreturn selectionText as textset selectionText to characters startPos thru endPos of documentTextset endPos to startPos + selectionLengthset selectionLength to item 2 of selectionRangeset startPos to item 1 of selectionRangeset selectionRange to rangeset documentText to thisDocumenton selection_text into thisDocument under rangeend template_fillset resultText to resultText & item idx of templatePartsset resultText to resultText & item idx of templateParts & contentif idx comes before maxLength thenrepeat with idx from 1 to maxLengthset maxLength to length of templatePartsset templateParts to (text items of template as list)set AppleScript's text item delimiters to {"䷖"}on template_fill into template under contentend template_contentreturn item_value as textset item_value to TemplatePoolData's valueForKey:pool_nameif (TemplatePoolDataKeys as list) contains pool_name thenset TemplatePoolDataKeys to TemplatePoolData's allKeys()set TemplatePoolData to my (NSDictionary's dictionaryWithDictionary:TemplatePool)set TemplatePool to {underlined_red:"", bg_blue:"", bg_orange:"", bg_purple:""}to template_content to pool_nameend randomDateInRangeset time of randomDate to 0on randomDateInRange(minDate, maxDate)log randomDateInRange((current date) - 10 * 365 * 24 * 60 * 60, (current date))write "" to _filelog "end loop"log cntwrite "" to _filewrite _title to _file as «class utf8»set _title to _record's titlewrite "\">" to _filewrite df to _fileset df to (do shell script "date -j -f '%A, %B %e, %Y at %l:%M:%S %p' '" & _added & "' '+%s'")set _added to _record's added datewrite "\" ADD_DATE=\"" to _filewrite _url to _file as «class utf8»set _url to _record's source URLwrite "
    Eagle Filer Bookmarks

    Eagle Filer Bookmarks

    " to _fileset _lf to ASCII character 10set _file to open for access _filename with write permissionset _records to selected records of browser window 1tell application "EagleFiler"set _filename to choose file name with prompt "Export Bookmarks" default name "eagle-bookmarks.html"set the comment of this_item to "W: " & (image_width as string) & the data_delimiter & "H: " & (image_height as string) & the data_delimiter & "R: " & (image_DPI as string) & the data_delimiter & "BD: " & bit_depth & the data_delimiter & "CS: " & color_spaceset this_image to open file this_pathset this_path to the image of this_itemend getFromFMPreturn inputDataset inputData to run script sendSourceset sendSource to beginTellFM & codeToGet & endTellFMset codeToGet to "cell 1 of layout \"" & asTransfer & "\" of window 1"set endTellFM to ""set beginTellFM to ""set endTellFM to return & "end tell"set beginTellFM to "tell app id \"com.filemaker.client.pro12\"" & returnset fmpActiveName to displayed name of (first application process whose displayed name begins with fmpName)if (path to me) does not contain fmpName thenset fmpName to "FileMaker Pro Advanced"set asTransfer to "AppleScript_Transfer-DO_NOT_RENAME"on getFromFMP(prefs)getFromFMP({})open (full path of fileRef as string)set found to fileRefif (path of fileRef) = searchPrefix thenrepeat with fileRef in file references of currentProjectset searchPrefix to searchPrefix & ".m"set searchPrefix to filePrefix & "Spec"set searchPrefix to (characters 1 thru (prefixLen - 4) of filePrefix) as stringif (specSuffix = "Spec") thenset specSuffix to (characters (prefixLen - 3) thru (prefixLen) of filePrefix) as stringset prefixLen to count of filePrefixset filePrefix to filePrefix & item textItemNumber of filePrefixItemsset filePrefix to filePrefix & "."if textItemNumber > 1 thenrepeat with textItemNumber from 1 to ((count of filePrefixItems) - 1)set filePrefix to ""set filePrefixItems to text items of currentFileName as listset currentFileName to last text item of currentFullPath as stringset currentFullPath to associated file name of first window of application "Xcode" as stringset currentProject to project of active project document of application "Xcode"using terms from application "Xcode"do shell script "open -a Firefox " & quoted form of _urlend sendimagesend theAttachment1 to theBuddyset the clipboard to theItemset theAttachment1 to POSIX file file_path as aliason sendimage(file_path, phone)end sendmessagesend content to theBuddyset theBuddy to participant phone of myidset myid to 1st account whose service type = iMessageon sendmessage(content, phone)if autohide_status is equal to false then set autohide of dock preferences to falsekey code 19 using {command down, option down}delay 0.1 #give time for clean fn to work (after showing desktop & activating finder)delay 1.2 #give time for hide to be noticed by clean fnset autohide of dock preferences to trueif autohide_status is equal to false thenset autohide_status to autohide of dock preferencesactivate application "Finder"key code 103set value of slider 1 of front window to 112 -- Values 0 to 112 for Icon Sizereturn tsvOutset the clipboard to emailOutset the clipboard to tsvOutset emailOut to emailOut & (name of theContact) & " <" & (value of i) & ">" & returnset tsvOut to tsvOut & (name of theContact) & tab & (value of i) & returnget value of irepeat with i in emails of theContactrepeat with theContact in (get selection)set emailOut to ""set tsvOut to ""log "Cancelled timer from AppDelegate"Controller's cancelTimer()script KitchenTimerAppDelegateproperty Controller : class "Controller" of current applicationend fmGUI_ManageSecurity_GoToTab_ExtendedPrivserror "fmGUI_ManageSecurity_GoToTab_PrivSets - " & errMsg number errNumreturn fmGUI_ManageSecurity_GotoTab({tabName:"Extended Privileges"} & prefs)on fmGUI_ManageSecurity_GoToTab_ExtendedPrivs(prefs)fmGUI_ManageSecurity_GoToTab_ExtendedPrivs({fullAccessAccountName:"admin", fullAccessPassword:""})screenshot(0)log "wait game end"log "sit down"delay 25log "ready"keyboard(keyRight)log "select doc"keyboard(keyDown)log "select location"keyboard(X)keyboard(O)log "Start game #" & countRepeat & ", you farmed " & countRepeat * 50 - 50set countRepeat to (countRepeat + 1)end screenshotscreenshot(stepValue + 1)log "GAME IS ENDED 🥳"if percent > 30 and percent < 100 thenlog "percent is: " & percentset percent to findAndReplaceInText(errmsg, ".", ",") as numberon error errmsg number errnrset diff to do shell script "/usr/local/bin/magick compare -metric PSNR /Users/whalemare/Desktop/original.png /Users/whalemare/Desktop/new.png /Users/whalemare/Desktop/diff.png"do shell script "screencapture -R0,0,1135,683 -tpng" & space & quoted form of thePathset thePath to theTempPath & "new.png"set theTempPath to POSIX path of (path to desktop)set theDate to do shell script "date +%Y_%m_%d_%H%M%S"if stepValue < repeatScreenshotCount thenlog "stepValue: " & stepValue & " of " & repeatScreenshotCounton screenshot(stepValue)set repeatScreenshotCount to 150global repeatScreenshotCountdisplay notification "Farm" with title "Farming" subtitle value sound name "Frog"on notify(value)end keyboardkey code codetell application "RemotePlay" to activateon keyboard(code)set maxOk to 17set minOk to 15set countRepeat to 0set keyRight to 124set keyLeft to 123set keyDown to 125set keyUp to 126set X to 36set O to 53make new open file alarm at theEvent with properties {trigger interval:0, filepath:POSIX path of theScriptToTrigger}set theEvent to make new event at end of calendar theCalendarName with properties {summary:"AppleScript Trigger: " & theScriptToTriggerName, start date:theCurrentDate, end date:theCurrentDate}set theCurrentDate to current datemake new calendar with properties {name:theCalendarName}if (calendar theCalendarName exists) = false thenset theScriptToTriggerName to displayed name of (info for theScriptToTrigger)set theScriptToTrigger to choose file with prompt "Please select a saved AppleScript application to attach to an event:" of type "app"set theCalendarName to "AppleScripts"set cue target of theStart to cue (userNumPrefix & theScene)if button returned of userInput is "Continue" and theScene is not "" thenset theScene to text returned of userInputset userInput to display dialog "Scene?" default answer "" buttons {"Cancel", "Continue"} default button "Continue"set userNumPrefix to "y"error "Could not get namesOfTOsOfWindowName of window name specified: '" & someWindowName & "'"if dbWindows contains someWindowName then return name of every table of database dbNumset dbWindows to name of every window of database dbNumon namesOfTOsOfWindowName(someWindowName)namesOfTOsOfWindowName(frontmostWindowName)end camelCaseModeif character (theLocation - (n - 1)) of sourceText is tab thenelse if action is "move cursor to previous word with selection" thenset selection to {theLocation - n, 0}if character (theLocation - (n - 1)) of sourceText is not tab thenelse if char is in invisibles thenset n to n - 1else if char is in delims thenif char is in caps thenelse if action is "move cursor to previous word" thenelse if action is "move cursor to next word with selection" thenset selection to {theLocation + n, 0}set char to character (theLocation + n) of sourceTextelse if action is "move cursor to next word" thenset selection to {theLocation - n, theRange + n}if char is in delims then set n to n - 1if char is in caps or char is in delims thenset char to character (theLocation - n) of sourceTextelse if action contains "delete to word start" thenset selection to {theLocation, theRange + n}if char is in caps or char is in delims then exit repeatset char to character (endOfSelection + n) of sourceTextif action contains "delete to word end" thenset invisibles to space & tab & return & linefeedset caps to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"set delims to " :{},()." & tab & return & linefeedon camelCaseMode(action)end wordActionset theLocation to endOfSelection - preif n > 0 then set pre to n - 1if forward is in delims then set post to nset delims to " :{},()\"" & return & tab & linefeedon wordAction(action)end moveLineset selection to {theLocation - ((length of p1) + 1), 0}if direction is "up" thenset selection to p2 & return & p1set p2 to paragraph 2 of selset p1 to paragraph 1 of selset selection to {theLocation, theRange}set pre to n - 1if n ≠ 0 then set pre to n - 1if backward is in delims thenset firstPara to nif firstPara is "" thenif direction is "down" thenset firstPara to ""on moveLine(direction)end lineActionset selection to ""set selection to {theLocation, theRange + 1}if action contains "delete" thenset action to "delete"display notification (the clipboard) with title "Copied"if action contains "copy" thenset the clipboard to characters theLocation thru (theLocation + theRange - 1) of sourceText as stringelse if action contains "copy" or action contains "cut" thenset selection to theSelectionif action = "select" thenset theSelection to {theLocation, theRange}set theRange to pre + postset theLocation to endOfSelection - (pre)if post ≠ "" and pre ≠ "" then exit repeatif backward is in delims then set pre to n - 1set backward to character (endOfSelection - n) of sourceTextif pre = "" thenif n = 0 then set n to n + 1set post to nif forward is in delims thenset forward to character (endOfSelection + n) of sourceTextif post = "" thentell me to runset delims to return & linefeedon lineAction(action)set pre to ""set post to ""set endOfSelection to theLocation + theRangeset sourceText to source textset {theLocation, theRange} to (get character range of selection)property pre : missing valueproperty post : missing valueproperty n : missing valueproperty endOfSelection : missing valueproperty theRange : missing valueproperty theLocation : missing valueproperty theSelection : missing valueproperty sourceText : missing valueproperty id : "com.kfunderburg.library.scriptDebuggerLibrary"property name : "ScriptDebugger Library"end sanitizeset txt to my replace_chars(txt, ")", "\\)")set txt to my replace_chars(txt, "(", "\\(")on sanitize(txt)end updateTrackLinelog resset res to (do shell script SET_ENCODING & the_command) as textset the_command to "sed \"" & line_number & "s/^\\(" & common_data & "\\).*$/\\1" & append_data & "/\" " & quoted form of FILEDB & " > " & quoted form of FILETMPset line_number to (do shell script "echo " & quoted form of match & " | cut -f1 -d ':'") as integeron updateTrackLine(FILEDB, FILETMP, match, common_data, append_data)end text2dateset {t's year, t's month, t's day, t's hours, t's minutes, t's seconds} to {yy, mm, dd, h, m, s}set t to current dateset {yy, mm, dd, h, m, s} to every text item in theDateStrset text item delimiters to "."on text2date(theDateStr)end date2textreturn yy & "." & mm & "." & dd & "." & h & "." & m & "." & s as textset s to (seconds of the_date as integer)set m to (minutes of the_date as integer)set h to (hours of the_date as integer)set dd to (day of the_date as integer)set mm to (month of the_date as integer)set yy to (year of the_date as integer)on date2text(the_date)end getTimestampDateset output to (do shell script "echo " & quoted form of track_line & " | cut -f6") as texton getTimestampDate(track_line)end getRatingsreturn (do shell script the_command) as integerset the_command to "echo " & quoted form of track_line & " | cut -f5"on getRatings(track_line)display dialog "All Ratings Synchronized" buttons "OK" default button "OK""mv " & quoted form of FILETMP & " " & quoted form of FILEDB"mv " & quoted form of FILEDB & " '" & FILEDB & ".bak'; " & ¬if global_dirty is equal to true thendo shell script SET_ENCODING & "echo " & quoted form of newline & " >> " & quoted form of FILETMPdo shell script SET_ENCODING & "cp " & quoted form of FILEDB & " " & quoted form of FILETMPif global_dirty is equal to false thenset newline to t's artist & tab & t's album & tab & t's track number & tab & t's name & tab & t's rating & tab & my date2text(t's played date)if t's played date is equal to missing value then set t's played date to current datelog "REMOTE: CREATING " & t's name & " Ratings to " & t's ratingif t's rating > 0 thenset global_dirty to truemy updateTrackLine(FILEDB, FILETMP, match, search_string, t's name & tab & t's rating & tab & my date2text(local_timestamp))log "UPDATE REMOTE: " & t's name & tab & remote_ratings & " -> " & t's ratingset t's played date to remote_timestampset t's rating to remote_ratingslog "UPDATE LOCAL: " & t's name & tab & t's rating & " -> " & remote_ratingsif t's rating is equal to 0 or local_timestamp is missing value or local_timestamp < remote_timestamp thenset local_timestamp to t's played datelog "CHECKING: " & t's name & " (" & t's rating & ") " & tab & "date: " & remote_timestampset remote_timestamp to my text2date(my getTimestampDate(match))if dirty is true thenif remote_ratings is not equal to t's rating then set dirty to trueset remote_ratings to my getRatings(match)if match is equal to "" thenset match to (do shell script SET_ENCODING & "sed -n '/" & search_string & "/{=;p;}' " & quoted form of FILEDB & " | sed '$!N;s/\\n/:/'") as «class utf8»set search_string to (t's artist & tab & t's album & tab & t's track number & tab) as «class utf8»set dirty to falseset t to track i of librepeat with i from 1 to total_tracksset total_tracks to (count of every track of lib)set lib to a reference to library playlist 1set global_dirty to falseset FILETMP to POSIX path of "/tmp/tmp.file"set FILEDB to POSIX path of ((path to home folder as string) & database_file)property SET_ENCODING : "export LANG=en_US.UTF-8; "property database_file : "Library:iTunes:Scripts:index_ratings.txt"click menu item "Update Packages to Latest Versions" of menu 1 of menu item "Packages" of menu 1 of menu bar item "File" of menu bar 1open projectPathset projectPath to ""display notification "tabUrl" with title "Sent Chrome tab url to Evernote" subtitle "《" & "tabTitle" & "》"set conversion1 to (ftemp - 273.15)else if whichconv is "Kelvin to Celsius" thenset conversion1 to (ftemp + 273.15)set ftemp to text returned of (display dialog "Convert Celsius to Kelvin" default answer "" buttons {"Cancel", "Convert"} default button "Convert")else if whichconv is "Celsius to Kelvin" thenset conversion1 to (ftemp * 1.8) - 459.67else if whichconv is "Kelvin to Fahrenheit" thendisplay dialog "The temperature is " & conversion1 & " Kelvin" buttons {"Ok"} default button "Ok"set conversion1 to (ftemp + 459.67) * 0.5555555556set ftemp to text returned of (display dialog "Convert Fahrenheit to Kelvin" default answer "" buttons {"Cancel", "Convert"} default button "Convert")else if whichconv is "Fahrenheit to Kelvin" thendisplay dialog "The temperature is " & conversion1 & " Fahrenheit" buttons {"Ok"} default button "Ok"set conversion1 to ftemp * 9 / 5 + 32set ftemp to text returned of (display dialog "Convert Celsius to Fahrenheit" default answer "" buttons {"Cancel", "Convert"} default button "Convert")else if whichconv is "Celsius to Fahrenheit" thenset conversion1 to round conversion1if whichconv is "Fahrenheit to Celsius" thenset whichconv to whichconv as textset whichconv to choose from list {"Celsius to Fahrenheit", "Celsius to Kelvin", "Fahrenheit to Celsius", "Fahrenheit to Kelvin", "Kelvin to Celsius", "Kelvin to Fahrenheit"} with title "Convert Temperature"keystroke "home"key code 16 using {command down, shift down}key code 19 using command downwindowSize's windowSize({xsize:1, ysize:0.5, xpos:0, ypos:0.5, appName:"iTerm"})set pars to {xsize:1, ysize:0.5, xpos:0, ypos:0.5, appName:"iTerm"}log "Check Settings"else if button returned of dialogAnswer is "Check" thensetSettings()log "Save Settings"if button returned of dialogAnswer is "Save" thenclearSettings()log "Clear Settings"set dialogAnswer to display dialog "Store current camera settings?" buttons {"Check", "Clear Settings", "Save"} default button 3 cancel button 2end clearSettingsdo shell script "defaults delete photo.lostcause.CameraWarning"on clearSettings()end getSettingsreturn {iso:theISO, shutter:theShutter, aperture:theAperture}set theAperture to do shell script "defaults read photo.lostcause.CameraWarning aperture"set theShutter to do shell script "defaults read photo.lostcause.CameraWarning shutterSpeed"set theISO to do shell script "defaults read photo.lostcause.CameraWarning iso"on getSettings()end setSettingsdisplay alert "No Camera Connected" message "Please connect a camera or select it in the current document."do shell script "defaults write photo.lostcause.CameraWarning aperture " & theAperturedo shell script "defaults write photo.lostcause.CameraWarning shutterSpeed " & theShutterdo shell script "defaults write photo.lostcause.CameraWarning iso " & theISOon setSettings()end checkSettingsdisplay notification errors with title "Camera Settings Error" sound name "sosumi"if (count of errors) is not 0 thenset errors to "• Aperture is not f/" & aperture of savedSettings & "if aperture of savedSettings is not equal to theAperture thenset errors to "• Shutter Speed is not " & shutter of savedSettings & "if shutter of savedSettings is not equal to theShutter then" & errorsset errors to "• ISO is not " & iso of savedSettings & "if iso of savedSettings is not equal to theISO thenset errors to ""set theAperture to aperture of camera of current documentset theShutter to shutter speed of camera of current documentset theISO to ISO of camera of current documenttell application "Capture One"set savedSettings to getSettings()on checkSettings()checkSettings()end bbopen _liston bb(_list)on open (_list)bb(_list)copy _item to end of _listset _item to _item as aliasrepeat with _item in _itemscopy _folder to end of _listset _folder to folder of the front window as stringif _items is {} thenset _items to selectionset _list to {}end prepend_to_filewrite newInboxData & fileContents to the open_target_file starting at 0set newInboxData to "Inbox:" & return & " " & this_dataopen for access file target_file with write permissionset the open_target_file to ¬close access target_fileset fileContents to (read target_file from 7 to eof)open for access target_fileon prepend_to_file(this_data, target_file) -- (string, file path as string, boolean)end WriteLogmy prepend_to_file(this_story, this_file)set this_file to (POSIX file theTaskFile)set this_story to the_texton WriteLog(the_text)my WriteLog("- resolve: " & theMessageSubject & " from " & (word 1 of theMessageSender) & " " & (character 1 of word 2 of theMessageSender) & "." & " @due(" & theMessageDate & ")")set theMessageURL to selectedMessageUrlset theMessageContent to the content of the theMessageset theMessageSubject to the subject of the theMessageset theMessageSender to the sender of the theMessageset theMessageDate to short date string of (get current date)repeat with theMessage in theSelectionset theSelection to selected messagestell application "Airmail 2"set theTaskFile to "/Users/tbendt/Dropbox/_Tim/Projects/_tasks/projects.taskpaper"write text "zl analytics"tell sixth sessionwrite text "redis-cli shutdown; redis-server"tell fifth sessionwrite text "z lumberyard; r s"tell fourth sessionwrite text "z woodshop; grunt serve"tell third sessionkey code 125 using {shift down, command down, control down}write text "z lumberyard; r c"tell second sessionwrite text "node"set name to "Console Panes"tell first sessionkey code 124 using {shift down, command down, control down}tell first terminalkey code 124 using {control down, command down, option down}keystroke "'" using {shift down, command down, option down}tell AppleScript to delay endTime - (current date)display notification "is OFF" with title "VPN RWTH"disconnect VPNserviceelse if current configuration of VPNservice is connected thendisplay notification "is ON" with title "VPN RWTH"repeat while (current configuration of VPNservice is not connected)connect VPNserviceif current configuration of VPNservice is not connected thenif VPNservice exists thenset VPNservice to service "VPNRWTH"tell current location of network preferencesmy loadingURL(testURL)end loadingURLreturn "loaded"if loading of goTo is true then exit repeatdisplay notification "Loading URL:" & testURLrepeat until loading of goTo is "false"on loadingURL(testURL)tell application "Finder" to move theFile to trashset SESSION_PLIST to text 8 thru -1 of (URL of folder "applescript-core" of (path to home folder) as text) & "session.plist"set logger to std's import("logger")'s new("dec-terminal-run")end doCdtell application "Terminal" to do script "cd " & thePath in my appWindowon doCd(thePath)end runAndWaitdelay 0.2 -- Seems to solve mysterious issues. 0.1 has issues, finding BSS stack reports incorrect result._refreshTabName()waitForPrompt()delay 0.2 -- experiment from 0.1, SSH to EC2 stack on new install is crappy.runShellVoid(shellCommand)on runAndWait(shellCommand)end runShellVoiddo script shellCommand in my appWindowdo script "" in my appWindowon runShellVoid(shellCommand)end runShellreturn waitResultlogger's warn("Bash Script did not communicate OK via session.plist")if waitResult is missing value or waitResult is equal to NO_RESULT thenset waitResult to exec of retry on CommandWaiter for my commandRunMax by my commandRetrySleepSecreturn NO_RESULTlogger's debug("Prompt detected and result was not returned.")if theText ends with " " & promptEndChar thenset theText to textUtil's rtrim(theText as text)set theText to the history of selected tab of appWindowif commandResult is not missing value and the length of commandResult is greater than 0 then return commandResultset commandResult to sessionPlist's getValue(propertyName)script CommandWaiterdo script calcCommmand in my appWindowdo script "" in appWindowif my refreshPrompt thenset NO_RESULT to "_noresult_"set calcCommmand to format {"plutil -replace {} -string \"`{}`\" {}", {quoted form of propertyName, shellCommand, SESSION_PLIST}}sessionPlist's deleteKey(propertyName)set propertyName to format {"runShell-{}", my getTabName()}set lastCommand to shellCommandon runShell(shellCommand)sut's runAndWait("sleep 5")sut's doCd("~/Desktop")sut's runShellVoid("echo world")logger's infof("Run echo command result: {}", sut's runShell("echo hello"))Manual: Run and WaitManual: Change DirectoryManual: Run Shell VoidManual: Run Shellset thisCaseId to "term-ext-run-spotCheck"global SESSION_PLISTglobal std, retry, textUtil, sessionPlistset logger to std's import("logger")'s new("enter-user-country")set infoKey to "User Country" -- e.g. Philippinestell application "Slack" to activateend repeat -- sheet closedrepeat while existsclick menu item "Save PDF to Evernote" of menu 1tell menu button "PDF"end repeat -- sheet openedif i > 4 then return -- no print window, exit this scriptrepeat until existskeystroke "p" using command down -- shortcut to printif exists window 1 thenset body text of new_document to contentset new_document to make new document at end of documentsif content is not missing value thenset content to text of first documentset content to missing valueget properties of (path to me)class of (path to me)end getAllActionsmy getAllActions(actionList's elseactions's actions)if actionList's elseactions ≠ missing value thenmy getAllActions(actionList's thenactions's actions)if actionList's thenactions ≠ missing value thenmy getAllActions(actionList's case entries)if (count of actionList's case entries) > 0 thenset end of allActions to actionListelse if class of actionList = action thenmy getAllActions(actionList's actions)if (count of actionList's actions) > 0 thenelse if class of actionList = case entry thenmy getAllActions(act)repeat with act in actionListand (count of items of actionList) > 0 thenclass of actionList = action list) ¬if (class of actionList = list or ¬local actionListon getAllActions(actionList)if disclosed of a is true then set disclosed of a to falsea's name contains "Set Variable" thena's name contains "in the Menu" or ¬a's name contains "Delete Past Clipboard" or ¬a's name contains "Paste from Named" or ¬a's name contains "Execute Macro" or ¬a's name contains "Cancel" or ¬a's name contains "Notification" or ¬a's name contains "Type the" or ¬if a's name contains "Pause for" or ¬repeat with a in allActionsmy getAllActions(m's actions)set acts to a reference to m's actionsset allActions to {}global allActionsset title of note_found to new_note_titleset the new_note_title to my replace_chars((note_found's title) as string, note_name, "")repeat with note_found in notes_foundelse if (count of notes_found) > 1 thenif notes_found = {} thenset notes_found to (find notes ("intitle:\"" & note_name & "\""))set note_name to text returned of (display dialog "Enter the text to search:" default answer "")set note_name to item 1 of argvif (count of argv) > 2 thenend PDFreturn PLPDFset PLPDF's metadata to theDocument's documentAttributes() as recordset PLPDF's pageCount to theDocument's pageCount() as numberset theDocument to PLPDF's _getPDFDocument()error theTarget & " is not a PDF file."if theTarget does not end with ".pdf" thenopen location targetopen targettell application "Preview"theDocument's writeToFile:filePathon save in filePath : (missing value)rotatedPdfData's writeToFile:filePath atomically:trueset rotatedPdfData to pdfDoc's dataRepresentation()(PDFPage's setRotation:((PDFPage's |rotation|()) + degrees))set PDFPage to (pdfDoc's pageAtIndex:i)on rotate by degrees into filePath : (missing value)flippedPdfData's writeToFile:filePath atomically:true(transform's translateXBy:0 yBy:(-(item 2 of item 2 of pdfRect)))set pdfDoc to my _getPDFDocument()on flip over axis into filePath : (missing value)return theDocument's |string|() as textset theDocument to my _getPDFDocument()end _getPDFDocumentreturn current application's PDFDocument's alloc()'s initWithURL:fileURLset fileURL to current application's NSURL's URLWithString:(my target)set fileURL to current application's NSURL's fileURLWithPath:(my target)set fileURL to missing valueon _getPDFDocument()property metadata : missing valueproperty pageCount : missing valuescript PLPDFon PDF(theTarget)log theTextEncset theTextEnc to theTextEnc & (useChar as string)return replace_chars(theText, " ", "%20")on encode(theText)if statement is not "" then display alert statement as warningon alert(statement)end createDeferDatereturn deferDateset deferDate to ((current date) + dateOffset)set dateOffset to (dueDate - (current date)) / 2on createDeferDate(dueDate)end createDueDateset newDate to ((current date) + (86400 * 7))on createDueDate()end createLinksay "task has no name"return name of the currentTask & ":" & return & currentLink & return & returnset currentLink to currentLink & "&project=" & projectNameset projectName to (name of the containing project of the currentTask) as stringset currentLink to currentLink & "&flagged=true"if flagged of the currentTask is true thenset currentLink to currentLink & "&defer=" & encodedDeferset encodedDefer to my encode(defer date of currentTask as string)if defer date of currentTask is not missing value thenset currentLink to currentLink & "&due=" & encodedDateset encodedDate to my encode(due date of currentTask as string)if due date of currentTask is not missing value thenset currentLink to currentLink & "¬e=" & encodedNoteset encodedNote to my encode(theNote)if theNote is not equal to "" thenset theNote to text of (note of the currentTask)if note of the currentTask is not missing value thenset currentLink to "omnifocus:///add?name=" & my encode(name of currentTask)if name of the currentTask is not missing value thenon createLink(currentTask)end createContexton createContext(contextName)end createFollowUpsdisplay dialog "not ok"set completed of currentTask to trueset defer date of followUp to the defer date of currentTaskset due date of followUp to the due date of currentTaskset followUp to make task with properties {{name:(name of currentTask), note:("Delegated on: " & (current date) as string) & return & return & (note of the currentTask) as string, context:my createContext(personContext)}}tell containing project of currentTaskif the containing project of the currentTask is not missing value thenon createFollowUps(selectedTasks)end createEmailmake new to recipient with properties {name:personContext, address:emailAddress}set the sender to "Travis "tell newMailset newMail to make new outgoing message with properties {subject:"New Tasks", visible:true}set emailAddress to item (getPositionOfItemInList((personContext as string), people)) of emailsset mailContent to mailContent & newLink & returnset newLink to my createLink(newTask)set newTask to value of selectedItemset mailContent to ""on createEmail(selectedTasks)end grabSelectedTasksreturn selected trees of contenton grabSelectedTasks()end personToReceiveTasksdisplay dialog "To whom should I send the task(s)?" default answer "john" buttons {"Nahhhh", "Send it!"} default button 2on personToReceiveTasks()end confirmDatesForset defer date of the currentTask to my createDeferDate(due date of the currentTask)if defer date of the currentTask is missing value thenset due date of the currentTask to my createDueDate()if due date of the currentTask is missing value thenset currentTask to value of selectedItemrepeat with selectedItem in selectedTaskson confirmDatesFor(selectedTasks)my createFollowUps(selectedTasks)my createEmail(selectedTasks)my confirmDatesFor(selectedTasks)if handleCreation = "Send it!" thenset handleCreation to (the button returned of dialogAnswer) as stringset personContext to (the text returned of dialogAnswer) as stringset dialogAnswer to my personToReceiveTasks()my alert("You need to select at least 1 task.")if ((count of selectedTasks) < 1) thenset selectedTasks to my grabSelectedTasks()property emailTo : ""property emails : {"john@somewhere.com"} #add an email for every name in the previous variableproperty people : {"john"} #add more names here, and make sure they line up with the emailsproperty personContext : ""frontmost_app.setTheClipboardTo(markdown_link);var markdown_link = `[${current_tab_title}](${current_tab_url})`;throw new Error('You need a supported browser as your frontmost app.');frontmost_app.displayNotification('You need a supported browser as your frontmost app.', { withTitle: 'Browser Not Supported' });} else {var current_tab_url = frontmost_app.documents[0].url();var current_tab_title = frontmost_app.documents[0].name();if (['Google Chrome', 'Google Chrome Canary', 'Chromium', 'Opera', 'Vivaldi', 'Brave'].indexOf(frontmost_app_name) > -1) { var current_tab_title = frontmost_app.windows[0].activeTab.name(); var current_tab_url = frontmost_app.windows[0].activeTab.url(); } else if (['Safari', 'Safari Technology Preview', 'Webkit'].indexOf(frontmost_app_name) > -1) {frontmost_app.includeStandardAdditions = true;var frontmost_app = Application(frontmost_app_name)var frontmost_app_name = se.applicationProcesses.where({ frontmost: true }).name()[0]var se = Application('System Events');Link to the Gist: https://gist.github.com/vitorgalvao/5392178#file-get_title_and_url-jsMostly adapted from a GitHub Gist by Vítor Galvão.This script returns the title and URL of the frontmost tab of the active browser, and sets the clipboard to a markdownified link.set color of eachCharacter to {random number from 0 to 65535, random number from 0 to 65535, random number from 0 to 65535}set size of eachCharacter to (random number from lowFontSize to highFontSize)set font of eachCharacter to (some item of fontList)repeat with eachCharacter in characterstell crazyTextMessageset crazyTextMessage to make new outgoing message with properties {content:messageText, visible:true}set fontList to {"American Typewriter", "American Typewriter Light", "American Typewriter Bold", "American Typewriter Condensed", "American Typewriter Condensed Light", "American Typewriter Condensed Bold", "Arial", "Arial Italic", "Arial Bold", "Arial Bold Italic", "Arial Black", "Baskerville", "Baskerville Italic", "Baskerville SemiBold", "Baskerville Bold", "Baskerville SemiBold Italic", "Baskerville Bold Italic", "Big Caslon Medium", "Comic Sans MS", "Comic Sans MS Bold", "Copperplate", "Copperplate Light", "Copperplate Bold", "Didot", "Didot Italic", "Didot Bold", "Futura Medium", "Futura Medium Italic", "Futura Condensed Medium", "Futura Condensed ExtraBold", "Geneva", "Gill Sans", "Gill Sans Italic", "Gill Sans Light", "Gill Sans Light Italic", "Gill Sans Bold", "Gill Sans Bold Italic", "Herculanum", "Lucida Grande", "Lucida Grande Bold", "Marker Felt Thin", "Marker Felt Wide", "Optima Regular", "Optima Italic", "Optima Bold", "Optima Bold Italic", "Optima ExtraBlack", "Papyrus", "Verdana", "Verdana Italic", "Verdana Bold", "Verdana Bold Italic", "Zapfino"}set messageText to theTextif theText is not "" thenset theText to text returned of userInputelse -- button returned of userInput is "Continue"set highFontSize to lowFontSizeset highFontSize to newFontSizeif newFontSize is greater than lowFontSize thendisplay dialog "Enter the maximum font size to use:" & return & return & "(Must be greater than " & (lowFontSize as string) & ")" default answer highFontSize buttons {"OK"}set lowFontSize to minimumFontSizeset lowFontSize to newFontSizeif newFontSize is greater than or equal to minimumFontSize thenset newFontSize to text returned of the result as integerdisplay dialog "Enter the minimum font size to use:" & return & return & "(Must be at least " & (minimumFontSize as string) & ")" default answer lowFontSize buttons {"OK"}set minimumFontSize to 9if the button returned of userInput is "Set Prefs" thenset userInput to display dialog "Enter some message text:" & return & return & "Minimum Character Size: " & (lowFontSize as string) & return & "Maximum Character Size: " & (highFontSize as string) default answer messageText buttons {"Cancel", "Set Prefs", "Continue"} default button 3property messageText : "Happy Birthday!"property highFontSize : 72property lowFontSize : 36display dialog "No fonts were found."display dialog "This PDF contains " & (count font_info_list) & " fonts, out of which " & embedded_font_count & " are embedded."set embedded_font_count to embedded_font_count + 1if is_embedded is "yes" thenset is_embedded to word -5 of font_info_refrepeat with font_info_ref in font_info_listset embedded_font_count to 0set font_info_list to paragraphs 3 thru -1 of shell_resultif (count paragraphs of shell_result) > 2 thendisplay dialog "Error:" & return & error_messageset shell_result to do shell script shell_scriptset shell_script to "/usr/local/bin/pdffonts " & quoted form of POSIX path of pdf_file on open {pdf_file}set the title of thisPic to my composeTitle(thePadding, thePrefix, i, theSuffix)set i to theStartif thePadding is greater than 20 then set thePadding to 20set thePadding to theNewPadding as numberset theNewPadding to the text returned of resultdisplay dialog ScriptName & "Changing Settings - Step 4 of 4" & return & return & "The number of DIGITS:" buttons {"Done"} default answer thePadding with icon 1set theStart to theNewStart as numberset {theNewStart, theAction} to the {text returned, button returned} of resultdisplay dialog ScriptName & "Changing Settings - Step 3 of 4" & return & return & "The STARTING number:" buttons {"Done", "Next"} default answer theStart with icon 1set {theSuffix, theAction} to the {text returned, button returned} of resultdisplay dialog ScriptName & "Changing Settings - Step 2 of 4" & return & return & "New SUFFIX:" buttons {"Done", "Next"} default answer theSuffix with icon 1if theAction is "Done" then exit repeatset {thePrefix, theAction} to the {text returned, button returned} of resultdisplay dialog ScriptName & "Changing Settings - Step 1 of 4" & return & return & "New PREFIX:" buttons {"Done", "Next"} default answer thePrefix with icon 1else if theAction is "Change Settings" thenelse if theAction is "Set titles" thenif theAction is "Quit" thenset theAction to the button returned of resultdisplay dialog ScriptName & "Settings:" & return & return & theSettings & return & return & "First photo will be titled: " & return & return & tab & theSample buttons {"Quit", "Change Settings", "Set Titles"} with icon 1set theSample to my composeTitle(thePadding, thePrefix, theStart, theSuffix)set theSettings to tab & "Prefix" & tab & ": " & thePrefix & return & tab & "Suffix" & tab & ": " & theSuffix & return & tab & "Init on" & tab & ": " & theStart & return & tab & "Digits" & tab & ": " & thePaddingdisplay dialog ScriptName & "First you must select the pictures" buttons {"Ouch!"} with icon 0id of item 1 of thePics -- only pictures hade IDsset ScriptName to "[ " & ScriptName & " ]" & return & returnend composeTitlereturn thePrefix & theNumber & theSuffixset theNumber to items -thePadding thru -1 of theNumber as textset theNumber to "00000000000000000000" & theNumber -- :)on composeTitle(thePadding, thePrefix, theNumber, theSuffix)set thePadding to 3set theStart to 1set theSuffix to ""set thePrefix to "Photo "set scriptVersion to "1.0"set ScriptName to "iPhoto Set Sequential Title"key code 53 --escapeclick menu item "Turn Bluetooth Off"else if menu item "Turn Bluetooth Off" exists thenclick menu item "Turn Bluetooth On"if exists menu item "Turn Bluetooth On" thentell menu of btend renameFilesreveal my pathsToFiles(renamedFiles)set renamedFiles to paragraphs of (do shell script renameCommand)set renameCommand to renameCommand & " " & my quotePaths(theFiles)set renameCommand to renameCommand & " -H " & theTypeif theType is false then returnset theType to (choose from list availableTypes with prompt "Choose hash algorithm:")set availableTypes to paragraphs of (do shell script renameCommand & " -L")set renameCommand to homeFolder & ".local/bin/rename-hash"set theFiles to regularFiles(theFiles)end quotePathsend pathsToFilesend regularFilesreturn newFilesset end of newFiles to theFileif the URL of theFile does not end with "/" thenset newFiles to {}on regularFiles(theFiles)tell application "Finder" to eject (every disk where ejectable is true)end CopyValuesFromViewIndexWindowreturn indexTextBlockset the clipboard to indexTextBlocktell application "htcLib" to set indexTextBlock to unParseChars(indexList, return)keystroke (ASCII character 31) -- down arrowkeystroke (ASCII character 30) -- up arrowselect last row of itset indexList to get value of text field 1 of rows of ittell table 1 of scroll area 1 of window 1display dialog "Please choose View Index on the field you'd like the list of index values for." buttons {"OK"} default button "OK"if name of window 1 is not "View Index" thenon CopyValuesFromViewIndexWindow({})CopyValuesFromViewIndexWindow({})do shell script "echo $SAVE_CHROME_TAB_TO_EVERNOTE_ID"do shell script "source /Users/apple/.zshrc;"open POSIX file "/Users/username/someFolder/workspace.qlab4"end getCSVPropertiesreturn ((filename of theMediaItem) & "; " & (date of theMediaItem) as string) & "; " & (favorite of theMediaItem) & "; " & theKeywordsset theKeywords to theKeywords & i & "|"repeat with i in (keywords of mediaProps)if keywords of mediaProps is not missing value thenset theKeywords to ""set mediaProps to properties of theMediaItemon getCSVProperties(theMediaItem)end printAlbumKeyWordsreturn theCSVset the clipboard to theCSVset theCSV to theCSV & return & my getCSVProperties(i)repeat with i in (media items of theAlbum)set theCSV to ""set theProps to properties of firstPhotoset firstPhoto to media item 1 of theAlbumset theAlbum to album theAlbumNameon printAlbumKeywords(theAlbumName)set theList to theList & return & (my printAlbumKeywords(theAlbumName))repeat with theAlbumName in theAlbumsset theList to ""set theAlbums to {"5 star", "4 star", "3 star", "2 star", "1 star"}tell application "Opera" to set the minimized of the window 1 to falsetell application "firefox" to set the miniaturized of the window 1 to falsetell application "Google Chrome" to set the minimized of the window 1 to falsetell application "Safari" to set the miniaturized of the window 1 to falsedo shell script enablePathVarmy activate_open_instance(filePath, true)do shell script enablePathVar & space & fileCmdPathset fileCmdPath to quoted form of (POSIX path of (input as text))if true or not my activate_open_instance(filePath, false) thenset filePath to quoted form of POSIX path of (input as text)set enablePathVar to "eval \"$(/usr/libexec/path_helper -s)\"; PATH=$PATH:/opt/homebrew/bin neovide"end activate_open_instancetell procif myFiles contains fName thenset fName to my replace_chars(win_title, "'", "")set myFiles to paragraphs of (do shell script "lsof -F -p" & space & PID & space & "| grep ^n/ | cut -c2-")set PID to proc's unix idrepeat with proc in neovideProcListset neovideProcList to a reference to (every process whose name is "neovide")on activate_open_instance(win_title, is_first_time)set selected of new_group to trueadd person_ref to new_grouprepeat with person_ref in (get selection)set new_group to make new group with properties {name:group_name}set group_name to text returned of (display dialog "Enter name of new group:" default answer "")set anyNumber to my (random number from 5 to 50)refreshmake new bookmark with properties {url:tab_address, title:tab_title, desc:tab_description}do shell script "echo \"" & DayOneEntry & "\" | /usr/local/bin/dayone -d=\"" & EmailDate & "\" new"display dialog "Item Failed to Export: " & errNum & return & errText with icon 0else if "GrowlHelperApp" is not in processnames then -- NON-GROWL ERROR MSG. FOR ERRORapplication name growlName"\" due to the following error: " & return & errText ¬"Import Failure" description "Failed to export " & return & myTitle & ¬tell application "GrowlHelperApp" -- GROWL FAILURE FOR ERRORdisplay dialog "No Messages or Notes Selected!" with icon 0else if "GrowlHelperApp" is not in processnames then -- NON-GROWL ERROR MSG. FOR NO SELECTION"No Messages or Notes Selected!" application name growlName"Export Failure" description ¬"Failure Notification" title ¬tell application "GrowlHelperApp" -- GROWL FAILURE FOR NO SELECTIONelse if "GrowlHelperApp" is in processnames then"Mail to Day One" description "Successfully Exported Email with Subject: \"" & myTitle & "\" to Day One" application name growlName"Success Notification" title ¬tell application "GrowlHelperApp" -- GROWL SUCCESSif "GrowlHelperApp" is in processnames thenset successCount to successCount + 1set DayOneEntry to CustomHeader & return & return & "---" & return & return & theTextset msgnr to msgnr + 1set theFilePath to (SaveLoc & msgnr & "_" & theFileName & ".txt")set theText to messageMeatset theFileName to legalNameset AppleScript's text item delimiters to previousDelimiterset legalName to legalName as rich textset legalName to items 1 thru 32 of legalName as rich textif length of legalName is greater than 32 thenset the end of legalName to thisCharacterif thisCharacter is not in illegalCharacters thenset thisCharacter to thisCharacter as rich textrepeat with thisCharacter in the characters of potentialNameset illegalCharacters to {".", ",", "/", ":", "[", "]"}set legalName to {}set potentialName to myTitleset previousDelimiter to AppleScript's text item delimitersset CustomHeader to "## Email Message from " & afzendername & return & return & "[View Original Message](message://%3c" & messageURL & "%3e)" & return & return & "**Subject:** " & myTitle & return & "**From:** " & afzendername & " (" & afzenderaddress & ")" & return & "**Date:** " & EmailDateset messageURL to the message id of thisMessageset theSource to the source of thisMessageset EmailDate to the date received of thisMessageset afzenderaddress to extract address from sender of thisMessageset afzendername to extract name from sender of thisMessageset ReplyAddr to the reply to of thisMessageset messageMeat to (do shell script "echo " & (quoted form of myContent) & "")set myContent to the content of thisMessage as stringset myTitle to the subject of thisMessageset theCcRecipients to theCcRecipients & (name of CurrentCCRecipient) & " (" & (address of CurrentCCRecipient) & "); " as rich textrepeat with CurrentCCRecipient in CcRecipientListset theCcRecipients to "**Cc:** "set CcRecipientList to cc recipients of thisMessageset theRecipients to theRecipients & (address of CurrentRecipient) & "; " & (name of CurrentRecipient) as rich textrepeat with CurrentRecipient in recipientlistset theRecipients to "**To:** "set recipientlist to (to recipients of thisMessage)set msgnr to 1if (selection is not {}) thenset SaveLoc to FolderLoc as stringset FolderLoc to (make new folder at (path to desktop folder) with properties {name:"Temp Export Folder"})���$��,����;��@�Ep�����c��%<Xx��Co����7z��An�� E m � � � L t � � � 1 R � b � � � $ K x � � � � Ts����S���Ay��>z��9v�� /Z����%E{�� %Bb���Us���On���@r���?a���$T�����CT}��Da������?\���Gw�� D i � � :!j!�!w"�"�"�"�"#K#�#�#$K$X$�$�$�$�$+%T%~%�%.&�&�&>'�'�'�'((�(�(�(})�)�) *,*=*l*�*�*�*+8+W+�+�+�+�+',H,s,�,�,-'-N--�-�-�-.B.c.z.�.�.�.�.�./8/Y/u/�/�/�/�/�/0,0G0]0�0�0�0101C1\1u1�1�1�1�1�2�2�2p3�3�3�3�4�4�45�56"6�6�6�6�6�7�7�7�7 8M8y8�8�89I9�9�9�9�9':T:;';M;`;�;�;�;�; <<'<E<�<�<�<=7=B=`=~=�=�=>>*>d>o>�>�>�>�>??,?^?k?�?�?�?�?4@�@4ANAfAA�A�A�A�AB0BWB`B�B�B�B�B�B�B�B�B�B C(C5C�C�CDYD�D�D.EoE�E�E9FwF�F�F2GSG�G�GcHIYI�I�I�I�I J#J`p`�`�`�`ala�a�a�a�a>b_byb�b�b�b ccSchc}c�c�c�cdd$d4dVdzd�dBeme�eYf�f�f.g[g�g�gJhlh�h�h>ilij.j?jYj�j�j�j�j�jDk�k�k)lpapkp�p�pq,q^q�q�q�q�q$rZr�r�r�rs,s�s�st-tNtpt�t�tu=u_u�u%vqv�vwOw�w�w#xExix�x�x�x y�y�y�yz2zDz^zmz}z�z�z{K{T{f{x{�{�{�{�{$|-|@|[|�|�|�|�|*}]}�}�}�}~!~7~O~c~�~�~�~!o�����O�q���Ӏ� � �T�k��������6�d���:�R�r���у�=�e�{���̄!�?���Յ�7�I������?���ч/�U���Lj��;�S����i�{�����8�x���� �c�����5�O�z��������L�|�����M�]�n�����я��*�F�b���ѐ�&�n��� �H�f����J�f�|�� �����ڔ<�^�����ҕI�`���Ζݖ�U���ۗ�G�e������V�����"�N�w������:�b�����Λ�C�R���������.�`���Ɲם �����-�R�^�p�՟8�_���Р��7�H�u���͡�)�I�W�����ߢ���@�b�����ʣ�� �.�N�{������������ҥߥ��8���Ϧ ��<�`�y���<�H�Z�u�������ҩ���+�7�ת#�_�����ث�)�=�Q�{�������Ь���+�9�P���ӭ�j���Ӯ�?�q��� �������ʰ����8�Q�c�q�������1�[�������K�U�y�����ϳ��!�i�״��������V���ȷ�V���Ǹ�4�N�]�����̹#�r�����*�������ܻ�O���Ǽ�� �E���Ľ�*�A�����׾!�S�����ɿ �;�|�������j�~�����4�r�������G�`���P�������N�n����~�����[���6�N�d������6�V���������!�P����������"�E��������� �1�<�a���������-�W������� �9�T�q��������r�����������&�������� �:������K�y�������=�j������������l������g�����&�g����g�����*�Q���������6�X��������Q�Z�u��� �)�]���������!�k���������%�m��������D�_�������:�������"�l�����������H�h���������8�S������� �2�l������� �#�9�����0������@�b������F�^��E�w��������&�L����&�6�`�u������c����$�A���3����������l�������D�s������������/�_�Q���W��3��O��k����N����!\��]��& Q � � � � ? � � � �    I a z � �   = Z { � � �  + M { � � Hy��*a����7\}�=Qg|��l��� +?~8�������g���%In���<U|���$T~��2Xg���$g���&a���� )Kp����L�e � e!�!-"T"�"�"�">#g#�#$B$n$�$�$�$%5%j%�%�%1&k&�&�&'U'|'�'�'�' (q(�(�(�(�( )A)y)�)�)*9*r*�*�*�*?+d+�+�+,W,--&-:-W-k-�-�-�-.5.T.s.�.�.�././F/`/�/�/;0j0O1p1�1�1�1�12!2B2n3�3�3 4-4N4`4x4�4�4�4�4�4�5�5�56v6�6�6�6�6s7�7�7�7�78�8�89<9�9�9:::q:�:�:;4;P;^;o;�;�;�;<<j<�<�<#=A==�=�=�=�=>C>�>�>�>?+?^?�?�?@&@A@W@g@v@�@�@�@�@�@A(A4A=ALA�A�AB=BkB�B�B�B�BC"C4CtC�C�C�CD>DLDZD�D�D.E;EKE[E�E�E�E�EAFjF�F�F�F�F�FGGG&G3G�G�G�G�G�G/H�H�H�H�HIKIxI�I�IJ8JZJtJ�J�J�JlK�KL�_���Ҕ�=�I�d�ÕՕ�K�[�x�Ԗ��`�s������6�����Ԙ3�N�m�əܙ�f������C�����ۛ3�M�j���Ӝ��V�n�����(���������=�����ϟ,�@�a���ՠ��B�Y�������� �N�]�v�����Ţ���7�\�����ӣ��*�U�s�������פ� �=�L�n�����ɥ����#�=�S�b������ʦ��7�������Чާ��-�>�P���Ũ�!�5�k�~�����ʩ���)�=�Z�h�}�������ߪ��"�1�G�f�v�������ӫ���7�G�_�������ŬӬ���Y�f�y�����ѭ��)�a�o���Ӯ�4�I�a�������&�9�I�X�j���°&�}������X�g�y�������²���/�P�������γ���#�L�^�x���������a�������͵C�R�i�����ն���6�K�^�p���:�J�Z�r�������¸и�����7�D�W�x�������ùӹ��� �.�<�]�����׺,�8�����ܻ*�������k�о"���+�F�������/�`�q�k�����Q����a�����9�J�����(�l���H����N���,�m�����W�j������� �`��������� �6��������F�u������7�w����������\�~����������$�1�;�E�^��������{������������� ��)�E�P�g���c�~������� ��A�O�b��������,�M������� �f�������#�|�������2��������Z�k������� �"�U�i�w����� �"�A�T���$�A�_������g����� �*�@�t����������@�]������/�h������� �C��������-�V��������6�r������� �&�B�_�y����������K�y�������(�������������O�e�w�������-�?�T�������B�T�~�����V�i������� �&�?�a��������Z�|���������:�F�a�{������� �@�O�o���������)�U�b�z����������N���� �<�C�_�����w�������6���&������ ��{������,�M�o��������������"����� �z���7������+�Z�������>�b�[m���,Tl���.��,����;^{��]����) c � � � �  5 h ~ � � � �  6 � � � �  B w � # D W Z � � � � � !]t���H\��� /m��3z��/v�����8���2W����3r�� l|�� )2F�� 7s����?�� :g��=k���6u�U�� X��4 n � � !{!i"�"#b#�#�#.$[$�$�$�$%%%6%\%�%�%�%�%9&H&e&�&�&�&�&9's'�'�'*(c(�(�( )j)�)�)�)�)D*X*�*�*+=+Z+{+�+�+�+�+,/,A,f,�,�,�,6-K-a-x-�-�-�-�-�-3.�.�.�.�.P/�/B0y0�0�0�0�0 1s1�1�1�1 2B2f2t2�2�2�2�223�3�3�3�344D4T4i4�4525K5{5�5�5�5:6n6�6�6�6�607p7�7�7�7'8t8�8�8�8939�9�9�9 :W:q:�:�:;?;m;�;�;�;�;*<B<X<�<�< =�=�=�=z>�>�>�>B?`?x?�?�?@8@W@o@�@�@5AbAsA�A�A�A�A B8BsB�B�B�BCVCoC�C�C�C�CDDD+D:DiDwD�D�DE&E7E�E�E�EF7FFF�F�F�F�FG G5G^GhG~G�G�G�G�GHOH�H�H�H�H�HI2I=I[IeI|I�I J?JUJkJ}J�J�J�J9KAK_KtK�K�KL.LnL�L�LMM'M7MFMUMgMxM�M�M�M�M NSN�N�N�NO-OeO�O�O�OP?PVP�P�P�PQ=Q�QZR�RS/S>SlS�S�S�S�T�T�T�T U�U�U VV1VRV�V�V�V�V�VW W*WDW�W�W�W�W X>XgX�X@YcY�Y�[�[\I\�\ ]2]X]�]�]^9^f^|^�^�^�^_�_�_`�`�a�a�a b�b�b�b�b�c�c�d�e�e�e%fLfof�f�f�ffg�g�g h�h�h�h i,iai�i�ij�f�ɽ�:�����о��'�O�m���������L��������f������9�X�w�������G�^�u������������]�������_�z����H�x��������D���I�e�B�d����������-�H�i��������,�D�V�n��������������/�Z����������� �8�}��������� �R�������M�������H�z������B�t����� �<�n��������/�H�s��������C������3�l�������3������J����������'�8��� ��9�a�������T�������7�U�f�o��������� �>�p����� �7�Y���������%�G�i�����9�s�������+�X�z�����$�N����������?�������������E����� �\�����D�k������h����<�����?�����,�������&�C�n����� �-�����F�k�����=�^������D�i����������9�d�����9����/�b��������r�����$�t����������9����"�u�������"�D�q������������J�t����)�9��������H����2�S���������bt��C��<��?x�d��Qq���%����D����3 H k u � � � � � �  < ]  �  9 g � � � � � - l � �  R � C�R��\y��"���/Nk��� (4o���AR���,c���'v� 3G`w����?���F~���9h��D���'���Ms�����?W�����(Aa����/ � � !E!�!")"R"�"�"!#M#�#�#E$p$�$�$�$-%\%�%�% &_&�&1'�'�'#(�(�(�(x)�)�)�)*I*�*�*�*+5+|+�+,I,�,�,�,�,-T-�-�-�.�.*/X/�/�/00Y0�0�01U1�1�1�1'2?2{2�2�2�2G3]3z3�3V4u4�4,5e5�566N6�677�788T8�8�8�8�89�9�9�9:):C:b:}:�:�:;2;S;�;�;�; <A<�<�<====n=�=>->K>m>�>�>?�?�?�?�?@@R@m@�@�@�@�@A5ASAiA�A�A�A�A�A BB2BJB{B�B�B�B�BCC7CWCfC�C�C�CDDbD�D�D�D�D�D!E2E>EUEkE�E�E�E�EF0F�F�F0GAG]GtG�G�GHNHkH�H�H&IRI�I�I�I J*J=JUJ�JK]K~K�K�K�K)L_L�L�LMWMrM�M�MN@N�N�N ODO[OsO�O�O�O8P�P�P�PQ\Q�Q�Q�Q+RSR�R�R�R�R�R$SYSfSxS�S�ST2T�T�T�TUKU�U�U�U�UV*V^V�V�VW/WFW_W�W�WX&XGX�X�XYNYbY�Y�Y�Y�Y�Y$ZOZ�Z�Z�Z�Z5[�[�[�[ \&\4\K\e\�\�\�\�\1]J]]�]�]+^�^�^__4_T_�_�_�_`'`T`h`�`�`�`�`a!a4aRaea�a�a�a�abIbtb�b�b�bc$c7cLcc�c�c�cd>dyd�d�d1ene�e�e�ef8fbf�f�f�fgHgyg�g�g�g�ghMhph�h�h�h ini�i�i�i�ij&jOj]j~j�j�jk6kZk�k�k�k lSl�l�l1m�mGnXn�n$oQo�o�o�p�p.qQq�q�q%rEr�r�r*s�s�s�s�stAtStqt�t�t�t�t!uWuru�u�u�udvsv�v�vQw�wdx�x�xy;ydy�y�y�yWztz�z�z?{b{m{�{�{|-|X|�|�|%}f}�}�}~V~�~3q����=�M�p������2�@�q���ˁ��L���̂7�P�i���ރ�@�Y���A�^�����^���φO������|���ڈ�e�׉O��� ���ʋ��2�X���̌[�r���͍�A�j���َ��������Аl����Α��o�ڒ�A�R���ٓ �n�ܔ$�j������#�L����/�|��/�t�ǘH��ә��š��R����;���ޜ&�l���ܝ�f����%�m���͟��5�O�{�����ڠ��������=�b�����ڢ�2�\�����ɣ��>�e�Ф����&�k�ť�]���A�j����ͧ��9�X�������ި��F���A�U�e�ĪH�W�i�)�]�n�E���"�r�ݮ(�K�n�������A�e��������+�@��7�_�����Բ��=�s���ݳ�set newFilepathPOSIX to POSIX path of dest_folderif name extension of this_item is "MTS" thenset origFileModificationDate to modification date of this_itemset origFileCreationDate to creation date of this_itemset origFilepathPOSIX to quoted form of POSIX path of origFilepathset origFilepath to this_item as stringset label index of this_item to 7if (label index of this_item is 0) thenlog "Processing file: " & this_item as stringon convert_video(this_item, dest_folder)convert_video(the_item, dest_folder)if (package folder of the item_info is false) and (alias of the item_info is false) and ((this_filetype is in the type_list) or (this_extension is in the extension_list) or (this_typeID is in typeIDs_list)) thenset this_typeID to ""set this_typeID to the type identifier of item_infoset this_filetype to ""set this_filetype to the file type of item_infoset this_extension to ""set this_extension to the name extension of item_infoprocess_item(this_item, dest_folder)set this_item to alias ((the_item as Unicode text) & (item i of these_items))set these_items to list folder the_item without invisiblesset the item_info to info for the_itemon process_item(the_item, dest_folder)process_item(one_item, dest_folder)repeat with one_item in these_itemsset dest_folder to choose folder with prompt "Select a destination folder:"set these_items to choose folder with prompt "Select a folder to convert:" with multiple selections allowedproperty typeIDs_list : {} -- e.g.: {"public.jpeg", "public.tiff", "public.png"}property extension_list : {"m2ts", "mts", "mov", "avi", "mpg", "mkv", "dv"} -- e.g.: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}property type_list : {} -- e.g.: {"PICT", "JPEG", "TIFF", "GIFf"}tell (load script POSIX file "/Users/matt/code/chrome-window-management-scripts/Raise in Chrome Library.scpt") to raiseChromeTab("https://drive.google.com/drive/(?!u/[1-9]/)", " - Google Drive", "Personal Docs", "")end tailLatestLogdo script "tail -f " & the quoted form of theLogPathset theLogPath to do shell script "find $HOME/Library/Logs/CoreSimulator -print0 | xargs -0 -n 100 stat -f\"%m %Sm %N\" | sort -nr | awk '{$1=\"\";print}' | head -1 | perl -pe 's/.*?\\//\\//'"on tailLatestLog()tailLatestLog()display dialog displayText & "NB! No MD5Sum match!" buttons {"CANCEL"} default button "CANCEL" with title fileName with icon cautiondisplay dialog displayText & "MD5um OK!" buttons {"OK"} default button "OK" with title fileName" & checkSum & "set displayText to "set checkSumResult to first word of (do shell script "/sbin/md5 -q " & quoted form of POSIX path of chosenFile & " | tr '[:lower:]' '[:upper:]'")set checkSum to the text returned of (display dialog "Paste MD5Sum" default answer "" with title fileName)display alert "Multible selections are not allowed!" as warning giving up after 5set chosenFile to inputif (count of input) is 1 thenset chosenFile to ""end makeList3return (theList & items 1 thru (listLength - (count of ListB)) of ListB)copy theList & ListB to theListcopy contents of theList to ListBrepeat while (count of theList) < listLength / 2set theList to {theElement}if listLength = 1 then return {theElement}on makeList3(listLength, theElement)end splitstringtoliston splitstringtolist(theString, theDelim)global Result_Doc_ref, debugLogLevel, SE_Logging, parent_name, ResultsFileMaxDebug, enableResultsFile, enableResultsByDialog, enableResultsByClipboard, DialogTextListglobal initEnableResultsByDialog, initEnableResultsByClipboardset Ref2ResultAlbum to make new collection with properties {kind:album, name:nameResultAlbum}tell application "Capture One 20" to tell ref2ResultProjectif ("project" = my convertKindList(kind of (get collection named nameResultProject))) thenglobal debugLogLevel, COPDocRef, Ref2ResultAlbum, enableNotificationsend convertKindListreturn item 1 of kind_s_listreturn kind_s_listif input_is_list thenif fail_flag then loqqed_Error_Halt3(true, "convertKindList received an unexpected Kind string: " & kind_s)set the end of kind_s_list to "session"set the end of kind_s_list to "catalog"set the end of kind_s_list to "imagery"set the end of kind_s_list to "textual"set the end of kind_s_list to "none"set the end of kind_s_list to "heal"set the end of kind_s_list to "clone"set the end of kind_s_list to "adjustment"set the end of kind_s_list to "background"set the end of kind_s_list to "catalog folder"set the end of kind_s_list to "favorite"set the end of kind_s_list to "smart album"set the end of kind_s_list to "album"set the end of kind_s_list to "group"set the end of kind_s_list to "project"set kind_s to Kind_item as textset kind_type to get (text code_start thru (code_start + 1) of kind_s1)set code_start to (get length of kind_s1) - 4if 6 > length of kind_s1 then loqqed_Error_Halt3(true, "convertKind received an unexpected Kind string: " & kind_s1)set the end of kind_s_list to (get Kind_item as text)repeat with Kind_item in kind_listif "«" ≠ (get text 1 of kind_s1) thenset kind_s_list to {}set kind_s1 to (item 1 of kind_list) as textset input_is_list to falseset kind_list to {kind_list}set input_is_list to trueif "list" = (get (class of kind_list) as text) thenon convertKindList(kind_list)("favorite" = item collectionCounter of kindsTopCollections_s) thenif ("favorite" ≠ item collectionCounter of kindsTopCollections_s) then(selectedCollectionIndex ≤ topUserCollectionIndex)))(selectedCollectionMirroredAtTopLast or ((selectedCollectionIndex ≥ bottomUserCollectionIndex) and ¬set selectedCollectionIsUser to ¬({"catalog folder", "favorite"} does not contain last item of kindsTopCollections_s)(selectedCollectionIndex = countTopCollections) and ¬set selectedCollectionMirroredAtTopLast to ¬if ("Trash" = item collectionCounter of namesTopCollections) and ¬("smart album" = item collectionCounter of kindsTopCollections_s) thenif ("in Catalog" = item collectionCounter of namesTopCollections) and ¬(kindSelectedCollection_s = item collectionCounter of kindsTopCollections_s) thenif (nameSelectedCollection = item collectionCounter of namesTopCollections) and ¬set kindsTopCollections_s to my convertKindList(kind of every collection)set {everyTopCollection, namesTopCollections} to {it, name} of every collectionset kindSelectedCollection_s to my convertKindList(kind of selectedCollectionRef)set nameSelectedCollection to name of selectedCollectionRefset current collection to collection 1if (missing value = selectedCollectionRef) thentell application "Capture One 20" to tell COPDocRefglobal everyTopCollection, namesTopCollections, kindsTopCollections_s, countTopCollections, selectedCollectionRef, selectedCollectionIndex, kindSelectedCollection_s, nameSelectedCollectiontell application "Capture One 20" to set COPDocRef to item 1 of current_doc_ref_listset COPDocKind_s to convertKindList(current_doc_kind_p)loqqed_Error_Halt3(true, "The Script could not retrieve the Capture One document - Perhaps a Capture One Dialog window is open?")tell application "Capture One 20" to set COPDocName to get name of current documentglobal debugLogLevel, COPDocName, COPDocKind_s, COPDocRef, theAppNameend validateCOP2my loqqed_Error_Halt3(true, "This COP Version is " & copDetailedVersion & " - the supported COP versions are from " & minCOPversionstr & " to " & maxCOPversionstr)if enableNotifications then display notification "COP Version is unsupported"if (Version_digit < min_digit) or (Version_digit ≥ max_digit) thenif (dig_ctr = digit_count) then set max_digit to max_digit + digit_multset max_digit to max_digit + (get item dig_ctr of maxCOPversion as integer) * digit_multrepeat with dig_ctr from 1 to digit_countset digit_count to count of maxCOPversionset max_digit to 0set maxCOPversion to (splitstringtolist(maxCOPversionstr, "."))set minCOPversion to (splitstringtolist(minCOPversionstr, "."))set numCOPversion to (splitstringtolist((word -1 of copVersion), "."))tell application "Capture One 20" to set copVersion to (get app version)set COPProcNameList to name of every process whose name begins with "Capture One" and background only is falseset COPProcList to every process whose name begins with "Capture One" and background only is falseon validateCOP2(minCOPversionstr, maxCOPversionstr)set {theImageList, everyImageNameList, everyImageIDList} to {null, null, null}global theImageList, everyImageNameList, everyImageIDListend makeImageListset theImageListSize to get count of theImageListset theImageList to makeList3(newImageListSize, false)if debugLogLevel ≥ 2 then log "Increased image list from " & theImageListSize & " to " & newImageListSizeset theImageList to theImageList & makeList3((newImageListSize - theImageListSize), false)if newImageListSize > theImageListSize thenif 0 < theImageListSize thenset newImageListSize to newImageListSize + 24on makeImageList(newImageListSize)end indexCollectionindexCollection((theCollRefList's item collCtr), (theCollKindList's item collCtr), (theCollCollRefList's item collCtr), (theCollImageIDList's item collCtr))repeat with collCtr from 1 to (get count of theCollRefList)local collCtr{every collection's collection, every collection's image's id, my convertKindList(every collection's kind)}tell application "Capture One 20" to tell ThisRef to set {theCollCollRefList, theCollImageIDList, theCollKindList} to ¬if (0 = (get count of theCollRefList)) or ("project" = theCollKind) then return -- don't search below this collection if it is a project, or has no subcollectionsset theImageList's item theImageID to trueif theImageID > theImageListSize then my makeImageList(theImageID)set theImageID to (get anIDString as integer)repeat with anIDString in theIDStringListtell application "Capture One 20" to tell ThisRef to if (0 < (get count of images)) thenlocal anIDString, theImageIDon indexCollection(ThisRef, theCollKind, theCollRefList, theIDStringList)end searchDocumentreturn notFoundNameListset {theImageList, everyImageNameList, everyImageIDList} to {null, null, null} -- clear large lists to control AppleScript's memory utilizationif not (get theImageList's item thisImageID) then ¬copy (everyImageNameList's item vctr) to end of notFoundNameListif thisImageID > theImageListSize thenset thisImageID to (get (everyImageIDList's item vctr) as integer)repeat with vctr from 1 to countImagesset notFoundNameList to {}tell application "Capture One 20" to tell thisDocRef to tell collection "All Images" to set {everyImageIDList, everyImageNameList} to {id of images, name of images}local everyImageIDList, notFoundIdList, notFoundIndexList, notFoundNameList, vctr, theImageID, theImageNameList, anIndexdisplay notification "Done Checking Collections, Now the analysis .."indexCollection(thisCollRef, (theCollKindList's item collCtr), (theCollCollRefList's item collCtr), thisCollImageIDList)tell application "Capture One 20" to tell thisDocRef to set thisCollImageIDList to get id of images of thisCollRefset thisCollRef to (get contents of theCollRefList's item collCtr) -- a CO referencerepeat with collCtr from 1 to (count of theCollRefList)local thisCollRef, thisCollImageIDList, collCtrdisplay notification "Checking each collection"display notification "Finding Images not in a user collection: " & countImages & " images of " & theDocNametell application "Capture One 20" to tell thisDocRef to set theDocName to its namemakeImageList(countImages)set {theImageList, theImageListSize} to {{}, 0} -- initialise and clear the Image listtell application "Capture One 20" to tell thisDocRef to tell collection "All Images" to set countImages to (get count of images){it, its collection, my convertKindList(its kind)}set {theCollRefList, theCollCollRefList, theCollKindList} to ¬tell application "Capture One 20" to tell thisDocRef to tell (every collection whose user is true) to ¬local theCollRefList, countImages, theCollKindList, theCollCollRefList, thisCollCollList, theDocNameglobal theImageListSize, theImageList, debugLogLevelon searchDocument(thisDocRef)loq_Results2(0, true, displayString)set displayString to "All Images found in a User Collection"set displayString to (get countNotFound as text) & " Images not found in a User Collection: " & joinListToString(notFoundNameList, ", ")if 0 < countNotFound thenset countNotFound to (count of notFoundNameList)set notFoundNameList to searchDocument(thisDocRef)tell application "Capture One 20" to set thisDocRef to get current documentvalidateCOP2(minCOPversion, maxCOPversion)set maxCOPversion to "21"set minCOPversion to "12"loq_Results2(0, false, ("Started from: " & parent_name & " Action: Find Images not in a User Collection"))set Result_DocName to "CO_Image_Search.txt"set COPisParent to (get parent_name begins with "Capture One") -- version independentset Script_Title to text item -1 of script_pathset Script_Title to text item -2 of script_pathif (script_path ends with ":") thenset script_path to (path to me) as texttell application "TextEdit" to get count of windowstell application "Finder" to get count of windowseditMacro uuidset uuid to id of first macro group whose name contains theAppset theApp to name of first process whose frontmost is trueend exampleMounter_log ("ERROR: Unknown failure - no mount point listed")log ("Success - found mount point")log (mountPoint)if (mountPoint is not equal to None) thenif (mountPoint is not equal to None) then exit repeatset mountPoint to anItem's objectForKey_("mount-point")repeat with anItem in theEntitiesset mountPoint to Noneset theEntities to thePlist's objectForKey_("system-entities")set thePlist to NSPropertyListSerialization's propertyListFromData_mutabilityOption_format_errorDescription_(theData, NSPropertyListImmutable, None, None)set theData to theString's dataUsingEncoding_(NSUTF8StringEncoding)set theString to NSString's stringWithString_(mountOutputPlist)log ("ERROR: Unable to mount")set mountOutputPlist to (do shell script "/usr/bin/hdiutil attach /Users/mike/Desktop/kodi-14.1-Helix-x86_64.dmg -plist")on exampleMounter_(sender)property NSPropertyListImmutable: myApp's NSPropertyListImmutableproperty NSUTF8StringEncoding: myApp's NSUTF8StringEncodingproperty NSPropertyListSerialization: myApp's class "NSPropertyListSerialization"property NSMutableDictionary: myApp's class "NSMutableDictionary"property NSString: myApp's class "NSString"property NSData: myApp's class "NSData"property None: missing value -- Be careful not to bind this as a IBOutlet!property myApp: current applicationproperty parent: class "NSObject"end messagedisplay alert msg giving up after 1do shell script "/usr/local/bin/growlnotify " & title & " -m " & quoted form of msgon message(title, msg)my message("クリップボード", "AppleScriptをURLに変換して、セットしました。")set the clipboard to myStringset myString to html1 & "applescript://com.apple.scripteditor?action=new&script=" & myString & html2set text item delimiters of AppleScript to oldDelset myString to mylist as stringset text item delimiters of AppleScript to item i of afterListset mylist to every text item of myStringset text item delimiters of AppleScript to xrepeat with x in beforeListset oldDel to text item delimiters of AppleScriptset html2 to "\"\nsetTimeout('window.close();', 1000);\n//-->\n\n\n\n\n"set html1 to "\n\n\n\n\n\n
    " & bookFiles & "" & yy & "
    " & allTagNames & "
    " & aNoteAttach & "
    " & parentCell & "" & spanTag & "
    " & my textHT(aNoteTitle) & "" & cond(aNoteAuthor = "", " ", textHT(aNoteAuthor)) & "" & textHT(trim(text 1 thru (fOff - 1) of aNoteAuthor)) & " ✉️
    " & (((weekday of theDate as string)) & " " & month of theDate as string) & " " & day of theDate as string) & "
    Week " & (n as string) & "