commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
816400fa37afc2390b9a7b5233a7eafb7dc44219
Run.dyalog
Run.dyalog
 output←regexes(op Run options)input;from;to;options;lines;trans;Expand :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⎕NGET regexes 1 :EndTrap options←(0⍴⊂⍬),('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM')/⍨'gidmauo'∊819⌶options~' -' :If 2|≢regexes :OrIf '⍵'∊⊃⌽regexes from←¯1↓regexes :If ~'⍵'∊⊃⌽regexes Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{,⍕{'(Expand⊃⌽regexes)'}⍵}' to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If ∨/'Rr'∊op output←from ⎕R to⍠options⊢input :ElseIf ∨/'Ss'∊op output←from ⎕S to⍠options⊢input :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
 output←regexes(op Run options)input;from;to;options;lines;trans;Expand :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM')/⍨1,'gidmauo'∊819⌶options~' -' :If 2|≢regexes :OrIf '⍵'∊⊃⌽regexes from←¯1↓regexes :If ~'⍵'∊⊃⌽regexes Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{,⍕{'(Expand⊃⌽regexes)'}⍵}' to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If ∨/'Rr'∊op output←from ⎕R to⍠options⊢input :ElseIf ∨/'Ss'∊op output←from ⎕S to⍠options⊢input :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
Fix missing ⊃ and always give simple result.
Fix missing ⊃ and always give simple result.
APL
mit
abrudz/QuadRS
74fc0567c21704cfa8a0a0bdc253e7ef64a9df8f
HTML/_HTML.dyalog
HTML/_HTML.dyalog
:Namespace _HTML :class Form : #._html.form :field public Method←'post' :field public Action←'' :field public Serialize←0 ∇ make;c :Access public :Implements constructor :If {6::0 ⋄ ''≢c∘←##.context ⍵}'_Request' Action←c._Request.Page :EndIf ∇ ∇ make1 action :Access public :Implements constructor Action←action ∇ ∇ r←Render :Access public Attr['action' 'method']←Action Method r←⎕BASE.Render ∇ :endclass :class InputSubmit : #._html.input ∇ Make :Access public :Implements constructor :base (name value)←'submit' 'submit' SetAttr('type' 'submit') ∇ ∇ Make1 args;n;v :Access public :Implements constructor :base args←eis args (n v)←2↑args,(⍴args)↓'submit' 'submit' (name value)←n v SetAttr('type' 'submit') ∇ :endclass :class Input : #._html.input :field public Label←'' ∇ Make1 args;l;n;t;v :Access public :Implements constructor args←eis args t n v l←4↑args,(⍴args)↓'text' '' '' '' (type value Label)←t v l :If ~0∊⍴n ⋄ name←id←n ⋄ :EndIf ∇ ∇ html←Render :Access public html←'' :If ~0∊⍴Label :If id≡⎕NULL ⋄ id←'gen',⍕?1000 ⋄ :EndIf html,←'<label for="',(⍕id),'">',Label,'</label>' :EndIf html,←⎕BASE.Render ∇ :endclass :class InputGrid : #._html.table :field public Border←0 :field public Labels←'' :field public Inputs←'' :field public Headings←'' ∇ html←Render;cells;rows :Access public cells←{⎕NEW #._html.td(⍵)}¨renderIt¨Labels,[1.1]Inputs cells[;1].style←⊂'text-align:right' rows←⎕NEW¨(⊃⍴cells)⍴#._html.tr rows.Add↓cells Content←rows.Render SetAttr'border'(⍕Border) html←⎕BASE.Render ∇ :endclass :class EditField : #._html.input ∇ make1 nm :Access public :Implements constructor name←nm id←name type←'text' ∇ ∇ make2(nm val) :Access public :Implements constructor :If ~1=≡name←nm val ⍝ handle 2-character names (name value)←nm val :EndIf id←name type←'text' ∇ ∇ make3(nm val att) :Access public :Implements constructor :If ~1=≡name←nm val att ⍝ handle 3-character names (name value)←nm val SetAttr att :EndIf id←name type←'text' ∇ :endclass :class Button : #._html.button :field _content←'' ∇ Make0 :Access public :Implements constructor :base SetAttr('type' 'button') ∇ ∇ Make args;n;v :Access public :Implements constructor :base ⍝ arguments are name value {content} args←eis args (n v _content)←3↑args,(⍴args)↓'button' 'button' '' :If 0∊⍴_content ⋄ _content←v ⋄ :EndIf (name value)←n v id←name SetAttr('type' 'button') ∇ ∇ html←Render :Access public :If 0∊⍴Content Content←_content :EndIf html←⎕BASE.Render ∇ :endclass :class Script : #._html.script :field public File←'' :field public Code←'' ∇ Make0 :Access public :Implements constructor SetAttr'type="text/javascript"' ∇ ∇ Make1 params :Access public :Implements constructor params←eis params Code File←2↑params,(⍴params)↓'' '' SetAttr'type="text/javascript"' ∇ ∇ html←Render :Access public :If ~0∊⍴File SetAttr('src'File) :ElseIf ~0∊⍴Code Content←Code :EndIf html←⎕BASE.Render ∇ :endclass :class Style : #._html.style :field public Selector←'' :field public Styles←'' ∇ Make1 params :Access public :Implements constructor params←eis params (Selector Styles)←2↑params,(⍴params)↓'' '' ∇ ∇ html←Render :Access public Content←Selector,#.HTMLUtils.Styles Styles html←⎕BASE.Render ∇ :endclass :class StyleSheet : #._html.link :field public href←'' ∇ Make1 params :Access public :Implements constructor href←params ∇ ∇ html←Render :Access public SetAttr(('href'href)('rel' 'stylesheet')('type' 'text/css')) html←⎕BASE.Render ∇ :endclass :class Table : #._html.table :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←0 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 ∇ Make0 :Access public :Implements constructor ∇ ∇ Make1 data :Access public :Implements constructor Data←data ∇ ∇ html←Render;data;atts;tda;tha;hdrrows;cellids;rowids;rows;x;head;body;table;thead;tbody :Access public data tda tha hdrrows cellids rowids←Data CellAttr HeaderAttr HeaderRows MakeCellIds MakeRowIds hdrrows←⍬⍴hdrrows data←((rows←×/¯1↓⍴data),¯1↑⍴data)⍴data head←body←(0 1×⍴data)⍴⊂'' :If 0≠hdrrows head←{⎕NEW #._html.th ⍵}¨hdrrows↑data :If cellids head.id←{∊'rc',¨⍕¨⍵}¨⍳⍴head :EndIf :If ~0∊⍴tha head.SetAttr¨(⍴head)⍴⊂¨eis tha :EndIf :EndIf :If 0<(⊃⍴data)-hdrrows body←{⎕NEW #._html.td ⍵}¨hdrrows↓data :If cellids body.id←{∊'rc',¨⍕¨⍵}¨hdrrows↓⍳⍴data :EndIf :If ~0∊⍴tda body.SetAttr¨(⍴body)⍴⊂¨eis tda :EndIf :EndIf (table←⎕NEW¨rows⍴#._html.tr).Add↓head⍪body :If rowids table.id←{'row',⍕⍵}⍳rows :EndIf thead←tbody←'' :If 0≠hdrrows (thead←⎕NEW #._html.thead).Add hdrrows↑table :EndIf :If 0<(⊃⍴data)-hdrrows (tbody←⎕NEW #._html.tbody).Add hdrrows↓table :EndIf Content←thead,tbody html←⎕BASE.Render ∇ :endclass :EndNamespace
:Namespace _HTML :class Form : #._html.form :field public Method←'post' :field public Action←'' :field public Serialize←0 ∇ make;c :Access public :Implements constructor :If {6::0 ⋄ ''≢c∘←##.context ⍵}'_Request' Action←c._Request.Page :EndIf ∇ ∇ make1 action :Access public :Implements constructor Action←action ∇ ∇ r←Render :Access public Attr['action' 'method']←Action Method r←⎕BASE.Render ∇ :endclass :class InputSubmit : #._html.input ∇ Make :Access public :Implements constructor :base (name value)←'submit' 'submit' SetAttr('type' 'submit') ∇ ∇ Make1 args;n;v :Access public :Implements constructor :base args←eis args (n v)←2↑args,(⍴args)↓'submit' 'submit' (name value)←n v SetAttr('type' 'submit') ∇ :endclass :class Input : #._html.input :field public Label←'' ∇ Make1 args;l;n;t;v :Access public :Implements constructor args←eis args t n v l←4↑args,(⍴args)↓'text' '' '' '' (type value Label)←t v l :If ~0∊⍴n ⋄ name←id←n ⋄ :EndIf ∇ ∇ html←Render :Access public html←'' :If ~0∊⍴Label :If id≡⎕NULL ⋄ id←'gen',⍕?1000 ⋄ :EndIf html,←'<label for="',(⍕id),'">',Label,'</label>' :EndIf html,←⎕BASE.Render ∇ :endclass :class InputGrid : #._html.table :field public Border←0 :field public Labels←'' :field public Inputs←'' :field public Headings←'' ∇ html←Render;cells;rows :Access public cells←{⎕NEW #._html.td(⍵)}¨renderIt¨Labels,[1.1]Inputs cells[;1].style←⊂'text-align:right' rows←⎕NEW¨(⊃⍴cells)⍴#._html.tr rows.Add↓cells Content←rows.Render SetAttr'border'(⍕Border) html←⎕BASE.Render ∇ :endclass :class EditField : #._html.input ∇ make1 nm :Access public :Implements constructor name←nm id←name type←'text' ∇ ∇ make2(nm val) :Access public :Implements constructor :If ~1=≡name←nm val ⍝ handle 2-character names (name value)←nm val :EndIf id←name type←'text' ∇ ∇ make3(nm val att) :Access public :Implements constructor :If ~1=≡name←nm val att ⍝ handle 3-character names (name value)←nm val SetAttr att :EndIf id←name type←'text' ∇ :endclass :class Button : #._html.button :field _content←'' ∇ Make0 :Access public :Implements constructor :base SetAttr('type' 'button') ∇ ∇ Make args;n;v :Access public :Implements constructor :base ⍝ arguments are name value {content} args←eis args (n v _content)←3↑args,(⍴args)↓'button' 'button' '' :If 0∊⍴_content ⋄ _content←v ⋄ :EndIf (name value)←n v id←name SetAttr('type' 'button') ∇ ∇ html←Render :Access public :If 0∊⍴Content Content←_content :EndIf html←⎕BASE.Render ∇ :endclass :class Script : #._html.script :field public File←'' :field public Code←'' ∇ Make0 :Access public :Implements constructor SetAttr'type="text/javascript"' ∇ ∇ Make1 params :Access public :Implements constructor params←eis params Code File←2↑params,(⍴params)↓'' '' SetAttr'type="text/javascript"' ∇ ∇ html←Render :Access public :If ~0∊⍴File SetAttr('src'File) :ElseIf ~0∊⍴Code Content←Code :EndIf html←⎕BASE.Render ∇ :endclass :class Style : #._html.style :field public Selector←'' :field public Styles←'' ∇ Make1 params :Access public :Implements constructor params←eis params (Selector Styles)←2↑params,(⍴params)↓'' '' ∇ ∇ html←Render :Access public Content←Selector,#.HTMLUtils.Styles Styles html←⎕BASE.Render ∇ :endclass :class StyleSheet : #._html.link :field public href←'' ∇ Make1 params :Access public :Implements constructor href←params ∇ ∇ html←Render :Access public SetAttr(('href'href)('rel' 'stylesheet')('type' 'text/css')) html←⎕BASE.Render ∇ :endclass :class Table : #._html.table :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←0 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 ∇ Make0 :Access public :Implements constructor ∇ ∇ Make1 data :Access public :Implements constructor data←eis data (Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds)←6↑data,(⍴data)↓Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds ∇ ∇ html←Render;data;atts;tda;tha;hdrrows;cellids;rowids;rows;x;head;body;table;thead;tbody :Access public data tda tha hdrrows cellids rowids←Data CellAttr HeaderAttr HeaderRows MakeCellIds MakeRowIds hdrrows←⍬⍴hdrrows data←((rows←×/¯1↓⍴data),¯1↑⍴data)⍴data head←body←(0 1×⍴data)⍴⊂'' :If 0≠hdrrows head←{⎕NEW #._html.th ⍵}¨hdrrows↑data :If cellids head.id←{∊'rc',¨⍕¨⍵}¨⍳⍴head :EndIf :If ~0∊⍴tha head.SetAttr¨(⍴head)⍴⊂¨eis tha :EndIf :EndIf :If 0<(⊃⍴data)-hdrrows body←{⎕NEW #._html.td ⍵}¨hdrrows↓data :If cellids body.id←{∊'rc',¨⍕¨⍵}¨hdrrows↓⍳⍴data :EndIf :If ~0∊⍴tda body.SetAttr¨(⍴body)⍴⊂¨eis tda :EndIf :EndIf (table←⎕NEW¨rows⍴#._html.tr).Add↓head⍪body :If rowids table.id←{'row',⍕⍵}⍳rows :EndIf thead←tbody←'' :If 0≠hdrrows (thead←⎕NEW #._html.thead).Add hdrrows↑table :EndIf :If 0<(⊃⍴data)-hdrrows (tbody←⎕NEW #._html.tbody).Add hdrrows↓table :EndIf Content←thead,tbody html←⎕BASE.Render ∇ :endclass :EndNamespace
Extend _HTML.Table
Extend _HTML.Table
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
4badcb11d75f4533203c0a9f628fdc3143c74d2e
Extensions/SimpleSessions.dyalog
Extensions/SimpleSessions.dyalog
:Class SimpleSessions ⍝ Default Session Handler, used by the WebServer sample ⍝ Manages HTTP sessions using cookies ⍝ When a HTTP request arrives, checks to see if the session cookie is included and the session ⍝ is in the list of valid sessions. If it is, assign the Session property of the request. ⍝ If it isn't, create a new session and set the cookie :Field Public Sessions ⍝ Should be private, really :Field Public Server :Class Page :Field Public URL←'' :Field Public State←⎕NS '' :EndClass :Class Session :Field Public ID←0 :Field Public User←'' :Field Public LastActive←0 :Field Public Cookie←'' :Field Public AuthCookieName←'' :Field Public Timeout←0 :Field Public State :Field Public New←1 :Field Public Pages←0⍴⎕NEW Page :Field Public Server←⍬ :EndClass ∇ Start server;tn;root :Access Public :Implements Constructor ⍝ Initialize Session handler Sessions←0⍴⎕NEW Session root←server.Config.Root Timeout←server.Config.SessionTimeout timeout←Timeout÷24×60 ⍝ Convert minutes to fractions of a day :Trap 22 tn←(root,'sessions.dcf')⎕FCREATE 0 (0 ¯1 0)⎕FSTAC tn 0 ⎕FAPPEND tn ⍝ Session Number ⎕FUNTIE tn :EndTrap tn←(root,'sessions.dcf')⎕FSTIE 0 NextSession←⎕FREAD tn,1 ⎕FUNTIE tn Server←server ∇ ∇ GetSession req;c;tn;now;session;ns;new;t_out;i;r :Access Public ⍝ Return session. Right argument is a HTTPRequest. :If (1=Server.Config.CreateSession)∨'get'≢req.Method :Hold 'Sessions' session←req.GetCookie'Session' now←#.Dates.DateToIDN ⎕TS :If new←(1⊃⍴Sessions)<i←Sessions.Cookie⍳⊂session ⍝ Cookie is not in the table c←SessionCookie NextSession Sessions←Sessions,r←⎕NEW Session r.(ID User LastActive Cookie State Server)←NextSession''now c(⎕NS'')Server NextSession←(2*30)|NextSession+1 tn←(req.Server.Config.Root,'sessions.dcf')⎕FSTIE 0 NextSession ⎕FREPLACE tn,1 ⎕FUNTIE tn req.SetCookie'Session'c'/' 30 'HttpOnly' req.Session←r req.Server.onSessionStart req :Else ⍝ Old session (r←i⊃Sessions).LastActive←now ⍝ Just register activity r.New←0 req.Session←r :EndIf :EndHold :EndIf ∇ ∇ KillSessions ids;mask;i :Access Public :Hold 'Sessions' :If ∨/mask←Sessions.ID∊ids :For i :In mask/⍳⍴mask Server.onSessionEnd i⊃Sessions :EndFor Sessions/⍨←~mask :EndIf :EndHold ∇ ∇ Logout req;session;i;z :Access Public Instance ⍝ End session due to user request session←req.GetCookie'Session' :If (1⊃⍴Sessions)≥i←Sessions.Cookie⍳⊂session ⍝ Cookie is in the table req.Server.onSessionEnd(i⊃Sessions) req.DelCookie'Session' :If 0≠⍴z←req.Session.AuthCookieName ⋄ req.DelCookie z ⋄ :EndIf req.Return'Logged out ...' :Else req.Return'No session established ...' :EndIf ∇ ∇ r←SessionCookie n;⎕RL;z;seed;p ⍝ Create Cookie from session ID or vice versa :If (10|⎕DR n)∊0 2 ⍝ Session ID from Cookie z←⎕UCS #.Base64.Decode n ⎕RL←256⊥2↑z ⋄ p←30?30 r←30⍴0 ⋄ r[p]←2↓z r←256⊥4↑r :Else ⍝ Session ID to Cookie ⎕RL←10000000|3⊃⎕AI ⎕RL←seed←?¯1+256*2 ⋄ p←30?30 r←#.Base64.Encode #.Base64.Char(256 256⊤seed),((256 256 256 256⊤n),¯1+?26⍴256)[p] :EndIf ∇ ∇ HouseKeeping Server;now;m;i;p ⍝ Check to see if any sessions have expired due to inactivity ⍝ Call any page application callbacks (_Close) if necessary :Access Public now←#.Dates.DateToIDN ⎕TS :If ∨/m←Sessions.LastActive<now-timeout :Hold 'Sessions' :For i :In m/⍳⍴m Server.onSessionEnd i⊃Sessions :If 0≠⍴p←(i⊃Sessions).Pages :AndIf 0≠⊃p.⎕NC⊂'_Close' p._Close i⊃Sessions :EndIf :EndFor Sessions←(~m)/Sessions :EndHold :EndIf ∇ :EndClass
:Class SimpleSessions ⍝ Default Session Handler, used by the WebServer sample ⍝ Manages HTTP sessions using cookies ⍝ When a HTTP request arrives, checks to see if the session cookie is included and the session ⍝ is in the list of valid sessions. If it is, assign the Session property of the request. ⍝ If it isn't, create a new session and set the cookie :Field Public Sessions ⍝ Should be private, really :Field Public Server :Class Page :Field Public URL←'' :Field Public State←⎕NS '' :EndClass :Class Session :Field Public ID←0 :Field Public User←'' :Field Public LastActive←0 :Field Public Cookie←'' :Field Public AuthCookieName←'' :Field Public Timeout←0 :Field Public State :Field Public New←1 :Field Public Pages←0⍴⎕NEW Page :Field Public Server←⍬ :EndClass ∇ Start server;tn;root :Access Public :Implements Constructor ⍝ Initialize Session handler Sessions←0⍴⎕NEW Session root←server.Config.Root Timeout←server.Config.SessionTimeout timeout←Timeout÷24×60 ⍝ Convert minutes to fractions of a day :Trap 22 tn←(root,'sessions.dcf')⎕FCREATE 0 (0 ¯1 0)⎕FSTAC tn 0 ⎕FAPPEND tn ⍝ Session Number ⎕FUNTIE tn :EndTrap tn←(root,'sessions.dcf')⎕FSTIE 0 NextSession←⎕FREAD tn,1 ⎕FUNTIE tn Server←server ∇ ∇ GetSession req;c;tn;now;session;ns;new;t_out;i;r :Access Public ⍝ Return session. Right argument is a HTTPRequest. :If (1=Server.Config.CreateSession)∨'get'≢req.Method :Hold 'Sessions' session←req.GetCookie'Session' now←#.Dates.DateToIDN ⎕TS :If new←(1⊃⍴Sessions)<i←Sessions.Cookie⍳⊂session ⍝ Cookie is not in the table c←SessionCookie NextSession Sessions←Sessions,r←⎕NEW Session r.(ID User LastActive Cookie State Server Timeout)←NextSession''now c(⎕NS'')Server timeout NextSession←(2*30)|NextSession+1 tn←(req.Server.Config.Root,'sessions.dcf')⎕FSTIE 0 NextSession ⎕FREPLACE tn,1 ⎕FUNTIE tn req.SetCookie'Session'c'/' 30 'HttpOnly' req.Session←r req.Server.onSessionStart req :Else ⍝ Old session (r←i⊃Sessions).LastActive←now ⍝ Just register activity r.New←0 req.Session←r :EndIf :EndHold :EndIf ∇ ∇ KillSessions ids;mask;i :Access Public :Hold 'Sessions' :If ∨/mask←Sessions.ID∊ids :For i :In mask/⍳⍴mask Server.onSessionEnd i⊃Sessions :EndFor Sessions/⍨←~mask :EndIf :EndHold ∇ ∇ Logout req;session;i;z :Access Public Instance ⍝ End session due to user request session←req.GetCookie'Session' :If (1⊃⍴Sessions)≥i←Sessions.Cookie⍳⊂session ⍝ Cookie is in the table req.Server.onSessionEnd(i⊃Sessions) req.DelCookie'Session' :If 0≠⍴z←req.Session.AuthCookieName ⋄ req.DelCookie z ⋄ :EndIf req.Return'Logged out ...' :Else req.Return'No session established ...' :EndIf ∇ ∇ r←SessionCookie n;⎕RL;z;seed;p ⍝ Create Cookie from session ID or vice versa :If (10|⎕DR n)∊0 2 ⍝ Session ID from Cookie z←⎕UCS #.Base64.Decode n ⎕RL←256⊥2↑z ⋄ p←30?30 r←30⍴0 ⋄ r[p]←2↓z r←256⊥4↑r :Else ⍝ Session ID to Cookie ⎕RL←10000000|3⊃⎕AI ⎕RL←seed←?¯1+256*2 ⋄ p←30?30 r←#.Base64.Encode #.Base64.Char(256 256⊤seed),((256 256 256 256⊤n),¯1+?26⍴256)[p] :EndIf ∇ ∇ HouseKeeping Server;now;m;i;p ⍝ Check to see if any sessions have expired due to inactivity ⍝ Call any page application callbacks (_Close) if necessary :Access Public now←#.Dates.DateToIDN ⎕TS :If ∨/m←Sessions.LastActive<now-Sessions.Timeout :Hold 'Sessions' :For i :In m/⍳⍴m Server.onSessionEnd i⊃Sessions :If 0≠⍴p←(i⊃Sessions).Pages :AndIf 0≠⊃p.⎕NC⊂'_Close' p._Close i⊃Sessions :EndIf :EndFor Sessions←(~m)/Sessions :EndHold :EndIf ∇ :EndClass
Allow each session to have its own timeout
Allow each session to have its own timeout
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
0324eaa0c3429e92b3744bc7e170905fd12880cc
Run.dyalog
Run.dyalog
 output←regexes(op Run options)input;from;to;options;lines;trans;Expand :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM')/⍨1,'gidmauo'∊819⌶options~' -' :If 2|≢regexes :OrIf '⍵'∊⊃⌽regexes from←¯1↓regexes :If ~'⍵'∊⊃⌽regexes Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{,⍕{'(Expand⊃⌽regexes)'}⍵}' to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If ∨/'Rr'∊op output←from ⎕R to⍠options⊢input :ElseIf ∨/'Ss'∊op output←from ⎕S to⍠options⊢input :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
 output←regexes(op Run options)input;from;to;options;lines;trans;Expand :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶options~' -' options↓⍨←∨/'Ss'∊op :If 2|≢regexes :OrIf '⍵'∊⊃⌽regexes from←¯1↓regexes :If ~'⍵'∊⊃⌽regexes Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{,⍕{'(Expand⊃⌽regexes)'}⍵}' to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If ∨/'Rr'∊op output←from ⎕R to⍠options⊢input :ElseIf ∨/'Ss'∊op output←from ⎕S to⍠options⊢input :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
add missing OM option value and remove ResultText for QuadS
add missing OM option value and remove ResultText for QuadS
APL
mit
abrudz/QuadRS
e6ef2ace0f391e10e32c77769ffdb5f644b8f75a
Utils/SQL.dyalog
Utils/SQL.dyalog
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' :If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :Else ⋄ r←601 ''('Unable to connect to "',database,'" due to ',⍕3⊃rc) :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx;data ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} {nulls} r←⎕NS'' r.(ReturnCode Data Message)←¯1(0 0⍴0)'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 data←'' :If 3≤⍴ctl :If 1<|≡3⊃ctl ⋄ data←3⊃ctl :If 3<⍴ctl ⋄ data←(⊂data),ctl[4] ⋄ :EndIf ⍝ deal with nulls :Else ⋄ data←2↓ctl ⋄ :EndIf :EndIf →(0<1⊃z←#.SQA.Exec(⊂c),data)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1: →(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.Data←⊃2⊃z l2: :If 0<r.ReturnCode←1⊃z ⋄ r.Message←3⊃z ⋄ :EndIf →(0<1⊃z←#.SQA.Close conx)↓0 l3: r.ReturnCode←1⊃z r.Message←3⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' ⍝:If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :If 1>1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx ⍝ Baas: warning (¯1) means conn was established, so return ok! ⍝ discussed with BHC in Italy ;-) :Else ⋄ r←601 ''('Unable to connect to "',database,'" due to ',⍕3⊃rc) :EndIf :Else ⋄ r←601 ''('Unable to connect to "',database,'" due to ',⍕3⊃rc) :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx;data ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} {nulls} r←⎕NS'' r.(ReturnCode Data Message)←¯1(0 0⍴0)'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 data←'' :If 3≤⍴ctl :If 1<|≡3⊃ctl ⋄ data←3⊃ctl :If 3<⍴ctl ⋄ data←(⊂data),ctl[4] ⋄ :EndIf ⍝ deal with nulls :Else ⋄ data←2↓ctl ⋄ :EndIf :EndIf →(0<1⊃z←#.SQA.Exec(⊂c),data)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1: →(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.Data←⊃2⊃z l2: :If 0<r.ReturnCode←1⊃z ⋄ r.Message←3⊃z ⋄ :EndIf →(0<1⊃z←#.SQA.Close conx)↓0 l3: r.ReturnCode←1⊃z r.Message←3⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
Update SQL.dyalog
Update SQL.dyalog Connection warnings imply that conn was established, so the result of ConnectTo should show that (and not indicate failure as before)
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
60df8b13825b313059d0600aff26d8dadec616ed
Run.dyalog
Run.dyalog
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r;last;fns;Quote;q;hasrepeat;postproc;combine :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 hasrepeat←∨/args∊⍨'≡',⎕D ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S fns←+/∧\'⍵'∊¨regexes postproc←∊'{⍵}','∘{'∘,¨,∘'}'¨fns↑regexes ⍝ post-processing functions regexes↓⍨←fns last←⊃⌽regexes :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊last ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊last ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{'(r/',⍕{')(Expand last)(r/'}⍵')'}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf combine←'{⊃,/⍵↑¨⍨⌈/≢¨⍵}' q←⎕NS ⍬ :If s r∨.∧'?'∊args Quote←{q,q,⍨⍵/⍨1+⍵=q←''''} q.from←⍕Quote¨from :If 3=⎕NC'to' q.to←1⌽' ',3↓∊⎕NR'to' :Else q.to←⍕Quote¨to :EndIf :If 3=⎕NC'repeat' q.repeat←'⍣',∊⎕NR'repeat' :ElseIf 1≢repeat q.repeat←'⍣',⍕repeat :Else q.repeat←'' :EndIf :If ×≢options q.options←'⍠',∊{' (',(Quote⊃⍵),' ',({0 1∊⍨⊂⍵:⍕⍵ ⋄ '''',⍵,''''}⊃⌽⍵),')'}¨options :Else q.options←'' :EndIf q.op←s r/'SR' q.postproc←4↓postproc q.postproc,←(hasrepeat∧s)/(''≡q.postproc)↓'∘',combine output←q.(postproc,from,'⎕',op,to,options,repeat) :Else :Trap 6 11 :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←(⍎combine)⍣hasrepeat⊢output ⍝ merge search results if we need to continue :EndIf output←(⍎postproc)output :Case 6 ⍝ no output output←'*** Left operand must be ''R'' or ''S'' ***' :Case 11 ⍝ faulty regex output←'*** ',⎕DMX.Message,' ─ try adding ? to the Arguments to see the attempted APL expression ***' :EndTrap :EndIf
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r;last;fns;Quote;q;hasrepeat;postproc;combine :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 hasrepeat←∨/args∊⍨'≡',⎕D ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' 1)('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S fns←+/∧\'⍵'∊¨regexes postproc←∊'{⍵}','∘{'∘,¨,∘'}'¨fns↑regexes ⍝ post-processing functions regexes↓⍨←fns last←⊃⌽regexes :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊last ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊last ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX,⊂'to←{',(r/',⍕{'),(Expand last),(r/'}⍵'),'}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf combine←'{⊃,/⍵↑¨⍨⌈/≢¨⍵}' q←⎕NS ⍬ :If s r∨.∧'?'∊args Quote←{q,q,⍨⍵/⍨1+⍵=q←''''} q.from←⍕Quote¨from :If 3=⎕NC'to' q.to←1⌽' ',3↓∊⎕NR'to' :Else q.to←⍕Quote¨to :EndIf :If 3=⎕NC'repeat' q.repeat←'⍣',∊⎕NR'repeat' :ElseIf 1≢repeat q.repeat←'⍣',⍕repeat :Else q.repeat←'' :EndIf :If ×≢options q.options←'⍠',∊{' (',(Quote⊃⍵),' ',({0 1∊⍨⊂⍵:⍕⍵ ⋄ '''',⍵,''''}⊃⌽⍵),')'}¨options :Else q.options←'' :EndIf q.op←s r/'SR' q.postproc←4↓postproc q.postproc,←(hasrepeat∧s)/(''≡q.postproc)↓'∘',combine output←q.(postproc,from,'⎕',op,to,options,repeat) :Else :Trap 6 11 :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←(⍎combine)⍣hasrepeat⊢output ⍝ merge search results if we need to continue :EndIf output←(⍎postproc)output :Case 6 ⍝ no output output←'*** Left operand must be ''R'' or ''S'' ***' :Case 11 ⍝ faulty regex output←'*** ',⎕DMX.Message,' ─ try adding ? to the Arguments to see the attempted APL expression ***' :EndTrap :EndIf
Remove bad quotes. Use one-liner transformation function.
Remove bad quotes. Use one-liner transformation function.
APL
mit
abrudz/QuadRS
47d8438f9a4f45f6a7a16e4529081e54cab9b0b5
Utils/SQL.dyalog
Utils/SQL.dyalog
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' :If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :Else ⋄ r←601('Unable to connect to "',database,'"') :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} r←⎕NS'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 →(0<1⊃z←#.SQA.Exec(⊂c),2↓ctl)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1:→(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.ReturnCode←1⊃z r.Data←⊃2⊃z l2:→(0<1⊃z←#.SQA.Close conx)↓0 l3:r.ReturnCode←1⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' :If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :Else ⋄ r←601('Unable to connect to "',database,'"') :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx;data ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} r←⎕NS'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 :If 1<|≡3⊃ctl ⋄ data←3⊃ctl ⋄ :Else ⋄ data←2↓ctl ⋄ :EndIf →(0<1⊃z←#.SQA.Exec(⊂c),data)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1:→(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.ReturnCode←1⊃z r.Data←⊃2⊃z l2:→(0<1⊃z←#.SQA.Close conx)↓0 l3:r.ReturnCode←1⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
Improve SQL.Do bind variable handling
Improve SQL.Do bind variable handling
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
75cffd24be205fa0c630dc47afa45b8535b31e69
src/prelude.apl
src/prelude.apl
⍬←() ⍝ ⍬ <=> 0⍴0 ⍝ ⍴⍬ <=> ,0 ⍝# ⍬←5 !!! ⍝ ⍳0 <=> ⍬ ⍝ ⍴0 <=> ⍬ ⍝ ⍬ <=> ⍬ ⍝ ⍬⍬ <=> ⍬ ⍬ ⍝ 1⍬2⍬3 <=> 1 ⍬ 2 ⍬ 3 ~←~⍠{(~⍺∊⍵)/⍺} ⍝ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"~"AEIOU" <=> 'BCDFGHJKLMNPQRSTVWXYZ' ⍝ 1 2 3 4 5 6~2 4 6 <=> 1 3 5 ⍝ "THIS IS TEXT"~" " <=> 'THISISTEXT' ⍝ "THIS" "AND" "THAT"~"T" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~"AND" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~⊂"AND" <=> 'THIS' 'THAT' ⍝ "THIS" "AND" "THAT"~"TH" "AND" <=> 'THIS' 'THAT' ⍝ 11 12 13 14 15 16~2 3⍴1 2 3 14 5 6 <=> 11 12 13 15 16 ⍝ (2 2⍴⍳4)~2 !!! RANK ERROR _hook←{⍵⍶⍹⍵;⍺⍶⍹⍵} ⍝ (+÷)\3 7 16 ¯294 <=> (3 3.142857142857143 3.1415929203539825 3.141592653921421) ⍝ (=⌊)123 <=> 1 ⍝ (=⌊)123.4 <=> 0 ⍝ (÷⍟)1000 <=> 144.76482730108395 ⊃←{ 0=⍴⍴⍵:↑⍵ 0=×/⍴⍵:⍵ shape←⍴⍵ ⋄ ⍵←,⍵ r←⌈/≢¨shapes←⍴¨⍵ ⍝ maximum rank of all shapes max←↑⌈/shapes←(⍴ ↓ (r⍴1)∘,)¨shapes ⍝ maximum shape of rank adjusted shapes (shape,max)⍴↑⍪/shapes{max↑⍺⍴⍵}¨⍵ ; 1<⍴⍴⍺:↗'RANK ERROR' x←⍵ { 1<⍴⍴⍵:↗'RANK ERROR' ⍵←,⍵ (⍴⍵)≠⍴⍴x:↗'RANK ERROR' ∨/⍵≥⍴x:↗'INDEX ERROR' x←⊃⍵⌷x }¨⍺ x } ⍝ ⊃3 <=> 3 ⍝ ⊃(1 2)(3 4) <=> 2 2⍴1 2 3 4 ⍝ ⊃(1 2)(3 4 5) <=> 2 3⍴1 2 0 3 4 5 ⍝ ⊃1 2 <=> 1 2 ⍝ ⊃(1 2)3 <=> 2 2⍴1 2 3 0 ⍝ ⊃1(2 3) <=> 2 2⍴1 0 2 3 ⍝ ⊃2 2⍴1(1 1 2⍴3 4)(5 6)(2 0⍴0) <=> 2 2 1 2 2⍴1 0 0 0 3 4 0 0 5 6 0 0 0 0 0 0 ⍝ ⊃⍬ <=> ⍬ ⍝ ⊃2 3 0⍴0 <=> 2 3 0⍴0 ⍝ ⍬⊃3 <=> 3 ⍝ 2⊃'PICK' <=> 'C' ⍝ (⊂1 0)⊃2 2⍴'ABCD' <=> 'C' ⍝ 1⊃'foo' 'bar' <=> 'bar' ⍝ 1 2⊃'foo' 'bar' <=> 'r' ⍝ (2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 1⍴0)⊃2 2⍴0 !!! RANK ERROR ⍝ (⊂2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 2)⊃1 2 !!! RANK ERROR ⍝ (⊂0 2)⊃2 2⍴'ABCD' !!! INDEX ERROR ⍪←{(≢⍵)(×/1↓⍴⍵)⍴⍵; ⍺,[0]⍵} ⍝ ⍪2 3 4 <=> 3 1⍴2 3 4 ⍝ ⍪0 <=> 1 1⍴0 ⍝ ⍪2 2⍴2 3 4 5 <=> 2 2⍴2 3 4 5 ⍝ ⍴⍪2 3⍴⍳6 <=> 2 3 ⍝ ⍴⍪2 3 4⍴⍳24 <=> 2 12 ⍝ (2 3⍴⍳6)⍪9 <=> 3 3⍴(0 1 2 3 4 5 9 9 9) ⍝ 1⍪2 <=> 1 2 ⊢←{⍵} ⍝ 123⊢456 <=> 456 ⍝ ⊢456 <=> 456 ⊣←{;⍺} ⍝ 123⊣456 <=> 123 ⍝ ⊣456 <=> ⍬ ≢←{⍬⍴(⍴⍵),1; ~⍺≡⍵} ⍝ ≢0 <=> 1 ⍝ ≢0 0 0 <=> 3 ⍝ ≢⍬ <=> 0 ⍝ ≢2 3⍴⍳6 <=> 2 ⍝ 3≢3 <=> 0 ⌹←{ norm←{(⍵+.×+⍵)*0.5} QR←{ ⍝ QR decomposition n←(⍴⍵)[1] 1≥n:{t←norm,⍵ ⋄ (⍵÷t)(⍪t)}⍵ m←⌈n÷2 a0←((1↑⍴⍵),m)↑⍵ a1←(0,m)↓⍵ (q0 r0)←∇a0 c←(+⍉q0)+.×a1 (q1 r1)←∇a1-q0+.×c (q0,q1)((r0,c)⍪((⌊n÷2),-n)↑r1) } Rinv←{ ⍝ Inverse of an upper triangular matrix 1=n←1↑⍴⍵:÷⍵ m←⌈n÷2 ai←∇(m,m)↑⍵ di←∇(m,m)↓⍵ b←(m,m-n)↑⍵ bx←-ai+.×b+.×di (ai,bx)⍪((⌊n÷2),-n)↑di } 0=⍴⍴⍵:÷⍵ 1=⍴⍴⍵:,∇⍪⍵ 2≠⍴⍴⍵:↗'ASSERTION ERROR' 0∊≥/⍴⍵:↗'ASSERTION ERROR' (Q R)←QR ⍵ (Rinv R)+.×+⍉Q ; (⌹⍵)+.×⍺ } ⍝ ⌹2 <=> .5 ⍝ ⌹2 2⍴4 3 3 2 <=> 2 2⍴¯2 3 3 ¯4 ⍝ (4 4⍴12 1 4 10 ¯6 ¯5 4 7 ¯4 9 3 4 ¯2 ¯6 7 7)⌹93 81 93.5 120.5 <=> ⍝ ... .0003898888816687221 ¯.005029566573526544 .04730651764247189 .0705568912859835 ⍨←{⍵⍶⍵;⍵⍶⍺} ⍝ 17-⍨23 <=> 6 ⍝ 7⍴⍨2 3 <=> 2 3⍴7 ⍝ +⍨2 <=> 4 ⍝ -⍨123 <=> 0
⍬←() ⍝ ⍬ <=> 0⍴0 ⍝ ⍴⍬ <=> ,0 ⍝# ⍬←5 !!! ⍝ ⍳0 <=> ⍬ ⍝ ⍴0 <=> ⍬ ⍝ ⍬ <=> ⍬ ⍝ ⍬⍬ <=> ⍬ ⍬ ⍝ 1⍬2⍬3 <=> 1 ⍬ 2 ⍬ 3 ~←~⍠{(~⍺∊⍵)/⍺} ⍝ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"~"AEIOU" <=> 'BCDFGHJKLMNPQRSTVWXYZ' ⍝ 1 2 3 4 5 6~2 4 6 <=> 1 3 5 ⍝ "THIS IS TEXT"~" " <=> 'THISISTEXT' ⍝ "THIS" "AND" "THAT"~"T" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~"AND" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~⊂"AND" <=> 'THIS' 'THAT' ⍝ "THIS" "AND" "THAT"~"TH" "AND" <=> 'THIS' 'THAT' ⍝ 11 12 13 14 15 16~2 3⍴1 2 3 14 5 6 <=> 11 12 13 15 16 ⍝ (2 2⍴⍳4)~2 !!! RANK ERROR _hook←{⍵⍶⍹⍵;⍺⍶⍹⍵} ⍝ (+÷)\3 7 16 ¯294 <=> (3 3.142857142857143 3.1415929203539825 3.141592653921421) ⍝ (=⌊)123 <=> 1 ⍝ (=⌊)123.4 <=> 0 ⍝ (÷⍟)1000 <=> 144.76482730108395 ⊃←{ 0=⍴⍴⍵:↑⍵ 0=×/⍴⍵:⍵ shape←⍴⍵ ⋄ ⍵←,⍵ r←⌈/≢¨shapes←⍴¨⍵ ⍝ maximum rank of all shapes max←↑⌈/shapes←(⍴ ↓ (r⍴1)∘,)¨shapes ⍝ maximum shape of rank adjusted shapes (shape,max)⍴↑⍪/shapes{max↑⍺⍴⍵}¨⍵ ; 1<⍴⍴⍺:↗'RANK ERROR' x←⍵ { 1<⍴⍴⍵:↗'RANK ERROR' ⍵←,⍵ (⍴⍵)≠⍴⍴x:↗'RANK ERROR' ∨/⍵≥⍴x:↗'INDEX ERROR' x←⊃⍵⌷x }¨⍺ x } ⍝ ⊃3 <=> 3 ⍝ ⊃(1 2)(3 4) <=> 2 2⍴1 2 3 4 ⍝ ⊃(1 2)(3 4 5) <=> 2 3⍴1 2 0 3 4 5 ⍝ ⊃1 2 <=> 1 2 ⍝ ⊃(1 2)3 <=> 2 2⍴1 2 3 0 ⍝ ⊃1(2 3) <=> 2 2⍴1 0 2 3 ⍝ ⊃2 2⍴1(1 1 2⍴3 4)(5 6)(2 0⍴0) <=> 2 2 1 2 2⍴1 0 0 0 3 4 0 0 5 6 0 0 0 0 0 0 ⍝ ⊃⍬ <=> ⍬ ⍝ ⊃2 3 0⍴0 <=> 2 3 0⍴0 ⍝ ⍬⊃3 <=> 3 ⍝ 2⊃'PICK' <=> 'C' ⍝ (⊂1 0)⊃2 2⍴'ABCD' <=> 'C' ⍝ 1⊃'foo' 'bar' <=> 'bar' ⍝ 1 2⊃'foo' 'bar' <=> 'r' ⍝ (2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 1⍴0)⊃2 2⍴0 !!! RANK ERROR ⍝ (⊂2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 2)⊃1 2 !!! RANK ERROR ⍝ (⊂0 2)⊃2 2⍴'ABCD' !!! INDEX ERROR ⍪←{(≢⍵)(×/1↓⍴⍵)⍴⍵; ⍺,[0]⍵} ⍝ ⍪2 3 4 <=> 3 1⍴2 3 4 ⍝ ⍪0 <=> 1 1⍴0 ⍝ ⍪2 2⍴2 3 4 5 <=> 2 2⍴2 3 4 5 ⍝ ⍴⍪2 3⍴⍳6 <=> 2 3 ⍝ ⍴⍪2 3 4⍴⍳24 <=> 2 12 ⍝ (2 3⍴⍳6)⍪9 <=> 3 3⍴(0 1 2 3 4 5 9 9 9) ⍝ 1⍪2 <=> 1 2 ⊢←{⍵} ⍝ 123⊢456 <=> 456 ⍝ ⊢456 <=> 456 ⊣←{;⍺} ⍝ 123⊣456 <=> 123 ⍝ ⊣456 <=> ⍬ ≢←{⍬⍴(⍴⍵),1; ~⍺≡⍵} ⍝ ≢0 <=> 1 ⍝ ≢0 0 0 <=> 3 ⍝ ≢⍬ <=> 0 ⍝ ≢2 3⍴⍳6 <=> 2 ⍝ 3≢3 <=> 0 ⌹←{ norm←{(⍵+.×+⍵)*0.5} QR←{ ⍝ QR decomposition n←(⍴⍵)[1] 1≥n:{t←norm,⍵ ⋄ (⍵÷t)(⍪t)}⍵ m←⌈n÷2 a0←((1↑⍴⍵),m)↑⍵ a1←(0,m)↓⍵ (q0 r0)←∇a0 c←(+⍉q0)+.×a1 (q1 r1)←∇a1-q0+.×c (q0,q1)((r0,c)⍪((⌊n÷2),-n)↑r1) } Rinv←{ ⍝ Inverse of an upper triangular matrix 1=n←1↑⍴⍵:÷⍵ m←⌈n÷2 ai←∇(m,m)↑⍵ di←∇(m,m)↓⍵ b←(m,m-n)↑⍵ bx←-ai+.×b+.×di (ai,bx)⍪((⌊n÷2),-n)↑di } 0=⍴⍴⍵:÷⍵ 1=⍴⍴⍵:,∇⍪⍵ 2≠⍴⍴⍵:↗'RANK ERROR' 0∊≥/⍴⍵:↗'LENGTH ERROR' (Q R)←QR ⍵ (Rinv R)+.×+⍉Q ; (⌹⍵)+.×⍺ } ⍝ ⌹2 <=> .5 ⍝ ⌹2 2⍴4 3 3 2 <=> 2 2⍴¯2 3 3 ¯4 ⍝ (4 4⍴12 1 4 10 ¯6 ¯5 4 7 ¯4 9 3 4 ¯2 ¯6 7 7)⌹93 81 93.5 120.5 <=> ⍝ ... .0003898888816687221 ¯.005029566573526544 .04730651764247189 .0705568912859835 ⍝ ⌹2 2 2⍴⍳8 !!! RANK ERROR ⍝ ⌹2 3⍴⍳6 !!! LENGTH ERROR ⍨←{⍵⍶⍵;⍵⍶⍺} ⍝ 17-⍨23 <=> 6 ⍝ 7⍴⍨2 3 <=> 2 3⍴7 ⍝ +⍨2 <=> 4 ⍝ -⍨123 <=> 0
Throw the correct errors from matrix inverse, as specified in the ISO standard.
Throw the correct errors from matrix inverse, as specified in the ISO standard.
APL
mit
fineline/apl,fineline/apl,fineline/apl,fineline/apl
57f9e3f63669bf89d774fc18bb035e0c515a45f6
MS3/Code/Templates/MiPageSample.dyalog
MS3/Code/Templates/MiPageSample.dyalog
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code ∇ {r}←Wrap;lang;server;controls;sp;c :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server controls←∪Walk Body.Content ⍝ we use Syncfusion (which uses jQuery) to set up the controls to do cool stuff Use'Syncfusion' ⍝ this is a resource defined in Config/Resources.xml ⍝ set the title display in the browser to the name of the application defined in Config/Server.xml Add _.title server.Config.Name ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div Body.Push _.div'id="contentblock"' ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HTMLInput.APLToHTMLColour ⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' :If ~0∊⍴controls c←Body.Content Body.Content←'' (sp←Body.Add _.StackPanel(⊂FormatControls controls)c).Horizontal←1 :EndIf ⍝ wrap the content of the <body> element in a div Body.Push _.div'class="bodyblock"' ⍝ add the footer to the bottom of the page Add #.Files.GetText server.Config.Root,'Styles\footer.txt' ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.GetText server.Config.Root,'Styles\banner.txt' Body.Push _.div'id="wrapper"' ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script'$(function(){$("#bannerimage").on("click", function(evt){$("#contentblock,#codeblock,.widgethelp").toggle(400,"swing");});});' ⍝ set the language for the page lang←server.Config.Lang ⍝ use the language specified in Server.xml Set'lang="',lang,'" xml:lang="',lang,'" xmlns="http://www.w3.org/1999/xhtml"' :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (#.HtmlElement.isClass e)∨#.HtmlElement.isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ ∇ r←FormatControls controls;ctrls;ns;desc;field;n;ctrl;i;c;ref;l;u;nss;item;cn ctrls←⊃{⍺ ⍵}#.Utils.∆key/↓[1]0 1↓↑{⎕ML←3 ⋄ {⍵⊂⍨⍵≠'.'}⍕⍵}¨controls field←{0::'' ⋄ ⍺⍎⍵} nss←'_DC' '_SF' '_JQ' '_html' desc←'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' (r←⎕NEW _.div).class←'widgethelp' r.Add'This Page Contains<hr/>' :Trap 0 :For (ns ctrl i) :In ctrls{↓(⍺,⍵)[⍋⍵;]}nss⍳{(⊃⍣(¯1+≡⍵))⍵}¨ctrls[;1] (r.Add _.span(i⊃desc)).class←'widgetNs' u←r.Add _.ul n←#.⍎ns←⊃ns :For c :In ctrl ref←n.⍎c item←⍬ :Select ns :Case '_DC' item←u.Add _.li(New _.a(c(('href=/Documentation/DyalogAPIs/WidgetDoc?namespace=',ns,'&widget=',c)'target=_blank'))) :Case '_SF' item←u.Add _.li(New _.a c(('href'('http://js.syncfusion.com/demos/web/#!/azure/',(2×'ej'≡2↑c)↓c))('target' '_blank'))) :Case '_JQ' item←u.Add _.li(New _.a c(('href'('http://jqueryui.com/',(2×'jq'≡2↑c)↓c))('target' '_blank'))) :Case '_html' cn←c :If ~0∊⍴('^h[1-6]$'⎕S{⍵.Match})c cn←'hn' :EndIf item←u.Add _.li(New _.a c(('href'('http://www.w3schools.com/tags/tag_',cn,'.asp'))('target' '_blank'))) :EndSelect :If 0∊⍴item u.Add _.li c :EndIf :EndFor :EndFor :EndTrap ∇ :EndClass
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code ∇ {r}←Wrap;lang;server;controls;sp;c :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server controls←∪Walk Body.Content ⍝ we use Syncfusion (which uses jQuery) to set up the controls to do cool stuff Use'Syncfusion' ⍝ this is a resource defined in Config/Resources.xml ⍝ set the title display in the browser to the name of the application defined in Config/Server.xml Add _.title server.Config.Name ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div Body.Push _.div'id="contentblock"' ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HTMLInput.APLToHTMLColour ⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' :If ~0∊⍴controls c←Body.Content Body.Content←'' (sp←Body.Add _.StackPanel(⊂FormatControls controls)c).Horizontal←1 :EndIf ⍝ wrap the content of the <body> element in a div Body.Push _.div'class="bodyblock"' ⍝ add the footer to the bottom of the page Add #.Files.GetText server.Config.Root,'Styles\footer.txt' ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.GetText server.Config.Root,'Styles\banner.txt' Body.Push _.div'id="wrapper"' ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script'$(function(){$("#bannerimage").on("click", function(evt){$("#contentblock,#codeblock,.widgethelp").toggle(400,"swing");});});' ⍝ set the language for the page lang←server.Config.Lang ⍝ use the language specified in Server.xml Set'lang="',lang,'" xml:lang="',lang,'" xmlns="http://www.w3.org/1999/xhtml"' :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (#.HtmlElement.isClass e)∨#.HtmlElement.isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ ∇ r←FormatControls controls;ctrls;ns;desc;field;n;ctrl;i;c;ref;l;u;nss;item;cn ctrls←⊃{⍺ ⍵}#.Utils.∆key/↓[1]0 1↓↑{⎕ML←3 ⋄ {⍵⊂⍨⍵≠'.'}⍕⍵}¨controls field←{0::'' ⋄ ⍺⍎⍵} nss←'_DC' '_SF' '_JQ' '_html' desc←'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' (r←⎕NEW _.div).class←'widgethelp' r.Add'This Page Contains<hr/>' :Trap 0 :For (ns ctrl i) :In ctrls{↓(⍺,⍵)[⍋⍵;]}nss⍳{(⊃⍣(¯1+≡⍵))⍵}¨ctrls[;1] (r.Add _.span(i⊃desc)).class←'widgetNs' u←r.Add _.ul n←#.⍎ns←⊃ns :For c :In ctrl ref←n.⍎c item←⍬ :Select ns :Case '_DC' item←u.Add _.li(New _.a(c(('href=/Documentation/DyalogAPIs/WidgetDoc?namespace=',ns,'&widget=',c)'target=_blank'))) :Case '_SF' item←u.Add _.li(New _.a c(('href'('http://js.syncfusion.com/demos/web/default.htm#!/azure/',#.Strings.lc(2×'ej'≡2↑c)↓c))('target' '_blank'))) :Case '_JQ' item←u.Add _.li(New _.a c(('href'('http://jqueryui.com/',(2×'jq'≡2↑c)↓c))('target' '_blank'))) :Case '_html' cn←c :If ~0∊⍴('^h[1-6]$'⎕S{⍵.Match})c cn←'hn' :EndIf item←u.Add _.li(New _.a c(('href'('http://www.w3schools.com/tags/tag_',cn,'.asp'))('target' '_blank'))) :EndSelect :If 0∊⍴item u.Add _.li c :EndIf :EndFor :EndFor :EndTrap ∇ :EndClass
Update links to Syncfusion samples from MiPageSample - they moved again...
Update links to Syncfusion samples from MiPageSample - they moved again...
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
bdaa59540e24802506761c9fc372d3ed302c064e
apl/iota999.apl
apl/iota999.apl
⍝ Using the ⍳ (iota) function to generate a set of ordered numbers in a 3D array ⍳ 9 9 9
⍝ Using the ⍳ (iota) function to generate a set of ordered numbers in a 3D array ⍳ 9 9 9 ⍝=> 0 0 0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 ⍝ 0 1 0 0 1 1 0 1 2 0 1 3 0 1 4 0 1 5 0 1 6 0 1 7 0 1 8 ⍝ 0 2 0 0 2 1 0 2 2 0 2 3 0 2 4 0 2 5 0 2 6 0 2 7 0 2 8 ⍝ 0 3 0 0 3 1 0 3 2 0 3 3 0 3 4 0 3 5 0 3 6 0 3 7 0 3 8 ⍝ 0 4 0 0 4 1 0 4 2 0 4 3 0 4 4 0 4 5 0 4 6 0 4 7 0 4 8 ⍝ 0 5 0 0 5 1 0 5 2 0 5 3 0 5 4 0 5 5 0 5 6 0 5 7 0 5 8 ⍝ 0 6 0 0 6 1 0 6 2 0 6 3 0 6 4 0 6 5 0 6 6 0 6 7 0 6 8 ⍝ 0 7 0 0 7 1 0 7 2 0 7 3 0 7 4 0 7 5 0 7 6 0 7 7 0 7 8 ⍝ 0 8 0 0 8 1 0 8 2 0 8 3 0 8 4 0 8 5 0 8 6 0 8 7 0 8 8 ⍝ 1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 1 0 7 1 0 8 ⍝ 1 1 0 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 1 1 7 1 1 8 ⍝ 1 2 0 1 2 1 1 2 2 1 2 3 1 2 4 1 2 5 1 2 6 1 2 7 1 2 8 ⍝ 1 3 0 1 3 1 1 3 2 1 3 3 1 3 4 1 3 5 1 3 6 1 3 7 1 3 8 ⍝ 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 1 4 7 1 4 8 ⍝ 1 5 0 1 5 1 1 5 2 1 5 3 1 5 4 1 5 5 1 5 6 1 5 7 1 5 8 ⍝ 1 6 0 1 6 1 1 6 2 1 6 3 1 6 4 1 6 5 1 6 6 1 6 7 1 6 8 ⍝ 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 ⍝ 1 8 0 1 8 1 1 8 2 1 8 3 1 8 4 1 8 5 1 8 6 1 8 7 1 8 8 ⍝ 2 0 0 2 0 1 2 0 2 2 0 3 2 0 4 2 0 5 2 0 6 2 0 7 2 0 8 ⍝ 2 1 0 2 1 1 2 1 2 2 1 3 2 1 4 2 1 5 2 1 6 2 1 7 2 1 8 ⍝ 2 2 0 2 2 1 2 2 2 2 2 3 2 2 4 2 2 5 2 2 6 2 2 7 2 2 8 ⍝ 2 3 0 2 3 1 2 3 2 2 3 3 2 3 4 2 3 5 2 3 6 2 3 7 2 3 8 ⍝ 2 4 0 2 4 1 2 4 2 2 4 3 2 4 4 2 4 5 2 4 6 2 4 7 2 4 8 ⍝ 2 5 0 2 5 1 2 5 2 2 5 3 2 5 4 2 5 5 2 5 6 2 5 7 2 5 8 ⍝ 2 6 0 2 6 1 2 6 2 2 6 3 2 6 4 2 6 5 2 6 6 2 6 7 2 6 8 ⍝ 2 7 0 2 7 1 2 7 2 2 7 3 2 7 4 2 7 5 2 7 6 2 7 7 2 7 8 ⍝ 2 8 0 2 8 1 2 8 2 2 8 3 2 8 4 2 8 5 2 8 6 2 8 7 2 8 8 ⍝ 3 0 0 3 0 1 3 0 2 3 0 3 3 0 4 3 0 5 3 0 6 3 0 7 3 0 8 ⍝ 3 1 0 3 1 1 3 1 2 3 1 3 3 1 4 3 1 5 3 1 6 3 1 7 3 1 8 ⍝ 3 2 0 3 2 1 3 2 2 3 2 3 3 2 4 3 2 5 3 2 6 3 2 7 3 2 8 ⍝ 3 3 0 3 3 1 3 3 2 3 3 3 3 3 4 3 3 5 3 3 6 3 3 7 3 3 8 ⍝ 3 4 0 3 4 1 3 4 2 3 4 3 3 4 4 3 4 5 3 4 6 3 4 7 3 4 8 ⍝ 3 5 0 3 5 1 3 5 2 3 5 3 3 5 4 3 5 5 3 5 6 3 5 7 3 5 8 ⍝ 3 6 0 3 6 1 3 6 2 3 6 3 3 6 4 3 6 5 3 6 6 3 6 7 3 6 8 ⍝ 3 7 0 3 7 1 3 7 2 3 7 3 3 7 4 3 7 5 3 7 6 3 7 7 3 7 8 ⍝ 3 8 0 3 8 1 3 8 2 3 8 3 3 8 4 3 8 5 3 8 6 3 8 7 3 8 8 ⍝ 4 0 0 4 0 1 4 0 2 4 0 3 4 0 4 4 0 5 4 0 6 4 0 7 4 0 8 ⍝ 4 1 0 4 1 1 4 1 2 4 1 3 4 1 4 4 1 5 4 1 6 4 1 7 4 1 8 ⍝ 4 2 0 4 2 1 4 2 2 4 2 3 4 2 4 4 2 5 4 2 6 4 2 7 4 2 8 ⍝ 4 3 0 4 3 1 4 3 2 4 3 3 4 3 4 4 3 5 4 3 6 4 3 7 4 3 8 ⍝ 4 4 0 4 4 1 4 4 2 4 4 3 4 4 4 4 4 5 4 4 6 4 4 7 4 4 8 ⍝ 4 5 0 4 5 1 4 5 2 4 5 3 4 5 4 4 5 5 4 5 6 4 5 7 4 5 8 ⍝ 4 6 0 4 6 1 4 6 2 4 6 3 4 6 4 4 6 5 4 6 6 4 6 7 4 6 8 ⍝ 4 7 0 4 7 1 4 7 2 4 7 3 4 7 4 4 7 5 4 7 6 4 7 7 4 7 8 ⍝ 4 8 0 4 8 1 4 8 2 4 8 3 4 8 4 4 8 5 4 8 6 4 8 7 4 8 8 ⍝ 5 0 0 5 0 1 5 0 2 5 0 3 5 0 4 5 0 5 5 0 6 5 0 7 5 0 8 ⍝ 5 1 0 5 1 1 5 1 2 5 1 3 5 1 4 5 1 5 5 1 6 5 1 7 5 1 8 ⍝ 5 2 0 5 2 1 5 2 2 5 2 3 5 2 4 5 2 5 5 2 6 5 2 7 5 2 8 ⍝ 5 3 0 5 3 1 5 3 2 5 3 3 5 3 4 5 3 5 5 3 6 5 3 7 5 3 8 ⍝ 5 4 0 5 4 1 5 4 2 5 4 3 5 4 4 5 4 5 5 4 6 5 4 7 5 4 8 ⍝ 5 5 0 5 5 1 5 5 2 5 5 3 5 5 4 5 5 5 5 5 6 5 5 7 5 5 8 ⍝ 5 6 0 5 6 1 5 6 2 5 6 3 5 6 4 5 6 5 5 6 6 5 6 7 5 6 8 ⍝ 5 7 0 5 7 1 5 7 2 5 7 3 5 7 4 5 7 5 5 7 6 5 7 7 5 7 8 ⍝ 5 8 0 5 8 1 5 8 2 5 8 3 5 8 4 5 8 5 5 8 6 5 8 7 5 8 8 ⍝ 6 0 0 6 0 1 6 0 2 6 0 3 6 0 4 6 0 5 6 0 6 6 0 7 6 0 8 ⍝ 6 1 0 6 1 1 6 1 2 6 1 3 6 1 4 6 1 5 6 1 6 6 1 7 6 1 8 ⍝ 6 2 0 6 2 1 6 2 2 6 2 3 6 2 4 6 2 5 6 2 6 6 2 7 6 2 8 ⍝ 6 3 0 6 3 1 6 3 2 6 3 3 6 3 4 6 3 5 6 3 6 6 3 7 6 3 8 ⍝ 6 4 0 6 4 1 6 4 2 6 4 3 6 4 4 6 4 5 6 4 6 6 4 7 6 4 8 ⍝ 6 5 0 6 5 1 6 5 2 6 5 3 6 5 4 6 5 5 6 5 6 6 5 7 6 5 8 ⍝ 6 6 0 6 6 1 6 6 2 6 6 3 6 6 4 6 6 5 6 6 6 6 6 7 6 6 8 ⍝ 6 7 0 6 7 1 6 7 2 6 7 3 6 7 4 6 7 5 6 7 6 6 7 7 6 7 8 ⍝ 6 8 0 6 8 1 6 8 2 6 8 3 6 8 4 6 8 5 6 8 6 6 8 7 6 8 8 ⍝ 7 0 0 7 0 1 7 0 2 7 0 3 7 0 4 7 0 5 7 0 6 7 0 7 7 0 8 ⍝ 7 1 0 7 1 1 7 1 2 7 1 3 7 1 4 7 1 5 7 1 6 7 1 7 7 1 8 ⍝ 7 2 0 7 2 1 7 2 2 7 2 3 7 2 4 7 2 5 7 2 6 7 2 7 7 2 8 ⍝ 7 3 0 7 3 1 7 3 2 7 3 3 7 3 4 7 3 5 7 3 6 7 3 7 7 3 8 ⍝ 7 4 0 7 4 1 7 4 2 7 4 3 7 4 4 7 4 5 7 4 6 7 4 7 7 4 8 ⍝ 7 5 0 7 5 1 7 5 2 7 5 3 7 5 4 7 5 5 7 5 6 7 5 7 7 5 8 ⍝ 7 6 0 7 6 1 7 6 2 7 6 3 7 6 4 7 6 5 7 6 6 7 6 7 7 6 8 ⍝ 7 7 0 7 7 1 7 7 2 7 7 3 7 7 4 7 7 5 7 7 6 7 7 7 7 7 8 ⍝ 7 8 0 7 8 1 7 8 2 7 8 3 7 8 4 7 8 5 7 8 6 7 8 7 7 8 8 ⍝ 8 0 0 8 0 1 8 0 2 8 0 3 8 0 4 8 0 5 8 0 6 8 0 7 8 0 8 ⍝ 8 1 0 8 1 1 8 1 2 8 1 3 8 1 4 8 1 5 8 1 6 8 1 7 8 1 8 ⍝ 8 2 0 8 2 1 8 2 2 8 2 3 8 2 4 8 2 5 8 2 6 8 2 7 8 2 8 ⍝ 8 3 0 8 3 1 8 3 2 8 3 3 8 3 4 8 3 5 8 3 6 8 3 7 8 3 8 ⍝ 8 4 0 8 4 1 8 4 2 8 4 3 8 4 4 8 4 5 8 4 6 8 4 7 8 4 8 ⍝ 8 5 0 8 5 1 8 5 2 8 5 3 8 5 4 8 5 5 8 5 6 8 5 7 8 5 8 ⍝ 8 6 0 8 6 1 8 6 2 8 6 3 8 6 4 8 6 5 8 6 6 8 6 7 8 6 8 ⍝ 8 7 0 8 7 1 8 7 2 8 7 3 8 7 4 8 7 5 8 7 6 8 7 7 8 7 8 ⍝ 8 8 0 8 8 1 8 8 2 8 8 3 8 8 4 8 8 5 8 8 6 8 8 7 8 8 8
Update iota999.apl
Update iota999.apl
APL
mit
classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept
b1e1cd58aacef486428905e6e97ffb7b47bb16b6
Extensions/SimpleSessions.dyalog
Extensions/SimpleSessions.dyalog
:Class SimpleSessions ⍝ Default Session Handler, used by the WebServer sample ⍝ Manages HTTP sessions using cookies ⍝ When a HTTP request arrives, checks to see if the session cookie is included and the session ⍝ is in the list of valid sessions. If it is, assign the Session property of the request. ⍝ If it isn't, create a new session and set the cookie :Field Public Sessions ⍝ Should be private, really :Class Page :Field Public URL←'' :Field Public State←⎕NS '' :EndClass :Class Session :Field Public ID←0 :Field Public User←'' :Field Public LastActive←0 :Field Public Cookie←'' :Field Public AuthCookieName←'' :Field Public Timeout←0 :Field Public State :Field Public New←1 :Field Public Pages←0⍴⎕NEW Page :EndClass ∇ Start Server;tn;root :Access Public :Implements Constructor ⍝ Initialize Session handler Sessions←0⍴⎕NEW Session root←Server.Config.Root Timeout←Server.Config.SessionTimeout timeout←Timeout÷24×60 ⍝ Convert minutes to fractions of a day :Trap 22 tn←(root,'sessions.dcf')⎕FCREATE 0 (0 ¯1 0)⎕FSTAC tn 0 ⎕FAPPEND tn ⍝ Session Number ⎕FUNTIE tn :EndTrap tn←(root,'sessions.dcf')⎕FSTIE 0 NextSession←⎕FREAD tn,1 ⎕FUNTIE tn ∇ ∇ GetSession req;c;tn;now;session;ns;new;t_out;i;r :Access Public ⍝ Return session. Right argument is a HTTPRequest. :Hold 'Sessions' session←req.GetCookie'Session' now←#.Dates.DateToIDN ⎕TS :If new←(1⊃⍴Sessions)<i←Sessions.Cookie⍳⊂session ⍝ Cookie is not in the table c←SessionCookie NextSession Sessions←Sessions,r←⎕NEW Session r.(ID User LastActive Cookie State)←NextSession''now c(⎕NS'') NextSession←(2*30)|NextSession+1 tn←(req.Server.Config.Root,'sessions.dcf')⎕FSTIE 0 NextSession ⎕FREPLACE tn,1 ⎕FUNTIE tn req.SetCookie'Session'c req.Session←r req.Server.onSessionStart req :Else ⍝ Old session (r←i⊃Sessions).LastActive←now ⍝ Just register activity r.New←0 req.Session←r :EndIf :EndHold ∇ ∇ KillSessions ids;mask;i :Access Public :Hold 'Sessions' :If ∨/mask←Sessions.ID∊id :For i :In mask/⍳⍴mask Server.onSessionEnd i⊃Sessions :EndFor Sessions/⍨←~mask :EndIf :EndHold ∇ ∇ Logout req;session;i;z :Access Public Instance ⍝ End session due to user request session←req.GetCookie'Session' :If (1⊃⍴Sessions)≥i←Sessions.Cookie⍳⊂session ⍝ Cookie is in the table req.Server.onSessionEnd(i⊃Sessions) req.DelCookie'Session' :If 0≠⍴z←req.Session.AuthCookieName ⋄ req.DelCookie z ⋄ :EndIf req.Return'Logged out ...' :Else req.Return'No session established ...' :EndIf ∇ ∇ r←SessionCookie n;⎕RL;z;seed;p ⍝ Create Cookie from session ID or vice versa :If (10|⎕DR n)∊0 2 ⍝ Session ID from Cookie z←⎕UCS #.Base64.Decode n ⎕RL←256⊥2↑z ⋄ p←30?30 r←30⍴0 ⋄ r[p]←2↓z r←256⊥4↑r :Else ⍝ Session ID to Cookie ⎕RL←10000000|3⊃⎕AI ⎕RL←seed←?¯1+256*2 ⋄ p←30?30 r←#.Base64.Encode #.Base64.Char(256 256⊤seed),((256 256 256 256⊤n),¯1+?26⍴256)[p] :EndIf ∇ ∇ HouseKeeping Server;now;m;i;p ⍝ Check to see if any sessions have expired due to inactivity ⍝ Call any page application callbacks (_Close) if necessary :Access Public now←#.Dates.DateToIDN ⎕TS :If ∨/m←Sessions.LastActive<now-timeout :Hold 'Sessions' :For i :In m/⍳⍴m Server.onSessionEnd i⊃Sessions :If 0≠⍴p←(i⊃Sessions).Pages :AndIf 0≠⊃p.⎕NC⊂'_Close' p._Close i⊃Sessions :EndIf :EndFor Sessions←(~m)/Sessions :EndHold :EndIf ∇ :EndClass
:Class SimpleSessions ⍝ Default Session Handler, used by the WebServer sample ⍝ Manages HTTP sessions using cookies ⍝ When a HTTP request arrives, checks to see if the session cookie is included and the session ⍝ is in the list of valid sessions. If it is, assign the Session property of the request. ⍝ If it isn't, create a new session and set the cookie :Field Public Sessions ⍝ Should be private, really :Field Public Server :Class Page :Field Public URL←'' :Field Public State←⎕NS '' :EndClass :Class Session :Field Public ID←0 :Field Public User←'' :Field Public LastActive←0 :Field Public Cookie←'' :Field Public AuthCookieName←'' :Field Public Timeout←0 :Field Public State :Field Public New←1 :Field Public Pages←0⍴⎕NEW Page :Field Public Server←⍬ :EndClass ∇ Start server;tn;root :Access Public :Implements Constructor ⍝ Initialize Session handler Sessions←0⍴⎕NEW Session root←server.Config.Root Timeout←server.Config.SessionTimeout timeout←Timeout÷24×60 ⍝ Convert minutes to fractions of a day :Trap 22 tn←(root,'sessions.dcf')⎕FCREATE 0 (0 ¯1 0)⎕FSTAC tn 0 ⎕FAPPEND tn ⍝ Session Number ⎕FUNTIE tn :EndTrap tn←(root,'sessions.dcf')⎕FSTIE 0 NextSession←⎕FREAD tn,1 ⎕FUNTIE tn Server←server ∇ ∇ GetSession req;c;tn;now;session;ns;new;t_out;i;r :Access Public ⍝ Return session. Right argument is a HTTPRequest. :Hold 'Sessions' session←req.GetCookie'Session' now←#.Dates.DateToIDN ⎕TS :If new←(1⊃⍴Sessions)<i←Sessions.Cookie⍳⊂session ⍝ Cookie is not in the table c←SessionCookie NextSession Sessions←Sessions,r←⎕NEW Session r.(ID User LastActive Cookie State Server)←NextSession''now c(⎕NS'')Server NextSession←(2*30)|NextSession+1 tn←(req.Server.Config.Root,'sessions.dcf')⎕FSTIE 0 NextSession ⎕FREPLACE tn,1 ⎕FUNTIE tn req.SetCookie'Session'c req.Session←r req.Server.onSessionStart req :Else ⍝ Old session (r←i⊃Sessions).LastActive←now ⍝ Just register activity r.New←0 req.Session←r :EndIf :EndHold ∇ ∇ KillSessions ids;mask;i :Access Public :Hold 'Sessions' :If ∨/mask←Sessions.ID∊ids :For i :In mask/⍳⍴mask Server.onSessionEnd i⊃Sessions :EndFor Sessions/⍨←~mask :EndIf :EndHold ∇ ∇ Logout req;session;i;z :Access Public Instance ⍝ End session due to user request session←req.GetCookie'Session' :If (1⊃⍴Sessions)≥i←Sessions.Cookie⍳⊂session ⍝ Cookie is in the table req.Server.onSessionEnd(i⊃Sessions) req.DelCookie'Session' :If 0≠⍴z←req.Session.AuthCookieName ⋄ req.DelCookie z ⋄ :EndIf req.Return'Logged out ...' :Else req.Return'No session established ...' :EndIf ∇ ∇ r←SessionCookie n;⎕RL;z;seed;p ⍝ Create Cookie from session ID or vice versa :If (10|⎕DR n)∊0 2 ⍝ Session ID from Cookie z←⎕UCS #.Base64.Decode n ⎕RL←256⊥2↑z ⋄ p←30?30 r←30⍴0 ⋄ r[p]←2↓z r←256⊥4↑r :Else ⍝ Session ID to Cookie ⎕RL←10000000|3⊃⎕AI ⎕RL←seed←?¯1+256*2 ⋄ p←30?30 r←#.Base64.Encode #.Base64.Char(256 256⊤seed),((256 256 256 256⊤n),¯1+?26⍴256)[p] :EndIf ∇ ∇ HouseKeeping Server;now;m;i;p ⍝ Check to see if any sessions have expired due to inactivity ⍝ Call any page application callbacks (_Close) if necessary :Access Public now←#.Dates.DateToIDN ⎕TS :If ∨/m←Sessions.LastActive<now-timeout :Hold 'Sessions' :For i :In m/⍳⍴m Server.onSessionEnd i⊃Sessions :If 0≠⍴p←(i⊃Sessions).Pages :AndIf 0≠⊃p.⎕NC⊂'_Close' p._Close i⊃Sessions :EndIf :EndFor Sessions←(~m)/Sessions :EndHold :EndIf ∇ :EndClass
Fix to SimpleSessions.KillSessions
Fix to SimpleSessions.KillSessions
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
97401a3606d81bef4fc8e4505b036894b4eff883
MS3/Examples/SF/ejDateTimePickerAdvanced.dyalog
MS3/Examples/SF/ejDateTimePickerAdvanced.dyalog
:Class ejDateTimePickerAdvanced : MiPageSample ⍝ Control:: _SF.ejDateTimePicker ⍝ Description:: advance functionality. ⍝ Show 2 calendars to select reservation dates. ⍝ Display the time difference as result. ∇ Compose;today;fromidn;tbl;tr;td;head;todate;from;now;to :Access Public today←3↑now←⎕TS fromidn←dateToIDN today Add _.h2'R.U. Inn'_.br'Motel reservation system' ⍝ The in date from←'in'New _SF.ejDateTimePicker now'yyyy/MM/dd HH:mm' ⍝ The callback should return the date (value) of the argument for the IN date/time ⍝ and the model's value for the OUT date/time from.On'change' 'setNewDate',⊂('in' 'argument' 'value')('out' 'eval' '$("#out").ejDateTimePicker("model.value")') ⍝ The out date todate←IDNToDate fromidn+7 to←'out'New _SF.ejDateTimePicker todate'yyyy/MM/dd HH:mm' to.On'change' 'setNewDate',⊂('out' 'argument' 'value')('in' 'eval' '$("#in").ejDateTimePicker("model.value")') Add #._.InputGrid('Check In' 'Check Out',⍪from to) 'diff'Add _.div ∇ newDate←{'⍎new Date("',(⍕⍵),'")'} dateToIDN←{d←2 ⎕NQ'.' 'datetoidn'⍵ ⋄ d+(60⊥3↓6↑⍵)÷86400} IDNToDate←{d←3↑2 ⎕NQ'.' 'idntodate'⍵ ⋄ d,0 60 60⊤⌊86400×1|⍵} ∇ r←setNewDate;in;out :Access public ⍝ Find the difference between the dates in←dateToIDN stringToDate⍕Get'in' out←dateToIDN 6↑{b←~⍵∊'/-:' ⋄ FI b\b/⍵}Get'out' ⍝ If the new IN date is not before the OUT date we reset OUT to 1 week after :If in>out r←'#diff'Replace'Going back in time?' :Else r←'#diff'Replace'The difference in days is: ',⍕out-in :EndIf ∇ MONTHS←↓12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec' FI←{(b v)←⎕vfi ⍵ ⋄ b/v} ∇ dt←stringToDate str;pos;mon;t;ymd ⍝ str is of the genre "Wed Aug 05 2015 07:30:21 GMT-0400 (Eastern Daylight Time)" ⍝ We need to weed out the day of the week and the time str←(+/∧\' '=str)↓str ⍝ remove the leading spaces :If 0∊⍴t←MONTHS ⎕S 0 3⊢str ⍝ look for the month as a string. If not found ymd←3↑FI str ⍝ grab the 1st 3 numbers found ymd←ymd[⍒(2×31<ymd)+ymd<12] ⍝ put in correct order :Else ⍝ otherwise (if found) (pos mon)←0 1+1⊃t :If ~0∊⍴t←FI pos↑str ⍝ any number before the month? (e.g. 2 May 2021) ymd←⌽⍣(31<⍬⍴t)⊢(1↑FI pos↓str),mon,t :Else ymd←¯1⌽mon,2↑FI pos↓str :EndIf :EndIf ⍝ Now grab the time dt←ymd,FI⍕'(\d+):(\d+):(\d+)'⎕S'\1 \2 \3'⊢str ∇ :EndClass
:Class ejDateTimePickerAdvanced : MiPageSample ⍝ Control:: _SF.ejDateTimePicker ⍝ Description:: advance functionality. ⍝ Show 2 calendars to select reservation dates. ⍝ Display the time difference as result. ∇ Compose;today;fromidn;tbl;tr;td;head;todate;from;now;to :Access Public today←3↑now←⎕TS fromidn←dateToIDN today Add _.h2'R.U. Inn'_.br'Motel reservation system' ⍝ The in date from←'in'New _SF.ejDateTimePicker now'yyyy/MM/dd HH:mm' ⍝ The callback should return the date (value) of the argument for the IN date/time ⍝ and the model's value for the OUT date/time from.On'change' 'setNewDate',⊂('in' 'argument' 'value')('out' 'eval' '$("#out").ejDateTimePicker("model.value")') ⍝ The out date todate←IDNToDate fromidn+7 to←'out'New _SF.ejDateTimePicker todate'yyyy/MM/dd HH:mm' to.On'change' 'setNewDate',⊂('out' 'argument' 'value')('in' 'eval' '$("#in").ejDateTimePicker("model.value")') Add #._.InputGrid('Check In' 'Check Out',⍪from to) 'diff'Add _.div ∇ newDate←{'⍎new Date("',(⍕⍵),'")'} dateToIDN←{d←2 ⎕NQ'.' 'datetoidn'⍵ ⋄ d+(60⊥3↓6↑⍵)÷86400} IDNToDate←{d←3↑2 ⎕NQ'.' 'idntodate'⍵ ⋄ d,0 60 60⊤⌊86400×1|⍵} ∇ r←setNewDate;in;out :Access public ⍝ Find the difference between the dates in←dateToIDN stringToDate Get'in' out←dateToIDN stringToDate Get'out' :If in>out r←'#diff'Replace'Going back in time?' :Else r←'#diff'Replace'The difference in days is: ',⍕out-in :EndIf ∇ MONTHS←↓12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec' FI←{(b v)←⎕vfi ⍵ ⋄ b/v} ∇ dt←stringToDate str;pos;mon;t;ymd ⍝ str is of the genre "Wed Aug 05 2015 07:30:21 GMT-0400 (Eastern Daylight Time)" ⍝ We need to weed out the day of the week and the time str←(+/∧\' '=str)↓str ⍝ remove the leading spaces ⍝ What kind of string is this? :If ~∧/1⊃(dt dt)←{b←~⍵∊'/-:' ⋄ ⎕VFI b\b/⍵}str ⍝ yyyy/mm/dd hh:mm:ss ? :If 0∊⍴t←MONTHS ⎕S 0 3⊢str ⍝ look for the month as a string. If not found ymd←3↑FI str ⍝ grab the 1st 3 numbers found ymd←ymd[⍒(2×31<ymd)+ymd<12] ⍝ put in correct order :Else ⍝ otherwise (if found) (pos mon)←0 1+1⊃t :If ~0∊⍴t←FI pos↑str ⍝ any number before the month? (e.g. 2 May 2021) ymd←⌽⍣(31<⍬⍴t)⊢(1↑FI pos↓str),mon,t :Else ymd←¯1⌽mon,2↑FI pos↓str :EndIf :EndIf ⍝ Now grab the time dt←ymd,FI⍕'(\d+):(\d+):(\d+)'⎕S'\1 \2 \3'⊢str :EndIf ∇ :EndClass
format fixed
format fixed
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
7c438c0f3f4a8a4acef81384c8989f5204496475
MS3/Examples/Apps/ii.dyalog
MS3/Examples/Apps/ii.dyalog
:class ii :MiPageSample ⍝ Description:: Search the FinnAPL and Dyalog idiom lists ∇ Compose;fm;bn :Access public :If 0=⎕NC'idioms' idioms←⎕SE.SALT.Load'[ws]\MS3\Examples\Data\idioms -noname -nolink' :EndIf Add _.h1'Search Idiom Database' Add _.br ef←Add _.EditField'str' ef.On'keyup' ''('str' 'val') Add' Press ' Add _.Button'Enter' Add'to search' Add _.br (Add _.div).id←'res' ⍝ This is a container that will be filled with result ∇ ∇ r←APLJax;found;finn;dyal :Access public found←idioms⌿⍨∨/∨/¨idioms[;2 3 4]⍷¨⍨⊂Get'str' found←found\⍨7⍴1 0 found[;2×⍳3]←⊂6/⎕UCS 160 finn←found[;2+⍳5]⌿⍨~found[;1] dyal←found[;3 4 7]⌿⍨found[;1] :If ×≢found r←'#res'Replace'' :If ×≢finn r,←'#res'Append _.h3'One-liners from the reknown FinnAPL Idiom Library' r,←'#res'Append _.Table finn :EndIf :If ×≢dyal r,←'#res'Append _.h3'Recognised and evaluated internally for performance' r,←'#res'Append _.Table dyal :EndIf :Else r←'#res'Replace _.h3'No matching idioms found' :EndIf ∇ :endclass
:class ii :MiPageSample ⍝ Description:: Search the FinnAPL and Dyalog idiom lists ∇ Compose;fm;bn :Access public :If 0=⎕NC'idioms' idioms←⎕SE.SALT.Load'[ws]\MS3\Examples\Data\idioms -noname -nolink' :EndIf Add _.h1'Search Idiom Database' Add _.br ef←Add _.EditField'str' ef.On'keyup' ''('str' 'val') Add' Press ' Add _.Button'Enter' Add'to search' Add _.br (Add _.div).id←'res' ⍝ This is a container that will be filled with result ∇ ∇ r←APLJax;found;finn;dyal;rows :Access public found←idioms⌿⍨∨/∨/¨idioms[;2 3 4]⍷¨⍨⊂Get'str' found←found\⍨7⍴1 0 found[;2×⍳3]←⊂6/⎕UCS 160 finn←found[;2+⍳5]⌿⍨~found[;1] dyal←found[;3 4 7]⌿⍨found[;1] ⍝ Speedup: If more than 25 rows, then hide after 20 :If 25<rows←≢finn finn↑⍨←20 5 finn⍪←('[',(⍕rows-20),' more results...]')'' '' '' '' :EndIf :If 25<rows←≢dyal dyal↑⍨←20 3 dyal⍪←('[',(⍕rows-20),' more results...]')'' '' :EndIf :If ×≢found r←'#res'Replace'' :If ×≢finn r,←'#res'Append _.h3'One-liners from the reknown FinnAPL Idiom Library' r,←'#res'Append _.Table finn :EndIf :If ×≢dyal r,←'#res'Append _.h3'Recognised and evaluated internally for performance' r,←'#res'Append _.Table dyal :EndIf :Else r←'#res'Replace _.h3'No matching idioms found' :EndIf ∇ :endclass
Truncate long results for speedup.
ii: Truncate long results for speedup.
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
b527840ac4c14232374fe77b8c9a7c7340444d7b
Core/MiPage.dyalog
Core/MiPage.dyalog
:Class MiPage : #.HtmlPage ⍝∇:require =\HtmlPage.dyalog ⍝∇:require =\JSON.dyalog :Field Public _PageName←'' ⍝ Page file name :Field Public _PageDate←'' ⍝ Page saved date :field Public _Request ⍝ HTTPRequest :field Public _Scripts←'' :field Public _Styles←'' :field Public _CssReset←'' ⍝ location of CSS Reset file (if any) :field Public _CssOverride←'' ⍝ location of CSS Override file (if any) :field public _Serialized←1 ⍝ serialized forms to return in _PageData :field Public _event ⍝ set by APLJAX callback - event that was triggered :field Public _what ⍝ set by APLJAX callback - name or id of the triggering element :field Public _value ⍝ set by APLJAX callback - value of the triggering element :field Public _selector ⍝ set by APLJAX callback - CSS/jQuery selector for the element that triggered the event :field Public _callback ⍝ set by APLJAX callback - name of the callback function :field public _PageData :field public _AjaxResponse←'' :field public _DebugCallbacks←0 :field public OnLoad←'' ⍝ page equivalent to ⎕LX _used←'' ⍝ keep track of what's been used ∇ Make :Access public :Implements constructor :Base MakeCommon ∇ ∇ Make1 req :Access public _Request←req :Implements constructor :base MakeCommon ∇ ∇ MakeCommon _PageData←⎕NS'' ∇ ∇ {r}←Render;b;styles :Access public ∘∘∘ :If ''≢OnLoad Use'JQuery' :EndIf b←RenderBody styles←_Styles styles←styles,⍨{0∊⍴⍵:⍵ ⋄ ⊂⍵}_CssReset styles←styles,{0∊⍴⍵:⍵ ⋄ ⊂⍵}_CssOverride :If ~0∊⍴styles {(Head.Add _html.link).Set(('href=',⍵)('rel' 'stylesheet')('type' 'text/css'))}¨∪styles :EndIf :If ~0∊⍴_Scripts {(Head.Add _html.script).Set('src=',⍵)}¨∪_Scripts :EndIf :If ~0∊⍴Handlers b,←∊Handlers.Render :EndIf :If ''≢OnLoad b,←(⎕NEW #._html.script('$(function(){',OnLoad,'});')).Render :EndIf r←RenderPage b :If 0≠⎕NC⊂'_Request.Response' _Request.Response.HTML←r :EndIf ∇ ∇ {r}←Wrap :Access public r←Render ∇ ∇ Use resources;n;ind;t;x :Access public resources←eis resources :For x :In resources :If ~(⊂x)∊_used :Select ⊃x :Case '⍎' ⍝ script _Scripts,←⊂1↓x :Case '⍕' ⍝ style sheet _Styles,←⊂1↓x :Else :If 0≠⎕NC⊂'_Request.Server.Config.Resources' :AndIf ~0∊n←1↑⍴_Request.Server.Config.Resources :If n≥ind←_Request.Server.Config.Resources[;1]⍳⊂x :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 2)⊃_Request.Server.Config.Resources _Scripts,←t :EndIf :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 3)⊃_Request.Server.Config.Resources _Styles,←t :EndIf :Else 1 _Request.Server.Log _PageName,' references unknown resource: ',x :EndIf :EndIf :EndSelect _used,←⊂x :EndIf :EndFor ∇ ∇ r←{proto}Get names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←⊃r :EndIf :EndIf r←#.JSON.toAPL r ⍝ :If ~isChar proto ⍝ r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r ⍝ :EndIf :EndIf ∇ ∇ r←{proto}GetRaw names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←⊃r :EndIf :EndIf :If ~isChar proto r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ r←{proto}SessionGet names :Access public proto←{6::⍵ ⋄ proto}'' names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘SessionGet¨names :ElseIf 2≠_Request.Session.⎕NC names r←proto :Else r←_Request.Session⍎names :If 1<|≡r ⋄ r←∊r ⋄ :EndIf :If ~0 2∊⍨10|⎕DR proto r←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ Close session ⍝ Called when the session ends :Access Public Overridable ∇ :section APLJax ⍝ used for building APLJAX responses ∇ _resetAjax :Access public _AjaxResponse←'' ∇ ∇ r←_id :Access public ⍝ as there seems to be a problem with at least some Syncfusion widgets ⍝ being able to provide the id (or name) of the triggering element, we try to obtain it from _what or _selector r←'' :Trap 0 :If 0∊⍴r←_what :AndIf '#'=⊃_selector r←1↓_selector :EndIf :EndTrap ∇ ∇ Respond arg :Access public ∘∘∘ ∇ ∇ r←renderContent content;c r←'' content←eis content :While ~0∊⍴content :Select ≡c←⊃content :Case 0 :If isClass c :Select ⊃⍴content :Case 1 r,←(⎕NEW c).Render :Case 2 r,←(⎕NEW c(2⊃content)).Render :Else r,←(⎕NEW c(1↓content)).Render :EndSelect :ElseIf isInstance c r,←c.Render :Else r,←(⎕NEW #.HtmlElement(''content)).Render :EndIf content←'' :Case 1 :If isClass⊃c r,←(⎕NEW(⊃c)(1↓c)).Render :ElseIf isInstance⊃c ∘∘∘ ⍝ should not happen! (I think) :Else r,←(⎕NEW #.HtmlElement(''c)).Render :EndIf content←1↓content :Else r,←renderContent c content←1↓content :EndSelect :EndWhile ∇ ∇ r←selector Replace content :Access public r←⊂('replace'selector)('data'(renderContent content)) ∇ ∇ r←selector Append content :Access public r←⊂('append'selector)('data'(renderContent content)) ∇ ∇ r←selector Prepend content :Access public r←⊂('prepend'selector)('data'(renderContent content)) ∇ ∇ r←Execute content :Access public r←⊂('execute'content) ∇ ∇ r←name Assign data :Access public r←⊂('assign'name)('data'data) ∇ :endsection :section Position ∇ ref Position args;inds;mask;parameters;my;at;of;collision;within;q :Access public shared ⍝ ref - a reference to an instance of anything based on HtmlElement ⍝ args - position information per jQueryUI's Position widget http://api.jqueryui.com/position/ ⍝ can be in any of the following forms ⍝ 1) positional (my at of collision within) N.B. we don't use the "using" parameter ⍝ example: myDiv Position 'left top' 'right bottom' '#otherElement' ⍝ positions myDiv's top left corner at the bottom right corner of the element with id "otherElement" ⍝ 2) paired ⍝ myDiv Position 'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ myDiv Position ('my' 'left top') ('at' 'right bottom') ('of' '#otherElement') ⍝ myDiv Position 3 2⍴'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ Note: positional arguments are in form horizontal (left center right) vertical (top center bottom) parameters←'my' 'at' 'of' 'collision' 'within' q←{1⌽'''''',{⍵/⍨1+''''=⍵}⍕⍵} :If isInstance ref :If 2=⍴⍴args ⍝ matrix args←,args :ElseIf 3=≡args args←⊃,/args :EndIf args←eis args inds←parameters⍳args :If ∨/mask←inds≤⍴parameters :If mask≡(2×+/mask)⍴1 0 parameters←mask/args args←(1⌽mask)/args :EndIf :Else parameters←(⍴args)↑parameters :EndIf parameters(ref{⍺⍺⍎'Position.',⍺,'←',q ⍵})¨args ref.Uses,←⊂'JQueryUI' ref.Use :EndIf ∇ :endsection :section Event Handling Support ∇ r←isPost :Access public r←{0::0 ⋄ _Request.isPost}⍬ ∇ ∇ r←isAPLJax :Access public r←{0::0 ⋄ _Request.isAPLJAX}⍬ ∇ ∇ r←sel Css args ⍝ JQuery css cover :Access public r←(sel #._JSS.JQuery'css')args ∇ ∇ r←sel Val args ⍝ JQuery val cover :Access public r←(sel #._JSS.JQuery'val')args ∇ ∇ r←sel Attr args ⍝ JQuery attr cover :Access public r←(sel #._JSS.JQuery'attr')args ∇ ∇ r←sel RemoveAttr args ⍝ JQuery removeAttr cover :Access public r←(sel #._JSS.JQuery'removeAttr')args ∇ ∇ r←sel Html args ⍝ JQuery html cover :Access public r←(sel #._JSS.JQuery'html')args ∇ :endsection ∇ Debug;⎕TRAP :Access public ⎕TRAP←0⍴⎕TRAP ∘∘∘ ∇ :EndClass
:Class MiPage : #.HtmlPage ⍝∇:require =\HtmlPage.dyalog ⍝∇:require =\JSON.dyalog :Field Public _PageName←'' ⍝ Page file name :Field Public _PageDate←'' ⍝ Page saved date :field Public _Request ⍝ HTTPRequest :field Public _Scripts←'' :field Public _Styles←'' :field Public _CssReset←'' ⍝ location of CSS Reset file (if any) :field Public _CssOverride←'' ⍝ location of CSS Override file (if any) :field public _Serialized←1 ⍝ serialized forms to return in _PageData :field Public _event ⍝ set by APLJAX callback - event that was triggered :field Public _what ⍝ set by APLJAX callback - name or id of the triggering element :field Public _value ⍝ set by APLJAX callback - value of the triggering element :field Public _selector ⍝ set by APLJAX callback - CSS/jQuery selector for the element that triggered the event :field Public _callback ⍝ set by APLJAX callback - name of the callback function :field public _PageData :field public _AjaxResponse←'' :field public _DebugCallbacks←0 :field public OnLoad←'' ⍝ page equivalent to ⎕LX _used←'' ⍝ keep track of what's been used ∇ Make :Access public :Implements constructor :Base MakeCommon ∇ ∇ Make1 req :Access public _Request←req :Implements constructor :base MakeCommon ∇ ∇ MakeCommon _PageData←⎕NS'' ∇ ∇ {r}←Render;b;styles :Access public ⍝ ∘∘∘ :If ''≢OnLoad Use'JQuery' :EndIf b←RenderBody styles←_Styles styles←styles,⍨{0∊⍴⍵:⍵ ⋄ ⊂⍵}_CssReset styles←styles,{0∊⍴⍵:⍵ ⋄ ⊂⍵}_CssOverride :If ~0∊⍴styles {(Head.Add _html.link).Set(('href=',⍵)('rel' 'stylesheet')('type' 'text/css'))}¨∪styles :EndIf :If ~0∊⍴_Scripts {(Head.Add _html.script).Set('src=',⍵)}¨∪_Scripts :EndIf :If ~0∊⍴Handlers b,←∊Handlers.Render :EndIf :If ''≢OnLoad b,←(⎕NEW #._html.script('$(function(){',OnLoad,'});')).Render :EndIf r←RenderPage b :If 0≠⎕NC⊂'_Request.Response' _Request.Response.HTML←r :EndIf ∇ ∇ {r}←Wrap :Access public r←Render ∇ ∇ Use resources;n;ind;t;x :Access public resources←eis resources :For x :In resources :If ~(⊂x)∊_used :Select ⊃x :Case '⍎' ⍝ script _Scripts,←⊂1↓x :Case '⍕' ⍝ style sheet _Styles,←⊂1↓x :Else :If 0≠⎕NC⊂'_Request.Server.Config.Resources' :AndIf ~0∊n←1↑⍴_Request.Server.Config.Resources :If n≥ind←_Request.Server.Config.Resources[;1]⍳⊂x :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 2)⊃_Request.Server.Config.Resources _Scripts,←t :EndIf :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 3)⊃_Request.Server.Config.Resources _Styles,←t :EndIf :Else 1 _Request.Server.Log _PageName,' references unknown resource: ',x :EndIf :EndIf :EndSelect _used,←⊂x :EndIf :EndFor ∇ ∇ r←{proto}Get names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←⊃r :EndIf :EndIf r←#.JSON.toAPL r ⍝ :If ~isChar proto ⍝ r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r ⍝ :EndIf :EndIf ∇ ∇ r←{proto}GetRaw names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←⊃r :EndIf :EndIf :If ~isChar proto r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ r←{proto}SessionGet names :Access public proto←{6::⍵ ⋄ proto}'' names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘SessionGet¨names :ElseIf 2≠_Request.Session.⎕NC names r←proto :Else r←_Request.Session⍎names :If 1<|≡r ⋄ r←∊r ⋄ :EndIf :If ~0 2∊⍨10|⎕DR proto r←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ Close session ⍝ Called when the session ends :Access Public Overridable ∇ :section APLJax ⍝ used for building APLJAX responses ∇ _resetAjax :Access public _AjaxResponse←'' ∇ ∇ r←_id :Access public ⍝ as there seems to be a problem with at least some Syncfusion widgets ⍝ being able to provide the id (or name) of the triggering element, we try to obtain it from _what or _selector r←'' :Trap 0 :If 0∊⍴r←_what :AndIf '#'=⊃_selector r←1↓_selector :EndIf :EndTrap ∇ ∇ Respond arg :Access public ∘∘∘ ∇ ∇ r←renderContent content;c r←'' content←eis content :While ~0∊⍴content :Select ≡c←⊃content :Case 0 :If isClass c :Select ⊃⍴content :Case 1 r,←(⎕NEW c).Render :Case 2 r,←(⎕NEW c(2⊃content)).Render :Else r,←(⎕NEW c(1↓content)).Render :EndSelect :ElseIf isInstance c r,←c.Render :Else r,←(⎕NEW #.HtmlElement(''content)).Render :EndIf content←'' :Case 1 :If isClass⊃c r,←(⎕NEW(⊃c)(1↓c)).Render :ElseIf isInstance⊃c ∘∘∘ ⍝ should not happen! (I think) :Else r,←(⎕NEW #.HtmlElement(''c)).Render :EndIf content←1↓content :Else r,←renderContent c content←1↓content :EndSelect :EndWhile ∇ ∇ r←selector Replace content :Access public r←⊂('replace'selector)('data'(renderContent content)) ∇ ∇ r←selector Append content :Access public r←⊂('append'selector)('data'(renderContent content)) ∇ ∇ r←selector Prepend content :Access public r←⊂('prepend'selector)('data'(renderContent content)) ∇ ∇ r←Execute content :Access public r←⊂('execute'content) ∇ ∇ r←name Assign data :Access public r←⊂('assign'name)('data'data) ∇ :endsection :section Position ∇ ref Position args;inds;mask;parameters;my;at;of;collision;within;q :Access public shared ⍝ ref - a reference to an instance of anything based on HtmlElement ⍝ args - position information per jQueryUI's Position widget http://api.jqueryui.com/position/ ⍝ can be in any of the following forms ⍝ 1) positional (my at of collision within) N.B. we don't use the "using" parameter ⍝ example: myDiv Position 'left top' 'right bottom' '#otherElement' ⍝ positions myDiv's top left corner at the bottom right corner of the element with id "otherElement" ⍝ 2) paired ⍝ myDiv Position 'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ myDiv Position ('my' 'left top') ('at' 'right bottom') ('of' '#otherElement') ⍝ myDiv Position 3 2⍴'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ Note: positional arguments are in form horizontal (left center right) vertical (top center bottom) parameters←'my' 'at' 'of' 'collision' 'within' q←{1⌽'''''',{⍵/⍨1+''''=⍵}⍕⍵} :If isInstance ref :If 2=⍴⍴args ⍝ matrix args←,args :ElseIf 3=≡args args←⊃,/args :EndIf args←eis args inds←parameters⍳args :If ∨/mask←inds≤⍴parameters :If mask≡(2×+/mask)⍴1 0 parameters←mask/args args←(1⌽mask)/args :EndIf :Else parameters←(⍴args)↑parameters :EndIf parameters(ref{⍺⍺⍎'Position.',⍺,'←',q ⍵})¨args ref.Uses,←⊂'JQueryUI' ref.Use :EndIf ∇ :endsection :section Event Handling Support ∇ r←isPost :Access public r←{0::0 ⋄ _Request.isPost}⍬ ∇ ∇ r←isAPLJax :Access public r←{0::0 ⋄ _Request.isAPLJAX}⍬ ∇ ∇ r←sel Css args ⍝ JQuery css cover :Access public r←(sel #._JSS.JQuery'css')args ∇ ∇ r←sel Val args ⍝ JQuery val cover :Access public r←(sel #._JSS.JQuery'val')args ∇ ∇ r←sel Attr args ⍝ JQuery attr cover :Access public r←(sel #._JSS.JQuery'attr')args ∇ ∇ r←sel RemoveAttr args ⍝ JQuery removeAttr cover :Access public r←(sel #._JSS.JQuery'removeAttr')args ∇ ∇ r←sel Html args ⍝ JQuery html cover :Access public r←(sel #._JSS.JQuery'html')args ∇ :endsection ∇ Debug;⎕TRAP :Access public ⎕TRAP←0⍴⎕TRAP ∘∘∘ ∇ :EndClass
remove MiPage stop
remove MiPage stop
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
74ba054cc43c3d960da1c4e74bfc13e4bb22d8c6
Run.dyalog
Run.dyalog
 output←regexes(op Run args)input;from;to;options;lines;Expand;repeat;s;r;last;fns;q;hasrepeat;postproc;combine;Quote;Nest;a;n output←⍬⊤⍬ ⍝ default result is empty matrix n←⎕UCS 10 ⍝ newline a←⎕UCS 39 ⍝ apostrofe ⍎'Nest←{⊂⍣(1=≡,⍵)⊢⍵}' ⍎'Quote←{a,a,⍨⍵/⍨1+⍵=a}' :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap ⍎'regexes←{,¨⍣(¯2=≡⍵)⊢⍵}Nest regexes' repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 hasrepeat←∨/args∊⍨'≡',⎕D ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' 1)('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' :If s∨r options↓⍨←s ⍝ ResultText is not for ⎕S fns←+/∧\'⍵'∊¨regexes postproc←∊'⊢','∘{'∘,¨,∘'}'¨fns↑regexes ⍝ post-processing functions regexes↓⍨←fns last←⊃regexes↓⍨¯1+≢regexes :If '⍵'∊last ⍝ transformation function → many-to-function :OrIf 2|≢regexes ⍝ odd number of strings → many-to-one from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊last ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX,⊂'to←{',(r/',⍕{'),(Expand last),(r/'}⍵'),'}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←last :EndIf :Else lines←2÷⍨≢regexes from←regexes↓⍨-lines to←lines↓regexes :EndIf combine←'{⊃,/⍵↑¨⍨⌈/≢¨⍵}' q←⎕NS ⍬ q.from←⍕Quote¨Nest from :If 0=≢q.from q.from←a a :EndIf :If 1∧.=≢¨from q.(from←'(,¨',from,')') :EndIf :If 3=⎕NC'to' q.to←1⌽' ',3↓∊⎕NR'to' :Else q.to←⍕Quote¨Nest to :If 0=≢q.to q.to←a a :EndIf :If 1∧.=≢¨to q.(to←'(,¨',to,')') :EndIf :EndIf :If 3=⎕NC'repeat' q.repeat←'⍣',∊⎕NR'repeat' :ElseIf 1≢repeat q.repeat←'⍣',⍕repeat :Else q.repeat←'' :EndIf :If ×≢options q.options←'⍠',∊{' (',(Quote⊃⍵),' ',({0 1∊⍨⊂⍵:⍕⍵ ⋄ Quote ⍵}⊃⌽⍵),')'}¨options :Else q.options←'' :EndIf q.op←s r/'SR' q.postproc←2↓postproc q.postproc,←(hasrepeat∧s)/(''≡q.postproc)↓'∘',combine q.(expr←postproc,from,'⎕',op,to,options,repeat) :If '?'∊args ⍞←q.expr,n :EndIf :If 0=≢from from←'' :EndIf :If 2=⎕NC'to' :AndIf 0=≢to to←'' :EndIf :Trap 11 :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←(⍎combine)⍣hasrepeat⊢output ⍝ merge search results if we need to continue :EndIf output←(⍎postproc)output :Case 11 ⍝ faulty regex ⍞←'*** ',⎕DMX.(Message,(''≡Message)/⊃DM),' ***',n ⍞←'Attempted APL expression: ',q.expr,n :EndTrap :Else ⍞←'*** Left operand must be ''R'' or ''S'' ***' :EndIf
∇ output←regexes(op Run args)input;from;to;options;lines;Expand;repeat;s;r;last;fns;q;hasrepeat;postproc;combine;Quote;Nest;a;n output←⍬⊤⍬ ⍝ default result is empty matrix n←⎕UCS 10 ⍝ newline a←⎕UCS 39 ⍝ apostrofe ⍎'Nest←{⊂⍣(1=≡,⍵)⊢⍵}' ⍎'Quote←{a,a,⍨⍵/⍨1+⍵=a}' :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap ⍎'regexes←{,¨⍣(¯2=≡⍵)⊢⍵}Nest regexes' repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 hasrepeat←∨/args∊⍨'≡',⎕D ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' 1)('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' :If s∨r options↓⍨←s ⍝ ResultText is not for ⎕S fns←+/∧\'⍵'∊¨regexes postproc←∊'⊢','∘{'∘,¨,∘'}'¨fns↑regexes ⍝ post-processing functions regexes↓⍨←fns last←⊃regexes↓⍨¯1+≢regexes :If '⍵'∊last ⍝ transformation function → many-to-function :OrIf 2|≢regexes ⍝ odd number of strings → many-to-one from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊last ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX,⊂'to←{',(r/',⍕{'),(Expand last),(r/'}⍵'),'}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←last :EndIf :Else lines←2÷⍨≢regexes from←regexes↓⍨-lines to←lines↓regexes :EndIf combine←'{⊃,/⍵↑¨⍨⌈/≢¨⍵}' q←⎕NS ⍬ q.from←⍕Quote¨Nest from :If 0=≢q.from q.from←a a :EndIf :If 1∧.=≢¨from q.(from←'(,¨',from,')') :EndIf :If 3=⎕NC'to' q.to←1⌽' ',3↓∊⎕NR'to' :Else q.to←⍕Quote¨Nest to :If 0=≢q.to q.to←a a :EndIf :If 1∧.=≢¨to q.(to←'(,¨',to,')') :EndIf :EndIf :If 3=⎕NC'repeat' q.repeat←'⍣',∊⎕NR'repeat' :ElseIf 1≢repeat q.repeat←'⍣',⍕repeat :Else q.repeat←'' :EndIf :If ×≢options q.options←'⍠',∊{' (',(Quote⊃⍵),' ',({0 1∊⍨⊂⍵:⍕⍵ ⋄ Quote ⍵}⊃⌽⍵),')'}¨options :Else q.options←'' :EndIf q.op←s r/'SR' q.postproc←2↓postproc q.postproc,←(hasrepeat∧s)/(''≡q.postproc)↓'∘',combine q.(expr←postproc,from,'⎕',op,to,options,repeat) :If '?'∊args ⍞←q.expr,n :EndIf :If 0=≢from from←'' :EndIf :If 2=⎕NC'to' :AndIf 0=≢to to←'' :EndIf :Trap 11 :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←(⍎combine)⍣hasrepeat⊢output ⍝ merge search results if we need to continue :EndIf output←(⍎postproc)output :Case 11 ⍝ faulty regex ⍞←'*** ',⎕DMX.(Message,(''≡Message)/⊃DM),' ***',n ⍞←'Attempted APL expression: ',q.expr,n :EndTrap :Else ⍞←'*** Left operand must be ''R'' or ''S'' ***' :EndIf ∇
Prepend and append ∇ for stricter ⎕FIX
Prepend and append ∇ for stricter ⎕FIX
APL
mit
abrudz/QuadRS
85d38db1b4684277c2e9b80aec0520c46ddf7fcd
Utils/SQL.dyalog
Utils/SQL.dyalog
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' :If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :Else ⋄ r←601('Unable to connect to "',database,'"') :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx;data ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} r←⎕NS'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 :If 1<|≡3⊃ctl ⋄ data←3⊃ctl ⋄ :Else ⋄ data←2↓ctl ⋄ :EndIf →(0<1⊃z←#.SQA.Exec(⊂c),data)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1:→(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.ReturnCode←1⊃z r.Data←⊃2⊃z l2:→(0<1⊃z←#.SQA.Close conx)↓0 l3:r.ReturnCode←1⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
:Namespace SQL (⎕IO ⎕ML)←1 ∇ r←ConnectTo database;ind;ds;dsn;opts;rc;conx;pwd;user;ms;find ms←#.Boot.ms find←{(⍴⍺){⍵×⍺≥⍵}⍺⍳⊂⍵} r←601 'No datasources defined' :If 0<⍴{6::'' ⋄ ⍵.Datasources}ms ⍝ do we have Datasources defined? :If 0=ind←ms.Datasources.Name find database ⍝ try to find it r←601 ''('Datasource "',database,'" not found') :Return :Else ⍝ found it ds←ind⊃ms.Datasources r←601 'SQAPL not available' :If 0=⊃#.SQA.Init'' (dsn opts user pwd)←{6::'' ⋄ ⍎⍵}¨'ds.'∘,¨'DSN' 'DriverOptions' 'User' 'Password' conx←{⊃('C'∘,¨⍕¨⍳1+⍴⍵)~⍵}⊃¨2 2⊃#.SQA.Tree'.' :If 0=1⊃rc←#.SQA.Connect conx dsn pwd user('DriverOptions'(opts)) ⋄ r←0 conx :Else ⋄ r←601('Unable to connect to "',database,'"') :EndIf :EndIf :EndIf :EndIf ∇ ∇ r←Do ctl;c;m;z;ns;conx;data ⍝ Prepare, Execute, Fetch a statement. ⍝ ctl: database sqlstmt {bindvars} {nulls} r←⎕NS'' r.(ReturnCode Data Message)←¯1(0 0⍴0)'' →(0<1⊃z←ConnectTo(1⊃ctl))⍴l3 ⋄ conx←2⊃z →(0<1⊃z←#.SQA.CursorName conx)⍴l3 ⋄ c←2⊃z →(0<1⊃z←#.SQA.Prepare c(2⊃ctl))⍴l3 :If 1<|≡3⊃ctl ⋄ data←3⊃ctl :If 3<⍴ctl ⋄ data←(⊂data),ctl[4] ⋄ :EndIf ⍝ deal with nulls :Else ⋄ data←2↓ctl ⋄ :EndIf →(0<1⊃z←#.SQA.Exec(⊂c),data)⍴l2 →(0<1⊃z←0 #.SQA.Describe c)⍴l2 ⋄ r.Columns←{(0=(⊂1 3)⊃¨⍵)/(⊂1 1)⊃¨⍵}2 2⊃z →(0<2 1 5⊃z)⍴l1 ⍝ Fetch if there are Bind Vars r.(ReturnCode Data)←0(0 0⍴0) ⋄ →l2 l1: →(0<1⊃z←1 #.SQA.Fetch c)⍴l2 r.Data←⊃2⊃z l2: :If 0<r.ReturnCode←1⊃z ⋄ r.Message←3⊃z ⋄ :EndIf →(0<1⊃z←#.SQA.Close conx)↓0 l3: r.ReturnCode←1⊃z r.Message←3⊃z ∇ ∇ r←CloseAll →(0∊⍴r←2 2⊃#.SQA.Tree'.')⍴0 r←#.SQA.Close¨1⊃¨r ∇ :EndNamespace
Update SQL.dyalog to handle null values and return better diagnostics
Update SQL.dyalog to handle null values and return better diagnostics
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
76f9eb4405a35e8a3f212e517c00be7d0db7c740
examples/6-queens.apl
examples/6-queens.apl
#!/usr/bin/env apl queens←{⎕IO ⎕ML←0 1 ⍝ The N-queens problem. search←{ ⍝ Search for all solutions. (⊂⍬)∊⍵:0⍴⊂⍬ ⍝ stitched: abandon this branch. 0=⍴⍵:rmdups ⍺ ⍝ all done: solution! hd←⊃⍵ ⍝ head... tl←1↓⍵ ⍝ ... 'n tail of remaining ranks. next←⍺∘,¨hd ⍝ possible next steps. rems←hd free¨⊂tl ⍝ unchecked squares. ↑,/next ∇¨rems ⍝ ... in following ranks. } cvex←(1+⍳⍵)×⊂¯1 0 1 ⍝ Checking vectors. free←{⍵~¨⍺+(⍴⍵)↑cvex} ⍝ Unchecked squares. rmdups←{ ⍝ Ignore duplicate solution. rots←{{⍒⍵}\4/⊂⍵} ⍝ 4 rotations. refs←{{⍋⍵}\2/⊂⍵} ⍝ 2 reflections. best←{(⊃⍋↑⍵)⊃⍵} ⍝ best (=lowest) solution. all8←,↑refs¨rots ⍵ ⍝ all 8 orientations. (⍵≡best all8)⊃⍬(,⊂⍵) ⍝ ignore if not best. } fmt←{ ⍝ Format solution. chars←'·⍟'[(↑⍵)∘.=⍳⍺] ⍝ char array of placed queens. expd←1↓,↑⍺⍴⊂0 1 ⍝ expansion mask. ↑¨↓↓expd\chars ⍝ vector of char matrices. } squares←(⊂⍳⌈⍵÷2),1↓⍵⍴⊂⍳⍵ ⍝ initial squares ⍵ fmt ⍬ search squares ⍝ all distinct solutions. } ⎕←queens 5
#!/usr/bin/env apl queens←{ ⍝ The N-queens problem. search←{ ⍝ Search for all solutions. (⊂⍬)∊⍵:0⍴⊂⍬ ⍝ stitched: abandon this branch. 0=⍴⍵:rmdups ⍺ ⍝ all done: solution! hd←⊃⍵ ⍝ head... tl←1↓⍵ ⍝ ... 'n tail of remaining ranks. next←⍺∘,¨hd ⍝ possible next steps. rems←hd free¨⊂tl ⍝ unchecked squares. ↑,/next ∇¨rems ⍝ ... in following ranks. } cvex←(1+⍳⍵)×⊂¯1 0 1 ⍝ Checking vectors. free←{⍵~¨⍺+(⍴⍵)↑cvex} ⍝ Unchecked squares. rmdups←{ ⍝ Ignore duplicate solution. rots←{{⍒⍵}\4/⊂⍵} ⍝ 4 rotations. refs←{{⍋⍵}\2/⊂⍵} ⍝ 2 reflections. best←{(⊃⍋↑⍵)⊃⍵} ⍝ best (=lowest) solution. all8←,↑refs¨rots ⍵ ⍝ all 8 orientations. (⍵≡best all8)⊃⍬(,⊂⍵) ⍝ ignore if not best. } fmt←{ ⍝ Format solution. chars←'·⍟'[(↑⍵)∘.=⍳⍺] ⍝ char array of placed queens. expd←1↓,↑⍺⍴⊂0 1 ⍝ expansion mask. ↑¨↓↓expd\chars ⍝ vector of char matrices. } squares←(⊂⍳⌈⍵÷2),1↓⍵⍴⊂⍳⍵ ⍝ initial squares ⍵ fmt ⍬ search squares ⍝ all distinct solutions. } ⎕←queens 5
Fix issue #30: remove misleading line of code.
Fix issue #30: remove misleading line of code.
APL
mit
fineline/apl,fineline/apl,fineline/apl,fineline/apl
764ae7472a6d00fca56d8f244254e7a05c33dd9a
Core/MiPage.dyalog
Core/MiPage.dyalog
:Class MiPage : #.HtmlPage ⍝∇:require =\HtmlPage.dyalog ⍝∇:require =\JSON.dyalog :Field Public _PageName←'' ⍝ Page file name :Field Public _PageDate←'' ⍝ Page saved date :field Public _Request ⍝ HTTPRequest :field Public _Scripts←'' :field Public _Styles←'' :field public _Serialized←1 ⍝ serialized forms to return in _PageData :field Public _event ⍝ set by APLJAX callback - event that was triggered :field Public _what ⍝ set by APLJAX callback - name or id of the triggering element :field Public _value ⍝ set by APLJAX callback - value of the triggering element :field Public _selector ⍝ set by APLJAX callback - CSS/jQuery selector for the element that triggered the event :field Public _callback ⍝ set by APLJAX callback - name of the callback function :field public _PageData :field public _AjaxResponse←'' :field public _DebugCallbacks←0 :field public OnLoad←'' ⍝ page equivalent to ⎕LX :field public shared _true←#.JSON.true ⍝ same definition as in #.JSON :field public shared _false←#.JSON.false ⍝ same definition as in #.JSON _used←'' ⍝ keep track of what's been used ∇ Make :Access public :Implements constructor :Base MakeCommon ∇ ∇ Make1 req :Access public _Request←req :Implements constructor :base MakeCommon ∇ ∇ MakeCommon _PageData←⎕NS'' ∇ ∇ {r}←Render;b :Access public :If ''≢OnLoad Use'JQuery' :EndIf b←RenderBody :If ~0∊⍴_Styles {(Head.Insert _html.link).Set(('href=',⍵)('rel' 'stylesheet')('type' 'text/css'))}¨∪⌽_Styles :EndIf :If ~0∊⍴_Scripts {(Head.Add _html.script).Set('src=',⍵)}¨∪_Scripts :EndIf :If ~0∊⍴Handlers b,←∊Handlers.Render :EndIf :If ''≢OnLoad b,←(⎕NEW #._html.script('$(function(){',OnLoad,'});')).Render :EndIf r←RenderPage b :If 0≠⎕NC⊂'_Request.Response' _Request.Response.HTML←r :EndIf ∇ ∇ {r}←Wrap :Access public r←Render ∇ ∇ Use resources;n;ind;t;x :Access public resources←eis resources :For x :In resources :If ~(⊂x)∊_used :Select ⊃x :Case '⍎' ⍝ script _Scripts,←⊂1↓x :Case '⍕' ⍝ style sheet _Styles,←⊂1↓x :Else :If 0≠⎕NC⊂'_Request.Server.Config.Resources' :AndIf ~0∊n←1↑⍴_Request.Server.Config.Resources :If n≥ind←_Request.Server.Config.Resources[;1]⍳⊂x :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 2)⊃_Request.Server.Config.Resources _Scripts,←t :EndIf :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 3)⊃_Request.Server.Config.Resources _Styles,←t :EndIf :Else 1 _Request.Server.Log _PageName,' references unknown resource: ',x :EndIf :EndIf :EndSelect _used,←⊂x :EndIf :EndFor ∇ ∇ r←{proto}Get names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←#.JSON.toAPL⊃r :EndIf :EndIf ⍝ :If ~isChar proto ⍝ r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r ⍝ :EndIf :EndIf ∇ ∇ r←{proto}SessionGet names :Access public proto←{6::⍵ ⋄ proto}'' names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘SessionGet¨names :ElseIf 2≠_Request.Session.⎕NC names r←proto :Else r←_Request.Session⍎names :If 1<|≡r ⋄ r←∊r ⋄ :EndIf :If ~0 2∊⍨10|⎕DR proto r←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ Close session ⍝ Called when the session ends :Access Public Overridable ∇ :section APLJax ⍝ used for building APLJAX responses ∇ _resetAjax :Access public _AjaxResponse←'' ∇ ∇ r←_id :Access public ⍝ as there seems to be a problem with at least some Syncfusion widgets ⍝ being able to provide the id (or name) of the triggering element, we try to obtain it from _what or _selector r←'' :Trap 0 :If 0∊⍴r←_what :AndIf '#'=⊃_selector r←1↓_selector :EndIf :EndTrap ∇ ∇ Respond arg :Access public ∘∘∘ ∇ ∇ r←renderContent content;c r←'' content←eis content :While ~0∊⍴content :Select ≡c←⊃content :Case 0 :If isClass c :Select ⊃⍴content :Case 1 r,←(⎕NEW c).Render :Case 2 r,←(⎕NEW c(2⊃content)).Render :Else r,←(⎕NEW c(1↓content)).Render :EndSelect :ElseIf isInstance c r,←c.Render :Else r,←(⎕NEW #.HtmlElement(''content)).Render :EndIf content←'' :Case 1 :If isClass⊃c r,←(⎕NEW(⊃c)(1↓c)).Render :ElseIf isInstance⊃c ∘∘∘ ⍝ should not happen! (I think) :Else r,←(⎕NEW #.HtmlElement(''c)).Render :EndIf content←1↓content :Else r,←renderContent c content←1↓content :EndSelect :EndWhile ∇ ∇ r←selector Replace content :Access public r←⊂('replace'selector)('data'(renderContent content)) ∇ ∇ r←selector Append content :Access public r←⊂('append'selector)('data'(renderContent content)) ∇ ∇ r←selector Prepend content :Access public r←⊂('prepend'selector)('data'(renderContent content)) ∇ ∇ r←Execute content :Access public r←⊂('execute'content) ∇ ∇ r←name Assign data :Access public r←⊂('assign'name)('data'data) ∇ :endsection :section Position ∇ ref Position args;inds;mask;parameters;my;at;of;collision;within;q :Access public shared ⍝ ref - a reference to an instance of anything based on HtmlElement ⍝ args - position information per jQueryUI's Position widget http://api.jqueryui.com/position/ ⍝ can be in any of the following forms ⍝ 1) positional (my at of collision within) N.B. we don't use the "using" parameter ⍝ example: myDiv Position 'left top' 'right bottom' '#otherElement' ⍝ positions myDiv's top left corner at the bottom right corner of the element with id "otherElement" ⍝ 2) paired ⍝ myDiv Position 'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ myDiv Position ('my' 'left top') ('at' 'right bottom') ('of' '#otherElement') ⍝ myDiv Position 3 2⍴'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ Note: positional arguments are in form horizontal (left center right) vertical (top center bottom) parameters←'my' 'at' 'of' 'collision' 'within' q←{1⌽'''''',{⍵/⍨1+''''=⍵}⍕⍵} :If isInstance ref :If 2=⍴⍴args ⍝ matrix args←,args :ElseIf 3=≡args args←⊃,/args :EndIf args←eis args inds←parameters⍳args :If ∨/mask←inds≤⍴parameters :If mask≡(2×+/mask)⍴1 0 parameters←mask/args args←(1⌽mask)/args :EndIf :Else parameters←(⍴args)↑parameters :EndIf parameters(ref{⍺⍺⍎'Position.',⍺,'←',q ⍵})¨args ref.Uses,←⊂'JQueryUI' ref.Use :EndIf ∇ :endsection :section Event Handling Support ∇ r←isPost :Access public r←{0::0 ⋄ _Request.isPost}⍬ ∇ ∇ r←isAPLJax :Access public r←{0::0 ⋄ _Request.isAPLJAX}⍬ ∇ ∇ r←sel Css args ⍝ JQuery css cover :Access public r←(sel #._JSS.JQuery'css')args ∇ ∇ r←sel Val args ⍝ JQuery val cover :Access public r←(sel #._JSS.JQuery'val')args ∇ ∇ r←sel Attr args ⍝ JQuery attr cover :Access public r←(sel #._JSS.JQuery'attr')args ∇ ∇ r←sel RemoveAttr args ⍝ JQuery removeAttr cover :Access public r←(sel #._JSS.JQuery'removeAttr')args ∇ ∇ r←sel Html args ⍝ JQuery html cover :Access public r←(sel #._JSS.JQuery'html')args ∇ :endsection ∇ Debug;⎕TRAP :Access public ⎕TRAP←0⍴⎕TRAP ∘∘∘ ∇ :EndClass
:Class MiPage : #.HtmlPage ⍝∇:require =\HtmlPage.dyalog ⍝∇:require =\JSON.dyalog :Field Public _PageName←'' ⍝ Page file name :Field Public _PageDate←'' ⍝ Page saved date :field Public _Request ⍝ HTTPRequest :field Public _Scripts←'' :field Public _Styles←'' :field public _Serialized←1 ⍝ serialized forms to return in _PageData :field Public _event ⍝ set by APLJAX callback - event that was triggered :field Public _what ⍝ set by APLJAX callback - name or id of the triggering element :field Public _value ⍝ set by APLJAX callback - value of the triggering element :field Public _selector ⍝ set by APLJAX callback - CSS/jQuery selector for the element that triggered the event :field Public _callback ⍝ set by APLJAX callback - name of the callback function :field public _PageData :field public _AjaxResponse←'' :field public _DebugCallbacks←0 :field public OnLoad←'' ⍝ page equivalent to ⎕LX :field public shared _true←#.JSON.true ⍝ same definition as in #.JSON :field public shared _false←#.JSON.false ⍝ same definition as in #.JSON _used←'' ⍝ keep track of what's been used ∇ Make :Access public :Implements constructor :Base MakeCommon ∇ ∇ Make1 req :Access public _Request←req :Implements constructor :base MakeCommon ∇ ∇ MakeCommon _PageData←⎕NS'' ∇ ∇ {r}←Render;b :Access public :If ''≢OnLoad Use'JQuery' :EndIf b←RenderBody :If ~0∊⍴_Styles {(Head.Insert _html.link).Set(('href=',⍵)('rel' 'stylesheet')('type' 'text/css'))}¨∪⌽_Styles :EndIf :If ~0∊⍴_Scripts {(Head.Add _html.script).Set('src=',⍵)}¨∪_Scripts :EndIf :If ~0∊⍴Handlers b,←∊Handlers.Render :EndIf :If ''≢OnLoad b,←(⎕NEW #._html.script('$(function(){',OnLoad,'});')).Render :EndIf r←RenderPage b :If 0≠⎕NC⊂'_Request.Response' _Request.Response.HTML←r :EndIf ∇ ∇ {r}←Wrap :Access public r←Render ∇ ∇ Use resources;n;ind;t;x :Access public resources←eis resources :For x :In resources :If ~(⊂x)∊_used :Select ⊃x :Case '⍎' ⍝ script _Scripts,←⊂1↓x :Case '⍕' ⍝ style sheet _Styles,←⊂1↓x :Else :If 0≠⎕NC⊂'_Request.Server.Config.Resources' :AndIf ~0∊n←1↑⍴_Request.Server.Config.Resources :If n≥ind←_Request.Server.Config.Resources[;1]⍳⊂x :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 2)⊃_Request.Server.Config.Resources _Scripts,←t :EndIf :If ~0∊⍴t←{(~0∘∊∘⍴¨⍵)/⍵}(⊂ind 3)⊃_Request.Server.Config.Resources _Styles,←t :EndIf :Else 1 _Request.Server.Log _PageName,' references unknown resource: ',x :EndIf :EndIf :EndSelect _used,←⊂x :EndIf :EndFor ∇ ∇ r←{proto}Get names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←#.JSON.toAPL⊃r :EndIf :EndIf ⍝ :If ~isChar proto ⍝ r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r ⍝ :EndIf :EndIf ∇ ∇ r←{proto}GetRaw names :Access public proto←{6::⍵ ⋄ proto}'' names←eis names names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘Get¨names :ElseIf 2≠_PageData.⎕NC names r←,proto :Else r←_PageData⍎names :If 2=≡r :If 1=⍴,r r←⊃r :EndIf :EndIf :If ~isChar proto r←{0::⍵ ⋄ 0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ r←{proto}SessionGet names :Access public proto←{6::⍵ ⋄ proto}'' names←,⍕names names←#.Strings.deb names :If ' '∊names names←{⎕ML←3 ⋄ ⍵⊂⍨⍵≠' '}names r←proto∘SessionGet¨names :ElseIf 2≠_Request.Session.⎕NC names r←proto :Else r←_Request.Session⍎names :If 1<|≡r ⋄ r←∊r ⋄ :EndIf :If ~0 2∊⍨10|⎕DR proto r←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯' ⋄ ⊃(//)⎕VFI w}r :EndIf :EndIf ∇ ∇ Close session ⍝ Called when the session ends :Access Public Overridable ∇ :section APLJax ⍝ used for building APLJAX responses ∇ _resetAjax :Access public _AjaxResponse←'' ∇ ∇ r←_id :Access public ⍝ as there seems to be a problem with at least some Syncfusion widgets ⍝ being able to provide the id (or name) of the triggering element, we try to obtain it from _what or _selector r←'' :Trap 0 :If 0∊⍴r←_what :AndIf '#'=⊃_selector r←1↓_selector :EndIf :EndTrap ∇ ∇ Respond arg :Access public ∘∘∘ ∇ ∇ r←renderContent content;c r←'' content←eis content :While ~0∊⍴content :Select ≡c←⊃content :Case 0 :If isClass c :Select ⊃⍴content :Case 1 r,←(⎕NEW c).Render :Case 2 r,←(⎕NEW c(2⊃content)).Render :Else r,←(⎕NEW c(1↓content)).Render :EndSelect :ElseIf isInstance c r,←c.Render :Else r,←(⎕NEW #.HtmlElement(''content)).Render :EndIf content←'' :Case 1 :If isClass⊃c r,←(⎕NEW(⊃c)(1↓c)).Render :ElseIf isInstance⊃c ∘∘∘ ⍝ should not happen! (I think) :Else r,←(⎕NEW #.HtmlElement(''c)).Render :EndIf content←1↓content :Else r,←renderContent c content←1↓content :EndSelect :EndWhile ∇ ∇ r←selector Replace content :Access public r←⊂('replace'selector)('data'(renderContent content)) ∇ ∇ r←selector Append content :Access public r←⊂('append'selector)('data'(renderContent content)) ∇ ∇ r←selector Prepend content :Access public r←⊂('prepend'selector)('data'(renderContent content)) ∇ ∇ r←Execute content :Access public r←⊂('execute'content) ∇ ∇ r←name Assign data :Access public r←⊂('assign'name)('data'data) ∇ :endsection :section Position ∇ ref Position args;inds;mask;parameters;my;at;of;collision;within;q :Access public shared ⍝ ref - a reference to an instance of anything based on HtmlElement ⍝ args - position information per jQueryUI's Position widget http://api.jqueryui.com/position/ ⍝ can be in any of the following forms ⍝ 1) positional (my at of collision within) N.B. we don't use the "using" parameter ⍝ example: myDiv Position 'left top' 'right bottom' '#otherElement' ⍝ positions myDiv's top left corner at the bottom right corner of the element with id "otherElement" ⍝ 2) paired ⍝ myDiv Position 'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ myDiv Position ('my' 'left top') ('at' 'right bottom') ('of' '#otherElement') ⍝ myDiv Position 3 2⍴'my' 'left top' 'at' 'right bottom' 'of' '#otherElement' ⍝ Note: positional arguments are in form horizontal (left center right) vertical (top center bottom) parameters←'my' 'at' 'of' 'collision' 'within' q←{1⌽'''''',{⍵/⍨1+''''=⍵}⍕⍵} :If isInstance ref :If 2=⍴⍴args ⍝ matrix args←,args :ElseIf 3=≡args args←⊃,/args :EndIf args←eis args inds←parameters⍳args :If ∨/mask←inds≤⍴parameters :If mask≡(2×+/mask)⍴1 0 parameters←mask/args args←(1⌽mask)/args :EndIf :Else parameters←(⍴args)↑parameters :EndIf parameters(ref{⍺⍺⍎'Position.',⍺,'←',q ⍵})¨args ref.Uses,←⊂'JQueryUI' ref.Use :EndIf ∇ :endsection :section Event Handling Support ∇ r←isPost :Access public r←{0::0 ⋄ _Request.isPost}⍬ ∇ ∇ r←isAPLJax :Access public r←{0::0 ⋄ _Request.isAPLJAX}⍬ ∇ ∇ r←sel Css args ⍝ JQuery css cover :Access public r←(sel #._JSS.JQuery'css')args ∇ ∇ r←sel Val args ⍝ JQuery val cover :Access public r←(sel #._JSS.JQuery'val')args ∇ ∇ r←sel Attr args ⍝ JQuery attr cover :Access public r←(sel #._JSS.JQuery'attr')args ∇ ∇ r←sel RemoveAttr args ⍝ JQuery removeAttr cover :Access public r←(sel #._JSS.JQuery'removeAttr')args ∇ ∇ r←sel Html args ⍝ JQuery html cover :Access public r←(sel #._JSS.JQuery'html')args ∇ :endsection ∇ Debug;⎕TRAP :Access public ⎕TRAP←0⍴⎕TRAP ∘∘∘ ∇ :EndClass
Add MiPage.GetRaw
Add MiPage.GetRaw
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
8f40bd95601a5f0e1bee2a40787e3ec0e362c0a2
MS3/Code/MS3Server.dyalog
MS3/Code/MS3Server.dyalog
:Class MS3Server : MiServer ⍝ This is an example of a customized MiServer ⍝ The MiServer class exposes several overridable methods that can be customized by the user ⍝ In this case we customize the onServerLoad method ⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class :Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils ∇ Make config :Access Public :Implements Constructor :Base config ⍝ Version warning :If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion' ⎕←'' ⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later' ⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0' ⎕←'' ⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...' → :EndIf ∇ ∇ onServerLoad :Access Public Override ⍝ Handle any server startup processing {}C ⍝ initialize CACHE ∇ :EndClass
:Class MS3Server : MiServer ⍝ This is an example of a customized MiServer ⍝ The MiServer class exposes several overridable methods that can be customized by the user ⍝ In this case we customize the onServerLoad method ⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class :Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils ∇ Make config :Access Public :Implements Constructor :Base config ⍝ Version warning :If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion' ⎕←'' ⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later' ⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0' ⎕←'From version 15.0, Dyalog APL is available free of charge at http://www.dyalog.com' ⎕←'' ⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...' → :EndIf ∇ ∇ onServerLoad :Access Public Override ⍝ Handle any server startup processing {}C ⍝ initialize CACHE ∇ :EndClass
Upgrade message inculdes note of 15.0+ being free.
Upgrade message inculdes note of 15.0+ being free.
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
31522762e3e4a9e3ddfed315485fdaa02ff89d85
MS3/Examples/html/aSimple.dyalog
MS3/Examples/html/aSimple.dyalog
:class aSimple : MiPageSample ⍝ Control:: _html.a ⍝ Description:: Insert a hyperlink ∇ Compose :Access public Add 'Click ' 'href' 'http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here' Add ' to meet us.' ∇ :endclass
:class aSimple : MiPageSample ⍝ Control:: _html.a ⍝ Description:: Insert a hyperlink ∇ Compose :Access public Add'Click ' 'href=http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here' Add' to meet us.' ∇ :endclass
Fix to new ParseAttr syntax
Fix to new ParseAttr syntax
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
6054d202ca88d93d6604694a18e912e1747b485c
3-1.apl
3-1.apl
#!/usr/local/bin/apl -s 'Day 3: Perfectly Spherical Houses in a Vacuum' i ← (0 0) cmds ← ('<' '>' '^' 'v') dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1)) houses ← ∪ (0 0) , i { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞ ⍴ houses ⍝ the amount of houses to visit )OFF
#!/usr/local/bin/apl -s 'Day 3: Perfectly Spherical Houses in a Vacuum' cmds ← ('<' '>' '^' 'v') dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1)) houses ← ∪ (0 0) , { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞ ⍴ houses ⍝ the amount of houses to visit )OFF
Trim fat on apl nr 1
Trim fat on apl nr 1
APL
mit
profan/advent-of-code-2015,profan/advent-of-code-2015,profan/advent-of-code-2015
3cb01d3477c50c121d8ed0d42e44a13497ecca66
Utils/Strings.dyalog
Utils/Strings.dyalog
:Namespace Strings (⎕IO ⎕ML)←1 lower←'abcdefghijklmnopqrstuvwxyzáâãçèêëìíîïðòóôõùúûýàäåæéñöøü' upper←'ABCDEFGHIJKLMNOPQRSTUVWXYZÁÂÃÇÈÊËÌÍÎÏÐÒÓÔÕÙÚÛÝÀÄÅÆÉÑÖØÜ' ∇ r←lc r;m m←r∊upper (m/r)←lower[upper⍳m/r] ∇ ∇ r←uc r;m m←r∊lower (m/r)←upper[lower⍳m/r] ∇ vtom←{⎕ML←3 ⋄ ⍺←' ' ⋄ ⊃⍵⊂⍨~⍵∊⍺} ⍝ vector to matrix ∇ r←dlb x ⍝ Delete Leading Blanks r←(+/∧\' '=x)↓x ∇ ∇ r←dtb x ⍝ Delete Trailing Blanks r←(-+/∧\' '=⌽x)↓x ∇ ∇ r←deb x ⍝ Delete extraneous blanks r←{1↓¯1↓(~' '⍷⍵)/⍵}' ',x,' ' ∇ ∇ r←dmb x;m ⍝ Delete multiple blanks r←(m⍲1⌽m←' '=x)/x ∇ ∇ str←str subst(from to);m;⎕IO;i ⍝ simple string substitution ⎕IO←0 :Trap 0 str←((esc from)⎕R(esc to))str :Else →(∨/m←from⍷str)↓0 i←m⍳1 str←((i↑str),to,(i+⍴from)↓str)subst(from to) :EndTrap ∇ esc←{m←∊(-1+⍵∊'%\')↑¨1 ⋄ r←m\⍵ ⋄ ((~m)/r)←'\' ⋄ r } scaledFmt←{0=⍵:' 0' ⋄ ⍵{((1+⍵)⊃(⊂''),'KMGTQP'),⍨(1⌊⍵)⍕⍺÷10*3×⍵}⌊3÷⍨10⍟⍵} tonum←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯'⋄2 1⊃⎕VFI w} ∇ r←{d}commaFmt n :If 0=⎕NC'd' r←(,¨'CI20'∘⎕FMT¨n)~¨' ' :Else r←(,¨('CF20.',⍕d)∘⎕FMT¨n)~¨' ' :EndIf ∇ beginsWith←{(,⍺){⍵≡(⍴⍵)↑⍺},⍵} endsWith←{(,⍺){⍵≡(-⍴⍵)↑⍺},⍵} :EndNamespace
:Namespace Strings (⎕IO ⎕ML)←1 lower←'abcdefghijklmnopqrstuvwxyzáâãçèêëìíîïðòóôõùúûýàäåæéñöøü' upper←'ABCDEFGHIJKLMNOPQRSTUVWXYZÁÂÃÇÈÊËÌÍÎÏÐÒÓÔÕÙÚÛÝÀÄÅÆÉÑÖØÜ' ∇ r←lc r;m m←r∊upper (m/r)←lower[upper⍳m/r] ∇ ∇ r←uc r;m m←r∊lower (m/r)←upper[lower⍳m/r] ∇ vtom←{⎕ML←3 ⋄ ⍺←' ' ⋄ ⊃⍵⊂⍨~⍵∊⍺} ⍝ vector to matrix ∇ r←dlb x ⍝ Delete Leading Blanks r←(+/∧\' '=x)↓x ∇ ∇ r←dtb x ⍝ Delete Trailing Blanks r←(-+/∧\' '=⌽x)↓x ∇ ∇ r←deb x ⍝ Delete extraneous blanks r←{1↓¯1↓(~' '⍷⍵)/⍵}' ',x,' ' ∇ ∇ r←dmb x;m ⍝ Delete multiple blanks r←(m⍲1⌽m←' '=x)/x ∇ ∇ str←str subst(from to);m;⎕IO;i ⍝ simple string substitution ⎕IO←0 :Trap 0 str←((esc from)⎕R(esc to))str :Else →(∨/m←from⍷str)↓0 i←m⍳1 str←((i↑str),to,(i+⍴from)↓str)subst(from to) :EndTrap ∇ esc←{m←∊(-1+⍵∊'%\')↑¨1 ⋄ r←m\⍵ ⋄ ((~m)/r)←'\' ⋄ r } scaledFmt←{0=⍵:' 0' ⋄ ⍵{((1+⍵)⊃(⊂''),'KMGTQP'),⍨(1⌊⍵)⍕⍺÷10*3×⍵}⌊3÷⍨10⍟⍵} tonum←{0∊⍴⍵:⍬ ⋄ w←⍵ ⋄ ((w='-')/w)←'¯'⋄2 1⊃⎕VFI w} ∇ r←{d}commaFmt n :If 0=⎕NC'd' r←(,¨'CI20'∘⎕FMT¨n)~¨' ' :Else r←(,¨('CF20.',⍕d)∘⎕FMT¨n)~¨' ' :EndIf (∊r)←{w←⍵ ⋄ w⊣((w='¯')/w)←'-'}∊r ∇ beginsWith←{(,⍺){⍵≡(⍴⍵)↑⍺},⍵} endsWith←{(,⍺){⍵≡(-⍴⍵)↑⍺},⍵} :EndNamespace
replace high minus by low
strings.commaFmt: replace high minus by low
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
a080a1f0541680ce1dfa5cea331de4fe0daef8f7
src/prelude.apl
src/prelude.apl
⍬←0⍴0 ⍝ ⍬ <=> 0⍴0 ⍝ ⍴⍬ <=> ,0 ⍝# ⍬←5 !!! ⍝ ⍳0 <=> ⍬ ⍝ ⍴0 <=> ⍬ ⍝ ⍬ <=> ⍬ ⍝ ⍬⍬ <=> ⍬ ⍬ ⍝ 1⍬2⍬3 <=> 1 ⍬ 2 ⍬ 3 ~←~⍠{(~⍺∊⍵)/⍺} ⍝ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"~"AEIOU" <=> 'BCDFGHJKLMNPQRSTVWXYZ' ⍝ 1 2 3 4 5 6~2 4 6 <=> 1 3 5 ⍝ "THIS IS TEXT"~" " <=> 'THISISTEXT' ⍝ "THIS" "AND" "THAT"~"T" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~"AND" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~⊂"AND" <=> 'THIS' 'THAT' ⍝ "THIS" "AND" "THAT"~"TH" "AND" <=> 'THIS' 'THAT' ⍝ 11 12 13 14 15 16~2 3⍴1 2 3 14 5 6 <=> 11 12 13 15 16 ⍝ (2 2⍴⍳4)~2 !!! RANK ERROR _hook←{⍵⍶⍹⍵;⍺⍶⍹⍵} ⍝ (+÷)\3 7 16 ¯294 <=> (3 3.142857142857143 3.1415929203539825 3.141592653921421) ⍝ (=⌊)123 <=> 1 ⍝ (=⌊)123.4 <=> 0 ⍝ (÷⍟)1000 <=> 144.76482730108395 ⊃←{ 0=×/⍴⍵:⍵ shape←⍴⍵ ⋄ ⍵←,⍵ r←⌈/≢¨shapes←⍴¨⍵ ⍝ maximum rank of all shapes max←↑⌈/shapes←(⍴ ↓ (r⍴1)∘,)¨shapes ⍝ maximum shape of rank adjusted shapes (shape,max)⍴↑⍪/shapes{max↑⍺⍴⍵}¨⍵ ; 1<⍴⍴⍺:↗'RANK ERROR' x←⍵ { 1<⍴⍴⍵:↗'RANK ERROR' ⍵←,⍵ (⍴⍵)≠⍴⍴x:↗'RANK ERROR' ∨/⍵≥⍴x:↗'INDEX ERROR' x←⊃⍵⌷x }¨⍺ x } ⍝ ⊃3 <=> 3 ⍝ ⊃(1 2)(3 4) <=> 2 2⍴1 2 3 4 ⍝ ⊃(1 2)(3 4 5) <=> 2 3⍴1 2 0 3 4 5 ⍝ ⊃1 2 <=> 1 2 ⍝ ⊃(1 2)3 <=> 2 2⍴1 2 3 0 ⍝ ⊃1(2 3) <=> 2 2⍴1 0 2 3 ⍝ ⊃2 2⍴1(1 1 2⍴3 4)(5 6)(2 0⍴0) <=> 2 2 1 2 2⍴1 0 0 0 3 4 0 0 5 6 0 0 0 0 0 0 ⍝ ⊃⍬ <=> ⍬ ⍝ ⊃2 3 0⍴0 <=> 2 3 0⍴0 ⍝ ⍬⊃3 <=> 3 ⍝ 2⊃'PICK' <=> 'C' ⍝ (⊂1 0)⊃2 2⍴'ABCD' <=> 'C' ⍝ 1⊃'foo' 'bar' <=> 'bar' ⍝ 1 2⊃'foo' 'bar' <=> 'r' ⍝ (2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 1⍴0)⊃2 2⍴0 !!! RANK ERROR ⍝ (⊂2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 2)⊃1 2 !!! RANK ERROR ⍝ (⊂0 2)⊃2 2⍴'ABCD' !!! INDEX ERROR ⍪←{(≢⍵)(×/1↓⍴⍵)⍴⍵; ⍺,[0]⍵} ⍝ ⍪2 3 4 <=> 3 1⍴2 3 4 ⍝ ⍪0 <=> 1 1⍴0 ⍝ ⍪2 2⍴2 3 4 5 <=> 2 2⍴2 3 4 5 ⍝ ⍴⍪2 3⍴⍳6 <=> 2 3 ⍝ ⍴⍪2 3 4⍴⍳24 <=> 2 12 ⍝ (2 3⍴⍳6)⍪9 <=> 3 3⍴(0 1 2 3 4 5 9 9 9) ⍝ 1⍪2 <=> 1 2 ⊢←{⍵} ⍝ 123⊢456 <=> 456 ⍝ ⊢456 <=> 456 ⊣←{;⍺} ⍝ 123⊣456 <=> 123 ⍝ ⊣456 <=> ⍬ ≢←{⍬⍴(⍴⍵),1; ~⍺≡⍵} ⍝ ≢0 <=> 1 ⍝ ≢0 0 0 <=> 3 ⍝ ≢⍬ <=> 0 ⍝ ≢2 3⍴⍳6 <=> 2 ⍝ 3≢3 <=> 0 ⌹←{ norm←{(⍵+.×+⍵)*0.5} QR←{ ⍝ QR decomposition n←(⍴⍵)[1] 1≥n:{t←norm,⍵ ⋄ (⍵÷t)(⍪t)}⍵ m←⌈n÷2 a0←((1↑⍴⍵),m)↑⍵ a1←(0,m)↓⍵ (q0 r0)←∇a0 c←(+⍉q0)+.×a1 (q1 r1)←∇a1-q0+.×c (q0,q1)((r0,c)⍪((⌊n÷2),-n)↑r1) } Rinv←{ ⍝ Inverse of an upper triangular matrix 1=n←1↑⍴⍵:÷⍵ m←⌈n÷2 ai←∇(m,m)↑⍵ di←∇(m,m)↓⍵ b←(m,m-n)↑⍵ bx←-ai+.×b+.×di (ai,bx)⍪((⌊n÷2),-n)↑di } 0=⍴⍴⍵:÷⍵ 1=⍴⍴⍵:,∇⍪⍵ 2≠⍴⍴⍵:↗'ASSERTION ERROR' 0∊≥/⍴⍵:↗'ASSERTION ERROR' (Q R)←QR ⍵ (Rinv R)+.×+⍉Q ; (⌹⍵)+.×⍺ } ⍝ ⌹2 <=> .5 ⍝ ⌹2 2⍴4 3 3 2 <=> 2 2⍴¯2 3 3 ¯4 ⍝ (4 4⍴12 1 4 10 ¯6 ¯5 4 7 ¯4 9 3 4 ¯2 ¯6 7 7)⌹93 81 93.5 120.5 <=> ⍝ ... .0003898888816687221 ¯.005029566573526544 .04730651764247189 .0705568912859835 ⍨←{⍵⍶⍵;⍵⍶⍺} ⍝ 17-⍨23 <=> 6 ⍝ 7⍴⍨2 3 <=> 2 3⍴7 ⍝ +⍨2 <=> 4 ⍝ -⍨123 <=> 0
⍬←0⍴0 ⍝ ⍬ <=> 0⍴0 ⍝ ⍴⍬ <=> ,0 ⍝# ⍬←5 !!! ⍝ ⍳0 <=> ⍬ ⍝ ⍴0 <=> ⍬ ⍝ ⍬ <=> ⍬ ⍝ ⍬⍬ <=> ⍬ ⍬ ⍝ 1⍬2⍬3 <=> 1 ⍬ 2 ⍬ 3 ~←~⍠{(~⍺∊⍵)/⍺} ⍝ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"~"AEIOU" <=> 'BCDFGHJKLMNPQRSTVWXYZ' ⍝ 1 2 3 4 5 6~2 4 6 <=> 1 3 5 ⍝ "THIS IS TEXT"~" " <=> 'THISISTEXT' ⍝ "THIS" "AND" "THAT"~"T" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~"AND" <=> 'THIS' 'AND' 'THAT' ⍝ "THIS" "AND" "THAT"~⊂"AND" <=> 'THIS' 'THAT' ⍝ "THIS" "AND" "THAT"~"TH" "AND" <=> 'THIS' 'THAT' ⍝ 11 12 13 14 15 16~2 3⍴1 2 3 14 5 6 <=> 11 12 13 15 16 ⍝ (2 2⍴⍳4)~2 !!! RANK ERROR _hook←{⍵⍶⍹⍵;⍺⍶⍹⍵} ⍝ (+÷)\3 7 16 ¯294 <=> (3 3.142857142857143 3.1415929203539825 3.141592653921421) ⍝ (=⌊)123 <=> 1 ⍝ (=⌊)123.4 <=> 0 ⍝ (÷⍟)1000 <=> 144.76482730108395 ⊃←{ 0=⍴⍴⍵:↑⍵ 0=×/⍴⍵:⍵ shape←⍴⍵ ⋄ ⍵←,⍵ r←⌈/≢¨shapes←⍴¨⍵ ⍝ maximum rank of all shapes max←↑⌈/shapes←(⍴ ↓ (r⍴1)∘,)¨shapes ⍝ maximum shape of rank adjusted shapes (shape,max)⍴↑⍪/shapes{max↑⍺⍴⍵}¨⍵ ; 1<⍴⍴⍺:↗'RANK ERROR' x←⍵ { 1<⍴⍴⍵:↗'RANK ERROR' ⍵←,⍵ (⍴⍵)≠⍴⍴x:↗'RANK ERROR' ∨/⍵≥⍴x:↗'INDEX ERROR' x←⊃⍵⌷x }¨⍺ x } ⍝ ⊃3 <=> 3 ⍝ ⊃(1 2)(3 4) <=> 2 2⍴1 2 3 4 ⍝ ⊃(1 2)(3 4 5) <=> 2 3⍴1 2 0 3 4 5 ⍝ ⊃1 2 <=> 1 2 ⍝ ⊃(1 2)3 <=> 2 2⍴1 2 3 0 ⍝ ⊃1(2 3) <=> 2 2⍴1 0 2 3 ⍝ ⊃2 2⍴1(1 1 2⍴3 4)(5 6)(2 0⍴0) <=> 2 2 1 2 2⍴1 0 0 0 3 4 0 0 5 6 0 0 0 0 0 0 ⍝ ⊃⍬ <=> ⍬ ⍝ ⊃2 3 0⍴0 <=> 2 3 0⍴0 ⍝ ⍬⊃3 <=> 3 ⍝ 2⊃'PICK' <=> 'C' ⍝ (⊂1 0)⊃2 2⍴'ABCD' <=> 'C' ⍝ 1⊃'foo' 'bar' <=> 'bar' ⍝ 1 2⊃'foo' 'bar' <=> 'r' ⍝ (2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 1⍴0)⊃2 2⍴0 !!! RANK ERROR ⍝ (⊂2 2⍴0)⊃1 2 !!! RANK ERROR ⍝ (⊂2 2)⊃1 2 !!! RANK ERROR ⍝ (⊂0 2)⊃2 2⍴'ABCD' !!! INDEX ERROR ⍪←{(≢⍵)(×/1↓⍴⍵)⍴⍵; ⍺,[0]⍵} ⍝ ⍪2 3 4 <=> 3 1⍴2 3 4 ⍝ ⍪0 <=> 1 1⍴0 ⍝ ⍪2 2⍴2 3 4 5 <=> 2 2⍴2 3 4 5 ⍝ ⍴⍪2 3⍴⍳6 <=> 2 3 ⍝ ⍴⍪2 3 4⍴⍳24 <=> 2 12 ⍝ (2 3⍴⍳6)⍪9 <=> 3 3⍴(0 1 2 3 4 5 9 9 9) ⍝ 1⍪2 <=> 1 2 ⊢←{⍵} ⍝ 123⊢456 <=> 456 ⍝ ⊢456 <=> 456 ⊣←{;⍺} ⍝ 123⊣456 <=> 123 ⍝ ⊣456 <=> ⍬ ≢←{⍬⍴(⍴⍵),1; ~⍺≡⍵} ⍝ ≢0 <=> 1 ⍝ ≢0 0 0 <=> 3 ⍝ ≢⍬ <=> 0 ⍝ ≢2 3⍴⍳6 <=> 2 ⍝ 3≢3 <=> 0 ⌹←{ norm←{(⍵+.×+⍵)*0.5} QR←{ ⍝ QR decomposition n←(⍴⍵)[1] 1≥n:{t←norm,⍵ ⋄ (⍵÷t)(⍪t)}⍵ m←⌈n÷2 a0←((1↑⍴⍵),m)↑⍵ a1←(0,m)↓⍵ (q0 r0)←∇a0 c←(+⍉q0)+.×a1 (q1 r1)←∇a1-q0+.×c (q0,q1)((r0,c)⍪((⌊n÷2),-n)↑r1) } Rinv←{ ⍝ Inverse of an upper triangular matrix 1=n←1↑⍴⍵:÷⍵ m←⌈n÷2 ai←∇(m,m)↑⍵ di←∇(m,m)↓⍵ b←(m,m-n)↑⍵ bx←-ai+.×b+.×di (ai,bx)⍪((⌊n÷2),-n)↑di } 0=⍴⍴⍵:÷⍵ 1=⍴⍴⍵:,∇⍪⍵ 2≠⍴⍴⍵:↗'ASSERTION ERROR' 0∊≥/⍴⍵:↗'ASSERTION ERROR' (Q R)←QR ⍵ (Rinv R)+.×+⍉Q ; (⌹⍵)+.×⍺ } ⍝ ⌹2 <=> .5 ⍝ ⌹2 2⍴4 3 3 2 <=> 2 2⍴¯2 3 3 ¯4 ⍝ (4 4⍴12 1 4 10 ¯6 ¯5 4 7 ¯4 9 3 4 ¯2 ¯6 7 7)⌹93 81 93.5 120.5 <=> ⍝ ... .0003898888816687221 ¯.005029566573526544 .04730651764247189 .0705568912859835 ⍨←{⍵⍶⍵;⍵⍶⍺} ⍝ 17-⍨23 <=> 6 ⍝ 7⍴⍨2 3 <=> 2 3⍴7 ⍝ +⍨2 <=> 4 ⍝ -⍨123 <=> 0
Revert "rm "0=⍴⍴⍵:"; the joys of being dimension-agnostic"
Revert "rm "0=⍴⍴⍵:"; the joys of being dimension-agnostic" This reverts commit c7ece6626849698c9480e23228bb2f48cd945f15. issue #67
APL
mit
fineline/apl,fineline/apl,fineline/apl,fineline/apl
ef0f87b2ddbd3cea27838cdc632008dd0a51e44b
MS3/Examples/Menuexample3.dyalog
MS3/Examples/Menuexample3.dyalog
:Class Menuexample3 : MiPageSample ⍝ Demonstrate the SyncFusion ejMenu widget ⎕ml←⎕io←1 ∇ r←Render;items;t;tmp;a;i;m;opt :Access Public ⍝ tmp←⎕XML∊example ⍝ i←a/⍳⍴a←tmp[;2]∊⊂,'a' ⋄ tmp[i-1;3]←tmp[i;3] ⋄ tmp←(~a)⌿tmp ⍝ items←↓⍉tmp[;1 3],⊂'' Add build m←Add _SF.ejMenu opt←'{dataSource: data, id: "id", parentId: "parentId", text: "text", spriteCssClass: "sprite"}' 'fields'm.Option opt ⍝ 'datasource'm.Option'data' ⍝ 'id'm.Option'id' ⍝ 'parentid'm.Option'parentId' ⍝ 'text'm.Option'text' ⍝ 'spriteCssClass'm.Option'sprite' ⍝ Add m ∇ ∇ m←build;P;F;C;cr ⍝ This data recreates SuncFusion's http://js.syncfusion.com/demos/web/#!/azure/menu/databinding-localdata page example ⍝[{id:1,parentid:null,text:"Group A"} ⍝,{id:2,parentid:null,text:"Group B"} ⍝,{id:3,parentid:null,text:"Group C"} ⍝,{id:4,parentid:null,text:"Group D"} ⍝,{id:5,parentid:null,text:"Group E"} ⍝,{id:11,parentId:1,sprite:"flag-dz",text:"Algeria"} ⍝,{id:12,parentId:1,sprite:"flag-am",text:"Armenia"} ⍝,{id:13,parentId:1,sprite:"flag-bd",text:"Bangladesh"} ⍝,{id:14,parentId:1,sprite:"flag-cu",text:"Cuba"} ⍝,{id:15,parentId:2,sprite:"flag-dk",text:"Denmark"} ⍝,{id:16,parentId:2,sprite:"flag-eg",text:"Egypt"} ⍝,{id:17,parentId:3,sprite:"flag-fi",text:"Finland"} ⍝,{id:18,parentId:3,sprite:"flag-in",text:"India"} ⍝,{id:19,parentId:3,sprite:"flag-my",text:"Malaysia"} ⍝,{id:20,parentId:4,sprite:"flag-nz",text:"New Zealand"} ⍝,{id:21,parentId:4,sprite:"flag-no",text:"Norway"} ⍝,{id:22,parentId:4,sprite:"flag-pl",text:"Poland"} ⍝,{id:23,parentId:5,sprite:"flag-ro",text:"Romania"} ⍝,{id:24,parentId:5,sprite:"flag-sg",text:"Singapore"} ⍝,{id:25,parentId:5,sprite:"flag-th",text:"Thailand"} ⍝,{id:26,parentId:5,sprite:"flag-ua",text:"Ukraine"} ⍝,{id:111,parentId:11,text:"First Place"} ⍝,{id:112,parentId:12,text:"Second Place"} ⍝,{id:113,parentId:13,text:"Third Place"} ⍝,{id:114,parentId:14,text:"Fourth Place"} ⍝,{id:115,parentId:15,text:"First Place"} ⍝,{id:116,parentId:16,text:"Second Place"} ⍝,{id:117,parentId:17,text:"Third Place"} ⍝,{id:118,parentId:18,text:"First Place"} ⍝,{id:119,parentId:19,text:"Second Place"} ⍝,{id:120,parentId:20,text:"First Place"} ⍝,{id:121,parentId:21,text:"Second Place"} ⍝,{id:122,parentId:22,text:"Third Place"} ⍝,{id:123,parentId:23,text:"Fourth Place"} ⍝,{id:124,parentId:24,text:"First Place"} ⍝,{id:125,parentId:25,text:"Second Place"} ⍝,{id:126,parentId:26,text:"Third Place"}] m←{'{id:',(⍕⍵),',text:"Group ',⎕A[⍵],'",parentid:null},'}¨⍳5 C←'Algeria' 'Armenia' 'Bangladesh' 'Cuba' 'Denmark' 'Egypt' 'Finland' 'India' C,←'Malaysia' 'New Zealand' 'Norway' 'Poland' 'Romania' 'Singapore' 'Thailand' 'Ukraine' F←'flag-'∘,¨↓16 2⍴'dzambdcudkegfiinmynznoplrosgthua' m,←(4 2 3 3 4/⍳5){'{id:',(⍕10+⍵),',parentId:',(⍕⍺),',text:"',(⍵⊃C),'",sprite:"',(⍵⊃F),'"},'}¨⍳16 P←'First' 'Second' 'Third' 'Fourth'[1 2 3 4 1 2 3 1 2 1 2 3 4 1 2 3],¨⊂' Place' m,←{'{id:',(⍕110+⍵),',parentId:',(⍕10+⍵),',text:"',(⍵⊃P),'"},'}¨⍳16 m[⍴m]↓⍨←¯1 m←m,¨cr←⎕UCS 13 m←∊1⌽('];' '<script type="text/javascript">var data = [',¨cr),m ∇ :EndClass
:Class Menuexample3 : MiPageSample ⍝ Demonstrate the SyncFusion ejMenu widget ⎕ml←⎕io←1 ∇ r←Render;items;t;tmp;a;i;m;opt :Access Public ⍝ tmp←⎕XML∊example ⍝ i←a/⍳⍴a←tmp[;2]∊⊂,'a' ⋄ tmp[i-1;3]←tmp[i;3] ⋄ tmp←(~a)⌿tmp ⍝ items←↓⍉tmp[;1 3],⊂'' Add build m←Add _SF.ejMenu opt←'{dataSource: data, id: "id", parentId: "parentId", text: "text", spriteCssClass: "sprite"}' 'fields'm.Option opt ⍝ 'datasource'm.Option'data' ⍝ 'id'm.Option'id' ⍝ 'parentid'm.Option'parentId' ⍝ 'text'm.Option'text' ⍝ 'spriteCssClass'm.Option'sprite' ⍝ Add m ∇ ∇ m←build;P;F;C;cr ⍝ This data recreates SuncFusion's http://js.syncfusion.com/demos/web/#!/azure/menu/databinding-localdata page example ⍝[{id:1,parentid:null,text:"Group A"} ⍝,{id:2,parentid:null,text:"Group B"} ⍝,{id:3,parentid:null,text:"Group C"} ⍝,{id:4,parentid:null,text:"Group D"} ⍝,{id:5,parentid:null,text:"Group E"} ⍝,{id:11,parentId:1,sprite:"flag-dz",text:"Algeria"} ⍝,{id:12,parentId:1,sprite:"flag-am",text:"Armenia"} ⍝,{id:13,parentId:1,sprite:"flag-bd",text:"Bangladesh"} ⍝,{id:14,parentId:1,sprite:"flag-cu",text:"Cuba"} ⍝,{id:15,parentId:2,sprite:"flag-dk",text:"Denmark"} ⍝,{id:16,parentId:2,sprite:"flag-eg",text:"Egypt"} ⍝,{id:17,parentId:3,sprite:"flag-fi",text:"Finland"} ⍝,{id:18,parentId:3,sprite:"flag-in",text:"India"} ⍝,{id:19,parentId:3,sprite:"flag-my",text:"Malaysia"} ⍝,{id:20,parentId:4,sprite:"flag-nz",text:"New Zealand"} ⍝,{id:21,parentId:4,sprite:"flag-no",text:"Norway"} ⍝,{id:22,parentId:4,sprite:"flag-pl",text:"Poland"} ⍝,{id:23,parentId:5,sprite:"flag-ro",text:"Romania"} ⍝,{id:24,parentId:5,sprite:"flag-sg",text:"Singapore"} ⍝,{id:25,parentId:5,sprite:"flag-th",text:"Thailand"} ⍝,{id:26,parentId:5,sprite:"flag-ua",text:"Ukraine"} ⍝,{id:111,parentId:11,text:"First Place"} ⍝,{id:112,parentId:12,text:"Second Place"} ⍝,{id:113,parentId:13,text:"Third Place"} ⍝,{id:114,parentId:14,text:"Fourth Place"} ⍝,{id:115,parentId:15,text:"First Place"} ⍝,{id:116,parentId:16,text:"Second Place"} ⍝,{id:117,parentId:17,text:"Third Place"} ⍝,{id:118,parentId:18,text:"First Place"} ⍝,{id:119,parentId:19,text:"Second Place"} ⍝,{id:120,parentId:20,text:"First Place"} ⍝,{id:121,parentId:21,text:"Second Place"} ⍝,{id:122,parentId:22,text:"Third Place"} ⍝,{id:123,parentId:23,text:"Fourth Place"} ⍝,{id:124,parentId:24,text:"First Place"} ⍝,{id:125,parentId:25,text:"Second Place"} ⍝,{id:126,parentId:26,text:"Third Place"}] m←{'{id:',(⍕⍵),',text:"Group ',⎕A[⍵],'",parentid:null},'}¨⍳5 C←'Algeria' 'Armenia' 'Bangladesh' 'Cuba' 'Denmark' 'Egypt' 'Finland' 'India' C,←'Malaysia' 'New Zealand' 'Norway' 'Poland' 'Romania' 'Singapore' 'Thailand' 'Ukraine' F←'flag-'∘,¨↓16 2⍴'dzambdcudkegfiinmynznoplrosgthua' m,←(4 2 3 3 4/⍳5){'{id:',(⍕10+⍵),',parentId:',(⍕⍺),',text:"',(⍵⊃C),'",sprite:"',(⍵⊃F),'"},'}¨⍳16 P←'First' 'Second' 'Third' 'Fourth'[1 2 3 4 1 2 3 1 2 1 2 3 4 1 2 3],¨⊂' Place' m,←{'{id:',(⍕110+⍵),',parentId:',(⍕10+⍵),',text:"',(⍵⊃P),'"},'}¨⍳16 m[⍴m]↓⍨←¯1 m←m,¨cr←⎕UCS 13 m←∊2⌽('];' '</script>' '<script type="text/javascript">var data = [',¨cr),m ∇ :EndClass
complete script tag
complete script tag tag was missing
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
756dcb223aa06385c487ba370afbb5fdbd11c17c
HTML/_DC/Select.dyalog
HTML/_DC/Select.dyalog
:class Select : #._html.select ⍝ Description:: Dyalog Enhanced HTML select ⍝ Constructor:: [options [[selected] [prompt]]] ⍝ options - vector of options or 2 column matrix of displayed[;1] and returned[;2] values ⍝ selected - Boolean or integer array indicating pre-selected options(s) ⍝ prompt - first item to display (has no value) (default '[Select]') ⍝ Public Fields:: ⍝ Options - vector of options or 2 column matrix of displayed[;1] and returned[;2] values ⍝ Selected - Boolean or integer array indicating pre-selected options(s) ⍝ Prompt - first item to display (has no value) (default '[Select]') ⍝ Examples:: ⍝ Select ('Choice 1' 'Choice 2' 'Choice 3') ⍝ Select (3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') 2) ⍝ second item is selected ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') (0 1 0)) ⍝ second item is selected ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') 2 'Pick One') :field public Options←0 2⍴⊂'' ⍝ vector or matrix [;1] display, [;2] value :field public Selected←⍬ ⍝ either Boolean integer vector indicating :field public Prompt←'[Select]' ⍝ character vector "Prompt" choice - the first choice on the list and does not have a value ∇ make :Access public :Implements constructor ∇ ∇ make1 args;attr :Access public :Implements constructor args←eis args :If (|≡args)∊0 1 2 args←,⊂args :EndIf (Options Selected Prompt)←args defaultArgs Options Selected Prompt ∇ ∇ r←Render;opts :Access public Content←'' SetId :If ~0∊⍴Options opts←eis Options :If 1=⍴⍴opts opts←opts,⍪opts :EndIf :If 11=⎕DR sel←Selected sel←{⍵/⍳⍴⍵},sel :EndIf opts[sel;1],⍨←⎕UCS 1 Add Prompt FormatOptions opts :EndIf r←⎕BASE.Render ∇ ∇ r←{Prompt}FormatOptions opts;opt :Access Public :If 0=⎕NC'Prompt' ⋄ Prompt←'' ⋄ :EndIf :If 1=⍴⍴opts ⋄ opts←opts,⍪opts ⋄ :EndIf opt←(0∊⍴Prompt)↓(Prompt'')⍪opts r←∊{sel←(⎕UCS 1)=1↑⍺ ⋄ '<option',(⍵ ine' value="',(HtmlSafeText ⍵),'"'),(sel/' selected="selected"'),'>',(⍕sel↓⍺),'</option>'}/opt ∇ :endclass
:class Select : #._html.select ⍝ Description:: Dyalog Enhanced HTML select ⍝ Constructor:: [options [[selected] [prompt]]] ⍝ options - vector of options or 2 column matrix of displayed[;1] and returned[;2] values ⍝ selected - Boolean or integer array indicating pre-selected options(s) ⍝ prompt - first item to display (has no value) (default '[Select]') ⍝ Public Fields:: ⍝ Options - vector of options or 2 column matrix of displayed[;1] and returned[;2] values ⍝ Selected - Boolean or integer array indicating pre-selected options(s) ⍝ Prompt - first item to display (has no value) (default '[Select]') ⍝ Examples:: ⍝ Select ('Choice 1' 'Choice 2' 'Choice 3') ⍝ Select (3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') 2) ⍝ second item is selected ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') (0 1 0)) ⍝ second item is selected ⍝ Select ((3 2⍴'Choice 1' 'c1' 'Choice 2' 'c2' 'Choice 3' 'c3') 2 'Pick One') :field public Options←0 2⍴⊂'' ⍝ vector or matrix [;1] display, [;2] value :field public Selected←⍬ ⍝ either Boolean integer vector indicating :field public Prompt←'[Select]' ⍝ character vector "Prompt" choice - the first choice on the list and does not have a value ∇ make :Access public :Implements constructor ∇ ∇ make1 args;attr :Access public :Implements constructor args←eis args :If (|≡args)∊0 1 2 args←,⊂args :EndIf (Options Selected Prompt)←args defaultArgs Options Selected Prompt ∇ ∇ r←Render;opts :Access public Content←'' SetId :If ~0∊⍴Options opts←eis Options :If 1=⍴⍴opts opts←opts,⍪opts :EndIf :If 11=⎕DR sel←Selected sel←{⍵/⍳⍴⍵},sel :EndIf opts[sel;1],⍨←⎕UCS 1 Add Prompt FormatOptions opts :EndIf r←⎕BASE.Render ∇ ∇ r←{Prompt}FormatOptions opts;opt :Access Public Shared :If 0=⎕NC'Prompt' ⋄ Prompt←'' ⋄ :EndIf :If 1=⍴⍴opts ⋄ opts←opts,⍪opts ⋄ :EndIf opt←(0∊⍴Prompt)↓(Prompt'')⍪opts r←∊{sel←(⎕UCS 1)=1↑⍺ ⋄ '<option',(⍵ ine' value="',(HtmlSafeText ⍵),'"'),(sel/' selected="selected"'),'>',(⍕sel↓⍺),'</option>'}/opt ∇ :endclass
Make _DC.Select.FormatOptions Public Shared
Make _DC.Select.FormatOptions Public Shared
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
0fcf18b9ec6206ee013e8b77df002b0cb64b36f6
MS3/QA/Examples/DC/FigureSimple.dyalog
MS3/QA/Examples/DC/FigureSimple.dyalog
 msg←Test dummy;fig fig←Find'fig' msg←(283 890≢fig.Size.(Height Width))/'figure size is not 283x890'
 msg←Test dummy;fig fig←Find'fig' msg←(~fig.Displayed∧0∧.≠fig.Size.(Height Width))/'figure not displayed'
Improve FigureSimple QA
Improve FigureSimple QA
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
87db57f12d3f2d9cd6b3b8585c08d57ce6548ca3
MS3/Examples/SF/ejButtonSimple.dyalog
MS3/Examples/SF/ejButtonSimple.dyalog
:Class ejButtonSimple : MiPageSample ⍝ Control:: _SF.ejButton ⍝ Description:: two buttons, one en/disables the other and another that displays an alert ∇ Compose :Access Public ⍝ The first button (b1) b1←'b1'Add _SF.ejButton'Toggle its state →' 'type'b1.Set'ej.ButtonType.Button' b1.On'click' 'myCallback' ⍝ The second button (b2) b2←Add _SF.ejButton'Show alert' b2.id←'b2' 'type' 'enabled'b2.Set'ej.ButtonType.Button'_false b2.On'click' 'myCallback' ∇ ∇ r←myCallback :Access public ∘∘∘∘ ⍝ This callback simply flips b2's state when b1 is clicked :If 'b1'≡_what r←'enabled'b2.Update⊃_true _false~b2.GetOption'enabled' :Else r←Execute'alert("Hi there!")' :EndIf ∇ :EndClass
:Class ejButtonSimple : MiPageSample ⍝ Control:: _SF.ejButton ⍝ Description:: two buttons, one en/disables the other and another that displays an alert ∇ Compose :Access Public ⍝ The first button (b1) b1←'b1'Add _SF.ejButton'Toggle its state →' 'type'b1.Set'ej.ButtonType.Button' b1.On'click' 'myCallback' ⍝ The second button (b2) b2←Add _SF.ejButton'Show alert' b2.id←'b2' 'type' 'enabled'b2.Set'ej.ButtonType.Button'_false b2.On'click' 'myCallback' ∇ ∇ r←myCallback :Access public ⍝ This callback simply flips b2's state when b1 is clicked :If 'b1'≡_what r←'enabled'b2.Update⊃_true _false~b2.GetOption'enabled' :Else r←Execute'alert("Hi there!")' :EndIf ∇ :EndClass
Remove stop in ejButtonSimple
Remove stop in ejButtonSimple
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
220c5d00a3d36ed40251a7629d982a2ae3198fc6
HTML/_JS/DataTable.dyalog
HTML/_JS/DataTable.dyalog
:Class DataTable : #._JQ._jqWidget ⍝ Description:: Enhanced HTML table using DataTables from https://www.datatables.net/ ⍝ Constructor:: [Data [CellAttr [HeaderRows [HeaderAttr [MakeCellIds [MakeRowIds]]]]] ⍝ Constructor arguments are identical to those for #._DC.Table ⍝ ⍝ Public Fields:: ⍝ Data - matrix of data to display in the table ⍝ CellAttr - Cell Attributes ⍝ HeaderRows - # of header rows ⍝ HeaderAttr - Header attributes ⍝ MakeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ MakeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←1 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 ∇ Make0 :Access public JQueryFn←Uses←'DataTable' :Implements constructor ∇ ∇ Make1 args :Access public JQueryFn←Uses←'DataTable' :Implements Constructor :If 2=⍴⍴args ⋄ args←,⊂args ⋄ :EndIf Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds←args defaultArgs Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds ∇ ∇ html←Render;tab :Access public SetId Selector←'#',id :If 'true'≡⍕GetOption'searchHighlight' Use'jquery.Highlight' Use'⍎/DataTables/extras/searchHighlight/DataTables.searchHighlight.min.js' Use'⍕/DataTables/extras/searchHighlight/DataTables.searchHighlight.css' :EndIf (tab←⎕NEW #._DC.Table(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds)).id←id html←(tab.Render),⎕BASE.Render ⍝ BPB - to be sorted out with Michael ⍝ ⍝***** the following should be optional! ⍝ ⍝ ⍝ ⍝ only applied if Options.searchHighlight=#.JSON.true ⍝ 'DataTables_searchHighlight'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ⍝ ⍝ only needed when Options.sDom contains 'W' ⍝ '⍎/DataTables/extras/ColumnFilterWidgets/media/js/ColumnFilterWidgets.js'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ⍝ '⍕/DataTables/extras/ColumnFilterWidgets/media/css/ColumnFilterWidgets.css'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ∇ :EndClass
:Class DataTable : #._JQ._jqWidget ⍝ Description:: Enhanced searchable and reorderable HTML table ⍝ Constructor:: [Data [CellAttr [HeaderRows [HeaderAttr [MakeCellIds [MakeRowIds]]]]] ⍝ Notes:: Constructor arguments are identical to those for _.Table ⍝ Public Fields:: ⍝ Data - matrix of data to display in the table ⍝ CellAttr - Cell Attributes ⍝ HeaderRows - # of header rows ⍝ HeaderAttr - Header attributes ⍝ MakeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ MakeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> :Field public shared readonly DocBase←'https://www.datatables.net/' :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←1 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 ∇ Make0 :Access public JQueryFn←Uses←'DataTable' :Implements constructor ∇ ∇ Make1 args :Access public JQueryFn←Uses←'DataTable' :Implements Constructor :If 2=⍴⍴args ⋄ args←,⊂args ⋄ :EndIf Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds←args defaultArgs Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds ∇ ∇ html←Render;tab :Access public SetId Selector←'#',id :If 'true'≡⍕GetOption'searchHighlight' Use'jquery.Highlight' Use'⍎/DataTables/extras/searchHighlight/DataTables.searchHighlight.min.js' Use'⍕/DataTables/extras/searchHighlight/DataTables.searchHighlight.css' :EndIf (tab←⎕NEW #._DC.Table(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds)).id←id html←(tab.Render),⎕BASE.Render ⍝ BPB - to be sorted out with Michael ⍝ ⍝***** the following should be optional! ⍝ ⍝ ⍝ ⍝ only applied if Options.searchHighlight=#.JSON.true ⍝ 'DataTables_searchHighlight'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ⍝ ⍝ only needed when Options.sDom contains 'W' ⍝ '⍎/DataTables/extras/ColumnFilterWidgets/media/js/ColumnFilterWidgets.js'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ⍝ '⍕/DataTables/extras/ColumnFilterWidgets/media/css/ColumnFilterWidgets.css'{6::⍺ ∇ 1↓⍵ ⋄ 0<⍴⍵:(1⊃⍵).Use ⍺}⎕RSI ∇ :EndClass
restructure of internal doc
DataTable: restructure of internal doc
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
8170e55d327e1da4c18be41c28acb809028131f4
HTML/_JS/DataTable.dyalog
HTML/_JS/DataTable.dyalog
:Class DataTable : #._JQ._jqWidget ⍝ Description:: Enhanced searchable and reorderable HTML table ⍝ Constructor:: [data [cellAttr [headerRows [headerAttr [makeCellIds [makeRowIds]]]]] ⍝ Note that constructor arguments are identical to those for Table ⍝ data - matrix of data to display in the table ⍝ cellAttr - Cell Attributes ⍝ headerRows - # of header rows ⍝ headerAttr - Header attributes ⍝ makeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ makeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> ⍝ Public Fields:: ⍝ Data - matrix of data to display in the table ⍝ CellAttr - Cell Attributes ⍝ HeaderRows - # of header rows ⍝ HeaderAttr - Header attributes ⍝ MakeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ MakeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> :Field public shared readonly DocBase←'https://www.datatables.net/' :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←1 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 :field public Plugins←'' ⍝ comma delimited list of "official" plugins to use :field private JSON_Data←'' ⍝ supporting JSON-Data transparently ("Data" can be JSON) ∇ Make0 :Access public JQueryFn←Uses←'DataTable' :Implements constructor Container←⎕NEW #._DC.Table ContainerTag←'table' ∇ ∇ Make1 args :Access public JQueryFn←Uses←'DataTable' :Implements Constructor :If 2=⍴⍴args ⋄ args←,⊂args ⋄ :EndIf Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds←args defaultArgs Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds :If 2≠⍴⍴Data :AndIf #.HtmlElement.isChar Data JSON_Data←Data ⋄ Data←0 0⍴0 :EndIf Container←⎕NEW #._DC.Table ContainerTag←'table' ∇ ∇ html←Render;tab :Access public ⍝∘∘∘ :If _true≡GetOption'mark' Use'DataTable_mark' SetUse :EndIf opts←Options JavaScript,←RenderPlugins Options←opts :If 0<⍴JSON_Data ⋄ 'data'Set⊂JSON_Data ⋄ :EndIf Container.(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds)←(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds) html←⎕BASE.Render ∇ ∇ js←RenderPlugins;plugin ⍝ might also update Options js←'' :For plugin :In ','#.Utils.penclose Plugins :Select plugin :Case 'yadcf' js,←yadcfRender Options.⎕EX'yadcf' :EndSelect :EndFor ∇ :section yadcf Plugin ∇ js←yadcfRender;flt js←'' :If 0<Options.⎕NC'yadcf.Filters' :AndIf 0<⍴Options.yadcf.Filters Uses←'DataTable_yadcf' flt←#.JSON.fromAPL Options.yadcf.Filters :If ∨/'"chosen"'⍷flt ⋄ Use'chosen' ⋄ :EndIf ⍝ load Chosen-Plugin for yadcf-Filters js←';yadcf.init($("#',id,'").DataTable(),',flt,');' :EndIf ∇ :endsection :EndClass
:Class DataTable : #._JQ._jqWidget ⍝ Description:: Enhanced searchable and reorderable HTML table ⍝ Constructor:: [data [cellAttr [headerRows [headerAttr [makeCellIds [makeRowIds]]]]] ⍝ Note that constructor arguments are identical to those for Table ⍝ data - matrix of data to display in the table ⍝ cellAttr - Cell Attributes ⍝ headerRows - # of header rows ⍝ headerAttr - Header attributes ⍝ makeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ makeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> ⍝ Public Fields:: ⍝ Data - matrix of data to display in the table ⍝ CellAttr - Cell Attributes ⍝ HeaderRows - # of header rows ⍝ HeaderAttr - Header attributes ⍝ MakeCellIds - 1 to generate IDs <td id="tableId_r2c3"> ⍝ MakeRowIds - 1 to generate Row IDs <tr id="tableId_row2"> :Field public shared readonly DocBase←'https://www.datatables.net/' :field public Data←0 0⍴⊂'' :field public CellAttr←'' :field public HeaderRows←1 :field public HeaderAttr←'' :field public MakeCellIds←0 :field public MakeRowIds←0 :field public Plugins←'' ⍝ comma delimited list of "official" plugins to use :field private JSON_Data←'' ⍝ supporting JSON-Data transparently ("Data" can be JSON) ∇ Make0 :Access public JQueryFn←Uses←'DataTable' :Implements constructor Container←⎕NEW #._DC.Table ContainerTag←'table' ∇ ∇ Make1 args :Access public JQueryFn←Uses←'DataTable' :Implements Constructor :If 2=⍴⍴args ⋄ args←,⊂args ⋄ :EndIf Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds←args defaultArgs Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds :If 2≠⍴⍴Data :AndIf #.HtmlElement.isChar Data JSON_Data←Data ⋄ Data←0 0⍴0 :EndIf Container←⎕NEW #._DC.Table ContainerTag←'table' ∇ ∇ html←Render;tab :Access public ⍝∘∘∘ :If _true≡GetOption'mark' Use'DataTable_mark' SetUse :EndIf opts←Options JavaScript,←RenderPlugins Options←opts :If 0<⍴JSON_Data ⋄ 'data'Set⊂JSON_Data ⋄ :EndIf Container.(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds)←(Data CellAttr HeaderRows HeaderAttr MakeCellIds MakeRowIds) html←⎕BASE.Render ∇ ∇ js←RenderPlugins;plugin ⍝ might also update Options js←'' :For plugin :In ','#.Utils.penclose Plugins :Select plugin :Case 'yadcf' js,←yadcfRender Options.⎕EX'yadcf' :EndSelect :EndFor ∇ :section yadcf Plugin ∇ js←yadcfRender;flt js←'' :If 0<Options.⎕NC'yadcf.Filters' :AndIf ×≢Options.yadcf.Filters Uses←'DataTable_yadcf' flt←#.JSON.fromAPL Options.yadcf.Filters :If ∨/'"chosen"'⍷flt ⋄ Use'chosen' ⋄ :EndIf ⍝ load Chosen-Plugin for yadcf-Filters js←';yadcf.init($("#',id,'").DataTable(),',flt,');' :EndIf ∇ :endsection :EndClass
Handle scalar yadcf.Filters
DataTable: Handle scalar yadcf.Filters
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
3d5d188f9add8bb811ab273dccdf1b3ba467f4c2
QA/SeleniumTests.dyalog
QA/SeleniumTests.dyalog
:Namespace SeleniumTests ∇ x←eis x ⍝ Enclose if simple :If (≡x)∊0 1 ⋄ x←,⊂,x ⋄ :EndIf ∇ ∇ r←lopFirst url ⍝ remove first segment of URL r←{⍵/⍨(1+'/'=1↑⍵)≤+\'/'=⍵}url ∇ ∇ r←Run1Test page;name;ref;Test ⍝ eg MS3Test '/QA/DC/InputGridSimple' Selenium.GoTo SITE,lopFirst page ⍝ Drop the "QA" :If 'Test'≡name←⎕SE.SALT.Load AppRoot,page :Trap stopOnError×9999 :If stopOnError∧0≠⍴r←Test ⍬ ⎕←'test for ',page,' failed:' ⋄ ⎕←r ⋄ ⎕←'Rerun:' ⋄ ' Test ⍬' ∘∘∘ :EndIf :Else r←'Trapped error: ',,⍕⎕DMX.EN :EndTrap :Else ⋄ r←AppRoot,page,' does not define a function called Test' :EndIf ∇ ∇ r←FindAllFiles root;folders;ext :If 0=⎕NC'Config.DefaultExtension' ⋄ ext←'.dyalog' :Else ⋄ ext←Config.DefaultExtension :EndIf root,←'/'/⍨~'/\'∊⍨¯1↑root ⍝ append trailing / if missing r←root∘,¨(('*',ext)#.Files.List root)[;1] :If 0≠⍴folders←{(('.'≠⊃¨⍵[;1])∧⍵[;4])/⍵[;1]}#.Files.List root r←r,⊃,/FindAllFiles¨root∘,¨folders :EndIf ∇ ∇ r←{stopOnError}Test site;count;ctl;examples;f;fail;nodot;start;t;time;z;i;START;COUNT;FAIL;Config;selpath;files;n;ext;filter;⎕PATH;keynames;maxlen;⎕USING r←'' (site filter)←2↑(eis site),'' '' :If 0=⍴AppRoot←#.Load site ⎕←'Test abandoned' ⋄ →0 :EndIf selpath←({∊'/',⍨¨¯1↓'/\'#.Utils.penclose ⍵}#.Boot.MSRoot),'Selenium/' :If 0=⎕NC'Selenium' :Trap 0 ⋄ ⎕SE.SALT.Load selpath,'/Selenium' :Else ⎕←'Selenium library not found at: ',selpath →0⍴⍨0∊⍴selpath←{⍞↓⍨⍴⍞←⍵,': '}'Selenium path' :Trap 0 ⋄ ⎕SE.SALT.Load selpath,'/Selenium' :Else ⋄ ⎕←'Unable to load Selenium' ⋄ →0 :EndTrap :EndTrap :EndIf ⎕PATH,←' Selenium' Selenium.DLLPATH←selpath Config←#.Boot.ConfigureServer AppRoot ext←Config.DefaultExtension Config.DefaultExtension←'.dyalog' ⍝ We are searching for code n←⍴files←(⍴AppRoot)↓¨¯7↓¨FindAllFiles AppRoot,'QA' ⍝ // Add code to compare this to the mipages found in the whole app :If 0≠⍴filter files←(filter ⎕S'%')files ⎕←'Selected: ',(⍕⍴files),' of ',(⍕n),' tests.' :EndIf n←⍴files SITE←'http://127.0.0.1:',⍕Config.Port ⍝⍝ Un-comment to play music while testing: ⍝ :If site filter≡'MS3' '' ⍝ ⎕CMD('"\Program Files (x86)\Windows Media Player\wmplayer.exe" "',AppRoot,'\Examples\Data\tellintro.mp3"')'' ⍝ :EndIf Selenium.InitBrowser'' Selenium.BROWSER.Manage.Window.Maximize ⍝ Localize non-alphanumeric key names for easy access keynames←⍕#.SeleniumTests.Selenium.Keys.⎕NL ¯2 ⍎keynames,'←∊#.SeleniumTests.Selenium.Keys.(',keynames,')' START←⎕AI[3] ⋄ COUNT←0 ⋄ FAIL←0 maxlen←¯2+⌈/⊃∘⍴¨files :For i :In ⍳n COUNT+←1 :If 0=⍴t←Run1Test{⍵⊣⍞←(⎕UCS 13),maxlen↑lopFirst ⍵}z←i⊃files ⍞←'*** PASSED ***' :Else FAIL+←1 r,←⊂z ⍞←'*** FAILED *** #',(⍕i),' of ',(⍕n),': ',z,': ',t :EndIf :EndFor ⎕←'Total of ',(⍕COUNT),' samples tested in ',(∊(⍕¨24 60⊤⌊0.5+(⎕AI[3]-START)÷1000),¨'ms'),': ',(⍕FAIL),' failed.' Selenium.BROWSER.Quit ∇ :EndNamespace
:Namespace SeleniumTests ∇ x←eis x ⍝ Enclose if simple :If (≡x)∊0 1 ⋄ x←,⊂,x ⋄ :EndIf ∇ ∇ r←lopFirst url ⍝ remove first segment of URL r←{⍵/⍨(1+'/'=1↑⍵)≤+\'/'=⍵}url ∇ ∇ r←Run1Test page;name;ref;Test ⍝ eg MS3Test '/QA/DC/InputGridSimple' Selenium.GoTo SITE,lopFirst page ⍝ Drop the "QA" :If 'Test'≡name←⎕SE.SALT.Load AppRoot,page :Trap stopOnError×9999 :If stopOnError∧0≠⍴r←Test ⍬ ⎕←'test for ',page,' failed:' ⋄ ⎕←r ⋄ ⎕←'Rerun:' ⋄ ' Test ⍬' ∘∘∘ :EndIf :Else r←'Trapped error: ',,⍕⎕DMX.EN :EndTrap :Else ⋄ r←AppRoot,page,' does not define a function called Test' :EndIf ∇ ∇ r←FindAllFiles root;folders;ext :If 0=⎕NC'Config.DefaultExtension' ⋄ ext←'.dyalog' :Else ⋄ ext←Config.DefaultExtension :EndIf root,←'/'/⍨~'/\'∊⍨¯1↑root ⍝ append trailing / if missing r←root∘,¨(('*',ext)#.Files.List root)[;1] :If 0≠⍴folders←{(('.'≠⊃¨⍵[;1])∧⍵[;4])/⍵[;1]}#.Files.List root r←r,⊃,/FindAllFiles¨root∘,¨folders :EndIf ∇ ∇ r←stopOnError_port Test site;count;ctl;examples;f;fail;nodot;start;t;time;z;i;START;COUNT;FAIL;Config;selpath;files;n;ext;filter;⎕PATH;keynames;maxlen;⎕USING;stopOnError stopOnError←⊃stopOnError_port r←'' (site filter)←2↑(eis site),'' '' :If 0=⍴AppRoot←#.Load site ⎕←'Test abandoned' ⋄ →0 :EndIf selpath←({∊'/',⍨¨¯1↓'/\'#.Utils.penclose ⍵}#.Boot.MSRoot),'Selenium/' :If 0=⎕NC'Selenium' :Trap 0 ⋄ ⎕SE.SALT.Load selpath,'/Selenium' :Else ⎕←'Selenium library not found at: ',selpath →0⍴⍨0∊⍴selpath←{⍞↓⍨⍴⍞←⍵,': '}'Selenium path' :Trap 0 ⋄ ⎕SE.SALT.Load selpath,'/Selenium' :Else ⋄ ⎕←'Unable to load Selenium' ⋄ →0 :EndTrap :EndTrap :EndIf ⎕PATH,←' Selenium' Selenium.DLLPATH←selpath Config←#.Boot.ConfigureServer AppRoot ext←Config.DefaultExtension Config.DefaultExtension←'.dyalog' ⍝ We are searching for code n←⍴files←(⍴AppRoot)↓¨¯7↓¨FindAllFiles AppRoot,'QA' ⍝ // Add code to compare this to the mipages found in the whole app :If 0≠⍴filter files←(filter ⎕S'%')files ⎕←'Selected: ',(⍕⍴files),' of ',(⍕n),' tests.' :EndIf n←⍴files SITE←'http://127.0.0.1:',⍕⊃1↓stopOnError_port,Config.Port ⍝⍝ Un-comment to play music while testing: ⍝ :If site filter≡'MS3' '' ⍝ ⎕CMD('"\Program Files (x86)\Windows Media Player\wmplayer.exe" "',AppRoot,'\Examples\Data\tellintro.mp3"')'' ⍝ :EndIf Selenium.InitBrowser'' Selenium.BROWSER.Manage.Window.Maximize ⍝ Localize non-alphanumeric key names for easy access keynames←⍕#.SeleniumTests.Selenium.Keys.⎕NL ¯2 ⍎keynames,'←∊#.SeleniumTests.Selenium.Keys.(',keynames,')' START←⎕AI[3] ⋄ COUNT←0 ⋄ FAIL←0 maxlen←¯2+⌈/⊃∘⍴¨files :For i :In ⍳n COUNT+←1 :If 0=⍴t←Run1Test{⍵⊣⍞←(⎕UCS 13),maxlen↑lopFirst ⍵}z←i⊃files ⍞←'*** PASSED ***' :Else FAIL+←1 r,←⊂z ⍞←'*** FAILED *** #',(⍕i),' of ',(⍕n),': ',z,': ',t :EndIf :EndFor ⎕←'Total of ',(⍕COUNT),' samples tested in ',(∊(⍕¨24 60⊤⌊0.5+(⎕AI[3]-START)÷1000),¨'ms'),': ',(⍕FAIL),' failed.' Selenium.BROWSER.Quit ∇ :EndNamespace
Test (Selenium) now allows specifying a port number after the Stop-On-Error Boolean (was always-8080).
Test (Selenium) now allows specifying a port number after the Stop-On-Error Boolean (was always-8080).
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
9502bca58493e8103e41498156690c859c717ff6
apl/iota999.apl
apl/iota999.apl
⍳ 9 9 9
⍝ Using the ⍳ (iota) function to generate a set of ordered numbers in a 3D array ⍳ 9 9 9
Update iota999.apl
Update iota999.apl
APL
mit
classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept,classmember/proof_of_concept
7b04dd8df888b490462e1c72d61e681105bfe074
HTML/_SF/ejdatepicker.dyalog
HTML/_SF/ejdatepicker.dyalog
:Class ejDatePicker : #._SF._ejWidget ⍝ Description:: Syncfusion DatePicker widget ⍝ Constructor:: [date [format]] ⍝ date - date in JavaScript format (see: http://www.w3schools.com/js/js_dates.asp) (default 3↑⎕TS) ⍝ format - (default 'yyyy/MM/dd') ⍝ Public Fields:: ⍝ Label - string of text to appear next to the input field ⍝ LabelPos - position of label relative to the date input field ('left' (default) or 'right') ⍝ Examples:: ⍝ ejDatePicker ⍝ ejDatePicker '27-Nov-1966' ⍝ ejDatePicker (2000 1 1)('dd-MMM-yyyy') :Field Public Shared ReadOnly DocBase←'http://help.syncfusion.com/js/api/ejDatePicker.html' :Field Public Shared ReadOnly ApiLevel←3 :Field Public Shared ReadOnly DocDyalog←'/Documentation/DyalogAPIs/Syncfusion/ejDatePicker.html' :Field Public Shared ReadOnly IntEvt←'beforeDateCreate' 'change' 'close' 'create' 'destroy' 'focusIn' 'focusOut' 'open' 'select' :field public Label←'' :field public LabelPos←'left' ⍝ valid are 'left' 'right' ∇ make0 :Access Public JQueryFn←Uses←'ejDatePicker' ContainerTag←'input' :Implements Constructor Container.type←'text' InternalEvents←IntEvt ∇ ∇ make args;val;fmt ⍝ Selector [value [dateFormat]] :Access Public JQueryFn←Uses←'ejDatePicker' ContainerTag←'input' :Implements Constructor args←(⊂⍣(3=10|⎕DR args))args (val fmt)←args defaultArgs(3↑⎕TS)'yyyy/MM/dd' ('value' 'dateFormat')Set(('⍎new Date("',(⍕val),'")')fmt) Container.type←'text' InternalEvents←IntEvt ∇ ∇ r←Render :Access public Container.NoEndTag←1 SetId r←⎕BASE.Render :If Label≢'' r←r((LabelPos≡'right'){⍺⍺:⍺,⍵ ⋄ ⍵,⍺})(⎕NEW #._html.label(Label('for'id))).Render :EndIf ∇ :EndClass
:Class ejDatePicker : #._SF._ejWidget ⍝ Description:: Syncfusion DatePicker widget ⍝ Constructor:: [date [format]] ⍝ date - date in JavaScript format (see: http://www.w3schools.com/js/js_dates.asp) (default 3↑⎕TS) ⍝ format - (default 'yyyy/MM/dd') ⍝ Public Fields:: ⍝ Label - string of text to appear next to the input field ⍝ LabelPos - position of label relative to the date input field ('left' (default) or 'right') ⍝ Examples:: ⍝ ejDatePicker ⍝ ejDatePicker '27-Nov-1966' ⍝ ejDatePicker (2000 1 1)('dd-MMM-yyyy') :Field Public Shared ReadOnly DocBase←'http://help.syncfusion.com/js/api/ejDatePicker.html' :Field Public Shared ReadOnly ApiLevel←3 :Field Public Shared ReadOnly DocDyalog←'/Documentation/DyalogAPIs/Syncfusion/ejDatePicker.html' :Field Public Shared ReadOnly IntEvt←'beforeDateCreate' 'change' 'close' 'create' 'destroy' 'focusIn' 'focusOut' 'open' 'select' :field public Label←'' :field public LabelPos←'left' ⍝ valid are 'left' 'right' ∇ make0 :Access Public JQueryFn←Uses←'ejDatePicker' ContainerTag←'input' :Implements Constructor Container.type←'text' InternalEvents←IntEvt ∇ ∇ make args;val;fmt ⍝ Selector [value [dateFormat]] :Access Public JQueryFn←Uses←'ejDatePicker' ContainerTag←'input' :Implements Constructor args←(⊂⍣(3=10|⎕DR args))args (val fmt)←args defaultArgs(3↑⎕TS)'yyyy/MM/dd' ('value' 'dateFormat')Set(('⍎new Date("',(⍕val),'")')fmt) Container.type←'text' InternalEvents←IntEvt ∇ ∇ r←Render :Access public Container.NoEndTag←1 SetId r←⎕BASE.Render :If Label≢'' r←r((LabelPos≡'right'){⍺⍺:⍺,⍵ ⋄ ⍵,⍺})(⎕NEW #._html.label(Label('for=',id))).Render :EndIf ∇ :EndClass
Fix label creation syntax for ejDatePicker
Fix label creation syntax for ejDatePicker
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
1d349d4f6e80357667b60d55e3669aa2c2b7da57
Utils/dates.dyalog
Utils/dates.dyalog
:Namespace Dates (⎕ML ⎕IO)←1 ∇ r←CookieFmt date;day;date;mon ⍝ Format date for cookie expiry ⍝ "expires Mon, 09-Dec-2002 13:46:00 GMT" day←(7 3⍴'MonTueWedThuFriSatSun')[WeekDay date;] mon←(12 3⍴'janfebmaraprmayjunjulaugsepoctnovdec')[2⊃date;] r←,('<',day,', >,ZI2,<-',mon,'->,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴(6↑date)[3 1 4 5 6] ∇ ∇ SetUtcOffset;ver;⎕USING :If 0=⎕NC'_UtcOffset' :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' :Hold '_UtcOffset' ⎕USING←,⊂'' _UtcOffset←¯60×(System.TimeZone.CurrentTimeZone.GetUtcOffset ⎕NEW System.DateTime(⎕TS)).Hours :EndHold :Else :If (⊂ver)∊'Lin' 'AIX' 'Sol' 'Mac' _UtcOffset←¯60×.01×⍎⊃⎕SH'date +%z' :Else _UtcOffset←0 ⍝ otherwise, assume GMT :EndIf :EndIf :EndIf ∇ ∇ r←{minOffset}HTTPDate ts;sign;day;mon;ver;⎕USING;t ⍝ return RCF 1123/822 compliant date ⍝ minOffset is option number of minutes to offset time with (used for HTTP caching expirations) minOffset←{0::0 ⋄ minOffset}'' ts←6↑ts SetUtcOffset ts←IDNToDate((_UtcOffset+minOffset)÷24×60)+t←DateToIDN ts day←(7 3⍴'MonTueWedThuFriSatSun')[1+7|(⌊t)-1;] mon←(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[2⊃ts;] r←,('<',day,', >,ZI2,< ',mon,' >,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴ts[3 1 4 5 6] ∇ ∇ SM←DateToIDN TS ⍝ Convert date format SM←2 ⎕NQ'.' 'DateToIDN'(3↑TS) :If 3<⍴TS SM+←(24 60 60 1000⊥4↑3↓TS)÷86400000 :EndIf ∇ ∇ TS←IDNToDate SM ⍝ Convert IDN to date format : 3↑⎕TS ← IDN (akd TS_SM) TS←3↑2 ⎕NQ'.' 'IDNToDate'(⌊SM) TS,←⌊0.5+24 60 60 1000⊤86400000×1|SM ∇ ∇ new←ts IdnAdd t ⍝ T is D HH MM SS new←ts+(0 24 60 60 1000⊥¯5↑t,0)÷86400000 ∇ ∇ r←Now r←DateToIDN ⎕TS ∇ ∇ r←TSFmt ts r←,'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2,<:>,ZI2'⎕FMT 1 6⍴6↑ts ∇ ∇ r←TSFmtNice ts;now;yday;today;z;i;m;idn;s ⍝ Format a vector of IDN's nicely s←⍴ts yday←¯1+today←⌊now←DateToIDN ⎕TS r←↑IDNToDate¨,ts←,ts ⍝ Make matrix r←'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 5↑[2]r :If 0≠⍴i←((ts≥yday)∧~m←ts≥today)/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Yesterday' :EndIf :If 0≠⍴i←m/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Today' :EndIf :If 0≠⍴i←(100>z←⌊(now-ts)×24×60)/⍳⍴ts r[i;]←16↑[2]↑(⍕¨⌊z[i]),¨(' minutes ago' ' minute ago')[1+1=z[i]] :EndIf :If 0≠⍴i←(z<1)/⍳⍴ts r[i;]←((⍴i),16)⍴16↑'Now' :EndIf r←(s,¯1↑⍴r)⍴r ∇ ∇ r←WeekDay Date ⍝ Return weekday (Monday=1, Sunday=7) r←1+7|(DateToIDN 3↑Date)-1 ∇ ∇ r←{opt}DateFormat ymd ⍝ opt - 0 dd MMM yyyy ⍝ 1 dd Month yyyy :If 0=⎕NC'opt' ⋄ opt←0 ⋄ :EndIf :Select ⊃opt :Case 0 r←(⍕ymd[3]),(1⌽' ',3↑(3ׯ1+ymd[2])↓'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'),⍕ymd[1] :Case 1 r←(⍕ymd[3]),(1⌽' ',ymd[2]⊃'January' 'February' 'March' 'April' 'May' 'June' 'July' 'August' 'September' 'October' 'November' 'December'),⍕ymd[1] :Else r←⍕ymd :EndSelect ∇ ∇ r←LogFmtNow;ver ⍝ returns now UTC adjusted, and formatted for log files (Common Log Format) :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' r←((⍎⎕NA'kernel32|GetSystemTime >{U2 U2 U2 U2 U2 U2 U2 U2}')⊂8⍴0)[4 2 1 5 6 7] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r :Else r←1⊃⎕SH'date +" [%d/%b/%Y:%T %z] "' :EndIf ∇ ∇ r←LogFmt ymdhms r←ymdhms[3 2 1 4 5 6] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r ∇ ∇ ts←FTT fts;md;shape;tmp;yr;z;⎕IO ⍝ *** convert ⎕FRDCI/⎕FHIST timestamp(s) to ⎕ts-format for Dyalog/W *** ⍝ right argument: ⎕FRDCI-type timestamp(s) of any shape ⍝ result: ⎕ts-type timestamp(s) with shape <(⍴argument),7> ⎕IO←0 ⋄ shape←⍴fts ⋄ ts←,fts+18626112000 md←365.2501|1+1461|yr←⌊ts÷5184000 tmp←31 61 92 122 153 184 214 245 275 306 337 366 z←(,⍉<⍀tmp∘.≥md)/,((⍴md),12)⍴⍳12 md←(1+12|z+2),[0.1]⌈md-(0,tmp)[z] ts←(1960+⌊(yr+60)÷365.25),md,⍉24 60 60 60⊤ts ts[;6]←⌊0.5+ts[;6]×100÷6 ts←(shape,7)⍴ts ∇ ∇ r←TTF ts;l;h;d;m;y ⍝ convert a ⎕TS style timestamp into 60ths of a second since 1st January 1970 a la ⎕FRDCI l←⌈60×ts[7]÷1000 ⍝ convert milliseconds to 60ths h←3600 60 60⊥ts[4 5 6] ⍝ hours minutes seconds to to the nearest seconds total d←ts[3]-1 ⍝ days since start of month m←(2⊃ts)⊃++\0 31,(28+0=4|⊃ts),31 30 31 30 31 31 30 31 30 ⍝ days in completed months y←{{(365×⍵)+⌈4÷⍨⍵-2}⍵-1970}⊃ts ⍝ days in years since 1970, leap years since 1972 r←l+60×h+86400×y+m+d ⍝ sum, convert to seconds, add seconds in the day convert to 60ths, add on 60ths ∇ tonum←{(b v)←⎕vfi ⍵ ⋄ b/v} ∇ dt←ParseDate str;pos;mon;t;ymd ⍝ str is of the genre "Wed Aug 05 2015 07:30:21 GMT-0400 (Eastern Daylight Time)" ⍝ We need to weed out the day of the week and the time str←(+/∧\' '=str)↓str ⍝ remove the leading spaces ⍝ What kind of string is this? :If ~∧/1⊃(dt dt)←{b←~⍵∊'/-:' ⋄ ⎕VFI b\b/⍵}str ⍝ yyyy/mm/dd hh:mm:ss ? :If 0∊⍴t←'Jan' 'Feb' 'Mar' 'Apr' 'May' 'Jun' 'Jul' 'Aug' 'Sep' 'Oct' 'Nov' 'Dec'⎕S 0 3⊢str ⍝ look for the month as a string. If not found ymd←3↑tonum str ⍝ grab the 1st 3 numbers found ymd←ymd[⍒(2×31<ymd)+ymd<12] ⍝ put in correct order :Else ⍝ otherwise (if found) (pos mon)←0 1+1⊃t :If ~0∊⍴t←tonum pos↑str ⍝ any number before the month? (e.g. 2 May 2021) ymd←⌽⍣(31<⍬⍴t)⊢(1↑tonum pos↓str),mon,t :Else ymd←¯1⌽mon,2↑tonum pos↓str :EndIf :EndIf ⍝ Now grab the time dt←ymd,tonum⍕'(\d+):(\d+):(\d+)'⎕S'\1 \2 \3'⊢str :EndIf ∇ ∇ ts←ParseISODate str SetUtcOffset ts←IDNToDate(-_UtcOffset÷24×60)+DateToIDN 7↑str{⊃(//)⎕VFI ⍵\⍵/⍺}str∊⎕D ∇ ∇ r←{unit}ParseTime string;chunks;units;factors ⍝ Parse time string into units (default is ms) ⍝ String is a string like '5d4h47m6s266ms' :If 0=⎕NC'unit' ⋄ unit←'ms' ⋄ :EndIf units←(1 1 1 1 1 0⊂'dhmsms'),⊂'' factors←86400000 3600000 60000 1000 1 1 chunks←{⎕ML←3 ⋄ (1+⍵∊⎕D)⊂⍵}string :Trap 0/0 r←(⍎¨{⍵∩⎕D}¨chunks)+.×factors[units⍳{#.Strings.lc ⍵~⎕D}¨chunks] :Else 'Invalid time string'⎕SIGNAL 11 :EndTrap r←r÷factors[units⍳⊂,unit] ∇ :EndNamespace
:Namespace Dates (⎕ML ⎕IO)←1 ∇ r←CookieFmt date;day;date;mon ⍝ Format date for cookie expiry ⍝ "expires Mon, 09-Dec-2002 13:46:00 GMT" day←(7 3⍴'MonTueWedThuFriSatSun')[WeekDay date;] mon←(12 3⍴'janfebmaraprmayjunjulaugsepoctnovdec')[2⊃date;] r←,('<',day,', >,ZI2,<-',mon,'->,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴(6↑date)[3 1 4 5 6] ∇ ∇ SetUtcOffset;ver;⎕USING :If 0=⎕NC'_UtcOffset' :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' :Hold '_UtcOffset' ⎕USING←,⊂'' _UtcOffset←¯60×(System.TimeZone.CurrentTimeZone.GetUtcOffset ⎕NEW System.DateTime(⎕TS)).Hours :EndHold :Else :If (⊂ver)∊'Lin' 'AIX' 'Sol' 'Mac' _UtcOffset←¯60×.01×⍎⊃⎕SH'date +%z' :Else _UtcOffset←0 ⍝ otherwise, assume GMT :EndIf :EndIf :EndIf ∇ ∇ r←{minOffset}HTTPDate ts;sign;day;mon;ver;⎕USING;t ⍝ return RCF 1123/822 compliant date ⍝ minOffset is option number of minutes to offset time with (used for HTTP caching expirations) minOffset←{0::0 ⋄ minOffset}'' ts←6↑ts SetUtcOffset ts←IDNToDate((_UtcOffset+minOffset)÷24×60)+t←DateToIDN ts day←(7 3⍴'MonTueWedThuFriSatSun')[1+7|(⌊t)-1;] mon←(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[2⊃ts;] r←,('<',day,', >,ZI2,< ',mon,' >,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴ts[3 1 4 5 6] ∇ ∇ SM←DateToIDN TS ⍝ Convert date format SM←2 ⎕NQ'.' 'DateToIDN'(3↑TS) :If 3<⍴TS SM+←(24 60 60 1000⊥4↑3↓TS)÷86400000 :EndIf ∇ ∇ TS←IDNToDate SM ⍝ Convert IDN to date format : 3↑⎕TS ← IDN (akd TS_SM) TS←3↑2 ⎕NQ'.' 'IDNToDate'(⌊SM) TS,←⌊0.5+24 60 60 1000⊤86400000×1|SM ∇ ∇ new←ts IdnAdd t ⍝ T is D HH MM SS new←ts+(0 24 60 60 1000⊥¯5↑t,0)÷86400000 ∇ ∇ r←Now r←DateToIDN ⎕TS ∇ ∇ r←TSFmt ts r←,'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2,<:>,ZI2'⎕FMT 1 6⍴6↑ts ∇ ∇ r←TSFmtNice ts;now;yday;today;z;i;m;idn;s ⍝ Format a vector of IDN's nicely s←⍴ts yday←¯1+today←⌊now←DateToIDN ⎕TS r←↑IDNToDate¨,ts←,ts ⍝ Make matrix r←'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 5↑[2]r :If 0≠⍴i←((ts≥yday)∧~m←ts≥today)/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Yesterday' :EndIf :If 0≠⍴i←m/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Today' :EndIf :If 0≠⍴i←(100>z←⌊(now-ts)×24×60)/⍳⍴ts r[i;]←16↑[2]↑(⍕¨⌊z[i]),¨(' minutes ago' ' minute ago')[1+1=z[i]] :EndIf :If 0≠⍴i←(z<1)/⍳⍴ts r[i;]←((⍴i),16)⍴16↑'Now' :EndIf r←(s,¯1↑⍴r)⍴r ∇ ∇ r←WeekDay Date ⍝ Return weekday (Monday=1, Sunday=7) r←1+7|(DateToIDN 3↑Date)-1 ∇ ∇ r←{opt}DateFormat ymd ⍝ opt - 0 dd MMM yyyy ⍝ 1 dd Month yyyy :If 0=⎕NC'opt' ⋄ opt←0 ⋄ :EndIf :Select ⊃opt :Case 0 r←(⍕ymd[3]),(1⌽' ',3↑(3ׯ1+ymd[2])↓'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'),⍕ymd[1] :Case 1 r←(⍕ymd[3]),(1⌽' ',ymd[2]⊃'January' 'February' 'March' 'April' 'May' 'June' 'July' 'August' 'September' 'October' 'November' 'December'),⍕ymd[1] :Else r←⍕ymd :EndSelect ∇ ∇ r←LogFmtNow;ver ⍝ returns now UTC adjusted, and formatted for log files (Common Log Format) :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' r←((⍎⎕NA'kernel32|GetSystemTime >{U2 U2 U2 U2 U2 U2 U2 U2}')⊂8⍴0)[4 2 1 5 6 7] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r :Else r←1⊃⎕SH'date +" [%d/%b/%Y:%T %z] "' :EndIf ∇ ∇ r←LogFmt ymdhms r←ymdhms[3 2 1 4 5 6] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r ∇ ∇ ts←FTT fts;md;shape;tmp;yr;z;⎕IO ⍝ *** convert ⎕FRDCI/⎕FHIST timestamp(s) to ⎕ts-format for Dyalog/W *** ⍝ right argument: ⎕FRDCI-type timestamp(s) of any shape ⍝ result: ⎕ts-type timestamp(s) with shape <(⍴argument),7> ⎕IO←0 ⋄ shape←⍴fts ⋄ ts←,fts+18626112000 md←365.2501|1+1461|yr←⌊ts÷5184000 tmp←31 61 92 122 153 184 214 245 275 306 337 366 z←(,⍉<⍀tmp∘.≥md)/,((⍴md),12)⍴⍳12 md←(1+12|z+2),[0.1]⌈md-(0,tmp)[z] ts←(1960+⌊(yr+60)÷365.25),md,⍉24 60 60 60⊤ts ts[;6]←⌊0.5+ts[;6]×100÷6 ts←(shape,7)⍴ts ∇ ∇ r←TTF ts;l;h;d;m;y ⍝ convert a ⎕TS style timestamp into 60ths of a second since 1st January 1970 a la ⎕FRDCI l←⌈60×ts[7]÷1000 ⍝ convert milliseconds to 60ths h←3600 60 60⊥ts[4 5 6] ⍝ hours minutes seconds to to the nearest seconds total d←ts[3]-1 ⍝ days since start of month m←(2⊃ts)⊃++\0 31,(28+0=4|⊃ts),31 30 31 30 31 31 30 31 30 ⍝ days in completed months y←{{(365×⍵)+⌈4÷⍨⍵-2}⍵-1970}⊃ts ⍝ days in years since 1970, leap years since 1972 r←l+60×h+86400×y+m+d ⍝ sum, convert to seconds, add seconds in the day convert to 60ths, add on 60ths ∇ tonum←{(b v)←⎕vfi ⍵ ⋄ b/v} ∇ dt←ParseDate str;pos;mon;t;ymd ⍝ str is of the genre "Wed Aug 05 2015 07:30:21 GMT-0400 (Eastern Daylight Time)" ⍝ We need to weed out the day of the week and the time str←(+/∧\' '=str)↓str ⍝ remove the leading spaces ⍝ What kind of string is this? :If ~∧/1⊃(dt dt)←{b←~⍵∊'/-:' ⋄ ⎕VFI b\b/⍵}str ⍝ yyyy/mm/dd hh:mm:ss ? :If 0∊⍴t←'Jan' 'Feb' 'Mar' 'Apr' 'May' 'Jun' 'Jul' 'Aug' 'Sep' 'Oct' 'Nov' 'Dec'⎕S 0 3⊢str ⍝ look for the month as a string. If not found ymd←3↑tonum str ⍝ grab the 1st 3 numbers found ymd←ymd[⍒(2×31<ymd)+ymd<12] ⍝ put in correct order :Else ⍝ otherwise (if found) (pos mon)←0 1+1⊃t :If ~0∊⍴t←tonum pos↑str ⍝ any number before the month? (e.g. 2 May 2021) ymd←⌽⍣(31<⍬⍴t)⊢(1↑tonum pos↓str),mon,t :Else ymd←¯1⌽mon,2↑tonum pos↓str :EndIf :EndIf ⍝ Now grab the time dt←ymd,tonum⍕'(\d+):(\d+):(\d+)'⎕S'\1 \2 \3'⊢str :EndIf ∇ ∇ ts←ParseISODate str SetUtcOffset ts←IDNToDate(-_UtcOffset÷24×60)+DateToIDN 7↑str{⊃(//)⎕VFI ⍵\⍵/⍺}str∊⎕D ∇ ∇ r←{unit}ParseTime string;chunks;units;factors ⍝ Parse time string into units (default is ms) ⍝ String is a string like '5d4h47m6s266ms' :If 0=⎕NC'unit' ⋄ unit←'ms' ⋄ :EndIf units←(1 1 1 1 1 0⊂'dhmsms'),⊂'' factors←86400000 3600000 60000 1000 1 1 chunks←{⍵⊆⍨1+⍵∊⎕D},string :Trap 0/0 r←(⍎¨{⍵∩⎕D}¨chunks)+.×factors[units⍳{#.Strings.lc ⍵~⎕D}¨chunks] :Else 'Invalid time string'⎕SIGNAL 11 :EndTrap r←r÷factors[units⍳⊂,unit] ∇ :EndNamespace
Make Dates.ParseTime work with scalar argument
Make Dates.ParseTime work with scalar argument
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
91bc376e581632a860dfbebcd4f1bd36ee0cd859
Run.dyalog
Run.dyalog
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊⊃⌽regexes ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊⊃⌽regexes ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX('to←{',(r/',⍕'),'{')(Expand⊃⌽regexes)'}⍵}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←{⊃,/⍵↑¨⍨⌈/≢¨⍵}⍣(∨/args∊⍨'≡',⎕D)⊢output ⍝ merge search results if we need to continue :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r;last;fns;Quote;q;hasrepeat;postproc;combine :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 hasrepeat←∨/args∊⍨'≡',⎕D ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S fns←+/∧\'⍵'∊¨regexes postproc←∊'{⍵}','∘{'∘,¨,∘'}'¨fns↑regexes ⍝ post-processing functions regexes↓⍨←fns last←⊃⌽regexes :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊last ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊last ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX'to←{'(r/',⍕{')(Expand last)(r/'}⍵')'}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf combine←'{⊃,/⍵↑¨⍨⌈/≢¨⍵}' q←⎕NS ⍬ :If s r∨.∧'?'∊args Quote←{q,q,⍨⍵/⍨1+⍵=q←''''} q.from←⍕Quote¨from :If 3=⎕NC'to' q.to←1⌽' ',3↓∊⎕NR'to' :Else q.to←⍕Quote¨to :EndIf :If 3=⎕NC'repeat' q.repeat←'⍣',∊⎕NR'repeat' :ElseIf 1≢repeat q.repeat←'⍣',⍕repeat :Else q.repeat←'' :EndIf q.op←s r/'SR' q.postproc←4↓postproc q.postproc,←(hasrepeat∧s)/(''≡q.postproc)↓'∘',combine output←q.(postproc,from,'⎕',op,to,repeat) :Else :Trap 6 11 :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←(⍎combine)⍣hasrepeat⊢output ⍝ merge search results if we need to continue :EndIf output←(⍎postproc)output :Case 6 ⍝ no output output←'*** Left operand must be ''R'' or ''S'' ***' :Case 11 ⍝ faulty regex output←'*** ',⎕DMX.Message,' ─ try adding ? to the Arguments to see the attempted APL expression ***' :EndTrap :EndIf
Allow postproc functions. Accept ? to display APL expression. Proper error messages.
Allow postproc functions. Accept ? to display APL expression. Proper error messages.
APL
mit
abrudz/QuadRS
9cc2e2dbac8a21d22dab9a799b5e66a87ba8c478
Run.dyalog
Run.dyalog
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘'sabcA')¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊⊃⌽regexes ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊⊃⌽regexes ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX('to←{',(r/',⍕'),'{')(Expand⊃⌽regexes)'}⍵}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←{⊃,/⍵↑¨⍨⌈/≢¨⍵}⍣(∨/args∊⍨'≡',⎕D)⊢output ⍝ merge search results if we need to continue :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
 output←regexes(op Run args)input;from;to;options;lines;trans;Expand;repeat;s;r :Trap 11 22 ⍝ accept filename or actual input input←input ⎕NTIE 0 :EndTrap :Trap 11 22 ⍝ accept filename or actual regex regexes←⊃⎕NGET regexes 1 :EndTrap repeat←⍎{×≢⍵:⍵ ⋄ '1'}args∩'≡',⎕D ⍝ extract repetition, if any, else 1 ⍝ select options: options←('ResultText' 'Simple')('Greedy' 0)('IC' 1)('Mode' 'D')('Mode' 'M')('DotAll' '1')('UCP' 1)('OM' 1)/⍨1,'gidmauo'∊819⌶args~' -' s r←(∨/∊∘op)¨'Ss' 'Rr' options↓⍨←s ⍝ ResultText is not for ⎕S :If 2|≢regexes ⍝ odd number of strings → many-to-one :OrIf '⍵'∊⊃⌽regexes ⍝ transformation function → many-to-function from←¯1↓regexes ⍝ remove transformation pattern/function :If ~'⍵'∊⊃⌽regexes ⍝ no ⍵ → pattern Expand←'⍵B' '⍵b' '⍵P' '⍵p' '⍵M' '⍵O' '⍵L' '⍵N'⎕R'⍵.Block' '⍵.BlockNum' '⍵.Pattern' '⍵.PatternNum' '⍵.Match' '⍵.Offsets' '⍵.Lengths' '⍵.Names' :OrIf ~≡⎕FX('to←{',(r/',⍕'),'{')(Expand⊃⌽regexes)'}⍵}' ⍝ if definition fails, revert to pattern (allows ⍵ in pattern) to←⊃⌽regexes :EndIf :Else lines←2÷⍨≢regexes from←lines↑regexes to←lines↓regexes :EndIf :If r output←from ⎕R to⍠options⍣repeat⊢input :ElseIf s output←from ⎕S to⍠options⍣repeat⊢input output←{⊃,/⍵↑¨⍨⌈/≢¨⍵}⍣(∨/args∊⍨'≡',⎕D)⊢output ⍝ merge search results if we need to continue :Else 'Left operand must be ''R'' or ''S'''⎕SIGNAL 11 :EndIf
Replace dummy string with actual variable name
Replace dummy string with actual variable name
APL
mit
abrudz/QuadRS
58740171f4b5f40819b69972297295e7cf9330d4
MS3/Documentation/DyalogAPIs/WidgetDoc.dyalog
MS3/Documentation/DyalogAPIs/WidgetDoc.dyalog
:Class WidgetDoc : MiPageTemplate ∇ Compose;ns;widget;doc :Access public (ns widget)←Get'namespace widget' Add _.StyleSheet'/Styles/widgetDoc.css' doc←ns Document widget :Select doc :Case ¯1 (Add _.h3('Namespace "',ns,'" not found.')).Style'color' 'red' :Case ¯2 (Add _.h3('Widget "',widget,'" not found in namespace ',ns)).Style'color' 'red' :Else Add _.h3 ns,'.',widget :If 0∊⍴doc Add _.h4'No documentation found.' :Else doc[;2]←{New _.pre ⍵}¨doc[;2] (Add #._.Table doc).CellAttr←'class="widgetDoc"' 'class="widgetDocContent"' :EndIf :EndSelect ∇ ∇ r←ns Document widget;ref;wref;src;mask;chunk;pv;c;c1;c2;samples;files :Access public shared r←¯1 :If 9.1=#.⎕NC⊂ns ref←#.⍎ns r←¯2 :If 9=ref.⎕NC widget wref←ref⍎widget src←1↓⎕SRC wref src↓⍨←+/∧\''∘≡¨src src←#.Strings.dlb¨src src←src/⍨∧\'⍝'=⊃¨src src←HtmlSafeText¨#.Strings.dlb¨1↓¨src pv←∨/¨'::'∘⍷¨src r←0 2⍴⊂'' :For chunk :In pv⊂src c←⊃chunk (c1 c2)←{⍵{(1,1↓<\⍵)⊂⍺}'::'⍷⍵}c c2←#.Strings.deb 2↓c2 c2←c2{0∊⍴⍺:⍵ ⋄ 0∊⍴⍵:⊂⍺ ⋄ (⊂⍺),⍵}1↓chunk c2←¯2↓∊c2,¨⊂⎕UCS 13 10 r⍪←c1 c2 :EndFor :If 0≠wref.⎕NC⊂'DocBase' r⍪←'Documentation'('target=_blank'New _.A(2⍴⊂wref.DocBase)) :EndIf samples←'/Examples/',(ns~'_'),'/' :If ~0∊⍴files←1⌷[2]#.Files.List #.Boot.ms.Config.AppRoot,samples files/⍨←∨/files∘.#.Strings.(beginsWith nocase)widget∘,¨'Simp' 'Adv' :AndIf ~0∊⍴files r⍪←'Sample Pages'({'target=_blank'New _.A(2⍴⊂⍵)}¨samples∘,¨files) :EndIf :EndIf :EndIf ∇ :EndClass
:Class WidgetDoc : MiPageTemplate ∇ Compose;ns;widget;doc;t;opts;og :Access public Add _.StyleSheet'/Styles/widgetDoc.css' (ns widget)←Get'namespace widget' :If 0∊⍴widget Add _.h3'Select widget' opts←'onchange="window.open(this.value,''this'');this.selectedIndex=0"'Add _.select 'disabled=' 'value='opts.Add _.option'[Select widget]' :For ns :In '_DC' '_SF' '_JQ' '_html' og←('label'ns)opts.Add _.optgroup :For widget :In (⍎ns).⎕NL ¯9 ('value=?namespace=',ns,'&widget=',widget)og.Add _.option widget :EndFor :EndFor :Else doc←ns Document widget doc[;2]←{New _.pre ⍵}¨doc[;2] Add _.h3 ns,'.',widget (Add #._.Table doc).CellAttr←'class="widgetDoc"' 'class="widgetDocContent"' :EndIf ∇ ∇ r←ns Document widget;ref;wref;src;mask;chunk;pv;c;c1;c2;samples;files :Access public shared r←'' :If 9.1=#.⎕NC⊂ns ref←#.⍎ns :If 9=ref.⎕NC widget wref←ref⍎widget src←1↓⎕SRC wref src↓⍨←+/∧\''∘≡¨src src←#.Strings.dlb¨src src←src/⍨∧\'⍝'=⊃¨src src←HtmlSafeText¨#.Strings.dlb¨1↓¨src pv←∨/¨'::'∘⍷¨src r←0 2⍴⊂'' :For chunk :In pv⊂src c←⊃chunk (c1 c2)←{⍵{(1,1↓<\⍵)⊂⍺}'::'⍷⍵}c c2←#.Strings.deb 2↓c2 c2←c2{0∊⍴⍺:⍵ ⋄ 0∊⍴⍵:⊂⍺ ⋄ (⊂⍺),⍵}1↓chunk c2←¯2↓∊c2,¨⊂⎕UCS 13 10 r⍪←c1 c2 :EndFor :If 0≠wref.⎕NC⊂'DocBase' r⍪←'Documentation'('target=_blank'New _.A(2⍴⊂wref.DocBase)) :EndIf samples←'/Examples/',(ns~'_'),'/' :If ~0∊⍴files←1⌷[2]#.Files.List #.Boot.ms.Config.AppRoot,samples :AndIf ~0∊⍴files/⍨←∨/files∘.#.Strings.(beginsWith nocase)widget∘,¨'Simp' 'Adv' r⍪←'Sample Pages'({'target=_blank'New _.A(2⍴⊂⍵)}¨samples∘,¨files) :EndIf :EndIf :EndIf ∇ :EndClass
Resolve conflict
Resolve conflict
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
a887047208b3c7cbdc9ae9d0502fb19b234d88aa
Extensions/Logger.dyalog
Extensions/Logger.dyalog
:Class Logger ⍝ Logs HTTP requests ⎕ML←1 :field public instance Active←0 :field private instance Directory←'' :field private instance Interval←10 ⍝ write cache interval in seconds :field private instance TieNo←⍬ :field private instance Cache←'' :field private instance Prefix←'' :field private instance tid←¯1 :field private EOL ⍝ End Of Line missing←{0∊⍴⍵:'-' ⋄ ⍵} ∇ Make ms;file;log :Access public :Implements Constructor ⍝ load logger information Active←0 EOL←⎕UCS 13 10↓⍨~#.Boot.isWin :If #.Files.Exists file←ms.Config.Root,'Config/Logger.xml' :AndIf ~0∊⍴log←(#.XML.ToNS #.Files.ReadText file).Logger Active←log #.Boot.Setting'active' 1 0 Prefix←log #.Boot.Setting'prefix' 0 '' Interval←log #.Boot.Setting'interval' 1 10 Directory←#.Boot.SubstPath log #.Boot.Setting'directory' 0 '' Directory,←(~'/\'∊⍨¯1↑Directory)/'/' ('Log file directory "',Directory,'" not found!')⎕SIGNAL 11/⍨~#.Files.DirExists Directory :EndIf :If Active tid←Run&0 :EndIf ∇ ∇ UnMake :Implements destructor Stop ⍬ ∇ ∇ Stop w :Access public :Trap 0 :If Active Active←0 ⎕TKILL tid :If Open ClearCache Close :EndIf :EndIf :EndTrap ∇ ∇ Start :Access public :If ~tid∊⎕TNUMS Active←1 tid←Run&0 :EndIf ∇ ∇ Run x;done :While Active {}⎕DL Interval :If Open ClearCache Close :EndIf :EndWhile ∇ ∇ r←Open;fn r←0 :Trap 6 fn←#.Files.Normalize Directory,Prefix,(⍕100⊥3↑⎕TS),'.log' :Else →0 :EndTrap :Trap 22 ⍝ file name error TieNo←fn ⎕NTIE 0 34 :Else :Trap 0 ⎕NUNTIE fn ⎕NCREATE 0 TieNo←fn ⎕NTIE 0 34 :Else 1 ##.ms.Log'Unable to open log file "',fn,'"' :Return :EndTrap :EndTrap r←0≠TieNo ∇ ∇ Log req :Access public :If Active :Hold 'Lumberjack' Cache,←((missing 2⊃req.PeerAddr),' ',(missing req.Session.User),#.Dates.LogFmtNow,'"',req.Method,' ',req.Page,'"',∊' '∘,∘⍕¨req.Response.(Status MSec Bytes)),EOL :EndHold :EndIf ∇ ∇ ClearCache :Hold 'Lumberjack' Cache ⎕NAPPEND TieNo Cache←'' :EndHold ∇ ∇ Close ⎕NUNTIE TieNo ∇ :EndClass
:Class Logger ⍝ Logs HTTP requests ⎕ML←1 :field public instance Active←0 :field private instance Directory←'' :field private instance Interval←10 ⍝ write cache interval in seconds :field private instance TieNo←⍬ :field private instance Cache←'' :field private instance Prefix←'' :field private instance tid←¯1 :field private EOL ⍝ End Of Line missing←{0∊⍴⍵:'-' ⋄ ⍵} ∇ Make ms;file;log :Access public :Implements Constructor ⍝ load logger information Active←0 EOL←⎕UCS 13 10↓⍨~#.Boot.isWin :If #.Files.Exists file←ms.Config.Root,'Config/Logger.xml' :AndIf ~0∊⍴log←(#.XML.ToNS #.Files.ReadText file).Logger Active←log #.Boot.Setting'active' 1 0 Prefix←log #.Boot.Setting'prefix' 0 '' Interval←log #.Boot.Setting'interval' 1 10 Directory←#.Boot.SubstPath log #.Boot.Setting'directory' 0 '' Directory,←(~'/\'∊⍨¯1↑Directory)/'/' ('Log file directory "',Directory,'" not found!')⎕SIGNAL 11/⍨~#.Files.DirExists Directory :EndIf :If Active tid←Run&0 :EndIf ∇ ∇ UnMake :Implements destructor Stop ⍬ ∇ ∇ Stop w :Access public :Trap 0 :If Active Active←0 ⎕TKILL tid :If Open ClearCache Close :EndIf :EndIf :EndTrap ∇ ∇ Start :Access public :If ~tid∊⎕TNUMS Active←1 tid←Run&0 :EndIf ∇ ∇ Run x;done :While Active {}⎕DL Interval :If Open ClearCache Close :EndIf :EndWhile ∇ ∇ r←Open;fn r←0 :Trap 6 fn←#.Files.Normalize Directory,Prefix,(⍕100⊥3↑⎕TS),'.log' :Else →0 :EndTrap :Trap 22 ⍝ file name error TieNo←fn ⎕NTIE 0 34 :Else :Trap 0 ⎕NUNTIE fn ⎕NCREATE 0 TieNo←fn ⎕NTIE 0 34 :Else 1 ##.ms.Log'Unable to open log file "',fn,'"' :Return :EndTrap :EndTrap r←0≠TieNo ∇ tryGetting←{0::('-'@(' '∘=))(⊃⎕DM),'-retrieving-"',⍵,'"' ⋄ ⍕⍎⍵} ∇ Log req;addr;user;ts;method;page;status;msec;bytes :Access public :If Active :Hold 'Lumberjack' :Trap 0 Cache,←((missing 2⊃req.PeerAddr),' ',(missing req.Session.User),#.Dates.LogFmtNow,'"',req.Method,' ',req.Page,'"',∊' '∘,∘⍕¨req.Response.(Status MSec Bytes)),EOL :Else ⍝ something in logging failed, try figuring out what addr←tryGetting'req.PeerAddr' user←tryGetting'req.Session.User' ts←tryGetting'#.Dates.LogFmtNow' method←tryGetting'req.Method' page←tryGetting'req.Page' status←tryGetting'req.Response.Status' msec←tryGetting'req.Response.MSec' bytes←tryGetting'req.Response.Bytes' Cache,←(missing addr),' ',(missing user),ts,'"',method,' ',page,'" ',status,' ',msec,' ',bytes,EOL :EndTrap :EndHold :EndIf ∇ ∇ ClearCache :Hold 'Lumberjack' Cache ⎕NAPPEND TieNo Cache←'' :EndHold ∇ ∇ Close ⎕NUNTIE TieNo ∇ :EndClass
Add debugging information to Logger.Log
Add debugging information to Logger.Log
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
78f251d5ca09ae7c61008604ce5c37224cfc647d
MS3/Code/Templates/MiPageSample.dyalog
MS3/Code/Templates/MiPageSample.dyalog
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code ∇ {r}←Wrap;lang;server;src;c :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server ⍝ we need jQuery to toggle content/source, other resources will be loaded if needed Use'JQuery' ⍝ this is a resource defined in Config/Resources.xml ⍝ set the title display in the browser to the name of the page or application Add _.title('Advanced' 'Simple' 'Examples?' 'index' '_'⎕R'' '' ''server.Config.Name' '((-'.'⍳⍨⌽)↓⊢↑⍨1-'/'⍳⍨⌽)_Request.Page) ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 ⍝ (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div 'contentblock'Body.Push _.div ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HtmlUtils.APLToHTMLColor src←⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' ⍝ extract the content and re-write it in parallel to the controls info div c←Body.Content Body.Content←'' Body.Add c ⍝ create a division with info about the controls used Body.Add CtrlsDiv src ⍝ wrap the content of the <body> element in a div '.bodyblock'Body.Push _.div ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.ReadText server.Config.Root,'Styles/banner.txt' 'wrapper'Body.Push _.div ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script ScriptFollows ⍝ $(function(){ ⍝ $("#tocode").click(function(){ ⍝ $("#contentblock").hide(); ⍝ $("#codeblock").show(); ⍝ $("#widgethelp").addClass("sliddown"); ⍝ $("#topage").removeClass("activetab"); ⍝ $("#tocode").addClass("activetab"); ⍝ }); ⍝ $("#topage").click(function(){ ⍝ $("#contentblock").show(); ⍝ $("#codeblock").hide(); ⍝ $("#widgethelp").removeClass("sliddown"); ⍝ $("#topage").addClass("activetab"); ⍝ $("#tocode").removeClass("activetab"); ⍝ }); ⍝ }); :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←CtrlsDiv source;control;controls;ns;pattern ⍝ Creates a div with info on the controls used in source ⍝ First we extract proper lists of controls controls←(⍴#.MS3SiteUtils.NSS)/⊂'' source←(⍳∘'⍝'↑⊢)¨source ⍝ remove comments source←{⍵/⍨~≠\''''=⍵}¨source ⍝ remove strings but leaves one ' as separator pattern←8⌽')\.(\w+)_(',∊#.MS3SiteUtils.NSS,¨'|' :For control :In 'Handler' 'Position'~⍨∪(pattern⎕S'\2')source ⍝ find controls :Trap 6 ⍝ unknown ns←(#.MS3SiteUtils.NSS(∨/⍷)¨⊂⍕⍎'#._.',control)/⍳⍴#.MS3SiteUtils.NSS ⍝ add to right list :Else ns←⍬ :EndTrap controls[ns],←⊂⊂control :EndFor controls←{⍵[⍋↑⍵]}¨controls ⍝ sort the lists ⍝ Now we create and populate the info div r←'<div id="widgethelp"><span id="used">Controls used on this page:</span>' :For ns :In (×≢¨controls)/⍳⍴#.MS3SiteUtils.NSS ⍝ do not process if empty r,←'&emsp;',(ns⊃#.MS3SiteUtils.GROUPS),':&nbsp;' :For control :In ns⊃controls r,←'<a target="_blank" href="/Documentation/DyalogAPIs/WidgetDoc?namespace=_',ns⊃#.MS3SiteUtils.NSS r,←'&amp;widget=',control,'">',control,'</a>,&nbsp;' :EndFor r↓⍨←¯7 :EndFor r,←'</div>' ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (isClass e)∨isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ :EndClass
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code :Field Public _Sessioned←0 ∇ {r}←Wrap;lang;server;src;c :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server ⍝ we need jQuery to toggle content/source, other resources will be loaded if needed Use'JQuery' ⍝ this is a resource defined in Config/Resources.xml ⍝ set the title display in the browser to the name of the page or application Add _.title('Advanced' 'Simple' 'Examples?' 'index' '_'⎕R'' '' ''server.Config.Name' '((-'.'⍳⍨⌽)↓⊢↑⍨1-'/'⍳⍨⌽)_Request.Page) ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 ⍝ (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div 'contentblock'Body.Push _.div ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HtmlUtils.APLToHTMLColor src←⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' ⍝ extract the content and re-write it in parallel to the controls info div c←Body.Content Body.Content←'' Body.Add c ⍝ create a division with info about the controls used Body.Add CtrlsDiv src ⍝ wrap the content of the <body> element in a div '.bodyblock'Body.Push _.div ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.ReadText server.Config.Root,'Styles/banner.txt' 'wrapper'Body.Push _.div ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script ScriptFollows ⍝ $(function(){ ⍝ $("#tocode").click(function(){ ⍝ $("#contentblock").hide(); ⍝ $("#codeblock").show(); ⍝ $("#widgethelp").addClass("sliddown"); ⍝ $("#topage").removeClass("activetab"); ⍝ $("#tocode").addClass("activetab"); ⍝ }); ⍝ $("#topage").click(function(){ ⍝ $("#contentblock").show(); ⍝ $("#codeblock").hide(); ⍝ $("#widgethelp").removeClass("sliddown"); ⍝ $("#topage").addClass("activetab"); ⍝ $("#tocode").removeClass("activetab"); ⍝ }); ⍝ }); :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←CtrlsDiv source;control;controls;ns;pattern ⍝ Creates a div with info on the controls used in source ⍝ First we extract proper lists of controls controls←(⍴#.MS3SiteUtils.NSS)/⊂'' source←(⍳∘'⍝'↑⊢)¨source ⍝ remove comments source←{⍵/⍨~≠\''''=⍵}¨source ⍝ remove strings but leaves one ' as separator pattern←8⌽')\.(\w+)_(',∊#.MS3SiteUtils.NSS,¨'|' :For control :In 'Handler' 'Position'~⍨∪(pattern ⎕S'\2')source ⍝ find controls :Trap 6 ⍝ unknown ns←(#.MS3SiteUtils.NSS(∨/⍷)¨⊂⍕⍎'#._.',control)/⍳⍴#.MS3SiteUtils.NSS ⍝ add to right list :Else ns←⍬ :EndTrap controls[ns],←⊂⊂control :EndFor controls←{⍵[⍋↑⍵]}¨controls ⍝ sort the lists ⍝ Now we create and populate the info div r←'<div id="widgethelp"><span id="used">Controls used on this page:</span>' :For ns :In (×≢¨controls)/⍳⍴#.MS3SiteUtils.NSS ⍝ do not process if empty r,←'&emsp;',(ns⊃#.MS3SiteUtils.GROUPS),':&nbsp;' :For control :In ns⊃controls r,←'<a target="_blank" href="/Documentation/DyalogAPIs/WidgetDoc?namespace=_',ns⊃#.MS3SiteUtils.NSS r,←'&amp;widget=',control,'">',control,'</a>,&nbsp;' :EndFor r↓⍨←¯7 :EndFor r,←'</div>' ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (isClass e)∨isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ :EndClass
Make MS3 site page unsessioned
Make MS3 site page unsessioned
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
05b308db282b0f8a5b61e6ce144c5c564db3fe46
MS3/Examples/HTML/abbrsample.dyalog
MS3/Examples/HTML/abbrsample.dyalog
:class abbrsample: MiPage ⍝ Control:: HTML.abbr ⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area ⍝ ⍝ This is an example of using the HTML 'abbr' element. ∇ Compose :Access public ⍝ We simply display the text 'Hover over THIS to reveal.' ⍝ First we add the text 'Hover over', then Add'Hover over ' ⍝ Then we add the element 'abbr' containing the text 'THIS', ⍝ making sure the text to display when hovering over it ⍝ (the title) displays 'True Http Internet Scripts' 'title' 'True Http Internet Scripts'Add _.abbr'THIS' ⍝ then we add the final text. Add' to reveal.' ∇ :endclass
:class abbrsample: MiPage ⍝ Control:: HTML.abbr ⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area ⍝ This is an example of using the HTML 'abbr' element. ∇ Compose :Access public ⍝ We simply display the text 'Hover over THIS to reveal.' ⍝ First we add the text 'Hover over', then Add'Hover over ' ⍝ Then we add the element 'abbr' containing the text 'THIS', ⍝ making sure the text to display when hovering over it ⍝ (the title) displays 'True Http Internet Scripts' 'title' 'True Http Internet Scripts'Add _.abbr'THIS' ⍝ then we add the final text. Add' to reveal.' ∇ :endclass
Remove empty comment that messes up the index page
Remove empty comment that messes up the index page
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
a9ecd22e0a15965edb1eb43229d10a8737c86f72
MS3/Code/Templates/MiPageSample.dyalog
MS3/Code/Templates/MiPageSample.dyalog
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code ∇ {r}←Wrap;lang;server;c;src;ctrlsdiv :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server ⍝ we use Syncfusion (which uses jQuery) to set up the controls to do cool stuff ⍝ Use'Syncfusion' ⍝ this is a resource defined in Config/Resources.xml ⍝ Will be loaded anyway if needed - speedup if not ⍝ set the title display in the browser to the name of the application defined in Config/Server.xml Add _.title server.Config.Name ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div Body.Push _.div'id="contentblock"' ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HTMLInput.APLToHTMLColour src←⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' ⍝ create a division with info about the controls used ctrlsdiv←CtrlsDiv src ⍝ extract the content and re-write it in parallel to the controls info div c←Body.Content Body.Content←'' (Body.Add _.StackPanel ctrlsdiv c).Horizontal←1 ⍝ wrap the content of the <body> element in a div Body.Push _.div'class="bodyblock"' ⍝ add the footer to the bottom of the page Add #.Files.GetText server.Config.Root,'Styles\footer.txt' ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.GetText server.Config.Root,'Styles\banner.txt' Body.Push _.div'id="wrapper"' ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script'$(function(){$("#bannerimage").on("click", function(evt){$("#contentblock,#codeblock,.widgethelp").toggle(400,"swing");});});' ⍝ set the language for the page lang←server.Config.Lang ⍝ use the language specified in Server.xml Set'lang="',lang,'" xml:lang="',lang,'" xmlns="http://www.w3.org/1999/xhtml"' :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←CtrlsDiv source;control;controls;lia;ns;ul;cali;h ⍝ Creates a div with info on the controls used in source ⍝ First we extract proper lists of controls controls←4/⊂'' source←(⍳∘'⍝'↑⊢)¨source ⍝ remove comments source←{⍵/⍨~≠\''''=⍵}¨source ⍝ remove strings but leaves one ' as separator :For control :In 'Handler' 'Position'~⍨∪('_(DC|SF|JQ|html|)\.(\w+)'⎕S'\2')source ⍝ find controls ⍝ add to right list: /¯¯¯¯¯SF¯¯¯¯¯\ /¯¯¯¯¯JQ¯¯¯¯¯\ /¯¯¯¯DC¯¯¯¯\ /¯html controls[⊃2 3 1 4/⍨('ej'≡2↑control)('jq'≡2↑control)(⎕A∊⍨⊃control)1],←⊂⊂control :EndFor controls←{⍵[⍋↑⍵]}¨controls ⍝ sort the lists ⍝ Now we create and populate the info div r←'.widgethelp'New _.div'This Page Contains<hr/>' lia←'<li><a target="_blank" href="' h←'http://' :For ns :In (×≢¨controls)/⍳4 ⍝ do not process if empty '.widgetNs'r.Add _.span,⊂ns⊃'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' ul←r.Add _.ul :For control :In ns⊃controls cali←'">',control,'</a></li>' :Select ns :Case 1 ⋄ ul.Add lia,'/Documentation/DyalogAPIs/WidgetDoc?namespace=_DC&widget=',control,cali ⍝ DC :Case 2 ⋄ ul.Add lia,h,'help.syncfusion.com/js/',(#.Strings.lc(2×'ej'≡2↑control)↓control,'/overview'),cali ⍝ SF :Case 3 ⋄ ul.Add lia,h,'jqueryui.com/',(2↓control),cali ⍝ JQ :Case 4 ⋄ ul.Add lia,h,'www.w3schools.com/tags/tag_',(('\d'⎕R'n')control),'.asp',cali ⍝ html :EndSelect :EndFor :EndFor ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (#.HtmlElement.isClass e)∨#.HtmlElement.isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ ⍝ ∇ r←FormatControls controls;ctrls;ns;desc;field;n;ctrl;i;c;ref;l;u;nss;item;cn ⍝ ctrls←⊃{⍺ ⍵}#.Utils.∆key/↓[1]0 1↓↑{⎕ML←3 ⋄ {⍵⊂⍨⍵≠'.'}⍕⍵}¨controls ⍝ field←{0::'' ⋄ ⍺⍎⍵} ⍝ nss←'_DC' '_SF' '_JQ' '_html' ⍝ desc←'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' ⍝ (r←⎕NEW _.div).class←'widgethelp' ⍝ r.Add'This Page Contains<hr/>' ⍝ :Trap 0 ⍝ :For (ns ctrl i) :In ctrls{↓(⍺,⍵)[⍋⍵;]}nss⍳{(⊃⍣(¯1+≡⍵))⍵}¨ctrls[;1] ⍝ (r.Add _.span(i⊃desc)).class←'widgetNs' ⍝ u←r.Add _.ul ⍝ n←#.⍎ns←⊃ns ⍝ :For c :In ctrl ⍝ ref←n.⍎c ⍝ item←⍬ ⍝ :Select ns ⍝ :Case '_DC' ⍝ item←u.Add _.li(New _.a(c(('href=/Documentation/DyalogAPIs/WidgetDoc?namespace=',ns,'&widget=',c)'target=_blank'))) ⍝ :Case '_SF' ⍝ item←u.Add _.li(New _.a c(('href'('http://js.syncfusion.com/demos/web/default.htm#!/azure/',#.Strings.lc(2×'ej'≡2↑c)↓c,'/'))('target' '_blank'))) ⍝ :Case '_JQ' ⍝ item←u.Add _.li(New _.a c(('href'('http://jqueryui.com/',(2×'jq'≡2↑c)↓c))('target' '_blank'))) ⍝ :Case '_html' ⍝ cn←c ⍝ :If ~0∊⍴('^h[1-6]$'⎕S{⍵.Match})c ⍝ cn←'hn' ⍝ :EndIf ⍝ item←u.Add _.li(New _.a c(('href'('http://www.w3schools.com/tags/tag_',cn,'.asp'))('target' '_blank'))) ⍝ :EndSelect ⍝ :If 0∊⍴item ⍝ u.Add _.li c ⍝ :EndIf ⍝ :EndFor ⍝ :EndFor ⍝ :EndTrap ⍝ ∇ :EndClass
:Class MiPageSample : #.MiPage ⍝ This is a template that "wraps" the page content by ⍝ - adding a header and footer ⍝ - adding a handler that will toggle the display of the web page and its APL source code ∇ {r}←Wrap;lang;server;c;src;ctrlsdiv :Access Public :If 0∊⍴Get'nowrapper' server←_Request.Server ⍝ we need jQuery to toggle content/source, other resources will be loaded if needed Use'JQuery' ⍝ this is a resource defined in Config/Resources.xml ⍝ set the title display in the browser to the name of the application defined in Config/Server.xml Add _.title server.Config.Name ⍝ add a link to our CSS stylesheet _CssReset←'/Styles/cssreset.css' _CssOverride←'/Styles/sampleStyles.css' ⍝ set a meta tag to make it explicitly UTF-8 (Add _.meta).Set'http-equiv="content-type" content="text/html;charset=UTF-8"' ⍝ wrap the content of the <body> element in a div Body.Push _.div'id="contentblock"' ⍝ add a hidden division to the body containing the APL source code (Add _.div(#.HTMLInput.APLToHTMLColour src←⎕SRC⊃⊃⎕CLASS ⎕THIS)).Set'id="codeblock"' 'style="display: none;"' ⍝ create a division with info about the controls used ctrlsdiv←CtrlsDiv src ⍝ extract the content and re-write it in parallel to the controls info div c←Body.Content Body.Content←'' (Body.Add _.StackPanel ctrlsdiv c).Horizontal←1 ⍝ wrap the content of the <body> element in a div Body.Push _.div'class="bodyblock"' ⍝ add the footer to the bottom of the page Add #.Files.GetText server.Config.Root,'Styles\footer.txt' ⍝ add the header to the top of the page and wrap the body in a div with id="wrapper" Body.Push #.Files.GetText server.Config.Root,'Styles\banner.txt' Body.Push _.div'id="wrapper"' ⍝ add a JQuery event handler to toggle the web page/APL source code Add _.Script'$(function(){$("#bannerimage").on("click", function(evt){$("#contentblock,#codeblock,.widgethelp").toggle(400,"swing");});});' ⍝ set the language for the page lang←server.Config.Lang ⍝ use the language specified in Server.xml Set'lang="',lang,'" xml:lang="',lang,'" xmlns="http://www.w3.org/1999/xhtml"' :Else Head.Add _.StyleSheet'/Styles/sampleStyles.css' Body.class←'bodyblock' :EndIf ⍝ call the base class Wrap function r←⎕BASE.Wrap ∇ ∇ r←CtrlsDiv source;control;controls;lia;ns;ul;cali;h;li ⍝ Creates a div with info on the controls used in source ⍝ First we extract proper lists of controls controls←4/⊂'' source←(⍳∘'⍝'↑⊢)¨source ⍝ remove comments source←{⍵/⍨~≠\''''=⍵}¨source ⍝ remove strings but leaves one ' as separator :For control :In 'Handler' 'Position'~⍨∪('_(DC|SF|JQ|html|)\.(\w+)'⎕S'\2')source ⍝ find controls ⍝ add to right list: /¯¯¯¯¯SF¯¯¯¯¯\ /¯¯¯¯¯JQ¯¯¯¯¯\ /¯¯¯¯DC¯¯¯¯\ /¯html controls[⊃2 3 1 4/⍨('ej'≡2↑control)('jq'≡2↑control)(⎕A∊⍨⊃control)1],←⊂⊂control :EndFor controls←{⍵[⍋↑⍵]}¨controls ⍝ sort the lists ⍝ Now we create and populate the info div r←'.widgethelp'New _.div'This Page Contains<hr/>' ⍝lia←'<li><a target="_blank" href="' h←'http://' :For ns :In (×≢¨controls)/⍳4 ⍝ do not process if empty '.widgetNs'r.Add _.span,⊂ns⊃'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' ul←r.Add _.ul :For control :In ns⊃controls ⍝cali←'">',control,'</a></li>' li←'<li><a target="_blank" href="/Documentation/DyalogAPIs/WidgetDoc?namespace=_',ns⊃#.MS3SiteUtils.NSS ul.Add li,'&widget=',control,'">',control,'</a></li>' ⍝ :Select ns ⍝ :Case 1 ⋄ ul.Add lia,'/Documentation/DyalogAPIs/WidgetDoc?namespace=_DC&widget=',control,cali ⍝ DC ⍝ :Case 2 ⋄ ul.Add lia,h,'help.syncfusion.com/js/',(#.Strings.lc(2×'ej'≡2↑control)↓control,'/overview'),cali ⍝ SF ⍝ :Case 3 ⋄ ul.Add lia,h,'jqueryui.com/',(2↓control),cali ⍝ JQ ⍝ :Case 4 ⋄ ul.Add lia,h,'www.w3schools.com/tags/tag_',(('\d'⎕R'n')control),'.asp',cali ⍝ html ⍝ :EndSelect :EndFor :EndFor ∇ ∇ r←Walk content;e r←⍬ :For e :In content :If (#.HtmlElement.isClass e)∨#.HtmlElement.isInstance e r←r,⊃⎕CLASS e :Trap 6 r,←Walk e.Content :EndTrap :EndIf :EndFor ∇ ⍝ ∇ r←FormatControls controls;ctrls;ns;desc;field;n;ctrl;i;c;ref;l;u;nss;item;cn ⍝ ctrls←⊃{⍺ ⍵}#.Utils.∆key/↓[1]0 1↓↑{⎕ML←3 ⋄ {⍵⊂⍨⍵≠'.'}⍕⍵}¨controls ⍝ field←{0::'' ⋄ ⍺⍎⍵} ⍝ nss←'_DC' '_SF' '_JQ' '_html' ⍝ desc←'Dyalog Controls' 'Syncfusion Widgets' 'jQuery Widgets' 'Native HTML5 Elements' ⍝ (r←⎕NEW _.div).class←'widgethelp' ⍝ r.Add'This Page Contains<hr/>' ⍝ :Trap 0 ⍝ :For (ns ctrl i) :In ctrls{↓(⍺,⍵)[⍋⍵;]}nss⍳{(⊃⍣(¯1+≡⍵))⍵}¨ctrls[;1] ⍝ (r.Add _.span(i⊃desc)).class←'widgetNs' ⍝ u←r.Add _.ul ⍝ n←#.⍎ns←⊃ns ⍝ :For c :In ctrl ⍝ ref←n.⍎c ⍝ item←⍬ ⍝ :Select ns ⍝ :Case '_DC' ⍝ item←u.Add _.li(New _.a(c(('href=/Documentation/DyalogAPIs/WidgetDoc?namespace=',ns,'&widget=',c)'target=_blank'))) ⍝ :Case '_SF' ⍝ item←u.Add _.li(New _.a c(('href'('http://js.syncfusion.com/demos/web/default.htm#!/azure/',#.Strings.lc(2×'ej'≡2↑c)↓c,'/'))('target' '_blank'))) ⍝ :Case '_JQ' ⍝ item←u.Add _.li(New _.a c(('href'('http://jqueryui.com/',(2×'jq'≡2↑c)↓c))('target' '_blank'))) ⍝ :Case '_html' ⍝ cn←c ⍝ :If ~0∊⍴('^h[1-6]$'⎕S{⍵.Match})c ⍝ cn←'hn' ⍝ :EndIf ⍝ item←u.Add _.li(New _.a c(('href'('http://www.w3schools.com/tags/tag_',cn,'.asp'))('target' '_blank'))) ⍝ :EndSelect ⍝ :If 0∊⍴item ⍝ u.Add _.li c ⍝ :EndIf ⍝ :EndFor ⍝ :EndFor ⍝ :EndTrap ⍝ ∇ :EndClass
Use 'JQuery' for big D. Controls info box now always links to WidgetDoc.
MiPageSample: Use 'JQuery' for big D. Controls info box now always links to WidgetDoc.
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
dc1d672b459c800ca19da6abf8c253c922c098ba
examples/dfns/queens.apl
examples/dfns/queens.apl
queens←{⎕IO ⎕ML←0 1 ⍝ The N-queens problem. search←{ ⍝ Search for all solutions. (⊂⍬)∊⍵:0⍴⊂⍬ ⍝ stitched: abandon this branch. 0=⍴⍵:rmdups ⍺ ⍝ all done: solution! hd←⊃⍵ ⍝ head... tl←1↓⍵ ⍝ ... 'n tail of remaining ranks. next←⍺∘,¨hd ⍝ possible next steps. rems←hd free¨⊂tl ⍝ unchecked squares. ↑,/next ∇¨rems ⍝ ... in following ranks. } cvex←(1+⍳⍵)×⊂¯1 0 1 ⍝ Checking vectors. free←{⍵~¨⍺+(⍴⍵)↑cvex} ⍝ Unchecked squares. rmdups←{ ⍝ Ignore duplicate solution. rots←{{⍒⍵}\4/⊂⍵} ⍝ 4 rotations. refs←{{⍋⍵}\2/⊂⍵} ⍝ 2 reflections. best←{(⊃⍋↑⍵)⊃⍵} ⍝ best (=lowest) solution. all8←,↑refs¨rots ⍵ ⍝ all 8 orientations. (⍵≡best all8)⊃⍬(,⊂⍵) ⍝ ignore if not best. } fmt←{ ⍝ Format solution. chars←'·⍟'[(↑⍵)∘.=⍳⍺] ⍝ char array of placed queens. expd←1↓,↑⍺⍴⊂0 1 ⍝ expansion mask. ↑¨↓↓expd\chars ⍝ vector of char matrices. } squares←(⊂⍳⌈⍵÷2),1↓⍵⍴⊂⍳⍵ ⍝ initial squares ⍵ fmt ⍬ search squares ⍝ all distinct solutions. } ⎕←queens 5
Add dfns queens example.
Add dfns queens example.
APL
mit
fineline/apl,fineline/apl,fineline/apl,fineline/apl
ecdd636140fb17b3e3737e51154e133adf106d2b
Utils/dates.dyalog
Utils/dates.dyalog
:Namespace Dates (⎕ML ⎕IO)←1 ∇ r←CookieFmt date;day;date;mon ⍝ Format date for cookie expiry ⍝ "expires Mon, 09-Dec-2002 13:46:00 GMT" day←(7 3⍴'MonTueWedThuFriSatSun')[WeekDay date;] mon←(12 3⍴'janfebmaraprmayjunjulaugsepoctnovdec')[2⊃date;] r←,('<',day,', >,ZI2,<-',mon,'->,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴(6↑date)[3 1 4 5 6] ∇ ∇ r←{minOffset}HttpDate ts;sign;day;mon;ver;⎕USING;t ⍝ return RCF 1123/822 compliant date ⍝ minOffset is option number of minutes to offset time with (used for HTTP caching expirations) minOffset←{0::0 ⋄ minOffset}'' ts←6↑ts :If 0=⎕NC'_UtcOffset' :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' ⎕USING←,⊂'' _UtcOffset←¯60×(System.TimeZone.CurrentTimeZone.GetUtcOffset ⎕NEW System.DateTime(ts)).Hours :Else :If (⊂ver)∊'Lin' 'AIX' 'Sol' _UtcOffset←¯60×⍎¯2↓{⍵↑⍨-' '⍳⍨⌽⍵}⊃⎕SH'date -R' :Else _UtcOffset←0 ⍝ otherwise, assume GMT :EndIf :EndIf :EndIf ts←IDNToDate((_UtcOffset+minOffset)÷24×60)+t←DateToIDN ts day←(7 3⍴'MonTueWedThuFriSatSun')[1+7|(⌊t)-1;] mon←(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[2⊃ts;] r←,('<',day,', >,ZI2,< ',mon,' >,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴ts[3 1 4 5 6] ∇ ∇ SM←DateToIDN TS ⍝ Convert date format SM←2 ⎕NQ'.' 'DateToIDN'(3↑TS) :If 3<⍴TS SM+←(24 60 60 1000⊥4↑3↓TS)÷86400000 :EndIf ∇ ∇ TS←IDNToDate SM ⍝ Convert IDN to date format : 3↑⎕TS ← IDN (akd TS_SM) TS←3↑2 ⎕NQ'.' 'IDNToDate'(⌊SM) TS,←⌊0.5+24 60 60 1000⊤86400000×1|SM ∇ ∇ new←ts IdnAdd t ⍝ T is D HH MM SS new←ts+(0 24 60 60 1000⊥¯5↑t,0)÷86400000 ∇ ∇ r←Now r←DateToIDN ⎕TS ∇ ∇ r←TSFmt ts r←,'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 1 5⍴ts ∇ ∇ r←TSFmtNice ts;now;yday;today;z;i;m;idn;s ⍝ Format a vector of IDN's nicely s←⍴ts yday←¯1+today←⌊now←DateToIDN ⎕TS r←↑IDNToDate¨,ts←,ts ⍝ Make matrix r←'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 5↑[2]r :If 0≠⍴i←((ts≥yday)∧~m←ts≥today)/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Yesterday' :EndIf :If 0≠⍴i←m/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Today' :EndIf :If 0≠⍴i←(100>z←⌊(now-ts)×24×60)/⍳⍴ts r[i;]←16↑[2]↑(⍕¨⌊z[i]),¨(' minutes ago' ' minute ago')[1+1=z[i]] :EndIf :If 0≠⍴i←(z<1)/⍳⍴ts r[i;]←((⍴i),16)⍴16↑'Now' :EndIf r←(s,¯1↑⍴r)⍴r ∇ ∇ r←WeekDay Date ⍝ Return weekday (Monday=1, Sunday=7) r←1+7|(DateToIDN 3↑Date)-1 ∇ ∇ r←LogFmtNow;ver ⍝ returns now UTC adjusted, and formatted for log files (Common Log Format) :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' r←((⍎⎕NA'kernel32|GetSystemTime >{U2 U2 U2 U2 U2 U2 U2 U2}')⊂8⍴0)[4 2 1 5 6 7] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r :Else r←1⊃⎕SH'date +" [%d/%b/%Y:%T %z] "' :EndIf ∇ ∇ r←LogFmt ymdhms r←ymdhms[3 2 1 4 5 6] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r ∇ ∇ ts←FTT fts;md;shape;tmp;yr;z;⎕IO ⍝ *** convert ⎕FRDCI/⎕FHIST timestamp(s) to ⎕ts-format for Dyalog/W *** ⍝ right argument: ⎕FRDCI-type timestamp(s) of any shape ⍝ result: ⎕ts-type timestamp(s) with shape <(⍴argument),7> ⎕IO←0 ⋄ shape←⍴fts ⋄ ts←,fts+18626112000 md←365.2501|1+1461|yr←⌊ts÷5184000 tmp←31 61 92 122 153 184 214 245 275 306 337 366 z←(,⍉<⍀tmp∘.≥md)/,((⍴md),12)⍴⍳12 md←(1+12|z+2),[0.1]⌈md-(0,tmp)[z] ts←(1960+⌊(yr+60)÷365.25),md,⍉24 60 60 60⊤ts ts[;6]←⌊0.5+ts[;6]×100÷6 ts←(shape,7)⍴ts ∇ ∇ r←TTF ts;l;h;d;m;y ⍝ convert a ⎕TS style timestamp into 60ths of a second since 1st January 1970 a la ⎕FRDCI l←⌈60×ts[7]÷1000 ⍝ convert milliseconds to 60ths h←3600 60 60⊥ts[4 5 6] ⍝ hours minutes seconds to to the nearest seconds total d←ts[3]-1 ⍝ days since start of month m←(2⊃ts)⊃++\0 31,(28+0=4|⊃ts),31 30 31 30 31 31 30 31 30 ⍝ days in completed months y←{{(365×⍵)+⌈4÷⍨⍵-2}⍵-1970}⊃ts ⍝ days in years since 1970, leap years since 1972 r←l+60×h+86400×y+m+d ⍝ sum, convert to seconds, add seconds in the day convert to 60ths, add on 60ths ∇ :EndNamespace
:Namespace Dates (⎕ML ⎕IO)←1 ∇ r←CookieFmt date;day;date;mon ⍝ Format date for cookie expiry ⍝ "expires Mon, 09-Dec-2002 13:46:00 GMT" day←(7 3⍴'MonTueWedThuFriSatSun')[WeekDay date;] mon←(12 3⍴'janfebmaraprmayjunjulaugsepoctnovdec')[2⊃date;] r←,('<',day,', >,ZI2,<-',mon,'->,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴(6↑date)[3 1 4 5 6] ∇ ∇ r←{minOffset}HttpDate ts;sign;day;mon;ver;⎕USING;t ⍝ return RCF 1123/822 compliant date ⍝ minOffset is option number of minutes to offset time with (used for HTTP caching expirations) minOffset←{0::0 ⋄ minOffset}'' ts←6↑ts :If 0=⎕NC'_UtcOffset' :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' :Hold '_UtcOffset' ⎕USING←,⊂'' _UtcOffset←¯60×(System.TimeZone.CurrentTimeZone.GetUtcOffset ⎕NEW System.DateTime(ts)).Hours :EndHold :Else :If (⊂ver)∊'Lin' 'AIX' 'Sol' _UtcOffset←¯60×⍎¯2↓{⍵↑⍨-' '⍳⍨⌽⍵}⊃⎕SH'date -R' :Else _UtcOffset←0 ⍝ otherwise, assume GMT :EndIf :EndIf :EndIf ts←IDNToDate((_UtcOffset+minOffset)÷24×60)+t←DateToIDN ts day←(7 3⍴'MonTueWedThuFriSatSun')[1+7|(⌊t)-1;] mon←(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[2⊃ts;] r←,('<',day,', >,ZI2,< ',mon,' >,ZI4,< >,ZI2,<:>,ZI2,<:>,ZI2,< GMT>')⎕FMT 1 5⍴ts[3 1 4 5 6] ∇ ∇ SM←DateToIDN TS ⍝ Convert date format SM←2 ⎕NQ'.' 'DateToIDN'(3↑TS) :If 3<⍴TS SM+←(24 60 60 1000⊥4↑3↓TS)÷86400000 :EndIf ∇ ∇ TS←IDNToDate SM ⍝ Convert IDN to date format : 3↑⎕TS ← IDN (akd TS_SM) TS←3↑2 ⎕NQ'.' 'IDNToDate'(⌊SM) TS,←⌊0.5+24 60 60 1000⊤86400000×1|SM ∇ ∇ new←ts IdnAdd t ⍝ T is D HH MM SS new←ts+(0 24 60 60 1000⊥¯5↑t,0)÷86400000 ∇ ∇ r←Now r←DateToIDN ⎕TS ∇ ∇ r←TSFmt ts r←,'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 1 5⍴ts ∇ ∇ r←TSFmtNice ts;now;yday;today;z;i;m;idn;s ⍝ Format a vector of IDN's nicely s←⍴ts yday←¯1+today←⌊now←DateToIDN ⎕TS r←↑IDNToDate¨,ts←,ts ⍝ Make matrix r←'ZI4,<->,ZI2,<->,ZI2,< >,ZI2,<:>,ZI2'⎕FMT 5↑[2]r :If 0≠⍴i←((ts≥yday)∧~m←ts≥today)/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Yesterday' :EndIf :If 0≠⍴i←m/⍳⍴ts r[i;]←r[i;11+⍳5],' ',((⍴i),10)⍴10↑'Today' :EndIf :If 0≠⍴i←(100>z←⌊(now-ts)×24×60)/⍳⍴ts r[i;]←16↑[2]↑(⍕¨⌊z[i]),¨(' minutes ago' ' minute ago')[1+1=z[i]] :EndIf :If 0≠⍴i←(z<1)/⍳⍴ts r[i;]←((⍴i),16)⍴16↑'Now' :EndIf r←(s,¯1↑⍴r)⍴r ∇ ∇ r←WeekDay Date ⍝ Return weekday (Monday=1, Sunday=7) r←1+7|(DateToIDN 3↑Date)-1 ∇ ∇ r←LogFmtNow;ver ⍝ returns now UTC adjusted, and formatted for log files (Common Log Format) :If 'Win'≡ver←3↑1⊃'.'⎕WG'APLVersion' r←((⍎⎕NA'kernel32|GetSystemTime >{U2 U2 U2 U2 U2 U2 U2 U2}')⊂8⍴0)[4 2 1 5 6 7] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r :Else r←1⊃⎕SH'date +" [%d/%b/%Y:%T %z] "' :EndIf ∇ ∇ r←LogFmt ymdhms r←ymdhms[3 2 1 4 5 6] r[2]←⊂(12 3⍴'JanFebMarAprMayJunJulAugSepOctNovDec')[,2⊃r;] r←,'< [>,ZI2,</>,3A1,</>,ZI4,<:>,ZI2,<:>,ZI2,<:>,ZI2,< +0000] >'⎕FMT r ∇ ∇ ts←FTT fts;md;shape;tmp;yr;z;⎕IO ⍝ *** convert ⎕FRDCI/⎕FHIST timestamp(s) to ⎕ts-format for Dyalog/W *** ⍝ right argument: ⎕FRDCI-type timestamp(s) of any shape ⍝ result: ⎕ts-type timestamp(s) with shape <(⍴argument),7> ⎕IO←0 ⋄ shape←⍴fts ⋄ ts←,fts+18626112000 md←365.2501|1+1461|yr←⌊ts÷5184000 tmp←31 61 92 122 153 184 214 245 275 306 337 366 z←(,⍉<⍀tmp∘.≥md)/,((⍴md),12)⍴⍳12 md←(1+12|z+2),[0.1]⌈md-(0,tmp)[z] ts←(1960+⌊(yr+60)÷365.25),md,⍉24 60 60 60⊤ts ts[;6]←⌊0.5+ts[;6]×100÷6 ts←(shape,7)⍴ts ∇ ∇ r←TTF ts;l;h;d;m;y ⍝ convert a ⎕TS style timestamp into 60ths of a second since 1st January 1970 a la ⎕FRDCI l←⌈60×ts[7]÷1000 ⍝ convert milliseconds to 60ths h←3600 60 60⊥ts[4 5 6] ⍝ hours minutes seconds to to the nearest seconds total d←ts[3]-1 ⍝ days since start of month m←(2⊃ts)⊃++\0 31,(28+0=4|⊃ts),31 30 31 30 31 31 30 31 30 ⍝ days in completed months y←{{(365×⍵)+⌈4÷⍨⍵-2}⍵-1970}⊃ts ⍝ days in years since 1970, leap years since 1972 r←l+60×h+86400×y+m+d ⍝ sum, convert to seconds, add seconds in the day convert to 60ths, add on 60ths ∇ :EndNamespace
Fix to Dates.HttpDate
Fix to Dates.HttpDate
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
b686026f4993f3934100324bb9a4cc593f06d434
shell/cgi.apl
shell/cgi.apl
#!/usr/local/bin/apl --script NEWLINE ← ⎕UCS 10 HEADERS ← 'Content-Type: text/plain', NEWLINE HEADERS ⍝ ⎕←HEADERS ⍝ ⍕⎕TS )OFF ⍝ testVars←'FUCKYEAH' ⍝ ≠\~(testVars ∊ 'AEIOU') ⍝ (124 × 4)≠(+/124 124 124) ⍝ testVars ∊ '<>'
Add boilerplate APL script to serve CGI webpages
Add boilerplate APL script to serve CGI webpages I can no longer tell if I've gone insane, or I've just become bored with web development. Probably a collusion of both. Either way, getting this script working required some changes in the GNU APL preferences file (interpreter built from source: v1.5 / SVN revision 694). The following settings were changed to the designated values: * Welcome: No * Color: No * SharedVars: Disabled That last setting is especially critical for running the APL interpreter as a CGI handler. Since multiple arguments can't be passed to a hashbang (at least in Apache), we can't set --script and --noSV at the same time. This leads to an error message being spat to STDOUT when the interpreter is invoked, screwing with the HTTP headers.
APL
isc
Alhadis/Snippets,Alhadis/Snippets,Alhadis/Snippets,Alhadis/Snippets,Alhadis/Snippets
46b0ad750ab11e25ba6cc629b3335078830b299d
Utils/HTTPCommand.dyalog
Utils/HTTPCommand.dyalog
:Class HTTPCommand ⍝ Issue an HTTP Command ⍝ Public Fields are: ⍝ Command - the HTTP command to issue, typically 'GET' 'POST' 'PUT etc ⍝ URL - the URL to direct the command at ⍝ format is: [HTTP[S]://][user:pass@]url[:port][/page[?params]] ⍝ Params - the parameters to pass with the command ⍝ for 'GET' you can pass parameters either in the URL or in Params (they will be appended to the URL) ⍝ Headers - any additional HTTP headers to send with the request (all the obvious headers like 'content-length' are precomputed) ⍝ a vector of 2-element (header-name value) vectors or a matrix of [;1] header-name [;2] values ⍝ Cert - if using a SSL, this is an instance of the X509Cert class ⍝ SSLFlags - if using SSL, these are the SSL flags as described in the Conga documentation ⍝ Priority - if using SSL, this is the ⎕ML←⎕IO←1 :field public Command←'GET' :field public Cert←⍬ :field public SSLFlags←32 :field public LocalDRC :field public URL←'' :field public Params←'' :field public Headers←'' :field public Priority←'NORMAL:!CTYPE-OPENPGP' :field public LDRC←'' ∇ make :Access public :Implements constructor ∇ ∇ make1 args :Access public :Implements constructor ⍝ args - [URL Params Headers Command Cert SSLFlags Priority] args←eis args Command URL Params Headers Cert SSLFlags Priority←7↑args,(⍴args)↓Command URL Params Headers Cert SSLFlags Priority ∇ ∇ r←Run;resp :Access public r←⎕NS'' :If 0∊⍴Cert resp←(Command HTTPCmd)URL Params Headers :Else resp←(Cert SSLFlags Priority)(Command HTTPCmd)URL Params Headers :EndIf r.(rc headers data peercert)←resp ∇ ∇ r←{certs}(cmd HTTPCmd)args;url;parms;hdrs;urlparms;p;b;secure;port;host;page;x509;flags;priority;pars;auth;req;err;chunked;chunk;buffer;chunklength;done;data;datalen;header;wr;headerlen ⍝ issue an HTTP command ⍝ certs - optional [X509Cert [SSLValidation [Priority]]] ⍝ args - [1] URL in format [HTTP[S]://][user:pass@]url[:port][/page] ⍝ {2} parameters is using POST - either a namespace or URL-encoded string ⍝ {3} HTTP headers in form {↑}(('hdr1' 'val1')('hdr2' 'val2')) ⍝ Makes secure connection if left arg provided or URL begins with https: ⍝ Result: (return code) (HTTP headers) (HTTP body) [PeerCert if secure] r←¯1(0 2⍴⊂'')''⍬ :If 9≠⎕NC'LDRC' :AndIf 9=#.⎕NC'DRC' LDRC←#.DRC :Else ⎕←'Conga namespace DRC not found or defined' →0 :EndIf {}LDRC.Init'' args←eis args (url parms hdrs)←args,(⍴args)↓''(⎕NS'')'' urlparms←'' cmd←uc,cmd :If 326=⎕DR parms ⍝ if parms are a namespace, format them :If 'POST'≡cmd parms←{0∊⍴t←⍵.⎕NL ¯2:'' ⋄ 1↓⊃,/⍵{'&',⍵,'=',(⍕⍺⍎⍵)}¨t}parms :Else urlparms←{0∊⍴⍵:'' ⋄ '?',⍵}{0∊⍴t←⍵.⎕NL ¯2:'' ⋄ 1↓⊃,/⍵{'&',⍵,'=',(⍕⍺⍎⍵)}¨t}parms parms←'' :EndIf :EndIf GET: p←(∨/b)×1+(b←'//'⍷url)⍳1 secure←{6::⍵ ⋄ ⍵∨0<⍴,certs}(lc(p-2)↑url)≡'https:' port←(1+secure)⊃80 443 ⍝ Default HTTP/HTTPS port url←p↓url ⍝ Remove HTTP[s]:// if present (host page)←'/'split url,(~'/'∊url)/'/' ⍝ Extract host and page from url :If 0=⎕NC'certs' ⋄ certs←'' ⋄ :EndIf :If secure x509 flags priority←3↑certs,(⍴,certs)↓(⎕NEW LDRC.X509Cert)32 'NORMAL:!CTYPE-OPENPGP' ⍝ 32=Do not validate Certs pars←('x509'x509)('SSLValidation'flags)('Priority'priority) :Else ⋄ pars←'' :EndIf :If '@'∊host ⍝ Handle user:password@host... auth←'Authorization: Basic ',(b64Encode(¯1+p←host⍳'@')↑host),NL host←p↓host :Else ⋄ auth←'' :EndIf (host port)←port{(⍴⍵)<ind←⍵⍳':':⍵ ⍺ ⋄ (⍵↑⍨ind-1)(1⊃2⊃⎕VFI ind↓⍵)}host ⍝ Check for override of port number hdrs←makeHeaders hdrs hdrs←'User-Agent'(hdrs addHeader)'Dyalog/Conga' hdrs←'Accept'(hdrs addHeader)'*/*' :If ~0∊⍴parms :If cmd≡'POST' hdrs←'Content-Length'(hdrs addHeader)⍴parms hdrs←'Content-Type'(hdrs addHeader)'application/x-www-form-urlencoded' :EndIf :EndIf hdrs←'Accept-Encoding'(hdrs addHeader)'gzip, deflate' req←cmd,' ',(page,urlparms),' HTTP/1.1',NL,'Host: ',host,NL req,←fmtHeaders hdrs req,←auth :If 0=⊃(err cmd)←2↑r←LDRC.Clt''host port'Text' 100000,pars ⍝ 100,000 is max receive buffer size :AndIf 0=⊃r←LDRC.Send cmd(req,NL,parms) chunked chunk buffer chunklength←0 '' '' 0 done data datalen headerlen header←0 ⍬ 0 0 ⍬ :Repeat :If ~done←0≠1⊃wr←LDRC.Wait cmd 5000 ⍝ Wait up to 5 secs :If wr[3]∊'Block' 'BlockLast' ⍝ If we got some data :If chunked chunk←4⊃wr :ElseIf 0<⍴data,←4⊃wr :AndIf 0=headerlen (headerlen header)←DecodeHeader data :If 0<headerlen data←headerlen↓data :If chunked←∨/'chunked'⍷header getHeader'Transfer-Encoding' chunk←data data←'' :Else datalen←⊃(toNum header getHeader'Content-Length'),¯1 ⍝ ¯1 if no content length not specified :EndIf :EndIf :EndIf :Else ⎕←wr ⍝ Error? ∘∘∘ :EndIf :If chunked buffer,←chunk :While done<¯1≠⊃(len chunklength)←getchunklen buffer :If (⍴buffer)≥4+len+chunklength data,←chunklength↑(len+2)↓buffer buffer←(chunklength+len+4)↓buffer :If done←0=chunklength ⍝ chunked transfer can add headers at the end of the transmission header←⊂header⍪2⊃DecodeHeader buffer :EndIf :EndIf :EndWhile :Else done←done∨'BlockLast'≡3⊃wr ⍝ Done if socket was closed :If datalen>0 done←done∨datalen≤⍴data ⍝ ... or if declared amount of data rcvd :Else done←done∨(∨/'</html>'⍷data)∨(∨/'</HTML>'⍷data) :EndIf :EndIf :EndIf :Until done :Trap 0 ⍝ If any errors occur, abandon conversion :Select header getHeader'content-encoding' ⍝ was the response compressed? :Case 'deflate' data←fromutf8 LDRC.flate.Inflate 120 156{(2×⍺≡2↑⍵)↓⍺,⍵}256|83 ⎕DR data ⍝ append 120 156 signature because web servers strip it out due to IE :Case 'gzip' data←fromutf8 256|¯3(219⌶)83 ⎕DR data :Else :If ∨/'charset=utf-8'⍷header getHeader'content-type' data←'UTF-8'⎕UCS ⎕UCS data ⍝ Convert from UTF-8 :EndIf :EndSelect :EndTrap :If {(⍵[3]∊'12357')∧'30 '≡⍵[1 2 4]}4↑{⍵↓⍨⍵⍳' '}(⊂1 1)⊃header ⍝ redirected? (HTTP status codes 301, 302, 303, 305, 307) →GET⍴⍨0<⍴url←'location'{(⍵[;1]⍳⊂⍺)⊃⍵[;2],⊂''}header ⍝ use the "location" header field for the URL :EndIf r←(1⊃wr)header data ⍬ :If secure ⋄ r[4]←⊂LDRC.GetProp cmd'PeerCert' ⋄ :EndIf :Else ⎕←'Connection failed ',,⍕r r←(⊂r)'' '' '' :EndIf {}LDRC.Close cmd ∇ NL←⎕UCS 13 10 fromutf8←{0::(⎕AV,'?')[⎕AVU⍳⍵] ⋄ 'UTF-8'⎕UCS ⍵} ⍝ Turn raw UTF-8 input into text utf8←{3=10|⎕DR ⍵: 256|⍵ ⋄ 'UTF-8' ⎕UCS ⍵} sint←{⎕io←0 ⋄ 83=⎕DR ⍵:⍵ ⋄ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 ¯128 ¯127 ¯126 ¯125 ¯124 ¯123 ¯122 ¯121 ¯120 ¯119 ¯118 ¯117 ¯116 ¯115 ¯114 ¯113 ¯112 ¯111 ¯110 ¯109 ¯108 ¯107 ¯106 ¯105 ¯104 ¯103 ¯102 ¯101 ¯100 ¯99 ¯98 ¯97 ¯96 ¯95 ¯94 ¯93 ¯92 ¯91 ¯90 ¯89 ¯88 ¯87 ¯86 ¯85 ¯84 ¯83 ¯82 ¯81 ¯80 ¯79 ¯78 ¯77 ¯76 ¯75 ¯74 ¯73 ¯72 ¯71 ¯70 ¯69 ¯68 ¯67 ¯66 ¯65 ¯64 ¯63 ¯62 ¯61 ¯60 ¯59 ¯58 ¯57 ¯56 ¯55 ¯54 ¯53 ¯52 ¯51 ¯50 ¯49 ¯48 ¯47 ¯46 ¯45 ¯44 ¯43 ¯42 ¯41 ¯40 ¯39 ¯38 ¯37 ¯36 ¯35 ¯34 ¯33 ¯32 ¯31 ¯30 ¯29 ¯28 ¯27 ¯26 ¯25 ¯24 ¯23 ¯22 ¯21 ¯20 ¯19 ¯18 ¯17 ¯16 ¯15 ¯14 ¯13 ¯12 ¯11 ¯10 ¯9 ¯8 ¯7 ¯6 ¯5 ¯4 ¯3 ¯2 ¯1[utf8 ⍵]} lc←(819⌶) ⍝ lower case conversion uc←1∘lc dlb←{(+/∧\' '=⍵)↓⍵} ⍝ delete leading blanks split←{(p↑⍵)((p←¯1+⍵⍳⍺)↓⍵)} ⍝ split ⍵ on first occurrence of ⍺ h2d←{⎕IO←0 ⋄ 16⊥'0123456789abcdef'⍳lc ⍵} ⍝ hex to decimal getchunklen←{¯1=len←¯1+⊃(NL⍷⍵)/⍳⍴⍵:¯1 ¯1 ⋄ chunklen←h2d len↑⍵ ⋄ (⍴⍵)<len+chunklen+4:¯1 ¯1 ⋄ len chunklen} eis←{⍺←1 ⋄ ,(⊂⍣(⍺=|≡⍵))⍵} ⍝ enclose if simple toNum←{0∊⍴⍵:⍬ ⋄ 1⊃2⊃⎕VFI ⍵} getHeader←{(⍺[;2],⊂'')⊃⍨⍺[;1]⍳eis lc ⍵} addHeader←{0∊⍴⍺⍺ getHeader ⍺:⍺⍺⍪⍺ ⍵ ⋄ ⍺⍺} makeHeaders←{⎕ML←1 ⋄ 0∊⍴⍵:0 2⍴⊂'' ⋄ 2=⍴⍴⍵:⍵ ⋄ ↑2 eis ⍵} fmtHeaders←{⎕ML←1 ⋄ 0∊⍴⍵:'' ⋄ ∊{NL,⍨(1⊃⍵),': ',⍕2⊃⍵}¨↓⍵} b64Encode←{ ⍝ Base64 Encode raw←⊃,/11∘⎕DR¨⍵ cols←6 rows←⌈(⊃⍴raw)÷cols mat←rows cols⍴(rows×cols)↑raw 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[⎕IO+2⊥⍉mat],(4|-rows)⍴'='} ∇ r←DecodeHeader buf;len;d;i ⍝ Decode HTTP Header r←0(0 2⍴⊂'') :If 0<i←⊃{((NL,NL)⍷⍵)/⍳⍴⍵}buf len←(¯1+⍴NL,NL)+i d←(⍴NL)↓¨{(NL⍷⍵)⊂⍵}NL,len↑buf d←↑{((p-1)↑⍵)((p←⍵⍳':')↓⍵)}¨d d[;1]←lc¨d[;1] d[;2]←dlb¨d[;2] r←len d :EndIf ∇ :EndClass
Add /Utils/HTTPCommand
Add /Utils/HTTPCommand
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
ddd7e517cff3840d82423e3ceac62cb59fcd20d4
Utils/FilesAndDirs.dyalog
Utils/FilesAndDirs.dyalog
:Class FilesAndDirs ⍝ This class exists solely in support of MarkAPL from APLTeam ⍝ It provides comparable functionality to the FilesAndDirs class from https://github.com/aplteam/filesanddirs ⍝ for 2 methods - NormalizePath and Exists (⎕ML ⎕IO)←1 1 ∇ r←{expand}NormalizePath f :Access public shared :If 0=⎕NC'expand' ⋄ expand←0 ⋄ :EndIf r←∊expand ⎕NPARTS f ∇ ∇ r←Exists f :Access public shared r←⎕NEXISTS∊⎕NPARTS f ∇ :EndClass
Create scaled down FilesAndDirs class so the new version of MarkAPL wll work.
Create scaled down FilesAndDirs class so the new version of MarkAPL wll work.
APL
mit
Dyalog/MiServer,Dyalog/MiServer,Dyalog/MiServer
8336dc33e410982bb77dad5d36e03e33a8b2fedd
samples/APL/UT.dyalog
samples/APL/UT.dyalog
:NameSpace UT sac ← 0 expect_orig ← expect ← ⎕NS⍬ exception ← ⍬ nexpect_orig ← nexpect ← ⎕NS⍬ ∇ {Z}←{Conf}run Argument;PRE_test;POST_test;TEST_step;COVER_step;FromSpace load_display_if_not_already_loaded load_salt_scripts_into_current_namespace_if_configured FromSpace←1⊃⎕RSI PRE_test←{} POST_test←{} COVER_step←{} :If 0≠⎕NC'Conf' :If Conf has'cover_target' PRE_test←{{}⎕PROFILE'start'} POST_test←{{}⎕PROFILE'stop'} :EndIf :EndIf :If is_function Argument TEST_step←single_function_test_function COVER_file←Argument,'_coverage.html' :ElseIf is_list_of_functions Argument TEST_step←list_of_functions_test_function COVER_file←'list_coverage.html' :ElseIf is_file Argument TEST_step←file_test_function COVER_file←(get_file_name Argument),'_coverage.html' :ElseIf is_dir Argument test_files←test_files_in_dir Argument TEST_step←test_dir_function Argument←test_files :EndIf :If 0≠⎕NC'Conf' :If Conf has'cover_target' COVER_step←{Conf,←⊂('cover_file'COVER_file) generate_coverage_page Conf} :EndIf :EndIf PRE_test ⍬ Z←FromSpace TEST_step Argument POST_test ⍬ COVER_step ⍬ ∇ ∇ load_display_if_not_already_loaded :If 0=⎕NC'#.DISPLAY' 'DISPLAY'#.⎕CY'display' :EndIf ∇ ∇ load_salt_scripts_into_current_namespace_if_configured :If 0≠⎕NC'#.UT.appdir' :If ⍬≢#.UT.appdir ⎕SE.SALT.Load #.UT.appdir,'src/*.dyalog -target=#' ⎕SE.SALT.Load #.UT.appdir,'test/*.dyalog -target=#' :EndIf :EndIf ∇ ∇ Z←FromSpace single_function_test_function TestName Z←run_ut FromSpace TestName ∇ ∇ Z←FromSpace list_of_functions_test_function ListOfNames;t t←⎕TS Z←run_ut¨{FromSpace ⍵}¨ListOfNames t←⎕TS-t ('Test execution report')print_passed_crashed_failed Z t ∇ ∇ Z←FromSpace file_test_function FilePath;FileNS;Functions;TestFunctions;t FileNS←⎕SE.SALT.Load FilePath,' -target=#' Functions←↓FileNS.⎕NL 3 TestFunctions←(is_test¨Functions)/Functions :If (0/⍬,⊂0/'')≡TestFunctions ⎕←'No test functions found' Z←⍬ :Else t←⎕TS Z←run_ut¨{FileNS ⍵}¨TestFunctions t←⎕TS-t (FilePath,' tests')print_passed_crashed_failed Z t :EndIf ∇ ∇ Z←FromSpace test_dir_function Test_files :If Test_files≡⍬/⍬,⊂'' ⎕←'No test files found' Z←⍬ :Else Z←#.UT.run¨Test_files :EndIf ∇ ∇ Z←get_file_name Argument;separator separator←⊃⌽(Argument∊'/\')/⍳⍴Argument Z←¯7↓separator↓Argument ∇ ∇ generate_coverage_page Conf;ProfileData;CoverResults;HTML ProfileData←⎕PROFILE'data' ToCover←retrieve_coverables¨(⊃'cover_target'in Conf) :If (⍴ToCover)≡(⍴⊂1) ToCover←⊃ToCover :EndIf Representations←get_representation¨ToCover CoverResults←ProfileData∘generate_cover_result¨↓ToCover,[1.5]Representations HTML←generate_html CoverResults Conf write_html_to_page HTML ⎕PROFILE'clear' ∇ ∇ Z←retrieve_coverables Something;nc;functions nc←⎕NC Something :If nc=3 Z←Something :ElseIf nc=9 functions←strip¨↓⍎Something,'.⎕NL 3' Z←{(Something,'.',⍵)}¨functions :EndIf ∇ ∇ Z←strip input Z←(input≠' ')/input ∇ ∇ Z←get_representation Function;nc;rep nc←⎕NC⊂Function :If nc=3.1 rep←↓⎕CR Function rep[1]←⊂'∇',⊃rep[1] rep,←⊂'∇' rep←↑rep :Else rep←⎕CR Function :EndIf Z←rep ∇ ∇ Z←ProfileData generate_cover_result(name representation);Indices;lines;functionlines;covered_lines Indices←({name≡⍵}¨ProfileData[;1])/⍳⍴ProfileData[;1] lines←ProfileData[Indices;2] nc←⎕NC⊂name :If 3.1=nc functionlines←¯2+⍴↓representation :Else functionlines←⊃⍴↓representation :EndIf covered_lines←(⍬∘≢¨lines)/lines Z←(nc lines functionlines covered_lines representation) ∇ ∇ Z←generate_html CoverResults;Covered;Total;Percentage;CoverageText;ColorizedCode;Timestamp;Page Covered←⊃⊃+/{⍴4⊃⍵}¨CoverResults Total←⊃⊃+/{3⊃⍵}¨CoverResults Percentage←100×Covered÷Total CoverageText←'Coverage: ',Percentage,'% (',Covered,'/',Total,')' ColorizedCode←⊃,/{colorize_code_by_coverage ⍵}¨CoverResults Timestamp←generate_timestamp_text Page←⍬ Page,←⊂⍬,'<html>' Page,←⊂⍬,'<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>' Page,←⊂⍬,'<style>pre cov {line-height:80%;}' Page,←⊂⍬,'pre cov {color: green;}' Page,←⊂⍬,'pre uncov {line-height:80%;}' Page,←⊂⍬,'pre uncov {color:red;}</style>' Page,←⊂⍬,CoverageText Page,←⊂⍬,'<pre>' Page,←ColorizedCode Page,←⊂⍬,'</pre>' Page,←Timestamp Page,←⊂⍬,'</html>' Z←Page ∇ ∇ Z←colorize_code_by_coverage CoverResult;Colors;Ends;Code :If 3.1=⊃CoverResult Colors←(2+3⊃CoverResult)⍴⊂'<uncov>' Colors[1]←⊂'' Colors[⍴Colors]←⊂'' Ends←(2+3⊃CoverResult)⍴⊂'</uncov>' Ends[1]←⊂'' Ends[⍴Ends]←⊂'' :Else Colors←(3⊃CoverResult)⍴⊂'<uncov>' Ends←(3⊃CoverResult)⍴⊂'</uncov>' :EndIf Colors[1+4⊃CoverResult]←⊂'<cov>' Ends[1+4⊃CoverResult]←⊂'</cov>' Code←↓5⊃CoverResult Z←Colors,[1.5]Code Z←{⍺,(⎕UCS 13),⍵}/Z,Ends ∇ ∇ Z←generate_timestamp_text;TS;YYMMDD;HHMMSS TS←⎕TS YYMMDD←⊃{⍺,'-',⍵}/3↑TS HHMMSS←⊃{⍺,':',⍵}/3↑3↓TS Z←'Page generated: ',YYMMDD,'|',HHMMSS ∇ ∇ Conf write_html_to_page Page;tie;filename filename←(⊃'cover_out'in Conf),(⊃'cover_file'in Conf) :Trap 22 tie←filename ⎕NTIE 0 filename ⎕NERASE tie filename ⎕NCREATE tie :Else tie←filename ⎕NCREATE 0 :EndTrap Simple_array←⍕⊃,/Page (⎕UCS'UTF-8'⎕UCS Simple_array)⎕NAPPEND tie ∇ ∇ Z←is_function Argument Z←'_TEST'≡¯5↑Argument ∇ ∇ Z←is_list_of_functions Argument Z←2=≡Argument ∇ ∇ Z←is_file Argument Z←'.dyalog'≡¯7↑Argument ∇ ∇ Z←is_dir Argument;attr :If 'Linux'≡5↑⊃'.'⎕WG'APLVersion' Z←'yes'≡⊃⎕CMD'test -d ',Argument,' && echo yes || echo no' :Else 'gfa'⎕NA'I kernel32|GetFileAttributes* <0t' :If Z←¯1≠attr←gfa⊂Argument ⍝ If file exists Z←⊃2 16⊤attr ⍝ Return bit 4 :EndIf :EndIf ∇ ∇ Z←test_files_in_dir Argument :If 'Linux'≡5↑⊃'.'⎕WG'APLVersion' Z←⎕SH'find ',Argument,' -name \*_tests.dyalog' :Else #.⎕CY'files' Z←#.Files.Dir Argument,'\*_tests.dyalog' Z←(Argument,'\')∘,¨Z :EndIf ∇ ∇ Z←run_ut ut_data;returned;crashed;pass;crash;fail;message (returned crashed time)←execute_function ut_data (pass crash fail)←determine_pass_crash_or_fail returned crashed message←determine_message pass fail crashed(2⊃ut_data)returned time print_message_to_screen message Z←(pass crash fail) ∇ ∇ Z←execute_function ut_data;function;t reset_UT_globals function←(⍕(⊃ut_data[1])),'.',⊃ut_data[2] :Trap sac :If 3.2≡⎕NC⊂function t←⎕TS Z←(⍎function,' ⍬')0 t←⎕TS-t :Else t←⎕TS Z←(⍎function)0 t←⎕TS-t :EndIf :Else Z←(↑⎕DM)1 :If exception≢⍬ expect←exception Z[2]←0 t←⎕TS-t :EndIf :EndTrap Z,←⊂t ∇ ∇ reset_UT_globals expect_orig ← expect← ⎕NS⍬ exception←⍬ nexpect_orig ← nexpect← ⎕NS⍬ ∇ ∇ Z←is_test FunctionName;wsIndex wsIndex←FunctionName⍳' ' FunctionName←(wsIndex-1)↑FunctionName Z←'_TEST'≡¯5↑FunctionName ∇ ∇ Heading print_passed_crashed_failed(ArrayRes time) ⎕←'-----------------------------------------' ⎕←Heading ⎕←' ⍋ Passed: ',+/{1⊃⍵}¨ArrayRes ⎕←' ⍟ Crashed: ',+/{2⊃⍵}¨ArrayRes ⎕←' ⍒ Failed: ',+/{3⊃⍵}¨ArrayRes ⎕←' ○ Runtime: ',time[5],'m',time[6],'s',time[7],'ms' ∇ determine_pass_crash_or_fail←{ r c←⍵ ⋄ 0≠c:0 1 0 ⋄ z←(0 0 1)(1 0 0) expect_orig≢expect:(⎕IO+expect≡r)⊃z ⋄ (⎕IO+nexpect≢r)⊃z } ∇ Z←determine_message(pass fail crashed name returned time) :If crashed Z←'CRASHED: 'failure_message name returned :ElseIf pass Z←'Passed ',time[5],'m',time[6],'s',time[7],'ms' :Else Z←'FAILED: 'failure_message name returned :EndIf ∇ ∇ print_message_to_screen message ⎕←message ∇ ∇ Z←term_to_text Term;Text;Rows Text←#.DISPLAY Term Rows←1⊃⍴Text Z←(Rows 4⍴''),Text ∇ ∇ Z←Cause failure_message(name returned);hdr;exp;expterm;got;gotterm hdr←Cause,name exp←'Expected' expterm←term_to_text #.UT.expect got←'Got' gotterm←term_to_text returned Z←align_and_join_message_parts hdr exp expterm got gotterm ∇ ∇ Z←align_and_join_message_parts Parts;hdr;exp;expterm;got;gotterm;R1;C1;R2;C2;W (hdr exp expterm got gotterm)←Parts (R1 C1)←⍴expterm (R2 C2)←⍴gotterm W←⊃⊃⌈/C1 C2(⍴hdr)(⍴exp)(⍴got) Z←(W↑hdr),[0.5](W↑exp) Z←Z⍪(R1 W↑expterm) Z←Z⍪(W↑got) Z←Z⍪(R2 W↑gotterm) ∇ ∇ Z←confparam in config Z←1↓⊃({confparam≡⊃⍵}¨config)/config ∇ ∇ Z←config has confparam Z←∨/{confparam≡⊃⍵}¨config ∇ :EndNameSpace
Add sample .dyalog file for file type APL
Add sample .dyalog file for file type APL Taken from https://github.com/Gianfrancoalongi/APLUnit/blob/master/UT.dyalog
APL
mit
alitalia/linguist,JJ/linguist,douglas-larocca/linguist,c-lipka/linguist,anhongyue/test222,MostAwesomeDude/linguist,blakeembrey/linguist,Rockyspade/linguist,cybernet14/linguist,FStarLang/linguist,stanhu/linguist,sebgod/linguist,pcantrell/linguist,jjatria/linguist,erkyrath/linguist,CoderXpert/linguist,nburkley/linguist,assimovt/ling-ist,yyx990803/linguist,pchaigno/linguist,Mx7f/linguist,alvarotrigo/linguist,alitalia/linguist,iblech/linguist,FStarLang/linguist,sebgod/linguist,mattn/linguist,assimovt/ling-ist,mwpastore/linguist,christop/linguist,manveru/linguist,adamkaplan/linguist,SRI-CSL/linguist,a0viedo/linguist,whitj00/linguist,erkyrath/linguist,R4PaSs/linguist,PsichiX/linguist,whitj00/linguist,mcandre/linguist,osorgin/linguist,matt40k/linguist,kr/linguist,georgesuperman/linguist,jtbandes/linguist,yyx990803/linguist,yyx990803/linguist,CoderXpert/linguist,ppaulweber/github-linguist,github/linguist,BerkeleyTrue/linguist,stanhu/linguist,0a-/linguist,anhongyue/test222,jjatria/linguist,cybernet14/linguist,pchaigno/linguist,yscho/linguist,hcutler/linguist,ppaulweber/github-linguist,ilyes14/linguist,Rockyspade/linguist,0a-/linguist,cokeboL/linguist,seanders/linguist,jtbandes/linguist,Mx7f/linguist,seanders/linguist,meunierfrederic/octocatlinguist,sagar290/linguist,mwpastore/linguist,sebgod/linguist,JJ/linguist,ilyes14/linguist,davidzchen/linguist,ammaraskar/linguist,github/linguist,hcatlin/linguist,BerkeleyTrue/linguist,davidzchen/linguist,pchaigno/linguist,douglas-larocca/linguist,marcojonker/test,wcandillon/linguist,MahmoudFayed/linguist,cokeboL/linguist,ya7lelkom/linguist,phpsgi/linguist,steventhanna/linguist,github/linguist,R4PaSs/linguist,thejameskyle/linguist,matt40k/linguist,adamkaplan/linguist,c-lipka/linguist,wcandillon/linguist,tschf/linguist,JJ/linguist,nburkley/linguist,thejameskyle/linguist,steventhanna/linguist,github/linguist,JJ/linguist,chiranjeevjain/linguist,a0viedo/linguist,mattn/linguist,hcutler/linguist,jrnold/linguist,hcatlin/linguist,phpsgi/linguist,martynbm/linguist,stanhu/linguist,pchaigno/linguist,SRI-CSL/linguist,PsichiX/linguist,yyx990803/linguist,kyoungrok0517/linguist,MostAwesomeDude/linguist,christop/linguist,tschf/linguist,mcandre/linguist,iblech/linguist,CegepVictoriaville/linguist,jrnold/linguist,georgesuperman/linguist,osorgin/linguist,stanhu/linguist,scttnlsn/linguist,kyoungrok0517/linguist,erkyrath/linguist,erkyrath/linguist,MadcapJake/linguist,MahmoudFayed/linguist,pcantrell/linguist,blakeembrey/linguist,sideci-sample/sideci-sample-linguist,alvarotrigo/linguist,sebgod/linguist,marcojonker/test,chiranjeevjain/linguist,meunierfrederic/octocatlinguist,ya7lelkom/linguist,yscho/linguist,ammaraskar/linguist,bluebear94/linguist,kr/linguist,sagar290/linguist,MadcapJake/linguist,martynbm/linguist,meunierfrederic/octocatlinguist,manveru/linguist,CegepVictoriaville/linguist,bluebear94/linguist,scttnlsn/linguist,sideci-sample/sideci-sample-linguist
0bdc9fa698b18e29e4e1a0c880fb8be8e8a69301
host/SendImessage.applescript
host/SendImessage.applescript
#! /usr/bin/osascript on run argv tell application "Messages" send (item 2 of argv) to buddy (item 1 of argv) of (service 1 whose service type is iMessage) end tell end run
#! /usr/bin/osascript on run argv tell application "Messages" send (item 2 of argv) to buddy (item 1 of argv) of (first service whose service type is iMessage) end tell end run
Use english syntax
Use english syntax
AppleScript
mit
chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator
36c34b538edb8a4e8d5eabb83cdac04078676d91
lib/nehm/applescripts/add_track_to_playlist.applescript
lib/nehm/applescripts/add_track_to_playlist.applescript
on run argv tell application "iTunes" set p to first item of argv set a to (p as POSIX file) add a to playlist (second item of argv) end tell end run
on run argv set posixFile to first item of argv set playlistName to second item of argv tell application "iTunes" set p to posixFile set a to (p as POSIX file) add a to playlist playlistName end tell end run
Add explanation of arguments in AppleScript scripts
Add explanation of arguments in AppleScript scripts
AppleScript
mit
bogem/nehm
1ee633a9f5f3897c095c4bceca23a1c807d37742
AppleScripts/Hammerspoon-scpt/bluetooth_toggle.applescript
AppleScripts/Hammerspoon-scpt/bluetooth_toggle.applescript
-- Symlinked into ~/Library/Services/ dir to be run as an Apple Service -- Using "blueutil" installed at: set blueutilpath to "/usr/local/bin/blueutil" -- Toggle Bluetooth off set sb to last word of (do shell script blueutilpath & " status") if sb is "on" then do shell script blueutilpath & " off" return "Bluetooth is now off" else do shell script blueutilpath & " on" return "Bluetooth is now on" end if
-- Symlinked into ~/Library/Services/ dir to be run as an Apple Service -- Using "blueutil" installed at: set blueutilpath to "/usr/local/bin/blueutil" -- Might work? The blueutil API changed in version 2 set sb to (do shell script blueutilpath) if "Power: 1" in sb then do shell script blueutilpath & " -p off" return "Bluetooth is now off" else do shell script blueutilpath & " -p on" return "Bluetooth is now on" end if
update blueutil version to v ^2
Fix: update blueutil version to v ^2
AppleScript
mit
KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook,KyleKing/My-Programming-Sketchbook
3da4ae8cce298ea5459f61c2cd8e06b7439a1063
support/template.applescript
support/template.applescript
on run (volumeName) tell application "Finder" tell disk (volumeName as string) open set theXOrigin to WINX set theYOrigin to WINY set theWidth to WINW set theHeight to WINH set theBottomRightX to (theXOrigin + theWidth) set theBottomRightY to (theYOrigin + theHeight) set dsStore to "\"" & "/Volumes/" & volumeName & "/" & ".DS_STORE\"" tell container window set current view to icon view set toolbar visible to false set statusbar visible to false set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY} set statusbar visible to false end tell set opts to the icon view options of container window tell opts set icon size to ICON_SIZE set text size to TEXT_SIZE set arrangement to not arranged end tell BACKGROUND_CLAUSE -- Positioning POSITION_CLAUSE -- Hiding HIDING_CLAUSE -- Application Link Clause APPLICATION_CLAUSE close open update without registering applications -- Force saving of the size delay 1 tell container window set statusbar visible to false set the bounds to {theXOrigin, theYOrigin, theBottomRightX - 10, theBottomRightY - 10} end tell update without registering applications end tell delay 1 tell disk (volumeName as string) tell container window set statusbar visible to false set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY} end tell update without registering applications end tell --give the finder some time to write the .DS_Store file delay 3 set waitTime to 0 set ejectMe to false repeat while ejectMe is false delay 1 set waitTime to waitTime + 1 if (do shell script "[ -f " & dsStore & " ]; echo $?") = "0" then set ejectMe to true end repeat log "waited " & waitTime & " seconds for .DS_STORE to be created." end tell end run
on run (volumeName) tell application "Finder" tell disk (volumeName as string) open set theXOrigin to WINX set theYOrigin to WINY set theWidth to WINW set theHeight to WINH set theBottomRightX to (theXOrigin + theWidth) set theBottomRightY to (theYOrigin + theHeight) set dsStore to "\"" & "/Volumes/" & volumeName & "/" & ".DS_STORE\"" tell container window set current view to icon view set toolbar visible to false set statusbar visible to false set position of every item to {theBottomRightX + 100, 100} set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY} set statusbar visible to false end tell set opts to the icon view options of container window tell opts set icon size to ICON_SIZE set text size to TEXT_SIZE set arrangement to not arranged end tell BACKGROUND_CLAUSE -- Positioning POSITION_CLAUSE -- Hiding HIDING_CLAUSE -- Application Link Clause APPLICATION_CLAUSE close open update without registering applications -- Force saving of the size delay 1 tell container window set statusbar visible to false set the bounds to {theXOrigin, theYOrigin, theBottomRightX - 10, theBottomRightY - 10} end tell update without registering applications end tell delay 1 tell disk (volumeName as string) tell container window set statusbar visible to false set the bounds to {theXOrigin, theYOrigin, theBottomRightX, theBottomRightY} end tell update without registering applications end tell --give the finder some time to write the .DS_Store file delay 3 set waitTime to 0 set ejectMe to false repeat while ejectMe is false delay 1 set waitTime to waitTime + 1 if (do shell script "[ -f " & dsStore & " ]; echo $?") = "0" then set ejectMe to true end repeat log "waited " & waitTime & " seconds for .DS_STORE to be created." end tell end run
Make sure all hidden files are outside the background image
Make sure all hidden files are outside the background image If the user enabled Mac OS X to show hidden files then when mounted the generated DMG package may show some of them within the bounds of the background image. This change makes sure that all items in the DMG package are moved to a position outside the bounds of the background image. The POSITITION_CLAUSE and APPLICATION_CLAUSE that are executed later will still place the app icon and Application correctly.
AppleScript
mit
andreyvit/create-dmg,mrpau/create-dmg,digitalreasoning/create-dmg,strukturag/create-dmg,heavilessrose/create-dmg,andreyvit/create-dmg,heavilessrose/create-dmg,mrpau/create-dmg,heavilessrose/create-dmg,andrey-str/create-dmg,digitalreasoning/create-dmg,andreyvit/create-dmg,mrpau/create-dmg,strukturag/create-dmg,strukturag/create-dmg,andrey-str/create-dmg,andrey-str/create-dmg,digitalreasoning/create-dmg
9c29d52bd0c27f84251adf023ad80993595be743
Release/dmg_growl.applescript
Release/dmg_growl.applescript
on run -- for testing in script editor process_disk_image("Growl", "/Users/evands/growl/Release/Artwork") end run on process_disk_image(volumeName, artPath) tell application "Finder" tell disk volumeName open tell container window set current view to icon view set toolbar visible to false set statusbar visible to false --set the bounds to {30, 50, 579, 600} end tell close set opts to the icon view options of container window tell opts set icon size to 64 set arrangement to not arranged end tell set background picture of opts to file ".background:growlDMGBackground.png" set position of item "Growl.pkg" to {147, 75} set position of item "Extras" to {100, 320} --set position of item "Scripts" to {36, 153} set position of item "Growl Documentation.webloc" to {100, 218} set position of item "Growl version history.webloc" to {275, 218} set position of item "Get more styles.webloc" to {415, 218} set position of item "Uninstall Growl.app" to {415, 320} -- Custom icons my copyIconOfTo(artPath & "/GrowlIcon", "/Volumes/" & volumeName & "/Growl.mpkg") update without registering applications tell container window open set the_window_id to id end tell update without registering applications end tell set bounds of window id the_window_id to {30, 50, 575, 450} --give the finder some time to write the .DS_Store file delay 5 end tell end process_disk_image on copyIconOfTo(aFileOrFolderWithIcon, aFileOrFolder) tell application "Finder" to set f to POSIX file aFileOrFolderWithIcon as alias -- grab the file's icon my CopyOrPaste(f, "c") -- now the icon is in the clipboard tell application "Finder" to set c to POSIX file aFileOrFolder as alias my CopyOrPaste(result, "v") end copyIconOfTo on CopyOrPaste(i, cv) tell application "Finder" activate open information window of i end tell tell application "System Events" to tell process "Finder" to tell window 1 keystroke tab -- select icon button keystroke (cv & "w") using command down (* (copy or paste) + close window *) end tell -- window 1 then process Finder then System Events end CopyOrPaste
on run -- for testing in script editor process_disk_image("Growl", "/Users/evands/growl/Release/Artwork") end run on process_disk_image(volumeName, artPath) tell application "Finder" tell disk volumeName open tell container window set current view to icon view set toolbar visible to false set statusbar visible to false set bounds to {30, 50, 579, 486} end tell close set opts to the icon view options of container window tell opts set icon size to 64 set arrangement to not arranged end tell set background picture of opts to file ".background:growlDMGBackground.png" set position of item "Growl.pkg" to {147, 75} set position of item "Extras" to {100, 320} --set position of item "Scripts" to {36, 153} set position of item "Growl Documentation.webloc" to {100, 218} set position of item "Growl version history.webloc" to {275, 218} set position of item "Get more styles.webloc" to {415, 218} set position of item "Uninstall Growl.app" to {415, 320} -- Custom icons my copyIconOfTo(artPath & "/GrowlIcon", "/Volumes/" & volumeName & "/Growl.mpkg") update without registering applications tell container window open set the_window_id to id end tell update without registering applications end tell set bounds of window id the_window_id to {30, 50, 575, 450} --give the finder some time to write the .DS_Store file delay 5 end tell end process_disk_image on copyIconOfTo(aFileOrFolderWithIcon, aFileOrFolder) tell application "Finder" to set f to POSIX file aFileOrFolderWithIcon as alias -- grab the file's icon my CopyOrPaste(f, "c") -- now the icon is in the clipboard tell application "Finder" to set c to POSIX file aFileOrFolder as alias my CopyOrPaste(result, "v") end copyIconOfTo on CopyOrPaste(i, cv) tell application "Finder" activate open information window of i end tell tell application "System Events" to tell process "Finder" to tell window 1 keystroke tab -- select icon button keystroke (cv & "w") using command down (* (copy or paste) + close window *) end tell -- window 1 then process Finder then System Events end CopyOrPaste
Set the bounds of the disk image volume window. I'm not sure why this was commented out. Not only have I uncommented it, I also changed the value.
Set the bounds of the disk image volume window. I'm not sure why this was commented out. Not only have I uncommented it, I also changed the value.
AppleScript
bsd-3-clause
tectronics/growl,an0nym0u5/growl,tectronics/growl,xhruso00/growl,morganestes/morganestes-growl,ylian/growl,chashion/growl,ylian/growl,nkhorman/archive-growl,an0nym0u5/growl,nagyistoce/growl,chashion/growl,an0nym0u5/growl,SalrJupiter/growl,tectronics/growl,xhruso00/growl,SalrJupiter/growl,nochkin/growl,timbck2/growl,nagyistoce/growl,nagyistoce/growl,tectronics/growl,ylian/growl,chashion/growl,tectronics/growl,nkhorman/archive-growl,SalrJupiter/growl,morganestes/morganestes-growl,nagyistoce/growl,nagyistoce/growl,xhruso00/growl,timbck2/growl,chashion/growl,an0nym0u5/growl,ylian/growl,SalrJupiter/growl,chashion/growl,timbck2/growl,morganestes/morganestes-growl,nagyistoce/growl,morganestes/morganestes-growl,nochkin/growl,nkhorman/archive-growl,timbck2/growl,nochkin/growl,SalrJupiter/growl,nkhorman/archive-growl,nochkin/growl,ylian/growl,timbck2/growl,nkhorman/archive-growl,xhruso00/growl,morganestes/morganestes-growl,tectronics/growl,morganestes/morganestes-growl,an0nym0u5/growl,nochkin/growl,xhruso00/growl,chashion/growl,nkhorman/archive-growl,nochkin/growl,an0nym0u5/growl,timbck2/growl,SalrJupiter/growl,ylian/growl,xhruso00/growl
13e6daaff29d31e342dae59e00f3a1652245e576
bin/spotify.scpt
bin/spotify.scpt
if application "Spotify" is running then tell application "Spotify" if exists current track then set theName to the name of the current track set theArtist to the artist of the current track try return "♫ " & theName & " - " & theArtist on error err end try end if end tell end if
#!/usr/bin/osascript tell application "Spotify" if it is running then if player state is playing then set track_name to name of current track set artist_name to artist of current track if artist_name > 0 # If the track has an artist set and is therefore most likely a song rather than an advert "♫ " & artist_name & " - " & track_name else # If the track doesn't have an artist set and is therefore most likely an advert rather than a song "~ " & track_name end if end if end if end tell
fix spotify
fix spotify
AppleScript
bsd-3-clause
ankoh/dotfiles
da076f89b13cbbf60f0de02c35960cbb536ec958
utils/launch_in_iterm.applescript
utils/launch_in_iterm.applescript
set test_cmd to system attribute "TEST_CMD" tell application "iTerm" activate (* set t to (make new terminal) *) -- make a new terminal -- set myterm to (current terminal) set myterm to (make new terminal) -- talk to the new terminal tell myterm -- make a new session set mysession to launch session "Default" -- set mysession to (make new session at the end of sessions) -- select mysession -- talk to the session tell mysession -- execute a command -- exec command test_cmd write text test_cmd end tell -- we are done talking to the session end tell end tell
-- Updated launcher for iTerm 3 beta set test_cmd to system attribute "TEST_CMD" tell application "iTerm" activate if (count of windows) = 0 then set t to (create window with default profile) else set t to current window end if tell t tell current session write text test_cmd end tell end tell end tell -- legacy iTerm2 code: -- set test_cmd to system attribute "TEST_CMD" -- tell application "iTerm" -- activate -- (* set t to (make new terminal) *) -- -- make a new terminal -- -- set myterm to (current terminal) -- set myterm to (make new terminal) -- -- talk to the new terminal -- tell myterm -- -- make a new session -- set mysession to launch session "Default" -- -- set mysession to (make new session at the end of sessions) -- -- select mysession -- -- talk to the session -- tell mysession -- -- execute a command -- -- exec command test_cmd -- write text test_cmd -- end tell -- we are done talking to the session -- end tell -- end tell
update applescript for iTerm 3 beta
fix(launch_in_iterm): update applescript for iTerm 3 beta
AppleScript
mit
asfaltboy/Sublime-Test-Plier,asfaltboy/Sublime-Test-Plier,asfaltboy/SublimeTestPlier
a249e9637caa7a9c479d05a64ab05f84aa0ab38b
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork (without extension) set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return selectFirstArtworkThatExists({ ¬ (artworkImageFolder & artworkName & ".jpeg"), ¬ (artworkImageFolder & artworkName & ".png")}) of me on error errorMessage log errorMessage end try end getSongArtworkPath -- select the first path (in the given set of artwork paths) that exists on the -- user's local system on selectFirstArtworkThatExists(artworkPaths) tell application "Finder" repeat with artworkPath in artworkPaths if artworkPath exists then return artworkPath as text end if end repeat end tell return defaultIconName end selectFirstArtworkThatExists -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork (without extension) set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return selectFirstArtworkThatExists({ ¬ (artworkImageFolder & artworkName & ".jpeg"), ¬ (artworkImageFolder & artworkName & ".png")}) of me on error errorMessage log errorMessage end try end getSongArtworkPath -- select the first path (in the given set of artwork paths) that exists on the -- user's local system on selectFirstArtworkThatExists(artworkPaths) tell application "Finder" repeat with artworkPath in artworkPaths if artworkPath exists then return artworkPath as text end if end repeat end tell return defaultIconName end selectFirstArtworkThatExists -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
Remove obsolete fileWrite() handler
Remove obsolete fileWrite() handler
AppleScript
mit
caleb531/play-song,caleb531/play-song
77adc261b070ce81c99ade972413bdcc94a7eced
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-2:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & quantityName else set theString to (theNumber as text) & pluralQuantityName end if return theString end quantifyNumber -- encodes XML reserved characters in the given string on encodeXmlChars(theString) set theString to replace("&", "&amp;", theString) set theString to replace("<", "&lt;", theString) set theString to replace(">", "&gt;", theString) set theString to replace("\"", "&quot;", theString) set theString to replace("'", "&apos;", theString) return theString end encodeXmlChars -- decodes XML reserved characters in the given string on decodeXmlChars(theString) set theString to replace("&amp;", "&", theString) set theString to replace("&lt;", "<", theString) set theString to replace("&gt;", ">", theString) set theString to replace("&quot;", "\"", theString) set theString to replace("&apos;", "'", theString) return theString end decodeXmlChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as XML on getResultXml(theResult) -- encode reserved XML characters set resultUid to encodeXmlChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeXmlChars(title of theResult) set resultSubtitle to encodeXmlChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeXmlChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set xml to "<item uid='" & resultUid & "' arg='" & resultUid & "' valid='" & resultValid & "'>" set xml to xml & "<title>" & resultTitle & "</title>" set xml to xml & "<subtitle>" & resultSubtitle & "</subtitle>" set xml to xml & "<icon>" & resultIcon & "</icon>" set xml to xml & "</item>" return xml end getResultXml -- retrieves XML document for Alfred results on getResultListXml() set xml to "<?xml version='1.0'?><items>" repeat with theResult in resultList set xml to xml & getResultXml(theResult) end repeat set xml to xml & "</items>" return xml end getResultListXml -- writes the given content to the given file on fileWrite(theFile, theContent) try set fileRef to open for access theFile with write permission set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeXmlChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeXmlChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeXmlChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & quantityName else set theString to (theNumber as text) & pluralQuantityName end if return theString end quantifyNumber -- encodes XML reserved characters in the given string on encodeXmlChars(theString) set theString to replace("&", "&amp;", theString) set theString to replace("<", "&lt;", theString) set theString to replace(">", "&gt;", theString) set theString to replace("\"", "&quot;", theString) set theString to replace("'", "&apos;", theString) return theString end encodeXmlChars -- decodes XML reserved characters in the given string on decodeXmlChars(theString) set theString to replace("&amp;", "&", theString) set theString to replace("&lt;", "<", theString) set theString to replace("&gt;", ">", theString) set theString to replace("&quot;", "\"", theString) set theString to replace("&apos;", "'", theString) return theString end decodeXmlChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as XML on getResultXml(theResult) -- encode reserved XML characters set resultUid to encodeXmlChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeXmlChars(title of theResult) set resultSubtitle to encodeXmlChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeXmlChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set xml to "<item uid='" & resultUid & "' arg='" & resultUid & "' valid='" & resultValid & "'>" set xml to xml & "<title>" & resultTitle & "</title>" set xml to xml & "<subtitle>" & resultSubtitle & "</subtitle>" set xml to xml & "<icon>" & resultIcon & "</icon>" set xml to xml & "</item>" return xml end getResultXml -- retrieves XML document for Alfred results on getResultListXml() set xml to "<?xml version='1.0'?><items>" repeat with theResult in resultList set xml to xml & getResultXml(theResult) end repeat set xml to xml & "</items>" return xml end getResultListXml -- writes the given content to the given file on fileWrite(theFile, theContent) try set fileRef to open for access theFile with write permission set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeXmlChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeXmlChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeXmlChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
Use Alfred 3 cache folder
Use Alfred 3 cache folder
AppleScript
mit
caleb531/play-song,caleb531/play-song
1ea0ec81dc1f4ebcd8c9ddac8950336bff8bf1a3
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs < resultLimit then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs < resultLimit then set searchSongs to {} if queryType is \"name\" then set searchSongs to (search playlist 2 for query only songs) else if queryType is not \"genre\" then set searchSongs to (search playlist 2 for query only " & queryType & "s) end if repeat with searchSong in searchSongs set duplicateSong to false repeat with theSong in theSongs if theSong is searchSong then set duplicateSong to true exit repeat end if end repeat if duplicateSong is false then copy searchSong to end of theSongs end if end repeat end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
Fix bug where search would yield duplicate results
Fix bug where search would yield duplicate results
AppleScript
mit
caleb531/play-song,caleb531/play-song
2dd417c1bec7abb4228c407b6fac2bd32a90110b
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & quantityName else set theString to (theNumber as text) & pluralQuantityName end if return theString end quantifyNumber -- encodes XML reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("&", "&amp;", theString) set theString to replace("<", "&lt;", theString) set theString to replace(">", "&gt;", theString) set theString to replace("\"", "&quot;", theString) set theString to replace("'", "&apos;", theString) return theString end encodeFeedbackChars -- decodes XML reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("&amp;", "&", theString) set theString to replace("&lt;", "<", theString) set theString to replace("&gt;", ">", theString) set theString to replace("&quot;", "\"", theString) set theString to replace("&apos;", "'", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as XML on getResultFeedback(theResult) -- encode reserved XML characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set xml to "<item uid='" & resultUid & "' arg='" & resultUid & "' valid='" & resultValid & "'>" set xml to xml & "<title>" & resultTitle & "</title>" set xml to xml & "<subtitle>" & resultSubtitle & "</subtitle>" set xml to xml & "<icon>" & resultIcon & "</icon>" set xml to xml & "</item>" return xml end getResultFeedback -- retrieves XML document for Alfred results on getResultListFeedback() set xml to "<?xml version='1.0'?><items>" repeat with theResult in resultList set xml to xml & getResultFeedback(theResult) end repeat set xml to xml & "</items>" return xml end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & quantityName else set theString to (theNumber as text) & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
Switch from XML to JSON for results feedback
Switch from XML to JSON for results feedback
AppleScript
mit
caleb531/play-song,caleb531/play-song
0efd6d52ba59d8f7cc024ae005d6fabe8680cdbf
macosx/scripts/iTunes/mobile-speakers.applescript
macosx/scripts/iTunes/mobile-speakers.applescript
script remoteSpeakerFinder global the_bwindow, the_state -- Find the remote speakers button on findCorrectButton() tell application "System Events" tell process "iTunes" set the_window to (get window "iTunes") set in_buttons to (get buttons of the_window) repeat with a_button in in_buttons set the_desc to (get description of a_button) if the_desc contains "remote speakers" then return a_button end if end repeat end tell end tell end findCorrectButton on makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" set the_speaker_button to (remoteSpeakerFinder's findCorrectButton()) -- Switch to the speakers in my bedroom set frontmost to true click the_speaker_button key code 119 -- Key Code for "END" key code 76 -- Click "enter" for last menu item delay 2 end tell end tell end makeSpeakerWindowShow on setValueOfComputerSpeaker(value_to_set) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate set the_cbox to (get checkbox 1 of group 1 of row 1 of table 1 of scroll area 1) set the_value to (get value of the_cbox as integer) if the_value is not equal to value_to_set then set value of the_cbox to value_to_set end if end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end setValueOfComputerSpeaker on turnOffAllRemoteSpeakers() makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate repeat with a_row in (get rows of table 1 of scroll area 1) set the_desc to (get description of checkbox 1 of group 1 of a_row) set the_value to (get value of checkbox 1 of group 1 of a_row as integer) if the_desc is not equal to "Computer" and the_value is not equal to 0 then set value of checkbox 1 of group 1 of a_row to 0 end if end repeat end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end turnOffAllRemoteSpeakers on turnOnGivenSpeakerName(speaker_name) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate repeat with a_row in (get rows of table 1 of scroll area 1) set the_desc to (get description of checkbox 1 of group 1 of a_row) set the_value to (get value of checkbox 1 of group 1 of a_row as integer) if the_desc is equal to speaker_name and the_value is not equal to 1 then set value of checkbox 1 of group 1 of a_row to 0 delay 5 end if end repeat end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end turnOnGivenSpeakerName on setRemoteSpeakersTo(speaker_name) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" -- Flip the right checkboxes tell (get window "Multiple Speakers") activate tell table 1 of scroll area 1 activate set did_activate_correct_speaker to 0 set computer_speaker to null repeat with i from 1 to (count of every row) tell group 1 of row i activate set the_desc to (description of checkbox 1) set the_value to (value of checkbox 1 as integer) if the_desc = "Computer" then set computer_speaker to (get checkbox 1) if the_value = 0 then click checkbox 1 delay 10 end if else if the_desc = speaker_name then set did_activate_correct_speaker to 1 if the_value = 0 then click checkbox 1 delay 10 end if else if the_value = 1 then click checkbox 1 delay 10 end if end tell end repeat -- Turn off the computer speakers if did_activate_correct_speaker = 1 then click computer_speaker delay 10 end if end tell end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end setRemoteSpeakersTo on prepareWindow() tell application "iTunes" set the_bwindow to (get first browser window) set the_state to (get minimized of the_bwindow) set visible of the_bwindow to true set minimized of the_bwindow to false end tell end prepareWindow on resetWindow() tell application "iTunes" -- Return window to previous state set minimized of the_bwindow to the_state end tell end resetWindow end script on run (argv) tell application "iTunes" to stop set speaker_name to (get item 1 of argv) remoteSpeakerFinder's prepareWindow() remoteSpeakerFinder's setValueOfComputerSpeaker(1) remoteSpeakerFinder's turnOffAllRemoteSpeakers() if speaker_name is not equal to "Computer" then remoteSpeakerFinder's turnOnGivenSpeakerName(speaker_name) remoteSpeakerFinder's setValueOfComputerSpeaker(0) end if remoteSpeakerFinder's resetWindow() end run
script remoteSpeakerFinder global the_bwindow, the_state -- Find the remote speakers button on findCorrectButton() tell application "System Events" tell process "iTunes" set the_window to (get window "iTunes") set in_buttons to (get buttons of the_window) repeat with a_button in in_buttons set the_desc to (get description of a_button) if the_desc contains "AirPlay" then return a_button end if end repeat end tell end tell end findCorrectButton on makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" set the_speaker_button to (remoteSpeakerFinder's findCorrectButton()) -- Switch to the speakers in my bedroom set frontmost to true click the_speaker_button key code 119 -- Key Code for "END" key code 76 -- Click "enter" for last menu item delay 2 end tell end tell end makeSpeakerWindowShow on setValueOfComputerSpeaker(value_to_set) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate set the_cbox to (get checkbox 1 of group 1 of row 1 of table 1 of scroll area 1) set the_value to (get value of the_cbox as integer) if the_value is not equal to value_to_set then set value of the_cbox to value_to_set end if end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end setValueOfComputerSpeaker on turnOffAllRemoteSpeakers() makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate repeat with a_row in (get rows of table 1 of scroll area 1) set the_desc to (get description of checkbox 1 of group 1 of a_row) set the_value to (get value of checkbox 1 of group 1 of a_row as integer) if the_desc is not equal to "Computer" and the_value is not equal to 0 then set value of checkbox 1 of group 1 of a_row to 0 end if end repeat end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end turnOffAllRemoteSpeakers on turnOnGivenSpeakerName(speaker_name) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" tell window "Multiple Speakers" activate repeat with a_row in (get rows of table 1 of scroll area 1) set the_desc to (get description of checkbox 1 of group 1 of a_row) set the_value to (get value of checkbox 1 of group 1 of a_row as integer) if the_desc is equal to speaker_name and the_value is not equal to 1 then set value of checkbox 1 of group 1 of a_row to 0 delay 5 end if end repeat end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end turnOnGivenSpeakerName on setRemoteSpeakersTo(speaker_name) makeSpeakerWindowShow() tell application "System Events" tell process "iTunes" -- Flip the right checkboxes tell (get window "Multiple Speakers") activate tell table 1 of scroll area 1 activate set did_activate_correct_speaker to 0 set computer_speaker to null repeat with i from 1 to (count of every row) tell group 1 of row i activate set the_desc to (description of checkbox 1) set the_value to (value of checkbox 1 as integer) if the_desc = "Computer" then set computer_speaker to (get checkbox 1) if the_value = 0 then click checkbox 1 delay 10 end if else if the_desc = speaker_name then set did_activate_correct_speaker to 1 if the_value = 0 then click checkbox 1 delay 10 end if else if the_value = 1 then click checkbox 1 delay 10 end if end tell end repeat -- Turn off the computer speakers if did_activate_correct_speaker = 1 then click computer_speaker delay 10 end if end tell end tell end tell end tell tell application "iTunes" to close window "Multiple Speakers" end setRemoteSpeakersTo on prepareWindow() tell application "iTunes" set the_bwindow to (get first browser window) set the_state to (get minimized of the_bwindow) set visible of the_bwindow to true set minimized of the_bwindow to false end tell end prepareWindow on resetWindow() tell application "iTunes" -- Return window to previous state set minimized of the_bwindow to the_state end tell end resetWindow end script on run (argv) tell application "iTunes" to stop set speaker_name to (get item 1 of argv) remoteSpeakerFinder's prepareWindow() remoteSpeakerFinder's setValueOfComputerSpeaker(1) remoteSpeakerFinder's turnOffAllRemoteSpeakers() if speaker_name is not equal to "Computer" then remoteSpeakerFinder's turnOnGivenSpeakerName(speaker_name) remoteSpeakerFinder's setValueOfComputerSpeaker(0) end if remoteSpeakerFinder's resetWindow() end run
Update for iTunes 10.1.2
Update for iTunes 10.1.2
AppleScript
bsd-3-clause
pjones/emacsrc
0dfeb53c383b10b43c2c40b9d9c69e761db91081
QuickStats/QuickStats.applescript
QuickStats/QuickStats.applescript
property pTitle : "OmniFocus: Quick Stats" property pVersion : "2.07.brett" property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2" property pstrMinOSX : "10.9" property pTimeOut : 20 -- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript -- Copyright 2012, 2013, 2014 Robin Trew -- -- Permission is hereby granted, free of charge, -- to any person obtaining a copy of this software -- and associated documentation files (the "Software"), -- to deal in the Software without restriction, -- including without limitation the rights to use, copy, -- modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons -- to whom the Software is furnished to do so, -- subject to the following conditions: -- -- ******* -- The above copyright notice and this permission notice -- shall be included in ALL copies -- or substantial portions of the Software. -- ******* -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Ver 0.8 adds clipboard option to dialogue -- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script -- Ver 1.0 slight simplification of the code -- Ver 1.1 added count of Pending projects -- Ver 1.2 added a count of available actions -- Ver 1.3 added a break-down of unavailable actions -- Ver 1.4 added count of Current projects to complement Pending projects -- ver 1.5 replaced Applescript time function with SQL time expression -- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF --Ver 1.8 Adjusts handling of variant bundle identifiers generally -- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ... property pToClipboard : "Copy list to clipboard" if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath() tell application "Finder" if (version < pstrMinOSX) then display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion return end if end tell if pstrDBPath "" then set inbox_cmd to " select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1); select ' Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0); select ' Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0); select null; " set folders_cmd to " select 'FOLDERS' , count(*) from folder; select ' Active folders', count(*) from folder where effectiveActive=1; select ' Dropped folders', count(*) from folder where effectiveActive=0; select null; " set projects_cmd to " select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0; select ' Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active'); select ' Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive'); select ' Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done'); select ' Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set lists_cmd to " select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1; select ' Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active'); select ' On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive'); select ' Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done'); select ' Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set contexts_cmd to " select 'CONTEXTS', count(*) from context; select ' Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1); select ' On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0; select ' Dropped contexts', count(*) from context where effectiveActive=0; select null; " set groups_cmd to " select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0); select ' Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0); select ' Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0); select null; " set actions_cmd to " select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0); select ' Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0); select ' Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0)); select ' Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and c.effectiveActive= 0; select ' Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1); select ' Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is not null and tp.status='inactive'); select ' Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is not null and c.allowsNextAction=0); select ' Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1; select ' Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=1; select ' Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=0; select ' Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=0; select null; " set commands to inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & actions_cmd set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands) -- try set strList to do shell script strCmd -- on error -- display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return & -- "Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion -- return -- end try tell application id "sevs" activate if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion) is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList end tell else tell application id "sevs" activate display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion end tell end if on FileExists(strPath) (do shell script "test -e " & strPath & " ; echo $?") = "0" end FileExists on GetCachePath() try tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2" on error error "OmniFocus not installed ..." end try end GetCachePath
property pTitle : "OmniFocus: Quick Stats" property pVersion : "2.07.brett" property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2" property pstrMinOSX : "10.9" property pTimeOut : 20 -- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript -- Copyright 2012, 2013, 2014 Robin Trew -- -- Permission is hereby granted, free of charge, -- to any person obtaining a copy of this software -- and associated documentation files (the "Software"), -- to deal in the Software without restriction, -- including without limitation the rights to use, copy, -- modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons -- to whom the Software is furnished to do so, -- subject to the following conditions: -- -- ******* -- The above copyright notice and this permission notice -- shall be included in ALL copies -- or substantial portions of the Software. -- ******* -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Ver 0.8 adds clipboard option to dialogue -- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script -- Ver 1.0 slight simplification of the code -- Ver 1.1 added count of Pending projects -- Ver 1.2 added a count of available actions -- Ver 1.3 added a break-down of unavailable actions -- Ver 1.4 added count of Current projects to complement Pending projects -- ver 1.5 replaced Applescript time function with SQL time expression -- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF --Ver 1.8 Adjusts handling of variant bundle identifiers generally -- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ... property pToClipboard : "Copy list to clipboard" if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath() tell application "Finder" if (version < pstrMinOSX) then display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion return end if end tell if pstrDBPath "" then set inbox_cmd to " select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1); select ' Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0); select ' Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0); select null; " set folders_cmd to " select 'FOLDERS' , count(*) from folder; select ' Active folders', count(*) from folder where effectiveActive=1; select ' Dropped folders', count(*) from folder where effectiveActive=0; select null; " set projects_cmd to " select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0; select ' Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active'); select ' Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive'); select ' Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done'); select ' Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set lists_cmd to " select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1; select ' Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active'); select ' On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive'); select ' Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done'); select ' Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set contexts_cmd to " select 'CONTEXTS', count(*) from context; select ' Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1); select ' On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0; select ' Dropped contexts', count(*) from context where effectiveActive=0; select null; " set groups_cmd to " select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0); select ' Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0); select ' Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0); select null; " set actions_cmd to " select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0); select ' Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0); select ' Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0)); select ' Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and c.effectiveActive= 0; select ' Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1); select ' Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is not null and tp.status='inactive'); select ' Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is not null and c.allowsNextAction=0); select ' Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1; select ' Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=1; select ' Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=0; select ' Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=0; select null; " set summary_cmd to " select 'SUMMARY'; select ' Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null); select ' Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); select ' Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and tp.effectiveFlagged; select ' Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'))); select null; " set commands to inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & actions_cmd & summary_cmd set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands) -- try set strList to do shell script strCmd -- on error -- display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return & -- "Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion -- return -- end try tell application id "sevs" activate if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion) is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList end tell else tell application id "sevs" activate display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion end tell end if on FileExists(strPath) (do shell script "test -e " & strPath & " ; echo $?") = "0" end FileExists on GetCachePath() try tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2" on error error "OmniFocus not installed ..." end try end GetCachePath
add a summary section
add a summary section
AppleScript
apache-2.0
brettporter/omnifocus-tools
03e79121376c1776653bb1a70180cc1f58ef1324
autoload/applescript/iterm.scpt
autoload/applescript/iterm.scpt
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "rspec" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
Change session name to 'rspec'
Change session name to 'rspec'
AppleScript
mit
chautoni/tube.vim
33c600d81ed29d18634ed92dac0f16d9b5f4def1
status.applescript
status.applescript
tell application "Finder" set json_path to file "json.scpt" of folder of (path to me) end tell set json to load script (json_path as alias) on is_running(appName) tell application "System Events" to (name of processes) contains appName end is_running set nl to " " set reply to json's createDict() if is_running("Hermes") then reply's setkv("running", true) set hermesInfo to json's createDict() tell application "Hermes" hermesInfo's setkv("state", playback state as string) hermesInfo's setkv("title", current song's title) hermesInfo's setkv("artist", current song's artist) hermesInfo's setkv("album", current song's album) hermesInfo's setkv("artwork", current song's artwork URL) hermesInfo's setkv("rating", current song's rating) hermesInfo's setkv("position", playback position as integer) hermesInfo's setkv("duration", current song duration as integer) end tell reply's setkv("info", hermesInfo) else reply's setkv("running", false) end if return reply's toJson()
tell application "Finder" set json_path to file "json.scpt" of folder of (path to me) end tell set json to load script (json_path as alias) on is_running(appName) tell application "System Events" to (name of processes) contains appName end is_running set reply to json's createDict() if is_running("Hermes") then reply's setkv("running", true) set hermesInfo to json's createDict() tell application "Hermes" hermesInfo's setkv("state", playback state as string) hermesInfo's setkv("title", current song's title) hermesInfo's setkv("artist", current song's artist) hermesInfo's setkv("album", current song's album) hermesInfo's setkv("artwork", current song's artwork URL) hermesInfo's setkv("rating", current song's rating) hermesInfo's setkv("position", playback position as integer) hermesInfo's setkv("duration", current song duration as integer) end tell reply's setkv("info", hermesInfo) else reply's setkv("running", false) end if return reply's toJson()
remove unused newline variable
remove unused newline variable
AppleScript
mit
winny-/HermesRemote,winny-/HermesRemote
a9ec3c8e94c22bdb296970a7f7a4297a80f02d45
bin/viscosity.applescript
bin/viscosity.applescript
#!/usr/bin/osascript tell application "Viscosity" if the state of the first connection is not "Connected" then connect the first connection repeat until state of the first connection is "Connected" delay 1 end repeat end if end tell
#!/usr/bin/osascript try tell application "Viscosity" if the state of the first connection is not "Connected" then connect the first connection repeat until state of the first connection is "Connected" delay 1 end repeat end if end tell on error tell me to quit end try
handle viscosity errors more gracefully
handle viscosity errors more gracefully
AppleScript
mit
kfox/dotfiles,kfox/dotfiles,kfox/dotfiles
7624fbc0053bb4f97f1af4e4ef0d826b470cf435
lib/scripts/get_state.applescript
lib/scripts/get_state.applescript
tell application "Spotify" set cstate to "{" set cstate to cstate & "\"track_id\": \"" & current track's id & "\"" set cstate to cstate & ",\"volume\": " & sound volume set cstate to cstate & ",\"position\": " & player position set cstate to cstate & ",\"state\": \"" & player state & "\"" set cstate to cstate & "}" return cstate end tell
on replace_chars(this_text, search_string, replacement_string) set AppleScript's text item delimiters to the search_string set the item_list to every text item of this_text set AppleScript's text item delimiters to the replacement_string set this_text to the item_list as string set AppleScript's text item delimiters to "" return this_text end replace_chars tell application "Spotify" -- force string coercion and locale format set position to "" & player position set cstate to "{" set cstate to cstate & "\"track_id\": \"" & current track's id & "\"" set cstate to cstate & ",\"volume\": " & sound volume -- replace , with . when locale has , as decimal delimiter set cstate to cstate & ",\"position\": " & my replace_chars(position, ",", ".") set cstate to cstate & ",\"state\": \"" & player state & "\"" set cstate to cstate & "}" return cstate end tell
Fix get state for locales that have commas as decimal delimiters
Fix get state for locales that have commas as decimal delimiters When your current set locale uses "," as decimal delimiter, AppleScript will automatically use this when you convert the number to a string. This will break the JSON parsing for the callback, as "," is invalid when not in quotes.
AppleScript
mit
andrehaveman/spotify-node-applescript
c7f2827b9a9923cf0ce0e07e6762feb40c67941e
Filterer.applescript
Filterer.applescript
on run tell application "BibDesk" try set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning if button returned of alertResult is "OK" then save first document in "Filtered " & (name of first document as string) & ".bib" repeat with thePub in first document's publications set thePub's note to my splitNote(thePub's note) repeat with theFile in thePub's linked files remove theFile from thePub end repeat end repeat save first document end if on error -128 display dialog "User cancelled." end try end tell end run to splitNote(theNoteText) try set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to {"---"} set theParts to every text item of theNoteText if length of theParts is greater than 1 then set outText to text 2 through end of last item of theParts else set outText to "" end if set AppleScript's text item delimiters to oldDelims on error set AppleScript's text item delimiters to oldDelims end try return outText end splitNote
on run tell application "BibDesk" try set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning if button returned of alertResult is "OK" then set theDocument to first document save theDocument set theFile to (theDocument's file) as alias tell application "Finder" set theContainer to (container of theFile) as alias set newFile to make new file with properties {container:theFile, name:"Filtered " & ((name of theDocument) as string)} end tell return save first document in (newFile as file) repeat with thePub in first document's publications set thePub's note to my splitNote(thePub's note) repeat with theFile in thePub's linked files remove theFile from thePub end repeat end repeat save first document end if on error -128 display dialog "User cancelled." end try end tell end run to splitNote(theNoteText) try set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to {"---"} set theParts to every text item of theNoteText if length of theParts is greater than 1 then set outText to (text 2 through end) of last item of theParts else set outText to "" end if set AppleScript's text item delimiters to oldDelims on error set AppleScript's text item delimiters to oldDelims end try return outText end splitNote
Simplify filterer code so it actually works.
Simplify filterer code so it actually works.
AppleScript
mit
kurtraschke/htmlbib,kurtraschke/htmlbib
8caa4cba5542dfb477b6fa61daef1d8a63e01b78
itunes-concatenator/itunes-concatenator/DASAppDelegate.applescript
itunes-concatenator/itunes-concatenator/DASAppDelegate.applescript
-- -- DASAppDelegate.applescript -- itunes-concatenator -- -- Created by David Schlachter on 2014-08-26. -- Copyright (c) 2014 Red Eft Software. All rights reserved. -- -- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays script DASAppDelegate property parent : class "NSObject" global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix -- IBOutlets property window : missing value property trackTable : missing value property catName : missing value property catArtist : missing value property catAlbum : missing value property catComposer : missing value property catGenre : missing value property catTrack : missing value property catTracks : missing value property catDisc : missing value property catDiscs : missing value -- Again, per macscripter, we'll set up bindings for the options property pcatName : "" property pcatArtist : "" property pcatAlbum : "" property pcatComposer : "" property pcatGenre : "" property pcatTrack : "" property pcatTracks : "" property pcatDisc : "" property pcatDiscs : "" -- Empty strings for each file name and location property pEachName : "" property pEachLocation : "" property these_titles : {} property these_files : {} property these_times: {} property the_index: {} property the_pipes: {} property theCounter : "" property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;" on awakeFromNib() -- -- Check for FFMPEG and MP4v2 -- -- (This works, but it's ugly!) -- -- try do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi" on error number error_number display dialog "You must install FFMPEG and MP4v2 to continue. \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG and MP4v2, ensure that they are in your bash path." buttons {"Quit","Install"} default button 2 If button returned of result is "Install" then try tell application "Terminal" -- TODO: This should be cleaner -- Terminal in front, only one window, focus back to the cat'er afterwards set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\";brew install ffmpeg mp4v2;fi" delay 4 repeat delay 0.1 if not busy of newTab then exit repeat end repeat end tell -- TODO: This needs a better test, i.e., check if ffmpeg is actually accessible on the path display dialog "FFMPEG was successfully installed" -- TODO: This should actually work! (Bring us back to the foreground) activate current application on error number error_number display dialog "FFMPEG did not successfully install" end try end If If button returned of result is "Quit" then -- Fix! current application's NSApp's terminate() end If end try end awakeFromNib on btnGetTracks_(sender) -- Code to add iTunes tracks to our list -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/ tell application "iTunes" set these_titles to {} set these_times to {} set these_files to {} set the_index to {} if selection is not {} then -- there ARE tracks selected... set mySelection to selection set i to 1 repeat with aTrack in mySelection if class of aTrack is file track then set end of these_titles to ((name of aTrack) as string) set end of these_times to ((time of aTrack) as string) set end of these_files to (posix path of (get location of aTrack)) set end of the_index to (count of these_titles) -- Get metadata from the first track if i is 1 then set pcatArtist to ((artist of aTrack) as string) set pcatAlbum to ((album of aTrack) as string) set pcatComposer to ((composer of aTrack) as string) set pcatGenre to ((genre of aTrack) as string) set pcatDisc to ((disc number of aTrack) as string) set pcatDiscs to ((disc count of aTrack) as string) end if set i to (i + 1) end if end repeat end if end tell -- Display the songs to be concatenated -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list set olddelimeters to AppleScript's text item delimiters set AppleScript's text item delimiters to "\n" set disp_titles to these_titles as string trackTable's setStringValue_(disp_titles) set AppleScript's text item delimiters to olddelimeters -- Update the default metadata catArtist's setStringValue_(pcatArtist) catAlbum's setStringValue_(pcatAlbum) catComposer's setStringValue_(pcatComposer) catGenre's setStringValue_(pcatGenre) catDisc's setStringValue_(pcatDisc) catDiscs's setStringValue_(pcatDiscs) end btnGetTracks_ on btnConcatenate_(sender) set the_pipes to {} repeat with theIndex in the_index -- TODO: Needs error checking! -- TODO: We need to check what kind of audio files we have, then adjust accordingly do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text) log ("Processed file number" & theIndex) as text set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text) end repeat -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!) -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files set olddelimeters to AppleScript's text item delimiters set AppleScript's text item delimiters to "|" set disp_thepipes to the_pipes as string do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4") set AppleScript's text item delimiters to olddelimeters -- Log some debugging information log (pcatArtist as string) log (pcatAlbum as string) log (pcatComposer as string) log (pcatGenre as string) log (pcatDisc as string) log (pcatDiscs as string) -- Now let's create the chapter file repeat with theIndex in the_index if theIndex < 2 then do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text) set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string) else set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text) do shell script ("/bin/echo \"" & (theDateStamp as text) & ".000 " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text) log ("Before the addition, theCounter is " & theCounter) as text set theCounter to do shell script (cmdPrefix & "t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text) log ("After the addition, theCounter is " & theCounter) as text end if end repeat -- Chapterize cat.mp4 do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text) -- Clean up do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.mp4" set theCounter to "" end btnConcatenate_ on applicationWillFinishLaunching_(aNotification) -- Insert code here to initialize your application before any files are opened end applicationWillFinishLaunching_ on applicationShouldTerminate_(sender) -- Insert code here to do any housekeeping before your application quits return current application's NSTerminateNow end applicationShouldTerminate_ end script
-- -- DASAppDelegate.applescript -- itunes-concatenator -- -- Created by David Schlachter on 2014-08-26. -- Copyright (c) 2014 Red Eft Software. All rights reserved. -- -- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays script DASAppDelegate property parent : class "NSObject" global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix -- IBOutlets property window : missing value property trackTable : missing value property catName : missing value property catArtist : missing value property catAlbum : missing value property catComposer : missing value property catGenre : missing value property catTrack : missing value property catTracks : missing value property catDisc : missing value property catDiscs : missing value -- Again, per macscripter, we'll set up bindings for the options property pcatName : "" property pcatArtist : "" property pcatAlbum : "" property pcatComposer : "" property pcatGenre : "" property pcatTrack : "" property pcatTracks : "" property pcatDisc : "" property pcatDiscs : "" -- Empty strings for each file name and location property pEachName : "" property pEachLocation : "" property these_titles : {} property these_files : {} property these_times: {} property the_index: {} property the_pipes: {} property theCounter : "" property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;" on awakeFromNib() -- -- Check for FFMPEG and MP4v2 -- -- (This works, but it's ugly!) -- -- try do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi" on error number error_number display dialog "You must install FFMPEG and MP4v2 to continue. \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG and MP4v2, ensure that they are in your bash path." buttons {"Quit","Install"} default button 2 If button returned of result is "Install" then try tell application "Terminal" -- TODO: This should be cleaner -- Terminal in front, only one window, focus back to the cat'er afterwards set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\";brew install ffmpeg mp4v2;fi" delay 4 repeat delay 0.1 if not busy of newTab then exit repeat end repeat end tell -- TODO: This needs a better test, i.e., check if ffmpeg is actually accessible on the path display dialog "FFMPEG was successfully installed" -- TODO: This should actually work! (Bring us back to the foreground) activate current application on error number error_number display dialog "FFMPEG did not successfully install" end try end If If button returned of result is "Quit" then -- Fix! current application's NSApp's terminate() end If end try end awakeFromNib on btnGetTracks_(sender) -- Code to add iTunes tracks to our list -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/ tell application "iTunes" set these_titles to {} set these_times to {} set these_files to {} set the_index to {} if selection is not {} then -- there ARE tracks selected... set mySelection to selection set i to 1 repeat with aTrack in mySelection if class of aTrack is file track then set end of these_titles to ((name of aTrack) as string) set end of these_times to ((time of aTrack) as string) set end of these_files to (posix path of (get location of aTrack)) set end of the_index to (count of these_titles) -- Get metadata from the first track if i is 1 then set pcatArtist to ((artist of aTrack) as string) set pcatAlbum to ((album of aTrack) as string) set pcatComposer to ((composer of aTrack) as string) set pcatGenre to ((genre of aTrack) as string) set pcatDisc to ((disc number of aTrack) as string) set pcatDiscs to ((disc count of aTrack) as string) end if set i to (i + 1) end if end repeat end if end tell -- Display the songs to be concatenated -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list set olddelimeters to AppleScript's text item delimiters set AppleScript's text item delimiters to "\n" set disp_titles to these_titles as string trackTable's setStringValue_(disp_titles) set AppleScript's text item delimiters to olddelimeters -- Update the default metadata catArtist's setStringValue_(pcatArtist) catAlbum's setStringValue_(pcatAlbum) catComposer's setStringValue_(pcatComposer) catGenre's setStringValue_(pcatGenre) catDisc's setStringValue_(pcatDisc) catDiscs's setStringValue_(pcatDiscs) end btnGetTracks_ on btnConcatenate_(sender) -- Update the metadata variables with the user's input set pcatArtist to catArtist's stringValue() set pcatAlbum to catAlbum's stringValue() set pcatComposer to catComposer's stringValue() set pcatGenre to catGenre's stringValue() set pcatTrack to catTrack's stringValue() set pcatTracks to catTracks's stringValue() set pcatDisc to catDisc's stringValue() set pcatDiscs to catDiscs's stringValue() set the_pipes to {} repeat with theIndex in the_index -- TODO: Needs error checking! -- TODO: We need to check what kind of audio files we have, then adjust accordingly do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text) log ("Processed file number" & theIndex) as text set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text) end repeat -- Run the actual concatenation command in ffmpeg (for mp4/AAC files only!) -- via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files set olddelimeters to AppleScript's text item delimiters set AppleScript's text item delimiters to "|" set disp_thepipes to the_pipes as string do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4") set AppleScript's text item delimiters to olddelimeters -- Now let's create the chapter file repeat with theIndex in the_index if theIndex < 2 then do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/cat.chapters.txt" as text) set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string) else set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text) do shell script ("/bin/echo \"" & (theDateStamp as text) & ".000 " & (item theIndex of these_titles as text) & "\" >> /private/tmp/cat.chapters.txt" as text) log ("Before the addition, theCounter is " & theCounter) as text set theCounter to do shell script (cmdPrefix & "t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text) log ("After the addition, theCounter is " & theCounter) as text end if end repeat -- Chapterize cat.mp4 do shell script (cmdPrefix & "mp4chaps -i /private/tmp/cat.mp4" as text) -- Clean up do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.chapters.txt /private/tmp/cat.mp4" set theCounter to "" end btnConcatenate_ on applicationWillFinishLaunching_(aNotification) -- Insert code here to initialize your application before any files are opened end applicationWillFinishLaunching_ on applicationShouldTerminate_(sender) -- Insert code here to do any housekeeping before your application quits return current application's NSTerminateNow end applicationShouldTerminate_ end script
Update the metadata variables from user input
Update the metadata variables from user input
AppleScript
bsd-2-clause
davidschlachter/itunes-concatenator,davidschlachter/itunes-concatenator
f26210bedca6c0696988d55564d89da2a6932fe9
Extras/GrowlAction/main.applescript
Extras/GrowlAction/main.applescript
-- main.applescript -- GrowlAction on run {input_items, parameters} set the output_items to {} set the notification_title to (|notificationTitle| of parameters) as string set the notification_description to (|notificationDescription| of parameters) as string set the notification_priority to (priority of parameters) as integer set the notification_sticky to (sticky of parameters) as boolean tell application "GrowlHelperApp" register as application "Automator" all notifications {"Automator notification"} default notifications {"Automator notification"} notify with name "Automator notification" title notification_title description notification_description application name "Automator" sticky notification_sticky priority notification_priority end tell return input_items end run on localized_string(key_string) return localized string key_string in bundle with identifier "com.growl.GrowlAction" end localized_string
-- main.applescript -- GrowlAction on run {input_items, parameters} set the output_items to {} set the notification_title to (|notificationTitle| of parameters) as string set the notification_description to (|notificationDescription| of parameters) as string set the notification_priority to (priority of parameters) as integer set the notification_sticky to (sticky of parameters) as boolean tell application "GrowlHelperApp" register as application "Automator" all notifications {"Automator notification"} default notifications {"Automator notification"} notify with name "Automator notification" title notification_title description notification_description application name "Automator" sticky notification_sticky priority notification_priority end tell return input_items end run
Fix the Automator action. The ?in bundle with identifier? parameter doesn't exist on my 10.5.5 machine (for some reason, even though the AppleScript Studio Release Notes claim it has since Tiger), which breaks compilation of the action's main script. We don't call the function that uses that phantom parameter, anyway, so I fixed the problem by simply axing the function.
Fix the Automator action. The ?in bundle with identifier? parameter doesn't exist on my 10.5.5 machine (for some reason, even though the AppleScript Studio Release Notes claim it has since Tiger), which breaks compilation of the action's main script. We don't call the function that uses that phantom parameter, anyway, so I fixed the problem by simply axing the function.
AppleScript
bsd-3-clause
timbck2/growl,timbck2/growl,coltonfisher/coltonfisher-growl,Shalaco/shalzers-growl,chashion/growl,morganestes/morganestes-growl,Shalaco/shalzers-growl,an0nym0u5/growl,nochkin/growl,nochkin/growl,nagyistoce/growl,coltonfisher/coltonfisher-growl,xhruso00/growl,nagyistoce/growl,morganestes/morganestes-growl,nochkin/growl,SalrJupiter/growl,Shalaco/shalzers-growl,coltonfisher/coltonfisher-growl,ylian/growl,CarlosCD/growl,nkhorman/archive-growl,Shalaco/shalzers-growl,ylian/growl,nagyistoce/growl,nagyistoce/growl,nagyistoce/growl,tectronics/growl,chashion/growl,an0nym0u5/growl,ylian/growl,an0nym0u5/growl,nkhorman/archive-growl,SalrJupiter/growl,timbck2/growl,ylian/growl,Shalaco/shalzers-growl,tectronics/growl,nochkin/growl,nagyistoce/growl,chashion/growl,coltonfisher/coltonfisher-growl,SalrJupiter/growl,Shalaco/shalzers-growl,coltonfisher/coltonfisher-growl,Shalaco/shalzers-growl,xhruso00/growl,doshinirav/doshinirav-myversion,doshinirav/doshinirav-myversion,CarlosCD/growl,nkhorman/archive-growl,morganestes/morganestes-growl,Shalaco/shalzers-growl,morganestes/morganestes-growl,SalrJupiter/growl,Shalaco/shalzers-growl,doshinirav/doshinirav-myversion,tectronics/growl,morganestes/morganestes-growl,CarlosCD/growl,CarlosCD/growl,morganestes/morganestes-growl,timbck2/growl,xhruso00/growl,coltonfisher/coltonfisher-growl,coltonfisher/coltonfisher-growl,SalrJupiter/growl,ylian/growl,timbck2/growl,nkhorman/archive-growl,Shalaco/shalzers-growl,doshinirav/doshinirav-myversion,Shalaco/shalzers-growl,SalrJupiter/growl,an0nym0u5/growl,tectronics/growl,xhruso00/growl,xhruso00/growl,tectronics/growl,tectronics/growl,nochkin/growl,CarlosCD/growl,doshinirav/doshinirav-myversion,ylian/growl,timbck2/growl,chashion/growl,chashion/growl,chashion/growl,nkhorman/archive-growl,doshinirav/doshinirav-myversion,nochkin/growl,an0nym0u5/growl,doshinirav/doshinirav-myversion,an0nym0u5/growl,CarlosCD/growl,nkhorman/archive-growl,CarlosCD/growl,xhruso00/growl
913f8dea1b8fc2b131ac03808701f47c5bd80868
Extras/GrowlAction/main.applescript
Extras/GrowlAction/main.applescript
-- main.applescript -- GrowlAction on run {input_items, parameters} set the output_items to {} set the notification_title to (|notificationTitle| of parameters) as string set the notification_description to (|notificationDescription| of parameters) as string set the notification_priority to (priority of parameters) as integer set the notification_sticky to (sticky of parameters) as boolean tell application "GrowlHelperApp" register as application "Automator" all notifications {"Automator notification"} default notifications {"Automator notification"} notify with name "Automator notification" title notification_title description notification_description application name "Automator" sticky notification_sticky priority notification_priority end tell return input_items end run on localized_string(key_string) return localized string key_string in bundle with identifier "com.growl.GrowlAction" end localized_string
-- main.applescript -- GrowlAction on run {input_items, parameters} set the output_items to {} set the notification_title to (|notificationTitle| of parameters) as string set the notification_description to (|notificationDescription| of parameters) as string set the notification_priority to (priority of parameters) as integer set the notification_sticky to (sticky of parameters) as boolean tell application "GrowlHelperApp" register as application "Automator" all notifications {"Automator notification"} default notifications {"Automator notification"} notify with name "Automator notification" title notification_title description notification_description application name "Automator" sticky notification_sticky priority notification_priority end tell return input_items end run
Fix the Automator action. The “in bundle with identifier” parameter doesn't exist on my 10.5.5 machine (for some reason, even though the AppleScript Studio Release Notes claim it has since Tiger), which breaks compilation of the action's main script. We don't call the function that uses that phantom parameter, anyway, so I fixed the problem by simply axing the function.
Fix the Automator action. The “in bundle with identifier” parameter doesn't exist on my 10.5.5 machine (for some reason, even though the AppleScript Studio Release Notes claim it has since Tiger), which breaks compilation of the action's main script. We don't call the function that uses that phantom parameter, anyway, so I fixed the problem by simply axing the function.
AppleScript
bsd-3-clause
PersonifyInc/growl,PersonifyInc/growl,incbee/Growl,incbee/Growl,PersonifyInc/growl,incbee/Growl,PersonifyInc/growl,incbee/Growl,PersonifyInc/growl,incbee/Growl
1f58ca688fd098222fd21d951ea7aa15e87cf0ea
setup/set-terminal-theme.applescript
setup/set-terminal-theme.applescript
(* This script is adapted from https://github.com/mathiasbynens/dotfiles/blob/master/.macos. I have mainly added more explicit handling of the path to the custom theme file and the ability to set the font. *) tell application "Terminal" local allOpenedWindows local initialOpenedWindows local windowID (* Set the fully qualified path to the .terminal file. We'll need to refer to the theme name separately though. *) set themeName to "Solarized Dark" set themePath to (system attribute "HOME") & "/.config/themes/osx-terminal.app-colors-solarized/" set themeFile to themePath & themeName & ".terminal" (* Set our desired font. *) set fontName to "SauceCodePowerline-Medium" set fontSize to 12 (* Store the IDs of all the open terminal windows. *) set initialOpenedWindows to id of every window (* Open the custom theme so that it gets added to the list of available terminal themes. Note: this will open an additional terminal window. *) do shell script "open '" & themeFile & "'" (* Wait a little bit to ensure that the custom theme is added. *) delay 1 (* Modify the custom theme to set our desired font. *) set font name of settings set themeName to fontName set font size of settings set themeName to fontSize (* Set the custom theme as the default terminal theme. *) set default settings to settings set themeName (* Get the IDs of all the currently opened terminal windows. *) set allOpenedWindows to id of every window repeat with windowID in allOpenedWindows (* Close the additional windows that were opened in order to add the custom theme to the list of terminal themes. *) if initialOpenedWindows does not contain windowID then close (every window whose id is windowID) (* Change the theme for the initial opened terminal windows to remove the need to close them in order for the custom theme to be applied. *) else set current settings of tabs of (every window whose id is windowID) to settings set themeName end if end repeat end tell
(* This script is adapted from https://github.com/mathiasbynens/dotfiles/blob/master/.macos. I have mainly added more explicit handling of the path to the custom theme file and the ability to set the font. *) tell application "Terminal" local allOpenedWindows local initialOpenedWindows local windowID (* Set the fully qualified path to the .terminal file. We'll need to refer to the theme name separately though. *) set themeName to "Solarized Dark" set themePath to (system attribute "HOME") & "/.config/themes/osx-terminal.app-colors-solarized/" set themeFile to themePath & themeName & ".terminal" (* Set our desired font. *) set fontName to "SourceCodePro-Regular" set fontSize to 12 (* Store the IDs of all the open terminal windows. *) set initialOpenedWindows to id of every window (* Open the custom theme so that it gets added to the list of available terminal themes. Note: this will open an additional terminal window. *) do shell script "open '" & themeFile & "'" (* Wait a little bit to ensure that the custom theme is added. *) delay 1 (* Modify the custom theme to set our desired font. *) set font name of settings set themeName to fontName set font size of settings set themeName to fontSize (* Set the custom theme as the default terminal theme. *) set default settings to settings set themeName (* Get the IDs of all the currently opened terminal windows. *) set allOpenedWindows to id of every window repeat with windowID in allOpenedWindows (* Close the additional windows that were opened in order to add the custom theme to the list of terminal themes. *) if initialOpenedWindows does not contain windowID then close (every window whose id is windowID) (* Change the theme for the initial opened terminal windows to remove the need to close them in order for the custom theme to be applied. *) else set current settings of tabs of (every window whose id is windowID) to settings set themeName end if end repeat end tell
Set terminal font to source code pro.
Set terminal font to source code pro.
AppleScript
mit
adriantrunzo/dotfiles
285dc3ae01f3c7aba05dd03136b0520a227a6964
iTerm2FinderButton.app/Contents/Resources/Scripts/main.scpt
iTerm2FinderButton.app/Contents/Resources/Scripts/main.scpt
FasdUAS 1.101.10 k i I 0 openiniterm openIniTerm  o 0 thefolder theFolder O) k(   r  I .Itrmnwwnnullnull o 0t l  O " I! .Itrmsntxnullobj   Text b b mcd n ! 1  strq !n"# "1  psxp #o 0 thefolder theFolder m$$%%;clear; l & &n '( '1   Wcsn (o 0t) )I#( .miscactvnullnull m**ITRMalisH Macintosh HD\H+ iTerm.appbnA Applications\Ag$Macintosh HD:Applications:iTerm.app iTerm.app Macintosh HDApplications/iTerm.app/+, +l,- -i./ .I .aevtoappnull**** /k*0012 1O#34 3Q"567 5r89 8l: :c;< ;n => =m  cfol >l ? ?4 @  cwin @m  <m   alis 9o 0 thefolder theFolder 6R .ascrerr ******** 7r"AB Al C CI DE .earsffdralis afdr Dm  afdmdeskEF  rtyp Fm  alis Bo 0 thefolder theFolder 4mGGMACSalist Macintosh HD\H+ Finder.appw CoreServices\Agvn 6Macintosh HD:System:Library:CoreServices:Finder.app Finder.app Macintosh HD&System/Library/CoreServices/Finder.app/2H HI$*I 0 openiniterm openIniTermIJ Jo%& 0 thefolder theFolderKLMNK 0 openiniterm openIniTerm .aevtoappnull**** 0 thefolder theFolderLOP 0 openiniterm openIniTermQQ 0 thefolder theFolderO 0 thefolder theFolder 0tP *$ .Itrmnwwnnullnull  Wcsn  Text  psxp  strq .Itrmsntxnullobj .miscactvnullnull*&*j EO,*,,%%l UO*j UM/RS .aevtoappnull****RS G  cwin  cfol  alis 0 thefolder theFolder  afdmdesk  rtyp .earsffdralis afdr 0 openiniterm openIniTerm+ *k/,&EWXl EUO*k+ Nd alis` Macintosh HD\H+ zus_parse[ժ Desktop\Ag[e*  Cg+Macintosh HD:Users:lex:Desktop:zus_parse zus_parse Macintosh HDUsers/lex/Desktop/zus_parse/ ascr ޭ
FasdUAS 1.101.10 k i I 0 openiniterm openIniTerm  o 0 thefolder theFolder OH kG   r  1  Crwn o 0t Q * O  I .Itrmntwpnullobj   Ntwp mDefault l  1   Crwn R .ascrerr ******** o 0mg r#* I#( .Itrmnwwnnullnull o 0t!" !O+A#$ #I1@% .Itrmsntxnullobj %&  Text &b3<'( 'b3:)* )m34++,,cd *n49-. -179  strq .n47/0 /157  psxp 0o45 0 thefolder theFolder (m:;1122;clear; $l+.3 3n+.45 41,.  Wcsn 5o+, 0t"6 6IBG .miscactvnullnull m77ITRMalisH Macintosh HD |H+G iTerm.app5q Applications 5FG$Macintosh HD:Applications:iTerm.app iTerm.app Macintosh HDApplications/iTerm.app/89 8l9: :i;< ;I .aevtoappnull**** <k*==>? >O#@A @Q"BCD BrEF ElG GcHI Hn JK Jm  cfol Kl L L4 M  cwin Mm  Im   alis Fo 0 thefolder theFolder CR .ascrerr ******** Dr"NO Nl P PI QR .earsffdralis afdr Qm  afdmdeskRS  rtyp Sm  alis Oo 0 thefolder theFolder AmTTMACSalist Macintosh HD |H+' Finder.appw CoreServices o '&%6Macintosh HD:System:Library:CoreServices:Finder.app Finder.app Macintosh HD&System/Library/CoreServices/Finder.app/?U UI$*V 0 openiniterm openIniTermVW Wo%& 0 thefolder theFolderXYZX 0 openiniterm openIniTerm .aevtoappnull****Y[\ 0 openiniterm openIniTerm]] 0 thefolder theFolder[ 0 thefolder theFolder 0t 0mg\7+1  Crwn  Ntwp .Itrmntwpnullobj 0mg .Itrmnwwnnullnull  Wcsn  Text  psxp  strq .Itrmsntxnullobj .miscactvnullnullIE*,EO*, *l UWX*j EO,*,,%%l UO*j UZ<^_ .aevtoappnull****^_ T  cwin  cfol  alis 0 thefolder theFolder  afdmdesk  rtyp .earsffdralis afdr 0 openiniterm openIniTerm+ *k/,&EWXl EUO*k+ ascr ޭ
Create a new tab when iTerm already has a window, otherwise create a new window
Create a new tab when iTerm already has a window, otherwise create a new window
AppleScript
mit
lexrus/LTFinderButtons
e33f82284f6d4740d517ad38c162de971f99a918
Uninstall.applescript
Uninstall.applescript
property stdout : "" on run set newline to ASCII character 10 set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher.com not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" get the name of every login item if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
property stdout : "" on run set newline to ASCII character 10 set stdout to stdout & " shutdown TotalFinderCrashWatcher ..." & newline try do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges on error set stdout to stdout & " TotalFinderCrashWatcher not running" & newline end try set stdout to stdout & " shutdown Finder ..." & newline try tell application "Finder" to quit on error set stdout to stdout & " Finder was not running prior uninstallation" & newline end try set stdout to stdout & " remove TotalFinder.app from login items ..." & newline try tell application "System Events" get the name of every login item if login item "TotalFinder.app" exists then delete login item "TotalFinder.app" end if end tell on error set stdout to stdout & " Encountered problems when removing TotalFinder.app from login items" end try -- old version set stdout to stdout & " removing the old TotalFinder files (0.8.2 and earlier) ..." & newline try do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges end try try do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges end try try do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges end try -- new version set stdout to stdout & " unload TotalFinder.kext ..." & newline try do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " TotalFinder.kext not loaded" & newline end try set stdout to stdout & " remove TotalFinder.app ..." & newline try do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges on error set stdout to stdout & " unable to remove /Applications/TotalFinder.app" & newline end try set stdout to stdout & " remove TotalFinder.kext ..." & newline try do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges on error set stdout to stdout & " unable to remove /System/Library/Extensions/TotalFinder.kext" & newline end try set stdout to stdout & " remove TotalFinder.osax ..." & newline try do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges on error set stdout to stdout & " unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline end try set stdout to stdout & " enable Finder animations again ..." & newline try do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges on error set stdout to stdout & " unable to enable animations back" & newline end try set stdout to stdout & " hide system files in Finder again ..." & newline try do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges on error set stdout to stdout & " hide system files in Finder back" & newline end try set stdout to stdout & " relaunch Finder ..." & newline try tell application "Finder" to launch on error set stdout to stdout & " failed to relaunch Finder" & newline end try -- at this point Finder should start cleanly and with no signs of TotalFinder -- you may check Events/Replies tab to see if there were no issues with uninstallation stdout -- this is needed for platypus to display output in details window end run
fix a typo in uninstaller message
fix a typo in uninstaller message
AppleScript
bsd-3-clause
binaryage/totalfinder-installer
9da6f2fe6e6562bae4cc99de5a6dad09be1c591f
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "iTunes" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to getPlaylist(playlistId) of me set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is not greater than 1 then return theSongsSorted end if set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is 0 or discCount is 0 then return theSongsSorted end if set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if (disc number of theSong is discIndex or (disc number of theSong is 0 and discIndex is 1)) and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "iTunes" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to getPlaylist(playlistId) of me set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" if length of theSongs is not greater than 1 then return theSongs end if set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is 0 or discCount is 0 then return theSongs end if set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if (disc number of theSong is discIndex or (disc number of theSong is 0 and discIndex is 1)) and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
Simplify return statements in sorting function
Simplify return statements in sorting function
AppleScript
mit
caleb531/play-song,caleb531/play-song
9a8739087010687b52bbbcb65d3c63944973699e
org.hidetake.osx-go-to-bed.applescript
org.hidetake.osx-go-to-bed.applescript
#!/usr/bin/osascript set awake_time to date "08:00:00" set title_head to "Remaining" set description to "You can sleep only" set remain_time to date "0:0" + (awake_time - current date) display notification description with title title_head & " " & time string of remain_time
#!/usr/bin/osascript set awakeTime to date "8:00:00" set {hours: remainHours, minutes: remainMinutes} to (date "0:0") + (awakeTime - (current date)) set messageTitle to "Remaining " & remainHours & " hours " & remainMinutes & " minutes" set messageDescription to "now " & time string of (current date) display notification messageDescription with title messageTitle
Improve message
Improve message
AppleScript
apache-2.0
int128/osx-go-to-bed
f1f26a784aa41da91240b4f36879b96c6905fe21
src/call_with_finder_selection.applescript
src/call_with_finder_selection.applescript
(* Get images in Finder selection, then call the workflow again with the first selected image. If no images are selected, return an error message, which can be passed to a Post Notification action. *) -- The filetypes understood by Google Image Search set imageExtensions to {"jpg", "jpeg", "bmp", "gif", "png"} -- Return list of files selected in Finder whose extensions are -- in imageExtensions on selectedImages() set theImages to {} tell application "Finder" set theSelection to the selection if (the count of theSelection) is greater than 0 then repeat with theFile in theSelection if the name extension of theFile is in my imageExtensions then set the end of theImages to (theFile as alias) end if end repeat end if log ((the count of theImages) as text) & " image(s) selected" end tell return theImages end selectedImages set theImages to my selectedImages() if (count of theImages) is greater than 0 then set theImage to item 1 of theImages set thePath to POSIX path of theImage -- Use the workflow's own external trigger tell application "Alfred 3" to run trigger "Find Similar Images" in workflow "net.deanishe.alfred-google-similar-images" with argument thePath else return "No images selected" end if
(* Get images in Finder selection, then call the workflow again with the first selected image. If no images are selected, return an error message, which can be passed to a Post Notification action. *) -- The filetypes understood by Google Image Search set imageExtensions to {"jpg", "jpeg", "bmp", "gif", "png"} -- Return list of files selected in Finder whose extensions are -- in imageExtensions on selectedImages() set theImages to {} tell application "Finder" set theSelection to the selection if (the count of theSelection) is greater than 0 then repeat with theFile in theSelection if the name extension of theFile is in my imageExtensions then set the end of theImages to (theFile as alias) end if end repeat end if log ((the count of theImages) as text) & " image(s) selected" end tell return theImages end selectedImages set theImages to my selectedImages() if (count of theImages) is greater than 0 then set theImage to item 1 of theImages set thePath to POSIX path of theImage -- Use the workflow's own external trigger tell application "Alfred 4" to run trigger "Find Similar Images" in workflow "net.deanishe.alfred-google-similar-images" with argument thePath else return "No images selected" end if
Update call_with_finder_selection.applescript
Update call_with_finder_selection.applescript
AppleScript
mit
deanishe/alfred-similar-image-search
fe5d7c99a2c3280f665d030d1b58e9d1c724f6da
lib/nehm/applescripts/list_of_playlists.applescript
lib/nehm/applescripts/list_of_playlists.applescript
tell application "iTunes" get name of playlists end tell
tell application "iTunes" get name of playlists end tell
Add newline in list_of_playlists
Add newline in list_of_playlists
AppleScript
mit
bogem/nehm
e866d8e1cf220f51469dbb52679e8931d69d0bcc
tube/autoload/tube/applescript/iterm.applescript
tube/autoload/tube/applescript/iterm.applescript
-- iterm.applescript --- -- this script requires an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try tell mysession write text command end tell end tell end run
-- iterm.applescript --- -- this script requires an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application iTerm2 tell current session of first window write text command end tell end tell end run
Use new iTerm applescript
Use new iTerm applescript
AppleScript
mit
alisnic/tube.vim
ce2d601d2b9e5efafdc3afce6fabbeaf2bd2e534
autoload/tube/applescript/iterm.applescript
autoload/tube/applescript/iterm.applescript
-- iterm.applescript --- -- this script requires an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try tell mysession write text command end tell end tell end run
on run argv set command to (item 1 of argv) tell application iTerm2 set _window to (current window) if _window is equal to missing value then create window with default profile end if tell current window tell current session write text command end tell end tell end tell end run
Update applescript
Update applescript
AppleScript
mit
alisnic/tube.vim
bef22a8743b249a2c66e50049324982a6caddf14
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1.jpeg\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return artworkPath on error errorMessage log errorMessage end try end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork (without extension) set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return selectFirstArtworkThatExists({ ¬ (artworkImageFolder & artworkName & ".jpeg"), ¬ (artworkImageFolder & artworkName & ".png")}) of me on error errorMessage log errorMessage end try end getSongArtworkPath -- select the first path (in the given set of artwork paths) that exists on the -- user's local system on selectFirstArtworkThatExists(artworkPaths) tell application "Finder" repeat with artworkPath in artworkPaths if artworkPath exists then return artworkPath as text end if end repeat end tell return defaultIconName end selectFirstArtworkThatExists -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
Fix bug where some non-Apple Music songs were missing artwork
Fix bug where some non-Apple Music songs were missing artwork The original algorithm assumed that the file extension of every artwork image was always jpeg. However, some songs (which I did not download from Apple Music, coincidentally) happened to have png artwork, and so the algorithm would fail to return the correct artwork path for those songs.
AppleScript
mit
caleb531/play-song,caleb531/play-song
698772ca16b63f60ff287df21abeb88f15b2afe4
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1.jpeg\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return artworkPath on error errorMessage log errorMessage end try end getNativeCachedArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 15 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- -- workflow folders property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text -- album artwork folders property artworkDocsFolder : ((get path to library folder from user domain as text) & "Containers:com.apple.AMPArtworkAgent:Data:Documents") property artworkImageFolder : (artworkDocsFolder & ":artwork:") -- the default icon used for search results without album artwork property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- query path to artwork image file cached natively by Music.app in Catalina on getSongArtworkPath(theSong) try if albumArtEnabled is false then return defaultIconName tell application "Music" -- get persistent ID of song and convert from hexadecimal to decimal (base-10) set hexSongId to persistent ID of theSong set decSongId to (do shell script "echo $((16#" & hexSongId & "))") -- retrieve filename of cached artwork set artworkName to (do shell script ("/usr/bin/sqlite3 " & (POSIX path of artworkDocsFolder) & "/artworkd.sqlite '" & ¬ "select ZHASHSTRING, ZKIND from ZIMAGEINFO where Z_PK = (" & ¬ "(select ZIMAGEINFO from ZSOURCEINFO where Z_PK = (" & ¬ "select ZSOURCEINFO from ZDATABASEITEMINFO where ZPERSISTENTID = " & ¬ decSongId & ")))' | " & ¬ "awk '{split($0,a,\"|\"); print a[1] \"_sk_\" a[2] \"_cid_1.jpeg\"}'")) set artworkPath to (artworkImageFolder & artworkName) end tell return artworkPath on error errorMessage log errorMessage end try end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "Music" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "Music" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "Music" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "Music" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "Music" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "Music" set thePlaylist to getPlaylist(playlistId) of me set playlistSongs to every track of thePlaylist end tell return playlistSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "Music" set genreSongs to every track of playlist 2 whose genre is genreName set artistNames to {} repeat with theSong in genreSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set genreSongs to {} repeat with artistName in artistNames set genreSongs to genreSongs & getArtistSongs(artistName) of me end repeat return genreSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "Music" set artistSongs to every track of playlist 2 whose artist is artistName set albumNames to {} repeat with theSong in artistSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "Music" set albumNames to getArtistAlbums(artistName) of me set artistSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName) set artistSongs to artistSongs & albumSongs end repeat end tell return artistSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "Music" set albumSongs to every track of playlist 2 whose album is albumName end tell return albumSongs end getAlbumSongs -- retrieves the song with the given ID on getSong(songId) tell application "Music" set theSong to first track of playlist 2 whose database ID is songId end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit) tell application \"Music\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query)) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set albumSongs to getAlbumSongs(albumName) queueSongs(albumSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set artistSongs to getArtistSongs(artistName) queueSongs(artistSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set genreSongs to getGenreSongs(genreName) queueSongs(genreSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set playlistSongs to getPlaylistSongs(playlistId) queueSongs(playlistSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unsupported type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
Fix mismatched handler end tag
Fix mismatched handler end tag
AppleScript
mit
caleb531/play-song,caleb531/play-song
c01e12bb3bd74ab1a86cd428ea9eb35415c67c75
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "iTunes" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to getPlaylist(playlistId) of me set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "resources/icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue on getPlaylist(playlistId) tell application "iTunes" return (first playlist whose id is playlistId) end tell end getPlaylist on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to getPlaylist(playlistId) of me set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if (disc number of theSong is discIndex or (disc number of theSong is 0 and discIndex is 1)) and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if length of theSongs is 0 then if queryType is \"name\" then set theSongs to theSongs & (search playlist 2 for query only songs) else if queryType is not \"genre\" then set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s) end if end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if end queue on play(query) clearQueue() queue(query) playQueue() end play
Fix bug where disc number-less songs would be excluded
Fix bug where disc number-less songs would be excluded
AppleScript
mit
caleb531/play-song,caleb531/play-song
d63b1f75ef971489a00339f4ec8af0e4f3113bad
ports/darwin_dmg/adjust_installation_window.scpt
ports/darwin_dmg/adjust_installation_window.scpt
tell application "Finder" tell disk "Rakudo_Star" open set top_left_X to 100 set top_left_Y to 100 set bottom_right_X to 600 set bottom_right_Y to 500 tell container window set current view to icon view set toolbar visible to false set statusbar visible to false set bounds to { top_left_X, top_left_Y, bottom_right_X, bottom_right_Y } end tell make new alias file at container window to POSIX file "/Applications" with properties { name:"Applications" } set opts to the icon view options of container window tell opts set icon size to 128 set text size to 16 set arrangement to not arranged end tell set position of item "Rakudo_Star" to {120, 74} set position of item "Applications" to {360, 74} set position of item "HOW_TO_INSTALL.txt" to {120, 264} delay 5 close delay 5 open delay 5 end tell end tell
tell application "Finder" tell disk "Rakudo" open set top_left_X to 100 set top_left_Y to 100 set bottom_right_X to 600 set bottom_right_Y to 500 tell container window set current view to icon view set toolbar visible to false set statusbar visible to false set bounds to { top_left_X, top_left_Y, bottom_right_X, bottom_right_Y } end tell make new alias file at container window to POSIX file "/Applications" with properties { name:"Applications" } set opts to the icon view options of container window tell opts set icon size to 128 set text size to 16 set arrangement to not arranged end tell set position of item "Rakudo" to {120, 74} set position of item "Applications" to {360, 74} set position of item "HOW_TO_INSTALL.txt" to {120, 264} delay 5 close delay 5 open delay 5 end tell end tell
use Rakudo in applescript too
use Rakudo in applescript too
AppleScript
artistic-2.0
stmuk/star,rakudo/star
bb1f289638bfe60cb9186d571be3619dd900dc2d
library/fmGUI_ManageSecurity/fmGUI_ManageSecurity_Save.applescript
library/fmGUI_ManageSecurity/fmGUI_ManageSecurity_Save.applescript
-- fmGUI_ManageSecurity_Save({fullAccessAccountName:null, fullAccessPassword:null}) -- Daniel A. Shockley, NYHTC -- Close ( and save ) Manage Security (* HISTORY: 1.5 - 2017-10-19 ( eshagdar ): sub-handlers: button clicks, window checks, authentication. 1.4.2 - 2017-08-09 ( eshagdar ): instead of waiting for a set amount of time, wait until the frontmost window is not manage security ( it will either be the confirm full access window, or finished saving ). 1.4.1 - 2017-08-07 ( eshagdar ): added windowWaitUntil handler to execute sample code 1.4 - 2017-07-14 ( eshagdar ): renamed params: fullAccount -> fullAccessAccountName and fullPassword -> fullAccessPassword. wait until windows are gone. 1.3 - 2016-07-20 ( eshagdar ): converted params from list to record 1.2 - parameter as 'prefs' list for now, instead of two parameters. 1.1 - 1.0 - created REQUIRES: fmGUI_AppFrontMost fmGUI_AuthenticateDialog fmGUI_NameOfFrontmostWindow fmGUI_ObjectClick_OkButton windowWaitUntil*) on run fmGUI_ManageSecurity_Save({fullAccessAccountName:"admin", fullAccessPassword:""}) end run -------------------- -- START OF CODE -------------------- on fmGUI_ManageSecurity_Save(prefs) --version 1.5 set defaulPrefs to {fullAccessAccountName:null, fullAccessPassword:null} set prefs to prefs & defaulPrefs set authWindowName to "Confirm Full access Login" set securityWindowName to "Manage Security for" try fmGUI_AppFrontMost() -- save security changes fmGUI_ObjectClick_OkButton({}) -- confirm with full access account if fmGUI_NameOfFrontmostWindow() is equal to authWindowName then fmGUI_AuthenticateDialog({accountName:fullAccessAccountName of prefs, pwd:fullAccessPassword of prefs, windowname:authWindowName}) -- wait until window is gone windowWaitUntil({whichWindow:"front", windowNameTest:"does not start with", windowname:securityWindowName}) return true on error errMsg number errNum error "Couldn't save Manage Security - " & errMsg number errNum end try end fmGUI_ManageSecurity_Save -------------------- -- END OF CODE -------------------- on fmGUI_AppFrontMost() tell application "htcLib" to fmGUI_AppFrontMost() end fmGUI_AppFrontMost on fmGUI_AuthenticateDialog(prefs) tell application "htcLib" to fmGUI_AuthenticateDialog(prefs) end fmGUI_AuthenticateDialog on fmGUI_NameOfFrontmostWindow() tell application "htcLib" to fmGUI_NameOfFrontmostWindow() end fmGUI_NameOfFrontmostWindow on fmGUI_ObjectClick_OkButton(prefs) tell application "htcLib" to fmGUI_ObjectClick_OkButton(prefs) end fmGUI_ObjectClick_OkButton on windowWaitUntil(prefs) tell application "htcLib" to windowWaitUntil(prefs) end windowWaitUntil
-- fmGUI_ManageSecurity_Save({fullAccessAccountName:null, fullAccessPassword:null}) -- Daniel A. Shockley, NYHTC -- Close ( and save ) Manage Security (* HISTORY: 1.5.1 - 2017-10-23 ( eshagdar ): FM16 renamed auth window name, so windw test is 'begins with' instead of 'is' 1.5 - 2017-10-19 ( eshagdar ): sub-handlers: button clicks, window checks, authentication. 1.4.2 - 2017-08-09 ( eshagdar ): instead of waiting for a set amount of time, wait until the frontmost window is not manage security ( it will either be the confirm full access window, or finished saving ). 1.4.1 - 2017-08-07 ( eshagdar ): added windowWaitUntil handler to execute sample code 1.4 - 2017-07-14 ( eshagdar ): renamed params: fullAccount -> fullAccessAccountName and fullPassword -> fullAccessPassword. wait until windows are gone. 1.3 - 2016-07-20 ( eshagdar ): converted params from list to record 1.2 - parameter as 'prefs' list for now, instead of two parameters. 1.1 - 1.0 - created REQUIRES: fmGUI_AppFrontMost fmGUI_AuthenticateDialog fmGUI_NameOfFrontmostWindow fmGUI_ObjectClick_OkButton windowWaitUntil*) on run fmGUI_ManageSecurity_Save({fullAccessAccountName:"admin", fullAccessPassword:""}) end run -------------------- -- START OF CODE -------------------- on fmGUI_ManageSecurity_Save(prefs) --version 1.5.1 set defaulPrefs to {fullAccessAccountName:null, fullAccessPassword:null} set prefs to prefs & defaulPrefs set authWindowName to "Confirm Full access" set securityWindowName to "Manage Security for" try fmGUI_AppFrontMost() -- save security changes fmGUI_ObjectClick_OkButton({}) -- confirm with full access account if fmGUI_NameOfFrontmostWindow() begins with authWindowName then fmGUI_AuthenticateDialog({accountName:fullAccessAccountName of prefs, pwd:fullAccessPassword of prefs, windowname:authWindowName}) -- wait until window is gone windowWaitUntil({whichWindow:"front", windowNameTest:"does not start with", windowname:securityWindowName}) return true on error errMsg number errNum error "Couldn't save Manage Security - " & errMsg number errNum end try end fmGUI_ManageSecurity_Save -------------------- -- END OF CODE -------------------- on fmGUI_AppFrontMost() tell application "htcLib" to fmGUI_AppFrontMost() end fmGUI_AppFrontMost on fmGUI_AuthenticateDialog(prefs) tell application "htcLib" to fmGUI_AuthenticateDialog(prefs) end fmGUI_AuthenticateDialog on fmGUI_NameOfFrontmostWindow() tell application "htcLib" to fmGUI_NameOfFrontmostWindow() end fmGUI_NameOfFrontmostWindow on fmGUI_ObjectClick_OkButton(prefs) tell application "htcLib" to fmGUI_ObjectClick_OkButton(prefs) end fmGUI_ObjectClick_OkButton on windowWaitUntil(prefs) tell application "htcLib" to windowWaitUntil(prefs) end windowWaitUntil
save security dialog window name changed in fm16.
save security dialog window name changed in fm16.
AppleScript
mit
NYHTC/applescript-fm-helper
ffeece1eb5445a75d34edf403f0268d86334516c
TotalFinder.app/Contents/Resources/Scripts/main.applescript
TotalFinder.app/Contents/Resources/Scripts/main.applescript
tell application "Finder" delay 3 -- this delay is important to prevent random "Connection is Invalid -609" AppleScript errors try event BATFinit on error msg number num display dialog " Unable to launch TotalFinder. " & msg & " (" & (num as text) & ")" & " You may visit http://getsatisfaction.com/binaryage to get support on this issue." with icon 0 end try end tell
set lastErrMsg to "Unable to inject TotalFinder" set lastErrCode to -1 set failed to yes set nextDelay to 1 tell application "Finder" set startTime to current date -- under some conditions like system startup the system may be busy delivering apple events -- in this case we may get random "Connection is Invalid -609" AppleScript errors -- solution: we try it multiple times repeat -- increase the delay between individual trials log "delay " & (nextDelay as text) & "..." delay nextDelay set nextDelay to nextDelay + 1 -- try injection try event BATFinit set failed to no exit repeat on error msg number code log "error: " & msg & "(" & (code as text) & ")" set lastErrMsg to msg set lastErrCode to code end try -- make sure we don't repeat this forever, two minutes should be enough if (current date) - startTime is greater than (2 * 60) then exit repeat end repeat if failed is yes then display dialog " Unable to launch TotalFinder. " & lastErrMsg & " (" & (lastErrCode as text) & ")" & " Please email [email protected] to get support on this issue." with icon 0 giving up after 30 end if end tell
make the injector script more robust => repeat injection trials to overcome -609 errors
make the injector script more robust => repeat injection trials to overcome -609 errors
AppleScript
bsd-3-clause
binaryage/totalfinder-installer
56f1069b73f9074b934b403c8068dde1b5efe282
AppleScript/openQnA.scpt
AppleScript/openQnA.scpt
-- http://www-01.ibm.com/support/docview.wss?uid=swg21506026 -- https://github.com/jgstew/tools/blob/master/bash/openQnA.sh -- http://alvinalexander.com/blog/post/mac-os-x/applescript-use-comments tell application "Terminal" if not (exists window 1) then reopen activate do script "/Library/BESAgent/BESAgent.app/Contents/MacOS/QnA -showtypes" in window 1 end tell
-- http://www-01.ibm.com/support/docview.wss?uid=swg21506026 -- https://github.com/jgstew/tools/blob/master/bash/openQnA.sh -- http://alvinalexander.com/blog/post/mac-os-x/applescript-use-comments tell application "Terminal" if not (exists window 1) then reopen activate do script "/Library/BESAgent/BESAgent.app/Contents/MacOS/QnA -showtypes" in window 1 end tell -- http://stackoverflow.com/questions/5288161/converting-to-one-line-applescript -- osascript -e 'tell application "Terminal"' -e 'if not (exists window 1) then reopen' -e 'activate' -e 'do script "/Library/BESAgent/BESAgent.app/Contents/MacOS/QnA -showtypes" in window 1' -e 'end tell'
Update openQnA.scpt
Update openQnA.scpt
AppleScript
mit
jgstew/tools,jgstew/tools,jgstew/tools,jgstew/tools
e05c2c648a2b215c84cd1832023d8368bb31349c
TotalFinder.app/Contents/Resources/Scripts/main.applescript
TotalFinder.app/Contents/Resources/Scripts/main.applescript
tell application "Finder" delay 1 -- this delay is important to prevent random "Connection is Invalid -609" AppleScript errors try event BATFinit on error msg number num display dialog " Unable to launch TotalFinder. " & msg & " (" & (num as text) & ")" & " You may visit http://getsatisfaction.com/binaryage to get support on this issue." with icon 0 end try end tell
tell application "Finder" delay 3 -- this delay is important to prevent random "Connection is Invalid -609" AppleScript errors try event BATFinit on error msg number num display dialog " Unable to launch TotalFinder. " & msg & " (" & (num as text) & ")" & " You may visit http://getsatisfaction.com/binaryage to get support on this issue." with icon 0 end try end tell
increase delay before injection from 1s to 3s this could help some slower systems during system startup
increase delay before injection from 1s to 3s this could help some slower systems during system startup
AppleScript
bsd-3-clause
binaryage/totalfinder-installer
2b6069f41f0ecc505e5690153cc990ae6d7de5ad
autoload/applescript/iterm.scpt
autoload/applescript/iterm.scpt
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "rspec" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" repeat with _terminal in terminals repeat with _session in (every session of _terminal whose name contains "rspec") tell the _session write text command end tell end repeat end repeat end tell end run
Change script for rspec command only
Change script for rspec command only
AppleScript
mit
chautoni/tube.vim
abf78aefb0e57c7fc50194bc0e5b219c6bff32db
filters/playplaylist.applescript
filters/playplaylist.applescript
-- playplaylist filter -- on loadConfig() do shell script "./compile-config.sh" set config to load script alias ((path to library folder from user domain as text) & "Caches:com.runningwithcrayons.Alfred-3:Workflow Data:com.calebevans.playsong:config.scpt") return config end loadConfig on getPlaylistResultListFeedback(query) global config set query to trimWhitespace(query) of config tell application "iTunes" -- retrieve list of playlists matching query (ordered by relevance) set thePlaylists to (get user playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0) if length of thePlaylists < config's resultLimit then set thePlaylists to thePlaylists & (get user playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0) end if if length of thePlaylists < config's resultLimit then set thePlaylists to thePlaylists & (get user playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0) end if if length of thePlaylists > config's resultLimit then set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists end if repeat with thePlaylist in thePlaylists set playlistName to name of thePlaylist set playlistId to id of thePlaylist set songCount to number of tracks in thePlaylist set playlistDuration to time of thePlaylist set theSong to (first track in user playlist playlistName whose kind contains (songDescriptor of config)) set songArtworkPath to getSongArtworkPath(theSong) of config set itemSubtitle to (quantifyNumber(songCount, "song", "songs") of config) & ", " & playlistDuration & " in length" addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config end repeat if config's resultListIsEmpty() then addNoResultsItem(query, "playlist") of config end if end tell return getResultListFeedback() of config end getPlaylistResultListFeedback set config to loadConfig() getPlaylistResultListFeedback("{query}")
-- playplaylist filter -- on loadConfig() do shell script "./compile-config.sh" set config to load script alias ((path to library folder from user domain as text) & "Caches:com.runningwithcrayons.Alfred-3:Workflow Data:com.calebevans.playsong:config.scpt") return config end loadConfig on getPlaylistResultListFeedback(query) global config set query to trimWhitespace(query) of config tell application "iTunes" -- retrieve list of playlists matching query (ordered by relevance) set thePlaylists to (get user playlists whose name starts with query and name is not config's workflowPlaylistName and special kind is none and size is not 0) if length of thePlaylists < config's resultLimit then set thePlaylists to thePlaylists & (get user playlists whose name contains (space & query) and name does not start with query and name is not config's workflowPlaylistName and special kind is none and size is not 0) end if if length of thePlaylists < config's resultLimit then set thePlaylists to thePlaylists & (get user playlists whose name contains query and name does not start with query and name does not contain (space & query) and name is not config's workflowPlaylistName and special kind is none and size is not 0) end if if length of thePlaylists > config's resultLimit then set thePlaylists to items 1 thru (config's resultLimit) of thePlaylists end if repeat with thePlaylist in thePlaylists set playlistName to name of thePlaylist set playlistId to id of thePlaylist set songCount to number of tracks in thePlaylist set playlistDuration to time of thePlaylist try set theSong to (first track in user playlist playlistName whose kind contains (songDescriptor of config)) set songArtworkPath to getSongArtworkPath(theSong) of config set itemSubtitle to (quantifyNumber(songCount, "track", "tracks") of config) & ", " & playlistDuration & " in length" addResult({uid:("playlist-" & playlistId) as text, valid:"yes", title:playlistName, subtitle:itemSubtitle, icon:songArtworkPath}) of config on error number -1728 end try end repeat if config's resultListIsEmpty() then addNoResultsItem(query, "playlist") of config end if end tell return getResultListFeedback() of config end getPlaylistResultListFeedback set config to loadConfig() getPlaylistResultListFeedback("{query}")
Fix error when encountering non-music playlists
Fix error when encountering non-music playlists
AppleScript
mit
caleb531/play-song,caleb531/play-song
e48fd9cf6cc7ceba954a64ecebc7d9eae378b05d
scripts/itermcolors.applescript
scripts/itermcolors.applescript
set dateFormat to "%H" set hour to do shell script "date +" & (quoted form of dateFormat) if hour > 7 and hour < 19 then set tint to "light" else set tint to "dark" end if tell application "iTerm" set t to current terminal tell t set s to current session tell s if tint is equal to "light" then set ansiWhiteColor to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set selected text color to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set cursor_text color to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set ansiBrightWhiteColor to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiGreenColor to {2.9475974609375E+4, 3.54645859375E+4, 1324.3807373047} set ansiBrightBlackColor to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightYellowColor to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set bold color to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiYellowColor to {4.24316015625E+4, 3.0638546875E+4, 1539.0771484375} set ansiBrightRedColor to {4.861141015625E+4, 1.39755361328125E+4, 4818.8168945312} set ansiBrightCyanColor to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set background color to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiBrightGreenColor to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiBlueColor to {8358.9130859375, 3.0320388671875E+4, 5.12689609375E+4} set cursor color to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set ansiBrightMagentaColor to {2.280528515625E+4, 2.22139375E+4, 4.778054296875E+4} set ansiMagentaColor to {5.094621484375E+4, 7079.39453125, 2.8518626953125E+4} set AnsiBlackColor to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiCyanColor to {9620.2333984375, 3.740892578125E+4, 3.44073671875E+4} set selection color to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set ansiBrightBlueColor to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set foreground color to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set ansiRedColor to {5.369084765625E+4, 7104.4169921875, 9270.392578125} else set ansiWhiteColor to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set selected text color to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set cursor_text color to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiBrightWhiteColor to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiGreenColor to {2.9475974609375E+4, 3.54645859375E+4, 1324.3807373047} set ansiBrightBlackColor to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightYellowColor to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set bold color to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set ansiYellowColor to {4.24316015625E+4, 3.0638546875E+4, 1539.0771484375} set ansiBrightRedColor to {4.861141015625E+4, 1.39755361328125E+4, 4818.8168945312} set ansiBrightCyanColor to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set background color to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightGreenColor to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiBlueColor to {8358.9130859375, 3.0320388671875E+4, 5.12689609375E+4} set cursor color to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set ansiBrightMagentaColor to {2.280528515625E+4, 2.22139375E+4, 4.778054296875E+4} set ansiMagentaColor to {5.094621484375E+4, 7079.39453125, 2.8518626953125E+4} set AnsiBlackColor to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiCyanColor to {9620.2333984375, 3.740892578125E+4, 3.44073671875E+4} set selection color to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiBrightBlueColor to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set foreground color to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set ansiRedColor to {5.369084375E+4, 7104.4233398438, 9270.3935546875} end if end tell end tell end tell return
set h to hours of (current date) if (h > 7) and (h < 19) then set tint to "light" else set tint to "dark" end if tell application "iTerm" set t to current terminal tell t set s to current session tell s if tint is "light" then set ansiWhiteColor to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set selected text color to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set cursor_text color to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set ansiBrightWhiteColor to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiGreenColor to {2.9475974609375E+4, 3.54645859375E+4, 1324.3807373047} set ansiBrightBlackColor to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightYellowColor to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set bold color to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiYellowColor to {4.24316015625E+4, 3.0638546875E+4, 1539.0771484375} set ansiBrightRedColor to {4.861141015625E+4, 1.39755361328125E+4, 4818.8168945312} set ansiBrightCyanColor to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set background color to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiBrightGreenColor to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiBlueColor to {8358.9130859375, 3.0320388671875E+4, 5.12689609375E+4} set cursor color to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set ansiBrightMagentaColor to {2.280528515625E+4, 2.22139375E+4, 4.778054296875E+4} set ansiMagentaColor to {5.094621484375E+4, 7079.39453125, 2.8518626953125E+4} set AnsiBlackColor to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiCyanColor to {9620.2333984375, 3.740892578125E+4, 3.44073671875E+4} set selection color to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set ansiBrightBlueColor to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set foreground color to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set ansiRedColor to {5.369084765625E+4, 7104.4169921875, 9270.392578125} else set ansiWhiteColor to {6.003730859375E+4, 5.83269609375E+4, 5.2284546875E+4} set selected text color to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set cursor_text color to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiBrightWhiteColor to {6.48425703125E+4, 6.277885546875E+4, 5.662616015625E+4} set ansiGreenColor to {2.9475974609375E+4, 3.54645859375E+4, 1324.3807373047} set ansiBrightBlackColor to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightYellowColor to {2.1257337890625E+4, 2.6684328125E+4, 2.8737466796875E+4} set bold color to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set ansiYellowColor to {4.24316015625E+4, 3.0638546875E+4, 1539.0771484375} set ansiBrightRedColor to {4.861141015625E+4, 1.39755361328125E+4, 4818.8168945312} set ansiBrightCyanColor to {3.31601796875E+4, 3.70179921875E+4, 3.6937921875E+4} set background color to {0.0, 7722.3891601562, 9941.8388671875} set ansiBrightGreenColor to {1.813483984375E+4, 2.337368359375E+4, 2.50989140625E+4} set ansiBlueColor to {8358.9130859375, 3.0320388671875E+4, 5.12689609375E+4} set cursor color to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set ansiBrightMagentaColor to {2.280528515625E+4, 2.22139375E+4, 4.778054296875E+4} set ansiMagentaColor to {5.094621484375E+4, 7079.39453125, 2.8518626953125E+4} set AnsiBlackColor to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiCyanColor to {9620.2333984375, 3.740892578125E+4, 3.44073671875E+4} set selection color to {0.0, 1.020768359375E+4, 1.2694220703125E+4} set ansiBrightBlueColor to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set foreground color to {2.887342578125E+4, 3.339855859375E+4, 3.38722890625E+4} set ansiRedColor to {5.369084375E+4, 7104.4233398438, 9270.3935546875} end if end tell end tell end tell return
Update iTerm script to fix time issue
Update iTerm script to fix time issue
AppleScript
mit
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
505a0489cbfbacc752a19b4be4d04a9e986994ce
QuickStats/QuickStats.applescript
QuickStats/QuickStats.applescript
property pTitle : "OmniFocus: Quick Stats" property pVersion : "2.07.brett" property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2" property pstrMinOSX : "10.9" property pTimeOut : 20 -- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript -- Copyright 2012, 2013, 2014 Robin Trew -- -- Permission is hereby granted, free of charge, -- to any person obtaining a copy of this software -- and associated documentation files (the "Software"), -- to deal in the Software without restriction, -- including without limitation the rights to use, copy, -- modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons -- to whom the Software is furnished to do so, -- subject to the following conditions: -- -- ******* -- The above copyright notice and this permission notice -- shall be included in ALL copies -- or substantial portions of the Software. -- ******* -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Ver 0.8 adds clipboard option to dialogue -- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script -- Ver 1.0 slight simplification of the code -- Ver 1.1 added count of Pending projects -- Ver 1.2 added a count of available actions -- Ver 1.3 added a break-down of unavailable actions -- Ver 1.4 added count of Current projects to complement Pending projects -- ver 1.5 replaced Applescript time function with SQL time expression -- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF --Ver 1.8 Adjusts handling of variant bundle identifiers generally -- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ... property pToClipboard : "Copy list to clipboard" if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath() tell application "Finder" if (version < pstrMinOSX) then display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion return end if end tell if pstrDBPath "" then set inbox_cmd to " select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1); select ' Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0); select ' Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0); select null; " set folders_cmd to " select 'FOLDERS' , count(*) from folder; select ' Active folders', count(*) from folder where effectiveActive=1; select ' Dropped folders', count(*) from folder where effectiveActive=0; select null; " set projects_cmd to " select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0; select ' Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active'); select ' Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive'); select ' Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done'); select ' Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set lists_cmd to " select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1; select ' Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active'); select ' On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive'); select ' Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done'); select ' Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set contexts_cmd to " select 'CONTEXTS', count(*) from context; select ' Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1); select ' On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0; select ' Dropped contexts', count(*) from context where effectiveActive=0; select null; " set groups_cmd to " select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0); select ' Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0); select ' Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0); select null; " set actions_cmd to " select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0); select ' Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0); select ' Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0)); select ' Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and c.effectiveActive= 0; select ' Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1); select ' Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is not null and tp.status='inactive'); select ' Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is not null and c.allowsNextAction=0); select ' Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1; select ' Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=1; select ' Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=0; select ' Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=0; select null; " set summary_cmd to " select 'SUMMARY'; select ' Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null); select ' Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); select ' Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and tp.effectiveFlagged; select ' Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'))); select null; " set commands to inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & actions_cmd & summary_cmd set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands) -- try set strList to do shell script strCmd -- on error -- display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return & -- "Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion -- return -- end try tell application id "sevs" activate if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion) is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList end tell else tell application id "sevs" activate display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion end tell end if on FileExists(strPath) (do shell script "test -e " & strPath & " ; echo $?") = "0" end FileExists on GetCachePath() try tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2" on error error "OmniFocus not installed ..." end try end GetCachePath
property pTitle : "OmniFocus: Quick Stats" property pVersion : "2.07.brett" property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2" property pstrMinOSX : "10.9" property pTimeOut : 20 -- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript -- Copyright 2012, 2013, 2014 Robin Trew -- -- Permission is hereby granted, free of charge, -- to any person obtaining a copy of this software -- and associated documentation files (the "Software"), -- to deal in the Software without restriction, -- including without limitation the rights to use, copy, -- modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons -- to whom the Software is furnished to do so, -- subject to the following conditions: -- -- ******* -- The above copyright notice and this permission notice -- shall be included in ALL copies -- or substantial portions of the Software. -- ******* -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Ver 0.8 adds clipboard option to dialogue -- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script -- Ver 1.0 slight simplification of the code -- Ver 1.1 added count of Pending projects -- Ver 1.2 added a count of available actions -- Ver 1.3 added a break-down of unavailable actions -- Ver 1.4 added count of Current projects to complement Pending projects -- ver 1.5 replaced Applescript time function with SQL time expression -- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF --Ver 1.8 Adjusts handling of variant bundle identifiers generally -- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ... property pToClipboard : "Copy list to clipboard" if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath() tell application "Finder" if (version < pstrMinOSX) then display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion return end if end tell if pstrDBPath "" then set inbox_cmd to " select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1); select ' Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0); select ' Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0); select null; " set folders_cmd to " select 'FOLDERS' , count(*) from folder; select ' Active folders', count(*) from folder where effectiveActive=1; select ' Dropped folders', count(*) from folder where effectiveActive=0; select null; " set projects_cmd to " select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0; select ' Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active'); select ' Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01'))); select ' On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive'); select ' Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done'); select ' Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set lists_cmd to " select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1; select ' Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active'); select ' On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive'); select ' Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done'); select ' Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0)); select null; " set contexts_cmd to " select 'CONTEXTS', count(*) from context; select ' Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1); select ' On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0; select ' Dropped contexts', count(*) from context where effectiveActive=0; select null; " set groups_cmd to " select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0); select ' Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0); select ' Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0); select null; " set tasks_cmd to " select 'ALL TASKS', count(*) from task; select null; " set actions_cmd to " select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0); select ' Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0); select ' Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0)); select ' Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and c.effectiveActive= 0; select ' Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1); select ' Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is not null and tp.status='inactive'); select ' Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is not null and c.allowsNextAction=0); select ' Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1; select ' Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=1; select ' Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=1 and tp.blockedByFutureStartDate=0; select ' Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.context is null or c.effectiveActive= 1) and (tp.containingProjectInfo is null or tp.status!='inactive') and (tp.context is null or c.allowsNextAction=1) and tp.blocked=0; select null; " set summary_cmd to " select 'SUMMARY'; select ' Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null); select ' Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); select ' Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and tp.effectiveFlagged; select ' Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0)) or containsSingletonActions=0) and (dateCompleted is null) and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1)) and (tp.containingProjectInfo is null or tp.status!='inactive') and tp.blockedByFutureStartDate=0 and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01'))); select null; " set commands to inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & actions_cmd & tasks_cmd & summary_cmd set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands) -- try set strList to do shell script strCmd -- on error -- display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return & -- "Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion -- return -- end try tell application id "sevs" activate if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion) is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList end tell else tell application id "sevs" activate display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion end tell end if on FileExists(strPath) (do shell script "test -e " & strPath & " ; echo $?") = "0" end FileExists on GetCachePath() try tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2" on error error "OmniFocus not installed ..." end try end GetCachePath
add all tasks to stats
add all tasks to stats
AppleScript
apache-2.0
brettporter/omnifocus-tools
da6f742cdf9d345cf699279bcd138ea533548221
recall.applescript
recall.applescript
#!/usr/bin/env osascript set journal to "~/ia/Journal/Journal.md" tell application "Terminal" set lineCount to (do shell script "wc -l < " & journal) as integer set randomLine to (random number from 1 to lineCount) as integer activate do script "vim -c ':call ToggleBackground()' -c ':Goyo' -c '" & randomLine & "' " & journal tell application "System Events" to keystroke "f" using {command down, control down} end tell
#!/usr/bin/env osascript set journal to "~/ia/Journal/Journal.md" tell application "Terminal" set lineCount to (do shell script "wc -l < " & journal) as integer set randomLine to (random number from 1 to lineCount) as integer activate do script "vim -c ':Goyo' -c ':set bg=light' " & journal & ":" & randomLine set current settings of first window to settings set "Solarized Light" tell application "System Events" to keystroke "f" using {command down, control down} end tell
Fix recall script to set background more reliably
Fix recall script to set background more reliably
AppleScript
mit
mk12/scripts,mk12/scripts,mk12/scripts,mk12/scripts
54fd72486a414cd105d6654e7a8e73bd01fde75a
connector-osx-kn.scpt
connector-osx-kn.scpt
-- -- slideshow -- Observe and Control Slideshow Applications -- Copyright (c) 2014 Ralf S. Engelschall <http://engelschall.com> -- -- This Source Code Form is subject to the terms of the Mozilla Public -- License (MPL), version 2.0. If a copy of the MPL was not distributed -- with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -- -- File: connector-osx-keynote.js -- Purpose: connector engine for Apple Keynote under Mac OS X -- Language: AppleScript -- -- utility function on offsetOf(theString, subString) if theString does not contain subString then return 0 end if set stringCharacterCount to (get count of characters in theString) set substringCharacterCount to (get count of characters in subString) set lastCharacter to (stringCharacterCount - substringCharacterCount + 1) repeat with n from 1 to lastCharacter set m to (n + substringCharacterCount) - 1 set currentSubstring to (get characters n thru m of theString) as string if currentSubstring is subString then return n end if end repeat return 0 end offsetOf -- get Apple Keynote current slide on knGetCurSlide() try tell application "Keynote" return (get slide number of current slide of front document) end tell on error errMsg return 0 end try end knGetCurSlide -- get Apple Keynote maximum slide on knGetMaxSlide() try tell application "Keynote" return (get count of slides of front document) end tell on error errMsg return 0 end try end knGetMaxSlide -- get Apple Keynote current slide on knGetSlideInfo() try tell application "Keynote" set thePresentation to front document set slideCount to (get count of slides of thePresentation) set slideInfo to "[ " repeat with slideNum from 1 to slideCount set theSlide to slide slideNum of thePresentation set theNote to "" repeat with theChars in (presenter notes of theSlide) set theText to ("" & (theChars as string) & "") set offStart to my offsetOf(theText, "TK<") if offStart is not 0 then set offStart to (offStart + 3) set tmp to (get characters offStart thru ((get count of characters in theText)) of theText) as string set offEnd to my offsetOf(tmp, ">") if offEnd is not 0 and offENd is not 1 then set theNote to (get characters offStart thru (offStart + (offEnd - 1) - 1) of theText) as string exit repeat end if end if end repeat if slideInfo is "[ " then set slideInfo to (slideInfo & "\"" & theNote & "\"") else set slideInfo to (slideInfo & ", \"" & theNote & "\"") end if end repeat set slideInfo to (slideInfo & " ]") return slideInfo end tell on error errMsg return "[]" end try end knGetSlideInfo -- get Apple Keynote slide titles on knGetSlideTitles() -- try tell application "Keynote" set thePresentation to front document set slideCount to (get count of slides of thePresentation) set slideTitles to "[ " repeat with slideNum from 1 to slideCount set theSlide to slide slideNum of thePresentation set theTitle to object text of default title item of theSlide if slideTitles is "[ " then set slideTitles to (slideTitles & "\"" & theTitle & "\"") else set slideTitles to (slideTitles & ", \"" & theTitle & "\"") end if end repeat set slideTitles to (slideTitles & " ]") return slideTitles end tell -- on error errMsg return 0 -- end try end knGetCurSlide -- control slide show on knSlideShowControl(command, arg) tell application "Keynote" if command is "START" then start (front document) from (slide 1 of front document) else if command is "NEXT" then show next else if command is "GOTO" then show slide (arg as integer) of front document else if command is "PREV" then show previous else if command is "STOP" then stop front document end if end tell end knSlideShowControl -- main procedure on run argv set cmd to item 1 of argv set arg to "" if count of argv is 2 then set arg to item 2 of argv end if if cmd is "STAT" then set curSlide to knGetCurSlide() set maxSlide to knGetMaxSlide() set output to ("{ \"curSlide\": " & curSlide & ", \"maxSlide\": " & maxSlide & " }") else if cmd is "INFO" then set slideInfo to knGetSlideInfo() set output to ("{ \"slideInfo\": " & slideInfo & " }") else if cmd is "TITLES" then set theTitles to knGetSlideTitles() set output to ("{ \"titles\": " & theTitles & " }") else if cmd is "START" or cmd is "NEXT" or cmd is "GOTO" or cmd is "PREV" or cmd is "STOP" then my knSlideShowControl(cmd, arg) set output to "{}" end if copy output to stdout end run
-- -- slideshow -- Observe and Control Slideshow Applications -- Copyright (c) 2014 Ralf S. Engelschall <http://engelschall.com> -- -- This Source Code Form is subject to the terms of the Mozilla Public -- License (MPL), version 2.0. If a copy of the MPL was not distributed -- with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -- -- File: connector-osx-kn.js -- Purpose: connector engine for Apple Keynote 5 under Mac OS X -- Language: AppleScript -- -- utility function on filterText(this_text, allowed_chars) set new_text to "" repeat with this_char in this_text set x to the offset of this_char in allowed_chars if x is not 0 then set new_text to (new_text & this_char) as string end if end repeat return new_text end filterText -- utility function on replaceText(this_text, search_string, replacement_string) set AppleScript's text item delimiters to the search_string set the item_list to every text item of this_text set AppleScript's text item delimiters to the replacement_string set this_text to the item_list as string set AppleScript's text item delimiters to "" return this_text end replace_chars -- utility function on asciiCharset() set charset to " \"'!#$%()*+,-./:;<=>?@[\\]^_{|}~" set charset to (charset & "0123456789") set charset to (charset & "ABCDEFGHIJKLMNOPQRSTUVWXYZ") set charset to (charset & "abcdefghijklmnopqrstuvwxyz") return charset end asciiCharset -- get application state on knGetState() set state to "closed" tell application "System Events" set is_running to (exists (some process whose name is "Keynote")) end tell if is_running then try set state to "running" tell application "Keynote" if playing then set state to "viewing" else if (get count of slides of front document) > 0 then set state to "editing" end if end tell on error errMsg end try end if return state end knGetState -- get Apple Keynote current slide on knGetCurSlide() try tell application "Keynote" if playing then return (get slide number of current slide of front document) else return (get slide number of current slide of front document) end if end tell on error errMsg return 0 end try end knGetCurSlide -- get Apple Keynote maximum slide on knGetMaxSlide() try tell application "Keynote" return (get count of slides of front document) end tell on error errMsg return 0 end try end knGetMaxSlide -- the STATE command on cmdSTATE() set state to knGetState() if state is "closed" then set position to 0 set slides to 0 else set position to knGetCurSlide() set slides to knGetMaxSlide() end if return ("{ \"response\": { " & ¬ "\"state\": \"" & state & "\", " & ¬ "\"position\": " & position & ", " & ¬ "\"slides\": " & slides & " " & ¬ "} }") end cmdSTATE -- the INFO command on cmdINFO() set output to "" if knGetMaxSlide() is 0 then error "still no active presentation" end if tell application "Keynote" set thePresentation to front document set theTitles to "" set theNotes to "" set slideCount to (get count of slides of thePresentation) repeat with slideNum from 1 to slideCount set theSlide to slide slideNum of thePresentation set theTitle to (title of theSlide) as string if theTitles is not "" then set theTitles to (theTitles & ", ") end if set theTitles to (theTitles & "\"" & (my replaceText(theTitle, "\"", "\\\"")) & "\"") set theNote to (notes of theSlide) as string set theNote to (my filterText(theNote, my asciiCharset())) if theNotes is not "" then set theNotes to (theNotes & ", ") end if set theNotes to (theNotes & "\"" & (my replaceText(theNote, "\"", "\\\"")) & "\"") end repeat set theTitles to ("[ " & theTitles & " ]") set theNotes to ("[ " & theNotes & " ]") set output to ("{ \"response\": { \"titles\": " & theTitles & ", \"notes\": " & theNotes & " } }") end tell return output end cmdINFO -- the control commands on cmdCTRL(command, arg) set state to knGetState() if command is "BOOT" then if state is not "closed" then error "application already running" end if tell application "Keynote" activate end tell else if command is "QUIT" then if state is "closed" then error "application already closed" end if tell application "Keynote" quit end tell else if command is "OPEN" then if state is "editing" or state is "viewing" then error "active presentation already existing" end if tell application "Keynote" tell application "Finder" to set thePath to ¬ POSIX file (POSIX path of (container of (path to me) as string) & (arg)) as alias open thePath end tell else if command is "CLOSE" then if state is "closed" or state is "running" then error "still no active presentation" end if tell application "Keynote" close front document end tell else if command is "START" then if state is "closed" or state is "running" then error "still no active presentation" end if if state is "viewing" then error "active presentation already viewing" end if tell application "Keynote" start from (slide 1 of front document) end tell else if command is "STOP" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" stop slideshow (slideshow 1) end tell else if command is "PAUSE" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" activate tell application "System Events" to keystroke "b" end tell else if command is "RESUME" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" activate tell application "System Events" to keystroke "b" end tell else if command is "FIRST" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" show (item 1 of slides of slideshow 1) end tell else if command is "LAST" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" show (item (get count of slides of slideshow 1) of slides of slideshow 1) end tell else if command is "GOTO" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" show (item (arg as integer) of slides of slideshow 1) end tell else if command is "PREV" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" show previous end tell else if command is "NEXT" then if state is not "viewing" then error "no active slideshow" end if tell application "Keynote" show next end tell end if return "{ \"result\": \"OK\" }" end cmdCTRL -- main procedure on run argv set cmd to item 1 of argv set arg to "" if count of argv is 2 then set arg to item 2 of argv end if try if cmd is "STAT" then set output to cmdSTATE() else if cmd is "INFO" then set output to cmdINFO() else if cmd is "BOOT" ¬ or cmd is "QUIT" ¬ or cmd is "OPEN" ¬ or cmd is "CLOSE" ¬ or cmd is "START" ¬ or cmd is "STOP" ¬ or cmd is "PAUSE" ¬ or cmd is "RESUME" ¬ or cmd is "FIRST" ¬ or cmd is "LAST" ¬ or cmd is "GOTO" ¬ or cmd is "PREV" ¬ or cmd is "NEXT" then set output to cmdCTRL(cmd, arg) else set output to "{ \"error\": \"invalid command\" }" end if on error errMsg set output to ("{ \"error\": \"" & errMsg & "\" }") end try copy output to stdout end run
align the Keynote (5) scripting to the PowerPoint variants
align the Keynote (5) scripting to the PowerPoint variants
AppleScript
mpl-2.0
rse/slideshow,rse/slideshow
77d69cb4ba40a92646584137acded2cb0f0752a2
source/Reminders/RemindersNewItem.applescript
source/Reminders/RemindersNewItem.applescript
on sortList(unsortedList) set oldDelimiters to AppleScript's text item delimiters set AppleScript's text item delimiters to (ASCII character 10) set sortedList to paragraphs of (do shell script "echo " & quoted form of (unsortedList as string) & "| sort -d -f") set AppleScript's text item delimiters to oldDelimiters return sortedList end sortList -- sort the list tell application "Reminders" activate get the name of every account set theAccount to name of first account tell account theAccount set allLists to the name of every list end tell end tell set sortedList to sortList(allLists) set theList to first item of sortedList tell application "Reminders" tell account theAccount to set myReminder to (make new reminder at list theList with properties {name:"{popclip text}"}) end tell
tell application "Reminders" activate set theAccount to name of first account tell account theAccount set theList to name of first list set myReminder to (make new reminder at list theList with properties {name:"{popclip text}"}) end tell end tell
revert reminders change
revert reminders change
AppleScript
mit
dreki/PopClip-Extensions,a-b/PopClip-Extensions,a-b/PopClip-Extensions,Kapeli/PopClip-Extensions,dreki/PopClip-Extensions,Kapeli/PopClip-Extensions,onecrayon/PopClip-Extensions,bopo/PopClip-Extensions,chenruixuan/PopClip-Extensions,chenruixuan/PopClip-Extensions,Kapeli/PopClip-Extensions,bopo/PopClip-Extensions,onecrayon/PopClip-Extensions,chenruixuan/PopClip-Extensions,bopo/PopClip-Extensions,Kapeli/PopClip-Extensions,bopo/PopClip-Extensions,a-b/PopClip-Extensions,dreki/PopClip-Extensions,Kapeli/PopClip-Extensions,dreki/PopClip-Extensions,onecrayon/PopClip-Extensions,Kapeli/PopClip-Extensions,bopo/PopClip-Extensions,onecrayon/PopClip-Extensions,onecrayon/PopClip-Extensions,onecrayon/PopClip-Extensions,a-b/PopClip-Extensions,chenruixuan/PopClip-Extensions,a-b/PopClip-Extensions,chenruixuan/PopClip-Extensions,dreki/PopClip-Extensions,chenruixuan/PopClip-Extensions,bopo/PopClip-Extensions,dreki/PopClip-Extensions,a-b/PopClip-Extensions
4f3a6101b7abad5e9052acaea45efb35ff1b21d2
Scripts/reset-simulator.applescript
Scripts/reset-simulator.applescript
tell application "iPhone Simulator" activate end tell tell application "System Events" tell process "iPhone Simulator" tell menu bar 1 tell menu bar item "iOs Simulator" tell menu "iOs Simulator" click menu item "Reset Content and Settings…" end tell end tell end tell tell window 1 click button "Reset" end tell end tell end tell
tell application "iPhone Simulator" activate end tell tell application "System Events" tell process "iPhone Simulator" tell menu bar 1 tell menu bar item "iOs Simulator" tell menu "iOs Simulator" click menu item "Reset Content and Settings…" end tell end tell end tell tell window 1 click button "Reset" end tell end tell end tell
Update Scripts/reset-simulator.applescript
Update Scripts/reset-simulator.applescript add ending new line
AppleScript
mit
blazingcloud/sealant,blazingcloud/sealant,blazingcloud/sealant,blazingcloud/sealant
a4a75d63dfb60cbcb9568081cf922b90651d1a38
keynote.applescript
keynote.applescript
on newPresentation(themeName) tell application "Keynote" activate -- FIXME: Make this selectable? set targetWidth to 1024 -- 1440 <-- higher resolution set targetHeight to 768 -- 1080 <-- higher resolution set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight} set thisDocument to make new document with properties props return name of thisDocument end tell end newPresentation on savePresentation(docname, posixPath) tell application "Keynote" save document named docname in POSIX file posixPath end tell end savePresentation on createSlide(docname, masterSlideName, thisSlideTitle, thisSlideBody) try tell application "Keynote" tell document named docname set thisSlide to make new slide with properties {base slide:master slide masterSlideName} tell thisSlide -- set the transition properties to {transition effect:dissolve, transition duration:defaultTransitionDuration, transition delay:defaultTransitionDelay, automatic transition:defaultAutomaticTransition} if title showing is true then set the object text of the default title item to thisSlideTitle end if if body showing is true then set the object text of the default body item to thisSlideBody end if end tell end tell return thisSlide end tell on error return 0 end try end createSlide on finalize(docname) tell application "Keynote" tell document named docname to delete slide 1 end tell end finalize on themeMasters(docname) -- tell application "Keynote" to get the name of every master slide of thisDocument tell application "Keynote" set names to the name of every master slide of document named docname return names end tell end themeMasters on addImage(docname, filepath) (* FIXME: Use slide ID to adress slide instead of "current slide" *) tell application "Keynote" tell document named docname tell the current slide -- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE: set thisPlaceholderImageItem to image 1 -- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file set macPath to POSIX file filepath as Unicode text set file name of thisPlaceholderImageItem to ¬ alias macPath end tell end tell end tell end addImage
on newPresentation(themeName) tell application "Keynote" activate -- FIXME: Make this selectable? set targetWidth to 1024 -- 1440 <-- higher resolution set targetHeight to 768 -- 1080 <-- higher resolution set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight} set thisDocument to make new document with properties props return name of thisDocument end tell end newPresentation on savePresentation(docname, posixPath) tell application "Keynote" save document named docname in POSIX file posixPath end tell end savePresentation on createSlide(docname, masterSlideName) try tell application "Keynote" tell document named docname set thisSlide to make new slide with properties {base slide:master slide masterSlideName} end tell return thisSlide end tell on error return 0 end try end createSlide on finalize(docname) tell application "Keynote" tell document named docname to delete slide 1 end tell end finalize on themeMasters(docname) -- tell application "Keynote" to get the name of every master slide of thisDocument tell application "Keynote" set names to the name of every master slide of document named docname return names end tell end themeMasters on addImage(docname, filepath) (* FIXME: Use slide ID to adress slide instead of "current slide" *) tell application "Keynote" tell document named docname tell the current slide -- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE: set thisPlaceholderImageItem to image 1 -- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file set macPath to POSIX file filepath as Unicode text set file name of thisPlaceholderImageItem to ¬ alias macPath end tell end tell end tell end addImage on addTitle(docname, thisSlideTitle) (* FIXME: Use slide ID to adress slide instead of "current slide" *) tell application "Keynote" tell document named docname tell the current slide if title showing is true then set the object text of the default title item to thisSlideTitle end if end tell end tell end tell end addTitle on addBody(docname, thisSlideBody) (* FIXME: Use slide ID to adress slide instead of "current slide" *) tell application "Keynote" tell document named docname tell the current slide if body showing is true then set the object text of the default body item to thisSlideBody end if end tell end tell end tell end addTitle
Break up slide creation
Break up slide creation
AppleScript
mit
persquare/md2keynote
03476f629ed575808c641045b0609f9c6378ff0a
javascript/safari-driver/reinstall.scpt
javascript/safari-driver/reinstall.scpt
#!/usr/bin/osascript (* Copyright 2012 Software Freedom Conservancy. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) (* This script can be used to quickly re-install the SafariDriver extension during development. Requirements: - The extension must be manually installed before use - This script must be run from the trunk. *) -- Keep this in sync with the name of the extension in the Info.plist set EXTENSION to "WebDriver" tell application "System Events" set ui_elements_enabled to UI elements enabled end tell if ui_elements_enabled is false then tell application "System Preferences" activate set current pane to pane id "com.apple.preference.universalaccess" display dialog "Please \"Enable access for assistive devices\" " & ¬ "and try again..." error number -128 end tell end if tell application "Safari" to activate tell application "System Events" tell process "Safari" tell menu bar 1 tell menu "Develop" click menu item "Show Extension Builder" delay 1 end tell end tell -- https://discussions.apple.com/thread/2726674?start=0&tstart=0 tell UI element 1 of scroll area 1 of window "Extension Builder" set found_extension to false set tc to (count (groups whose its images is not {})) repeat with i from 1 to tc if exists (static text 1 of group i) then set t_name to name of static text 1 of group i if t_name is EXTENSION then set found_extension to true click button "Reload" of UI element ("ReloadUninstall" & t_name) exit repeat end if end if keystroke (character id 31) delay 0.2 end repeat if found_extension is false then display dialog "Was unable to locate the extension \"" & EXTENSION ¬ & "\"" & return & return ¬ & "It must be manually installed before this script may be used." error number -128 end if end tell end tell end tell tell application "Safari" to quit
#!/usr/bin/osascript (* Copyright 2012 Software Freedom Conservancy. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) (* This script can be used to quickly re-install the SafariDriver extension during development. Requirements: - The extension must be manually installed before use - This script must be run from the trunk. *) -- Keep this in sync with the name of the extension in the Info.plist set EXTENSION to "WebDriver" tell application "System Events" set ui_elements_enabled to UI elements enabled end tell if ui_elements_enabled is false then tell application "System Preferences" activate set current pane to pane id "com.apple.preference.universalaccess" display dialog "Please \"Enable access for assistive devices\" " & ¬ "and try again..." error number -128 end tell end if tell application "Safari" to activate tell application "System Events" tell process "Safari" tell menu bar 1 -- tell menu "Develop" tell menu bar item 8 tell menu 1 -- click menu item "Show Extension Builder" click menu item 7 end tell end tell end tell delay 0.2 -- https://discussions.apple.com/thread/2726674?start=0&tstart=0 -- tell UI element 1 of scroll area 1 of window "Extension Builder" tell UI element 1 of scroll area 1 of window 1 set found_extension to false set tc to (count (groups whose its images is not {})) repeat with i from 1 to tc if exists (static text 1 of group i) then set t_name to name of static text 1 of group i if t_name is EXTENSION then set found_extension to true -- click button "Reload" of UI element ("ReloadUninstall" & t_name) click button 1 of UI element 4 exit repeat end if end if keystroke (character id 31) delay 0.2 end repeat if found_extension is false then display dialog "Was unable to locate the extension \"" & EXTENSION ¬ & "\"" & return & return ¬ & "It must be manually installed before this script may be used." error number -128 end if end tell end tell end tell tell application "Safari" to quit
Make reinstall.scpt system language independent.
JasonLeyba: Make reinstall.scpt system language independent. git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@16964 07704840-8298-11de-bf8c-fd130f914ac9
AppleScript
apache-2.0
winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium
6968f1694181681f5520551bf214152ca4b88cff
resources/config.applescript
resources/config.applescript
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & quantityName else set theString to (theNumber as text) & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
-- core configuration -- -- configurable options -- -- limit number of songs to improve efficiency property resultLimit : 25 -- whether or not to retrieve/display album artwork for each result property albumArtEnabled : true -- workflow parameters -- property homeFolder : (path to home folder as text) property libraryFolder : (path to library folder from user domain as text) property cacheFolder : (libraryFolder & "Caches:") property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred-3:Workflow Data:") property bundleId : "com.calebevans.playsong" property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text property artworkCacheFolderName : "Album Artwork" property artworkCachePath : (workflowCacheFolder & artworkCacheFolderName & ":") property songArtworkNameSep : " | " property defaultIconName : "icon-noartwork.png" -- the name of the playlist used by the workflow for playing songs property workflowPlaylistName : "Alfred Play Song" -- the text used to determine if a track is an audio file property songDescriptor : "audio" -- list of Alfred results property resultList : {} -- replaces substring in string with another substring on replace(replaceThis, replaceWith, theString) set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to replaceThis set strItems to text items of theString set AppleScript's text item delimiters to replaceWith set newString to strItems as text set AppleScript's text item delimiters to oldDelims return newString end replace -- retrieve the plural/singular form of a quantity based on the given number on quantifyNumber(theNumber, quantityName, pluralQuantityName) if theNumber is 1 then set theString to (theNumber as text) & space & quantityName else set theString to (theNumber as text) & space & pluralQuantityName end if return theString end quantifyNumber -- encodes JSON reserved characters in the given string on encodeFeedbackChars(theString) set theString to replace("\\", "\\\\", theString) set theString to replace("\"", "\\\"", theString) return theString end encodeFeedbackChars -- decodes JSON reserved characters in the given string on decodeFeedbackChars(theString) set theString to replace("\\\\", "\\", theString) set theString to replace("\\\"", "\"", theString) return theString end decodeFeedbackChars -- adds Alfred result to result list on addResult(theResult) copy theResult to the end of resultList end addResult -- adds item for "No Results" message on addNoResultsItem(query, queryType) addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName}) end addNoResultsItem on resultListIsFull() return (length of resultList is resultLimit) end resultListIsFull on resultListIsEmpty() return (length of resultList is 0) end resultListIsFull -- builds Alfred result item as JSON on getResultFeedback(theResult) -- encode reserved JSON characters set resultUid to encodeFeedbackChars(uid of theResult) set resultValid to (valid of theResult) as text set resultTitle to encodeFeedbackChars(title of theResult) set resultSubtitle to encodeFeedbackChars(subtitle of theResult) if (icon of theResult) contains ":" then set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult) else set resultIcon to icon of theResult end if set json to "{" set json to json & "\"uid\":\"" & resultUid & "\"," set json to json & "\"arg\":\"" & resultUid & "\"," set json to json & "\"valid\":\"" & resultValid & "\"," set json to json & "\"title\":\"" & resultTitle & "\"," set json to json & "\"subtitle\":\"" & resultSubtitle & "\"," set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}" set json to json & "}" return json end getResultFeedback -- retrieves JSON document for Alfred results on getResultListFeedback() set json to "{\"items\": [" repeat with theResult in resultList set json to json & getResultFeedback(theResult) set json to json & "," end repeat -- remove trailing comma after last item set json to text 1 thru (length of json - 1) of json set json to json & "]}" return json end getResultListFeedback -- writes the given content to the given file on fileWrite(theFile, theContent) set fileRef to open for access theFile with write permission try set eof of fileRef to 0 write theContent to fileRef starting at eof close access fileRef on error close access fileRef end try end fileWrite -- builds path to album art for the given song on getSongArtworkPath(theSong) if albumArtEnabled is false then return defaultIconName tell application "iTunes" set songArtist to artist of theSong set songAlbum to album of theSong -- generate a unique identifier for that album set songArtworkName to (songArtist & songArtworkNameSep & songAlbum) as text -- remove forbidden path characters set songArtworkName to replace(":", "", songArtworkName) of me set songArtworkName to replace("/", "", songArtworkName) of me set songArtworkName to replace(".", "", songArtworkName) of me set songArtworkPath to (artworkCachePath & songArtworkName & ".jpg") end tell tell application "Finder" -- cache artwork if it's not already cached if not (songArtworkPath exists) then tell application "iTunes" set songArtworks to artworks of theSong -- only save artwork if artwork exists for this song if (length of songArtworks) is 0 then -- use default iTunes icon if song has no artwork set songArtworkPath to defaultIconName else -- save artwork to file set songArtwork to data of (item 1 of songArtworks) fileWrite(songArtworkPath, songArtwork) of me end if end tell end if end tell return songArtworkPath end getSongArtworkPath -- creates album artwork cache on createWorkflowPlaylist() tell application "iTunes" if not (user playlist workflowPlaylistName exists) then make new user playlist with properties {name:workflowPlaylistName, shuffle:false} end if end tell end createWorkflowPlaylist on clearQueue() tell application "iTunes" if user playlist workflowPlaylistName exists then delete tracks of user playlist workflowPlaylistName end if end tell end clearQueue on queueSongs(theSongs) tell application "iTunes" repeat with theSong in theSongs duplicate theSong to user playlist workflowPlaylistName end repeat end tell end queueSongs on playQueue() tell application "iTunes" if number of tracks in user playlist workflowPlaylistName is not 0 then play user playlist workflowPlaylistName end if end tell end playQueue -- brings queue into view in iTunes window on focusQueue() tell application "iTunes" reveal user playlist workflowPlaylistName end tell end focusQueue on getPlaylistSongs(playlistId) tell application "iTunes" set thePlaylist to first user playlist whose id is playlistId set theSongs to every track of thePlaylist end tell return theSongs end getPlaylistSongs -- retrieves list of artist names for the given genre on getGenreArtists(genreName) tell application "iTunes" set theSongs to every track of playlist 2 whose genre is genreName and kind contains songDescriptor set artistNames to {} repeat with theSong in theSongs if (artist of theSong) is not in artistNames then set artistNames to artistNames & (artist of theSong) end if end repeat end tell return artistNames end getGenreArtists -- retrieves list of songs within the given genre, sorted by artist on getGenreSongs(genreName) set artistNames to getGenreArtists(genreName) of me set theSongs to {} repeat with artistName in artistNames set theSongs to theSongs & getArtistSongs(artistName) of me end repeat return theSongs end getGenreSongs -- retrieves list of album names for the given artist on getArtistAlbums(artistName) tell application "iTunes" set theSongs to every track of playlist 2 whose artist is artistName and kind contains songDescriptor set albumNames to {} repeat with theSong in theSongs if (album of theSong) is not in albumNames then set albumNames to albumNames & (album of theSong) end if end repeat end tell return albumNames end getArtistAlbums -- retrieves list of songs by the given artist, sorted by album on getArtistSongs(artistName) tell application "iTunes" set albumNames to getArtistAlbums(artistName) of me set theSongs to {} repeat with albumName in albumNames set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName and kind contains songDescriptor) set albumSongs to sortSongsByAlbumOrder(albumSongs) of me set theSongs to theSongs & albumSongs end repeat end tell return theSongs end getArtistSongs -- retrieves list of songs in the given album on getAlbumSongs(albumName) tell application "iTunes" set theSongs to every track of playlist 2 whose album is albumName and kind contains songDescriptor set theSongs to sortSongsByAlbumOrder(theSongs) of me end tell return theSongs end getAlbumSongs -- sorts songs from the same album by track number on sortSongsByAlbumOrder(theSongs) tell application "iTunes" set theSongsSorted to theSongs if length of theSongs is greater than 1 then set trackCount to track count of (item 1 of theSongs) set discCount to disc count of (item 1 of theSongs) if trackCount is not 0 and discCount is not 0 then set theSongsSorted to {} as list repeat with discIndex from 1 to discCount repeat with songIndex from 1 to trackCount repeat with theSong in theSongs if disc number of theSong is discIndex and track number of theSong is songIndex then set nextSong to theSong copy nextSong to the end of theSongsSorted end if end repeat end repeat end repeat end if end if end tell return theSongsSorted end sortSongsByAlbumOrder -- retrieves the song with the given ID on getSong(songId) tell application "iTunes" set theSong to first track of playlist 2 whose database ID is songId and kind contains songDescriptor end tell return theSong end getSong -- retrieves a list of objects or names matching the given query and type on getResultsFromQuery(query, queryType) set evalScript to run script " script on findResults(query, queryType, resultLimit, songDescriptor) tell application \"iTunes\" set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query and kind contains songDescriptor) if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query and kind contains songDescriptor) end if if length of theSongs < resultLimit then set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query) and kind contains songDescriptor) end if if queryType is \"name\" then if length of theSongs > resultLimit then set theSongs to items 1 thru resultLimit of theSongs end if set theResults to theSongs else set theResults to {} repeat with theSong in theSongs if length of theResults is resultLimit then exit repeat set theResult to " & queryType & " of theSong if theResult is not in theResults then set theResults to theResults & theResult end if end repeat end if end tell return theResults end findResults end script " evalScript's findResults(query, queryType, resultLimit, songDescriptor) end getResultsFromQuery -- returns the given string with leading and trailing whitespace removed on trimWhitespace(theString) -- trim leading whitespace repeat while theString begins with space if length of theString is 1 then return "" set theString to text 2 thru end of theString end repeat -- trim trailing whitespace repeat while theString ends with space set theString to text 1 thru ((length of theString) - 1) of theString end repeat return theString end trimWhitespace -- queues the song with the given ID on queueSong(songId) set theSong to getSong(songId) queueSongs({theSong}) end queueSong -- queues all songs belonging to the given album on queueAlbum(albumName) set albumName to decodeFeedbackChars(albumName) set theSongs to getAlbumSongs(albumName) queueSongs(theSongs) end queueAlbum -- queues all songs by the given artist on queueArtist(artistName) set artistName to decodeFeedbackChars(artistName) set theSongs to getArtistSongs(artistName) queueSongs(theSongs) end queueArtist -- queues all songs within the given genre on queueGenre(genreName) set genreName to decodeFeedbackChars(genreName) set theSongs to getGenreSongs(genreName) queueSongs(theSongs) end queueGenre -- queues all songs in the given playlist on queuePlaylist(playlistId) set theSongs to getPlaylistSongs(playlistId) queueSongs(theSongs) end queuePlaylist -- parses the given result query to retrieve type and id of item to queue on parseResultQuery(query) set pos to offset of "-" in query set theType to text 1 thru (pos - 1) of query set theId to text (pos + 1) thru end of query return {type:theType, id:theId} end parseResultQuery on queue(query) set typeAndId to parseResultQuery(query) set theType to type of typeAndId set theId to id of typeAndId createWorkflowPlaylist() if theType is "song" then queueSong(theId) else if theType is "album" then queueAlbum(theId) else if theType is "artist" then queueArtist(theId) else if theType is "genre" then queueGenre(theId) else if theType is "playlist" then queuePlaylist(theId) else log "Unknown type: " & theType end if focusQueue() end queue on play(query) clearQueue() queue(query) focusQueue() playQueue() end play
Add space between quantity number and quantity name
Add space between quantity number and quantity name
AppleScript
mit
caleb531/play-song,caleb531/play-song
be432b7e1afa47c978d34b97440ce894967c2dc0
installer/vba-blocks.applescript
installer/vba-blocks.applescript
tell application "Terminal" activate set currentTab to do script ("vba-blocks help") end tell
tell application "Terminal" activate do script ("vba-blocks help") end tell
Tweak run applescript
Tweak run applescript
AppleScript
mit
vba-blocks/vba-blocks,vba-blocks/vba-blocks,vba-blocks/vba-blocks
49f23c9646bbc9a8f955ba4cb5f1c036d641e065
status.applescript
status.applescript
tell application "Finder" set json_path to file "json.scpt" of folder of (path to me) end tell set json to load script (json_path as alias) on is_running(appName) tell application "System Events" to (name of processes) contains appName end is_running set reply to json's createDict() if is_running("Hermes") then reply's setkv("running", true) set hermesInfo to json's createDict() -- set hermesStations to json's createDict() tell application "Hermes" hermesInfo's setkv("state", playback state as string) hermesInfo's setkv("volume", playback volume) -- XXX: execution error: Hermes got an error: every station doesn’t understand the “count” message. (-1708) -- repeat with theStation in stations -- hermesStations's setkv("name", theStation's name) -- hermesStations's setkv("id", theStation's station ID) -- end repeat hermesInfo's setkv("title", current song's title) hermesInfo's setkv("artist", current song's artist) hermesInfo's setkv("album", current song's album) hermesInfo's setkv("artwork", current song's artwork URL) hermesInfo's setkv("rating", current song's rating) hermesInfo's setkv("position", playback position as integer) hermesInfo's setkv("duration", current song duration as integer) hermesInfo's setkv("station_name", current station's name) hermesInfo's setkv("station_id", current station's station ID) end tell -- hermesInfo's setkv("stations", hermesStations) reply's setkv("info", hermesInfo) else reply's setkv("running", false) end if return reply's toJson()
tell application "Finder" set json_path to file "json.scpt" of folder of (path to me) end tell set json to load script (json_path as alias) on is_running(appName) tell application "System Events" to (name of processes) contains appName end is_running set reply to json's createDict() if is_running("Hermes") then reply's setkv("running", true) set hermesInfo to json's createDict() -- set hermesStations to json's createDict() tell application "Hermes" hermesInfo's setkv("state", playback state as string) hermesInfo's setkv("volume", playback volume) -- XXX: execution error: Hermes got an error: every station doesn’t understand the “count” message. (-1708) -- repeat with theStation in stations -- hermesStations's setkv("name", theStation's name) -- hermesStations's setkv("id", theStation's station ID) -- end repeat hermesInfo's setkv("title", current song's title) hermesInfo's setkv("artist", current song's artist) hermesInfo's setkv("album", current song's album) hermesInfo's setkv("artwork", current song's artwork URL) hermesInfo's setkv("rating", current song's rating) hermesInfo's setkv("position", playback position as integer) hermesInfo's setkv("duration", current song duration as integer) hermesInfo's setkv("station_name", current station's name) hermesInfo's setkv("station_id", current station's station ID) end tell -- hermesInfo's setkv("stations", hermesStations) reply's setkv("info", hermesInfo) else reply's setkv("running", false) end if reply's setkv("time", (do shell script "date -u +%s")) return reply's toJson()
Add UTC unix epoch as "time" as string
Add UTC unix epoch as "time" as string otherwise it converts to a real since AppleScript's integer is seemingly narrow...
AppleScript
mit
winny-/HermesRemote,winny-/HermesRemote
3a58557c1262f691a0019299e89884c24c779481
mpkg/boot2docker.app/Contents/Resources/Scripts/main.scpt
mpkg/boot2docker.app/Contents/Resources/Scripts/main.scpt
FasdUAS 1.101.10 lR OR kQ I .miscactvnullnull  l  } TODO: test if ~/.boot2docker/boot2docker.iso exists, and if not, copy it from the install (need to ship it in the installer)  TODO: test if ~/.boot2docker/boot2docker.iso exists, and if not, copy it from the install (need to ship it in the installer)  r  I  .coredoscnullctxt o 0 newwindow newWindow r m&Boot2Docker for OSX o 0 windowtitle windowTitle r m  boovtrue n 1  tdct o 0 newwindow newWindow r!!" !o 0 windowtitle windowTitle "n#$ #1  titl $o 0 newwindow newWindow %& %r"%'( 'm"#))**4/usr/local/bin/boot2docker (o 0b2d&+, +I&--. .coredoscnullctxt -m&'//00.mkdir -p ~/.boot2docker.1  kfil 1o() 0 newwindow newWindow,23 2I.545 .coredoscnullctxt 4m./6677if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi58  kfil 8o01 0 newwindow newWindow39: 9I6?;< .coredoscnullctxt ;b69=> =o67 0b2d >m78??@@ init <A  kfil Ao:; 0 newwindow newWindow:BC BI@IDE .coredoscnullctxt Db@CFG Fo@A 0b2d GmABHHII up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375EJ  kfil JoDE 0 newwindow newWindowCK KIJQLM .coredoscnullctxt LmJKNNOOdocker versionMP  kfil PoLM 0 newwindow newWindow mQQ@alisZOSX-OSxH+P Terminal.app(>e Utilitiesy`?APO,OSX-OS:Applications:Utilities:Terminal.app Terminal.appOSX-OS#Applications/Utilities/Terminal.app/RSR .aevtoappnull****STUV .aevtoappnull**** TkRWWUVQ)/6?HN .miscactvnullnull .coredoscnullctxt 0 newwindow newWindow 0 windowtitle windowTitle  tdct  titl 0b2d  kfilSO*j O*j EOEOe,FO,FOEOl Ol O%l O%l Ol Uascr ޭ
FasdUAS 1.101.10 l\ O\ k[ I .miscactvnullnull  l  } TODO: test if ~/.boot2docker/boot2docker.iso exists, and if not, copy it from the install (need to ship it in the installer)  TODO: test if ~/.boot2docker/boot2docker.iso exists, and if not, copy it from the install (need to ship it in the installer)  r  I  .coredoscnullctxt o 0 newwindow newWindow r m&Boot2Docker for OSX o 0 windowtitle windowTitle r m  boovtrue n 1  tdct o 0 newwindow newWindow r!!" !o 0 windowtitle windowTitle "n#$ #1  titl $o 0 newwindow newWindow %& %r"%'( 'm"#))**4/usr/local/bin/boot2docker (o 0b2d&+, +I&--. .coredoscnullctxt -m&'//00bash.1  kfil 1o() 0 newwindow newWindow,23 2I.545 .coredoscnullctxt 4m./6677.mkdir -p ~/.boot2docker58  kfil 8o01 0 newwindow newWindow39: 9I6=;< .coredoscnullctxt ;m67==>>if [ ! -f ~/.boot2docker/boot2docker.iso ]; then cp /usr/local/share/boot2docker/boot2docker.iso ~/.boot2docker/ ; fi<?  kfil ?o89 0 newwindow newWindow:@A @I>GBC .coredoscnullctxt Bb>ADE Do>? 0b2d Em?@FFGG init CH  kfil HoBC 0 newwindow newWindowAIJ IIHQKL .coredoscnullctxt KbHKMN MoHI 0b2d NmIJOOPP up && export DOCKER_HOST=tcp://$(/usr/local/bin/boot2docker ip 2>/dev/null):2375LQ  kfil QoLM 0 newwindow newWindowJR RIR[ST .coredoscnullctxt SmRUUUVVdocker versionTW  kfil WoVW 0 newwindow newWindow mXX@alisl Macintosh HDH++ Terminal.app_?O Utilities?A+*2Macintosh HD:Applications:Utilities:Terminal.app Terminal.app Macintosh HD#Applications/Utilities/Terminal.app/YZY .aevtoappnull****Z[\] .aevtoappnull**** [k\^^\]X)/6=FOU .miscactvnullnull .coredoscnullctxt 0 newwindow newWindow 0 windowtitle windowTitle  tdct  titl 0b2d  kfil]Y*j O*j EOEOe,FO,FOEOl Ol Ol O%l O%l Oal Uascr ޭ
fix for issue #28, switch to bash before executing script
fix for issue #28, switch to bash before executing script
AppleScript
apache-2.0
JoeWoo/osx-installer,boot2docker/osx-installer,JoeWoo/osx-installer,yut148/osx-installer,yut148/osx-installer,boot2docker/osx-installer,lakwarus/c5-osx-installer,cgvarela/osx-installer,lakwarus/c5-osx-installer,cgvarela/osx-installer
fb7eb172817b1bee7e4a5448b4250aa2b5cdeb8a
Xmod/Xmod.applescript
Xmod/Xmod.applescript
tell application "Xcode" if not (exists active project document) then error "No active project. Please open an Xcode project and re-run the script." try my updateProjectXmod(project of active project document) on error errMsg my logger("Xmod.scpt exception: " & errMsg) end try end tell on updateProjectXmod(_project) tell application "Xcode" -- Iterate over every .xcdatamodel in the project. set modelList to every file reference of _project whose file kind is "wrapper.xcdatamodel" repeat with modelIt in modelList if comments of modelIt contains "xmod" then set modelSrcDir to my modelSrcDirPath(full path of modelIt) set targetList to my everyTargetWithBuildFilePath(_project, full path of modelIt) -- Create the .xcdatamodel related source group if necessary. if not (exists (every item reference of group of modelIt whose full path is modelSrcDir)) then tell group of modelIt make new group with properties {full path:modelSrcDir, name:text 1 thru -13 of ((name of modelIt) as string)} end tell end if set modelSrcGroup to item 1 of (every item reference of group of modelIt whose full path is modelSrcDir) tell modelSrcGroup to delete every item reference -- clear it out for population in case we didn't just create it -- Meat. do shell script "/usr/bin/mogenerator --model '" & full path of modelIt & "' --output-dir '" & modelSrcDir & "'" -- Build a list of resulting source files. tell application "System Events" set modelSrcDirAlias to POSIX file modelSrcDir as alias set humanHeaderFileList to (every file of modelSrcDirAlias whose name ends with ".h" and name does not start with "_") set humanSourceFileList to (every file of modelSrcDirAlias whose (name ends with ".m" or name ends with ".mm") and name does not start with "_") set machineHeaderFileList to (every file of modelSrcDirAlias whose name ends with ".h" and name starts with "_") set machineSourceFileList to (every file of modelSrcDirAlias whose (name ends with ".m" or name ends with ".mm") and name starts with "_") set fileList to humanHeaderFileList & humanSourceFileList & machineHeaderFileList & machineSourceFileList set pathList to {} repeat with fileItem in fileList set pathList to pathList & POSIX path of fileItem end repeat end tell -- Add the source files to the model's source group and the model's targets. repeat with pathIt in pathList tell modelSrcGroup set modelSrcFileRef to make new file reference with properties {full path:pathIt, name:name of (info for POSIX file pathIt)} repeat with targetIndex from 1 to (count of targetList) set targetIt to item targetIndex of targetList add modelSrcFileRef to targetIt end repeat end tell end repeat end if end repeat end tell end updateProjectXmod on everyTargetWithBuildFilePath(_project, _buildFilePath) set theResult to {} tell application "Xcode" repeat with targetIt in (every target of _project) repeat with buildFileIt in build files of targetIt if full path of file reference of buildFileIt is _buildFilePath then set theResult to theResult & {(targetIt as anything)} end repeat end repeat end tell return theResult end everyTargetWithBuildFilePath on modelSrcDirPath(modelFileUnixPath) set modelFilePosixRef to POSIX file modelFileUnixPath set modelFileAlias to modelFilePosixRef as alias tell application "Finder" set modelFileFolder to folder of modelFileAlias set modelFileName to name of modelFileAlias set modelSrcFolderName to text 1 thru -13 of modelFileName -- pull off the .xcdatamodel extension if not (exists folder modelSrcFolderName of modelFileFolder) then make folder at modelFileFolder with properties {name:modelSrcFolderName} end if set modelSrcFolder to folder modelSrcFolderName of modelFileFolder end tell return text 1 thru -2 of (POSIX path of (modelSrcFolder as alias)) -- kill the trailing slash end modelSrcDirPath on logger(msg) do shell script "logger '" & msg & "'" end logger
tell application "Xcode" if not (exists active project document) then error "No active project. Please open an Xcode project and re-run the script." try my updateProjectXmod(project of active project document) on error errMsg my logger("Xmod.scpt exception: " & errMsg) end try end tell on updateProjectXmod(_project) tell application "Xcode" -- Iterate over every .xcdatamodel in the project. set modelList to every file reference of _project whose file kind is "wrapper.xcdatamodel" repeat with modelIt in modelList if comments of modelIt contains "xmod" then set modelSrcDir to my modelSrcDirPath(full path of modelIt) set targetList to my everyTargetWithBuildFilePath(_project, full path of modelIt) -- Create the .xcdatamodel related source group if necessary. if not (exists (every item reference of group of modelIt whose full path is modelSrcDir)) then tell group of modelIt make new group with properties {full path:modelSrcDir, name:text 1 thru -13 of ((name of modelIt) as string)} end tell end if set modelSrcGroup to item 1 of (every item reference of group of modelIt whose full path is modelSrcDir) tell modelSrcGroup to delete every item reference -- clear it out for population in case we didn't just create it -- Meat. do shell script "/usr/bin/mogenerator --model '" & full path of modelIt & "' --output-dir '" & modelSrcDir & "'" -- Build a list of resulting source files. tell application "System Events" set modelSrcDirAlias to POSIX file modelSrcDir as alias set humanHeaderFileList to (every file of modelSrcDirAlias whose name ends with ".h" and name does not start with "_") set humanSourceFileList to (every file of modelSrcDirAlias whose (name ends with ".m" or name ends with ".mm") and name does not start with "_") set machineHeaderFileList to (every file of modelSrcDirAlias whose name ends with ".h" and name starts with "_") set machineSourceFileList to (every file of modelSrcDirAlias whose (name ends with ".m" or name ends with ".mm") and name starts with "_") set fileList to humanSourceFileList & humanHeaderFileList & machineSourceFileList & machineHeaderFileList set pathList to {} repeat with fileItem in fileList set pathList to pathList & POSIX path of fileItem end repeat end tell -- Add the source files to the model's source group and the model's targets. repeat with pathIt in pathList tell modelSrcGroup set modelSrcFileRef to make new file reference with properties {full path:pathIt, name:name of (info for POSIX file pathIt)} repeat with targetIndex from 1 to (count of targetList) set targetIt to item targetIndex of targetList add modelSrcFileRef to targetIt end repeat end tell end repeat end if end repeat end tell end updateProjectXmod on everyTargetWithBuildFilePath(_project, _buildFilePath) set theResult to {} tell application "Xcode" repeat with targetIt in (every target of _project) repeat with buildFileIt in build files of targetIt if full path of file reference of buildFileIt is _buildFilePath then set theResult to theResult & {(targetIt as anything)} end repeat end repeat end tell return theResult end everyTargetWithBuildFilePath on modelSrcDirPath(modelFileUnixPath) set modelFilePosixRef to POSIX file modelFileUnixPath set modelFileAlias to modelFilePosixRef as alias tell application "Finder" set modelFileFolder to folder of modelFileAlias set modelFileName to name of modelFileAlias set modelSrcFolderName to text 1 thru -13 of modelFileName -- pull off the .xcdatamodel extension if not (exists folder modelSrcFolderName of modelFileFolder) then make folder at modelFileFolder with properties {name:modelSrcFolderName} end if set modelSrcFolder to folder modelSrcFolderName of modelFileFolder end tell return text 1 thru -2 of (POSIX path of (modelSrcFolder as alias)) -- kill the trailing slash end modelSrcDirPath on logger(msg) do shell script "logger '" & msg & "'" end logger
change file ordering to human.m, human.h, machine.m, machine.h (from human.h, human.m, machine.h, machine.m).
[CHANGE] Xmo'd: change file ordering to human.m, human.h, machine.m, machine.h (from human.h, human.m, machine.h, machine.m).
AppleScript
mit
mjasa/mogenerator,rentzsch/mogenerator,fizker/mogenerator,bewebste/mogenerator,anton-matosov/mogenerator,iv-mexx/mogenerator,fizker/mogenerator,ef-ctx/mogenerator,skywinder/mogenerator,ef-ctx/mogenerator,seanm/mogenerator,hardikdevios/mogenerator,casademora/mogenerator,willowtreeapps/mattgenerator,rentzsch/mogenerator,skywinder/mogenerator,VladimirGoncharov/mogenerator,Erin-Mounts/mogenerator,bewebste/mogenerator,casademora/mogenerator,skywinder/mogenerator,Erin-Mounts/mogenerator,otaran/mogenerator,seanm/mogenerator,kostiakoval/mogenerator,rentzsch/mogenerator,pronebird/mogenerator,bgulanowski/mogenerator,VladimirGoncharov/mogenerator,bgulanowski/mogenerator,iv-mexx/mogenerator,bewebste/mogenerator,fizker/mogenerator,pronebird/mogenerator,iv-mexx/mogenerator,otaran/mogenerator,casademora/mogenerator,seanm/mogenerator,adozenlines/mogenerator,VladimirGoncharov/mogenerator,mjasa/mogenerator,adozenlines/mogenerator,pronebird/mogenerator,bewebste/mogenerator,hardikdevios/mogenerator,anton-matosov/mogenerator,untitledstartup/mogenerator,untitledstartup/mogenerator,ef-ctx/mogenerator,Erin-Mounts/mogenerator,untitledstartup/mogenerator,anton-matosov/mogenerator,kostiakoval/mogenerator,mjasa/mogenerator,otaran/mogenerator,iv-mexx/mogenerator,adozenlines/mogenerator,willowtreeapps/mattgenerator,kostiakoval/mogenerator,willowtreeapps/mattgenerator,bgulanowski/mogenerator,hardikdevios/mogenerator
f057989121a8e2fdb173dacb76b60b9b3c2772d3
AppleScript/openQnA.scpt
AppleScript/openQnA.scpt
tell application "Terminal" if not (exists window 1) then reopen activate do script "/Library/BESAgent/BESAgent.app/Contents/MacOS/QnA -showtypes" in window 1 end tell
-- http://www-01.ibm.com/support/docview.wss?uid=swg21506026 -- https://github.com/jgstew/tools/blob/master/bash/openQnA.sh -- http://alvinalexander.com/blog/post/mac-os-x/applescript-use-comments tell application "Terminal" if not (exists window 1) then reopen activate do script "/Library/BESAgent/BESAgent.app/Contents/MacOS/QnA -showtypes" in window 1 end tell
Update openQnA.scpt
Update openQnA.scpt
AppleScript
mit
jgstew/tools,jgstew/tools,jgstew/tools,jgstew/tools