Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Number

式評価(eval)を行う

Posted on 8月 7, 2019 by Takaaki Naganoya

文字列で与えられた計算式の評価(計算)を行うAppleScriptです。

計算式の評価(Eval)を行うといえば、AppleScriptではrun scriptで計算式の文字列を実行するとか、

set aStr to "4 + 5 – 2^3"
set aRes to run script aStr

★Click Here to Open This Script 

bcコマンドに計算を依頼するのが一般的です。

set aStr to "4 + 5 – 2^3"
set yC to string id 92
set aCMD to "echo \" scale=10; " & aStr & "\" | bc"
set aRes to do shell script aCMD

★Click Here to Open This Script 

CocoaのNSExpressionによる式評価を試してみましたが、「**」でべき乗計算を行う形式はあまり見かけないように思います。
→ 調べてみたら、他のプログラミング言語ではこっちが一般的だったので訂正(^ー^; Basic系はべき乗記号(^)でしょうか。

run scriptコマンドでAppleScriptのコマンドを実行して結果を取得できますが、ユーザーから入力させられたり他のファイルからコマンド文字列を取ってくるような仕様になっている場合には、危険なコマンドを仕込まれる危険性があるので、AppleScriptのコマンドが文字列中に入っていないかを事前にチェックするとよいと思われます。

→ 指定のAppleScriptテキストを構文確認して指定の構文要素が入っていないかチェック

AppleScript名:式評価(eval)を行う
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/07
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property NSExpression : a reference to current application’s NSExpression

set aStr to "4 + 5 – 2**3"
set d1Res to calcEval(aStr) of me
–> 1.0

–式評価(Evaluate)
on calcEval(aStr)
  –https://nshipster.com/nsexpression/
  
set anExp to NSExpression’s expressionWithFormat:aStr
  
set valList to anExp’s expressionValueWithObject:(missing value) context:(missing value)
  
return valList as real
end calcEval

★Click Here to Open This Script 

(Visited 234 times, 1 visits today)
Posted in Number | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSExpression | Leave a comment

標準偏差を求める v2

Posted on 8月 7, 2019 by Takaaki Naganoya

1次元配列から標準偏差を求めるAppleScriptです。

Numbersで検算してみたら結果が異なりました。元になっているSwiftのプログラムとは計算結果が合っているので、そういうこと(Cocoaの計算機能+変数型による差異)なんでしょうか。

AppleScript名:標準偏差を求める v2
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/07
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property NSExpression : a reference to current application’s NSExpression
property NSMutableArray : a reference to current application’s NSMutableArray

set aList to {14.0, 37.0, 18.5, 59.0, 100}
set d1Res to calcStddev(aList) of me
–> 122.708110069451

set a2List to {1, 2, 3, 4, 4, 5, 9, 11}
set d2Res to calcStddev(a2List) of me
–> 3.218598297396

–標準偏差を計算する
on calcStddev(aList)
  –https://nshipster.com/nsexpression/
  
set anArray to NSMutableArray’s arrayWithArray:aList
  
set anExp to NSExpression’s expressionForFunction:"stddev:" arguments:{(NSExpression’s expressionForConstantValue:anArray)}
  
set valList to anExp’s expressionValueWithObject:(missing value) context:(missing value)
  
return valList as real
end calcStddev

★Click Here to Open This Script 

(Visited 61 times, 1 visits today)
Posted in list Number | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSExpression NSMutableArray | Leave a comment

NumbersのColumn Adr(26進数)と10進数との相互変換

Posted on 7月 22, 2019 by Takaaki Naganoya

Numbersの表のカラムを表現するアドレス文字列(26進数)と数値の間のエンコーダーおよびデコーダーのAppleScriptです。

もともとは、Excel 2004/2008で採用されたカラムアドレス形式に対処するためのScriptでした。

Excel上のセルのアドレス(場所)を指し示す方法は、「R1C1」(行とカラムを数値指定)形式、あるいはAppleScriptの行オブジェクトとセルオブジェクトで指定する形式でした。

そこへ新たに「A1」形式……画面上で表記されている行、カラムと親和性の高い形式が採用されることになりました。当初は相互変換のための関数なども用意されていなかったと記憶しています(間違っていたらご指摘ください)。そのため、Scripterが自力でこのA1形式に対応する必要が出てきました。

そんな中、Excel書類にAppleScriptを埋め込んで実行するAppleScriptを開発。本ルーチンはそのScript開発のために作成したものです。

Excel 2008でVBAの処理系が外されてMac上のVBA的なマクロ処理はAppleSctiptに一本化されるという話になっていたため(当時の話)、これを好機ととらえ、マイクロソフトのご担当にデモして、US本社で紹介していただくということになりました。

ただ、その会議上でVBAの復活プランが発表され、自分の提案したプランは廃案に(まさか当時のREALbasicのコンパイラの開発者を引き抜いてきてVBAの処理系をスクラッチで書かせるとは思いませんでしたわー)。

その後は、Excel 2011でVBAの処理系が復活。本ルーチンも割とHDDの肥やしとして絶賛在庫状態になっておりました。ごくたまーに、このExcel 2011でVBAの処理系が復活したことを知らない方がいて、「VBAで動いているマクロをAppleScriptに移植してほしい」という問い合わせがあるのですが、「Excelの最新版を購入してください。VBAがありますよ」とお返事しています。最新のExcelが動く環境を購入する費用よりも安く仕事としてお受けすることは困難なので。

そこから年月が流れ、AppleがNumbersをリリース。そのカラム表記がExcel 2004/2008と同じ形式になっているために、しまいこんでいたルーチンをふたたび引っ張り出してきた次第です。

一応、条件つきで使えるものの、作りが古い(やっつけ仕事な)点が気になります。きっと、誰かがもっといいルーチンを作って使っているに違いありません。一応、本ルーチンでは1〜1351の範囲での動作を確認しています。

もう少し改良したいところではあります。実用上は、Numbersでそこまで大きなデータは扱わない(はず)ので、問題はあまりないものと思われます。

AppleScript名:NumbersのColumn Adr(26進数)と10進数との相互変換
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/07/21
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSString : a reference to current application’s NSString
property NSArray : a reference to current application’s NSArray
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

repeat with i from 1 to 1351
  set a to numAdrToColumnEncode(i) of me
  
set b to colAddrToNumDecode(a) of me
  
set aRes to (i = b) as boolean
  
log {i, b, a, aRes}
  
if aRes = false then display dialog i as string
end repeat

–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン(エンコード範囲:1〜1351)
on numAdrToColumnEncode(origNum)
  if origNum > 1351 then
    error "エラー:Numbersのカラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
  end if
  
  
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
  
set oNum to origNum
  
set nTh to 26
  
set stringLength to 4
  
  
–数字が1桁の場合の対応
  
if origNum < 27 then
    set aRes to (item origNum of upperDigitEncTable) as string
    
return aRes
  end if
  
  
  
if origNum > 702 then
    –3桁になる場合
    
set upupNum to oNum div 676 –整数除算–上の上の桁
    
set oNum to oNum – (upupNum * 676)
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–log {origNum, upupNum, upNum, lowNum}
    
    
–超つじつま合わせルーチン【強引】
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upupChar to (item upupNum of upperDigitEncTable) as string
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upupChar & upChar & lowChar
    
  else
    –2桁の場合
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
    
–超つじつま合わせルーチン【強引】
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upChar & lowChar
    
  end if
  
  
return resText
  
end numAdrToColumnEncode

–Numbersの横方向アドレス(A〜Zの26進数)文字列を10進数に変換
on colAddrToNumDecode(origStr)
  return aNthToDecimal(origStr, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}) of me
end colAddrToNumDecode

–n進数文字列を10進数に変換する
on aNthToDecimal(origStr, nTh)
  set resNumber to 0
  
  
set sList to reverse of (characters of origStr)
  
set aLen to length of nTh
  
set digitCount to 0
  
  
repeat with i in sList
    set j to contents of i
    
set aRes to offsetInList(j, nTh) of me
    
    
set resNumber to resNumber + (aLen ^ digitCount) * aRes
    
    
set digitCount to digitCount + 1
  end repeat
  
  
return resNumber as integer
end aNthToDecimal

on offsetInList(aChar, aList)
  set anArray to NSArray’s arrayWithArray:aList
  
set aInd to (anArray’s indexOfObject:aChar)
  
if aInd = current application’s NSNotFound or (aInd as number) > 9.99999999E+8 then
    error "Invalid Character Error"
  else
    return (aInd as integer) + 1 –0 to 1 based index conversion
  end if
end offsetInList

★Click Here to Open This Script 

(Visited 252 times, 1 visits today)
Posted in list Number | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSArray NSRegularExpressionSearch NSString Numbers | Leave a comment

度量衡の変換

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースの「DDUnitConverter」(By Dave DeLong)を用いて、度量衡(measurement unit)の変換を行うAppleScriptです。AppleScriptから呼び出すために、DDUnitConverterをフレームワーク化した「ddUnitConversionKit」を作成しています。

もともと、AppleScriptには内蔵の度量衡変換機能があり、

AppleScript名:インチからセンチへの変換
set a to 1
set a to a as inches
–> inches 1.0

set b to a as centimeters
–> centimeters 2.54

set c to a as meters
–> meters 0.0254

set d to a as kilometers
–> kilometers 2.54E-5

★Click Here to Open This Script 

とか、

AppleScript名:液体の容積の単位変換
–液体の容積の単位変換
set a to 10 as liters
–> liters 10.0

set b to a as gallons
–> gallons 2.641720372842

set c to a as quarts
–> quarts 10.566881491367

★Click Here to Open This Script 

ぐらいは簡単にできます。AppleScriptがサポートしている度量衡は、長さ、重さ、温度、液体の容積です。

ただ、mmの下のμmとか、オングストロームとか、そういう単位には対応していませんし、重量でいえばKgに対応していてもt(トン)の単位はサポートしていなかったりと、日常的な度量衡の単位の世界でも不十分な感じが否めません(数値の有効桁数が10桁と小さいことも影響?)。

Cocoaの世界で度量衡変換機能について調べてみたところ、km→m→cm→mmといった変換はしてくれるものの、他の単位への変換は行ってくれていなかったりして、標準機能だけではいまひとつな印象です。

AppleScript名:NSLengthFormatterのじっけん
— Created 2015-11-18 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://dev.classmethod.jp/references/ios8-new-formatter/

set aLengthFormatter to current application’s NSLengthFormatter’s alloc()’s init()
set aMeters to 5000
set aRes to (aLengthFormatter’s stringFromMeters:aMeters) as text
–>  "5 km"
set bRes to (aLengthFormatter’s stringFromMeters:500) as text
–>  "500 m"
set cRes to (aLengthFormatter’s stringFromMeters:0.5) as text
–>  "50 cm"
set dRes to (aLengthFormatter’s stringFromMeters:0.005) as text
–>  "5 mm"
set eRes to (aLengthFormatter’s stringFromMeters:("0.000005" as real)) as text
–>  "0.005 mm"

set res2 to aLengthFormatter’s getObjectValue:(missing value) forString:aRes errorDescription:(missing value)
–>  false

set res3 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMillimeter)) as text
–>  "5,000 mm"
set res4 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitCentimeter)) as text
–>  "5,000 cm"
set res5 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMeter)) as text
–>  "5,000 m"
set res6 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitKilometer)) as text
–>  "5,000 km"
set res7 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitInch)) as text
–>  "5,000 in"
set res8 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitFoot)) as text
–>  "5,000 ft"
set res9 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitYard)) as text
–>  "5,000 yd"
set res10 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMile)) as text
–>  "5,000 mi"

★Click Here to Open This Script 

AppleScript名:NSMassFormatterのじっけん
— Created 2015-11-18 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://dev.classmethod.jp/references/ios8-new-formatter/

set aMasFormatter to current application’s NSMassFormatter’s alloc()’s init()
set aKilloGrams to 60.0
set aRes to (aMasFormatter’s stringFromKilograms:aKilloGrams) as text
–>  "60 kg"
set a2Res to (aMasFormatter’s stringFromKilograms:(0.5)) as text
–>  "500 g"
set a3Res to (aMasFormatter’s stringFromKilograms:(5000000)) as text
–>  "5,000,000 kg"
set a4Res to (aMasFormatter’s stringFromKilograms:("0.0005" as real)) as text
–>  "0.5 g"

set bRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitGram)) as text
–>  "60 g"
set cRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitKilogram)) as text
–>  "60 kg"
set dRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitOunce)) as text
–>  "60 oz"
set eRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitPound)) as text
–>  "60 lb"
set fRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitStone)) as text
–>  "60 st"

set gRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitGram)) as text
–>  "g"
set hRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitKilogram)) as text
–>  "kg"
set iRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitOunce)) as text
–>  "oz"
set jRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitPound)) as text
–>  "lb"
set kRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitStone)) as text
–>  "st"

set res01 to aMasFormatter’s getObjectValue:(missing value) forString:fRes errorDescription:(missing value)
–>  false

set res02 to (aMasFormatter’s stringFromKilograms:80) as text
–>  "80 kg"

set res03 to aMasFormatter’s unitStyle()
–>  2 = NSFormattingUnitStyleMedium

★Click Here to Open This Script 

そこで、冒頭に紹介したようにDDUnitConverterを導入してみたわけですが、これはこれで問題がないわけでもありません。本来、通貨同士の変換をサポートしており、通貨レートの更新機能を持っているのですが、実際に呼び出してみると更新されていない雰囲気が濃厚です(呼び出し方を間違っているのか?)。

なので、「通貨レート以外」の度量衡変換にのみ用いるのが安全な使い方なのかもしれない、というところです。

例によって、OS X 10.10以降用にビルドしたバイナリを用意しておきましたので、興味のある方はアーカイブを展開したあとで、~/Library/Frameworksに入れておためしください。

–> Download ddUnitConversionKit.framework(To ~/Library/Frameworks/)

AppleScript名:DDUnitConverterのじっけん1
— Created 2015-11-19 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version “2.4”
use scripting additions
use framework “Foundation”
use framework “ddUnitConversionKit” –davedelong/DDUnitConverter
–https://github.com/davedelong/DDUnitConverter

–enums in DDVelocityUnitConverter.h
property DDVelocityUnitCentimetersPerHour : 0
property DDVelocityUnitCentimetersPerMinute : 1
property DDVelocityUnitCentimetersPerSecond : 2
property DDVelocityUnitFeetPerHour : 3
property DDVelocityUnitFeetPerMinute : 4
property DDVelocityUnitFeetPerSecond : 5
property DDVelocityUnitInchesPerHour : 6
property DDVelocityUnitInchesPerMinute : 7
property DDVelocityUnitInchesPerSecond : 8
property DDVelocityUnitKilometersPerHour : 9
property DDVelocityUnitKilometersPerMinute : 10
property DDVelocityUnitKilometersPerSecond : 11
property DDVelocityUnitKnots : 12
property DDVelocityUnitLight : 13
property DDVelocityUnitMach : 14
property DDVelocityUnitMetersPerHour : 15
property DDVelocityUnitMetersPerMinute : 16
property DDVelocityUnitMetersPerSecond : 17
property DDVelocityUnitMilesPerHour : 18
property DDVelocityUnitMilesPerMinute : 19
property DDVelocityUnitMilesPerSecond : 20
property DDVelocityUnitFurlongsPerFortnight : 21

–時速100kmを秒速kmに変換
set aVal to ((current application’s DDUnitConverter’s velocityUnitConverter())’s convertNumber:100 fromUnit:(DDVelocityUnitKilometersPerHour) toUnit:(DDVelocityUnitKilometersPerSecond)) as real
–>  0.027777777778

★Click Here to Open This Script 

AppleScript名:DDCurrencyUnitConverterのじっけん
— Created 2015-11-19 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version “2.4”
use scripting additions
use framework “Foundation”
use framework “ddUnitConversionKit” –davedelong/DDUnitConverter
–https://github.com/davedelong/DDUnitConverter

–enums in DDCurrencyUnitConverter.h
property DDCurrencyUnitEuro : 0
property DDCurrencyUnitJapaneseYen : 1
property DDCurrencyUnitUKPoundSterling : 2
property DDCurrencyUnitUSDollar : 3
property DDCurrencyUnitAlgerianDinar : 4
property DDCurrencyUnitArgentinePeso : 5
property DDCurrencyUnitAustralianDollar : 6
property DDCurrencyUnitBahrainDinar : 7
property DDCurrencyUnitBotswanaPula : 8
property DDCurrencyUnitBrazilianReal : 9
property DDCurrencyUnitBruneiDollar : 10
property DDCurrencyUnitCanadianDollar : 11
property DDCurrencyUnitChileanPeso : 12
property DDCurrencyUnitChineseYuan : 13
property DDCurrencyUnitColombianPeso : 14
property DDCurrencyUnitCzechKoruna : 15
property DDCurrencyUnitDanishKrone : 16
property DDCurrencyUnitHungarianForint : 17
property DDCurrencyUnitIcelandicKrona : 18
property DDCurrencyUnitIndianRupee : 19
property DDCurrencyUnitIndonesianRupiah : 20
property DDCurrencyUnitIranianRial : 21
property DDCurrencyUnitIsraeliNewSheqel : 22
property DDCurrencyUnitKazakhstaniTenge : 23
property DDCurrencyUnitKoreanWon : 24
property DDCurrencyUnitKuwaitiDinar : 25
property DDCurrencyUnitLibyanDinar : 26
property DDCurrencyUnitMalaysianRinggit : 27
property DDCurrencyUnitMauritianRupee : 28
property DDCurrencyUnitMexicanPeso : 29
property DDCurrencyUnitNepaleseRupee : 30
property DDCurrencyUnitNewZealandDollar : 31
property DDCurrencyUnitNorwegianKrone : 32
property DDCurrencyUnitRialOmani : 33
property DDCurrencyUnitPakistaniRupee : 34
property DDCurrencyUnitNuevoSol : 35
property DDCurrencyUnitPhilippinePeso : 36
property DDCurrencyUnitPolishZloty : 37
property DDCurrencyUnitQatarRiyal : 38
property DDCurrencyUnitRussianRuble : 39
property DDCurrencyUnitSaudiArabianRiyal : 40
property DDCurrencyUnitSingaporeDollar : 41
property DDCurrencyUnitSouthAfricanRand : 42
property DDCurrencyUnitSriLankaRupee : 43
property DDCurrencyUnitSwedishKrona : 44
property DDCurrencyUnitSwissFranc : 45
property DDCurrencyUnitThaiBaht : 46
property DDCurrencyUnitTrinidadAndTobagoDollar : 47
property DDCurrencyUnitTunisianDinar : 48
property DDCurrencyUnitUAEDirham : 49
property DDCurrencyUnitPesoUruguayo : 50
property DDCurrencyUnitBolivarFuerte : 51
property DDCurrencyUnitSDR : 52

–最初に通貨レートの更新を行う必要があるが、実行しても変わらないのはなぜ????
set aConv to current application’s DDUnitConverter’s currencyUnitConverter()
aConv’s refreshExchangeRates()
set aVal to (aConv’s convertNumber:100 fromUnit:(DDCurrencyUnitUSDollar) toUnit:(DDCurrencyUnitJapaneseYen))
–>  (NSNumber) 1.006839721743

★Click Here to Open This Script 

(Visited 31 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy NSLengthFormatter NSMassFormatter | Leave a comment

数値演算ライブラリ「calcLibAS」v1.3(28倍速)

Posted on 6月 8, 2018 by Takaaki Naganoya

数値演算の関数を35個提供するAppleScript Libraries「calcLibAS」の高速版です。

–> Download calcLibAS (To ~/Library/Script Libraries/)

掘っ建て小屋とか犬小屋みたいな吹けば飛ぶような数値演算ライブラリだったものが、気づけば最初のバージョンから28倍速といったトンでもない状況になっています。ただ、前バージョンとくらべて少し安定性が損なわれているような気がしないでもありません。

計算に速度が求められる用途では、BridgePlusやSatimage OSAXなどを使うのがよいと思いますが、これらのライブラリやOSAXがサポートしていない数値関数が割とあるので(とくにatan2)それを埋めるためだけに本ライブラリは存在しています。

こうしてグラフで比較してみると、C++で書かれたSatimage OSAX、Objective-Cで書かれたCocoa Frameworkと1桁違うぐらいの処理速度でAppleScriptによる(JavaScript処理系呼んでますけど)数値演算ができているのは割とすごいと思います(自分ではなくCPUとかOSとかShane Stanleyの高速化とかが。割と他力本願ライブラリなので)。

本来であれば、AppleがNumbersの関数の充実のために導入した「Cephes Math Library」をNSNumberを介してAppleScriptから呼べるようにラッピングするのがよいのですが(Github上にあるObjectiveCephesは、単にCocoa Framework化しただけでC言語レベルでデータを扱っているのでAppleScriptからは使えない)、割と手間がかかるので「とりあえずJavaScriptの処理系の関数を使えるようにしてみよう」ということで(数時間で)でっち上げた、その場しのぎのためのライブラリです。

AppleScript名:testScript1
— Created 2018-06-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use mLib : script "calcLibAS"

set a01Res to calcAbs(-10) of mLib –> 10
set a02Res to calcAcos(-1) of mLib –> 3.14159265359
set a03Res to calcAcosh(10) of mLib –> 2.993222846126
set a04Res to calcAsin(-1) of mLib –> -1.570796326795
set a05Res to calcAsinh(10) of mLib –> 2.998222950298
set a06Res to calcAtan(10) of mLib –> 1.471127674304
set a07Res to calcAtan2(10, 20) of mLib –> 0.463647609001
set a08Res to calcAtanh(0.5) of mLib –> 0.549306144334
set a09Res to calcCbrt(3) of mLib –> 1.442249570307
set a10Res to calcCeil(0.95) of mLib –> 1
set a11Res to calcClz32(1) of mLib –> 31
set a12Res to calcCos(1) of mLib –> 0.540302305868
set a13Res to calcCosh(1) of mLib –> 1.543080634815
set a14Res to calcExp(1) of mLib –> 2.718281828459
set a15Res to calcExpm1(-1) of mLib –> -0.632120558829
set a16Res to calcFloor(45.95) of mLib –> 45
set a17Res to calcFround(1.337) of mLib –> 1.337000012398
set a18Res to calcHypot({3, 4, 5}) of mLib –> 7.071067811865
set a19Res to calcImul(2, 5) of mLib –> 10
set a20Res to calcLog(10) of mLib –> 2.302585092994
set a21Res to calcLog10(2) of mLib –> 0.301029995664
set a22Res to calcLog1p(1) of mLib –> 0.69314718056
set a23Res to calcLog2(3) of mLib –> 1.584962500721
set a24Res to calcMax({1, 2, 3, 4, 6, 2, 10}) of mLib –> 10
set a25Res to calcMin({1, 2, 3, 4, 6, 2, 10, 0}) of mLib –> 0
set a26Res to calcPow(7, 2) of mLib –>  49.0
set a27Res to calcRandom() of mLib –>  0.200867049467
set a28Res to calcRound(5.95) of mLib –>  6.0
set a29Res to calcSign(10) of mLib –> -1/0/1 –> -1.0/0.0/1.0
set a30Res to calcSin(pi / 2) of mLib –> 1–>  1.0
set a31Res to calcSinh(1) of mLib –> 1.175201193644
set a32Res to calcSqrt(2) of mLib –> 1.414213562373
set a33Res to calcTan(30) of mLib –> -6.405331196646
set a34Res to calcTanh(10) of mLib –> 0.999999995878
set a35Res to calcTrunc(13.37) of mLib –> 13 –>  13.0

★Click Here to Open This Script 

AppleScript名:calcLibAS
— Created 2018-06-06 by Takaaki Naganoya
— 2017 Piyomaru Software
–v1.0 First Version。run scriptでJXAを呼び出して計算。連続呼び出し時にクラッシュが頻発
–v1.1 JavaScriptCoreを使用。run script命令をフックして呼び出し。JXA呼び出しをやめて6倍の高速化
–v1.2 JavaScriptCoreを使用。run script命令のフックをやめて若干の高速化
–v1.3 Shane Stanleyによる高速化。JSContextをpropertyにキャッシュして高速化

— Created 2018-06-06 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "JavaScriptCore"

property theContext : missing value

–数値の絶対値を返す
on calcAbs(aNum as string)
  set aStr to "Math.abs(" & aNum & ")"
  
return exeJS(aStr)
end calcAbs

–アークコサインをラジアン単位で返す
on calcAcos(aNum as string)
  set aStr to "Math.acos(" & aNum & ")"
  
return exeJS(aStr)
end calcAcos

–ハイパーボリックアークコサインを返す
on calcAcosh(aNum as string)
  set aStr to "Math.acosh(" & aNum & ")"
  
return exeJS(aStr)
end calcAcosh

–アークサインをラジアン単位で返す
on calcAsin(aNum as string)
  set aStr to "Math.asin(" & aNum & ")"
  
return exeJS(aStr)
end calcAsin

–ハイパーボリックアークサインを返す
on calcAsinh(aNum as string)
  set aStr to "Math.asinh(" & aNum & ")"
  
return exeJS(aStr)
end calcAsinh

–アークタンジェントをラジアン単位で返す
on calcAtan(aNum as string)
  set aStr to "Math.atan(" & aNum & ")"
  
return exeJS(aStr)
end calcAtan

–アークタンジェントを返す
on calcAtan2(aNum as string, bNum as string)
  set aStr to "Math.atan2(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcAtan2

–ハイパーボリックアークタンジェントを返す
on calcAtanh(aNum as string)
  set aStr to "Math.atanh(" & aNum & ")"
  
return exeJS(aStr)
end calcAtanh

–引数として与えた数の立方根を返す
on calcCbrt(aNum as string)
  set aStr to "Math.cbrt(" & aNum & ")"
  
return exeJS(aStr)
end calcCbrt

–引数として与えた数以上の最小の整数を返す
on calcCeil(aNum as string)
  set aStr to "Math.ceil(" & aNum & ")"
  
return exeJS(aStr)
end calcCeil

–引数として与えた数以上の最小の整数を返す
on calcClz32(aNum as string)
  set aStr to "Math.clz32(" & aNum & ")"
  
return exeJS(aStr)
end calcClz32

–引数として与えた数のコサインを返す
on calcCos(aNum as string)
  set aStr to "Math.cos(" & aNum & ")"
  
return exeJS(aStr)
end calcCos

–引数として与えた数のハイパーボリックコサインを返す
on calcCosh(aNum as string)
  set aStr to "Math.cosh(" & aNum & ")"
  
return exeJS(aStr)
end calcCosh

–Ex を返す。ここでの x は引数、E は、自然対数の底であるネイピア数(オイラー数)
on calcExp(aNum as string)
  set aStr to "Math.exp(" & aNum & ")"
  
return exeJS(aStr)
end calcExp

–ex – 1 を返す。x は引数で、e は自然対数の底
on calcExpm1(aNum as string)
  set aStr to "Math.expm1(" & aNum & ")"
  
return exeJS(aStr)
end calcExpm1

–引数として与えた数以下の最大の整数を返す
on calcFloor(aNum as string)
  set aStr to "Math.floor(" & aNum & ")"
  
return exeJS(aStr)
end calcFloor

–引数として与えた数の最も近い単精度 floatを返す
on calcFround(aNum as string)
  set aStr to "Math.fround(" & aNum & ")"
  
return exeJS(aStr)
end calcFround

–引数の二乗和の平方根を返す
on calcHypot(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.hypot(" & bStr & ")"
  
return exeJS(aStr)
end calcHypot

— 2 つの引数をとり、C 言語の様な 32 ビット乗算の結果を返す
on calcImul(aNum as string, bNum as string)
  set aStr to "Math.imul(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcImul

— 引数として与えた数の自然対数 (底は e) を返す
on calcLog(aNum as string)
  set aStr to "Math.log(" & aNum & ")"
  
return exeJS(aStr)
end calcLog

— 引数として与えた数に対して、10を底とする対数を返す
on calcLog10(aNum as string)
  set aStr to "Math.log10(" & aNum & ")"
  
return exeJS(aStr)
end calcLog10

— 引数として与えた数と 1 の合計の自然対数(底 e)を返す
on calcLog1p(aNum as string)
  set aStr to "Math.log1p(" & aNum & ")"
  
return exeJS(aStr)
end calcLog1p

— 引数として与えた数の2を底とする対数を返す
on calcLog2(aNum as string)
  set aStr to "Math.log2(" & aNum & ")"
  
return exeJS(aStr)
end calcLog2

–引数として与えた複数の数の中で最大の数を返す
on calcMax(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.max(" & bStr & ")"
  
return exeJS(aStr)
end calcMax

–引数として与えた複数の数の中で最小の数を返す
on calcMin(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.min(" & bStr & ")"
  
return exeJS(aStr)
end calcMin

–引数として与えた複数の数の中で最小の数を返す
on calcPow(aNum as string, bNum as string)
  set aStr to "Math.pow(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcPow

–(0以上、1未満)の範囲で浮動小数点の擬似乱数を返す
on calcRandom()
  set aStr to "Math.random()"
  
return (run script aStr in "JavaScript")
end calcRandom

–引数として与えた数を四捨五入して、もっとも近似の整数を返す
on calcRound(aNum as string)
  set aStr to "Math.round(" & aNum & ")"
  
return exeJS(aStr)
end calcRound

–引数として与えた数が正、負、0 のどれであるか示す符号を返す
on calcSign(aNum as string)
  set aStr to "Math.sign(" & aNum & ")"
  
return exeJS(aStr)
end calcSign

–引数として与えた数のサイン(正弦)を返す
on calcSin(aNum as string)
  set aStr to "Math.sin(" & aNum & ")"
  
return exeJS(aStr)
end calcSin

–引数として与えた数のハイパーボリックサインを返す
on calcSinh(aNum as string)
  set aStr to "Math.sinh(" & aNum & ")"
  
return exeJS(aStr)
end calcSinh

–引数として与えた数の平方根を返す
on calcSqrt(aNum as string)
  set aStr to "Math.sqrt(" & aNum & ")"
  
return exeJS(aStr)
end calcSqrt

–引数として与えた数のタンジェントを返す
on calcTan(aNum as string)
  set aStr to "Math.tan(" & aNum & ")"
  
return exeJS(aStr)
end calcTan

–引数として与えた数のハイパーボリックタンジェントを返す
on calcTanh(aNum as string)
  set aStr to "Math.tanh(" & aNum & ")"
  
return exeJS(aStr)
end calcTanh

–引数として与えた数の小数部の桁を取り除いて整数部を返す
on calcTrunc(aNum as string)
  set aStr to "Math.trunc(" & aNum & ")"
  
return exeJS(aStr)
end calcTrunc

–Sub Routines

–リストを指定デリミタをはさんでテキスト化
on retArrowText(aList, aDelim) –自分のASでよく使うハンドラ名称なので、同じものを用意
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retArrowText

–JavaScriptCore版実行部
on exeJS(aStr)
  return (myContext()’s evaluateScript:aStr)’s toDouble()
end exeJS

on myContext()
  if theContext = missing value then set theContext to current application’s JSContext’s new()
  
return theContext
end myContext

★Click Here to Open This Script 

(Visited 153 times, 2 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値演算ライブラリ「calcLibAS」v1.2(6倍速)

Posted on 6月 7, 2018 by Takaaki Naganoya

数値演算の関数を35個提供するAppleScript Libraries「calcLibAS」の高速・安定化版です。

–> Download calcLibAS (To ~/Library/Script Libraries/)


▲atan2 calculation comparison

前バージョンのv1.0よりも6倍高速で、JXAの利用をやめてJavaScript Coreに切り替えたため、数百回呼び出したときでもクラッシュすることがなくなりました(ひどい場合だと数回でクラッシュしていたため、JXAを外せて本当によかったです。run scriptコマンドがひどいのかもしれませんが)。

v1.1ではrun scriptコマンドをのっとってJavaScript Coreを呼び出していましたが、v1.2ではrun scriptコマンドの利用をやめてすべてサブルーチン呼び出しに書き換えたので、若干高速化しました。

JavaScript CoreのほかWebKit経由でもJavaScriptの実行は行えますが、WebKitではメインスレッドでの実行が求められたため、JavaScript Coreを使用しています。ただし、このためかどうかわかりませんが、macOS 10.13の環境で本Scriptを実行したときにSafariのJavaScriptデバッグ画面が実行回数だけオープンするという怪奇現象に直面しました。Safariを起動していない場合には発生しませんし、テスト環境では2度目以降は発生していません。ご注意ください。

AppleScript名:calcLibAS
— Created 2018-06-06 by Takaaki Naganoya
— 2017 Piyomaru Software
–v1.0 First Version。run scriptでJXAを呼び出して計算。連続呼び出し時にクラッシュが頻発
–v1.1 JavaScriptCoreを使用。run script命令をフックして呼び出し。JXA呼び出しをやめて6倍の高速化
–v1.2 JavaScriptCoreを使用。run script命令のフックをやめて若干の高速化
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "JavaScriptCore"

set a01Res to calcAbs(-10) of me –> 10
set a02Res to calcAcos(-1) of me –> 3.14159265359
set a03Res to calcAcosh(10) of me –> 2.993222846126
set a04Res to calcAsin(-1) of me –> -1.570796326795
set a05Res to calcAsinh(10) of me –> 2.998222950298
set a06Res to calcAtan(10) of me –> 1.471127674304
set a07Res to calcAtan2(10, 20) of me –> 0.463647609001
set a08Res to calcAtanh(0.5) of me –> 0.549306144334
set a09Res to calcCbrt(3) of me –> 1.442249570307
set a10Res to calcCeil(0.95) of me –> 1
set a11Res to calcClz32(1) of me –> 31
set a12Res to calcCos(1) of me –> 0.540302305868
set a13Res to calcCosh(1) of me –> 1.543080634815
set a14Res to calcExp(1) of me –> 2.718281828459
set a15Res to calcExpm1(-1) of me –> -0.632120558829
set a16Res to calcFloor(45.95) of me –> 45
set a17Res to calcFround(1.337) of me –> 1.337000012398
set a18Res to calcHypot({3, 4, 5}) of me –> 7.071067811865
set a19Res to calcImul(2, 5) of me –> 10
set a20Res to calcLog(10) of me –> 2.302585092994
set a21Res to calcLog10(2) of me –> 0.301029995664
set a22Res to calcLog1p(1) of me –> 0.69314718056
set a23Res to calcLog2(3) of me –> 1.584962500721
set a24Res to calcMax({1, 2, 3, 4, 6, 2, 10}) of me –> 10
set a25Res to calcMin({1, 2, 3, 4, 6, 2, 10, 0}) of me –> 0
set a26Res to calcPow(7, 2) of me –>  49.0
set a27Res to calcRandom() of me –>  0.200867049467
set a28Res to calcRound(5.95) of me –>  6.0
set a29Res to calcSign(10) of me –> -1/0/1 –> -1.0/0.0/1.0
set a30Res to calcSin(pi / 2) of me –> 1–>  1.0
set a31Res to calcSinh(1) of me –> 1.175201193644
set a32Res to calcSqrt(2) of me –> 1.414213562373
set a33Res to calcTan(30) of me –> -6.405331196646
set a34Res to calcTanh(10) of me –> 0.999999995878
set a35Res to calcTrunc(13.37) of me –> 13 –>  13.0

–数値の絶対値を返す
on calcAbs(aNum as string)
  set aStr to "Math.abs(" & aNum & ")"
  
return exeJS(aStr)
end calcAbs

–アークコサインをラジアン単位で返す
on calcAcos(aNum as string)
  set aStr to "Math.acos(" & aNum & ")"
  
return exeJS(aStr)
end calcAcos

–ハイパーボリックアークコサインを返す
on calcAcosh(aNum as string)
  set aStr to "Math.acosh(" & aNum & ")"
  
return exeJS(aStr)
end calcAcosh

–アークサインをラジアン単位で返す
on calcAsin(aNum as string)
  set aStr to "Math.asin(" & aNum & ")"
  
return exeJS(aStr)
end calcAsin

–ハイパーボリックアークサインを返す
on calcAsinh(aNum as string)
  set aStr to "Math.asinh(" & aNum & ")"
  
return exeJS(aStr)
end calcAsinh

–アークタンジェントをラジアン単位で返す
on calcAtan(aNum as string)
  set aStr to "Math.atan(" & aNum & ")"
  
return exeJS(aStr)
end calcAtan

–アークタンジェントを返す
on calcAtan2(aNum as string, bNum as string)
  set aStr to "Math.atan2(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcAtan2

–ハイパーボリックアークタンジェントを返す
on calcAtanh(aNum as string)
  set aStr to "Math.atanh(" & aNum & ")"
  
return exeJS(aStr)
end calcAtanh

–引数として与えた数の立方根を返す
on calcCbrt(aNum as string)
  set aStr to "Math.cbrt(" & aNum & ")"
  
return exeJS(aStr)
end calcCbrt

–引数として与えた数以上の最小の整数を返す
on calcCeil(aNum as string)
  set aStr to "Math.ceil(" & aNum & ")"
  
return exeJS(aStr)
end calcCeil

–引数として与えた数以上の最小の整数を返す
on calcClz32(aNum as string)
  set aStr to "Math.clz32(" & aNum & ")"
  
return exeJS(aStr)
end calcClz32

–引数として与えた数のコサインを返す
on calcCos(aNum as string)
  set aStr to "Math.cos(" & aNum & ")"
  
return exeJS(aStr)
end calcCos

–引数として与えた数のハイパーボリックコサインを返す
on calcCosh(aNum as string)
  set aStr to "Math.cosh(" & aNum & ")"
  
return exeJS(aStr)
end calcCosh

–Ex を返す。ここでの x は引数、E は、自然対数の底であるネイピア数(オイラー数)
on calcExp(aNum as string)
  set aStr to "Math.exp(" & aNum & ")"
  
return exeJS(aStr)
end calcExp

–ex – 1 を返す。x は引数で、e は自然対数の底
on calcExpm1(aNum as string)
  set aStr to "Math.expm1(" & aNum & ")"
  
return exeJS(aStr)
end calcExpm1

–引数として与えた数以下の最大の整数を返す
on calcFloor(aNum as string)
  set aStr to "Math.floor(" & aNum & ")"
  
return exeJS(aStr)
end calcFloor

–引数として与えた数の最も近い単精度 floatを返す
on calcFround(aNum as string)
  set aStr to "Math.fround(" & aNum & ")"
  
return exeJS(aStr)
end calcFround

–引数の二乗和の平方根を返す
on calcHypot(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.hypot(" & bStr & ")"
  
return exeJS(aStr)
end calcHypot

— 2 つの引数をとり、C 言語の様な 32 ビット乗算の結果を返す
on calcImul(aNum as string, bNum as string)
  set aStr to "Math.imul(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcImul

— 引数として与えた数の自然対数 (底は e) を返す
on calcLog(aNum as string)
  set aStr to "Math.log(" & aNum & ")"
  
return exeJS(aStr)
end calcLog

— 引数として与えた数に対して、10を底とする対数を返す
on calcLog10(aNum as string)
  set aStr to "Math.log10(" & aNum & ")"
  
return exeJS(aStr)
end calcLog10

— 引数として与えた数と 1 の合計の自然対数(底 e)を返す
on calcLog1p(aNum as string)
  set aStr to "Math.log1p(" & aNum & ")"
  
return exeJS(aStr)
end calcLog1p

— 引数として与えた数の2を底とする対数を返す
on calcLog2(aNum as string)
  set aStr to "Math.log2(" & aNum & ")"
  
return exeJS(aStr)
end calcLog2

–引数として与えた複数の数の中で最大の数を返す
on calcMax(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.max(" & bStr & ")"
  
return exeJS(aStr)
end calcMax

–引数として与えた複数の数の中で最小の数を返す
on calcMin(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.min(" & bStr & ")"
  
return exeJS(aStr)
end calcMin

–引数として与えた複数の数の中で最小の数を返す
on calcPow(aNum as string, bNum as string)
  set aStr to "Math.pow(" & aNum & ", " & bNum & ")"
  
return exeJS(aStr)
end calcPow

–(0以上、1未満)の範囲で浮動小数点の擬似乱数を返す
on calcRandom()
  set aStr to "Math.random()"
  
return (run script aStr in "JavaScript")
end calcRandom

–引数として与えた数を四捨五入して、もっとも近似の整数を返す
on calcRound(aNum as string)
  set aStr to "Math.round(" & aNum & ")"
  
return exeJS(aStr)
end calcRound

–引数として与えた数が正、負、0 のどれであるか示す符号を返す
on calcSign(aNum as string)
  set aStr to "Math.sign(" & aNum & ")"
  
return exeJS(aStr)
end calcSign

–引数として与えた数のサイン(正弦)を返す
on calcSin(aNum as string)
  set aStr to "Math.sin(" & aNum & ")"
  
return exeJS(aStr)
end calcSin

–引数として与えた数のハイパーボリックサインを返す
on calcSinh(aNum as string)
  set aStr to "Math.sinh(" & aNum & ")"
  
return exeJS(aStr)
end calcSinh

–引数として与えた数の平方根を返す
on calcSqrt(aNum as string)
  set aStr to "Math.sqrt(" & aNum & ")"
  
return exeJS(aStr)
end calcSqrt

–引数として与えた数のタンジェントを返す
on calcTan(aNum as string)
  set aStr to "Math.tan(" & aNum & ")"
  
return exeJS(aStr)
end calcTan

–引数として与えた数のハイパーボリックタンジェントを返す
on calcTanh(aNum as string)
  set aStr to "Math.tanh(" & aNum & ")"
  
return exeJS(aStr)
end calcTanh

–引数として与えた数の小数部の桁を取り除いて整数部を返す
on calcTrunc(aNum as string)
  set aStr to "Math.trunc(" & aNum & ")"
  
return exeJS(aStr)
end calcTrunc

–Sub Routines

–リストを指定デリミタをはさんでテキスト化
on retArrowText(aList, aDelim) –自分のASでよく使うハンドラ名称なので、同じものを用意
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retArrowText

–JavaScriptCore版実行部
on exeJS(aStr)
  set theContext to current application’s JSContext’s alloc()’s init()
  
set x to (theContext’s evaluateScript:aStr)’s toNumber()
  
return x as list of string or string –as anything
end exeJS

★Click Here to Open This Script 

(Visited 35 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値演算ライブラリ「calcLibAS」

Posted on 6月 7, 2018 by Takaaki Naganoya

数値演算の関数を35個提供するAppleScript Librariesです。

Cocoa Frameworkを呼び出して計算するよりも262倍、OSAXを呼び出して計算するよりも760倍遅いのですが、関数の数はたいへんに多いです。

スピードが遅い上に数百回連続で呼び出すとScript Editorがクラッシュする傾向があります(本当)。

run scriptコマンドでJavaScript(JXA)を呼び出して計算しているのですが、run script経由でJavaScript(JXA)を呼び出すのがこんなに危険だと思わなかったので、いっそJavaScript Coreを呼び出して実行してみてもよいのかもしれません(それでも高速にはならなさそうで)。

最初は「calcLib」というライブラリをJXAで試しに書いて、AppleScriptから呼び出せないかどうか実験してみたのですが、useコマンドでJXAのライブラリを指定したら「OSA言語が違うので呼び出せないよ」といったエラーになりました(AppleScript用語辞書を用意すれば複数のOSA言語間から利用できるのだと思います、まだやっていませんけれども)。

そのあとで作ったので「calcLibAS」という名前に。

AppleScript名:atan2をライブラリ呼び出しで計算する
— Created 2018-06-06 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use mLib : script "calcLibAS"

set aRes to calcAtan2(10, 20) of mLib

★Click Here to Open This Script 

本ライブラリは~/Library/Script Librariesフォルダなどに入れて呼び出してください。

AppleScript名:calcLibAS
— Created 2018-06-06 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set a01Res to calcAbs(-10) of me –> 10
set a02Res to calcAcos(-1) of me –> 3.14159265359
set a03Res to calcAcosh(10) of me –> 2.993222846126
set a04Res to calcAsin(-1) of me –> -1.570796326795
set a05Res to calcAsinh(10) of me –> 2.998222950298
set a06Res to calcAtan(10) of me –> 1.471127674304
set a07Res to calcAtan2(10, 20) of me –> 0.463647609001
set a08Res to calcAtanh(0.5) of me –> 0.549306144334
set a09Res to calcCbrt(3) of me –> 1.442249570307
set a10Res to calcCeil(0.95) of me –> 1
set a11Res to calcClz32(1) of me –> 31
set a12Res to calcCos(1) of me –> 0.540302305868
set a13Res to calcCosh(1) of me –> 1.543080634815
set a14Res to calcExp(1) of me –> 2.718281828459
set a15Res to calcExpm1(-1) of me –> -0.632120558829
set a16Res to calcFloor(45.95) of me –> 45
set a17Res to calcFround(1.337) of me –> 1.337000012398
set a18Res to calcHypot({3, 4, 5}) of me –> 7.071067811865
set a19Res to calcImul(2, 5) of me –> 10
set a20Res to calcLog(10) of me –> 2.302585092994
set a21Res to calcLog10(2) of me –> 0.301029995664
set a22Res to calcLog1p(1) of me –> 0.69314718056
set a23Res to calcLog2(3) of me –> 1.584962500721
set a24Res to calcMax({1, 2, 3, 4, 6, 2, 10}) of me –> 10
set a25Res to calcMin({1, 2, 3, 4, 6, 2, 10, 0}) of me –> 0
set a26Res to calcPow(7, 2) of me
set a27Res to calcRandom() of me
set a28Res to calcRound(5.95) of me
set a29Res to calcSign(0) of me –> -1/0/1
set a30Res to calcSin(pi / 2) of me –> 1
set a31Res to calcSinh(1) of me –> 1.175201193644
set a32Res to calcSqrt(2) of me –> 1.414213562373
set a33Res to calcTan(30) of me –> -6.405331196646
set a34Res to calcTanh(10) of me –> 0.999999995878
set a35Res to calcTrunc(13.37) of me –> 13

–数値の絶対値を返す
on calcAbs(aNum as string)
  set aStr to "Math.abs(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAbs

–アークコサインをラジアン単位で返す
on calcAcos(aNum as string)
  set aStr to "Math.acos(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAcos

–ハイパーボリックアークコサインを返す
on calcAcosh(aNum as string)
  set aStr to "Math.acosh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAcosh

–アークサインをラジアン単位で返す
on calcAsin(aNum as string)
  set aStr to "Math.asin(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAsin

–ハイパーボリックアークサインを返す
on calcAsinh(aNum as string)
  set aStr to "Math.asinh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAsinh

–アークタンジェントをラジアン単位で返す
on calcAtan(aNum as string)
  set aStr to "Math.atan(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAtan

–アークタンジェントを返す
on calcAtan2(aNum as string, bNum as string)
  set aStr to "Math.atan2(" & aNum & ", " & bNum & ")"
  
return (run script aStr in "JavaScript")
end calcAtan2

–ハイパーボリックアークタンジェントを返す
on calcAtanh(aNum as string)
  set aStr to "Math.atanh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcAtanh

–引数として与えた数の立方根を返す
on calcCbrt(aNum as string)
  set aStr to "Math.cbrt(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcCbrt

–引数として与えた数以上の最小の整数を返す
on calcCeil(aNum as string)
  set aStr to "Math.ceil(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcCeil

–引数として与えた数以上の最小の整数を返す
on calcClz32(aNum as string)
  set aStr to "Math.clz32(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcClz32

–引数として与えた数のコサインを返す
on calcCos(aNum as string)
  set aStr to "Math.cos(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcCos

–引数として与えた数のハイパーボリックコサインを返す
on calcCosh(aNum as string)
  set aStr to "Math.cosh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcCosh

–Ex を返す。ここでの x は引数、E は、自然対数の底であるネイピア数(オイラー数)
on calcExp(aNum as string)
  set aStr to "Math.exp(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcExp

–ex – 1 を返す。x は引数で、e は自然対数の底
on calcExpm1(aNum as string)
  set aStr to "Math.expm1(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcExpm1

–引数として与えた数以下の最大の整数を返す
on calcFloor(aNum as string)
  set aStr to "Math.floor(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcFloor

–引数として与えた数の最も近い単精度 floatを返す
on calcFround(aNum as string)
  set aStr to "Math.fround(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcFround

–引数の二乗和の平方根を返す
on calcHypot(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.hypot(" & bStr & ")"
  
return (run script aStr in "JavaScript")
end calcHypot

— 2 つの引数をとり、C 言語の様な 32 ビット乗算の結果を返す
on calcImul(aNum as string, bNum as string)
  set aStr to "Math.imul(" & aNum & ", " & bNum & ")"
  
return (run script aStr in "JavaScript")
end calcImul

— 引数として与えた数の自然対数 (底は e) を返す
on calcLog(aNum as string)
  set aStr to "Math.log(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcLog

— 引数として与えた数に対して、10を底とする対数を返す
on calcLog10(aNum as string)
  set aStr to "Math.log10(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcLog10

— 引数として与えた数と 1 の合計の自然対数(底 e)を返す
on calcLog1p(aNum as string)
  set aStr to "Math.log1p(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcLog1p

— 引数として与えた数の2を底とする対数を返す
on calcLog2(aNum as string)
  set aStr to "Math.log2(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcLog2

–引数として与えた複数の数の中で最大の数を返す
on calcMax(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.max(" & bStr & ")"
  
return (run script aStr in "JavaScript")
end calcMax

–引数として与えた複数の数の中で最小の数を返す
on calcMin(aList as list)
  set bStr to retArrowText(aList, ", ") of me
  
set aStr to "Math.min(" & bStr & ")"
  
return (run script aStr in "JavaScript")
end calcMin

–引数として与えた複数の数の中で最小の数を返す
on calcPow(aNum as string, bNum as string)
  set aStr to "Math.pow(" & aNum & ", " & bNum & ")"
  
return (run script aStr in "JavaScript")
end calcPow

–(0以上、1未満)の範囲で浮動小数点の擬似乱数を返す
on calcRandom()
  set aStr to "Math.random()"
  
return (run script aStr in "JavaScript")
end calcRandom

–引数として与えた数を四捨五入して、もっとも近似の整数を返す
on calcRound(aNum as string)
  set aStr to "Math.round(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcRound

–引数として与えた数が正、負、0 のどれであるか示す符号を返す
on calcSign(aNum as string)
  set aStr to "Math.sign(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcSign

–引数として与えた数のサイン(正弦)を返す
on calcSin(aNum as string)
  set aStr to "Math.sin(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcSin

–引数として与えた数のハイパーボリックサインを返す
on calcSinh(aNum as string)
  set aStr to "Math.sinh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcSinh

–引数として与えた数の平方根を返す
on calcSqrt(aNum as string)
  set aStr to "Math.sqrt(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcSqrt

–引数として与えた数のタンジェントを返す
on calcTan(aNum as string)
  set aStr to "Math.tan(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcTan

–引数として与えた数のハイパーボリックタンジェントを返す
on calcTanh(aNum as string)
  set aStr to "Math.tanh(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcTanh

–引数として与えた数の小数部の桁を取り除いて整数部を返す
on calcTrunc(aNum as string)
  set aStr to "Math.trunc(" & aNum & ")"
  
return (run script aStr in "JavaScript")
end calcTrunc

–Sub Routines

–リストを指定デリミタをはさんでテキスト化
on retArrowText(aList, aDelim) –自分のASでよく使うハンドラ名称なので、同じものを用意
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retArrowText

(*
–run scriptコマンドに問題が出た場合にはJavaScriptCoreなどで実行してもよさそう
on run script aStr in osaLangName
  display dialog aStr
end run script
*)

★Click Here to Open This Script 

(Visited 104 times, 1 visits today)
Posted in JXA Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定のリスト中の指定要素が占める割合をパーセントで返す

Posted on 5月 11, 2018 by Takaaki Naganoya

指定List中の指定要素が占める割合をパーセントの数値で返すAppleScriptです。

ローカルのiTunesライブラリに入っている楽曲のアーティスト名を集計して、各アーティストがiTunes Music Storeで販売している楽曲のうち、どの程度の割合でApple Musicでも配信しているかを調査するAppleScriptを作成するために作成したものです。

AppleScript名:指定のリスト中の指定要素が占める割合をパーセントで返す
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, true, true, true, false, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}

set tPercent to calcOneItemsPercent(aList, true) of me
–> 62 (%)

–true/falseで構成されるlistのうち、指定要素が占める割合を%で計算。小数点以下を四捨五入
on calcOneItemsPercent(aList, targItem)
  set aLen to length of aList
  
set theCountedSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
  
set tRes to (theCountedSet’s countForObject:targItem)
  
if tRes < 1 then return 0
  
set pRes to (tRes / aLen) * 100
  
return (round pRes rounding as taught in school)
end calcOneItemsPercent

★Click Here to Open This Script 

(Visited 25 times, 1 visits today)
Posted in list Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

atan2をFramework呼び出しで計算する

Posted on 5月 8, 2018 by Takaaki Naganoya

自作のCocoa Frameworkを呼び出してatan2の値を計算するAppleScriptです。

2点の緯度経度情報同士の方位(角度)を計算するatan2は、位置情報計算において割と重要な関数ですが、AppleScriptの標準状態では利用できません。

Satimage SoftwareのSatimage OSAX(フリー)をインストールすることでAppleScript中から利用できるようになりますが、これだけだといまひとつ不安なので、atan2を呼び出すだけの簡単なCocoa FrameworkをObjective-Cで記述して、呼び出してみました。

trigonometry.framework (To ~/Library/Frameworks)

Cocoa FrameworkとAppleScriptの間ではNSNumberでやりとりしますが、atan2の計算をObjective-C内で行うにはCGFloatで値を渡す必要がありました(maybe)。また、atan2の計算後に結果をCGFloatからNSNumberに変換。この計算結果をAppleScriptで受け取っています。

一応、両方の計算結果を付けあわせて0〜180度、0〜-180度の範囲で検算を行なったところ、同じ結果が得られました。

atan2の計算速度について、Satimage OSAXとFramework呼び出しで比較してみたところ(1万回ループで計測)、

  Satimage OSAX:0.0000224 sec
  Cocoa Framework:0.0000649 sec

と、OSAXよりもFramework呼び出しのほうが3倍時間がかかることがわかりました。ただし、1回あたりの所要時間がごくごく短いので、あまり問題にならないレベルでしょう。

Numbers.appの内部で利用している関数ライブラリ「cephes math library」をCocoa FrameworkにWrappingした「ObjectiveCephes」が存在しているものの、同ライブラリがCのライブラリであるためか、入出力をNSNumberで行うことができない仕様になっていました(処理速度を確保するため???)。このatan2の計算フレームワークと同様にパラメータをcastするようにすれば、cephes math libraryに含まれる各関数をAppleScriptから利用できることになるはずです。

AppleScript名:atan2をFramework呼び出しで計算する
— Created 2018-05-07 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "trigonometry" –By myself

set aNum to 10
set bNum to 20
set aList to {aNum, bNum}
set cNum to atan2 aList –SatImage OSAX
–>  0.463647609001

set dNum to (current application’s calcAtan2’s atan2Num:aNum withNum:bNum) as real
–>  0.463647609001

★Click Here to Open This Script 

AppleScript名:atan2をFramework呼び出しで計算する(検算)
— Created 2018-05-07 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "trigonometry" –By myself

set aNum to 0
set notMatchList to {}

repeat with bNum from 0 to 180
  set aList to {aNum, bNum}
  
set cNum to atan2 aList –SatImage OSAX
  
set dNum to (current application’s calcAtan2’s atan2Num:aNum withNum:bNum) as real
  
  
if cNum is not equal to dNum then
    set the end of notMatchList to {cNum, dNum}
  end if
end repeat

repeat with bNum from 0 to -180 by -1
  set aList to {aNum, bNum}
  
set cNum to atan2 aList –SatImage OSAX
  
set dNum to (current application’s calcAtan2’s atan2Num:aNum withNum:bNum) as real
  
  
if cNum is not equal to dNum then
    set the end of notMatchList to {cNum, dNum}
  end if
end repeat

return notMatchList

★Click Here to Open This Script 

(Visited 54 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

テキストのパーセント表記を数値に変換する

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:テキストのパーセント表記を数値に変換する
— Created 2018-03-18 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to current application’s NSString’s stringWithString:"80%"
set aNum to aStr’s intValue()
–>  80

set bNum to aStr’s doubleValue()
–>  80.0

★Click Here to Open This Script 

(Visited 40 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ベクトルの長さを求める

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:ベクトルの長さを求める
set vL to getVectorLength(5, 2) of me

–ベクトルの長さを求める
on getVectorLength(a, b)
  return getSQR(a ^ 2 + b ^ 2) of me
end getVectorLength

–平方根を求める
on getSQR(aNum)
  return (aNum ^ 0.5)
end getSQR

★Click Here to Open This Script 

(Visited 24 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指数表示数値を文字列化

Posted on 2月 24, 2018 by Takaaki Naganoya

指数表示の数値を文字列化するAppleScriptです。

AppleScriptの数値変数で表現可能な範囲は割と狭く、±1.79769E308。実数部は9桁です。

そのため、不意に指数表示になってしまったデータから指数表現を解除して、数値文字列に変換し、適宜bcコマンドなどで数値文字列同士の演算を行うことがままあります。そういう場合に使用します。

AppleScript text item delimitersを活用していることから、あきらかに自分が組んだScriptではありません(なるべく避けるので)。たぶん、Mailing Listに流れていたScriptです。

AppleScript名:指数表示数値を文字列化
set longNumber to "1082204521"
set exponent to longNumber as number –> 1.082204521E+9
set numberString to Stringify(exponent)

on Stringify(x) — for E+ numbers
  set x to x as string
  
set {tids, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, {"E+"}}
  
if (count (text items of x)) = 1 then
    set AppleScript’s text item delimiters to {tids}
    
return x
  else
    set {n, z} to {text item 1 of x, (text item 2 of x) as integer}
    
set AppleScript’s text item delimiters to {tids}
    
set i to character 1 of n
    
set decSepChar to character 2 of n — "." or ","
    
set d to text 3 thru -1 of n
    
set l to count d
    
if l > z then
      return (i & (text 1 thru z of d) & decSepChar & (text (z + 1) thru -1 of d))
    else
      repeat (z – l) times
        set d to d & "0"
      end repeat
      
return (i & d)
    end if
  end if
end Stringify

★Click Here to Open This Script 

(Visited 167 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

序数を求めるルーチン同士を比較

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:序数を求めるルーチン同士を比較
repeat with i from 1 to 1000
  set a to retOrdinalNumStr(i) of me
  
set b to getOrdinalNumber(i) of me
  
  
log {a, b}
end repeat

–数値を与えると序数の文字列を返す
on retOrdinalNumStr(aNum)
  set aStr to aNum as string
  
  
–下1桁の数字を取得
  
set last1Str to last character of aStr
  
  
–下2桁目の数字を取得
  
if length of aStr > 1 then
    set last2Str to character -2 of aStr
  else
    set last2Str to ""
  end if
  
  
–場合分け
  
set retStr to ""
  
if last1Str = "1" then
    if last2Str = "1" then
      set retStr to "th" –11
    else
      set retStr to "st"
    end if
    
  else if last1Str = "2" then
    if last2Str = "1" then
      set retStr to "th" –12
    else
      set retStr to "nd"
    end if
    
  else if last1Str = "3" then
    if last2Str = "1" then
      set retStr to "th" –13
    else
      set retStr to "rd"
    end if
    
  else
    set retStr to "th"
    
  end if
  
  
return aStr & retStr
  
end retOrdinalNumStr

— 序数表現に変更
on getOrdinalNumber(anyInteger)
  
  
if (anyInteger mod 10) = 1 and (anyInteger mod 100) ≠ 11 then
    set tempList to anyInteger & "st"
  else if (anyInteger mod 10) = 2 and (anyInteger mod 100) ≠ 12 then
    set tempList to anyInteger & "nd"
  else if (anyInteger mod 10) = 3 and (anyInteger mod 100) ≠ 13 then
    set tempList to anyInteger & "rd"
  else
    set tempList to anyInteger & "th"
  end if
  
  
return tempList as text
  
end getOrdinalNumber

★Click Here to Open This Script 

(Visited 32 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

奇数かどうかチェック

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:奇数かどうかチェック
set a to 5
set aRes to chkOddNum(a) of me
–> true

set b to 8
set bRes to chkEvenNum(b) of me
–> true

–奇数かどうかチェック
on chkOddNum(aNum)
  set a to aNum mod 2
  
if a = 1 then
    return true
  else
    return false
  end if
end chkOddNum

–偶数かどうかチェック
on chkEvenNum(aNum)
  set a to aNum mod 2
  
if a = 0 then
    return true
  else
    return false
  end if
end chkEvenNum

★Click Here to Open This Script 

(Visited 157 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

文字で書いた数値を本物の数値に変換

Posted on 2月 24, 2018 by Takaaki Naganoya

仰々しくタイトルを書いていますが、なんのことはない文字で書いた数字文字列の数値へのcastを行う処理です。

AppleScriptのネイティブのやりかただと、

set a to "12345"
set b to a as number

という程度ですみます(Adobe Illustratorへのtellブロック内で上記のScriptを実行しないでください。L*a*b*色空間のaとbの1文字の予約語を持っているので、動作がおかしくなります)。

本Scriptで紹介しているのは、Cocoaのオブジェクトの数値文字列をCocoaの数値オブジェクト(NSNumber)に変換するものです。

本来はNSNumberのままなのですが、Scripting Bridgeの仕様でNSNumberになったものは自動でAppleScriptの数値まで変換されます。

AppleScript名:文字で書いた数値を本物の数値に変換
— Created 2014-12-28 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set j to "123456789"
set aStr to current application’s NSString’s stringWithString:j
set aNum to aStr’s intValue()

★Click Here to Open This Script 

(Visited 510 times, 2 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値の桁数を求める v2

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:数値の桁数を求める v2
— Created 2014-12-04 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"

set aList to {}
set aRes to 0

repeat with i from 1 to 9999 by 1
  set d to getDigit(i) of me
  
  
if aRes is not equal to d then
    set the end of aList to {i, d}
    
set aRes to d
  end if
end repeat
aList
–> {{1, 1}, {10, 2}, {100, 3}, {1000, 4}}

–数値の桁数を求める(マイナスの数は想定外)
on getDigit(aNum as integer)
  load framework
  
set b to ((current application’s SMSForder’s log10ValueOf:aNum))
  
set c to b as real
  
set d to round c rounding down
  
return (d + 1)
end getDigit

★Click Here to Open This Script 

BridgePlusがmacOS 10.15以降でうまく動かない環境もあるので、数値演算ライブラリcalcLibASを呼び出すものも掲載しておきます。

AppleScript名:数値の桁数を求める v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/06/30
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use calSub : script "calcLibAS" –http://piyocast.com/as/asinyaye

set aRes1 to getNumDigit(-9999) of me
–> 3

set aRes2 to getNumDigit(100) of me
–> 2

on getNumDigit(aNum)
  set a2Val to abs aNum
  
return round (log10 a2Val) rounding down
end getNumDigit

★Click Here to Open This Script 

(Visited 51 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値にゼロパディングしたテキストを返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:数値にゼロパディングしたテキストを返す
set aNum to 1
set aStr to retZeroPaddingText(aNum, 4) of me

–数値にゼロパディングしたテキストを返す
on retZeroPaddingText(aNum, aLen)
  set tText to ("0000000000" & aNum as text)
  
set tCount to length of tText
  
set resText to text (tCount – aLen + 1) thru tCount of tText
  
return resText
end retZeroPaddingText

★Click Here to Open This Script 

(Visited 216 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

数値を指定桁でゼロパディング

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:数値を指定桁でゼロパディング
— Created 2015-08-05 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aTEXT to numToZeroPaddingStr(99, 4, "0")
–>  "0099"

set aTEXT to numToZeroPaddingStr(99999999, 20, "0")
–> "00000000000099999999"

–整数の値に指定桁数ゼロパディングして文字列で返す
on numToZeroPaddingStr(aNum as integer, aDigit as integer, paddingChar as text)
  
  
set aNumForm to current application’s NSNumberFormatter’s alloc()’s init()
  
aNumForm’s setPaddingPosition:(current application’s NSNumberFormatterPadBeforePrefix)
  
aNumForm’s setPaddingCharacter:paddingChar
  
aNumForm’s setMinimumIntegerDigits:aDigit
  
  
set bNum to current application’s NSNumber’s numberWithInt:aNum
  
set aStr to aNumForm’s stringFromNumber:bNum
  
  
return aStr as text
  
end numToZeroPaddingStr

★Click Here to Open This Script 

(Visited 86 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ローマ数字エンコーダー、デコーダー v2

Posted on 2月 23, 2018 by Takaaki Naganoya
AppleScript名:ローマ数字エンコーダー、デコーダー v2
— Created 2015-11-16 by Takaaki Naganoya
— Modified 2017-05-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://stackoverflow.com/questions/14762282/how-to-convert-a-roman-numeral-to-an-nsnumer

repeat with i from 1 to 3999
  set aRes to numberToRomanNumerals(i) of me
  
set bRes to romanNumeralsToNumber(aRes) of me
  
log {i, aRes, bRes}
end repeat

–Roman Number String Encoder
on numberToRomanNumerals(aNum)
  if (aNum < 0 or aNum > 3999) then return "" –条件が間違っていたので直した(2017/5/18)
  
  
set r_ones to {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
  
set r_tens to {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
  
set r_hunds to {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
  
set r_thouds to {"M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM", "MMMMMMMMM"}
  
  
set ones to aNum mod 10
  
set tens to (aNum – ones) mod 100
  
set hundreds to (aNum – tens – ones) mod 1000
  
set thou to (aNum – hundreds – tens – ones) mod 10000
  
  
set tens to tens / 10
  
set hundreds to hundreds / 100
  
set thou to thou / 1000
  
  
set rNum to current application’s NSString’s stringWithString:""
  
  
if thou > 0 then set rNum to rNum’s stringByAppendingString:(item thou of r_thouds)
  
if hundreds > 0 then set rNum to rNum’s stringByAppendingString:(item hundreds of r_hunds)
  
if tens > 0 then set rNum to rNum’s stringByAppendingString:(item tens of r_tens)
  
if ones > 0 then set rNum to rNum’s stringByAppendingString:(item ones of r_ones)
  
  
return rNum as text
end numberToRomanNumerals

–Roman Number String Decoder
on romanNumeralsToNumber(str)
  — Piero Garzotto (http://scriptbuilders.net/files/romannumerals1.0.html)
  
local str, r, i
  
set r to 0
  
repeat with i from 1 to count str
    set r to r + (item (offset of (item i of str) in "mdclxvi") of ¬
      {1000, 500, 100, 50, 10, 5, 1}) * (((((offset of ¬
      (
item (i + 1) of (str & "@")) in "mdclxvi@") ≥ (offset of ¬
      (
item i of str) in "mdclxvi")) as integer) * 2) – 1)
  end repeat
  
return r
end romanNumeralsToNumber

★Click Here to Open This Script 

(Visited 34 times, 1 visits today)
Posted in Number Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ABSを求める

Posted on 2月 23, 2018 by Takaaki Naganoya
AppleScript名:ABSを求める
set x to -44
set x to absNum(x)
–> 44

on absNum(q)
  if q is less than 0 then set q to –q
  
return q
end absNum

★Click Here to Open This Script 

(Visited 50 times, 1 visits today)
Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 13, Ventura(継続更新)
  • ドラッグ&ドロップ機能の未来?
  • macOS 12.x上のAppleScriptのトラブルまとめ
  • PFiddlesoft UI Browserが製品終了に
  • macOS 12.3 beta 5、ASの障害が解消される(?)
  • SF Symbolsを名称で指定してPNG画像化
  • 新刊発売:AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 12.3 beta4、まだ直らないASまわりの障害
  • macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件
  • Safariで表示中のYouTubeムービーのサムネイル画像を取得
  • macOS 12のスクリプトエディタで、Context Menu機能にバグ
  • Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加
  • 人類史上初、魔導書の観点から書かれたAppleScript入門書「7つの宝珠」シリーズ開始?!
  • CotEditor v4.1.2でAppleScript系の機能を追加
  • macOS 12.5(21G72)がリリースされた!
  • UI Browserがgithub上でソース公開され、オープンソースに
  • Pages v12に謎のバグ。書類上に11枚しか画像を配置できない→解決
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (434) 11.0savvy (274) 12.0savvy (174) 13.0savvy (34) CotEditor (60) Finder (47) iTunes (19) Keynote (97) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (21) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (42) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (118) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSUUID (18) NSView (33) NSWorkspace (20) Numbers (55) Pages (36) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC