Is there a way to cancel all builds from queue? - teamcity

I can't find a UI way in TeamCity to clear all queued builds in bulk.
One by one is possible, but sometimes triggers/dependencies hit the fan and you end-up with tens of unwanted builds.
REST API is another way, also requires individually cancelling each build.
I expected to have "Remove All" or "Drop Queue" button

There is now an official way to do this :
Go to queue
Pause build queue
Select -> All X builds
Click on "Remove from queue..."

Self answer :)
go to queue page
stop queue
copy/paste safe js code below to browser dev console (tested on chrome)
const count = $x("//button[contains(#class,'removeFromQueueIcon')]").length;
const xxx = $x;
for( i=0 ; i<count ; i++ ) {
setTimeout(() => {
const r = xxx("//button[contains(#class,'removeFromQueueIcon')]")[0];
r.onclick();
setTimeout(() => {
const rem = xxx("//input[#value='Remove']")[0].click();
}, 1000);
}, i * 2000);
}
Enter and watch your problem go away :)
resume queue

Updated version:
const count = $x("//button[contains(#title,'Cancel build...')]").length;
const xxx = $x;
for( i=0 ; i<count ; i++ ) {
setTimeout(() => {
const r = xxx("//button[contains(#title,'Cancel build...')]")[0];
r.click();
setTimeout(() => {
const rem = xxx("//input[#id='submitRemoveQueuedBuild']")[0];
console.log('Button', rem);
rem.click();
}, 1000);
}, i * 2000);
}

Related

Bookmarklet - Multiple lines of input

I am trying to create a simple bookmarklet that creates a little textbox that can be created, written in, and then closed.
Thank you ahead of time.
See a live example here
(() => {
const d = document.createElement('div')
d.style = "position:fixed;top:0px;left:0px;padding:5px;background-color:red;"
const e = document.createElement('textarea')
const b = document.createElement('button')
b.innerText = "Close"
b.onclick = () => {
document.body.removeChild(d)
}
d.appendChild(e)
d.appendChild(b)
document.body.appendChild(d)
})();

Is it possible to keep executing test if element wasn't found with Cypress

I have a case when I need to wait for element (advertising), if it's visible then needs to click it, but if element wasn't found after timeout then needs to keep executing a test.
How to handle the situation with Cypress ?
The way Cypress says to check for a conditional element is Element existence
cy.get('body').then(($body) => {
const modal = $body.find('modal')
if (modal.length) {
modal.click()
}
})
Most likely you put that at the top of the test, and it runs too soon (there's no retry timeoout).
You can add a wait say 30 seconds, but the test is delayed every time.
Better to call recursively
const clickModal = (selector, attempt = 0) => {
if (attempt === 100) return // whole 30 seconds is up
cy.get('body').then(($body) => {
const modal = $body.find('modal')
if (!modal.length) {
cy.wait(300) // wait in small chunks
clickModal(selector, ++attempt)
}
})
return // done, exit
}
cy.get('body')
.then($body => clickModal('modal'))
Intercept the advert
Best is if you can find the url for the advert in network tab, use cy.intercept() to catch it and stub it out to stop the modal displaying.
I tried the above solution, but seems that in some cases parameter $body could not contain necessary element, cause it was not loaded when we invoked cy.get('body'). So, I found another solution, using jQuery via Cypress, here is it:
let counter = 0;
const timeOut: number = Cypress.config('defaultCommandTimeout');
const sleep = (milliseconds) => {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
};
while (true) {
if (Cypress.$(element).length > 0 && Cypress.$(element).is(':visible')) {
Cypress.$(element).click();
break;
} else {
sleep(500);
counter = counter + 500;
if (counter >= timeOut) {
cy.log(elementName+ ' was not found after timeout');
break;
}
}
}

Why mapTo changes only one time?

I'm making a stopwatch and when I wanna reset the clock for the second time, it is not changed.
On click at the first time, it sets h: 0, m: 0, s: 0. But when click again, it doesn't set h: 0, m: 0, s: 0 and stopwatch goes ahead.
const events$ = merge(
fromEvent(startBtn, 'click').pipe(mapTo({count: true})),
click$.pipe(mapTo({count: false})),
fromEvent(resetBtn, 'click').pipe(mapTo({time: {h: 0, m: 0, s: 0}})) // there is reseting
)
const stopWatch$ = events$.pipe(
startWith({count: false, time: {h: 0, m: 0, s: 0}}),
scan((state, curr) => (Object.assign(Object.assign({}, state), curr)), {}),
switchMap((state) => state.count
? interval(1000)
.pipe(
tap(_ => {
if (state.time.s > 59) {
state.time.s = 0
state.time.m++
}
if (state.time.s > 59) {
state.time.s = 0
state.time.h++
}
const {h, m, s} = state.time
secondsField.innerHTML = s + 1
minuitesField.innerHTML = m
hours.innerHTML = h
state.time.s++
}),
)
: EMPTY)
stopWatch$.subscribe()
The Problem
You're using mutable state and updating it as a side-effect of events being emitted by observable (That's what tap does).
In general, it's a bad idea to create side effects that indirectly alter the stream they're created in. So creating a log or displaying a value are unlikely to cause issues, but mutating an object and then injecting it back the stream is difficult to maintain/scale.
A sort-of-fix:
Create a new object.
// fromEvent(resetBtn, 'click').pipe(mapTo({time: {h: 0, m: 0, s: 0}}))
fromEvent(resetBtn, 'click').pipe(map(_ => ({time: {h: 0, m: 0, s: 0}})))
That should work, though it's admittedly a band-aid solution.
A Pre-fab Solution
Here's a stopwatch I made a while ago. Here's how it works. You create a stopwatch by giving it a control$ observable (I use a Subject called controller in this example).
When control$ emits "START", the stopWatch starts, when it emits "STOP", the stopwatch stops, and when it emits "RESET" the stopwatch sets the counter back to zero. When control$ errors, completes, or emits "END", the stopwatch errors or completes.
function createStopwatch(control$: Observable<string>, interval = 1000): Observable<number>{
return defer(() => {
let toggle: boolean = false;
let count: number = 0;
const ticker = () => {
return timer(0, interval).pipe(
map(x => count++)
)
}
return control$.pipe(
catchError(_ => of("END")),
s => concat(s, of("END")),
filter(control =>
control === "START" ||
control === "STOP" ||
control === "RESET" ||
control === "END"
),
switchMap(control => {
if(control === "START" && !toggle){
toggle = true;
return ticker();
}else if(control === "STOP" && toggle){
toggle = false;
return EMPTY;
}else if(control === "RESET"){
count = 0;
if(toggle){
return ticker();
}
}
return EMPTY;
})
);
});
}
// Adapted to your code :)
const controller = new Subject<string>();
const seconds$ = createStopwatch(controller);
fromEvent(startBtn, 'click').pipe(mapTo("START")).subscribe(controller);
fromEvent(resetBtn, 'click').pipe(mapTo("RESET")).subscribe(controller);
seconds$.subscribe(seconds => {
secondsField.innerHTML = seconds % 60;
minuitesField.innerHTML = Math.floor(seconds / 60) % 60;
hours.innerHTML = Math.floor(seconds / 3600);
});
As a bonus, you can probably see how you might make a button that Stops this timer without resetting it.
Without a Subject
Here's an even more idiomatically reactive way to do this. It makes a control$ for the stopwatch by merging DOM events directly (No Subject in the middle).
This does take away your ability to write something like controller.next("RESET"); to inject your own value into the stream at will. OR controller.complete(); when your app is done with the stopwatch (Though you might do that automatically through some other event instead).
...
// Adapted to your code :)
createStopwatch(merge(
fromEvent(startBtn, 'click').pipe(mapTo("START")),
fromEvent(resetBtn, 'click').pipe(mapTo("RESET"))
)).subscribe(seconds => {
secondsField.innerHTML = seconds % 60;
minuitesField.innerHTML = Math.floor(seconds / 60) % 60;
hours.innerHTML = Math.floor(seconds / 3600);
});

How to make this RxJs code more elegant? The code recording mouse hover time on a specific area

I want to record mouse hover time on a specific area such as a 'div' container box area , by using RxJs.
const element = document.querySelector('#some-div');
let totalHoverTime = 0;
const INTERVAL = 100;
const mousePos = {
x: -1,
y: -1
};
const accumulate = () => {
const x = mousePos.x;
const y = mousePos.y;
const divx1 = element.offsetLeft;
const divy1 = element.offsetTop;
const divx2 = element.offsetLeft + element.offsetWidth;
const divy2 = element.offsetTop + element.offsetHeight;
// out of area
if (x < divx1 || x > divx2 || y < divy1 || y > divy2) {
console.log('out')
} else {
// in area
console.log('in')
totalHoverTime += INTERVAL;
}
};
const accumulateTimer = rx.interval(INTERVAL);
accumulateTimer.subscribe(() => {
accumulate();
});
rx
.fromEvent(element, 'mousemove')
.pipe(rxOp.debounce(() => rx.timer(INTERVAL)))
.subscribe((e: MouseEvent) => {
mousePos.x = e.clientX;
mousePos.y = e.clientY;
});
I'm not very familiar with rxjs, I think this code may can be more elegant to implement.
Optimized code
Thank you very much for your answers. #hugo #der_berni
const element = document.body;
const INTERVAL = 2000;
const withinBounds = ({ x, y }: { x: number; y: number }) => {
const divx1 = element.offsetLeft;
const divy1 = element.offsetTop;
const divx2 = element.offsetLeft + element.offsetWidth;
const divy2 = element.offsetTop + element.offsetHeight;
const outOfBounds = x < divx1 || x > divx2 || y < divy1 || y > divy2;
if (outOfBounds) {
// out of area
console.log('out');
} else {
// in area
console.log('in');
}
return !outOfBounds;
};
const mousePositions = rx
.fromEvent(document, 'mousemove')
.pipe(rxOp.throttleTime(200))
.pipe(rxOp.map((e: MouseEvent) => ({ x: e.pageX, y: e.pageY })));
const mousePositionIsValid = mousePositions
.pipe(rxOp.map(withinBounds))
.pipe(rxOp.distinctUntilChanged());
const hoverTimer = mousePositionIsValid.pipe(rxOp.switchMap(valid => (valid ? accumulateTimer : rx.empty())));
const totalHoverTime = hoverTimer.pipe(rxOp.scan((x, y) => x + INTERVAL, -500)); // The first time mouse moves in, this will be triggered once, so it is set to -500, and the first time it comes in is 0ms.
totalHoverTime.subscribe(hoverTime => {
console.log('totalHoverTime is:', hoverTime);
});
Finally, I found that I still need to use mousemove event combined timer to implement this function. When the mouse is already hovering above the div on page load, the mouseenter event will never triggerd in my page seemly. Maybe only in jsfiddle can be no problem.
I' also only started using RxJS recently, so there might be a better way to solve your problem.
However, a huge improvement over your approach would already be to chain the observables and use the switchMap operator. One thing to keep in mind when working with rxjs is, that you want to avoid manual subscriptions, because you will have to keep track of them and unsubscribe yourself to prevent leaks. When using operators like switchMap, these keep track of the subscriptions to inner observables, and also automatically unsubscribe.
Following code snippet should solve your problem:
Rx.Observable.fromEvent(element, 'mouseenter') // returns Observable<Event>
.map(() => Date.now()) // transform to Observable<number>
.switchMap((startTime) => { // switches to new inner observable
return Rx.Observable.fromEvent(button, 'mouseleave')
// When the observable from mouseleave emmits, calculate the hover time
.map(() => Date.now() - startTime);
})
.subscribe((hoverTime) => {console.log(hoverTime)});
If you want to try it out, see this jsFiddle: https://jsfiddle.net/derberni/hLgw1yvj/3/
EDIT:
Even if your div is very large, and the mouse might never leave it and trigger the mouseleave event, this can be solved with rxjs. You just have to change when the observable emits, and for how long you let it emit before you complete it. The WHEN can be adapted, so that it emits in a set interval, and the UNTIL can be set with the rxjs function takeUntil. takeUntil receives an observable as an argument, and takes values from the source observable, until the 'argument' observable emits.
Check out this code and fiddle, which updates the hover time in 1s steps and when the mouseleave event triggers: https://jsfiddle.net/derberni/3cky0g4e/
let div = document.querySelector('.hover-target');
let text = document.querySelector('.hover-time');
Rx.Observable.fromEvent(div, 'mouseenter')
.map(() => Date.now())
.switchMap((startTime) => {
return Rx.Observable.merge(
Rx.Observable.interval(1000),
Rx.Observable.fromEvent(div, 'mouseleave')
)
.takeUntil(Rx.Observable.fromEvent(div, 'mouseleave'))
.map(() => Date.now() - startTime);
})
//.takeUntil(Rx.Observable.fromEvent(div, 'mouseleave'))
.subscribe((hoverTime) => {
text.innerHTML = "Hover time: " + hoverTime + "ms"
});
At least in the fiddle this works also when the mouse is already hovering above the div on page load, because then the mouseenter event is also triggered.
Point-free
The simplest thing: replace (x => f(x)) with simply f. It's equivalent and will read better in most cases. This:
accumulateTimer.subscribe(() => {
accumulate();
});
Becomes:
accumulateTimer.subscribe(accumulate);
Fat functions:
The accumulate function could be broken down into:
const accumulate = () => {
const x = mousePos.x;
const y = mousePos.y;
if (withinBounds(x, y)) {
totalHoverTime += INTERVAL;
}
};
const withinBounds = ({x, y}) => {
const divx1 = element.offsetLeft;
const divy1 = element.offsetTop;
const divx2 = element.offsetLeft + element.offsetWidth;
const divy2 = element.offsetTop + element.offsetHeight;
const outOfBounds = x < divx1 || x > divx2 || y < divy1 || y > divy2;
if (outOfBounds) {
// out of area
console.log('out')
} else {
// in area
console.log('in')
}
return !outOfBounds;
};
See how we separated withinBounds which is pretty big but performs a simple definite task, purely functionally (no side-effect, one input gives the same output) -- ignoring the debug calls that is. Now we don't have to think so hard about it and we can focus on accumulate.
Avoid side-effects & compose
The most glaring issue is the whole loop relying on a side effect on mousePos:
const mousePositions = rx
.fromEvent(element, 'mousemove')
.pipe(rxOp.debounce(() => rx.timer(INTERVAL)))
//.subscribe((e: MouseEvent) => {
// mousePos.x = e.clientX;
// mousePos.y = e.clientY;
//});
.map((e: MouseEvent) => ({ x: e.clientX, y: e.clientY )));
Don't subscribe and save the value, it breaks the idea of flow behind rxjs. Use the return value, Luke. More specifically, pipe further to refine it until you reach the desired data. Above, we have a stream that emits the mouse positions alone.
// Will emit true when the mouse enters and false when it leaves:
const mousePositionIsValid = mousePositions
.map(withinBounds)
.distinctUntilChanged();
// Fires every INTERVAL, only when mouse is within bounds:
const hoverTimer = mousePositionIsValid
.switchMap(valid => valid ? accumulateTimer : rx.empty())
(edited with switchMap as suggested by #der_berni)
You wrote a function named "accumulate". Whenever you say "accumulate", reduce (and the likes) should come to mind. Reduce emits a single aggregate value when the stream completes. Here we use scan to get a new updated value each time the underlying stream emits:
// For each element produced by hoverTimer, add INTERVAL
const totalHoverTime = hoverTimer.scan((x, y) => x + INTERVAL, 0);
Note that it doesn't add to global each time, but every value it emits is the previous one + INTERVAL. So you can subscribe to that to get your total hover time.

Magento Enterprise Tabs - How to select specific tab in link?

I am trying to link to a specific tab in Magento Enterprise. It seems that all of the answers I've found don't apply well to their method. I just need a link to the page to also pull up a specific tab. This is the code they use:
Enterprise.Tabs = Class.create();
Object.extend(Enterprise.Tabs.prototype, {
initialize: function (container) {
this.container = $(container);
this.container.addClassName('tab-list');
this.tabs = this.container.select('dt.tab');
this.activeTab = this.tabs.first();
this.tabs.first().addClassName('first');
this.tabs.last().addClassName('last');
this.onTabClick = this.handleTabClick.bindAsEventListener(this);
for (var i = 0, l = this.tabs.length; i < l; i ++) {
this.tabs[i].observe('click', this.onTabClick);
}
this.select();
},
handleTabClick: function (evt) {
this.activeTab = Event.findElement(evt, 'dt');
this.select();
},
select: function () {
for (var i = 0, l = this.tabs.length; i < l; i ++) {
if (this.tabs[i] == this.activeTab) {
this.tabs[i].addClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 2;
/*this.tabs[i].next('dd').show();*/
new Effect.Appear (this.tabs[i].next('dd'), { duration:0.5 });
this.tabs[i].parentNode.style.height=this.tabs[i].next('dd').getHeight() + 15 + 'px';
} else {
this.tabs[i].removeClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
this.tabs[i].next('dd').hide();
}
}
}
});
Anyone have an idea?
I would consider modifying how the class starts up.
initialize: function (container) {
this.container = $(container);
this.container.addClassName('tab-list');
this.tabs = this.container.select('dt.tab');
// change starts here //
var hashTab = $(window.location.hash.slice(1));
this.activeTab = ( this.tabs.include(hashTab) ? hashTab : this.tabs.first());
// change ends here //
this.tabs.first().addClassName('first');
this.tabs.last().addClassName('last');
this.onTabClick = this.handleTabClick.bindAsEventListener(this);
for (var i = 0, l = this.tabs.length; i < l; i ++) {
this.tabs[i].observe('click', this.onTabClick);
}
this.select();
}
Here, I have only changed how the initial tab is chosen. It checks for an URL fragment which is commonly known as a hash, if that identifies one of the tabs it is preselected. As a bonus the browser will also scroll to that element if possible.
Then you only need to append the tab's ID to the URL. For example you might generate the URL by;
$productUrl = Mage::getUrl('catalog/product/view', array(
'id' => $productId,
'_fragment' => 'tab_id',
));
If you've recently migrated from an earlier Magento release, e.g. from Enterprise 1.11 to Enterprise 1.12, make sure the javascript in /template/catalog/product/view.phtml
right after the foreach that generates the tabs gets updated to the 1.12 version:
<script type="text/javascript">
var collateralTabs = new Enterprise.Tabs('collateral-tabs');
Event.observe(window, 'load', function() {
collateralTabs.select();
});
</script>
surfimp's VERY helpful suggestions did not produce the desired opening of the closed tab otherwise. Once this updated javascript was added, clicking on a link to read Review or Add Your Review on the product page, jumped to the Reviews tab, even if the tab had been hidden.
Similar to Zifius' answer, you can modify the initialize function to just take another argument which will be the active tab.
Event.observe(window, 'load', function() {
new Enterprise.Tabs('collateral-tabs', $('tab_review'));
});
and then in the scripts.js (or wherever this class may exist for you)
initialize: function (container, el) {
...
this.activeTab = el;
...
}
Use whatever logic in the template you like to set 'el' to the desired value.
The reason I did it this way is because when I used Zifius' method, the desired tab would be the active tab, but the default tab's content was still displayed.
Had the same task yesterday and as I don't know about prototype much I solved it by adding another method:
selectTab: function (element) {
this.activeTab = element;
this.select();
},
Usage:
var Tabs = new Enterprise.Tabs('collateral-tabs');
Tabs.selectTab($('tabId'));
Would like to know if it's a correct approach

Resources