I have this reverse function which works in english,
However it doesn't work with hebrew,
Reverse(string)
{
length := StrLen(string)
Loop, parse, string
{
loc := Abs(A_Index - length) + 1
revloc%loc% := A_LoopField
}
Loop %length%
final .= revloc%A_index%
return final
}
ReverseByAddress(address,len){
Loop % (len){
out.=Chr(NumGet(address+0,len-A_index,"Char"))
}
Return out
}
^m::
;ClipSaved := ClipboardAll
;text.="new line of some text`n"
text= %Clipboard%
clipboard := Reverse(text)
send, ^v
Any help with making this work with Unicode will be appreciated.
This has been solved without saving the data back to the clipboard:
^,::
text= %Clipboard%
newText := Reverse(text)
send, %newText%
Can you get this kind of schedule, at 2 or 3 characters?
2 character ex. -AutoHotKey -> uAotoHKtYe
................................uA ot oH Kt Ye
or
3 character ex. -AutoHotKey -> tuAoHoeKty
......tuA oHo eKt y
Related
I have tried to find the solution for this problem, but keep running my head at the wall with this one.
This function is part of a Go SQL wrapper, and the function getJSON is called to extract the informations from the sql response.
The problem is, that the id parameter becomes jibberish and does not match the desired response, all the other parameters read are correct thou, so this really weirds me out.
Thank you in advance, for any attempt at figurring this problem out, it is really appreciated :-)
func getJSON(rows *sqlx.Rows) ([]byte, error) {
columns, err := rows.Columns()
rawResult := make([][]byte, len(columns))
dest := make([]interface{}, len(columns))
for i := range rawResult {
dest[i] = &rawResult[i]
}
defer rows.Close()
var results []map[string][]byte
for rows.Next() {
result := make(map[string][]byte, len(columns))
rows.Scan(dest...)
for i, raw := range rawResult {
if raw == nil {
result[columns[i]] = []byte("")
} else {
result[columns[i]] = raw
fmt.Println(columns[i] + " : " + string(raw))
}
}
results = append(results, result)
}
s, err := json.Marshal(results)
if err != nil {
panic(err)
}
rows.Close()
return s, nil
}
An example of the response, taking from the terminal:
id : r�b�X��M���+�2%
name : cat
issub : false
Expected result:
id : E262B172-B158-4DEF-8015-9BA12BF53225
name : cat
issub : false
That's not about type conversion.
An UUID (of any type; presently there are four) is defined to be a 128-bit-long lump of bytes, which is 128/8=16 bytes.
This means any bytes — not necessarily printable.
What you're after, is a string representation of an UUID value, which
Separates certain groups of bytes using dashes.
Formats each byte in these groups using hexadecimal (base-16) representation.
Since base-16 positional count represents values 0 through 15 using a single digit ('0' through 'F'), a single byte is represented by two such digits — a digit per each group of 4 bits.
I think any sensible UUID package should implement a "decoding" function/method which would produce a string representation out of those 16 bytes.
I have picked a random package produced by performing this search query, and it has github.com/google/uuid.FromBytes which produces an UUID from a given byte slice, and the type of the resulting value implements the String() method which produces what you're after.
I have been trying to find a way to remap my keyboard and send 5-digit hex unicode chars, the method described here: ahk Send only supports 4-digit hex codes {U+nnnn}, I know that in the past, autohotkey didnt support unicode natively so it was needed some functions in order to do that, maybe thats the solution for me.
Example:
#If GetKeyState("CapsLock","T")
+u::Send {U+1D4B0}
The results from that is 풰 instead of 𝒰, and the code for 풰 is {U+D4B0}, meaning AHK is reading only the last 4 digits. How can I fix it even if I need to make new functions to achieve that?
Thanks
-Mark
Unicode values larger than 0xFFFF must be encoded as two surrogate pairs:
+u:: SendInput ,{U+D835}{U+DCB0}
Here is the algorithm to convert a Unicode code point that is in range 0x10000 to 0x10FFFF, to surrogate pairs, paraphrased from wikipedia:
First subtract 0x10000 from the code point, to get a number in range 0xFFFFF.
Then right shift the number by 10 bits and add 0xD800 to it to get the high surrogate.
Take the lowest ten bits of the number and add 0xDC00 to it to get the low surrogate
I took 2501's solution from above and turned it into working a working ahk script. I have been searching on and off for this solution for months!
+u:: FUNC_SEND_UNICODE( 0x1D4B0 )
FUNC_SEND_UNICODE(func_args)
{
/*
;commented out proof of concept code:
str := ""
u1 := Chr( 0xD835 )
u2 := Chr( 0xDCB0 )
str := u1 . u2
bk := clipboard
clipboard := str
send, ^v
sleep,200
clipboard := bk
*/
;bk == "clipboard [B]ac[K]up
bk := clipboard
;chunk of data that needs to be cut into
;two chunks.
ful := func_args + 0
/* commented out testing code, using original
sample input of stack overflow post
;msgbox,ful:[%ful%]
;for testing. Expecting input to be equal to
;the value in the post.
if(ful != 0x1D4B0 ){
msgbox,"[WHATTHEHECK]"
}
*/
;Subtract 0x10000 from ful, gets number
;in range(rng) 0x0 to 0xFFFFFF inclusive
rng := ful - 0x10000
if(rng > 0xFFFFF)
{
msgBox,[Step1 Resulted In Out Of Range]
}
;Do shifting and masking, then check to make
;sure the value is in the expected range:
big_shif := (rng >> 10)
lit_mask := (rng & 0x3FF)
if(big_shif > 0x3FF)
{
msgBox,[MATH_ERROR:big_shif]
}
if(lit_mask > 0x3FF)
{
msgBox,[MATH_ERROR:lit_mask]
}
big := big_shif + 0xD800
lit := lit_mask + 0xDC00
if(big < 0xD800 || big >= 0xDBFF){
msgBox, [HIGH_SURROGATE_OUT_OF_BOUNDS]
}
if(lit < 0xDC00 || lit >= 0xDFFF){
msgBox, [LOW_SURROGATE_OUT_OF_BOUNDS]
}
;Convert code points to actual characters:
u1 := Chr( big )
u2 := Chr( lit )
;concatentate those two characters to
;create our final surrogate output:
str := u1 . u2
;set it equal to clipboard, and send
;the clipboard. This is a hack.
;send,%str% works fine in google chrome,
;but fails in notepad++ for some reason.
;tried appending EOF, STX, ETX control codes
;along with output, but to no effect.
clipboard := str
send, ^v
;Must sleep before restoring clipboard,
;otherwise, the clipboard will get
;overwritten before ctrl+v has the chance
;to output the character. You'll end up just
;pasting whatever was originally on the
;clipboard.
sleep,200
clipboard := bk
return
}
An implementation of 2501's answer.
Listens for ;u
Followed by an ending character (e.g. ; or Return)
Waits for a sequence of keypresses like 1D4B0
Input ends when terminated by a ;
Sends the desired Unicode character directly if below 65536, calculates surrogate pairs otherwise
Inserts the desired Unicode character
:?:`;u::
Input, keys, , `;
if (StrLen(keys) < 5)
Send {U+%keys%}
else {
keys := "0x" + keys
num := keys - 0x10000
w1 := Format("{:x}", (num >> 10) + 0xD800)
w2 := Format("{:x}", (num & 1023) + 0xDC00)
Send {U+%w1%}{U+%w2%}
}
return
For reference:
Hotstrings
Input
StrLen
Casting string to numeric
Format
Bitwise operations
Send
From somewhere on the internet: sendunicodechar(0x1D4B0)
SendUnicodeChar(charCode)
{
VarSetCapacity(ki, 28 * 2, 0)
EncodeInteger(&ki + 0, 1)
EncodeInteger(&ki + 6, charCode)
EncodeInteger(&ki + 8, 4)
EncodeInteger(&ki +28, 1)
EncodeInteger(&ki +34, charCode)
EncodeInteger(&ki +36, 4|2)
DllCall("SendInput", "UInt", 2, "UInt", &ki, "Int", 28)
}
EncodeInteger(ref, val)
{
DllCall("ntdll\RtlFillMemoryUlong", "Uint", ref, "Uint", 4, "Uint", val)
}
edit. probably got downvoted bc of missing source. I simply dont know where I got it from anymore. But when I used it a few years ago, it worked flawlessly.
is there a way to change the shortcut to invoke auto completion in the squeak vm (standard is tab)?
Thanks in advance
(I assume you use OCompletion or ECompletion)
The only way to change this currently is to change the code.
OController>>handleKeystrokeBefore: kbEvent editor: theEditor
"I return a boolean. true when I have handled the event and no futher processing is needed by the caller."
| keyValue ctrl cmd down tab colon alphanum del esc enter up |
self editor: theEditor.
self setModel: theEditor model.
keyValue := kbEvent keyValue.
ctrl := kbEvent controlKeyPressed.
cmd := kbEvent commandKeyPressed.
down := keyValue = 31.
up := keyValue = 30.
tab := kbEvent keyCharacter = Character tab. "<-- change this to your desired key"
enter := kbEvent keyCharacter = Character cr.
colon := kbEvent keyCharacter = $:.
alphanum := kbEvent keyCharacter isAlphaNumeric.
"..."
Or, when you only use ECompletion
ECController>>handleKeystrokeBefore: aKeyboardEvent editor: anEditor
"I return a boolean. true when I have handled the event and no futher processing is needed by the caller."
| theEditor keyValue controlKeyPressed isSpaceKey |
self editor: anEditor.
theEditor := self editor.
self setModel: theEditor model.
keyValue := aKeyboardEvent keyValue.
controlKeyPressed := aKeyboardEvent controlKeyPressed.
isSpaceKey := #(0 32 ) includes: keyValue.
"Ctrl-Space or Tab for open"
self isMenuOpen
ifFalse: [(isSpaceKey & controlKeyPressed
or: [keyValue = 9 " <-- change this to your desired key"
and: [theEditor isCaretBehindChar
and: [controlKeyPressed not]]])
"..."
What does Go want for the second param in this SQL query.
I am trying to use the IN lookup in postgres.
stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field IN $2")
rows, err := stmt.Query(10, ???)
What I really want:
SELECT * FROM awesome_table WHERE id=10 AND other_field IN (this, that);
It looks like you may be using the pq driver. pq recently added Postgres-specific Array support via pq.Array (see pull request 466). You can get what you want via:
stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field = ANY($2)")
rows, err := stmt.Query(10, pq.Array([]string{'this','that'})
I think this generates the SQL:
SELECT * FROM awesome_table WHERE id=10 AND other_field = ANY('{"this", "that"}');
Note this utilizes prepared statements, so the inputs should be sanitized.
Query just takes varargs to replace the params in your sql
so, in your example, you would just do
rows, err := stmt.Query(10)
say, this and that of your second example were dynamic, then you'd do
stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id=$1 AND other_field IN ($2, $3)")
rows, err := stmt.Query(10,"this","that")
If you have variable args for the "IN" part, you can do (play)
package main
import "fmt"
import "strings"
func main() {
stuff := []interface{}{"this", "that", "otherthing"}
sql := "select * from foo where id=? and name in (?" + strings.Repeat(",?", len(stuff)-1) + ")"
fmt.Println("SQL:", sql)
args := []interface{}{10}
args = append(args, stuff...)
fakeExec(args...)
// This also works, but I think it's harder for folks to read
//fakeExec(append([]interface{}{10},stuff...)...)
}
func fakeExec(args ...interface{}) {
fmt.Println("Got:", args)
}
Incase anyone like me was trying to use an array with a query, here is an easy solution.
get https://github.com/jmoiron/sqlx
ids := []int{1, 2, 3}
q,args,err := sqlx.In("SELECT id,username FROM users WHERE id IN(?);", ids) //creates the query string and arguments
//you should check for errors of course
q = sqlx.Rebind(sqlx.DOLLAR,q) //only if postgres
rows, err := db.Query(q,args...) //use normal POSTGRES/ANY SQL driver important to include the '...' after the Slice(array)
With PostgreSQL, at least, you have the option of passing the entire array as a string, using a single placeholder:
db.Query("select 1 = any($1::integer[])", "{1,2,3}")
That way, you can use a single query string, and all the string concatenation is confined to the parameter. And if the parameter is malformed, you don't get an SQL injection; you just get something like: ERROR: invalid input syntax for integer: "xyz"
https://groups.google.com/d/msg/golang-nuts/vHbg09g7s2I/RKU7XsO25SIJ
if you use sqlx, you can follow this way:
https://github.com/jmoiron/sqlx/issues/346
arr := []string{"this", "that"}
query, args, err := sqlx.In("SELECT * FROM awesome_table WHERE id=10 AND other_field IN (?)", arr)
query = db.Rebind(query) // sqlx.In returns queries with the `?` bindvar, rebind it here for matching the database in used (e.g. postgre, oracle etc, can skip it if you use mysql)
rows, err := db.Query(query, args...)
var awesome AwesomeStruct
var awesomes []*AwesomeStruct
ids := []int{1,2,3,4}
q, args, err := sqlx.In(`
SELECT * FROM awesome_table WHERE id=(?) AND other_field IN (?)`, 10, ids)
// use .Select for multiple return
err = db.Select(&awesomes, db.SQL.Rebind(q), args...)
// use .Get for single return
err = db.Get(&awesome, db.SQL.Rebind(q), args...)
//I tried a different way. A simpler and easier way, maybe not too efficient.
stringedIDs := fmt.Sprintf("%v", ids)
stringedIDs = stringedIDs[1 : len(stringedIDs)-1]
stringedIDs = strings.ReplaceAll(stringedIDs, " ", ",")
query := "SELECT * FROM users WHERE id IN (" + stringedIDs + ")"
//Then follow your standard database/sql Query
rows, err := db.Query(query)
//error checking
if err != nil {
// Handle errors
} else {
// Process rows
}
Rather pedestrian and only to be used if server generated. Where UserIDs is a slice (list) of strings:
sqlc := `select count(*) from test.Logins where UserID
in ("` + strings.Join(UserIDs,`","`) + `")`
errc := db.QueryRow(sqlc).Scan(&Logins)
You can also use this direct conversion.
awesome_id_list := []int{3,5,8}
var str string
for _, value := range awesome_id_list {
str += strconv.Itoa(value) + ","
}
query := "SELECT * FROM awesome_table WHERE id IN (" + str[:len(str)-1] + ")"
WARNING
This is method is vulnerable to SQL Injection. Use this method only if awesome_id_list is server generated.
I'm not stupid... really.
How do you map a key SEQUENCE (ie: Ctrl + Q , F) in AutoHotKey.
I've got Ctrl + Q down:
^q::
I've even got F:
f::
The examples in the help files even show how to do two keystrokes in a row:
Numpad0 & Numpad1::
But it just will not work with:
^q & f ::
Or any of these either:
LCtrl & q & f::
^q & ^f::
^q^f::
^qf::
How do I accomplish a Key SEQUENCE triggering something, when one of those keys is the Ctrl key? I looked into using a HOTSTRING instead, but couldn't work out how to include the Ctrl character, in that context!
Alright; The answer seems to be:
^q::
Input Key, L1
if Key=f
...some code here...
return
In case someone's looking for a similar thing, but actually want CtrlQ + CtrlF and only if Ctrl is held throughout (so, to some, this might seem like CtrlQ + F), then here's how to do that:
$Ctrl::Send {Ctrl Down}
$Ctrl UP::
ChordIsBroken := True
Send {Ctrl Up}
Return
^q::
ChordIsBroken := False
Input, OutputVar, L1 M
If (!ChordIsBroken && Asc(OutputVar) = 6)
{
MsgBox "Hello, World!"
}
Else
{
SendInput %OutputVar%
}
Return
See https://superuser.com/a/725303/145431 for my explanation.
Or you can do it like this:
q & f::
if GetKeyState("Control") {
; Do something
return
}
return
I think this is a bit more readable than using Input Key, L1 as in above.
This catches CTRL+F. If Q is held down at that moment, your code fires.
^f::
If GetKeyState("q", "p") {
MsgBox test
} Else {
Send ^f
}
return
The selected answer works fine, but I spend the whole night writing me own solution before I found this answer, so...
Here is my over engineered solution -
SequenceRegister() {
registeredHook := 0
inputLen := 0
actions := Map()
return SequenceClosure
SequenceClosure(seq := "", ActionCb := () => true) {
if (!registeredHook) {
h := InputHook("BI")
h.KeyOpt("{All}", "N")
h.OnKeyDown := KeyDownHandler
h.Start()
registeredHook := h
}
actionKey := actions.Count
actions.Set(actionKey, Action)
Action(hook, VK, SC) {
if (SubStr(seq, 1, inputLen) = hook.Input && inputLen < StrLen(seq)) {
return
}
if (hook.Input = seq && inputLen = StrLen(seq)) {
ActionCb()
return
}
actions.delete(actionKey)
if (actions.Count = 0) {
Send("{Blind}" . Format("{{}vk{:x}sc{:x}{}}", VK, SC))
hook.Stop()
return
}
}
}
KeyDownHandler(hook, VK, SC) {
inputLen++
for key, value in actions.Clone() {
value(hook, VK, SC)
}
}
}
Use it like this -
Capslock & s::{
CreateSequence := SequenceRegister()
CreateSequence("sleep", () => MsgBox("I sleep"))
CreateSequence("sleed", SleedCb)
SleedCb() {
MsgBox("I sleed")
}
}
This allows to register any number of sequences and if none of the sequences match - the pressed key is replayed.
Note, that this code works only in AHK v2