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

16進数の計算

Posted on 1月 25 by Takaaki Naganoya

ちょっとした16進数の計算を行いたいときに、AppleScriptのネイティブ機能にはそういうのはないので、別のものが持っている機能を利用することになります。

いろいろCocoa系の機能も探してみたものの、結局「shellのbcコマンドが手っ取り早くていいよね!」ということに。

ポケコンサークルの会誌のダンプリストをもとに、入力用のBASICのリストを自動作成するとき、アドレスを変更しなくては入力できないことが判明。このさい、アドレス計算を行うのに16進数の加算が必要でした。そのために作ってみたものです。

AppleScript名:16進数の計算.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/25
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set a to "8030"
set b to "6000"
set h1 to hexStrAdd(a, b) of me
–> "E030"

set h3 to hexStrSub(a, b) of me
–> "2030"

on hexStrAdd(aStr as string, bStr as string)
  set sStr to "echo \"ibase=10; obase=10; " & aStr & "+" & bStr & "\" | bc"
  
set aRes to do shell script sStr
  
return aRes as string
end hexStrAdd

on hexStrSub(aStr as string, bStr as string)
  set sStr to "echo \"ibase=10; obase=10; " & aStr & "-" & bStr & "\" | bc"
  
set aRes to do shell script sStr
  
return aRes as string
end hexStrSub

★Click Here to Open This Script 

(Visited 20 times, 1 visits today)
Posted in Hex Number | Tagged 13.0savvy | Leave a comment

AppleScriptの数値変数で指数表示にならない最大値、最小値

Posted on 9月 26, 2022 by Takaaki Naganoya

いろいろ、本に書くさいに「数値9桁」みたいに書くことが多いですが、本当にギリギリまで指数表示にならない数値というのは、調べたことはありませんでした。

そこで、スクリプトエディタ上で指数表示にならないギリギリの数値を確認してみたところ、

±536,870,911

でした。日本語数値表現でいえば、5億3,687万911です。これは、macOS 12.6+M1 Mac mini上のスクリプトエディタで確認した数値です。

AppleScript名:指数表示にならない最大値と最小値.scpt
set a to 536870911
set b to -536870911
return {a, b}

★Click Here to Open This Script 

(Visited 28 times, 1 visits today)
Posted in Number | Leave a comment

AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib

Posted on 8月 22, 2022 by Takaaki Naganoya

AS関連データの取り扱いを簡単にすることを目的に書き出した、privateDatatypeLibです。

プログラムとデータを分離して、データ記述部分を外部ファイル(設定ファイルなど)に追い出したときに、どのようなデータかを表現するための道具として試作してみました。

macOS上のデータ記述子は、

などのさまざまなデータ識別方法が存在していますが、どれも(自分の)用途には合わなかったので、検討・試作をはじめてみました。Predicatesが一番近いものの、不十分なのでいろんなデータ型や用途に拡張。あくまで自分用なので「public」などの宣言はとくに不必要と考え、縮小して処理を行なっています。

とくに、ファイルパスの処理なんて定型処理しかしないのに、わざわざ何かの表現を行う必要があるのはナンセンスですし、日付関連も割と余計な記述が多いように感じています。

また、緯度/経度のデータや座標データなども、もう少しなんとかならないかと思っています。

AppleScript名:privateDataTypeLib.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/08/22
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aData to "100"
set dType to "@number"
set bData to "" –不要なケース多数。不要な場合にはヌル文字を指定
set mePath to path to me –実際には、呼び出し側で取得して指定。ライブラリ自体のパスを求めているのはテスト実行時のみ
set aRes to getParameterAndCalc(aData, dType, bData, mePath) of me

on getParameterAndCalc(aData, dType, bData, mePath)
  if dType = "@string" then
    return normalizeByNFC(aData) of me
    
  else if dType = "@number" then
    set tmpA to zenToHan(aData) of charConvKit of me –全角→半角変換
    
set a to detectOutNumStr(tmpA) of me –数字+関連・意外の文字を除外
    
return normalizeByNFC(a) of me
    
  else if dType = "@filepath.sub.foldername" then
    set aClass to class of aData –aliasだったらPOSIX pathに変換。file…はどうなんだか
    
if aClass = alias then set aData to POSIX path of aData
    
return aData & bData & "/"
    
  else if dType = "@file.comment" then
    set aStr to getFinderComment(POSIX path of mePath) of me
    
return normalizeByNFC(aStr) of me
    
  else if dType = "@file.name" then
    set aClass to class of aData
    
if aClass = alias then set aData to POSIX path of aData
    
set aStr to (current application’s NSString’s stringWithString:aData)’s lastPathComponent()’s stringByDeletingPathExtension()
    
return normalizeByNFC(aStr as string) of me
    
  else if dType = "@date.month" then
    set curDate to current date
    
set curMonth to month of curDate as number
    
return curMonth as string
    
  else
    return aData
  end if
end getParameterAndCalc

on normalizeByNFC(aStr)
  set aNSStr to current application’s NSString’s stringWithString:aStr
  
set aNFC to aNSStr’s precomposedStringWithCanonicalMapping()
  
return aNFC as string
end normalizeByNFC

–ANK文字列以外のものをそぎ落とす
on detectOutNumStr(testStr)
  set sList to characters of testStr
  
set aStr to ""
  
  
repeat with i in sList
    if detectOutNumChar(i) of me then
      set aStr to aStr & (i as string)
    end if
  end repeat
  
  
return aStr
end detectOutNumStr

on detectOutNumChar(testText)
  –Numeric + Special char
  
set ankChar to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-", "+", "E", ","}
  
  
set _testChar to testText as Unicode text
  
  
ignoring case
    repeat with i in _testChar
      set j to contents of i
      
if j is not in ankChar then
        return false
      end if
    end repeat
  end ignoring
  
  
return true
end detectOutNumChar

–Finderコメントを取得
on getFinderComment(aPOSIX)
  set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIX
  
set aMetaInfo to current application’s NSMetadataItem’s alloc()’s initWithURL:aURL
  
set metaDict to (aMetaInfo’s valuesForAttributes:{"kMDItemFinderComment"}) as record
  
if metaDict = {} then return ""
  
set aComment to kMDItemFinderComment of (metaDict)
  
return aComment
end getFinderComment

script charConvKit
  — Created 2017-09-06 by Shane Stanley
  
— Modified 2017-09-06 by Takaaki Naganoya
  
use AppleScript
  
use framework "Foundation"
  
property parent : AppleScript
  
  
property NSString : a reference to current application’s NSString
  
property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth
  
property NSStringTransformHiraganaToKatakana : a reference to current application’s NSStringTransformHiraganaToKatakana
  
property NSStringTransformLatinToHiragana : a reference to current application’s NSStringTransformLatinToHiragana
  
property NSStringTransformLatinToKatakana : a reference to current application’s NSStringTransformLatinToKatakana
  
property NSStringTransformToUnicodeName : a reference to current application’s NSStringTransformToUnicodeName
  
property NSStringTransformToXMLHex : a reference to current application’s NSStringTransformToXMLHex
  
  
–半角→全角変換
  
on hanToZen(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:true) as string
  end hanToZen
  
  
–全角→半角変換
  
on zenToHan(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string
  end zenToHan
  
  
–ひらがな→カタカナ変換
  
on hiraganaToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:false) as string
  end hiraganaToKatakana
  
  
–カタカナ→ひらがな変換
  
on katakanaToHiraganaTo(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:true) as string
  end katakanaToHiraganaTo
  
  
–ローマ字→ひらがな変換
  
on alphabetToHiragana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:false) as string
  end alphabetToHiragana
  
  
–ひらがな→ローマ字変換
  
on hiraganaToalphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:true) as string
  end hiraganaToalphabet
  
  
–ローマ字→カタカナ変換
  
on alphabetToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:false) as string
  end alphabetToKatakana
  
  
–カタカナ→ローマ字変換
  
on katakanaToAlphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:true) as string
  end katakanaToAlphabet
  
  
–文字→Unicode Name変換
  
on characterToUnicodeName(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:false) as string
  end characterToUnicodeName
  
  
–Unicode Name→文字変換
  
on unicodeNameToCharacter(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:true) as string
  end unicodeNameToCharacter
  
  
–文字→XML Hex変換
  
on stringToXMLHex(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:false) as string
  end stringToXMLHex
  
  
–XML Hex→文字変換
  
on xmlHexTostring(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:true) as string
  end xmlHexTostring
end script

★Click Here to Open This Script 

(Visited 63 times, 1 visits today)
Posted in Calendar file File path folder Library Number Text URL | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | 1 Comment

選択中の表の指定行・列のマル付き数字リナンバー v3

Posted on 12月 4, 2021 by Takaaki Naganoya

Keynoteの現在オープン中の書類の、現在表示中のスライド(ページ)上にある、選択中の表オブジェクトの、選択中のセルに入っているマルつき数字(①②③….)を左から順番にリナンバーするAppleScriptです。

以前のバージョン(v2)では処理対象行や列をダイアログ上で選択するようになっていましたが、本バージョンではKeynote上で処理対象のセルを選択しておくことで処理範囲をScript側に知らせるようにしました。

選択範囲のセルのデータを取得し、それらに入っているマルつき数字の最小値を計算し、ユーザーに開始値としてダイアログで確認を行います。前バージョンと違ってユーザーに確認するのはこの点だけです。

すぐに選択範囲のセルのテキスト冒頭に入っているマルつき数字をリナンバーします。本Scriptにおけるマルつき数字の範囲は1から50です(白地のマルつき数字に限る)。

AppleScript名:選択中の表の指定行・列のマル付き数字リナンバー v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/12/03
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — macOS 10.13 or later
use framework "Foundation"
use scripting additions

set aOffset to 0

–現在選択中の表オブジェクトを取得
set curTable to returnSelectedTableOnCurrentSlide() of me
if curTable = false then return

–現在選択中の表オブジェクト中の選択範囲(range)を取得
set aRange to returnSelectedRangeOnCurrentSlide() of me
if aRange = false then
  display dialog ""
  
return
end if

–現在選択中の表オブジェクト中の選択範囲中のセルをすべて取得(1D List)
using terms from application "Keynote"
  tell curTable
    set cellList to every cell of range aRange
  end tell
end using terms from

–現在選択中の表オブジェクト中の選択範囲中のセルの値をすべて取得(1D List)
set aList to returnSelectedTableCellDataOnCurrentSlide() of me
set bList to cleanUp1DList(aList, missing value) of me

—データ中に丸つき数字が存在した場合には、最小のものを取得
set aOffset to (getMinimumNumFromNumberWithSign(bList) of me)

–一応、ユーザーに推測した開始値でよいか確認を取る
set dRes to text returned of (display dialog "丸つき数字の開始値:" default answer (aOffset as string))
try
  set aOffset to (dRes as number) – 1
on error
  set aOffset to 0
end try

–Keynoteの表のセルから取得したデータから丸つき数字を除去する
set cList to removeNumberWithSignFromList(bList) of me

–list中の各アイテムの冒頭に順次丸つき数字を追加する
set dList to {}
set aCount to 1

repeat with i in cList
  set j to convNumToNumWithSign(aCount + aOffset) of me
  
set jj to contents of i
  
  
set the end of dList to (j & jj)
  
  
set aCount to aCount + 1
end repeat

–リナンバー対象のセルをリナンバーした丸つき数字+内容で置換
set aCount to 1
using terms from application "Keynote"
  tell curTable
    repeat with i in cellList
      set value of i to contents of item aCount of dList
      
set aCount to aCount + 1
    end repeat
  end tell
end using terms from

–1~50の範囲の数値を丸つき数字に変換して返す
on convNumToNumWithSign(aNum as number)
  if (aNum ≤ 0) or (aNum > 50) then return ""
  
set aStr to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set bChar to character aNum of aStr
  
return bChar
end convNumToNumWithSign

–1D List上で指定データを検索してヒットしたアイテム番号を返す
on search1DList(aList, aTarg)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aList
  
set anIndex to anArray’s indexOfObject:aTarg
  
if (anIndex = current application’s NSNotFound) or (anIndex > 9.99999999E+8) then
    return false
  end if
  
return (anIndex as integer) + 1 –convert index base (0 based to 1 based)
end search1DList

–1D listのクリーニング
on cleanUp1DList(aList as list, cleanUpItems as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
if j is not in cleanUpItems then
      set the end of bList to j
    else
      set the end of bList to ""
    end if
  end repeat
  
return bList
end cleanUp1DList

–text in listから丸つき数字を除去する
on removeNumberWithSignFromList(aList as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
set j2 to removeNumberWithSign(j) of me
    
set the end of bList to j2
  end repeat
  
return bList
end removeNumberWithSignFromList

–文字列から丸つき数字を除去する
on removeNumberWithSign(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeNumberWithSign

–1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める
on getMinimumNumFromNumberWithSign(aList)
  set nList to {}
  
  
repeat with i in aList
    set j to contents of i
    
–与えられたテキストのうち、丸つき数字(白)の
    
set j2 to holdNumberWithSignOnly(j) of me
    
set n2List to characters of j2 –複数の丸つき数字が入っている場合に対処
    
    
repeat with ii in n2List
      set jj to contents of ii
      
set tmpNum to decodeNumFromNumWithSign(jj) of me
      
set the end of nList to tmpNum
    end repeat
    
  end repeat
  
  
set anArray to current application’s NSArray’s arrayWithArray:nList
  
set cRes to (anArray’s valueForKeyPath:"@min.self") as integer
  
return cRes
end getMinimumNumFromNumberWithSign

–指定文字列から丸つき数字のみ抽出する
on holdNumberWithSignOnly(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[^\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end holdNumberWithSignOnly

–丸つき数字を数値にデコードする v2
on decodeNumFromNumWithSign(aStr as string)
  set numStr1 to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set numStr2 to "❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴"
  
set numStr3 to "➀➁➂➃➄➅➆➇➈➉"
  
set numStr4 to "➊➋➌➍➎➏➐➑➒➓"
  
set numStr5 to "⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾"
  
  
set nList to {numStr1, numStr2, numStr3, numStr4, numStr5}
  
  
repeat with i in nList
    set numTemp to contents of i
    
if numTemp contains aStr then
      using terms from scripting additions
        set bNum to offset of aStr in numTemp
      end using terms from
      
return bNum
    end if
  end repeat
  
return false
end decodeNumFromNumWithSign

–現在のスライド上で選択中の表オブジェクトへの参照を取得する
on returnSelectedTableOnCurrentSlide()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
return theTable
        
      end tell
    end tell
  end tell
end returnSelectedTableOnCurrentSlide

–現在のスライド上で選択中の表オブジェクト内の選択中のセルの値を取得する
on returnSelectedTableCellDataOnCurrentSlide()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
tell theTable
          set vList to value of every cell of selection range
          
set cCount to count of column of selection range
          
set rCount to count of row of selection range
          
          
if rCount > 1 then return false –複数行選択されていた場合にはエラーを返す
          
          
return vList
        end tell
      end tell
    end tell
  end tell
end returnSelectedTableCellDataOnCurrentSlide

–現在のスライド上で選択中の表オブジェクト内の選択中の範囲(range)のnameを取得する
on returnSelectedRangeOnCurrentSlide()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
tell theTable
          set aPref to properties of selection range
          
set aRangeStr to name of aPref
          
return aRangeStr
        end tell
      end tell
    end tell
  end tell
end returnSelectedRangeOnCurrentSlide

★Click Here to Open This Script 

(Visited 45 times, 1 visits today)
Posted in list Number | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | Leave a comment

選択中の表の指定行・列のマル付き数字リナンバー v2

Posted on 11月 27, 2021 by Takaaki Naganoya

Keynote書類の現在表示中のスライド(ページ)中の選択中の「表」において、指定の行、指定のヘッダー列以降のセルに対して、(1)丸つき数字の削除 (2)丸つき数字の最小値の計算 を行い、丸つき数字の番号降り直しの開始値をユーザーに確認したうえで、丸つき数字部分のみのリナンバーを行います。

本ScriptはmacOS 12+Keynote v11.2で作成・動作確認を行なってあります。それほどOSおよびKeynoteのバージョンに依存するような処理は行なっていないため、上記以外のOSおよびKeynoteのバージョンの組み合わせでも動くと思います。

–> Watch Demo Movie

初期状態では、

と、丸つき数字のナンバリングが項目の入れ替えなどで正しく並んでいない状態を想定しています。

リナンバー対象の表を選択した状態で本Scriptを実行すると、

リナンバー対象行の問い合わせを行います。一番左の列のデータを抽出して選択させます。この場合には、「名称」を選択します。

次に、リナンバー対象データの列指定を行います。指定列「以降」から「末尾」までをリナンバー処理対象とみなします。この場合には「名称」を選択します。

最後に、丸つき数字のリナンバー開始数値を確認します。

すでに、対象範囲のデータを取り出して丸つき数字の最小値については計算してあるので、その確認のためにダイアログ入力を求めます。推測した数値でよければOKを、修正の必要があれば数値を変更したうえでOKボタンをクリック。

適切に処理が行われれば、丸つき数字部分のリナンバーが完了することでしょう。

AppleScript名:選択中の表の指定行・列のマル付き数字リナンバー v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/11/26
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — macOS 10.13 or later
use framework "Foundation"
use scripting additions

set aOffset to 0

–選択中のKeynote書類上の表への参照を取得する
set aTable to returnSelectedTableOnCurrentSlide() of me

if aTable = false then
  display notification "No selected table on Keynote document"
  
return
end if

–行選択
using terms from application "Keynote"
  tell aTable
    tell column 1
      set aList to value of every cell
    end tell
  end tell
end using terms from

set a2List to cleanUp1DList(aList, missing value) of me
set aRes to choose from list a2List with prompt "リナンバー対象の行選択"
set a2Res to search1DList(a2List, first item of aRes) of me

–列選択
using terms from application "Keynote"
  tell aTable
    tell row a2Res
      set bList to value of every cell
    end tell
  end tell
end using terms from

set b2List to cleanUp1DList(bList, missing value) of me
set bRes to choose from list b2List with prompt "リナンバー対象の列選択(ヘッダー末尾列)"
set b2Res to search1DList(b2List, first item of bRes) of me

–リナンバー対象のデータを取得(対象データのみ抽出)
using terms from application "Keynote"
  tell aTable
    tell row a2Res
      set bList to value of cells (b2Res + 1) thru -1
    end tell
  end tell
end using terms from

—データ中に丸つき数字が存在した場合には、最小のものを取得
set aOffset to (getMinimumNumFromNumberWithSign(bList) of me)

–一応、ユーザーに推測した開始値でよいか確認を取る
set dRes to text returned of (display dialog "丸つき数字の開始値:" default answer (aOffset as string))
try
  set aOffset to (dRes as number) – 1
on error
  set aOffset to 0
end try

–Keynoteの表のセルから取得したデータから丸つき数字を除去する
set cList to removeNumberWithSignFromList(bList) of me

–list中の各アイテムの冒頭に順次丸つき数字を追加する
set dList to {}
set aCount to 1

repeat with i in cList
  set j to convNumToNumWithSign(aCount + aOffset) of me
  
set jj to contents of i
  
  
set the end of dList to (j & jj)
  
  
set aCount to aCount + 1
end repeat

–リナンバー対象のセルをリナンバーした丸つき数字+内容で置換
set aCount to 1
using terms from application "Keynote"
  tell aTable
    tell row a2Res
      repeat with i from (b2Res + 1) to ((length of bList) + 1)
        set value of cell i to contents of item aCount of dList
        
set aCount to aCount + 1
      end repeat
    end tell
  end tell
end using terms from

–1~50の範囲の数値を丸つき数字に変換して返す
on convNumToNumWithSign(aNum as number)
  if (aNum ≤ 0) or (aNum > 50) then return ""
  
set aStr to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set bChar to character aNum of aStr
  
return bChar
end convNumToNumWithSign

–現在のスライド上で選択中の表オブジェクトへの参照を取得する
on returnSelectedTableOnCurrentSlide()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
return theTable
        
      end tell
    end tell
  end tell
end returnSelectedTableOnCurrentSlide

–1D List上で指定データを検索してヒットしたアイテム番号を返す
on search1DList(aList, aTarg)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aList
  
set anIndex to anArray’s indexOfObject:aTarg
  
if (anIndex = current application’s NSNotFound) or (anIndex > 9.99999999E+8) then
    return false
  end if
  
return (anIndex as integer) + 1 –convert index base (0 based to 1 based)
end search1DList

–1D listのクリーニング
on cleanUp1DList(aList as list, cleanUpItems as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
if j is not in cleanUpItems then
      set the end of bList to j
    else
      set the end of bList to ""
    end if
  end repeat
  
return bList
end cleanUp1DList

–text in listから丸つき数字を除去する
on removeNumberWithSignFromList(aList as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
set j2 to removeNumberWithSign(j) of me
    
set the end of bList to j2
  end repeat
  
return bList
end removeNumberWithSignFromList

–文字列から丸つき数字を除去する
on removeNumberWithSign(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeNumberWithSign

–1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める
on getMinimumNumFromNumberWithSign(aList)
  set nList to {}
  
  
repeat with i in aList
    set j to contents of i
    
–与えられたテキストのうち、丸つき数字(白)の
    
set j2 to holdNumberWithSignOnly(j) of me
    
set n2List to characters of j2 –複数の丸つき数字が入っている場合に対処
    
    
repeat with ii in n2List
      set jj to contents of ii
      
set tmpNum to decodeNumFromNumWithSign(jj) of me
      
set the end of nList to tmpNum
    end repeat
    
  end repeat
  
  
set anArray to current application’s NSArray’s arrayWithArray:nList
  
set cRes to (anArray’s valueForKeyPath:"@min.self") as integer
  
return cRes
end getMinimumNumFromNumberWithSign

–指定文字列から丸つき数字のみ抽出する
on holdNumberWithSignOnly(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[^\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end holdNumberWithSignOnly

–丸つき数字を数値にデコードする v2
on decodeNumFromNumWithSign(aStr as string)
  set numStr1 to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set numStr2 to "❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴"
  
set numStr3 to "➀➁➂➃➄➅➆➇➈➉"
  
set numStr4 to "➊➋➌➍➎➏➐➑➒➓"
  
set numStr5 to "⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾"
  
  
set nList to {numStr1, numStr2, numStr3, numStr4, numStr5}
  
  
repeat with i in nList
    set numTemp to contents of i
    
if numTemp contains aStr then
      using terms from scripting additions
        set bNum to offset of aStr in numTemp
      end using terms from
      
return bNum
    end if
  end repeat
  
return false
end decodeNumFromNumWithSign

★Click Here to Open This Script 

(Visited 40 times, 1 visits today)
Posted in list Number Text | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | 1 Comment

1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める

Posted on 11月 26, 2021 by Takaaki Naganoya

1D List(1D Array)に入っているテキスト要素から、丸つき数字を抽出して数値化し、得られた数値のうち最小のものを求めるAppleScriptです。

こんな、丸つき数字のテキストが入った「表」をKeynote上に作成したときに、

項目を追加したり順番を入れ替えたりすると、セルの中に入れている丸つき数字も変更する必要があります。これが手作業でたいへんめんどくさいので、Scriptで処理できるようにサブルーチンを整備してみました。

やりたいことは割とシンプルなはずなのに、割といろいろ書かないと実現しない処理でもあります。

そして、本Scriptは置換対象のデータから丸つき数字部分を取り出して、最小のものを判別し、リナンバー時の開始値を既存のデータから推測するという処理のために作ったものです。

AppleScript名:1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/11/26
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aList to {"❹Script Editor", "②Xcode", "③ショートカット", "④Script Debugger④", "⑤SD Notary", "⑥UI Browser", "⑦Accessibility Inspector"}
set aSmallestNum to getMinimumNumFromNumberWithSign(aList) of me
–> 2

–1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める
on getMinimumNumFromNumberWithSign(aList)
  set nList to {}
  
  
repeat with i in aList
    set j to contents of i
    
–与えられたテキストのうち、丸つき数字(白)の
    
set j2 to holdNumberWithSignOnly(j) of me
    
set n2List to characters of j2 –複数の丸つき数字が入っている場合に対処
    
    
repeat with ii in n2List
      set jj to contents of ii
      
set tmpNum to decodeNumFromNumWithSign(jj) of me
      
set the end of nList to tmpNum
    end repeat
    
  end repeat
  
  
set anArray to current application’s NSArray’s arrayWithArray:nList
  
set cRes to (anArray’s valueForKeyPath:"@min.self") as integer
  
return cRes
end getMinimumNumFromNumberWithSign

–指定文字列から丸つき数字のみ抽出する
on holdNumberWithSignOnly(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[^\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end holdNumberWithSignOnly

–丸つき数字を数値にデコードする v2
on decodeNumFromNumWithSign(aStr as string)
  set numStr1 to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set numStr2 to "❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴"
  
set numStr3 to "➀➁➂➃➄➅➆➇➈➉"
  
set numStr4 to "➊➋➌➍➎➏➐➑➒➓"
  
set numStr5 to "⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾"
  
–set numStr6 to "⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇"
  
–set numStr7 to "1︎⃣2︎⃣3︎⃣4︎⃣5︎⃣8︎⃣9︎⃣"
  
–set numStr8 to "⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛"
  
  
set nList to {numStr1, numStr2, numStr3, numStr4, numStr5}
  
  
repeat with i in nList
    set numTemp to contents of i
    
if numTemp contains aStr then
      using terms from scripting additions
        set bNum to offset of aStr in numTemp
      end using terms from
      
return bNum
    end if
  end repeat
  
return false
end decodeNumFromNumWithSign

★Click Here to Open This Script 

(Visited 64 times, 1 visits today)
Posted in Number Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

文字列から丸つき数字のみ抽出する

Posted on 11月 26, 2021 by Takaaki Naganoya

指定の文字列から丸つき数字の部分だけを抽出するAppleScriptです。

丸つき数字の文字を数値に変換するサブルーチンのために作成したものです。

AppleScript名:文字列から丸つき数字のみ抽出する.scpt
–  Original by: Shane Stanley
–  Created on: 2019/11/04
–  Modified by: Takaaki Naganoya
–  Modified on: 2021/11/26

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aRes to holdNumberWithSignOnly("⑦Accessibility Inspector") of me
–> "⑦"

on holdNumberWithSignOnly(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[^\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end holdNumberWithSignOnly

★Click Here to Open This Script 

(Visited 95 times, 1 visits today)
Posted in Number Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

丸つき数字を数値にデコードする v2

Posted on 11月 26, 2021 by Takaaki Naganoya

丸つき数字を数値にデコードするAppleScriptです。よくよく考えるとこれまでに作っていなかったので、作っておきました。

AppleScript名:丸つき数字を数値にデコードする v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/11/26
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

set dRes to decodeNumFromNumWithSign("⑮") of me
–> 15

–丸つき数字を数値にデコードする v2
on decodeNumFromNumWithSign(aStr as string)
  set numStr1 to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set numStr2 to "❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴"
  
set numStr3 to "➀➁➂➃➄➅➆➇➈➉"
  
set numStr4 to "➊➋➌➍➎➏➐➑➒➓"
  
set numStr5 to "⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾"
  
–set numStr6 to "⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇"
  
–set numStr7 to "1︎⃣2︎⃣3︎⃣4︎⃣5︎⃣8︎⃣9︎⃣"
  
–set numStr8 to "⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛"
  
  
set nList to {numStr1, numStr2, numStr3, numStr4, numStr5}
  
  
repeat with i in nList
    set numTemp to contents of i
    
if numTemp contains aStr then
      using terms from scripting additions
        set bNum to offset of aStr in numTemp
      end using terms from
      
return bNum
    end if
  end repeat
  
return false
end decodeNumFromNumWithSign

★Click Here to Open This Script 

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

丸つき数字の除去と数値からの変換

Posted on 11月 26, 2021 by Takaaki Naganoya

丸つき数字を指定文字列から削除するAppleScriptと、1〜50の範囲の数値を丸つき数字に変換するAppleScriptです。

Keynoteの表に入っている丸つき数字のリナンバーを行うために、必要な処理を書いてみたものです。日本語環境でしかこういう文字は使わないことでしょう。

丸つき数字が文字コード上でところどころ切れているため、単純に調べるのに手間がかかりました。

AppleScript名:数字を丸つき数字に変換.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/11/26
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

repeat with i from -10 to 100 by 1
  set aStr to convNumToNumWithSign(i) of me
  
log {i, aStr}
end repeat

on convNumToNumWithSign(aNum as number)
  if (aNum ≤ 0) or (aNum > 50) then return ""
  
set aStr to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
  
set bChar to character aNum of aStr
  
return bChar
end convNumToNumWithSign

★Click Here to Open This Script 

AppleScript名:丸つき数字を検出・削除
–  Original by: Shane Stanley
–  Created on: 2019/11/04
–  Modified by: Takaaki Naganoya
–  Modified on: 2021/11/26

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aRes to removeNumberWithSign("⓪①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿⓿❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓") of me
–> "‍‍‍‍‍‍"

on removeNumberWithSign(aStr as text)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeNumberWithSign

★Click Here to Open This Script 

(Visited 71 times, 1 visits today)
Posted in Number Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

Pagesでページ数とfacing pagesフラグの値から右側ページを判定

Posted on 9月 26, 2021 by Takaaki Naganoya

Pagesでページ数とfacing pagesの値から該当のページが右側に存在するかどうかを判定するAppleScriptです。

ページが右側にあるかどうか、というこの判定処理はツメ処理のために用意したものです。見開きの右側に置くのが基本といいますか、別に左側にもあってもいいんですが、右側ページ右端に置いた縦長の表オブジェクトをツメと見立てて処理することに(個人的に)したためです。


▲同一のPages書類を「見開きページ」の設定をオフにした状態(左)、オンにした状態(右)でページの並びが変わる

AppleScript名:Pages書類のfacing Pagesを取得.scpt

set fRes to getFacingPages() of me

on getFacingPages()
  tell application "Pages"
    tell front document
      return facing pages
    end tell
  end tell
end getFacingPages

★Click Here to Open This Script 

こんな記述でfacing pagesの値を取得でき、この値とページ数(ノンブル)をもとに奇数ページ、偶数ページの判定を行い、ページの左右を判定できます。

本Scriptを実行すると、以下のようにログ表示を行います。{facing pages, ノンブル, 右側ページかどうかの判定結果}を表示しています。

(*false, 1, false*)
(*false, 2, true*)
(*false, 3, false*)
(*false, 4, true*)
(*false, 5, false*)
(*false, 6, true*)
(*true, 1, true*)
(*true, 2, false*)
(*true, 3, true*)
(*true, 4, false*)
(*true, 5, true*)
(*true, 6, false*)

以前にどこかで「奇数/偶数の判定処理なんて、素朴な処理をサブルーチンとして独立して用意しておくのか?」と聞かれたことがありましたが、このように、サブルーチンとして用意しておいたので簡単に使い回して利用できているわけです。

AppleScript名:Pagesのページ番号の該当ページが右側にあるかどうか計算.scpt

set flagList to {false, true}
repeat with i in flagList
  set aFlag to contents of i
  
repeat with aPage from 1 to 6
    set rRes to checkPagesRightPage(aPage, aFlag) of me
    
log {i, aPage, rRes}
  end repeat
end repeat

–Pagesのページ番号の該当ページが右側にあるかどうか計算
on checkPagesRightPage(aNum, aFlag)
  set oddF to chkOddNum(aNum) of me –奇数チェック
  
if {aFlag, oddF} = {true, true} then
    return true –右側ページ
  else if {aFlag, oddF} = {false, false} then
    return true –右側ページ
  else
    return false
  end if
end checkPagesRightPage

–奇数かどうかチェック
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 137 times, 1 visits today)
Posted in boolean Number | Tagged 10.15savvy 11.0savvy 12.0savvy Pages | Leave a comment

Keynoteで現在表示中のスライド上にあるすべての表のカラム幅を自動調整

Posted on 4月 28, 2021 by Takaaki Naganoya

Keynoteで現在オープン中の書類の表示中のスライド(ページ)に存在する表のカラム幅を自動調整するAppleScriptです。


▲スライド上のカラム幅が不揃いの表を….


▲1列目はそのままの幅で、残りは均等割で調整します

AppleScript名:Keynoteで現在表示中のスライド上にあるすべての表のカラム幅を自動調整
— Created 2017-10-06 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Keynote"
  tell front document
    tell current slide
      set tList to every table
      
      
repeat with i in tList
        set j to contents of i
        
prepareCoumnWidthInATable(j) of me
      end repeat
    end tell
  end tell
end tell

on prepareCoumnWidthInATable(aTable)
  tell application "Keynote"
    tell aTable
      set cCount to count every column
      
set cWidth to width of every column
      
set aWidth to width –table width
      
      
set aveWidth to (aWidth – (first item of cWidth)) / (cCount – 1)
      
      
tell columns 2 thru cCount
        set width to aveWidth
      end tell
    end tell
  end tell
end prepareCoumnWidthInATable

★Click Here to Open This Script 

(Visited 44 times, 1 visits today)
Posted in Number | Tagged 10.14savvy 10.15savvy 11.0savvy Keynote | Leave a comment

大きな数値同士の平均値を求める

Posted on 3月 26, 2021 by Takaaki Naganoya

大きな数字同士の平均値を求めるAppleScriptです。大きい数字というのは、桁数が(大きい方に)多いものと、小数点以下の桁数が多いものを指しています。

AppleScriptの数値は10桁ぐらいで指数表示になってしまう、一種のウィークポイントですが、数値を文字で保持することでこのように計算できます。

テキストで書いた数値をリストに入れて計算しますが、ヌル要素が入っていると問題になるのであらかじめヌル要素は削除するようにしています。

ちょうど、書籍の原稿で巨大な配列要素を追加するベンチマークを実施したさいに、5回実行してその平均値を求めるために書いたものです。

AppleScript名:大きな数値同士の平均値を求める
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/03/26
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aList to {"", "0.4345240592956544", "0.3104130029678344192", "0.3132869005203247104", "0.2978630065917968384", "0.3173710107803344896"}

set c to aveLargeNumber(aList) of me

–AppleScriptの範囲外の精度の数値テキストの平均を計算する
on aveLargeNumber(aNumList as list)
  –ヌル要素の削除
  
set bNumList to listSweep1D(aNumList) of me
  
  
set aCount to count every item of bNumList
  
set aNumStr to retDelimedText(bNumList, " + ") of me
  
  
set aCMD to "echo \" scale=10; (" & aNumStr & ") / " & (aCount as string) & " \" | bc"
  
set aRes to do shell script aCMD
  
if aRes begins with "." then set aRes to "0" & aRes
  
  
return aRes
end aveLargeNumber

on retDelimedText(aList as list, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as string
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

–1Dリスト項目のうち、ヌルの項目はリストから除去する
on listSweep1D(aList as list)
  set bList to {}
  
repeat with i in aList
    set j to contents of i
    
if j is not equal to "" then
      set the end of bList to j
    end if
  end repeat
  
return bList
end listSweep1D

★Click Here to Open This Script 

(Visited 21 times, 1 visits today)
Posted in Number | Tagged 10.14savvy 10.15savvy | Leave a comment

Numbersの表の選択範囲をシーケンシャル番号で埋める

Posted on 3月 11, 2020 by Takaaki Naganoya

Numbersの最前面の書類で選択中の表の選択範囲を1からはじまるシーケンシャル番号で埋めるAppleScriptです。

Numbers書類のセルを埋めるのは、それなりにコストの高い(処理時間が長い)処理なので、数十とか百ぐらいの要素だと、このように悠長にループで埋めても大丈夫ですが、数千とか数万セルを相手にする場合には途方もない時間がかかります。

要素数が多い場合には、CSVのファイルを組み立ててオープンする処理方法をおすすめします(一瞬で終わるので)。

この手の処理は、ほぼ「書き捨て」で保存すらしないことが多いのですが、たまたま気が向いたので保存しておきました。

本ScriptはmacOS 10.14.6/10.15.3+Numbers v6.2.1、macOS 10.13.6+Numbers v6.2で動作確認しています。

AppleScript名:Numbersの表の選択範囲をシーケンシャル番号で埋める
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/03/10
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

tell application "Numbers"
  tell front document
    tell active sheet
      try
        set theTable to first table whose class of selection range is range
      on error
        display notification "Numbers: There is no selection"
        
return
      end try
      
      
tell theTable
        set aRes to value of cells of selection range
      end tell
      
      
set aLen to length of aRes
      
set newList to makeSequential1DList(aLen) of me
      
      
tell theTable
        set cList to cells of selection range
      end tell
      
      
repeat with i from 1 to aLen
        set anObj to contents of item i of cList
        
set aVal to contents of item i of newList
        
        
ignoring application responses
          set value of anObj to aVal
        end ignoring
        
      end repeat
    end tell
  end tell
end tell

on makeSequential1DList(itemLen)
  set outList to {}
  
repeat with i from 1 to itemLen
    set the end of outList to i
  end repeat
  
return outList
end makeSequential1DList

★Click Here to Open This Script 

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

Numbersでオープン中の最前面の書類のすべてのシートの表1の行数合計を計算する

Posted on 1月 15, 2020 by Takaaki Naganoya

Numbersでオープン中の最前面の書類のすべてのシートの表1の行数の合計を計算するAppleScriptです。

Blogアーカイブ本作成のために書いたものです。

この記事数をカウントするために使いました。

AppleScript名:Numbersでオープン中の最前面の書類のすべてのシートの表1の行数合計を計算する
set aCount to 0

tell application "Numbers"
  tell front document
    set sList to every sheet
    
repeat with i in sList
      tell i
        try
          set tmpC to count every row of table 1
          
set aCount to aCount + tmpC
        end try
      end tell
    end repeat
  end tell
end tell

return aCount

★Click Here to Open This Script 

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

指定緯度における1km相当の経度の大きさを求める

Posted on 12月 15, 2019 by Takaaki Naganoya

指定緯度における1kmあたりの経度の角度などを計算するAppleScriptです。Rubyのコードで書かれたものがあったので、AppleScriptに翻訳してみました。

三角関数を用いるため、関数計算ライブラリ「calcLibAS」を併用しています。

なんでこんな計算をすることになったかといえば、Apple Mapsの仕様で、地図表示エリアの指定時に表示距離ではなく表示角度(spn)が要求されるようなので、計算方法を求めておいたという次第です。

AppleScript名:1kmあたりの経度の大きさを求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/15
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use calcLib : script "calcLibAS"

–参照:1kmあたりの経度の大きさ
–https://github.com/ryym/google-maps-demo/blob/master/note.md
set aLat to 31.5719562 –鹿児島の緯度
set aDeg to calc1kmDegreeinLatitude(aLat) of me –経度方向(横)に1kmに相当する角度
–> 0.010543813284

set bDeg to calc100mDegreeinLatitude(aLat) of me –経度方向(横)に100mに相当する角度
–> 0.001054381328

set aLat to 35.73993521 –練馬の緯度
set aDeg to calc1kmDegreeinLatitude(aLat) of me –経度方向(横)に1kmに相当する角度
–> 0.011067403977

set bDeg to calc100mDegreeinLatitude(aLat) of me –経度方向(横)に100mに相当する角度
–> 0.001106740398

–1kmあたりの緯度の大きさ
set eRes to calc1kmDegreeinLong() of me –緯度方向(縦)に1kmに相当する角度
–> 0.008983152841

set eRes to calc100mDegreeinLong() of me –緯度方向(縦)に100mに相当する角度
–> 8.98315284119522E-4

–指定緯度における1km相当の経度の角度
on calc1kmDegreeinLatitude(aLat)
  set eRadius to 6378.137 –in km
  
set r to eRadius * (cos (aLat * pi / 180))
  
set cm to 2 * pi * r
  
set kd to 360 / cm
  
return kd
end calc1kmDegreeinLatitude

–指定緯度における1km相当の経度の角度
on calc100mDegreeinLatitude(aLat)
  set eRadius to 6378.137 –in km
  
set r to eRadius * (cos (aLat * pi / 180))
  
set cm to 2 * pi * r
  
set kd to 360 / cm
  
return kd / 10
end calc100mDegreeinLatitude

–1km相当の緯度の角度
on calc1kmDegreeinLong()
  set eRadius to 6378.137 –in km
  
set pc to 2 * pi * eRadius
  
set dLat to 360 / pc
  
return dLat
end calc1kmDegreeinLong

–100m相当の緯度の角度
on calc100mDegreeinLong()
  return calc1kmDegreeinLong() / 10
end calc100mDegreeinLong

★Click Here to Open This Script 

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

数値に3桁セパレータを付加、外して数値に戻す v2

Posted on 11月 12, 2019 by Takaaki Naganoya

10進数の数字文字列に3桁セパレータを付加、外して数字文字列に戻すAppleScriptです。

めんどくさい上にCocoaに機能があり、かつそれほど大量のデータ処理を行うわけでもない(スピードを要求されない)処理のはずなので、手抜きでCocoaの機能を呼び出しています。

AppleScript名:数値に3桁セパレータを付加、外して数値に戻す v2
— Created 2016-10-12 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–3桁セパレータ文字「,」をNSLocaleのcurrentLocaleから取得するように変更

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSLocaleGroupingSeparator : a reference to current application’s NSLocaleGroupingSeparator
property NSNumberFormatterDecimalStyle : a reference to current application’s NSNumberFormatterDecimalStyle

set aNum to 100000000
set aStr to formatNum(aNum) of me
–> "100,000,000"

set bNum to deFromatNumStr(aStr) of me
–>  "100000000"

on formatNum(theNumber as number)
  set theResult to NSNumberFormatter’s localizedStringFromNumber:theNumber numberStyle:(NSNumberFormatterDecimalStyle)
  
return theResult as text
end formatNum

on deFromatNumStrAndRetNumber(theNumericString as string)
  set aThousandSep to NSLocale’s currentLocale()’s objectForKey:(NSLocaleGroupingSeparator)
  
set notWantChars to NSCharacterSet’s characterSetWithCharactersInString:aThousandSep
  
set targStr to NSString’s stringWithString:theNumericString
  
set newStr to (targStr’s componentsSeparatedByCharactersInSet:notWantChars)’s componentsJoinedByString:""
  
return ((newStr as string) as number) –Danger in OS X 10.10 (floating point casting bug)
end deFromatNumStrAndRetNumber

on deFromatNumStr(theNumericString as string)
  set aThousandSep to NSLocale’s currentLocale()’s objectForKey:(NSLocaleGroupingSeparator)
  
set notWantChars to NSCharacterSet’s characterSetWithCharactersInString:aThousandSep
  
set targStr to NSString’s stringWithString:theNumericString
  
set newStr to (targStr’s componentsSeparatedByCharactersInSet:notWantChars)’s componentsJoinedByString:""
  
return (newStr as string)
end deFromatNumStr

★Click Here to Open This Script 

(Visited 48 times, 1 visits today)
Posted in Number Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSCharacterSet NSLocale NSLocaleGroupingSeparator NSNumberFormatter NSNumberFormatterDecimalStyle NSString | Leave a comment

10進数とn進数文字列の相互変換

Posted on 11月 12, 2019 by Takaaki Naganoya

10進数の数値とn進数の文字列を相互変換するAppleScriptです。

もともと、AppleScriptの言語仕様上、10進数とn進数文字列との相互変換機能は存在しないのですが、サードパーティから機能拡張書類(OSAX)でそのような機能が提供され、さらにClassic MacOSからMac OS Xへの移行時にそれらの機能拡張書類が使えなくなって(一部は移行)、個別にそれらの機能をスクリプター側で実装してMailing ListやBBS上、Blogなどで共有してきたという経緯があります。

AppleScript Users MLに流れていたもののような気がしますが、自分で作ったものかもしれません。出どころ不明です。

ただ、2進数変換や16進数変換などの各種変換ルーチンが乱立していたところに、「これ、全部1つで済むんじゃね?」と思ってまとめたような気がしないでもありません。自分で作っても簡単なので。

Cocoaの機能を一切使っていません。たしかにCocoaの機能を用いての変換も行えるのですが、データのサイズがとても小さい(桁数が少ない)ので、Cocoaの機能を呼び出さないほうが高速です。

もしも、AppleScriptの予約語のようにこれらの機能を呼び出したい場合には、これらのScriptをAppleScript Librariesにして、AppleScript用語辞書をつけて書き出せば(辞書はなくても大丈夫ですが)、

use nthLib: script "nThConvLib"

のように呼び出すことができるようになっています(macOS 10.9以降)。

AppleScript名:10進数をn進数文字列に変換する
set a to 100

–10進→16進数変換
set b to aNumToNthDecimal(a, 16, 4, {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}, true) of me
–> "64"

–10進→8進数変換
set c to aNumToNthDecimal(a, 8, 4, {"0", "1", "2", "3", "4", "5", "6", "7"}, true) of me
–> "144"

–10進→2進数変換
set d to aNumToNthDecimal(a, 2, 8, {"0", "1"}, false) of me
–> "01100100"

–10進数をn進数文字列に変換する

–origNum:変換対象の数字
–nTh: n進数のn
–stringLength: 出力指定桁(上位桁のアキはゼロパディングされる)
–zeroSuppress: 上位桁がゼロになった場合に評価を打ち切るかのフラグ、ゼロパディングを行わない(ゼロサプレスする)場合に指定
on aNumToNthDecimal(origNum, nTh, stringLength, stringSetList, zeroSuppress)
  set resString to {}
  
repeat with i from stringLength to 1 by -1
    if {origNum, zeroSuppress} = {0, true} then exit repeat
    
set resNum to (origNum mod nTh)
    
set resText to contents of item (resNum + 1) of stringSetList
    
set resString to resText & resString
    
set origNum to origNum div nTh
  end repeat
  
return (resString as string)
end aNumToNthDecimal

★Click Here to Open This Script 

AppleScript名:n進数文字列を10進数に変換する v2a
–2進数文字列→10進数数値変換
set a to "11"
set b to aNthToDecimal(a, {"0", "1"}) of me
–> 3

–8進数文字列→10進数数値変換
set a to "144"
set c to aNthToDecimal(a, {"0", "1", "2", "3", "4", "5", "6", "7"}) of me
–> 100

–16進数文字列→10進数数値変換
set a to "64"
set b to aNthToDecimal(a, {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}) of me
–> 100

–n進数文字列を10進数に変換する
on aNthToDecimal(origStr as string, nTh as list)
  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 – 1)
    
set digitCount to digitCount + 1
  end repeat
  
  
return resNumber as integer
end aNthToDecimal

–元はCocoaの機能を利用していたが、処理対象のデータが小さいのでOld Style AppleScriptで書き直した
on offsetInList(aChar as string, aList as list)
  set aCount to 1
  
repeat with i in aList
    set j to contents of i
    
if aChar is equal to j then
      return aCount
    end if
    
set aCount to aCount + 1
  end repeat
  
return 0
end offsetInList

★Click Here to Open This Script 

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

ゼロパディングのサンプルを生成してパディング桁数を選択

Posted on 10月 18, 2019 by Takaaki Naganoya

数値に対して「何桁分のゼロパディングを行うか」を選択するダイアログを表示するAppleScriptです。

数値に対して任意の桁数のゼロパディング(9–> 0009)を行うときに、桁数と実際にゼロパディングしたサンプルを生成してchoose from listによるダイアログで選択するようにしてみました。

本来であれば、ゼロパディングの桁数だけ文字入力させたり一覧から選択させるだけでよいのですが、よりわかりやすいように処理サンプルを同時に表示させています。また、サンプルは任意の範囲で乱数を表示させることで「それっぽい」「本物っぽい」雰囲気を醸し出すようにしてみました。

気分の問題なので、実用性とかそういうものを追求したものではありません。

最近は、AppleScriptもマシンの速度向上やCocoa Frameworkを利用することで高速処理が行えるようになり、何らかの処理を選択する際に「結果ごと表示して選択」するような処理を書くことが増えてきました。さすがに処理に数分かかるような処理ではそんな真似はできませんが、高速に処理できたぶんだけ使い勝手を考慮するとよいだろうかというところです。

AppleScript名:ゼロパディングのサンプルを生成.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/10/18
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSMutableArray : a reference to current application’s NSMutableArray

set aList to makeSampleList(1, 8) of me
set aRes to choose from list aList with prompt "Digit Samples" with title "Zero padding digits" default items first item of aList without empty selection allowed
if aRes = false then return false
set dRes to contents of first item of aRes
set nRes to search1DList(aList, dRes) of me

on makeSampleList(aMin as integer, aMax as integer)
  set sampleList to {}
  
set aSampleMaxDigit to length of (characters of (aMax as string))
  
  
repeat with i from aMin to aMax
    set aSample to makeFN(i, aSampleMaxDigit + 1) of me
    
    
set aRand to random number from (10 ^ aMin) to (10 ^ (i – 2) – 1)
    
set aTmpStr to makeFN(aRand, i) of me
    
    
set bSample to aSample & " Sample: " & aTmpStr
    
set the end of sampleList to bSample
  end repeat
  
  
return sampleList
end makeSampleList

on makeFN(aNum as integer, aDigit as integer)
  set aText to "00000000000" & (aNum as text)
  
set aLen to length of aText
  
set aRes to text (aLen – aDigit + 1) thru -1 of aText
  
return aRes
end makeFN

on search1DList(aList, aTarg)
  set anArray to NSMutableArray’s arrayWithArray:aList
  
set anIndex to anArray’s indexOfObject:aTarg
  
if (anIndex = current application’s NSNotFound) or (anIndex > 9.99999999E+8) then –macOS 10.12.x—10.13.0はNSNotFoundの定義値が間違っているので対処
    return false
  end if
  
return (anIndex as integer) + 1 –convert index base (0 based to 1 based)
end search1DList

★Click Here to Open This Script 

(Visited 107 times, 1 visits today)
Posted in dialog Number Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSMutableArray | Leave a comment

TTSで日本語数値読み上げ

Posted on 9月 26, 2019 by Takaaki Naganoya

桁数の大きな数値のText To Speech(TTS)読み上げのAppleScriptです。

# 日本語環境における枝葉的な(マニアックな)数値表現の仕様に関する話であり、他の言語では関係ない話です。漢字文化圏で使われる数値表現のようですが、たとえば中国や韓国で使われている数値桁表現との間で厳密な互換性があるかといった確認は行なっておりません

実行前に日本語TTS読み上げ音声の「Otoya」あるいは「Kyoko」をインストールしておいてください。

まず、AppleScriptが指数表示なしに表現できる数値は10^9程度で、それを超えると指数表示になります。

ただし、指数表示になった数値を数値文字列に変換するノウハウは全世界的に共有されており、そのためのサブルーチン(Stringify)を呼び出すだけで済みます。

AppleScriptのsayコマンドでは「100兆」までの読み上げはそれっぽく実行してくれますが、「1000兆」になると読み上げ内容が数字の羅列になってしまいます。

これについても、大きな数値を日本語数値エンコーディング文字列に変換するサブルーチンを昔から公開しており(本Blog開設当初の11年前に掲載)、それを呼び出すだけで日本語数値表現文字列に変換できるため、読み上げられることでしょう。

Number Japanese English
1 一(いち) one
10 十(じゅう) ten
100 百(ひゃく) hundred
1000 千(せん) thousand
10000 万(まん) 10 thousand
100000 十万(じゅうまん) 100 thousand
1000000 百万(ひゃくまん) million
10000000 千万(せんまん) 10 million
100000000 億(おく) 100million
1000000000000 兆(ちょう) villion
1000000000000000 京(けい) thousand villion
100000000000000000 100京(ひゃっけい) trillion
10^24 丈(じょ)
10^28 穣(じょう)
10^52 恒河沙(ごうがしゃ)
10^56 阿僧祇(あそうぎ)
10^60 那由他(なゆた)
10^64 不可思議(ふかしぎ)
10^68 無量大数(むりょうたいすう)

とはいえ、「阿僧祇(あそうぎ、10^56)「那由多(なゆた、10^60)」といった数値桁を読み上げさせるとTTSが正しく読み上げてくれません。さすがにこんなにマニアックな数値表現はカバーしなくてよいでしょう。「丈(じょ)」「穣(じょう)」など似た音の桁が存在するあたり、これらは口に出して読み上げるものではなく、文字で読むためだけのものだと強く感じるものです。

AppleScript名:TTSで日本語数値読み上げ
repeat with i from 0 to 15
  set aNum to (10 ^ i)
  
say Stringify(aNum) of me using "Kyoko" –or "Otoya"
end repeat

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 

AppleScript名:TTSで日本語数値読み上げ v2
repeat with i from 15 to 70
  set aNum to (10 ^ i)
  
set jRes to encodeJapaneseNumText(aNum) of japaneseNumberEncodingKit
  
say jRes using "Kyoko" –or "Otoya"
end repeat

–課題:オーバーフローチェックを行っていない
set a to "102320120000108220010"
set jRes to encodeJapaneseNumText(a) of japaneseNumberEncodingKit
–> "1垓232京120兆1億822万10"

script japaneseNumberEncodingKit
  –数字文字列を日本語数値表現文字列に変換
  
on encodeJapaneseNumText(aNum)
    
    
set aText to Stringify(aNum) of me
    
set aText to aText as Unicode text
    
set dotText to "." as Unicode text
    
set upperDigit to ""
    
set lowerDigit to ""
    
    
–小数点の処理
    
if dotText is in aText then
      set b to offset of dotText in aText
      
set upperDigit to characters 1 thru (b – 1) of aText
      
set upperDigit to upperDigit as Unicode text
      
set lowerDigit to characters b thru -1 of aText
      
set lowerDigit to lowerDigit as Unicode text
    else
      set upperDigit to aText
    end if
    
    
    
set scaleList3 to {"", "万", "億", "兆", "京", "垓", "丈", "壌", "溝", "砂", "正", "載", "極", "恒河沙", "阿僧梢", "那由他", "不可思議", "無量大数"}
    
set splitDigit to 4
    
set nList to splitByDigit(upperDigit, splitDigit) of me
    
set nList to reverse of nList
    
    
set resText to ""
    
set digCount to 1
    
repeat with i in nList
      set b to (contents of i) as number
      
if b is not equal to 0 then
        set resText to (b as text) & item digCount of scaleList3 & resText
      end if
      
set digCount to digCount + 1
    end repeat
    
    
    
    
return resText & lowerDigit
    
  end encodeJapaneseNumText
  
  
–指定桁数で区切る
  
on splitByDigit(a, splitDigit)
    set aList to characters of a
    
set aList to reverse of aList
    
log aList
    
set resList to {}
    
set tempT to ""
    
set tempC to 1
    
repeat with i in aList
      set tempT to contents of i & tempT
      
if tempC mod splitDigit = 0 then
        set resList to {tempT} & resList
        
set tempT to ""
      end if
      
set tempC to tempC + 1
    end repeat
    
    
if tempT is not equal to "" then
      set resList to {tempT} & resList
    end if
    
    
resList
    
  end splitByDigit
  
  
  
  
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
end script

★Click Here to Open This Script 

(Visited 121 times, 1 visits today)
Posted in Number System Text Text to Speech | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

JavaScriptCore経由で関数計算を行うcalcLibASをアップデート

Posted on 8月 23, 2019 by Takaaki Naganoya

関数計算機能をAppleScriptに提供するAppleScriptライブラリ「calcLibAS」をアップデートしてみました。

変更点:
 ・sdefを書いたので、各種関数が予約語で呼び出せるようになった

だけです。

–> Download calcLibASv1.5 (To ~/Library/Script Libraries/)

さまざまな関数計算の機能をAppleScriptに提供するモジュールと比べてもサポート関数の数が多く、さらに本ライブラリは単にJavaScriptCoreの関数計算機能を変換しているだけなので、ライブラリ内で計算は一切していません。

技術的に何も見るべき点がなく、高度なテーマに一切挑戦していないのに、大量の数値関数の機能を提供しているのが本ライブラリの特徴です。志の低さでは他に類を見ないレベルですが、実際に稼働して役に立っています。

本来はCephes Math Library(関数36個ぐらい)あたりをラッピングしようと考えていたのですが、JavaScriptCore経由でJavaScript(おそらくCephes Math Libraryをラッピング)の関数を呼び出してもほぼ同数の関数が使えることが判明したため、3時間ぐらいで作ってみたのがはじまりです。当初のバージョンはJXAで記述した計算ルーチンを呼び出していましたが、JXAが頻繁にクラッシュしたため、JavaScriptCoreを呼び出すように変更・高速化(最初のバージョンから28倍速)しました。

ハンドラ呼び出しとsdefによる予約語を通じて関数計算した場合で、計算精度などに差は出ていないことを内部の検証コマンドで確認してあります。

メンテナンスしやすいように、sdefからの呼び出しサービスを行うライブラリと実際の計算(呼び出し)を行うCoreライブラリの2つの部品に分けています。機能本体部分にsdefで定義した予約語を使うと、メンテナンスも何もできなくなるというapplescript-stdlibを反面教師とし、さらにsdefからの呼び出し部分がパラメータのチェックや例外処理への対応などで容易に機能がふくれあがっていくため、メンテナンス性を確保するためにこのような構造にしました。

log関数については、すでにAppleScriptビルトインで、まったく異なる働きを行うlogコマンド(スクリプトエディタ/Script Debuggerのログ表示機能でログ表示)があるので、重複を避けるためにsdef定義でlogarithmと表記するようにしました。

roundも同様にsdef定義でroundNumと表記しています。

実際に、三角関数やatan2などの関数を使い出していますが、精度や挙動、実行速度などに前バージョンから差異はありません。AppleScript用語の予約語がついて呼びやすくなっただけです。

AppleScript名:Every Functions
— Created 2019-08-20 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use calSub : script "calcLibAS"

set a001 to abs -10
set a002 to acos -1
set a003 to acosh 10
set a004 to asin 10
set a005 to asinh 10
set a006 to atan 10
set a007 to atan2 {10, 20}
set a008 to atanh 10
set a009 to cbrt 3
set a010 to ceil 0.95
set a011 to clz32 1
set a012 to cos 1
set a013 to cosh 1
set a014 to exp 1
set a015 to expm1 -1
set a016 to floor 45.95
set a017 to fround 1.337
set a018 to hypot {3, 4, 5}
set a019 to lmul {2, 5}
set a020 to logarithm 10
set a021 to log10 2
set a022 to log1p 1
set a023 to log2 3
set a024 to max {1, 2, 3, 4, 6, 2, 10}
set a025 to min {1, 2, 3, 4, 6, 2, 10, 0}
set a026 to pow {7, 2}
set a027 to rnd –random number
set a028 to roundNum 5.95
set a029 to sign 10
set a030 to sin (pi / 2)
set a031 to sinh 1
set a032 to sqrt 2
set a033 to tan 30
set a034 to tanh 10
set a035 to trunc 13.37

set aList to {a001, a002, a003, a004, a005, a006, a007, a008, a009, a010, a011, a012, a013, a014, a015, a016, a017, a018, a019, a020, a021, a022, a023, a024, a025, a026, a027, a028, a029, a030, a031, a032, a033, a034, a035}

return test() of calSub –Check function to calc from sdef and each handlers excepting random numbers

★Click Here to Open This Script 

AppleScript名:Calc direction from place A to B
— Created 2019-08-20 by Takaaki Naganoya
— 2017-2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use script "calcLibAS"

set coord1 to {latitude:35.73677496, longitude:139.63754457} –Nakamurabashi Sta.
set coord2 to {latitude:35.78839012, longitude:139.61241447} –Wakoshi Sta.
set dirRes1 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -25.925429877542

set coord2 to {latitude:35.7227821, longitude:139.63860897} –Saginomiya Sta.
set dirRes2 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  175.649833487804

set coord2 to {latitude:35.73590542, longitude:139.62986745} –Fujimidai Sta.
set dirRes3 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  -96.385293928667

set coord2 to {latitude:35.73785024, longitude:139.65339321} –Nerima Sta.
set dirRes4 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  85.959474671834

set coord2 to {latitude:35.71026838, longitude:139.81215754} –Tokyo Sky Tree
set dirRes5 to calcDirectionBetweenTwoPlaces(coord1, coord2) of me
–>  96.826542737106

–位置情報1から位置情報2の方角を計算。北が0度
on calcDirectionBetweenTwoPlaces(coord1, coord2)
  set deltaLong to (longitude of coord2) – (longitude of coord1)
  
set yComponent to sin deltaLong
  
set xComponent to (cos (latitude of coord1)) * (sin (latitude of coord2)) – (sin (latitude of coord1)) * (cos (latitude of coord2)) * (cos deltaLong)
  
  
set radians to (atan2 {yComponent, xComponent}) as real
  
set degreeRes to (radToDeg(radians) of me)
  
  
return degreeRes
end calcDirectionBetweenTwoPlaces

on radToDeg(aRadian)
  return aRadian * (180 / pi)
end radToDeg

★Click Here to Open This Script 

AppleScript名:日本測地系から世界測地系への座標変換.scpt
— Created 2018-07-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use math : script "calcLibAS"

set jpLat to 42.16593046887
set jpLng to 142.771877437246

set {wdLat, wdLng, wdH} to JapanGeodeticSystem’s convertIntoWgs(jpLat, jpLng)
–>  {​​​​​42.168504277889, ​​​​​142.768075650137, ​​​​​61.914452206343​​​}

–https://altarf.net/computer/ruby/3347
–日本測地系から世界測地系に換算
script JapanGeodeticSystem
  –ラジアン(度)
  
property rdNum : pi / 180
  
  
–日本測地系の定数(ベッセル楕円体)
  
property rJP : 6.377397155E+6 –赤道半径
  
property fJP : 1 / 299.1528128 –扁平率
  
property e2JP : (2 * fJP) – (fJP * fJP) –第一離心率
  
  
–世界測地系の定数(WGS84)
  
property rWS : 6.378137E+6 –赤道半径
  
property fWS : 1 / 298.257223563 –扁平率
  
property e2WS : (2 * fWS) – (fWS * fWS) –第一離心率
  
  
–並行移動量(m)
  
property dxNum : -148
  
property dyNum : 507.0
  
property dzNum : 681.0
  
  
–楕円体高
  
property heightNum : 0
  
  
  
–日本測地系から世界測地系に変換する
  
on convertIntoWgs(aLat, aLong)
    set {x, y, z} to llh2xyz(aLat, aLong, heightNum, rJP, e2JP, rdNum) of me
    
    
set x to x + dxNum
    
set y to y + dyNum
    
set z to z + dzNum
    
    
set {lat1, lng1, h1} to xyz2llh(x, y, z, rWS, e2WS, rdNum) of me
    
return {lat1, lng1, h1}
  end convertIntoWgs
  
  
  
–座標系の変換(緯度経度 -> xyz)
  
on llh2xyz(latLocal, lngLocal, hLocal, aLocal, e2Local, rdLocal)
    set latLocal to latLocal * rdLocal
    
set lngLocal to lngLocal * rdLocal
    
    
set sbNum to sin latLocal
    
set cbNum to cos latLocal
    
    
set rnLocal to aLocal / (sqrt (1 – e2Local * sbNum * sbNum))
    
    
set xLocal to (rnLocal + hLocal) * cbNum * (cos lngLocal)
    
set yLocal to (rnLocal + hLocal) * cbNum * (sin lngLocal)
    
set zLocal to (rnLocal * (1 – e2Local) + hLocal) * sbNum
    
    
return {xLocal, yLocal, zLocal}
  end llh2xyz
  
  
  
–座標系の変換(xyz -> 緯度経度)
  
on xyz2llh(x, y, z, a, e2, rdLocal)
    set bda to sqrt (1 – e2)
    
set p to sqrt (x * x + y * y)
    
set t to atan2 {z, p * bda}
    
set stNum to sin (t)
    
set ctNum to cos (t)
    
set b to atan2 {z + e2 * a / bda * stNum * stNum * stNum, p – e2 * a * ctNum * ctNum * ctNum}
    
    
set l to atan2 {y, x}
    
set sb to sin (b)
    
set rn to a / (sqrt (1 – e2 * sb * sb))
    
set h to p / (cos (b)) – rn
    
set l1 to b / rdLocal
    
set l2 to l / rdLocal
    
return {l1, l2, h}
  end xyz2llh
  
end script

★Click Here to Open This Script 

AppleScript名:Circulate Finder windows
— Created 2014-11-17 by Takaaki Naganoya
— Modified 2019-08-18 by Takaaki Naganoya
— 2014-2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit" — for NSScreen
use calLib : script "calcLibAS"

property aNum : 300
property aOffset : 0
property maxWin : 6
property winList : {}
property randList : {}
property winSize : 300

–Initialize
set winList to {}
set randList to {}

repeat maxWin times
  tell application "Finder"
    activate
    
set aWin to make new Finder window
    
    
tell aWin
      set toolbar visible to false
      
set sidebar width to 0
      
set statusbar visible to false
      
set position to {100, 100}
      
set bounds to {100, 100, 100 + winSize, 100 + winSize}
    end tell
    
    
set the end of winList to aWin
    
set the end of randList to {random number from 0 to 400, random number from 0 to 400, random number from 1 to 360}
    
  end tell
end repeat

–Main
repeat with i from 1 to 360 by 6
  
  
repeat with ii from 1 to maxWin
    
    
set aWinObj to contents of item ii of winList
    
set {aRandX, aRandY, aRandDegree} to item ii of randList
    
    
set aDeg to i + aRandDegree
    
    
set aSinNum to (sin aDeg) as real
    
set aCosNum to (cos aDeg) as real
    
    
set x to ((aNum * aSinNum) + aNum) * 2 + aOffset
    
set y to (aNum * aCosNum) + aNum + aOffset
    
    
ignoring application responses
      tell application "Finder"
        tell aWinObj
          set position to {(x as integer) + aRandX, (y as integer) + aRandY}
        end tell
      end tell
    end ignoring
    
  end repeat
  
end repeat

–Sweep
tell application "Finder"
  repeat with i in winList
    tell i
      close
    end tell
  end repeat
end tell

★Click Here to Open This Script 

AppleScript名:2点間の距離を求める(地球を球体として計算)
— Created 2019-08-22 by Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use script "calcLibAS"

property earth_radius : 6378140

set aPoint to {lat:35.7398693, long:139.6474103}
set bPoint to {lat:31.5719562, long:130.56257084}
set aRes to calcDistanceBetweenTwoPoint(aPoint, bPoint) of me

on calcDistanceBetweenTwoPoint(aPoint, bPoint)
  set lat1 to lat of aPoint
  
set lng1 to long of aPoint
  
set lat2 to lat of bPoint
  
set lng2 to long of bPoint
  
  
–緯度経度をラジアンに変換
  
set rlat1 to lat1 * pi / 180
  
set rlng1 to lng1 * pi / 180
  
  
set rlat2 to lat2 * pi / 180
  
set rlng2 to lng2 * pi / 180
  
  
— 2点の中心角(ラジアン)を求める
  
set a to (sin rlat1) * (sin rlat2) + (cos rlat1) * (cos rlat2) * (cos rlng1 – rlng2)
  
set rr to acos a
  
  
–2点間の距離(メートル)
  
set distance to earth_radius * rr
  
  
return distance
end calcDistanceBetweenTwoPoint

★Click Here to Open This Script 

(Visited 146 times, 1 visits today)
Posted in Number sdef | Tagged 10.12savvy 10.13savvy 10.14savvy Finder | 6 Comments

Post navigation

  • Older 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