How to append all list or union all set in a map's image in Isabelle - concatenation

Assume that p is a map defined as nat ⇒ string list or nat ⇀ string list and I want to append all string list in p's image
As the similar question, if p is a map defined as nat ⇒ string set or nat ⇀ string set and I want to union all string list in p's image.
For example, for p: 0 -> ["0.0"]; 1 -> ["1.0","1,1"], I want to get the result as ["0.0", "1.0", "1.1"]
for p: 0 -> {"0.0"}; 1 -> {"1.0","1,1"}, I want to get the result as {"0.0", "1.0", "1.1"}
It seems that in Isabelle has ⋃ to deal with the set union, but I can't find anything about append a set of lists.

Related

How to go through an array of images one after another

I'm quite new to programming and GDScript and wondering how to do something that I did think would be quite simple, but I'm struggling a bit!
I've loaded an array of images and I want it to go through each of these images one after the other each time a button is clicked and replace a sprite texture with that particular image.
Right now I can successfully get the sprite to change to any of the images if I put its array number in e.g. new_texture[0] or new_texture[3] etc., but I would like it to go through each of the images one after the other every time the user clicks the button. (And once it's got to the last image, go back to the first image again)
What am I missing?
Here is the code:
extends Node
onready var my_sprite = get_node("/root/Game/Picture/Sprite")
var new_texture = [
load("res://Art/Picture1.png"),
load("res://Art/Picture2.png"),
load("res://Art/Picture3.png"),
load("res://Art/Picture4.png"),
load("res://Art/Picture5.png"),
load("res://Art/Picture6.png")
]
func _on_Arrow_pressed() -> void:
my_sprite.texture = new_texture[0]
As you know, you can get the first image of the array like this:
new_texture[0]
Where new_texture is a variable that holds the array, and 0 is a constant (a literal, to be more precise) that indicates the position on the array.
So you can change the constant to get a different image, for example the fourth element is:
new_texture[3]
Now, that is fine if you want to change which element you get form one version to another of the game, since it requires to modify the code…
But you want which element from the array you get to change during the execution of the program. In other words, you don't want it to be constant, but variable.
So declare a variable that will hold which element you get:
var texture_index := 0
Use it instead of the constant:
func _on_Arrow_pressed() -> void:
my_sprite.texture = new_texture[texture_index]
And now you can change which element from the array you get by changing the value of the variable, for example:
func _on_Arrow_pressed() -> void:
my_sprite.texture = new_texture[texture_index]
texture_index += 1
Here we are changing the value of texture_index so the next time this code executes it gets the next position.
But be careful to keep the value of the variable inside the bounds of the array to avoid errors. So, what do you want to do after it reaches the last element? Do you want it to loop? Well, we can check if we reached the last element with an if, and set a different value to the variable, like this:
func _on_Arrow_pressed() -> void:
my_sprite.texture = new_texture[texture_index]
texture_index += 1
if texture_index == new_texture.size():
texture_index = 0
I remind you that elements of the array go from the position 0 to the position array.size() - 1. For example, if the array has 10 elements, they are in the positions 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (from 1 to 9, there are 9 numbers, plus the 0 you have 10 numbers). So an array with 10 elements does not have an element in the position 10. So there is no element in the position array.size(), thus, when the index reaches that value it is out of bounds of the array, and we reset it to the first element (position 0).
There are, of course, variation of this approach.

Converting TArray<string> to string (Delphi 10.2 Tokyo)

I want to convert a TArray<string> which is second parameter of third SelectDirectory (out Directories parameter) function to string to write selected path to edit box.
But I don't allow the user for multiple selection. So, only one directory can be selected.
What should I do?
Although you mention only the special case with a one-element-array, a general approach to convert a TArray<string> into a single string with all the array elements separated by a given string is using string.Join:
const
sep = ',';
var
arr: TArray<string>;
S: string;
begin
S := string.Join(sep, arr);
end;
If SelectDirectory() returns True, the output array is guaranteed to have at least 1 element in it. Since you don't enable multiple selection, the array is guaranteed to have only 1 element in it. So just access that element by index:
var
dirs: TArray<string>;
if SelectDirectory('', dirs) then
Edit1.Text := dirs[0]; // <--

Turning a list of Integers into a List of Colors

I have an image stored as a very large List Int and I would like to turn them into a List Color However remember that rgb requires 3 arguments and rgba requires 4. So let's try:
toColor : List Int -> List Color
toColor x =
if List.isEmpty x then
[]
else
List.append ( rgba <| List.take 4 x ) ( toColor <| List.drop 4 x )
This definition is recursive. We chomp 4 numbers, create an rgb color and append the results. However if x is List Int we cannot write this:
rgba <| List.take 4 x
Here is the kind of error we get. rgb is expecting three numbers and instead it gets a list
71| rgb <| List.take 4 x
^^^^^^^^^^^^^
(<|) is expecting the right argument to be a:
Int
But the right argument is:
List a
I wonder that taking out the first element of a List Int returns a Maybe Int
head : List a -> Maybe a
> head [1,2,3,4]
Just 1 : Maybe.Maybe number
Here is a modification of rgb which turns 3 Maybe Int into a Color. Now, reading the image data, I think rgba is necessary but I just add one more.
rgb' : Maybe Int -> Maybe Int -> Maybe Int -> Color
rgb' a b c =
case a of
Nothing -> rgb 0 0 0
Just a' -> case b of
Nothing -> rgb 0 0 0
Just b' -> case c of
Nothing -> rgb 0 0 0
Just c' -> rgb a' b' c'
this started when I was translating this d3js example to Elm and I noticed it used some features which aren't currently supported in Elm. In particular ctx.getImageData() since you can't import and image to Canvas. So this is part of my make-shift solution.
It seems to me that you're looking for a really clean way to
Collapse a List Int into a List (List Int), where each child list has at most 3 or 4 members if you want to do rgb or rgba.
Pass each List Int into a function that will convert it using rgb, handling the case where there aren't enough Ints in the final entry.
For the first step, you can write a function called groupList:
groupsOf : Int -> List a -> List (List a)
groupsOf size list =
let
group =
List.take size list
rest =
List.drop size list
in
if List.length group > 0 then
group :: groupsOf size rest
else
[]
You can also get this functionality by using the greedyGroupsOf function from the elm-community/list-extra package.
For the second step, it'll be much cleaner to pattern match on the structure of the list value itself rather than using List.head and matching on Maybe.
rgbFromList : List Int -> Color
rgbFromList values =
case values of
r::g::b::[] ->
rgb r g b
_ ->
rgb 0 0 0
The first case will be matched when there are exactly 3 entries in the list, and everything else will fall through to handing 0s to rgb.
You can put all of these things together by doing the following:
toColor : List Int -> List Color
toColor x =
x
|> groupsOf 3
|> List.map rgbFromList
Alternatively, if instead of ending up with rgb 0 0 0 for invalid colors you want to exclude them entirely, you can use the List.filterMap function to prune out things you don't want. We can change rgbFromList to look like
rgbFromList : List Int -> Maybe Color
rgbFromList values =
case values of
r::g::b::[] ->
Just <| rgb r g b
_ ->
Nothing
and then call it like
toColor : List Int -> List Color
toColor x =
x
|> groupsOf 3
|> List.filterMap rgbFromList
Please be advised that since the groupsOf function here as well as greedyGroupsOf in elm-community/list-extra is recursive, it will fail for very large lists.
Edit: for very large lists
For very large lists it's easy to get into trouble with recursion. Your best bet is to fold over the list and manage some intermediate state while you're folding:
groupsOf : Int -> List a -> List (List a)
groupsOf size list =
let
update next state =
if (List.length state.current) == size then
{ current = [next], output = state.current :: state.output }
else
{ state | current = state.current ++ [next] }
result =
List.foldl update { current = [], output = [] } list
in
List.reverse (result.current :: result.output)
This works by folding over the list, which is an iterative process rather than recursive, and building up groups one at a time. The last step reverses the list because it will be constructed in reverse order in order to cons instead of doing costly appends once the output list begins to grow large. I don't expect this to overflow the stack, but it is likely that it will be very slow. In my opinion, your best option to get the outcome you are looking for in a reasonable amount of time is to write the groupsOf function in JavaScript using a for loop and then pass the result in through a port.
This recursive implementation should work without building the stack, because Elm has tail call optimisation. Each step takes three ints from the original list, and appends them to the list of colors. Recursion stops and returns the list of colors, when there are less than three elements in the original list.
It uses rgb, but can be easily modified to take 4 elements from the list.
It also reverses the order, so you might need to combine it with List.reverse.
import Color exposing (rgb, Color)
listColors : List Int -> List Color
listColors =
listColors' []
listColors' : List Color -> List Int -> List Color
listColors' colors ints =
case ints of
r :: g :: b :: rest ->
listColors' (rgb r g b :: colors) rest
_ ->
colors

Django 1.6 - How to find gap between sorted IP addresses from pool and return top one

I have a model in my data base having users and IP addresses as field.
Assume table data is like:
**User** **IP Address**
xyz 127.0.0.1
pqr 127.0.0.2
lmn 127.0.0.3
qwe 127.0.0.4
fds 127.0.0.5
... ...
... ...
... ...
poi 127.0.0.100
Now I delete the 2nd, 4th, 8th and 50th row from the table
Now table looks like:
**User** **IP Address**
xyz 127.0.0.1
lmn 127.0.0.3
fds 127.0.0.5
... ...
... ...
... ...
poi 127.0.0.100
Now I want to check all IPs in sorting order and return the minimum deleted value of IP.
How to do that?
I assume you are only operating on one ip range like 127.0.0.*
if you want to work on multiple ip ranges the statement will become more complicated
so generally to sort a list of ip numbers by their last part (127.0.0.XXX), you can perform the following sort operation
sorted(my_ip_list, key=lambda x:int(x.split('.')[3]))
to return a new sorted list
or
my_ip_list.sort(cmp, key=lambda x:int(x.split('.')[3]))
for in-place sorting
to get the smallest gap in your ip list you can do the following list comprehension
sorted(
[ y for y in [ ''.join(['127.0.0.',str(x)]) for x in range(1,255) ]
if y not in my_ip_list ]
, key=lambda x:int(x.split('.')[3]))[0]
so what does it do?
let's look at it from inside out:
my_ip_list := is list of ip adresses with deleted entries
next: the list comprehension
[ y for y in [ ''.join(['127.0.0.',str(x)]) for x in range(1,255) ]
if y not in my_ip_list ]
This will build a list of ip addresses from 127.0.0.1 to 127.0.0.255.
Then it will iterate over each created ip address and check if it is NOT in your real ip addresses list. If not, append that ip address to a new list.
In other words: we get a list of deleted ip addresses
Last step, sort the list of deleted ip addresses to find the smallest one. here you can see why my approach only works with a very limited set of ip addresses, as we sort only by the last part of the address (the 127.0.0.XXX part)
Anyway this last step follows the aforementioned idea of sorting ip ranges with sorted(...), or list.sort()

How do I implement an array of strings?

I tried to implement a word that produces a string from an array when given a number on the stack in Forth.
My first naive attempt was:
create myarray s" Alpha" , s" Beta" , s" Charlie" ,
This was accepted, but it did not work as expected — myarray # type produces inconsistent output (instead of my naive expectation that it might print "Alpha").
When searching the web, I found in Gforth documentation that a string created with s" has a limited lifetime which means that my ansatz is bound to fail from the beginning. On the other hand, even arrays of regular objects seem to be not standardized according to Arrays in Forth section in Len's Forth Tutorial.
<Update> Apparently, this is not a trivial problem with Forth. There are libraries on the web that implement missing string functionality: FFL (str module) and String Functions by Bernd Paysan. This is a good starting point, although it still requires work to go from there to an array of strings. </Update>
So how can I implement a word that returns a string from a given array?
To address parts of your code, s" leaves addr u on the stack, an address and the length of the string. , only stores one value so you won't get the desired results that way. 2, might do it as that would store both of the stack items that represent the string. Once you have done that you need to get both values back too so 2# is what you want.
My rewrite would look like this:
create myarray s" Alpha" 2, s" Beta" 2, s" Charlie" 2,
\ Test
myarray 2# type Alpha **ok**
Getting at the other elements of your array is a bit trickier. When you type myarray you get the address of the start of the data in that dictionary entry, and you can then use 2# to get the the things that the first two addresses point to (which are the address and length of "Alpha"). If you want "Beta you need the next pair of addresses. So you can use
myarray 2 cells + \ increment the address by two cells
To get the addresses that point to "Beta" and so on. So in order to access "Beta" you would enter
myarray 2 cells + 2# type Beta **ok**
I have tested this with gforth and it seems to all work, although I am not sure how to rigorously test for persistence.
Your word would need to be able to do the address incrementing based on what is on the stack to start with. You might want to get into some more create does> stuff. I can give some pointers but I don't want to spoil the fun of discovery.
If I am skipping too many details of what this actually means just say, and I will try again.
Maybe this is too crude, but I had a go at making a "string type" of sorts a while ago.
: string ( addr u "name" -- )
create 2, \ add address and length to dict entry "name"
does> dup cell+ # swap # ; \ push addr u
\ Example
s" Some Words" string words **ok**
words type Some Words **ok**
It defines a word with a name of your choosing (in this case "words") that will push length and start address of your string (in this case "some words") when it is interpreted. As far as I know when the string is in a definition like this it is persistent.
This doesn't answer you question fully, but it might help.
I have had another go at a persistent string, this one definitely allots memory within a dictionary entry and will be safe as long as that word exists. Before the string "type" only stored the address and length that s" created which is only any good until something else writes over that region of memory. This now copies the string from where s" creates it into a dictionary item called "name" where it is guaranteed to last as long as "name" itself.
: string ( addr u "name" -- )
create \ create dict entry called "name"
dup >r here >r \ keep copies of string length and start of "name"'s memory
dup 2 cells + allot \ allot memory for the number of chars/bytes of the string plus 2
\ for the new addr u
r# 2 cells + \ Get the address two cells from the start the space for "name"
swap cmove \ copy the string at addr u into the alloted space for "name"
\ Now "name" looks like this: "name" -blank1- -blank2- "the text of the string at addr u"
\ blank1 should be the address of the start of the the text = addr2 and blank2 should be u
r# dup 2 cells + swap ! \ get the address of blank1, copy it, increment by 2 to get addr2
\ and then store that in blank1
r> cell+ r> swap ! \ get address of blank1, increment to get address of blank2, then get u and
\ store it in blank2
\ Now "name" looks like this: "name" addr2 u "the text of the string at addr u"
does> dup # swap cell+ # ; \ push addr2 u
For amusement, I thought I might show how little sense this makes without helpful formatting
: string-no-comments ( addr u "name" -- )
create dup >r here >r dup 2 cells + allot r#
2 cells + swap cmove r# dup 2 cells + swap !
r> cell+ r> swap ! does> dup # swap cell+ # ;
Firstly. You must ALLOT permanent storage to the strings. In ciforth (my Forth) there is the word $, that does this in the dictionary space.
S" aap" $,
leaves an address with one cell count, followed by characters.
There is no standard word that does similar, you have to write it yourself. This is assuming ALLOCATE is not available.
Using this the following code saves string pointers temporarily to the stack:
0 s" Alpha" $, s" Beta" $, s" Charlie" $,
Then you must store there pointers in an array, hence the sentinel 0, at the expense of an extra auxiliary word:
: ttt BEGIN DUP WHILE , REPEAT DROP ;
And then
( CREATE string-array) ttt
HERE CONSTANT ttt-end
Now you can address strings as follows:
tt-end 2 CELLS - ( #+ TYPE )
You may want add auxiliary words.
This is ugly, cumbersome and far and foremost standard way to do it.

Resources