how to make check/uncheck randomly in cypress - cypress

I want to make random check/uncheck(miss) checkboxes
cy.get('[type="checkbox"]').check()/uncheck()
How can I do this?

You can use Math.random() to generate a number and based on the number, you can check uncheck on the checkbox.
//Generate Random numbers between 1 and 100
cy.wrap(Math.floor(Math.random() * 101)).then((num) => {
if(num <=50){
cy.get('[type="checkbox"]').check()
}
else {
cy.get('[type="checkbox"]').uncheck()
}
})

Related

Add sum row at end DataTable dc.js/reactJS

I have been given task at work place to make sum row and since am still in process of learning dc.js/d3.js and quite stuck in progress to solve this. How can i add sum row at end of table?
https://codesandbox.io/s/dark-shape-g7o2b?file=/src/MyComponent.js
At work they are sending group as dimension, but don't know how to make it work
A previous answer described how to add a row using dc.numberDisplay and a <tfoot> row:
How to calculate the total sales and make the displayed totals dynamic?
However, if you can't modify the HTML, you can also display a total row by computing it using a fake group.
The idea is to create an object which supports .all() and .top(), the methods the data table will use to pull data. When it returns the data, it will add another entry with the totals:
return {
all: () => {
let all = orig_group.all();
const total = all.reduce(
(p, v) => {
range(ship_size_id_start, ship_size_id_end).forEach(
i => (p.value[i] = (p.value[i] || 0) + (v.value[i] || 0))
);
p.value.sum += v.value.sum;
return p;
},
{ key: "Total", value: { sum: 0 } }
);
all = all.concat([total]);
return all;
},
top: function(N) {
return this.all().slice(0, N);
}
};
This grabs the original data using orig_group.all(), then uses Array.reduce to find the sums. The Array.reduce function loops over all the ship size ids and sums the columns, and also sums the sums for a grand total.
I had to declare
const ship_size_id_start = 1,
ship_size_id_end = 8;
in order to know what to loop over.
I also had to add the translation
Total: "Total"
for the title to show up in the left column.
Fork of your code sandbox.
bolding the totals line
You can still bold the last line without editing the DataTable component; however you will need a unique selector (like a div with an #id) in order to do this safely.
So the following CSS works
table.data-table.dc-chart tbody tr:last-child {
font-weight: bold;
}
but it will style all dc data tables on the page, so be careful. I added it to the styles in my fork.

Laravel sort collection by multi fields

I stucked with a collection sorting in laravel based on different situations.
For simplicity here is an example collection:
1;
pmt: 1
thm: 1
customerFriendly: false
2;
pmt: 1
thm: 1
customerFriendly: true
3;
pmt: 2
thm: 4
customerFriendly: true
I need to sort this collection first based on the pmt value. Lowest first.
If there are same pmt values than I need a second sorting based on the thm value.
After that if there is maybe a same thm than I need to sort it again by the customer boolean field.
So based on the above example the final sorted list should be 2,1,3
As far as I get I can sort the list first by pmt and if same pmt-s found by thm, but I cant sort it by customerFriendly.
Here is my code:
$pmtDuplicated = $this->checkDuplicates($transformedLoans, 'pmt');
if ($pmtDuplicated) { //If we found same pmt-s sort by thm also
$secondSort = $transformedLoans->sortBy(function ($item) {
return $item->pmt . '-' . $item->thm;
})->values();
$thmDuplicatesInSecondSort = $this->checkDuplicates($secondSort, 'thm'); //Check again for same thm
if ($thmDuplicatesInSecondSort) { //If we found same thm sort by customerFriendly also
return $secondSort->sortBy('customerFriendly')->values();
} else {
return $secondSort;
}
} else {
return $transformedLoans->sortBy('pmt')->values();
}
Someone maybe can help me out? Thank you.
I found the solution, and I leave it here if for someone is a help later.
Instead of this section:
if ($thmDuplicatesInSecondSort) { //If we found same thm sort by customerFriendly also
return $secondSort->sortBy('customerFriendly')->values();
}
I needed to use this:
if ($thmDuplicatesInSecondSort) { //Ha van THM alapján is egyezés akkor fogyasztóbarát alapján is rendezzen
return $secondSort->sortBy(function ($item) {
return $item->customerFriendly === false ? 1 : 0;
})->values();
}

How to add filter result to select menu

I'm stuck with my first dashboard project with d3, dc and crossfilter. Cannot find a solution.
"ETCBTC","BUY","0.002325","1.04","0.00241800","0.00104","ETC"
"ETCBTC","SELL","0.002358","1.04","0.00245232","0.00000245","BTC"
"LTCETH","SELL","0.30239","0.006","0.00181434","0.00000181","ETH"
"LTCETH","SELL","0.30239","0.149","0.04505611","0.00004506","ETH"
I have different trading pairs in first column and from it i need to use only last pair BTC and ETH in this example.
I found the filter that helps me to do that.
The thing is I need to have BTC and ETH in my select menu which can apply filter.
function show_market_selector(ndx) {
var marketDim = ndx.dimension(dc.pluck("Market"));
var selectorMenu = marketDim.group();
function filterItems(query) {
return ndx.dimension(dc.pluck("Market")).filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > 0;
});
}
filterItems("BTC");
var select = dc.selectMenu("#market-selector")
.dimension(marketDim)
.group(selectorMenu);
select.title(function (d){
return "BTC";
});
}
Now I get all pair in group in this menu. But my target is just to have BTC and ETH in the select menu.
I hope someone can give me advice. Thank you.
I think it would be easier just to use the currency as your dimension key:
var currencyDim = ndx.dimension(d => d.Market.slice(3)),
currencyGroup = marketDim.group();
var select = dc.selectMenu("#market-selector")
.dimension(currencyDim)
.group(currencyGroup);
You don't really want to create a new dimension every time filterItems is called - dimensions are heavy-weight indices which are intended to be kept around.
The name of dimension.filter() is confusing - it's nothing like JavaScript's Array.prototype.filter(), which returns the matching rows. Instead, it's an imperative function which sets the current filter for that dimension (and changes what all the other dimensions see).
If you need a "from currency" dimension, that would be
var fromCurrencyDim = ndx.dimension(d => d.Market.slice(0,3))

jQuery Select2 - select same option multiple times

I am trying to make a page in my website where I want to use this select2 (http://ivaynberg.github.io/select2/) plugin. My requirement is to include same "words" multiple times.
My tags could be:
Monthly_Rent, Monthly_Rent, commission, mortgage, commission
Also when user loads the page, I want to maintain the order how user selected it before saving.
Currently when I add any option, its removed from the list. How can I add it again?
Another issue is, now if I want to remove "commission" which is before "mortgage", it should not delete another "commission" word which is at last.
Please help me understand how to achieve this.
just use a counter and a query function to provide data :
var fruits = ['apple', 'pear', 'orange', 'strawberry']
var counter = 0
$("#yourinput").select2({
query: function(query) {
var data = { results: []};
for (var i = 0; i < fruits.length; i++) {
data.results.push({"id": fruits[i] + "/" + counter, "text": fuits[i]});
}
counter += 1;
query.callback(data);
},
formatSelection: function(item) {
return item.text; // display apple, pear, ...
},
formatResult: function(item) {
return item.id; // display apple/1, pear/2, ... Return item.text to see apple, pear, ...
},
multiple: true,
closeOnSelect: true
}
So, the first time you click on your select box, the data are initialized with apple/1, pear/1, ... The next time, you get apple/2, pear/2, ..., next apple/3, ... and so on.
Each time you select a fruit, you get an different id, even you choose same fruit you have previously chosen. Keeping an unique counter you increment at each select allow you to delete a fruit without side effect : its id disappeared, and will not be reused.
closeOnSelect is set to true, to increment counter at each selection (more precisely, each time you open the select box). If you set it to false, when you select a fruit, it disappears from list, and you cannot select two times same fruit, except if you close the box.
When you validate your form, just remove trailing "/xx" to get the correct id.
I hope it's that you want.
Denis

Firebase: How to match opponents in a game?

I'm implementing a social chess game. Every user can create a new game, and they'll wait until the system will find an opponent for them.
When user creates a game, they specify constraints: color they'd like to play, and opponent's minimal chess rating.
Opponents can either match or not match. For example, the following two opponents will match:
// User 1 with rating 1700 // User 2 with rating 1800
// creates this game // creates this game
game: { game: {
color: 'white', minRating: 1650
minRating: 1600 }
} // User did not specify a preferred color,
// meaning they do not care which color to play
So, if User 1 is the first user in the system, and created their game, they'll wait. Once User 2 creates their game, they should be matched immediately with User 1.
On the other side, the following two opponents won't match, because they both want to play white. In this case, both should wait until someone else creates a game with color: 'black' (or color not specified), and minRating that would match the requirements.
// User 1 with rating 1700 // User 2 with rating 1800
// creates this game // creates this game
game: { game: {
color: 'white', color: 'white'
minRating: 1600 minRating: 1650
} }
My concerns related to scenarios where thousands of users creates new games at the same time. How do I make sure that I match opponents without creating deadlocks? i.e. how do I prevent scenarios when User 1, User 2, and User 3 are trying to find an opponent at the same time, and their matching algorithms return User 99. How do I recover from this scenario, assigning User 99 to only one of them?
How would you use the power of Firebase to implement such a matching system?
The obvious choice for a starting point would be the color, since this is an exclusive requirement. The others seem more like weighted results, so those could simply increment or decrement the weight.
Utilize priorities for min/max ranges, and keep each in a separate "index". Then grab the matches for each and create a union. Consider this structure:
/matches
/matches/colors/white/$user_id
/matches/ranking/$user_id (with a priority equal to ranking)
/matches/timezones/$user_id (with a priority of the GMT relationship)
Now to query, I would simply grab the matches in each category and rank them by the number of matches. I can start with colors, because this presumably isn't an optional or relative rating:
var rootRef = new Firebase('.../matches');
var VALUE = {
"rank": 10, "timezone": 5, "color": 0
}
var matches = []; // a list of ids sorted by weight
var weights = {}; // an index of ids to weights
var colorRef = rootRef.child('colors/black');
colorRef.on('child_added', addMatch);
colorRef.child('colors/black').on('child_removed', removeMatch);
var rankRef = rootRef.child('ranking').startAt(minRank).endAt(maxRank);
rankRef.on('child_added', addWeight.bind(null, VALUE['rank']));
rankRef.on('child_removed', removeWeight.bind(null, VALUE['rank']));
var tzRef = ref.child('timezone').startAt(minTz).endAt(maxTz);
tzRef.on('child_added', addWeight.bind(null, VALUE['timezone']));
tzRef.on('child_removed', removeWeight.bind(null, VALUE['timezone']));
function addMatch(snap) {
var key = snap.name();
weights[key] = VALUE['color'];
matches.push(key);
matches.sort(sortcmp);
}
function removeMatch(snap) {
var key = snap.name();
var i = matches.indexOf(key);
if( i > -1 ) { matches.splice(i, 1); }
delete weights[key];
}
function addWeight(amt, snap) {
var key = snap.name();
if( weights.hasOwnProperty(key) ) {
weights[key] += amt;
matches.sort(sortcmp);
}
}
function removeWeight(amt, snap) {
var key = snap.name();
if( weights.hasOwnProperty(key) ) {
weights[key] -= amt;
matches.sort(sortcmp);
}
}
function sortcmp(a,b) {
var x = weights[a];
var y = weights[b];
if( x === y ) { return 0; }
return x > y? 1 : -1;
}
Okay, now I've given what everyone asks for in this use case--how to create a rudimentary where clause. However, the appropriate answer here is that searches should be performed by a search engine. This is no simple where condition. This is a weighted search for the best matches, because fields like color are not optional or simply the best match, while others--ranking maybe--are the closest match in either direction, while some simply affect the quality of the match.
Check out flashlight for a simple ElasticSearch integration. With this approach, you should be able to take advantage of ES's great weighting tools, dynamic sorting, and everything else you need to conduct a proper matching algorithm.
Regarding deadlocks. I would not put too much focus here until you have hundreds of transactions per second (i.e. hundreds of thousands of users competing for matches). Split out the path where we will write to accept a join and do a transaction to ensure only one person succeeds in obtaining it. Keep it separate from the read data so that the lock on that path won't slow down processing. Keep the transaction to a minimal size (a single field if possible).
It is a challenging task in NoSQL environment especially if you want to match multiple fields
in your case, I would setup a simple index by color and within the color I would store the reference to the game with priority set to minRating.
That way you can query the games by the prefered colour with the priority of minRating.
indexes: {
color:{
white:{
REF_WITH_PRIORITY_TO_RATING: true
},
black:{
REF_WITH_PRIORITY_TO_RATING: true
}
}
}
if you want to get info whenever the match opens the game:
ref = new(Firebase)('URL');
query =ref.child('color_index/white/').startAt(minPriority);
query.on('child_added',function(snapshot){
//here is your new game matching the filter
});
This, however, it would get more complex if you introduce multiple fields for filtering the games for example dropRate, timeZone, 'gamesPlayed' etc... In this case, you can nest the indexes deeper:
indexes: {
GMT0: {
color:{
white:{
REF_WITH_PRIORITY_TO_RATING: true
},
black:{
REF_WITH_PRIORITY_TO_RATING: true
},
}
GMT1: {
// etc
}
}

Resources