Composable: Adjust items size like in LazyGrid - responsive-design

I have my custom grid. I need to adjust size of its elements like it weight(1f) except for the last row when the size should be same as other (like in LazyGrid on the screenshot), how's it possible?
#Composable
fun <T> VerticalGrid(
data: List<T>,
columnCount: Int,
itemContent: #Composable (T) -> Unit
) {
val size = data.size
val rows = if (size == 0) 0 else 1 + (size - 1) / columnCount
Column {
for (rowIndex in 0..rows) {
val itemIndex = rowIndex * columnCount
val end = min(itemIndex + columnCount, size)
Row(modifier = Modifier.fillMaxWidth()) {
for (index in itemIndex until end) {
itemContent(data[index])
}
}
}
}
}

Related

how do I format my response array in angular?

Need to format my array for chart purpose
myArr=[["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]
Below Formatted Array
formatArr= [["6709", "1949", "87484", "12760"], ["13326", "3356", "98000", "16949"], ["29981", "7879", "117640", "30727"], ["122071", "21325", "210406", "65824"], ["2744807", "56664", "382719", "134578"] ["2440528", "83819", "1362744", "450092"], ["2461", "336", "166446", "16363"]]
You could reduce it like this for example:
const formatArr: string[][] = myArr.reduce((prev, item, index) => {
if (index % 4 === 0) {
// every fourth item creates a new array with the current item:
prev.push(item);
} else {
// every other item pushes to the previously added item:
prev[prev.length - 1].push(item[0]);
}
return prev;
}, [] as string[][]);
myArr = [["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]
formatArr = []
function makeArray(params) {
let element = [];
for (let i = 0; i < myArr.length; i++) {
element.push(myArr[i][0])
if ((i + 1) % 4 == 0) {
formatArr.push(element);
element = [];
}
}
console.log(formatArr);
}
makeArray();
This is correct if myArr has 4n element, if not use this
function makeArray(params) {
let element = [];
for (let i = 0; i < myArr.length; i++) {
element.push(myArr[i][0])
if ((i + 1) % 4 == 0) {
formatArr.push(element);
element = [];
}
if (i == myArr.length - 1 && (i + 1) % 4 != 0) {
formatArr.push(element);
}
}
console.log(formatArr);
}

How to get max(id) of table = Rep[Option[Long]] for subsequent insert, without calling db.run in between

I have an insert to a table, that depends on the max id of another table.
def add(languageCode: String,
typeId: Long,
properties: Seq[Property]): Unit = {
val dbAction = (
for{
nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
language <- (languages.all filter (_.code === languageCode)).result.head
_ <- DBIO.seq(properties.map
{
property =>
val id = property.id
val name = property.key
val value = property.value
if(id == 0) {
val currentPropId: FixedSqlAction[Option[Long], h2Profile.api.NoStream, Effect.Read] = this.properties.all.map(_.id).max.result
val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, currentPropId + 1, name)
nodeProperties.all += NodeProperty(nodeId, 2, value)
} else {
nodeProperties.all += NodeProperty(nodeId, id, value)
}
}: _*)
} yield()).transactionally
db.run(dbAction)
}
As you can see, the problem is that currentPropId is of type Rep[Option[Long]] and of course Property needs a proper Long instead.
For the languageId it sufficed to add a result to the query (languages.all filter (_.code === languageCode)).result.head
But for the currentPropId the type then still is of FixedSqlAction
edit:
Trying it like this
if(id == 0) {
this.properties.all.map(_.id).max.map {
id =>
val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, id+1, name)
val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)
propertyId andThen nodeProperty
}
Does not work, because that's not a Seq[DBIOAction] anymore but a Seq[Object] (Not Any, but Object)
You cannot mix the lifted types (Rep[_]) with standard Scala types.
You can map over your SqlAction to extract the needed type.
val currentPropId: FixedSqlAction[Option[Long], NoStream, Effect.Read] = ???
currentPropId.flatMap { id: Option[Long] =>
???
}
In your exact case, something like this:
if(id == 0) {
properties.map(_.id).max.result.flatMap { id: Option[Long] =>
val propertyId = (properties returning properties.map(_.id)) += Property(language.id.get, id.map(_ + 1), name)
val nodeProperty = nodeProperties += NodeProperty(nodeId, 2, value)
propertyId andThen nodeProperty
}
}
...

Changing old C for loop to new Swift loop

I have an old Xcode 7.3 Swift 2 code. I need to change these two for loops to the new swift 3 for loop syntax.
fileprivate func collapseSubItemsAtIndex(_ index : Int) {
var indexPaths = [IndexPath]()
let parent = self.findParent(index)
checkCurrentLanguage()
if lang.isEqual(to: "en")
{
//For loop 1
for (var i = index + 1; i <= index + self.engsubItems[parent].count; i += 1 ){
indexPaths.append(IndexPath(row: i, section: 0))
}
self.engtableview.deleteRows(at: indexPaths, with: UITableViewRowAnimation.fade)
self.engtotal -= self.engsubItems[parent].count
}
else{
//For loop 2
for (var i = index + 1; i <= index + self.subItems[parent].count; i += 1 ){
indexPaths.append(IndexPath(row: i, section: 0))
}
self.tableView.deleteRows(at: indexPaths, with: UITableViewRowAnimation.fade)
self.total -= self.subItems[parent].count
}
}
let count = self.engsubItems[parent].count
let rowsToDelete = ((index + 1) ... (index + count))
.map { IndexPath(row: $0, section: 0) }
self.engtableview.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.fade)
self.engtotal -= count
for i in (index+1)...(index + self.engsubItems[parent].count) {
...
}
for i in (index+1)...(index + self.subItems[parent].count) {
...
}

Optimizing comparison of values in large arrays - Go

I am trying to learn Go, and made an attempt at solving the problem explained here https://projecteuler.net/problem=215
I made a solution that works, but it takes a very long time to compute once the problem gets complex, literally running for hours without solving the question so i assume i need to optimize my solution somehow. Below is my code
package main
import "fmt"
func main() {
fmt.Println(wall(18, 10))
}
func wall(width, height int) int64 {
var total int64
combinations := findCombinations(width)
combiPointer := &combinations
for i := 0; i < 4; i++ {
for _, a := range combinations[i] {
if i%2 == 0 {
buildWall(a, combiPointer[i+1], 0, height, i+1, &total, combiPointer)
} else {
buildWall(a, combiPointer[i-1], 0, height, i-1, &total, combiPointer)
}
}
}
return total
}
func buildWall(a []int, combi [][]int, level, height, index int, total *int64, pointer *[4][][]int) {
level++
var canCombine bool
for _, a1 := range combi {
canCombine = true
for _, value := range a {
if canCombine == false {
break
}
for _, value1 := range a1 {
if value == value1 {
canCombine = false
break
}
}
}
if canCombine == true && level < height {
if index%2 == 0 {
buildWall(a1, pointer[index+1], level, height, index+1, total, pointer)
} else {
buildWall(a1, pointer[index-1], level, height, index-1, total, pointer)
}
} else if level == height {
*total++
break
}
}
}
findCombinations works fine and returns a three dimensional array with all possible solutions. The arrays in [0] and [1] can (maybe) be put on top of each other without a crack occuring. Same for [2] and [3]. I choose to cut the array of all solutions up in 4 arrays by looking at the position of the first and last block used to build the wall as i assumed it would increase performance to loop over smaller arrays.
func findCombinations(width int) [4][][]int {
var i int
var tmp int
var tmpInt1 int
var tmpInt2 int
open := make([][]int, 0, 100)
var solutionsHolder [4][][]int
open = append(open, []int{3, 2})
tmpArray := make([]int, 0, 100)
for {
if len(open[i]) > 0 {
tmpArray = append(tmpArray[:i], open[i][0])
open[i] = append(open[i][:0], open[i][1:]...)
counter := 0
for _, x := range tmpArray {
counter += x
}
if counter == width {
solutionArray := make([]int, len(tmpArray)-1)
counter2 := 0
for n := 0; n < len(tmpArray)-1; n++ {
if n == 0 {
tmpInt1 = tmpArray[n] % 2
}
counter2 += tmpArray[n]
solutionArray[n] = counter2
}
tmpInt2 = counter2 % 2
if tmpInt1 == 0 && tmpInt2 == 0 {
solutionsHolder[0] = append(solutionsHolder[0], solutionArray)
} else if tmpInt1 == 1 && tmpInt2 == 1 {
solutionsHolder[1] = append(solutionsHolder[1], solutionArray)
} else if tmpInt1 == 1 && tmpInt2 == 0 {
solutionsHolder[2] = append(solutionsHolder[2], solutionArray)
} else {
solutionsHolder[3] = append(solutionsHolder[3], solutionArray)
}
for _, v := range open {
tmp += len(v)
}
if tmp == 0 {
return solutionsHolder
}
tmp = 0
} else if counter > width {
for _, v := range open {
tmp += len(v)
}
if tmp == 0 {
return solutionsHolder
}
tmp = 0
} else if counter < width {
i++
if len(open) <= i {
open = append(open, []int{3, 2})
} else {
open[i] = append(open[i], []int{3, 2}...)
}
}
} else {
i--
}
}
}
Its the wall function that calls a recursive function which will run for a very long time (i've had it run for an hour without a result) if you insert a width and height of wall(32,10) as they want you to compute on the website.
buildWall() which is called by wall checks whether there is no crack on the same position for two solutions and if this is the case it runs buildWall again for the next level of the wall until the walls height is reached. It does this for every solutions comparing it to all other possible solutions, though limited to one subset of the 3d array.
I'm thinking maybe there is another approach to find all the possible walls that can be combined, but i can't seem to wrap my head around it.

Get values from a Array in a Dictionary in Swift

My ambition is to have a Dictionary that contains (among other things) an array and being able to get out the values of that array.
var total: Int = 0;
let dice:[NSTextField:NSArray] = [
d4Amount:[d4OE, 4],
d6Amount:[d6OE, 6],
];
for (die, dieArray) in dice
{
let button:NSButton = dieArray[0] as! NSButton;
let num:Int = dieArray[1] as! Int;
total += DoRoll(die, oe: button, max: num);
}
In the above the line "let button:NSButton = dieArray[0]..." get's the error Thread 1: signal SIGABRT and the program fails.
First I only had the line:
total += DoRoll(die, oe: dieArray[0] as! NS Button, max: dieArray[1] as! Int);
Which didn't either work (quite obviously), but however when I do this, it works...
total += DoRoll(d4Amount, oe: d4OE, max: 4);
It works perfectly.
Any ideas??
The function DoRoll looks like this (which should not be relevant):
private func DoRoll(amount: NSTextField, oe: NSButton, max: Int) -> Int
{
let nrRolls: Int! = Int(amount.stringValue);
var total: Int = 0;
if(nrRolls != nil && nrRolls != 0)
{
OutputText.string = OutputText.string! + "Now rolling d" + String(max) + ": ";
for(var i: Int = 0; i < nrRolls; i++)
{
var randomNr: Int, specialMax: Int;
var textStr: String = "";
specialMax = max;
if(max >= 100)
{
if(max > 100)
{
specialMax = 995;
}
else if(max > 99)
{
specialMax = 95;
}
else
{
specialMax = max - 1;
}
}
repeat
{
randomNr = Int(arc4random_uniform(UInt32(max))) + 1;
total += randomNr;
if(textStr != "") { textStr = textStr + "+"; }
textStr = textStr + String(randomNr);
} while(oe.state == NSOnState && randomNr >= specialMax)
OutputText.string = OutputText.string! + textStr + " ";
}
OutputText.string = OutputText.string! + "\n";
}
return total;
}
I now know what I did wrong.
This is not at all a case of error in the code above but in the naming of items in the project. I had several different D4Amount in the same project in the View and thus that was why it crashed.
Sorry to bother you.

Resources