How to swift between face and line? - x3d

I want to display a obeject that can be changed between face and line by a switch. What should I do?
here is my code:

You can use a Switch node that contains two versions of the object (one using IndexedFaceSet and one using IndexedLineSet) and toggle between them using the Switch.whichChoice property.
Here's an example:
Group {
children [
DEF sensor TouchSensor {}
DEF shapes Switch {
whichChoice 0
choice [
# Choice 0: Not wireframe
Shape {
appearance DEF appearance Appearance {
material Material {
emissiveColor 0 0.5 0
}
}
geometry IndexedFaceSet {
coordIndex [0 1 2 0 -1]
coord DEF coords Coordinate {
point [
-2 -2 0, 0 2 0, 2 -2 0
]
}
solid FALSE
}
}
# Choice 1: Wireframe
Shape {
appearance USE appearance
geometry IndexedLineSet {
coordIndex [0 1 2 0 -1]
coord USE coords
}
}
]
}
]
}
DEF script Script {
field SFNode shapes USE shapes
eventIn SFTime clicked
directOutput TRUE
url "javascript:
function clicked(){
if (shapes.whichChoice == 0){
shapes.whichChoice = 1;
} else {
shapes.whichChoice = 0;
}
}
"
}
ROUTE sensor.touchTime TO script.clicked

Related

swift filter 2d array by some value

I have an array like this
var cinema = Array(repeating: Array(repeating: 0, count: 30), count: 5)
user might input some values like this
cinema[1][20] = 5
cinema[1][21] = 6
Now, I would like to find out all nun 0 values and its index.
I think it is maybe possible to do it by for loop, but this is takes more time.
Is there a way to use something simpler? such as array.filter?
cinema.map {
$0.enumerated().filter { $0.element != 0 }
}
The code from #Jessy is correct.
cinema.map {
$0.enumerated().filter { $0.element != 0 }
}
Additionally, one could try follows as well:
for (i, row) in cinema.enumerated() {
for (j, cell) in row.enumerated().filter({$0.element != 0 }) {
print("m[\(i),\(j)] = \(cell)")
}
}

Count hashmap elements with condition for members? [duplicate]

I'm basically looking for the swift equivalent of the follow c++ code:
std::count_if(list.begin(), list.end(), [](int a){ return a % 2 == 0; }); // counts instances of even numbers in list
My problem isn't actually searching for even numbers, of course; simply the general case of counting instances matching a criterion.
I haven't seen a builtin, but would love to hear that I simply missed it.
Like this:
let a: [Int] = ...
let count = a.filter({ $0 % 2 == 0 }).count
An alternative to Aderstedt's version
let a = [ .... ]
let count = a.reduce(0){
(count, element) in
return count + 1 - element % 2
}
My intuition says my way will be faster because it doesn't require the creation of a second array. However, you'd need to profile both methods to be sure.
Edit
Following MartinR's comment about generalisation of the function, here it is
extension SequenceType
{
func countMatchingCondition(condition: (Self.Generator.Element) -> Bool) -> Int
{
return self.reduce(0, combine: { (count, e) in count + (condition(e) ? 1 : 0) })
}
}
let a = [1, 2, 3, 3, 4, 12].countMatchingCondition { $0 % 2 == 0 }
print("\(a)") // Prints 3
Default array:
let array: [Int] = [10, 10, 2, 10, 1, 2, 3]
filter(_:) method
let countOfTen = array.filter({ $0 == 10 }).count // 3
count(where:) method
Update: This Swift 5.0 feature was withdrawn in beta testing because it was causing performance issues for the type checker.
let countOfTen = array.count(where: { $0 == 10 }) // 3
You can use Collection.lazy to have the simplicity of Aderstedt's Answer but with O(1) space.
let array = [1, 2, 3]
let count = array.lazy.filter({ $0 % 2 == 0 }).count
The most compact reduce statement that will do this is:
let a = Array(1 ... 20)
let evencount = a.reduce(0) { $0 + ($1 % 2 == 0 ? 1 : 0) }
Reduce takes two variables: starts with 0 (var $0) then for every element in Array a (var $1) if the value is divisible by 2 with no remainder then add one to your count.
This is also efficient as it does not create an additional array unlike using a.filter(){}.count .
You can also do this with reduce()
let a = Array(1 ... 20)
let evenCount = a.reduce(0) { (accumulator, value) -> Int in
guard value % 2 == 0 else { return accumulator }
return accumulator + 1
}
Almost everything you want to do with the map() and filter functions can actually be done with a reduce although it's not always the most readable.
Swift 5 or later:
public extension Sequence {
func occurrences(where predicate: (Element) throws -> Bool) rethrows -> Int {
try reduce(0) { try predicate($1) ? $0 + 1 : $0 }
}
}
public extension Sequence where Element: Equatable {
func occurrences(of element: Element) -> Int {
reduce(0) { element == $1 ? $0 + 1 : $0 }
}
}
let multiplesOf2 = [1,2,3,4,4,5,4,5].occurrences{$0.isMultiple(of: 2)} // 4
"abcdeabca".occurrences(of: "a") // 3
extension BinaryInteger {
var isOdd: Bool { !isMultiple(of: 2) }
var isEven: Bool { isMultiple(of: 2) }
}
(-4).isOdd // false
(-3).isOdd // true
(-2).isOdd // false
(-1).isOdd // true
0.isOdd // false
1.isOdd // true
2.isOdd // false
3.isOdd // true
4.isOdd // false
(-4).isEven // true
(-3).isEven // false
(-2).isEven // true
(-1).isEven // false
0.isEven // true
1.isEven // false
2.isEven // true
3.isEven // false
4.isEven // true
let odds = [1,2,3,4,4,5,5,11].occurrences(where: \.isOdd) // 5
let evens = [1,2,3,4,4,5,5,11].occurrences(where: \.isEven) // 3

How do I filter out hashes from an array of hashes?

I have params that looks like this:
params = [{:limit=>5}, {:skip=>0}, {:asc=>""}, {:desc=>""}]
I want to remove the hash elements whose value is 0 or an empty string. I tried doing:
params.reject { |h| h.values !== 0 }
but this gives me a syntax error
Also tried:
params.select { |h| h.values != 0 || h.values != "" }
but this gives me nothing. What am I doing wrong?
You have an array of hashes, so you have to operate on each hash.
params.reject { |hash| hash.any? { |_, v| [0, ''].include?(v) }}
#=> [{:limit=>5}]
Instead of having an array of hashes with only one pair of |key,value|, you could just merge all the hashes to get one big hash.
It becomes easier to remove the unwanted values, and it also becomes easier to extract information :
params = [{ limit: 5 }, { skip: 0 }, { asc: '' }, { desc: '' }]
hash = params.inject(&:merge).reject{|_, value| value == 0 || value == '' }
# => {:limit=>5}
hash[:limit]
# => 5
With an array of hashes, you'd have to write :
(h = array_of_hashes.find{|h| h.keys.include?(:limit)} ) && h[:limit]
#=> 5
I found two ways to do this:
filtered = params.reject { |hash| hash.values.any? { |v| v.to_i == 0 } }
and
filtered = params.select { |hash| hash.values.none? { |val| val == '' || val == 0 } }
Using reject with include will also solve this problem.
params.reject { |key| key.values.include?(0) || key.values.include?("") }

extracting csv data and plotting 2D array using scala and processing

I was wondering if anybody might be able to shed some light on this problem, I'm quite new to scala and generally non R programming, so i'm still learning some of the ropes so to speak.
What i'm trying to do is plot a 2D array, so a grid of squares on a gray scale with a darker colour representing a higher value. I have a csv file of x and y locations on the grid and a third value z which will be represented by the colour.
I've written two pieces of code which do what I want, one extracts data from a csv file, the other plots the type of data that is extracted. The problem I have is getting them to work together.
So piece of code 1 extracts data which is as follows:
x, y, z
50, 16, 52
21, 25, 29
13, 12, 445
etc...
code:
import scala.io.Source
import java.io._
///////extract the data
object DataExtractor extends App {
def using[T <: Closeable, R](resource: T)(block: T => R): R = {
try { block(resource) }
finally { resource.close() }
}
for (line <- io.Source.fromFile("C://~//TestData.csv").getLines.drop(1)) {
val array = line.split(",")
try {
val xloc = array(0)
val yloc = array(1)
val intense = array (2)
}catch { case ex: Exception => }
}
}
This gives me a value from each line of the csv the x axis location (xloc), y axis (yloc) and what will be the intensity value (intense) in order to plot how darkly shaded the grid square is.
The second piece of code plots a 2D array using "processing"
/////////plotting data
import processing.core._
class FT extends processing.core.PApplet {
val xloc = 9 //define locations
val yloc = 1
val intense = 4 //define intensity of colour
var grid: Array[Array[Cell]] = _
var cols: Int = 100 // grid size
var rows: Int = 100
override def setup() {
size(200, 200) //window size
grid = Array.ofDim[Cell](cols, rows)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j) = new Cell(i * 10, j * 10, 10, 10, i + j) //cell size
}
}
override def draw() {
background(0)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j).display()
grid(i)(j).height()
grid(i)(j).xl()
grid(i)(j).yl()
}
}
class Cell(var x: Float,
var y: Float,
var w: Float,
var h: Float,
var strength: Float) {
def display() {
stroke(255)
fill(strength)
rect(x, y, w, h)
}
def height() {
strength = intense
}
def xl() {
x = xloc
}
def yl() {
y = yloc
}
}
}
As you can see, in my second piece of code i've given xloc, yloc and intense arbitrary values. What i'm trying to do is to loop through a csv file and for each line plug in the data to the plotting code so the final result is a grid with differing colour intensities based on the x, y and z values in the csv file.
Any help will be much appreciated as i'm still trying to figure out how one links chunks of code together in scala.
Edit:
So what i've tried is to integrate the two pieces of code, however I'm running into a new problem which is that scala will not initialize a local varaible within a method (var grid). But by moving grid outside of the loop it can no longer access the Cell class...any pointers or ideas would be much appreciated
import processing.core._
import scala.io.Source
import java.io._
class FT extends processing.core.PApplet {
for (line <- io.Source.fromFile("C:~TestData.csv").getLines.drop(1)) {
try {
val array = line.split(",")
var xloct = array(0)
var yloct = array(1)
var intenset = array (2)
val xloc = xloct.toFloat
val yloc = yloct.toFloat
val intense = intenset.toFloat
var grid: Array[Array[Cell]] =_ // error "local variables must be initialized"
var cols: Int = 100 // grid size
var rows: Int = 100
def setup() {
size(200, 200) //window size
grid = Array.ofDim[Cell](cols, rows)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j) = new Cell(i * 10, j * 10, 10, 10, i + j) //cell size
}
}
def draw() {
background(0)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j).display()
grid(i)(j).height()
grid(i)(j).xl()
grid(i)(j).yl()
}
}
class Cell(var x: Float,
var y: Float,
var w: Float,
var h: Float,
var strength: Float) {
def display() {
stroke(255)
fill(strength)
rect(x, y, w, h)
}
def height() {
strength = intense
}
def xl() {
x = xloc
}
def yl() {
y = yloc
}
}
} catch { case ex: Exception => }
}
}

Double loop in Groovy

How can I double loop using each if I have a structure like this:
Termin 1
[ [ 1][2 ][3 ] ]
Termin 2
[ [1 ] [2 ] [3] ]
Termin.each(){
println("first");
it.each(){
println("second"); // 1 2 3
}
}
it is used when you don't define the attribute name. You can just change the name:
def nested = [[1],[2],[3]]
nested.each { n ->
n.each { s ->
print "Nested: $s \n"
}
}
UPDATE
it is implicit to the wrapped closure, so if you are fluent with Groovy semantics, you can also use
def nested = [[1],[2],[3]]
nested.each {
// `it` is meant for the nested.each{}
it.each {
// `it` is meant for the it.each{}
print "Nested: $it \n"
}
}
Both of the approach yield the same result.

Resources