Possible to create random numbers in SASS / Compass? - css

I'm working on a project where I utilize SASS and Compass and need to somehow come up with some random numbers in the CSS file. Specifically, I need some floating point numbers between 0 and 1. Is this possible with SASS and Compass alone?

This is very possible if you create a sass function since sass is ruby its as easy as opening the functions module and injecting your random function
module Sass::Script::Functions
module MyRandom
def random
rand(1.0)
end
end
include MyRandom
end
require the file after sass has loaded
Then in your stylesheet
$my-randome-number: random();

Yes, as Scott said, it is possible, but I am not a Rails programmer, so I just wanted to copy and paste the code but first I did not know where to place the Code and then it did not work.
I had to play around with the snipped and expanded it to more Flexibility that I had need for:
module Sass::Script::Functions
module USW_Random
## Create random Color
# inspired by: http://victorcoulon.fr/generating-random-color-in-sass/
#
def usw_randomColor()
Sass::Script::Color.new([rand(255), rand(255), rand(255)])
end
## Create random Number
# int max [optional] if max is not supplied a float between 0 and 1 is returned.
# if max is supplied, an Integer between 0 and max (both inclusive) will be returned.
# int min [optional] if min is supplied too, an Integer between min and max (both inclusive) will be returned.
#
def usw_random(max=-1, min=0)
Sass::Script::Number.new( max.to_i < 0 ? rand() : rand(min.to_i .. max.to_i ))
end
end
include USW_Random
end
Ths can be used in a SCSS file like this:
#debug usw_random();
#debug usw_random(10);
#debug usw_random(8, 2);
#debug usw_randomColor();
and will printout:
xxx.scss:25 DEBUG: 0.42782
xxx.scss:26 DEBUG: 3
xxx.scss:27 DEBUG: 5
xxx.scss:28 DEBUG: #e7c00b
I also did not know where to put the Code for this. I use SASS within compass framework. You can place this Code directly into your Compass Config.rb file.
Or you put it in another file and only put this line into your Compass Config.rb file:
## my "own" ruby functions.
require "../SASS/RUBY/at.usw.rb"

Update: With Sass 3.3 (2014), there is now a built-in random() function:
http://sass-lang.com/documentation/Sass/Script/Functions.html#random-instance_method
$number: random()
You can also build your own simple seeded random function in Sass. Example (SCSS):
/* YOUR SEED HERE: */
$seed: 369;
#function getRandom($max) {
//http://indiegamr.com/generate-repeatable-random-numbers-in-js/
//Note the "!global" flag:
//http://webdesign.tutsplus.com/articles/understanding-variable-scope-in-sass--cms-23498
$seed: ($seed * 9301 + 49297) % 233280 !global;
#return ($seed / 233280) * $max;
}
.my-class {
height: getRandom(200) + px;
opacity: getRandom(1);
}
http://codepen.io/Sphinxxxx/pen/Gpmmye

Related

Stylus: how to create a CSS variable with a Mixin interpolation

How can a Stylus Mixin interpolate for both sides of the definition of a variable, such as:
--MyVariable: MyVariable
In the compiled CSS, --MyVariable should remain as the variable name, whereas the second variable should be the numerical value computed for this Stylus variable defined elsewhere.
I will have many such pairs of a CSS variable and a Stylus variable. Now, even though I could just manually write them down in the Stylus file, I would like to have a Mixin that allows me to create them by writing the shared part of the names just once as the Mixin's single argument, such as:
VariablePair(MyVariable-1) // --MyVariable-1: MyVariable-1
VariablePair(MyVariable-2) // --MyVariable-2: MyVariable-2
VariablePair(MyVariable-3) // --MyVariable-3: MyVariable-3
I tried:
VariablePair(VariableName)
--{VariableName}: VariableName
VariablePair(MyVariable)
It didn't parse.
I realized that MyVariable without '' would come as an actual value that couldn't be affixed to --. But, adding '' to it as VariablePair('MyVariable') would result in the right side of the definition itself becoming a string instead of the Stylus variable for computation.
I tried the different combinations of the presence/lack of the brackets and '' and $ as well as concatenations, but none of them seem to work. '--' + VariableName + ': ' + VariableName (with/without the brackets/$) isn't working, it either doesn't parse or does parse but without creating a line in the compiled CSS.
Is there a solution to this?
unquote works for this:
VariablePair(name, val)
{unquote('--' + name)}: val
.selector
VariablePair('fontcolor', red)
color: var(--fontcolor)
will output
.selector {
--fontcolor: #f00;
color: var(--fontcolor);
}

Static variable for VUs in K6

Is there a way to use a static variable shared across VUs in K6.
Say
// init code
let x = 0 // i want this to be static
// options
export let options = {
vus : 10,
iterations : 10
};
// VU code
export default function() {
x++;
console.log(x);
}
When I run this piece of code, the output should be incremental (1 to 10) and not 1 printed 10 times (1 for each VU).
In k6, each VU is a separate independent JS runtime, so you essentially have 10 copies of x. There is no way around that with stock k6 for now, you have to use some external service as an incrementing counter via HTTP or something like that. Alternatively, if you'll run k6 locally and only on a single instance, you can use this xk6 extension (more info): https://github.com/MStoykov/xk6-counter. It was a PoC originally developed for https://community.k6.io/t/unique-test-data-per-vu-without-reserving-data-upfront/1136/3 , but can be easily extended.

Difference between two files view in HTML using Java or any jar

I want to write a script which compare two files in java and see there difference in html page ( side by side ), can someone help me out how to write ( where to start). I am pulling my hair out for this....
I want to use this script in beanshell postprocessor so that I can compare the standard output files with result files easily
I don't think you should be asking people for writing code for you here, consider hiring a freelancer instead.
Alternatively you can use the following approach:
Add JSR223 Assertion as a child of the request which you would like to fail if files won't be equal
Put the following code into "Script" area:
def file1 = new File('/path/to/file1')
def file2 = new File('/path/to/file2')
def file1Lines = file1.readLines('UTF-8')
def file2Lines = file2.readLines('UTF-8')
if (file1Lines.size() != file2Lines.size()) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Files size is different, omitting line-by-line compare')
} else {
def differences = new StringBuilder()
file1Lines.eachWithIndex {
String file1Line, int number ->
String file2Line = file2Lines.get(number)
if (!file1Line.equals(file2Line)) {
differences.append('Difference # ').append(number).append('. Expected: ')
.append(file1Line).append('. Actual: ' + file2Line)
differences.append(System.getProperty('line.separator'))
}
}
if (differences.toString().length() > 0) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage(differences.toString())
}
}
If there will be differences in files content you will see them listed one by one in the JSR223 Assertion
See Scripting JMeter Assertions in Groovy - A Tutorial for more details.

Is there a way to print SASS value to output?

Suppose we have:-
$value: 13.37;
$length: $value + 0em;
Now i wanted to check the value of $length.
Is there anything similar to Javascript's Console.log?
If you want it to appear on the page itself, I believe you could attach it as the value of a pseudo-element. Something like:
body::before{ content: "#{$length}"}
Additionally, sass includes #error, #warn, #debug directives that will log things to the terminal to verying degrees of of noisiness.
#error "the value of $length is `#{$length}`"
More info on those can be found here

Building of a string, which depends on variable number of parameters

My question is: how to build a string in Less, which depends on variable number of parameters. For instance, I would like to make a mixin, which helps me to write #font-face CSS rules. So I need to build src:... fonts property for arbitrary number of formats (.eot, .ttf, .oft, .woff, .woff2, .svg) of my font. Here is my Less loop to process all font formats in list:
// #some-types - it is my font formats list, just smth. like 'otf', 'eot',...
// #old-src-value - it is string with src for my font from previous loop
// #counter - it is my loop counter
.make-font-src(#some-types; #old-src-value; #counter) when (#counter <= length(#some-types)) {
// Here we get next font format from #some-types
#font-type: extract(#some-types, #counter);
// Used for building 'format("opentype")' - like part of src value string
.get-font-format(#font-type);
// Building a part of src value string for this iteration
#src-value: e('#{old-src-value}, url("#{font-path}#{font-filename}.#{font-type}") format("#{font-format}")');
// Recursive call of this mixin for looping
.make-font-src(#some-types; #src-value; (#counter + 1));
}
So I'm stuck in how to fetch complete src value string, when all font formats will be processed in the loop? Also please refer to this codepen demo.
As mentioned in my comment, this would not cause a recursive definition error because you have assigned the value to a different variable and then used it. However, it seems like Less is processing the property-value setting line as soon as the first iteration of the loop is completed. You can verify this by changing the counter value for the first iteration itself to 2 or more.
One solution (a better approach to the problem in my opinion) would be to use the property merging with comma feature and set the property-value pair directly like in the below snippet:
.make-font-src(#some-types; #counter) when (#counter <= length(#some-types)) {
#font-path: 'some/test/path/';
#font-filename: 'Arial';
#font-type: extract(#some-types, #counter);
src+: e('url("#{font-path}#{font-filename}.#{font-type}") format("#{font-type}")');
.make-font-src(#some-types; (#counter + 1));
}
div.test {
.make-font-src('eot', 'woff', 'svg'; 1);
}
This when compiled would produce the following output:
div.test {
src: url("some/test/path/Arial.eot") format("eot"),
url("some/test/path/Arial.woff") format("woff"),
url("some/test/path/Arial.svg") format("svg");
}
Finally, I found my own solution: if we add special 'getter' mixin with guard, which triggered on last iteration of the loop, we can get full src value from our loop mixin.
.getter(#cond; #list) when (#cond = length(#list)) {
#font-src-full: #src-value;
}
Here is a fiddle with demo

Resources