language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function update_actual_normal_speed(line) {
var journey = line.properties.journey;
var link = line.properties.link;
var time = speed_display === 'actual' ? journey.travelTime : journey.normalTravelTime;
var speed = (link.length / time) * TO_MPH;
var choice;
if (time === null) {
choice = BROKEN_COLOUR;
}
else if (speed < 5) {
choice = VERY_SLOW_COLOUR;
}
else if (speed < 10) {
choice = SLOW_COLOUR;
}
else if (speed < 20) {
choice = MEDIUM_COLOUR;
}
else {
choice = FAST_COLOUR;
}
line.setStyle({color: choice});
} | function update_actual_normal_speed(line) {
var journey = line.properties.journey;
var link = line.properties.link;
var time = speed_display === 'actual' ? journey.travelTime : journey.normalTravelTime;
var speed = (link.length / time) * TO_MPH;
var choice;
if (time === null) {
choice = BROKEN_COLOUR;
}
else if (speed < 5) {
choice = VERY_SLOW_COLOUR;
}
else if (speed < 10) {
choice = SLOW_COLOUR;
}
else if (speed < 20) {
choice = MEDIUM_COLOUR;
}
else {
choice = FAST_COLOUR;
}
line.setStyle({color: choice});
} |
JavaScript | function merge_preload(current_pages, preload_pages) {
// append each preload page if it is not already in current pages
for (var i=0; i<preload_pages.length; i++) {
append_page(current_pages, preload_pages[i]);
}
} | function merge_preload(current_pages, preload_pages) {
// append each preload page if it is not already in current pages
for (var i=0; i<preload_pages.length; i++) {
append_page(current_pages, preload_pages[i]);
}
} |
JavaScript | function append_page(current_pages, page) {
for (var i=0; i<current_pages.length; i++) {
if (page_match(current_pages[i], page)) {
// page is already in list of current pages, so do nothing and return
return;
}
}
current_pages.push(page);
} | function append_page(current_pages, page) {
for (var i=0; i<current_pages.length; i++) {
if (page_match(current_pages[i], page)) {
// page is already in list of current pages, so do nothing and return
return;
}
}
current_pages.push(page);
} |
JavaScript | function handle_page_list_click(evt) {
var list_item = evt.target.closest('ons-list-item');
if (!list_item) {
return;
}
var page_number = getElementIndex(list_item);
var ons_page = list_item.closest('ons-page#list');
var navigator = document.querySelector('#myNavigator');
// A click when editing
if (ons_page.classList.contains('edit-mode')) {
delete_page(page_number, ons_page);
}
// Otherwise
else {
navigator.pushPage('page-display.html', {data: { page_number: page_number }});
}
} | function handle_page_list_click(evt) {
var list_item = evt.target.closest('ons-list-item');
if (!list_item) {
return;
}
var page_number = getElementIndex(list_item);
var ons_page = list_item.closest('ons-page#list');
var navigator = document.querySelector('#myNavigator');
// A click when editing
if (ons_page.classList.contains('edit-mode')) {
delete_page(page_number, ons_page);
}
// Otherwise
else {
navigator.pushPage('page-display.html', {data: { page_number: page_number }});
}
} |
JavaScript | function display_map(ons_page) {
// Get the config for the stop_timetable currently being displayed
var timetable_config = PAGES[ons_page.data.page_number];
// Synthesise a stop_bus_map widget config
var map_config = {
'title': timetable_config.data.title,
'map': {
'zoom': 15,
'lat': timetable_config.data.stop.latitude,
'lng': timetable_config.data.stop.longitude,
},
'breadcrumbs': true,
'stops': [
timetable_config.data.stop
]
};
var overlay_container = ons_page.querySelector('#overlay-container');
clear_element(overlay_container);
var container_el = document.createElement('div');
container_el.id = 'widget-stop_bus_map';
container_el.classList.add('widget', 'stop_bus_map', 'full-screen');
overlay_container.appendChild(container_el);
map_widget = new StopBusMap('stop_bus_map');
map_widget.display(
{
container_id: 'widget-stop_bus_map',
static_url: STATIC_URL + 'stop_bus_map/',
display_id: instance_key,
layout_id: '',
rt_token: RT_TOKEN,
layout_name: '',
display_name: 'Pocket SmartPanel',
layout_owner: '',
display_owner: '',
settings: WIDGET_CONFIG
},
map_config
);
} | function display_map(ons_page) {
// Get the config for the stop_timetable currently being displayed
var timetable_config = PAGES[ons_page.data.page_number];
// Synthesise a stop_bus_map widget config
var map_config = {
'title': timetable_config.data.title,
'map': {
'zoom': 15,
'lat': timetable_config.data.stop.latitude,
'lng': timetable_config.data.stop.longitude,
},
'breadcrumbs': true,
'stops': [
timetable_config.data.stop
]
};
var overlay_container = ons_page.querySelector('#overlay-container');
clear_element(overlay_container);
var container_el = document.createElement('div');
container_el.id = 'widget-stop_bus_map';
container_el.classList.add('widget', 'stop_bus_map', 'full-screen');
overlay_container.appendChild(container_el);
map_widget = new StopBusMap('stop_bus_map');
map_widget.display(
{
container_id: 'widget-stop_bus_map',
static_url: STATIC_URL + 'stop_bus_map/',
display_id: instance_key,
layout_id: '',
rt_token: RT_TOKEN,
layout_name: '',
display_name: 'Pocket SmartPanel',
layout_owner: '',
display_owner: '',
settings: WIDGET_CONFIG
},
map_config
);
} |
JavaScript | function populate_page_list(ons_page) {
var list = ons_page.querySelector('.page-list');
// Remove existing entries
clear_element(list);
// Populate
for (var page_number = 0; page_number < PAGES.length; page_number++) {
var page_config = PAGES[page_number];
var item = document.createElement('ons-list-item');
item.setAttribute('tappable', '');
ons.modifier.add(item, 'longdivider');
// Add the chevron if not in edit mode
if (!ons_page.classList.contains('edit-mode')) {
ons.modifier.add(item, 'chevron');
}
item.innerHTML =
'<div class="left">' +
' <img class="list-item__icon list-icon" src=" ' + STATIC_URL + WIDGET_ICON[page_config.widget] +'"/>' +
'</div>' +
'<div class="center">' +
' ' + page_config.title +
'</div>' +
'<div class="right">' +
' <span class="show-edit delete">' +
' <ons-icon icon="ion-ios-trash, material:ion-android-delete" size="28px, material:lg">' +
' </ons-icon>' +
' </span>' +
'</div>';
list.appendChild(item);
}
} | function populate_page_list(ons_page) {
var list = ons_page.querySelector('.page-list');
// Remove existing entries
clear_element(list);
// Populate
for (var page_number = 0; page_number < PAGES.length; page_number++) {
var page_config = PAGES[page_number];
var item = document.createElement('ons-list-item');
item.setAttribute('tappable', '');
ons.modifier.add(item, 'longdivider');
// Add the chevron if not in edit mode
if (!ons_page.classList.contains('edit-mode')) {
ons.modifier.add(item, 'chevron');
}
item.innerHTML =
'<div class="left">' +
' <img class="list-item__icon list-icon" src=" ' + STATIC_URL + WIDGET_ICON[page_config.widget] +'"/>' +
'</div>' +
'<div class="center">' +
' ' + page_config.title +
'</div>' +
'<div class="right">' +
' <span class="show-edit delete">' +
' <ons-icon icon="ion-ios-trash, material:ion-android-delete" size="28px, material:lg">' +
' </ons-icon>' +
' </span>' +
'</div>';
list.appendChild(item);
}
} |
JavaScript | function choose_new_page() {
ons.openActionSheet({
title: 'Choose a page type',
cancelable: true,
buttons: [
'Bus timetable',
'Train timetable',
'Weather forecast',
{
label: 'Cancel',
icon: 'md-close'
}
]
}).then(function (index) {
var navigator = document.querySelector('#myNavigator');
switch (index) {
case 0:
navigator.pushPage('config.html', { data: { new_widget: 'stop_timetable' } });
break;
case 1:
navigator.pushPage('config.html', { data: { new_widget: 'station_board' } });
break;
case 2:
navigator.pushPage('config.html', { data: { new_widget: 'weather' } });
break;
}
});
} | function choose_new_page() {
ons.openActionSheet({
title: 'Choose a page type',
cancelable: true,
buttons: [
'Bus timetable',
'Train timetable',
'Weather forecast',
{
label: 'Cancel',
icon: 'md-close'
}
]
}).then(function (index) {
var navigator = document.querySelector('#myNavigator');
switch (index) {
case 0:
navigator.pushPage('config.html', { data: { new_widget: 'stop_timetable' } });
break;
case 1:
navigator.pushPage('config.html', { data: { new_widget: 'station_board' } });
break;
case 2:
navigator.pushPage('config.html', { data: { new_widget: 'weather' } });
break;
}
});
} |
JavaScript | function station_board_config(config_el, config, current_params) {
var result = list_chooser(config_el, current_params.data.station, STATION_OPTIONS);
return function () {
return {
widget: current_params.widget,
title: result().text,
data: {
station: result().value,
platforms: 'y'
}
};
};
} | function station_board_config(config_el, config, current_params) {
var result = list_chooser(config_el, current_params.data.station, STATION_OPTIONS);
return function () {
return {
widget: current_params.widget,
title: result().text,
data: {
station: result().value,
platforms: 'y'
}
};
};
} |
JavaScript | function stop_timetable_config(config_el, config, current_params, stops_callback) {
var chooser_options = {
multi_select: false,
popups: true,
location: true,
stops_callback: stops_callback,
api_endpoint: config.settings.SMARTPANEL_API_ENDPOINT,
api_token: config.settings.SMARTPANEL_API_TOKEN
};
var chooser = BusStopChooser.create(chooser_options);
if (current_params.data.stop) {
chooser.render(config_el, { stops: [current_params.data.stop] });
}
else {
chooser.render(config_el);
}
return function () {
var stop = chooser.getData().stops[0];
var title = formatted_stop_name(stop.indicator, stop.common_name);
return {
widget: current_params.widget,
title: title,
data: {
stop: stop,
title: title,
layout: 'multiline',
destinations: DESTINATIONS,
}
};
};
} | function stop_timetable_config(config_el, config, current_params, stops_callback) {
var chooser_options = {
multi_select: false,
popups: true,
location: true,
stops_callback: stops_callback,
api_endpoint: config.settings.SMARTPANEL_API_ENDPOINT,
api_token: config.settings.SMARTPANEL_API_TOKEN
};
var chooser = BusStopChooser.create(chooser_options);
if (current_params.data.stop) {
chooser.render(config_el, { stops: [current_params.data.stop] });
}
else {
chooser.render(config_el);
}
return function () {
var stop = chooser.getData().stops[0];
var title = formatted_stop_name(stop.indicator, stop.common_name);
return {
widget: current_params.widget,
title: title,
data: {
stop: stop,
title: title,
layout: 'multiline',
destinations: DESTINATIONS,
}
};
};
} |
JavaScript | function clear_element(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
} | function clear_element(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
} |
JavaScript | function random_chars(chars, count) {
var result = '';
for (var i = 0; i < count; ++i) {
var rnum = Math.floor(Math.random() * chars.length);
result += chars.substring(rnum, rnum+1);
}
return result;
} | function random_chars(chars, count) {
var result = '';
for (var i = 0; i < count; ++i) {
var rnum = Math.floor(Math.random() * chars.length);
result += chars.substring(rnum, rnum+1);
}
return result;
} |
JavaScript | function config_leaflet_map(parent_el, param_options, param_current)
{
'use strict';
console.log('Called config_leflet_map');
var OSM_TILES = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var OSM_MAX_ZOOM = 19;
var OSM_ATTRIBUTION = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> ' +
'contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a></a>';
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
var lat = param_options.lat || 52.204;
var lng = param_options.lng || 0.124;
var zoom = param_options.zoom || 15;
var row = document.createElement('tr');
// create td to hold 'name' prompt for field
var name = document.createElement('td');
name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
name.appendChild(label);
row.appendChild(name);
var value = document.createElement('td');
value.className = 'widget_config_property_value';
value.style.height = height;
value.style.width = width;
row.appendChild(value);
parent_el.appendChild(row);
var osm = new L.TileLayer(OSM_TILES,
{ attribution: OSM_ATTRIBUTION,
maxZoom: OSM_MAX_ZOOM
}
);
var map = new L.Map(value).addLayer(osm);
if (param_current && param_current.map ) {
map.setView([param_current.map.lat, param_current.map.lng],
param_current.map.zoom);
}
else {
map.setView([lat, lng], zoom);
}
return {
value: function() {
return {
map: {
lng: map.getCenter().lng,
lat: map.getCenter().lat,
zoom: map.getZoom(),
}
};
},
valid: function () { return true; }
};
} // end config_leaflet_map | function config_leaflet_map(parent_el, param_options, param_current)
{
'use strict';
console.log('Called config_leflet_map');
var OSM_TILES = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var OSM_MAX_ZOOM = 19;
var OSM_ATTRIBUTION = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> ' +
'contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a></a>';
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
var lat = param_options.lat || 52.204;
var lng = param_options.lng || 0.124;
var zoom = param_options.zoom || 15;
var row = document.createElement('tr');
// create td to hold 'name' prompt for field
var name = document.createElement('td');
name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
name.appendChild(label);
row.appendChild(name);
var value = document.createElement('td');
value.className = 'widget_config_property_value';
value.style.height = height;
value.style.width = width;
row.appendChild(value);
parent_el.appendChild(row);
var osm = new L.TileLayer(OSM_TILES,
{ attribution: OSM_ATTRIBUTION,
maxZoom: OSM_MAX_ZOOM
}
);
var map = new L.Map(value).addLayer(osm);
if (param_current && param_current.map ) {
map.setView([param_current.map.lat, param_current.map.lng],
param_current.map.zoom);
}
else {
map.setView([lat, lng], zoom);
}
return {
value: function() {
return {
map: {
lng: map.getCenter().lng,
lat: map.getCenter().lat,
zoom: map.getZoom(),
}
};
},
valid: function () { return true; }
};
} // end config_leaflet_map |
JavaScript | function config_google_map_inline(parent_el, param_options, current_map)
{
'use strict';
console.log('Called config_google_map_inline',param_options, current_map);
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
var row = document.createElement('tr');
parent_el.appendChild(row);
// create td to hold 'name' prompt for field
var td_name = document.createElement('td');
td_name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
td_name.appendChild(label);
row.appendChild(td_name);
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
//td_value.style.height = height;
//td_value.style.width = width;
row.appendChild(td_value);
var map_div = document.createElement('div');
map_div.setAttribute('style', 'height: 550px; width: 550px');
td_value.appendChild(map_div);
var map_result = choose_google_map(map_div, param_options, current_map);
return map_result;
} | function config_google_map_inline(parent_el, param_options, current_map)
{
'use strict';
console.log('Called config_google_map_inline',param_options, current_map);
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
var row = document.createElement('tr');
parent_el.appendChild(row);
// create td to hold 'name' prompt for field
var td_name = document.createElement('td');
td_name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
td_name.appendChild(label);
row.appendChild(td_name);
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
//td_value.style.height = height;
//td_value.style.width = width;
row.appendChild(td_value);
var map_div = document.createElement('div');
map_div.setAttribute('style', 'height: 550px; width: 550px');
td_value.appendChild(map_div);
var map_result = choose_google_map(map_div, param_options, current_map);
return map_result;
} |
JavaScript | function config_area(parent_el, param_options, param_current)
{
//console.log('widget_config','Called config_area');
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
// Setup HTML
var row = document.createElement('tr');
parent_el.appendChild(row);
// create td to hold 'name' prompt for field
var name = document.createElement('td');
name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
name.appendChild(label);
row.appendChild(name);
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
td_value.style.height = height;
td_value.style.width = width;
row.appendChild(td_value);
var chooser_return = choose_area(td_value, param_options, param_current);
return chooser_return;
} // end config_area | function config_area(parent_el, param_options, param_current)
{
//console.log('widget_config','Called config_area');
var title = param_options.title;
var text = param_options.text;
var width = param_options.width || "500px";
var height = param_options.height || "500px";
// Setup HTML
var row = document.createElement('tr');
parent_el.appendChild(row);
// create td to hold 'name' prompt for field
var name = document.createElement('td');
name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = title;
label.appendChild(document.createTextNode(text));
name.appendChild(label);
row.appendChild(name);
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
td_value.style.height = height;
td_value.style.width = width;
row.appendChild(td_value);
var chooser_return = choose_area(td_value, param_options, param_current);
return chooser_return;
} // end config_area |
JavaScript | function max_index(vector) {
var max_value = vector[0];
var max_index = 0;
for (var i=0; i<vector.length; i++)
{
if (vector[i] > max_value)
{
max_index = i;
max_value = vector[i];
}
}
return max_index;
} | function max_index(vector) {
var max_value = vector[0];
var max_index = 0;
for (var i=0; i<vector.length; i++)
{
if (vector[i] > max_value)
{
max_index = i;
max_value = vector[i];
}
}
return max_index;
} |
JavaScript | function pattern_init()
{
if (!segment_progress_vector)
{
return 1.0;
}
return 0.0;
} | function pattern_init()
{
if (!segment_progress_vector)
{
return 1.0;
}
return 0.0;
} |
JavaScript | function update_segment_distance_vector(update_msg) {
// How many nearest segments to consider (zero out others)
var NEAREST_COUNT = 5;
var P = get_msg_point(update_msg);
console.log('update_segment_distance_vector '+JSON.stringify(P)+' vs route length '+journey_profile.length);
var segment_count = journey_profile.length + 1;
// Create segment_distance_vector array of { segment_index:, distance: }
var segment_distance_vector = [];
// Add distance to first stop as segment_distance_vector[0]
console.log('update_segment_distance_vector journey_profile[0]='+JSON.stringify(journey_profile[0]));
segment_distance_vector.push( { segment_index: 0, distance: get_distance(P, stops_cache[journey_profile[0].stop_id]) } );
// Now add the distances for route segments
for (var seg_index=1; seg_index<segment_count-1; seg_index++)
{
//debug use journey_profile
var prev_stop = stops_cache[journey_profile[seg_index-1].stop_id];
var next_stop = stops_cache[journey_profile[seg_index].stop_id];
var dist = get_distance_from_line(P, [prev_stop,next_stop]);
segment_distance_vector.push({ segment_index: seg_index, distance: dist });
}
// And for the 'finished' segment[segment_count-1] add distance from last stop
//debug use journey_profile
// Add distance to last stop (for 'finished' segment)
segment_distance_vector.push({ segment_index: segment_count - 1,
distance: get_distance(P, stops_cache[journey_profile[journey_profile.length-1].stop_id]) });
// Create sorted nearest_segments array of NEAREST_COUNT
// { segment_index:, distance: } elements
var nearest_segments = segment_distance_vector
.slice() // create copy
.sort((a,b) => Math.floor(a.distance - b.distance))
.slice(0,NEAREST_COUNT);
//console.log('nearest : '+nearest_segments.map( x => JSON.stringify(x) ));
// Create array[NEAREST_COUNT] containing segment probabilities 0..1, summing to 1
//var nearest_probs = linear_adjust(
// nearest_segments.map( x =>
// SEGMENT_DISTANCE_ADJUST /
// ( x.distance/2 + SEGMENT_DISTANCE_ADJUST)));
var nearest_probs = segment_distances_to_probs(P, journey_profile, nearest_segments);
// Initialize final result segment_vector with zeros
// and then insert the weights of the nearest segments
var segment_probability_vector = new Array(segment_count);
// Initialize entire vector to 0
for (var i=0; i<segment_count; i++)
{
segment_probability_vector[i] = 0;
}
// Insert in the calculations for nearest segments
for (var j=0; j<nearest_segments.length; j++)
{
segment_probability_vector[nearest_segments[j].segment_index] = nearest_probs[j];
}
return segment_probability_vector;
} | function update_segment_distance_vector(update_msg) {
// How many nearest segments to consider (zero out others)
var NEAREST_COUNT = 5;
var P = get_msg_point(update_msg);
console.log('update_segment_distance_vector '+JSON.stringify(P)+' vs route length '+journey_profile.length);
var segment_count = journey_profile.length + 1;
// Create segment_distance_vector array of { segment_index:, distance: }
var segment_distance_vector = [];
// Add distance to first stop as segment_distance_vector[0]
console.log('update_segment_distance_vector journey_profile[0]='+JSON.stringify(journey_profile[0]));
segment_distance_vector.push( { segment_index: 0, distance: get_distance(P, stops_cache[journey_profile[0].stop_id]) } );
// Now add the distances for route segments
for (var seg_index=1; seg_index<segment_count-1; seg_index++)
{
//debug use journey_profile
var prev_stop = stops_cache[journey_profile[seg_index-1].stop_id];
var next_stop = stops_cache[journey_profile[seg_index].stop_id];
var dist = get_distance_from_line(P, [prev_stop,next_stop]);
segment_distance_vector.push({ segment_index: seg_index, distance: dist });
}
// And for the 'finished' segment[segment_count-1] add distance from last stop
//debug use journey_profile
// Add distance to last stop (for 'finished' segment)
segment_distance_vector.push({ segment_index: segment_count - 1,
distance: get_distance(P, stops_cache[journey_profile[journey_profile.length-1].stop_id]) });
// Create sorted nearest_segments array of NEAREST_COUNT
// { segment_index:, distance: } elements
var nearest_segments = segment_distance_vector
.slice() // create copy
.sort((a,b) => Math.floor(a.distance - b.distance))
.slice(0,NEAREST_COUNT);
//console.log('nearest : '+nearest_segments.map( x => JSON.stringify(x) ));
// Create array[NEAREST_COUNT] containing segment probabilities 0..1, summing to 1
//var nearest_probs = linear_adjust(
// nearest_segments.map( x =>
// SEGMENT_DISTANCE_ADJUST /
// ( x.distance/2 + SEGMENT_DISTANCE_ADJUST)));
var nearest_probs = segment_distances_to_probs(P, journey_profile, nearest_segments);
// Initialize final result segment_vector with zeros
// and then insert the weights of the nearest segments
var segment_probability_vector = new Array(segment_count);
// Initialize entire vector to 0
for (var i=0; i<segment_count; i++)
{
segment_probability_vector[i] = 0;
}
// Insert in the calculations for nearest segments
for (var j=0; j<nearest_segments.length; j++)
{
segment_probability_vector[nearest_segments[j].segment_index] = nearest_probs[j];
}
return segment_probability_vector;
} |
JavaScript | function segment_distance_to_prob(P, journey_profile, segment_index, segment_distance) {
var prob;
if (segment_index < journey_profile.length)
{
// First of all we'll see if the bus is BEYOND the end stop of the segment
//
// bearing_out is the bearing of the next route segment
var bearing_out;
if (segment_index < journey_profile.length - 1)
{
bearing_out = journey_profile[segment_index+1].bearing_in;
}
else
{
bearing_out = journey_profile[segment_index].bearing_in;
}
// bisector_out is the outer angle bisector of this segment and the next
var bisector_out = journey_profile[segment_index].bisector;
// turn_out is the degrees turned from this segment to the next (clockwise)
var turn_out = journey_profile[segment_index].turn;
// end_bearing_to_bus is the bearing of the bus from the end bus-stop
var end_bearing_to_bus = Math.floor(get_bearing(journey_profile[segment_index], P));
var beyond = test_beyond_segment(end_bearing_to_bus, turn_out, bearing_out, bisector_out);
if (!beyond)
{
// We believe the bus is probably NOT beyond the segment
//
// We can now test if it is BEFORE the start stop of the segment
//
if (segment_index == 0) // can't be before the 'not yet started' segment 0
{
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
else
{
// route bearing on the run-up towards the segment start bus-stop
var bearing_before = journey_profile[segment_index-1].bearing_in;
// outer angle bisector bearing at the segment start bus-stop
var bisector_before = journey_profile[segment_index-1].bisector;
// turn at start bus-stop (degrees clockwise, i.e. turn left 10 degrees is 350)
var turn_before = journey_profile[segment_index-1].turn;
// bearing of bus from start bus-stop
var start_bearing_to_bus = Math.floor(get_bearing(journey_profile[segment_index-1],P));
var before = test_before_segment(start_bearing_to_bus,
turn_before,
bearing_before,
bisector_before);
if (!before)
{
// Here we are neither BEFORE or BEYOND, so use default probability
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
else
{
// We believe we are BEFORE the segment, so adjust the probability
prob = ( SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST)) * SEGMENT_BEFORE_ADJUST ;
}
}
}
else
{
// We believe the bus is probably BEYOND the segment
prob = ( SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST)
) * SEGMENT_BEYOND_ADJUST;
}
console.log( '{ segment '+segment_index+
',dist='+Math.floor(segment_distance)+
',out='+bearing_out+'°'+
',turn='+turn_out+'°'+
',bus='+end_bearing_to_bus+'°'+
',bi='+bisector_out+'°'+
','+(before ? 'BEFORE' : 'NOT BEFORE')+
','+(beyond ? 'BEYOND' : 'NOT BEYOND')+
',prob='+(Math.floor(100*prob)/100)+
'}'
);
}
else // on 'finished' segment
{
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
return prob;
} | function segment_distance_to_prob(P, journey_profile, segment_index, segment_distance) {
var prob;
if (segment_index < journey_profile.length)
{
// First of all we'll see if the bus is BEYOND the end stop of the segment
//
// bearing_out is the bearing of the next route segment
var bearing_out;
if (segment_index < journey_profile.length - 1)
{
bearing_out = journey_profile[segment_index+1].bearing_in;
}
else
{
bearing_out = journey_profile[segment_index].bearing_in;
}
// bisector_out is the outer angle bisector of this segment and the next
var bisector_out = journey_profile[segment_index].bisector;
// turn_out is the degrees turned from this segment to the next (clockwise)
var turn_out = journey_profile[segment_index].turn;
// end_bearing_to_bus is the bearing of the bus from the end bus-stop
var end_bearing_to_bus = Math.floor(get_bearing(journey_profile[segment_index], P));
var beyond = test_beyond_segment(end_bearing_to_bus, turn_out, bearing_out, bisector_out);
if (!beyond)
{
// We believe the bus is probably NOT beyond the segment
//
// We can now test if it is BEFORE the start stop of the segment
//
if (segment_index == 0) // can't be before the 'not yet started' segment 0
{
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
else
{
// route bearing on the run-up towards the segment start bus-stop
var bearing_before = journey_profile[segment_index-1].bearing_in;
// outer angle bisector bearing at the segment start bus-stop
var bisector_before = journey_profile[segment_index-1].bisector;
// turn at start bus-stop (degrees clockwise, i.e. turn left 10 degrees is 350)
var turn_before = journey_profile[segment_index-1].turn;
// bearing of bus from start bus-stop
var start_bearing_to_bus = Math.floor(get_bearing(journey_profile[segment_index-1],P));
var before = test_before_segment(start_bearing_to_bus,
turn_before,
bearing_before,
bisector_before);
if (!before)
{
// Here we are neither BEFORE or BEYOND, so use default probability
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
else
{
// We believe we are BEFORE the segment, so adjust the probability
prob = ( SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST)) * SEGMENT_BEFORE_ADJUST ;
}
}
}
else
{
// We believe the bus is probably BEYOND the segment
prob = ( SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST)
) * SEGMENT_BEYOND_ADJUST;
}
console.log( '{ segment '+segment_index+
',dist='+Math.floor(segment_distance)+
',out='+bearing_out+'°'+
',turn='+turn_out+'°'+
',bus='+end_bearing_to_bus+'°'+
',bi='+bisector_out+'°'+
','+(before ? 'BEFORE' : 'NOT BEFORE')+
','+(beyond ? 'BEYOND' : 'NOT BEYOND')+
',prob='+(Math.floor(100*prob)/100)+
'}'
);
}
else // on 'finished' segment
{
prob = SEGMENT_DISTANCE_ADJUST /
( segment_distance / 2 +
SEGMENT_DISTANCE_ADJUST);
}
return prob;
} |
JavaScript | function progress_speed(segment_index, journey_profile) {
var MIN_EST_SPEED = 6.1; // (m/s) Minimum speed to use for estimated bus speed
var MAX_EST_SPEED = 15; // (m/s)
// Estimate bus_speed
// Calculate the local averate route segment distance, used for the speed estimate
var avg_segment_distance;
if (segment_index == 0)
{
avg_segment_distance = 100;
}
else if (segment_index <= journey_profile.length - 3)
{
avg_segment_distance = (journey_profile[segment_index+2].distance -
journey_profile[segment_index-1].distance
) / 3;
}
else if (segment_index <= journey_profile.length - 2)
{
avg_segment_distance = (journey_profile[segment_index+1].distance -
journey_profile[segment_index-1].distance
) / 2;
}
else
{
avg_segment_distance = journey_profile[segment_index].distance -
journey_profile[segment_index-1].distance;
}
avg_segment_distance = Math.floor(avg_segment_distance);
// Estimate bus speed (m/s)
return Math.min(MAX_EST_SPEED,
Math.max(MIN_EST_SPEED,
(avg_segment_distance - 240)/294 + MIN_EST_SPEED));
} | function progress_speed(segment_index, journey_profile) {
var MIN_EST_SPEED = 6.1; // (m/s) Minimum speed to use for estimated bus speed
var MAX_EST_SPEED = 15; // (m/s)
// Estimate bus_speed
// Calculate the local averate route segment distance, used for the speed estimate
var avg_segment_distance;
if (segment_index == 0)
{
avg_segment_distance = 100;
}
else if (segment_index <= journey_profile.length - 3)
{
avg_segment_distance = (journey_profile[segment_index+2].distance -
journey_profile[segment_index-1].distance
) / 3;
}
else if (segment_index <= journey_profile.length - 2)
{
avg_segment_distance = (journey_profile[segment_index+1].distance -
journey_profile[segment_index-1].distance
) / 2;
}
else
{
avg_segment_distance = journey_profile[segment_index].distance -
journey_profile[segment_index-1].distance;
}
avg_segment_distance = Math.floor(avg_segment_distance);
// Estimate bus speed (m/s)
return Math.min(MAX_EST_SPEED,
Math.max(MIN_EST_SPEED,
(avg_segment_distance - 240)/294 + MIN_EST_SPEED));
} |
JavaScript | function softmax(vector) {
// Each element x -> exp(x) / sum(all exp(x))
var denominator = vector.map(x => Math.exp(x)).reduce( (sum, x) => sum + x );
return vector.map( x => Math.exp(x) / denominator);
} | function softmax(vector) {
// Each element x -> exp(x) / sum(all exp(x))
var denominator = vector.map(x => Math.exp(x)).reduce( (sum, x) => sum + x );
return vector.map( x => Math.exp(x) / denominator);
} |
JavaScript | function linear_adjust(vector)
{
// Each element x -> x/ sum(all x)
var denominator = vector.reduce( (sum, x) => sum + x );
return vector.map( x => x / denominator);
} | function linear_adjust(vector)
{
// Each element x -> x/ sum(all x)
var denominator = vector.reduce( (sum, x) => sum + x );
return vector.map( x => x / denominator);
} |
JavaScript | function vector_to_string(vector, zero_value, max_flag, correct_flag, correct_cells)
{
if (!zero_value)
{
zero_value = '-';
}
if (!max_flag)
{
max_flag = '[';
}
if (!correct_flag || !correct_cells)
{
correct_cells = [];
}
var str = '';
// find index of largest element
var max_value = 0;
var max_index = 0;
for (var i=0; i<vector.length; i++)
{
if (vector[i] > max_value)
{
max_value = vector[i];
max_index = i;
}
}
// Build print string
for (var i=0; i<vector.length; i++)
{
// Compute leading spacer
var spacer = ' ';
if (correct_cells.includes(i))
{
spacer = correct_flag;
}
else if (i == max_index)
{
spacer = max_flag;
}
// Print the spacer + value
//
str += spacer;
var n = vector[i];
// Print zero or value
if (n == 0)
{
str += ' '+zero_value+' ';
}
else if (n == 1)
{
str += '1.0';
}
else // Print value
{
var n3 = Math.floor(n*100)/100;
if (n3==0)
{
str += '.00';
}
else
{
str += (''+Math.floor(n*100)/100+'00').slice(1,4);
}
}
}
return str;
} | function vector_to_string(vector, zero_value, max_flag, correct_flag, correct_cells)
{
if (!zero_value)
{
zero_value = '-';
}
if (!max_flag)
{
max_flag = '[';
}
if (!correct_flag || !correct_cells)
{
correct_cells = [];
}
var str = '';
// find index of largest element
var max_value = 0;
var max_index = 0;
for (var i=0; i<vector.length; i++)
{
if (vector[i] > max_value)
{
max_value = vector[i];
max_index = i;
}
}
// Build print string
for (var i=0; i<vector.length; i++)
{
// Compute leading spacer
var spacer = ' ';
if (correct_cells.includes(i))
{
spacer = correct_flag;
}
else if (i == max_index)
{
spacer = max_flag;
}
// Print the spacer + value
//
str += spacer;
var n = vector[i];
// Print zero or value
if (n == 0)
{
str += ' '+zero_value+' ';
}
else if (n == 1)
{
str += '1.0';
}
else // Print value
{
var n3 = Math.floor(n*100)/100;
if (n3==0)
{
str += '.00';
}
else
{
str += (''+Math.floor(n*100)/100+'00').slice(1,4);
}
}
}
return str;
} |
JavaScript | find_links(voronoi_viz, id1, id2) {
//id1 from (outbound)
//id2 to (inbound)
let obj = {
"out": null,
"in": null
}
for (let i = 0; i < voronoi_viz.site_db.all_links.length; i++) {
if (id1 == voronoi_viz.site_db.all_links[i].sites[0] && id2 == voronoi_viz.site_db.all_links[i].sites[1]) {
obj["out"] = voronoi_viz.site_db.all_links[i];
}
if (id1 == voronoi_viz.site_db.all_links[i].sites[1] && id2 == voronoi_viz.site_db.all_links[i].sites[0]) {
obj["in"] = voronoi_viz.site_db.all_links[i];
}
}
return obj;
} | find_links(voronoi_viz, id1, id2) {
//id1 from (outbound)
//id2 to (inbound)
let obj = {
"out": null,
"in": null
}
for (let i = 0; i < voronoi_viz.site_db.all_links.length; i++) {
if (id1 == voronoi_viz.site_db.all_links[i].sites[0] && id2 == voronoi_viz.site_db.all_links[i].sites[1]) {
obj["out"] = voronoi_viz.site_db.all_links[i];
}
if (id1 == voronoi_viz.site_db.all_links[i].sites[1] && id2 == voronoi_viz.site_db.all_links[i].sites[0]) {
obj["in"] = voronoi_viz.site_db.all_links[i];
}
}
return obj;
} |
JavaScript | calculate_deviation(voronoi_viz, link) {
//find the physical length of the requested link
let dist = voronoi_viz.site_db.all_links.find(x => x.id === link).length;
let travelTime, normalTravelTime;
//get travel time and normal travel time, if travel time is undefined replace it with normal travel time
try {
travelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === link).travelTime;
normalTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === link).normalTravelTime;
} catch {
return undefined
}
if (travelTime == null || travelTime == undefined) {
travelTime = normalTravelTime;
}
//convert time and distance to speed
let current = (dist / travelTime) * voronoi_viz.tools.TO_MPH;
let normal = (dist / normalTravelTime) * voronoi_viz.tools.TO_MPH; //historical speed
//negative speed is slower, positive speed is faster
return current - normal;
} | calculate_deviation(voronoi_viz, link) {
//find the physical length of the requested link
let dist = voronoi_viz.site_db.all_links.find(x => x.id === link).length;
let travelTime, normalTravelTime;
//get travel time and normal travel time, if travel time is undefined replace it with normal travel time
try {
travelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === link).travelTime;
normalTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === link).normalTravelTime;
} catch {
return undefined
}
if (travelTime == null || travelTime == undefined) {
travelTime = normalTravelTime;
}
//convert time and distance to speed
let current = (dist / travelTime) * voronoi_viz.tools.TO_MPH;
let normal = (dist / normalTravelTime) * voronoi_viz.tools.TO_MPH; //historical speed
//negative speed is slower, positive speed is faster
return current - normal;
} |
JavaScript | init() {
console.log('STARTING')
var voronoi_viz = this;
//-------------------------------//
//--------LOADING API DATA-------//
//-------------------------------//
voronoi_viz.site_db.load_api_data(voronoi_viz).then(() => {
voronoi_viz.site_db.initialise_nodes(voronoi_viz);
voronoi_viz.hud.init(voronoi_viz, URL_NODE);
voronoi_viz.draw_voronoi(voronoi_viz);
voronoi_viz.generate_hull(voronoi_viz);
});
//attach map event listeners
voronoi_viz.map.on("viewreset moveend", voronoi_viz.draw_voronoi.bind(voronoi_viz));
voronoi_viz.map.on("viewreset moveend", voronoi_viz.generate_hull.bind(voronoi_viz));
//Will execute myCallback every X seconds
//the use of .bind(this) is critical otherwise we can't call other class methods
//https://stackoverflow.com/questions/42238984/uncaught-typeerror-this-method-is-not-a-function-node-js-class-export
window.setInterval(voronoi_viz.update.bind(voronoi_viz), 60000);
} | init() {
console.log('STARTING')
var voronoi_viz = this;
//-------------------------------//
//--------LOADING API DATA-------//
//-------------------------------//
voronoi_viz.site_db.load_api_data(voronoi_viz).then(() => {
voronoi_viz.site_db.initialise_nodes(voronoi_viz);
voronoi_viz.hud.init(voronoi_viz, URL_NODE);
voronoi_viz.draw_voronoi(voronoi_viz);
voronoi_viz.generate_hull(voronoi_viz);
});
//attach map event listeners
voronoi_viz.map.on("viewreset moveend", voronoi_viz.draw_voronoi.bind(voronoi_viz));
voronoi_viz.map.on("viewreset moveend", voronoi_viz.generate_hull.bind(voronoi_viz));
//Will execute myCallback every X seconds
//the use of .bind(this) is critical otherwise we can't call other class methods
//https://stackoverflow.com/questions/42238984/uncaught-typeerror-this-method-is-not-a-function-node-js-class-export
window.setInterval(voronoi_viz.update.bind(voronoi_viz), 60000);
} |
JavaScript | date_shift(n, node_id) {
let voronoi_viz = this;
let new_date = new Date(document.getElementById('date_now_header').innerHTML); // as loaded in page template config_ values;
new_date.setDate(new_date.getDate() + n);
let new_year = new_date.getFullYear();
let new_month = ("0" + (new_date.getMonth() + 1)).slice(-2);
let new_month_long = new_date.toLocaleString('default', {
month: 'long'
});
let new_day = ("0" + new_date.getDate()).slice(-2);
let query_date = new_year + "-" + new_month + "-" + new_day;
document.getElementById('date_now_header').innerHTML = new_day + " " + new_month_long + " " + new_year
voronoi_viz.hud.show_node_information(voronoi_viz, node_id, query_date);
let url_date = new_year + '-' + new_month + '-' + new_day;
voronoi_viz.update_url(node_id, url_date);
} | date_shift(n, node_id) {
let voronoi_viz = this;
let new_date = new Date(document.getElementById('date_now_header').innerHTML); // as loaded in page template config_ values;
new_date.setDate(new_date.getDate() + n);
let new_year = new_date.getFullYear();
let new_month = ("0" + (new_date.getMonth() + 1)).slice(-2);
let new_month_long = new_date.toLocaleString('default', {
month: 'long'
});
let new_day = ("0" + new_date.getDate()).slice(-2);
let query_date = new_year + "-" + new_month + "-" + new_day;
document.getElementById('date_now_header').innerHTML = new_day + " " + new_month_long + " " + new_year
voronoi_viz.hud.show_node_information(voronoi_viz, node_id, query_date);
let url_date = new_year + '-' + new_month + '-' + new_day;
voronoi_viz.update_url(node_id, url_date);
} |
JavaScript | draw_link(voronoi_viz, link, dur, color) {
//add the link_group to the canvas again
//(we detach it previously to make it invisible after mouseout is being performed)
voronoi_viz.link_group = voronoi_viz.svg_canvas.append("g")
.attr("transform", "translate(" + (-voronoi_viz.topLeft.x) + "," + (-voronoi_viz.topLeft.y) + ")");
//find the sites that the link connects
let connected_sites = voronoi_viz.site_db.all_links.find(x => x.id === link).sites;
let from = voronoi_viz.site_db.get_node_from_id(voronoi_viz, connected_sites[0]);
let to = voronoi_viz.site_db.get_node_from_id(voronoi_viz, connected_sites[1]);
//acquire the direction of the link by checking if it's opposite exists.
//If the opposite's drawn on screen, make arc's curvature inverse.
let direction = voronoi_viz.links_drawn.includes(voronoi_viz.site_db.inverse_link(voronoi_viz, link)) ? "in" : "out";
//calculate the speed deviation for the link in question
let deviation = voronoi_viz.site_db.calculate_deviation(voronoi_viz, link) //negative slower, positive faster
//acquire the minmax values for the color scale.
//we create a new color scale, even though the old one exits
//because the drawn links always colored based on speed deviation,
//whereas the general set_colorScale can be changed to speed ranges etc.
let values = voronoi_viz.site_db.get_min_max(voronoi_viz);
var scale = d3.scaleLinear()
.domain([values.min, values.max])
.range([values.min, values.max]);
//if color's not defined, color the link based on speed deviation
color = color == undefined ? voronoi_viz.set_color(scale(deviation)) : color;
let strokeWeight = 5;
//animate the line
let link_line = generate_arc(from, to, direction, strokeWeight, color);
let line_length = link_line.node().getTotalLength();
animate_movement(link_line, line_length, dur);
//add to the drawn list so we know what the opposite link's
//direction is
voronoi_viz.links_drawn.push(link);
//----------Generating and Drawing Arcs--------//
function generate_arc(A, B, direction, strokeWeight, stroke) {
return voronoi_viz.link_group
.append('path')
.attr('d', curved_line(A.x, A.y, B.x, B.y, direction === "in" ? 1 : -1))
.attr('class', 'arc_line')
.style("fill", "none")
.style("fill-opacity", 0)
.attr("stroke", stroke)
.attr("stroke-opacity", 1)
.style("stroke-width", strokeWeight);
}
//compute the arc points given start/end coordinates
//[start/end coordinates, dir stands for direction]
function curved_line(start_x, start_y, end_x, end_y, dir) {
//find the middle location of where the curvature is 0
let mid_x = (start_x + end_x) / 2;
let a = Math.abs(start_x - end_x);
let b = Math.abs(start_y - end_y);
//curvature height/or how curved the line is
//[y offset in other words]
let off = a > b ? b / 10 : 15;
let mid_x1 = mid_x - off * dir;
//calculate the slope of the arc line
//let mid_y1 = voronoi_viz.slope(mid_x1, start_x, start_y, end_x, end_y);
//computes the slope on which we place the arc lines
//indicate links between sites
let midX = (start_x + end_x) / 2;
let midY = (start_y + end_y) / 2;
let slope = (end_y - start_y) / (end_x - start_x);
let mid_y1 = (-1 / slope) * (mid_x1 - midX) + midY;
return ['M', start_x, start_y, // the arc start coordinates (where the starting node is)
'C', // This means we're gonna build an elliptical arc
start_x, ",", start_y, ",",
mid_x1, mid_y1,
end_x, ',', end_y
]
.join(' ');
}
//animates lines being rendered as if they move through the map.
//It's how we create a sense of directionality from links
function animate_movement(line, outboundLength, dur) {
return line
.attr("stroke-dasharray", outboundLength + " " + outboundLength)
.attr("stroke-dashoffset", outboundLength)
.transition()
.duration(dur)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
.on("end",
function (d, i) {
// d3.select(this).remove()
}
);
}
} | draw_link(voronoi_viz, link, dur, color) {
//add the link_group to the canvas again
//(we detach it previously to make it invisible after mouseout is being performed)
voronoi_viz.link_group = voronoi_viz.svg_canvas.append("g")
.attr("transform", "translate(" + (-voronoi_viz.topLeft.x) + "," + (-voronoi_viz.topLeft.y) + ")");
//find the sites that the link connects
let connected_sites = voronoi_viz.site_db.all_links.find(x => x.id === link).sites;
let from = voronoi_viz.site_db.get_node_from_id(voronoi_viz, connected_sites[0]);
let to = voronoi_viz.site_db.get_node_from_id(voronoi_viz, connected_sites[1]);
//acquire the direction of the link by checking if it's opposite exists.
//If the opposite's drawn on screen, make arc's curvature inverse.
let direction = voronoi_viz.links_drawn.includes(voronoi_viz.site_db.inverse_link(voronoi_viz, link)) ? "in" : "out";
//calculate the speed deviation for the link in question
let deviation = voronoi_viz.site_db.calculate_deviation(voronoi_viz, link) //negative slower, positive faster
//acquire the minmax values for the color scale.
//we create a new color scale, even though the old one exits
//because the drawn links always colored based on speed deviation,
//whereas the general set_colorScale can be changed to speed ranges etc.
let values = voronoi_viz.site_db.get_min_max(voronoi_viz);
var scale = d3.scaleLinear()
.domain([values.min, values.max])
.range([values.min, values.max]);
//if color's not defined, color the link based on speed deviation
color = color == undefined ? voronoi_viz.set_color(scale(deviation)) : color;
let strokeWeight = 5;
//animate the line
let link_line = generate_arc(from, to, direction, strokeWeight, color);
let line_length = link_line.node().getTotalLength();
animate_movement(link_line, line_length, dur);
//add to the drawn list so we know what the opposite link's
//direction is
voronoi_viz.links_drawn.push(link);
//----------Generating and Drawing Arcs--------//
function generate_arc(A, B, direction, strokeWeight, stroke) {
return voronoi_viz.link_group
.append('path')
.attr('d', curved_line(A.x, A.y, B.x, B.y, direction === "in" ? 1 : -1))
.attr('class', 'arc_line')
.style("fill", "none")
.style("fill-opacity", 0)
.attr("stroke", stroke)
.attr("stroke-opacity", 1)
.style("stroke-width", strokeWeight);
}
//compute the arc points given start/end coordinates
//[start/end coordinates, dir stands for direction]
function curved_line(start_x, start_y, end_x, end_y, dir) {
//find the middle location of where the curvature is 0
let mid_x = (start_x + end_x) / 2;
let a = Math.abs(start_x - end_x);
let b = Math.abs(start_y - end_y);
//curvature height/or how curved the line is
//[y offset in other words]
let off = a > b ? b / 10 : 15;
let mid_x1 = mid_x - off * dir;
//calculate the slope of the arc line
//let mid_y1 = voronoi_viz.slope(mid_x1, start_x, start_y, end_x, end_y);
//computes the slope on which we place the arc lines
//indicate links between sites
let midX = (start_x + end_x) / 2;
let midY = (start_y + end_y) / 2;
let slope = (end_y - start_y) / (end_x - start_x);
let mid_y1 = (-1 / slope) * (mid_x1 - midX) + midY;
return ['M', start_x, start_y, // the arc start coordinates (where the starting node is)
'C', // This means we're gonna build an elliptical arc
start_x, ",", start_y, ",",
mid_x1, mid_y1,
end_x, ',', end_y
]
.join(' ');
}
//animates lines being rendered as if they move through the map.
//It's how we create a sense of directionality from links
function animate_movement(line, outboundLength, dur) {
return line
.attr("stroke-dasharray", outboundLength + " " + outboundLength)
.attr("stroke-dashoffset", outboundLength)
.transition()
.duration(dur)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
.on("end",
function (d, i) {
// d3.select(this).remove()
}
);
}
} |
JavaScript | function curved_line(start_x, start_y, end_x, end_y, dir) {
//find the middle location of where the curvature is 0
let mid_x = (start_x + end_x) / 2;
let a = Math.abs(start_x - end_x);
let b = Math.abs(start_y - end_y);
//curvature height/or how curved the line is
//[y offset in other words]
let off = a > b ? b / 10 : 15;
let mid_x1 = mid_x - off * dir;
//calculate the slope of the arc line
//let mid_y1 = voronoi_viz.slope(mid_x1, start_x, start_y, end_x, end_y);
//computes the slope on which we place the arc lines
//indicate links between sites
let midX = (start_x + end_x) / 2;
let midY = (start_y + end_y) / 2;
let slope = (end_y - start_y) / (end_x - start_x);
let mid_y1 = (-1 / slope) * (mid_x1 - midX) + midY;
return ['M', start_x, start_y, // the arc start coordinates (where the starting node is)
'C', // This means we're gonna build an elliptical arc
start_x, ",", start_y, ",",
mid_x1, mid_y1,
end_x, ',', end_y
]
.join(' ');
} | function curved_line(start_x, start_y, end_x, end_y, dir) {
//find the middle location of where the curvature is 0
let mid_x = (start_x + end_x) / 2;
let a = Math.abs(start_x - end_x);
let b = Math.abs(start_y - end_y);
//curvature height/or how curved the line is
//[y offset in other words]
let off = a > b ? b / 10 : 15;
let mid_x1 = mid_x - off * dir;
//calculate the slope of the arc line
//let mid_y1 = voronoi_viz.slope(mid_x1, start_x, start_y, end_x, end_y);
//computes the slope on which we place the arc lines
//indicate links between sites
let midX = (start_x + end_x) / 2;
let midY = (start_y + end_y) / 2;
let slope = (end_y - start_y) / (end_x - start_x);
let mid_y1 = (-1 / slope) * (mid_x1 - midX) + midY;
return ['M', start_x, start_y, // the arc start coordinates (where the starting node is)
'C', // This means we're gonna build an elliptical arc
start_x, ",", start_y, ",",
mid_x1, mid_y1,
end_x, ',', end_y
]
.join(' ');
} |
JavaScript | color_transition(voronoi_viz, viz_type) {
voronoi_viz.site_db.set_visualisations(voronoi_viz, viz_type)
let set_color = voronoi_viz.set_color_range(voronoi_viz);
voronoi_viz.polygon_group.selectAll(".cell")
.transition()
.duration('1000')
.attr('fill', function (d, i) {
let color = voronoi_viz.site_db.all[i].selected;
if (color == null || color == undefined) {
return "rgb(50,50,50);"
} else {
return set_color(color) //c10[i % 10]
}
})
} | color_transition(voronoi_viz, viz_type) {
voronoi_viz.site_db.set_visualisations(voronoi_viz, viz_type)
let set_color = voronoi_viz.set_color_range(voronoi_viz);
voronoi_viz.polygon_group.selectAll(".cell")
.transition()
.duration('1000')
.attr('fill', function (d, i) {
let color = voronoi_viz.site_db.all[i].selected;
if (color == null || color == undefined) {
return "rgb(50,50,50);"
} else {
return set_color(color) //c10[i % 10]
}
})
} |
JavaScript | generate_graph(voronoi_viz, start, finish) {
let graph = {};
//iterate over the SITE_DB to find the start/finish nodes
//and all the other nodes in between
voronoi_viz.site_db.all.forEach((element) => {
let neighbors = element.neighbors;
let obj = {};
//each neighbour is a node. Computes the weighted graph:
neighbors.forEach((neighbor) => {
//and the travel time between the nodes is the edge weight
if (neighbor.site == start) {
obj["S"] = neighbor.travelTime; //or dist;
}
if (neighbor.site == finish) {
obj["F"] = neighbor.travelTime; //or dist;
} else {
obj[neighbor.site] = neighbor.travelTime;
}
});
if (element.name == start) {
graph["S"] = obj;
}
if (element.name == finish) {
graph["F"] = obj;
} else {
graph[element.name] = obj;
}
});
return graph;
} | generate_graph(voronoi_viz, start, finish) {
let graph = {};
//iterate over the SITE_DB to find the start/finish nodes
//and all the other nodes in between
voronoi_viz.site_db.all.forEach((element) => {
let neighbors = element.neighbors;
let obj = {};
//each neighbour is a node. Computes the weighted graph:
neighbors.forEach((neighbor) => {
//and the travel time between the nodes is the edge weight
if (neighbor.site == start) {
obj["S"] = neighbor.travelTime; //or dist;
}
if (neighbor.site == finish) {
obj["F"] = neighbor.travelTime; //or dist;
} else {
obj[neighbor.site] = neighbor.travelTime;
}
});
if (element.name == start) {
graph["S"] = obj;
}
if (element.name == finish) {
graph["F"] = obj;
} else {
graph[element.name] = obj;
}
});
return graph;
} |
JavaScript | generate_hull(voronoi_viz) {
//on 'moveend' redeclare the voronoi_viz, otherwise the visualisaiton fails to load
//since the 'this' becomes the 'moveend' object
if (voronoi_viz.type == "moveend") {
voronoi_viz = this;
}
//get a list of group ids e.g (north, south, center etc)
voronoi_viz.site_db.zones.forEach((group_id) => {
let site_id_list = CELL_GROUPS[group_id]['acp_ids']
let point_list = []
let point_pairs = []
//get a list of site IDs inside a group e.g ('SITE_CA31BF74-167C-469D-A2BF-63F9C2CE919A',... etc)
site_id_list.forEach((site_acp_id) => {
//elements that are off-screen bounds will return as undefined
let element = d3.select('#' + site_acp_id).node();
//therefore we look out for those and skip part of the function if that occurs
if (element != undefined) {
let total_len = parseInt(element.getTotalLength());
for (let u = 0; u < total_len; u += 2) {
point_pairs.push([element.getPointAtLength(u).x, element.getPointAtLength(u).y])
point_list.push(element.getPointAtLength(u))
}
}
});
//set concvity threshold for the algorithm so that its zoom-dependent
let concavity_threshold;
if (voronoi_viz.map._zoom <= 12) {
concavity_threshold = 85
} else {
concavity_threshold = 185;
}
let defaultHull = d3.concaveHull().distance(concavity_threshold);
let paddedHull = d3.concaveHull().distance(concavity_threshold).padding(5);
CELL_GROUPS[group_id]['default_hull'] = defaultHull(point_pairs);
CELL_GROUPS[group_id]['padded_hull'] = paddedHull(point_pairs);
//'points' contains a set of x/y coordinates that denote the hull's line.
//we use 'points' list rather than padded_zone_outline because we have to
//reformat it to be used withing the d3.js context
let points = []
//zone outline in a single list -- to be reformated in the for loop below
let padded_zone_outline = paddedHull(point_pairs)[0]
if (padded_zone_outline != undefined) {
for (let j = 0; j < padded_zone_outline.length; j++) {
points.push({
'x': padded_zone_outline[j][0],
'y': padded_zone_outline[j][1]
})
}
}
CELL_GROUPS[group_id]['points'] = points;
})
} | generate_hull(voronoi_viz) {
//on 'moveend' redeclare the voronoi_viz, otherwise the visualisaiton fails to load
//since the 'this' becomes the 'moveend' object
if (voronoi_viz.type == "moveend") {
voronoi_viz = this;
}
//get a list of group ids e.g (north, south, center etc)
voronoi_viz.site_db.zones.forEach((group_id) => {
let site_id_list = CELL_GROUPS[group_id]['acp_ids']
let point_list = []
let point_pairs = []
//get a list of site IDs inside a group e.g ('SITE_CA31BF74-167C-469D-A2BF-63F9C2CE919A',... etc)
site_id_list.forEach((site_acp_id) => {
//elements that are off-screen bounds will return as undefined
let element = d3.select('#' + site_acp_id).node();
//therefore we look out for those and skip part of the function if that occurs
if (element != undefined) {
let total_len = parseInt(element.getTotalLength());
for (let u = 0; u < total_len; u += 2) {
point_pairs.push([element.getPointAtLength(u).x, element.getPointAtLength(u).y])
point_list.push(element.getPointAtLength(u))
}
}
});
//set concvity threshold for the algorithm so that its zoom-dependent
let concavity_threshold;
if (voronoi_viz.map._zoom <= 12) {
concavity_threshold = 85
} else {
concavity_threshold = 185;
}
let defaultHull = d3.concaveHull().distance(concavity_threshold);
let paddedHull = d3.concaveHull().distance(concavity_threshold).padding(5);
CELL_GROUPS[group_id]['default_hull'] = defaultHull(point_pairs);
CELL_GROUPS[group_id]['padded_hull'] = paddedHull(point_pairs);
//'points' contains a set of x/y coordinates that denote the hull's line.
//we use 'points' list rather than padded_zone_outline because we have to
//reformat it to be used withing the d3.js context
let points = []
//zone outline in a single list -- to be reformated in the for loop below
let padded_zone_outline = paddedHull(point_pairs)[0]
if (padded_zone_outline != undefined) {
for (let j = 0; j < padded_zone_outline.length; j++) {
points.push({
'x': padded_zone_outline[j][0],
'y': padded_zone_outline[j][1]
})
}
}
CELL_GROUPS[group_id]['points'] = points;
})
} |
JavaScript | function create_sensor(msg, clock_time)
{
// new sensor, create marker
log(self.widget_id, 'stop_bus_map ** New '+msg[RECORD_INDEX]);
var sensor_id = msg[RECORD_INDEX];
var sensor = { sensor_id: sensor_id,
msg: msg,
};
var marker_icon = create_sensor_icon(msg);
sensor['marker'] = L.Marker.movingMarker([[msg[RECORD_LAT], msg[RECORD_LNG]],
[msg[RECORD_LAT], msg[RECORD_LNG]]],
[1 * SECONDS],
{icon: marker_icon});
sensor['marker']
.addTo(map)
.bindPopup(popup_content(msg), { className: "sensor-popup"})
//.bindTooltip(tooltip_content(msg), {
// // permanent: true,
// className: "sensor-tooltip",
// interactive: true
// })
.on('click', function()
{
//log("marker click handler");
})
.start();
sensor.state = {};
sensors[sensor_id] = sensor;
// flag if this record is OLD or NEW
init_old_status(sensor, new Date());
} | function create_sensor(msg, clock_time)
{
// new sensor, create marker
log(self.widget_id, 'stop_bus_map ** New '+msg[RECORD_INDEX]);
var sensor_id = msg[RECORD_INDEX];
var sensor = { sensor_id: sensor_id,
msg: msg,
};
var marker_icon = create_sensor_icon(msg);
sensor['marker'] = L.Marker.movingMarker([[msg[RECORD_LAT], msg[RECORD_LNG]],
[msg[RECORD_LAT], msg[RECORD_LNG]]],
[1 * SECONDS],
{icon: marker_icon});
sensor['marker']
.addTo(map)
.bindPopup(popup_content(msg), { className: "sensor-popup"})
//.bindTooltip(tooltip_content(msg), {
// // permanent: true,
// className: "sensor-tooltip",
// interactive: true
// })
.on('click', function()
{
//log("marker click handler");
})
.start();
sensor.state = {};
sensors[sensor_id] = sensor;
// flag if this record is OLD or NEW
init_old_status(sensor, new Date());
} |
JavaScript | function update_sensor(msg, clock_time)
{
// existing sensor data record has arrived
var sensor_id = msg[RECORD_INDEX];
if (get_msg_date(msg).getTime() != get_msg_date(sensors[sensor_id].msg).getTime())
{
// store as latest msg
// moving current msg to prev_msg
sensors[sensor_id].prev_msg = sensors[sensor_id].msg;
sensors[sensor_id].msg = msg; // update entry for this msg
var sensor = sensors[sensor_id];
// move marker
var pos = get_msg_point(msg);
if (self.params.breadcrumbs && map.getBounds().contains(L.latLng(pos)))
{
add_breadcrumb(sensor);
}
var marker = sensors[sensor_id].marker;
marker.moveTo([pos.lat, pos.lng], [1 * SECONDS] );
marker.resume();
// update tooltip and popup
marker.setTooltipContent(tooltip_content(msg));
marker.setPopupContent(popup_content(msg));
draw_progress_indicator(sensor);
// flag if this record is OLD or NEW
update_old_status(sensor, new Date());
}
} | function update_sensor(msg, clock_time)
{
// existing sensor data record has arrived
var sensor_id = msg[RECORD_INDEX];
if (get_msg_date(msg).getTime() != get_msg_date(sensors[sensor_id].msg).getTime())
{
// store as latest msg
// moving current msg to prev_msg
sensors[sensor_id].prev_msg = sensors[sensor_id].msg;
sensors[sensor_id].msg = msg; // update entry for this msg
var sensor = sensors[sensor_id];
// move marker
var pos = get_msg_point(msg);
if (self.params.breadcrumbs && map.getBounds().contains(L.latLng(pos)))
{
add_breadcrumb(sensor);
}
var marker = sensors[sensor_id].marker;
marker.moveTo([pos.lat, pos.lng], [1 * SECONDS] );
marker.resume();
// update tooltip and popup
marker.setTooltipContent(tooltip_content(msg));
marker.setPopupContent(popup_content(msg));
draw_progress_indicator(sensor);
// flag if this record is OLD or NEW
update_old_status(sensor, new Date());
}
} |
JavaScript | function add_breadcrumb(sensor)
{
var pos = get_msg_point(sensor.msg);
var prev_pos = get_msg_point(sensor.prev_msg);
var distance = get_distance(prev_pos, pos);
// only update bearing of bus if we've moved at least 40m
if (distance > PROGRESS_MIN_DISTANCE)
{
var crumb = L.circleMarker([pos.lat, pos.lng], { color: 'blue', radius: 1 }).addTo(map);
if (crumbs.length < CRUMB_COUNT) // fewer than CRUMB_COUNT so append
{
crumbs.push(crumb);
}
else // replace a random existing crumb
{
var index = Math.floor(Math.random() * CRUMB_COUNT);
map.removeLayer(crumbs[index]);
crumbs[index] = crumb;
}
}
} | function add_breadcrumb(sensor)
{
var pos = get_msg_point(sensor.msg);
var prev_pos = get_msg_point(sensor.prev_msg);
var distance = get_distance(prev_pos, pos);
// only update bearing of bus if we've moved at least 40m
if (distance > PROGRESS_MIN_DISTANCE)
{
var crumb = L.circleMarker([pos.lat, pos.lng], { color: 'blue', radius: 1 }).addTo(map);
if (crumbs.length < CRUMB_COUNT) // fewer than CRUMB_COUNT so append
{
crumbs.push(crumb);
}
else // replace a random existing crumb
{
var index = Math.floor(Math.random() * CRUMB_COUNT);
map.removeLayer(crumbs[index]);
crumbs[index] = crumb;
}
}
} |
JavaScript | function create_sensor_icon(msg)
{
var line = '';
if (msg.LineRef != null)
{
line = msg.LineRef;
}
var marker_html = '<div class="marker_label_'+icon_size+'">'+line+'</div>';
var marker_size = new L.Point(30,30);
switch (icon_size)
{
case 'L':
marker_size = new L.Point(45,45);
break;
default:
break;
}
return L.divIcon({
className: 'marker_sensor_'+icon_size,
iconSize: marker_size,
iconAnchor: L.point(23,38),
html: marker_html
});
} | function create_sensor_icon(msg)
{
var line = '';
if (msg.LineRef != null)
{
line = msg.LineRef;
}
var marker_html = '<div class="marker_label_'+icon_size+'">'+line+'</div>';
var marker_size = new L.Point(30,30);
switch (icon_size)
{
case 'L':
marker_size = new L.Point(45,45);
break;
default:
break;
}
return L.divIcon({
className: 'marker_sensor_'+icon_size,
iconSize: marker_size,
iconAnchor: L.point(23,38),
html: marker_html
});
} |
JavaScript | function more_content(sensor_id)
{
var sensor = sensors[sensor_id];
var content = JSON.stringify(sensor.msg).replace(/,/g,', ');
content +=
'<br/><a href="#" onclick="click_less('+"'"+sensor_id+"'"+')">less</a>';
return content;
} | function more_content(sensor_id)
{
var sensor = sensors[sensor_id];
var content = JSON.stringify(sensor.msg).replace(/,/g,', ');
content +=
'<br/><a href="#" onclick="click_less('+"'"+sensor_id+"'"+')">less</a>';
return content;
} |
JavaScript | function check_old_records(clock_time)
{
//parent.log('checking for old data records..,');
// do nothing if timestamp format not recognised
switch (RECORD_TS_FORMAT)
{
case 'ISO8601':
break;
default:
return;
}
for (var sensor_id in sensors)
{
update_old_status(sensors[sensor_id], clock_time);
}
} | function check_old_records(clock_time)
{
//parent.log('checking for old data records..,');
// do nothing if timestamp format not recognised
switch (RECORD_TS_FORMAT)
{
case 'ISO8601':
break;
default:
return;
}
for (var sensor_id in sensors)
{
update_old_status(sensors[sensor_id], clock_time);
}
} |
JavaScript | function draw_stops(stops)
{
log('draw_stops()','drawing '+stops.length+' stops');
for (var i=0; i < stops.length; i++)
{
draw_stop(stops[i]);
}
} | function draw_stops(stops)
{
log('draw_stops()','drawing '+stops.length+' stops');
for (var i=0; i < stops.length; i++)
{
draw_stop(stops[i]);
}
} |
JavaScript | function input_stop_bus_map(widget_config, parent_el, params) {
log('input_stop_bus_map with',params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a map, including selected bus stops, on which it overlays real-time buses.";
config_info_text += " 'Main Title' is any text to appear in bold at the top of the map.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_info3 = document.createElement('p');
config_info_text = "'Breadcrumbs' are small blue dots that are drawn on the map each time a bus moves to a new position, so they draw the bus paths.";
config_info3.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info3);
var config_info4 = document.createElement('p');
config_info_text = "For the 'map and stops' you just need to drag and zoom the map, and select stops, which will then be displayed in the widget.";
config_info4.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info4);
var config_table = document.createElement('table');
config_table.className = 'config_input_stop_timetable';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// TITLE
//
var title_result = widget_config.input( config_tbody,
'string',
{ text: 'Main Title:',
title: 'The main title at the top of the widget, e.g. bus stop name'
},
params.title);
// BREADCRUMBS
//
var breadcrumbs_result = widget_config.input( config_tbody,
'select',
{ text: 'Breadcrumbs:',
title: 'Select whether you want dots drawn on the map highlighting the path of the buses',
options: [ { value: 'true', text: 'Yes - add blue dots to the map as buses move' },
{ value: 'false', text: "No - I like my map blissfully free of blue dots" }
]
},
params.breadcrumbs ? 'true' : 'false'); // note we're using a 'select' input so mangle the bool to the select keys.
// STOPS and MAP
//
log('configure() calling widget_config.input', 'stop', 'with',params.stops, params.map);
var stops_map_result = widget_config.input( config_tbody,
'bus_stops',
{ text: 'Map and Stops:',
title: "Click 'choose' to select stops from map",
},
{ stops: params.stops,
map: params.map
});
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// title
config_params.title = title_result.value();
// breadcrumbs
config_params.breadcrumbs = breadcrumbs_result.value() === 'true';
// stops and map
var stops_map_value = stops_map_result.value();
config_params.stops = stops_map_value.stops;
config_params.map = stops_map_value.map;
log(self.widget_id,'input_stop_bus_map returning params:',config_params);
return config_params;
}
var config_fn = function () {
return { title: title_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_stop_bus_map) | function input_stop_bus_map(widget_config, parent_el, params) {
log('input_stop_bus_map with',params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a map, including selected bus stops, on which it overlays real-time buses.";
config_info_text += " 'Main Title' is any text to appear in bold at the top of the map.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_info3 = document.createElement('p');
config_info_text = "'Breadcrumbs' are small blue dots that are drawn on the map each time a bus moves to a new position, so they draw the bus paths.";
config_info3.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info3);
var config_info4 = document.createElement('p');
config_info_text = "For the 'map and stops' you just need to drag and zoom the map, and select stops, which will then be displayed in the widget.";
config_info4.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info4);
var config_table = document.createElement('table');
config_table.className = 'config_input_stop_timetable';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// TITLE
//
var title_result = widget_config.input( config_tbody,
'string',
{ text: 'Main Title:',
title: 'The main title at the top of the widget, e.g. bus stop name'
},
params.title);
// BREADCRUMBS
//
var breadcrumbs_result = widget_config.input( config_tbody,
'select',
{ text: 'Breadcrumbs:',
title: 'Select whether you want dots drawn on the map highlighting the path of the buses',
options: [ { value: 'true', text: 'Yes - add blue dots to the map as buses move' },
{ value: 'false', text: "No - I like my map blissfully free of blue dots" }
]
},
params.breadcrumbs ? 'true' : 'false'); // note we're using a 'select' input so mangle the bool to the select keys.
// STOPS and MAP
//
log('configure() calling widget_config.input', 'stop', 'with',params.stops, params.map);
var stops_map_result = widget_config.input( config_tbody,
'bus_stops',
{ text: 'Map and Stops:',
title: "Click 'choose' to select stops from map",
},
{ stops: params.stops,
map: params.map
});
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// title
config_params.title = title_result.value();
// breadcrumbs
config_params.breadcrumbs = breadcrumbs_result.value() === 'true';
// stops and map
var stops_map_value = stops_map_result.value();
config_params.stops = stops_map_value.stops;
config_params.map = stops_map_value.map;
log(self.widget_id,'input_stop_bus_map returning params:',config_params);
return config_params;
}
var config_fn = function () {
return { title: title_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_stop_bus_map) |
JavaScript | addRegistration(registration) {
// Make sure we have an array to hold the registrations
if (!this._registrations) this._registrations = [];
// Abort if we are already listening for this registration
if (this._registrations.includes(registration)) return;
// Add the registration to the array of registrations
this._registrations.push(registration);
// Add a reference to the event listener and attach it to a registration so we can remove it when needed
var addEventListenerForRegistration = (registration, target, type, listener) => {
if (!this._eventListeners) this._eventListeners = [];
this._eventListeners.push({ 'registration': registration, 'target': target, 'type': type, 'listener': listener });
target.addEventListener(type, listener);
}
// Convenience method to both dispatch the update event and call the relating method
var dispatchUpdateStateChange = (state, serviceWorker, registration) => {
var type = 'update' + state;
var method = 'on' + type;
var event = new CustomEvent(type, { detail: { 'serviceWorker': serviceWorker, 'registration': registration } });
this.dispatchEvent(event);
if (this[method] && typeof this[method] === 'function') this[method].call(this, event);
};
// Fire the `onupdatewaiting` event if there is already a Service Worker waiting
if (registration.waiting) dispatchUpdateStateChange('waiting', registration.waiting, registration);
// Listen for a new service worker at ServiceWorkerRegistration.installing
addEventListenerForRegistration(registration, registration, 'updatefound', updatefoundevent => {
// Abort if we have no active service worker already, that would mean that this is a new service worker and not an update
// There should be a service worker installing else this event would not have fired, but double check to be sure
if (!registration.active || !registration.installing) return;
// Listen for state changes on the installing service worker
addEventListenerForRegistration(registration, registration.installing, 'statechange', statechangeevent => {
// The state should be installed, but double check to make sure
if (statechangeevent.target.state !== 'installed') return;
// Fire the `onupdatewaiting` event as we have moved from installing to the installed state
dispatchUpdateStateChange('waiting', registration.waiting, registration);
});
// Fire the `onupdateinstalling` event
dispatchUpdateStateChange('installing', registration.installing, registration);
});
// Listen for the document's associated ServiceWorkerRegistration to acquire a new active worker
addEventListenerForRegistration(registration, navigator.serviceWorker, 'controllerchange', controllerchangeevent => {
// Postpone the `onupdateready` event until the new active service worker is fully activated
controllerchangeevent.target.ready.then(registration => {
// Fire the `onupdateready` event
dispatchUpdateStateChange('ready', registration.active, registration);
});
});
} | addRegistration(registration) {
// Make sure we have an array to hold the registrations
if (!this._registrations) this._registrations = [];
// Abort if we are already listening for this registration
if (this._registrations.includes(registration)) return;
// Add the registration to the array of registrations
this._registrations.push(registration);
// Add a reference to the event listener and attach it to a registration so we can remove it when needed
var addEventListenerForRegistration = (registration, target, type, listener) => {
if (!this._eventListeners) this._eventListeners = [];
this._eventListeners.push({ 'registration': registration, 'target': target, 'type': type, 'listener': listener });
target.addEventListener(type, listener);
}
// Convenience method to both dispatch the update event and call the relating method
var dispatchUpdateStateChange = (state, serviceWorker, registration) => {
var type = 'update' + state;
var method = 'on' + type;
var event = new CustomEvent(type, { detail: { 'serviceWorker': serviceWorker, 'registration': registration } });
this.dispatchEvent(event);
if (this[method] && typeof this[method] === 'function') this[method].call(this, event);
};
// Fire the `onupdatewaiting` event if there is already a Service Worker waiting
if (registration.waiting) dispatchUpdateStateChange('waiting', registration.waiting, registration);
// Listen for a new service worker at ServiceWorkerRegistration.installing
addEventListenerForRegistration(registration, registration, 'updatefound', updatefoundevent => {
// Abort if we have no active service worker already, that would mean that this is a new service worker and not an update
// There should be a service worker installing else this event would not have fired, but double check to be sure
if (!registration.active || !registration.installing) return;
// Listen for state changes on the installing service worker
addEventListenerForRegistration(registration, registration.installing, 'statechange', statechangeevent => {
// The state should be installed, but double check to make sure
if (statechangeevent.target.state !== 'installed') return;
// Fire the `onupdatewaiting` event as we have moved from installing to the installed state
dispatchUpdateStateChange('waiting', registration.waiting, registration);
});
// Fire the `onupdateinstalling` event
dispatchUpdateStateChange('installing', registration.installing, registration);
});
// Listen for the document's associated ServiceWorkerRegistration to acquire a new active worker
addEventListenerForRegistration(registration, navigator.serviceWorker, 'controllerchange', controllerchangeevent => {
// Postpone the `onupdateready` event until the new active service worker is fully activated
controllerchangeevent.target.ready.then(registration => {
// Fire the `onupdateready` event
dispatchUpdateStateChange('ready', registration.active, registration);
});
});
} |
JavaScript | removeRegistration(registration) {
// Abort if we don't have any registrations
if (!this._registrations || this._registrations.length <= 0) return;
// Remove all event listeners attached to a certain registration
var removeEventListenersForRegistration = (registration) => {
if (!this._eventListeners) this._eventListeners = [];
this._eventListeners = this._eventListeners.filter(eventListener => {
if (eventListener.registration === registration) {
eventListener.target.removeEventListener(eventListener.type, eventListener.listener);
return false;
} else {
return true;
}
});
}
// Remove the registration from the array
this._registrations = this._registrations.filter(current => {
if (current === registration) {
removeEventListenersForRegistration(registration);
return false;
} else {
return true;
}
});
} | removeRegistration(registration) {
// Abort if we don't have any registrations
if (!this._registrations || this._registrations.length <= 0) return;
// Remove all event listeners attached to a certain registration
var removeEventListenersForRegistration = (registration) => {
if (!this._eventListeners) this._eventListeners = [];
this._eventListeners = this._eventListeners.filter(eventListener => {
if (eventListener.registration === registration) {
eventListener.target.removeEventListener(eventListener.type, eventListener.listener);
return false;
} else {
return true;
}
});
}
// Remove the registration from the array
this._registrations = this._registrations.filter(current => {
if (current === registration) {
removeEventListenersForRegistration(registration);
return false;
} else {
return true;
}
});
} |
JavaScript | function onreadystatechange(){
// Wait until the data is fully loaded,
// and make sure that the request hasn't already timed out
if ( xml.readyState == 4 && !requestDone ) {
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
// Check to see if the request was successful
if ( httpSuccess( xml ) ) {
// Execute the success callback with the data returned from the server
options.onSuccess( httpData( xml, options.type ) );
// Otherwise, an error occurred, so execute the error callback
} else {
options.onError();
}
// Call the completion callback
options.onComplete();
// Clean up after ourselves, to avoid memory leaks
xml = null;
}
} | function onreadystatechange(){
// Wait until the data is fully loaded,
// and make sure that the request hasn't already timed out
if ( xml.readyState == 4 && !requestDone ) {
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
// Check to see if the request was successful
if ( httpSuccess( xml ) ) {
// Execute the success callback with the data returned from the server
options.onSuccess( httpData( xml, options.type ) );
// Otherwise, an error occurred, so execute the error callback
} else {
options.onError();
}
// Call the completion callback
options.onComplete();
// Clean up after ourselves, to avoid memory leaks
xml = null;
}
} |
JavaScript | renderViewMode() {
if (this.state.selectedTabIndex == 0) {
return (
<SectionList
renderItem={({ item, index }) => {
return (
<SectionListItem item={item} index={index} >
</SectionListItem>
);
}}
renderSectionHeader={({ section }) => {
return (
<SectionHeader section={section} />
);
}}
sections={this.state.data}
keyExtractor={(item, index) => { item.startTime }}
>
</SectionList>
);
} else {
return (
<Charts graphData={this.state.data_graph}/>
);
}
} | renderViewMode() {
if (this.state.selectedTabIndex == 0) {
return (
<SectionList
renderItem={({ item, index }) => {
return (
<SectionListItem item={item} index={index} >
</SectionListItem>
);
}}
renderSectionHeader={({ section }) => {
return (
<SectionHeader section={section} />
);
}}
sections={this.state.data}
keyExtractor={(item, index) => { item.startTime }}
>
</SectionList>
);
} else {
return (
<Charts graphData={this.state.data_graph}/>
);
}
} |
JavaScript | function _safeSetDataURI(fSuccess, fFail) {
var self = this;
self._fFail = fFail;
self._fSuccess = fSuccess;
// Check it just once
if (self._bSupportDataURI === null) {
var el = document.createElement("img");
var fOnError = function() {
self._bSupportDataURI = false;
if (self._fFail) {
self._fFail.call(self);
}
};
var fOnSuccess = function() {
self._bSupportDataURI = true;
if (self._fSuccess) {
self._fSuccess.call(self);
}
};
el.onabort = fOnError;
el.onerror = fOnError;
el.onload = fOnSuccess;
el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data.
return;
} else if (self._bSupportDataURI === true && self._fSuccess) {
self._fSuccess.call(self);
} else if (self._bSupportDataURI === false && self._fFail) {
self._fFail.call(self);
}
} | function _safeSetDataURI(fSuccess, fFail) {
var self = this;
self._fFail = fFail;
self._fSuccess = fSuccess;
// Check it just once
if (self._bSupportDataURI === null) {
var el = document.createElement("img");
var fOnError = function() {
self._bSupportDataURI = false;
if (self._fFail) {
self._fFail.call(self);
}
};
var fOnSuccess = function() {
self._bSupportDataURI = true;
if (self._fSuccess) {
self._fSuccess.call(self);
}
};
el.onabort = fOnError;
el.onerror = fOnError;
el.onload = fOnSuccess;
el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data.
return;
} else if (self._bSupportDataURI === true && self._fSuccess) {
self._fSuccess.call(self);
} else if (self._bSupportDataURI === false && self._fFail) {
self._fFail.call(self);
}
} |
JavaScript | function createSlaveService() {
console.log("Creating " + INACTIVE_SLAVES + " slaves using replicas");
let command = "docker service create --restart-condition='none' --network='host' --name " + INSTANCE_NAME
+ " --replicas " + INACTIVE_SLAVES + " " + IMAGE + " ./hash_extractor s " + ADDR
console.log(command)
exec(command, (err, _stdout, _stderr) => {
if (err) {
console.error("Error executing " + command);
console.error(err);
return;
}
setInterval(checkInactive, 5000);
});
} | function createSlaveService() {
console.log("Creating " + INACTIVE_SLAVES + " slaves using replicas");
let command = "docker service create --restart-condition='none' --network='host' --name " + INSTANCE_NAME
+ " --replicas " + INACTIVE_SLAVES + " " + IMAGE + " ./hash_extractor s " + ADDR
console.log(command)
exec(command, (err, _stdout, _stderr) => {
if (err) {
console.error("Error executing " + command);
console.error(err);
return;
}
setInterval(checkInactive, 5000);
});
} |
JavaScript | function activeInactiveSlaves(difficultySearchMode, hash) {
let inactiveSlaves = getInactiveSlaves();
let slavesForHash = [];
for (let i = 0; i < difficultySearchMode.length; i++) {
let slave = inactiveSlaves[i];
let begin = difficultySearchMode[i].begin;
let end = difficultySearchMode[i].end;
let emit = "search " + hash + " " + begin + " " + end;
console.log("Sent to " + slave.name + " : " + emit);
slave.ws.send(emit);
slave.active = true;
slavesForHash.push(slave);
}
hashInSearch[hash] = slavesForHash;
} | function activeInactiveSlaves(difficultySearchMode, hash) {
let inactiveSlaves = getInactiveSlaves();
let slavesForHash = [];
for (let i = 0; i < difficultySearchMode.length; i++) {
let slave = inactiveSlaves[i];
let begin = difficultySearchMode[i].begin;
let end = difficultySearchMode[i].end;
let emit = "search " + hash + " " + begin + " " + end;
console.log("Sent to " + slave.name + " : " + emit);
slave.ws.send(emit);
slave.active = true;
slavesForHash.push(slave);
}
hashInSearch[hash] = slavesForHash;
} |
JavaScript | function saveHashInDB(hash, solution) {
let newHash = new Hash({
hash: hash,
solution: solution
});
newHash.save(function (err, hash) {
if (err)
console.error(err);
else
console.log("New hash : " + hash.hash + " - " + hash.solution);
});
} | function saveHashInDB(hash, solution) {
let newHash = new Hash({
hash: hash,
solution: solution
});
newHash.save(function (err, hash) {
if (err)
console.error(err);
else
console.log("New hash : " + hash.hash + " - " + hash.solution);
});
} |
JavaScript | function restoreDataForPreview(dataStorageRetrieved) {
document.querySelector('#element-name').innerText = dataStorageRetrieved.name;
document.querySelector('#element-role').innerText = dataStorageRetrieved.job;
document.querySelector('#element-mail').href = 'mailto:' + dataStorageRetrieved.email;
document.querySelector('#element-tel').href = 'tel:' + dataStorageRetrieved.phone;
document.querySelector('#element-lin').href = 'https://linkedin.com/in/' + dataStorageRetrieved.linkedin;
document.querySelector('#element-gh').href = 'https://github.com/' + dataStorageRetrieved.github;
document.querySelector('.personal-image').src = dataStorageRetrieved.photo;
var cardPreview = document.querySelector('#card');
console.log(dataStorageRetrieved.palette);
if (dataStorageRetrieved.palette === '1') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-azul');
} else if (dataStorageRetrieved.palette === '2') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-roja');
} else if (dataStorageRetrieved.palette === '3') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-gris');
}
if (dataStorageRetrieved.typography === '1') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--ubuntu');
} else if (dataStorageRetrieved.typography === '2') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--comicsans');
} else if (dataStorageRetrieved.typography === '3') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--montserrat');
}
} | function restoreDataForPreview(dataStorageRetrieved) {
document.querySelector('#element-name').innerText = dataStorageRetrieved.name;
document.querySelector('#element-role').innerText = dataStorageRetrieved.job;
document.querySelector('#element-mail').href = 'mailto:' + dataStorageRetrieved.email;
document.querySelector('#element-tel').href = 'tel:' + dataStorageRetrieved.phone;
document.querySelector('#element-lin').href = 'https://linkedin.com/in/' + dataStorageRetrieved.linkedin;
document.querySelector('#element-gh').href = 'https://github.com/' + dataStorageRetrieved.github;
document.querySelector('.personal-image').src = dataStorageRetrieved.photo;
var cardPreview = document.querySelector('#card');
console.log(dataStorageRetrieved.palette);
if (dataStorageRetrieved.palette === '1') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-azul');
} else if (dataStorageRetrieved.palette === '2') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-roja');
} else if (dataStorageRetrieved.palette === '3') {
cardPreview.classList.remove('paleta-azul', 'paleta-roja', 'paleta-gris');
cardPreview.classList.add('paleta-gris');
}
if (dataStorageRetrieved.typography === '1') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--ubuntu');
} else if (dataStorageRetrieved.typography === '2') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--comicsans');
} else if (dataStorageRetrieved.typography === '3') {
cardPreview.classList.remove('font-card--comicsans', 'font-card--ubuntu', 'font-card--montserrat');
cardPreview.classList.add('font-card--montserrat');
}
} |
JavaScript | function rudderPercent(rudder) {
if (Math.abs(rudder) < 0.001) {
rudder = 0.001;
}
return (rudder / MAX_RUDDER) * 100;
} | function rudderPercent(rudder) {
if (Math.abs(rudder) < 0.001) {
rudder = 0.001;
}
return (rudder / MAX_RUDDER) * 100;
} |
JavaScript | function modulo(n, d) {
if (n < 0)
{ return d - Math.abs(n % d) }
else {
return n % d;
}
} | function modulo(n, d) {
if (n < 0)
{ return d - Math.abs(n % d) }
else {
return n % d;
}
} |
JavaScript | function nav_notifications_handler(){
// Update the status of the unread articles.
fetch("{% url 'notification:nav_notifications_handler' %}").then(function(response){
if (response.status == 200){
// Remove animation
document.getElementById("ntf_ping").classList.add("hidden");
// Remove 'new notifications' effects
notifications = document.querySelectorAll('.not-element');
notifications.forEach(item =>{
item.classList.remove("font-semibold");
});
}else{
}
});
} | function nav_notifications_handler(){
// Update the status of the unread articles.
fetch("{% url 'notification:nav_notifications_handler' %}").then(function(response){
if (response.status == 200){
// Remove animation
document.getElementById("ntf_ping").classList.add("hidden");
// Remove 'new notifications' effects
notifications = document.querySelectorAll('.not-element');
notifications.forEach(item =>{
item.classList.remove("font-semibold");
});
}else{
}
});
} |
JavaScript | function showError(errorMessageKey) {
const messageString = strings[errorMessageKey];
if (messageString) {
atom.notifications.addError(messageString, {dismissable: true});
}
} | function showError(errorMessageKey) {
const messageString = strings[errorMessageKey];
if (messageString) {
atom.notifications.addError(messageString, {dismissable: true});
}
} |
JavaScript | function parseAuthorDate(line) {
const dateMatcher = /^author-time\s(.*)$/m;
const dateStamp = line.match(dateMatcher)[1];
return formatDate(moment.unix(dateStamp));
} | function parseAuthorDate(line) {
const dateMatcher = /^author-time\s(.*)$/m;
const dateStamp = line.match(dateMatcher)[1];
return formatDate(moment.unix(dateStamp));
} |
JavaScript | function parseCommitterDate(line) {
const dateMatcher = /^committer-time\s(.*)$/m;
const dateStamp = line.match(dateMatcher)[1];
return formatDate(moment.unix(dateStamp));
} | function parseCommitterDate(line) {
const dateMatcher = /^committer-time\s(.*)$/m;
const dateStamp = line.match(dateMatcher)[1];
return formatDate(moment.unix(dateStamp));
} |
JavaScript | function parseBlameLine(blameData, index) {
return markIfNoCommit({
hash: parseRevision(blameData),
lineNumber: index + 1,
author: parseAuthor(blameData),
date: parseAuthorDate(blameData),
committer: parseCommitter(blameData),
committerDate: parseCommitterDate(blameData),
summary: parseSummary(blameData),
});
} | function parseBlameLine(blameData, index) {
return markIfNoCommit({
hash: parseRevision(blameData),
lineNumber: index + 1,
author: parseAuthor(blameData),
date: parseAuthorDate(blameData),
committer: parseCommitter(blameData),
committerDate: parseCommitterDate(blameData),
summary: parseSummary(blameData),
});
} |
JavaScript | function markIfNoCommit(parsedBlame) {
const noCommit = /^0*$/.test(parsedBlame.hash);
return {
...parsedBlame,
noCommit,
};
} | function markIfNoCommit(parsedBlame) {
const noCommit = /^0*$/.test(parsedBlame.hash);
return {
...parsedBlame,
noCommit,
};
} |
JavaScript | exec(args, callback) {
if (!isArray(args) || !isFunction(callback)) {
return;
}
const gitBinary = atom.config.get('git-blame.gitBinaryPath') || 'git';
const child = childProcess.spawn(gitBinary, args, {cwd: this.workingDirectory});
let stdout = '';
let stderr = '';
let processError;
child.stdout.on('data', function (data) {
stdout += data;
});
child.stderr.on('data', function (data) {
stderr += data;
});
child.on('error', function (error) {
processError = error;
});
child.on('close', function (errorCode) {
if (processError) {
return callback(processError);
}
if (errorCode) {
const error = new Error(stderr);
error.code = errorCode;
return callback(error);
}
return callback(null, stdout.trimRight());
});
} | exec(args, callback) {
if (!isArray(args) || !isFunction(callback)) {
return;
}
const gitBinary = atom.config.get('git-blame.gitBinaryPath') || 'git';
const child = childProcess.spawn(gitBinary, args, {cwd: this.workingDirectory});
let stdout = '';
let stderr = '';
let processError;
child.stdout.on('data', function (data) {
stdout += data;
});
child.stderr.on('data', function (data) {
stderr += data;
});
child.on('error', function (error) {
processError = error;
});
child.on('close', function (errorCode) {
if (processError) {
return callback(processError);
}
if (errorCode) {
const error = new Error(stderr);
error.code = errorCode;
return callback(error);
}
return callback(null, stdout.trimRight());
});
} |
JavaScript | blame(fileName, callback) {
const args = ['blame', '--line-porcelain'];
// ignore white space based on config
if (atom.config.get('git-blame.ignoreWhiteSpaceDiffs')) {
args.push('-w');
}
args.push(fileName);
// Execute blame command and parse
this.exec(args, function (err, blameStdOut) {
if (err) {
return callback(err, blameStdOut);
}
return callback(null, parseBlame(blameStdOut));
});
} | blame(fileName, callback) {
const args = ['blame', '--line-porcelain'];
// ignore white space based on config
if (atom.config.get('git-blame.ignoreWhiteSpaceDiffs')) {
args.push('-w');
}
args.push(fileName);
// Execute blame command and parse
this.exec(args, function (err, blameStdOut) {
if (err) {
return callback(err, blameStdOut);
}
return callback(null, parseBlame(blameStdOut));
});
} |
JavaScript | function repositoryForEditorPath(pathString) {
const directory = new Directory(pathString);
return atom.project.repositoryForDirectory(directory)
.then((projectRepo) => {
if (!projectRepo) {
throw new Error(`Unable to find GitRepository for path ${pathString}.`);
}
return projectRepo;
});
} | function repositoryForEditorPath(pathString) {
const directory = new Directory(pathString);
return atom.project.repositoryForDirectory(directory)
.then((projectRepo) => {
if (!projectRepo) {
throw new Error(`Unable to find GitRepository for path ${pathString}.`);
}
return projectRepo;
});
} |
JavaScript | function withAdviceAround(advised, advice) {
return function () {
return advice.apply(this, Array.concat([advised], arguments));
};
} | function withAdviceAround(advised, advice) {
return function () {
return advice.apply(this, Array.concat([advised], arguments));
};
} |
JavaScript | function goToSerial0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 50, 1); // 2
tunnel.sendMessage("key", 50, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} | function goToSerial0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 50, 1); // 2
tunnel.sendMessage("key", 50, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} |
JavaScript | function goToParallel0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 51, 1); // 3
tunnel.sendMessage("key", 51, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} | function goToParallel0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 51, 1); // 3
tunnel.sendMessage("key", 51, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} |
JavaScript | function comeFromSerial0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 49, 1); // 1
tunnel.sendMessage("key", 49, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} | function comeFromSerial0() {
tunnel.sendMessage("key", 65507, 1); // enable CTRL
tunnel.sendMessage("key", 65513, 1); // enable ALT
tunnel.sendMessage("key", 49, 1); // 1
tunnel.sendMessage("key", 49, 0);
tunnel.sendMessage("key", 65513, 0);
tunnel.sendMessage("key", 65507, 0);
} |
JavaScript | function filterUserCreatedClassifier(result, classifier_ids) {
var ids = classifier_ids || [];
if (result && result.images) {
result.images.forEach(function(image) {
if (util.isArray(image.scores))
image.scores = image.scores.filter(function (score) {
// IBM's classifiers have the id = name
return (score.classifier_id === score.name) ||
(ids.indexOf(score.classifier_id) !== -1);
});
});
}
return result;
} | function filterUserCreatedClassifier(result, classifier_ids) {
var ids = classifier_ids || [];
if (result && result.images) {
result.images.forEach(function(image) {
if (util.isArray(image.scores))
image.scores = image.scores.filter(function (score) {
// IBM's classifiers have the id = name
return (score.classifier_id === score.name) ||
(ids.indexOf(score.classifier_id) !== -1);
});
});
}
return result;
} |
JavaScript | function normalizeResult(item) {
var result = {
name: item.text || 'Unknown',
score: parseFloat(item.score || '0')
};
return result;
} | function normalizeResult(item) {
var result = {
name: item.text || 'Unknown',
score: parseFloat(item.score || '0')
};
return result;
} |
JavaScript | function formatAlchemyVisionResults(results) {
return {
images: [{
scores: results.imageKeywords.map(normalizeResult).filter(noTags)
}]
};
} | function formatAlchemyVisionResults(results) {
return {
images: [{
scores: results.imageKeywords.map(normalizeResult).filter(noTags)
}]
};
} |
JavaScript | function landscapify(imgSelector) {
$(imgSelector).on('load', function() {
addLandscape(this);
}).each(function() {
if (this.complete)
$(this).load();
});
} | function landscapify(imgSelector) {
$(imgSelector).on('load', function() {
addLandscape(this);
}).each(function() {
if (this.complete)
$(this).load();
});
} |
JavaScript | function nextHour() {
var oneHour = new Date();
oneHour.setHours(oneHour.getHours() + 1);
return oneHour;
} | function nextHour() {
var oneHour = new Date();
oneHour.setHours(oneHour.getHours() + 1);
return oneHour;
} |
JavaScript | function showResult(results) {
$loading.hide();
$error.hide();
if (!results || !results.images || !results.images[0]) {
showError('Error processing the request, please try again later.');
return;
}
var scores = results.images[0].scores;
if (!scores || scores.length === 0) {
var message = $('.test--classifier-name').length === 0 ?
'The image could not be classified' :
'This image is not a match for ' + $('.test--classifier-name').text();
if ($('#test').hasClass('active'))
message = 'Not a positive match for ' + $('.test--classifier-name').text() +
' with a confidence above 50%';
$tbody.html(
'<tr class="base--tr use--output-tr" >' +
'<td class="base--td use--output-td">' +
message +
'</td>' +
'</tr>');
} else {
populateTable(scores);
}
$result.show();
scrollToElement($result);
} | function showResult(results) {
$loading.hide();
$error.hide();
if (!results || !results.images || !results.images[0]) {
showError('Error processing the request, please try again later.');
return;
}
var scores = results.images[0].scores;
if (!scores || scores.length === 0) {
var message = $('.test--classifier-name').length === 0 ?
'The image could not be classified' :
'This image is not a match for ' + $('.test--classifier-name').text();
if ($('#test').hasClass('active'))
message = 'Not a positive match for ' + $('.test--classifier-name').text() +
' with a confidence above 50%';
$tbody.html(
'<tr class="base--tr use--output-tr" >' +
'<td class="base--td use--output-td">' +
message +
'</td>' +
'</tr>');
} else {
populateTable(scores);
}
$result.show();
scrollToElement($result);
} |
JavaScript | function populateTable(classifiers) {
var top5 = classifiers.slice(0, Math.min(5, classifiers.length));
$tbody.html(top5.map(function rowFromClassifier(c) {
return '<tr class="base--tr use--output-tr" >' +
'<td class="base--td use--output-td">' +
c.name +
'</td>' +
'<td class="base--td use--output-td ' +
(c.score > 0.70 ? 'use--output-td_positive' : 'use--output-td_medium') + '">' +
percentagify(c.score) + '% </td>' +
'</tr>';
}).join(''));
} | function populateTable(classifiers) {
var top5 = classifiers.slice(0, Math.min(5, classifiers.length));
$tbody.html(top5.map(function rowFromClassifier(c) {
return '<tr class="base--tr use--output-tr" >' +
'<td class="base--td use--output-td">' +
c.name +
'</td>' +
'<td class="base--td use--output-td ' +
(c.score > 0.70 ? 'use--output-td_positive' : 'use--output-td_medium') + '">' +
percentagify(c.score) + '% </td>' +
'</tr>';
}).join(''));
} |
JavaScript | function imageExists(url, callback) {
var img = new Image();
img.onload = function() {
callback(true);
};
img.onerror = function() {
callback(false);
};
img.src = url;
} | function imageExists(url, callback) {
var img = new Image();
img.onload = function() {
callback(true);
};
img.onerror = function() {
callback(false);
};
img.src = url;
} |
JavaScript | restoreDefaultBinding() {
this.controlPlayButton.onclick = () => {
this.playerState.buttonWasClicked();
};
this.replayButton.onclick = null;
this.playerLayer.onclick = () => {
this.playerState.buttonWasClicked();
};
if(YangPlayer_GLOBAL.isFullscreen) {
document.onkeydown = (event) => {
let keyCode = event.key || event.keyCode; // be careful that `event.keyCode` has been removed from the Web standards
if(keyCode === ' ' || keyCode === 32) { // the Unicode vaule of `Space`
this.playerState.buttonWasClicked();
}
};
}
} | restoreDefaultBinding() {
this.controlPlayButton.onclick = () => {
this.playerState.buttonWasClicked();
};
this.replayButton.onclick = null;
this.playerLayer.onclick = () => {
this.playerState.buttonWasClicked();
};
if(YangPlayer_GLOBAL.isFullscreen) {
document.onkeydown = (event) => {
let keyCode = event.key || event.keyCode; // be careful that `event.keyCode` has been removed from the Web standards
if(keyCode === ' ' || keyCode === 32) { // the Unicode vaule of `Space`
this.playerState.buttonWasClicked();
}
};
}
} |
JavaScript | notOverControlBar() {
this.controlBar.onmouseover = () => {
this.controlBar.style.opacity = 1;
};
this.controlBar.onmouseout = () => {
this.controlBar.style.opacity = 0;
};
} | notOverControlBar() {
this.controlBar.onmouseover = () => {
this.controlBar.style.opacity = 1;
};
this.controlBar.onmouseout = () => {
this.controlBar.style.opacity = 0;
};
} |
JavaScript | controlContinueBulletScreen() {
if(this.ifPauseBulletScreen) {
for(let userId in this.userIdCollection) {
this.ifPauseBulletScreen = false;
if(Utility.hasClass('YangPlayer-bulletScreen-move', this.userIdCollection[userId])) {
let itemRect = Utility.getOffsetAndLength(this.userIdCollection[userId]);
let transition = (itemRect.offsetLeft + itemRect.width + this.bulletScreenSpace) * this.transitionRateScale;
let translateX;
// solve the bug of method `window.getComputedStyle` in Safari
// find more info here: [http://stackoverflow.com/questions/22034989/is-there-a-bug-in-safari-with-getcomputedstyle]
if(Utility.isWhichBrowser('Safari')) {
translateX = (-Number.parseInt(window.getComputedStyle(this.userIdCollection[userId]).right)) + itemRect.parentWidth + this.bulletScreenSpace;
}
else {
translateX = Number.parseInt(window.getComputedStyle(this.userIdCollection[userId]).left) + itemRect.width + this.bulletScreenSpace;
}
this.userIdCollection[userId].style.cssText += `transition: transform ${transition}s linear; transform: translateX(-${translateX}px)`;
}
if(Utility.hasClass('YangPlayer-bulletScreen-top', this.userIdCollection[userId])) {
let timeoutFunc = () => {
if(this.userIdCollection[userId]) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
}
delete this.userIdCollection[userId];
delete this.timeoutIdCollection[userId];
};
this.timeoutId = window.setTimeout(timeoutFunc, 1000);
this.timeoutIdCollection[userId] = this.timeoutId;
}
}
}
} | controlContinueBulletScreen() {
if(this.ifPauseBulletScreen) {
for(let userId in this.userIdCollection) {
this.ifPauseBulletScreen = false;
if(Utility.hasClass('YangPlayer-bulletScreen-move', this.userIdCollection[userId])) {
let itemRect = Utility.getOffsetAndLength(this.userIdCollection[userId]);
let transition = (itemRect.offsetLeft + itemRect.width + this.bulletScreenSpace) * this.transitionRateScale;
let translateX;
// solve the bug of method `window.getComputedStyle` in Safari
// find more info here: [http://stackoverflow.com/questions/22034989/is-there-a-bug-in-safari-with-getcomputedstyle]
if(Utility.isWhichBrowser('Safari')) {
translateX = (-Number.parseInt(window.getComputedStyle(this.userIdCollection[userId]).right)) + itemRect.parentWidth + this.bulletScreenSpace;
}
else {
translateX = Number.parseInt(window.getComputedStyle(this.userIdCollection[userId]).left) + itemRect.width + this.bulletScreenSpace;
}
this.userIdCollection[userId].style.cssText += `transition: transform ${transition}s linear; transform: translateX(-${translateX}px)`;
}
if(Utility.hasClass('YangPlayer-bulletScreen-top', this.userIdCollection[userId])) {
let timeoutFunc = () => {
if(this.userIdCollection[userId]) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
}
delete this.userIdCollection[userId];
delete this.timeoutIdCollection[userId];
};
this.timeoutId = window.setTimeout(timeoutFunc, 1000);
this.timeoutIdCollection[userId] = this.timeoutId;
}
}
}
} |
JavaScript | removeMovingBulletScreen() {
let itemRect, canRemoveMovingBulletScreen;
for(let userId in this.userIdCollection) {
itemRect = Utility.getOffsetAndLength(this.userIdCollection[userId]);
canRemoveMovingBulletScreen = Utility.hasClass('YangPlayer-bulletScreen-move', this.userIdCollection[userId]) && itemRect.offsetRight >= itemRect.parentWidth;
if(canRemoveMovingBulletScreen) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
delete this.userIdCollection[userId];
}
}
} | removeMovingBulletScreen() {
let itemRect, canRemoveMovingBulletScreen;
for(let userId in this.userIdCollection) {
itemRect = Utility.getOffsetAndLength(this.userIdCollection[userId]);
canRemoveMovingBulletScreen = Utility.hasClass('YangPlayer-bulletScreen-move', this.userIdCollection[userId]) && itemRect.offsetRight >= itemRect.parentWidth;
if(canRemoveMovingBulletScreen) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
delete this.userIdCollection[userId];
}
}
} |
JavaScript | removeAllBulletScreen() {
window.clearInterval(this.intervalId);
this.intervalId = null;
for(let userId in this.userIdCollection) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
window.clearTimeout(this.timeoutIdCollection[userId]);
delete this.userIdCollection[userId];
delete this.timeoutIdCollection[userId];
}
} | removeAllBulletScreen() {
window.clearInterval(this.intervalId);
this.intervalId = null;
for(let userId in this.userIdCollection) {
this.userIdCollection[userId].parentNode.removeChild(this.userIdCollection[userId]);
window.clearTimeout(this.timeoutIdCollection[userId]);
delete this.userIdCollection[userId];
delete this.timeoutIdCollection[userId];
}
} |
JavaScript | function _createSafeReference(type, prefix, arg) {
// For security reasons related to innerHTML, we ensure this string only
// contains potential entity characters
if (!arg.match(/^[0-9A-Z_a-z]+$/)) {
throw new TypeError('Bad ' + type);
}
var elContainer = doc.createElement('div'); // Todo: No workaround for XML?
// eslint-disable-next-line no-unsanitized/property
elContainer.textContent = '&' + prefix + arg + ';';
return doc.createTextNode(elContainer.textContent);
} | function _createSafeReference(type, prefix, arg) {
// For security reasons related to innerHTML, we ensure this string only
// contains potential entity characters
if (!arg.match(/^[0-9A-Z_a-z]+$/)) {
throw new TypeError('Bad ' + type);
}
var elContainer = doc.createElement('div'); // Todo: No workaround for XML?
// eslint-disable-next-line no-unsanitized/property
elContainer.textContent = '&' + prefix + arg + ';';
return doc.createTextNode(elContainer.textContent);
} |
JavaScript | static loaded(block) {
var il = new _fpa_admin.all.index_page(block)
il.setup_shrinkable_blocks()
il.handle_filter_selections();
} | static loaded(block) {
var il = new _fpa_admin.all.index_page(block)
il.setup_shrinkable_blocks()
il.handle_filter_selections();
} |
JavaScript | set disabled(val) {
if (this.def_block.default) return
if (val) this.def_block.disabled, false
} | set disabled(val) {
if (this.def_block.default) return
if (val) this.def_block.disabled, false
} |
JavaScript | _upgradeProperty(prop) {
if (this.hasOwnProperty(prop)) {
let value = this[prop];
delete this[prop];
this[prop] = value;
}
} | _upgradeProperty(prop) {
if (this.hasOwnProperty(prop)) {
let value = this[prop];
delete this[prop];
this[prop] = value;
}
} |
JavaScript | function* loginAsync() {
yield put(loginActions.enableLoader());
//how to call api
//const response = yield call(loginUser, action.username, action.password);
//mock response
const response = { success: true, data: { id: 1 } };
if (response.success) {
yield put(loginActions.onLoginResponse(response.data));
yield put(loginActions.disableLoader({}));
// no need to call navigate as this is handled by redux store with SwitchNavigator
//yield call(navigationActions.navigateToHome);
} else {
yield put(loginActions.loginFailed());
yield put(loginActions.disableLoader({}));
setTimeout(() => {
Alert.alert('BoilerPlate', response.Message);
}, 200);
}
} | function* loginAsync() {
yield put(loginActions.enableLoader());
//how to call api
//const response = yield call(loginUser, action.username, action.password);
//mock response
const response = { success: true, data: { id: 1 } };
if (response.success) {
yield put(loginActions.onLoginResponse(response.data));
yield put(loginActions.disableLoader({}));
// no need to call navigate as this is handled by redux store with SwitchNavigator
//yield call(navigationActions.navigateToHome);
} else {
yield put(loginActions.loginFailed());
yield put(loginActions.disableLoader({}));
setTimeout(() => {
Alert.alert('BoilerPlate', response.Message);
}, 200);
}
} |
JavaScript | halmaOnClick(event) {
let cell = this.#getCursorPosition(event);
for (let i = 0; i < this.#gNumPieces; i++) {
if ((this.#gPieces[i].getrow() === cell.getrow()) &&
(this.#gPieces[i].getcolumn() === cell.getcolumn())) {
this.#clickOnPiece(i);
return;
}
}
this.#clickOnEmptyCell(cell);
} | halmaOnClick(event) {
let cell = this.#getCursorPosition(event);
for (let i = 0; i < this.#gNumPieces; i++) {
if ((this.#gPieces[i].getrow() === cell.getrow()) &&
(this.#gPieces[i].getcolumn() === cell.getcolumn())) {
this.#clickOnPiece(i);
return;
}
}
this.#clickOnEmptyCell(cell);
} |
JavaScript | isThereAPieceBetween(cell1, cell2) {
let rowBetween = (cell1.getrow() + cell2.getrow()) / 2;
let columnBetween = (cell1.getcolumn() + cell2.getcolumn()) / 2;
for (let i = 0; i < this.#gNumPieces; i++) {
if ((this.#gPieces[i].getrow() == rowBetween) &&
(this.#gPieces[i].getcolumn() == columnBetween)) {
return true;
}
}
return false;
} | isThereAPieceBetween(cell1, cell2) {
let rowBetween = (cell1.getrow() + cell2.getrow()) / 2;
let columnBetween = (cell1.getcolumn() + cell2.getcolumn()) / 2;
for (let i = 0; i < this.#gNumPieces; i++) {
if ((this.#gPieces[i].getrow() == rowBetween) &&
(this.#gPieces[i].getcolumn() == columnBetween)) {
return true;
}
}
return false;
} |
JavaScript | isGameOver() {
for (let i = 0; i < this.#gPieces.length; i++) {
if (this.#gPieces[i].getrow() > 2) {
return false;
}
if (this.#gPieces[i].getcolumn() < (this.#SIZE- 3)) {
return false;
}
}
return true;
} | isGameOver() {
for (let i = 0; i < this.#gPieces.length; i++) {
if (this.#gPieces[i].getrow() > 2) {
return false;
}
if (this.#gPieces[i].getcolumn() < (this.#SIZE- 3)) {
return false;
}
}
return true;
} |
JavaScript | drawBoard() {
let game = 'Game in progress';
if (this.#model.isGameOver() && this.#gameInProgress) {
this.#selected = -1;
this.#gameInProgress = false;
game = 'Game over';
} else {
this.#gameInProgress = true;
}
this.#ctx.clearRect(0, 0, this.#PIXELWIDTH, this.#PIXELHEIGHT);
this.#ctx.beginPath();
for (let x = 0; x <= this.#PIXELWIDTH; x += this.#PIECEWIDTH) {
this.#ctx.moveTo(0.5 + x, 0);
this.#ctx.lineTo(0.5 + x, this.#PIXELHEIGHT);
}
for (let y = 0; y <= this.#PIXELHEIGHT; y += this.#PIECEHEIGHT) {
this.#ctx.moveTo(0, 0.5 + y);
this.#ctx.lineTo(this.#PIXELWIDTH, 0.5 + y);
}
this.#ctx.strokeStyle = 'black';
this.#ctx.stroke();
for (let i = 0; i < this.#gPieces.length; i++) {
this.#drawPiece(this.#gPieces[i], i == this.#selected);
}
let moves = 'Number of moves: ' + this.#gMoveCount;
this.#gMoveElement.textContent = moves;
this.#progress.textContent = game;
} | drawBoard() {
let game = 'Game in progress';
if (this.#model.isGameOver() && this.#gameInProgress) {
this.#selected = -1;
this.#gameInProgress = false;
game = 'Game over';
} else {
this.#gameInProgress = true;
}
this.#ctx.clearRect(0, 0, this.#PIXELWIDTH, this.#PIXELHEIGHT);
this.#ctx.beginPath();
for (let x = 0; x <= this.#PIXELWIDTH; x += this.#PIECEWIDTH) {
this.#ctx.moveTo(0.5 + x, 0);
this.#ctx.lineTo(0.5 + x, this.#PIXELHEIGHT);
}
for (let y = 0; y <= this.#PIXELHEIGHT; y += this.#PIECEHEIGHT) {
this.#ctx.moveTo(0, 0.5 + y);
this.#ctx.lineTo(this.#PIXELWIDTH, 0.5 + y);
}
this.#ctx.strokeStyle = 'black';
this.#ctx.stroke();
for (let i = 0; i < this.#gPieces.length; i++) {
this.#drawPiece(this.#gPieces[i], i == this.#selected);
}
let moves = 'Number of moves: ' + this.#gMoveCount;
this.#gMoveElement.textContent = moves;
this.#progress.textContent = game;
} |
JavaScript | isThereAPieceBetween(cell1, cell2) {
let rowBetween = (cell1.getrow() + cell2.getrow()) / 2;
let columnBetween = (cell1.getcolumn() + cell2.getcolumn()) / 2;
for (let i = 0; i < this.#gPieces.length; i++) {
if ((this.#gPieces[i].getrow() == rowBetween) &&
(this.#gPieces[i].getcolumn() == columnBetween)) {
return true;
}
}
return false;
} | isThereAPieceBetween(cell1, cell2) {
let rowBetween = (cell1.getrow() + cell2.getrow()) / 2;
let columnBetween = (cell1.getcolumn() + cell2.getcolumn()) / 2;
for (let i = 0; i < this.#gPieces.length; i++) {
if ((this.#gPieces[i].getrow() == rowBetween) &&
(this.#gPieces[i].getcolumn() == columnBetween)) {
return true;
}
}
return false;
} |
JavaScript | isGameOver() {
for (let i = 0; i < this.#gPieces.length; i++) {
if (this.#gPieces[i].getrow() > 2) {
return false;
}
if (this.#gPieces[i].getcolumn() < 6) {
return false;
}
}
return true;
} | isGameOver() {
for (let i = 0; i < this.#gPieces.length; i++) {
if (this.#gPieces[i].getrow() > 2) {
return false;
}
if (this.#gPieces[i].getcolumn() < 6) {
return false;
}
}
return true;
} |
JavaScript | function renameFiles(names) {
const countName = {};
for (let index = 0; index < names.length; index++) {
const name = names[index];
if (countName.hasOwnProperty(name)) {
names[index] = names[index] + `(${countName[name]})`;
countName[names[index]] = 1;
countName[name] = countName[name] + 1;
} else {
countName[name] = 1;
}
}
return names;
} | function renameFiles(names) {
const countName = {};
for (let index = 0; index < names.length; index++) {
const name = names[index];
if (countName.hasOwnProperty(name)) {
names[index] = names[index] + `(${countName[name]})`;
countName[names[index]] = 1;
countName[name] = countName[name] + 1;
} else {
countName[name] = 1;
}
}
return names;
} |
JavaScript | function minesweeper(matrix) {
const board = matrix.reduce(function (newMatrix, itemArr, i) {
newMatrix.push(
itemArr.reduce(function (row, item, j, rowMatrix) {
let countMine = 0;
if (i - 1 > -1) {
if (j - 1 > -1) {
countMine = countMine + (matrix[i - 1][j - 1] ? 1 : 0);
}
countMine = countMine + (matrix[i - 1][j] ? 1 : 0);
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i - 1][j + 1] ? 1 : 0);
}
}
if (j - 1 > -1) {
countMine = countMine + (matrix[i][j - 1] ? 1 : 0);
}
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i][j + 1] ? 1 : 0);
}
if (i + 1 < matrix.length) {
if (j - 1 > -1) {
countMine = countMine + (matrix[i + 1][j - 1] ? 1 : 0);
}
countMine = countMine + (matrix[i + 1][j] ? 1 : 0);
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i + 1][j + 1] ? 1 : 0);
}
}
row.push(countMine);
return row;
}, [])
);
return newMatrix;
}, []);
return board;
} | function minesweeper(matrix) {
const board = matrix.reduce(function (newMatrix, itemArr, i) {
newMatrix.push(
itemArr.reduce(function (row, item, j, rowMatrix) {
let countMine = 0;
if (i - 1 > -1) {
if (j - 1 > -1) {
countMine = countMine + (matrix[i - 1][j - 1] ? 1 : 0);
}
countMine = countMine + (matrix[i - 1][j] ? 1 : 0);
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i - 1][j + 1] ? 1 : 0);
}
}
if (j - 1 > -1) {
countMine = countMine + (matrix[i][j - 1] ? 1 : 0);
}
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i][j + 1] ? 1 : 0);
}
if (i + 1 < matrix.length) {
if (j - 1 > -1) {
countMine = countMine + (matrix[i + 1][j - 1] ? 1 : 0);
}
countMine = countMine + (matrix[i + 1][j] ? 1 : 0);
if (j + 1 < rowMatrix.length) {
countMine = countMine + (matrix[i + 1][j + 1] ? 1 : 0);
}
}
row.push(countMine);
return row;
}, [])
);
return newMatrix;
}, []);
return board;
} |
JavaScript | function createDreamTeam(members) {
function isNan(value) {
return value !== value;
}
if (members === null || members === undefined || isNan(members)) {
return false;
}
if (members.constructor !== Array) {
return false;
}
let array = members.filter((item) => typeof item === "string");
for (let index = 0; index < array.length; index++) {
array[index] = array[index].trim().toUpperCase();
}
array.sort();
let result = "";
for (let index = 0; index < array.length; index++) {
result = `${result}${array[index][0]}`;
}
return result;
} | function createDreamTeam(members) {
function isNan(value) {
return value !== value;
}
if (members === null || members === undefined || isNan(members)) {
return false;
}
if (members.constructor !== Array) {
return false;
}
let array = members.filter((item) => typeof item === "string");
for (let index = 0; index < array.length; index++) {
array[index] = array[index].trim().toUpperCase();
}
array.sort();
let result = "";
for (let index = 0; index < array.length; index++) {
result = `${result}${array[index][0]}`;
}
return result;
} |
JavaScript | function _setTable(data) {
var self = this;
table = data;
return self;
} | function _setTable(data) {
var self = this;
table = data;
return self;
} |
JavaScript | function debug() {
if (!debugAllowed) {
return;
}
const manifest = runtime.getManifest();
const prefix = `[${manifest.name}]`;
console.log(prefix, ...arguments);
} | function debug() {
if (!debugAllowed) {
return;
}
const manifest = runtime.getManifest();
const prefix = `[${manifest.name}]`;
console.log(prefix, ...arguments);
} |
JavaScript | function touchMove(event) {
if (defaults.preventDefaultEvents) {
event.preventDefault();
};
finalCoord.x = event.targetTouches[0].pageX; // Updated X,Y coordinates
finalCoord.y = event.targetTouches[0].pageY;
} | function touchMove(event) {
if (defaults.preventDefaultEvents) {
event.preventDefault();
};
finalCoord.x = event.targetTouches[0].pageX; // Updated X,Y coordinates
finalCoord.y = event.targetTouches[0].pageY;
} |
JavaScript | function touchEnd(event) {
var changeY = originalCoord.y - finalCoord.y;
if (changeY < defaults.threshold.y && changeY > (defaults.threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x;
if (changeX > defaults.threshold.x) {
defaults.swipeLeft();
};
if (changeX < (defaults.threshold.x * -1)) {
defaults.swipeRight();
};
};
} | function touchEnd(event) {
var changeY = originalCoord.y - finalCoord.y;
if (changeY < defaults.threshold.y && changeY > (defaults.threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x;
if (changeX > defaults.threshold.x) {
defaults.swipeLeft();
};
if (changeX < (defaults.threshold.x * -1)) {
defaults.swipeRight();
};
};
} |
JavaScript | _save() {
const value = this.state.value;
const string = value.charAt(0).toUpperCase() + value.slice(1);
this.props.onSave(string, this.props.group);
this.setState({
value: '',
});
} | _save() {
const value = this.state.value;
const string = value.charAt(0).toUpperCase() + value.slice(1);
this.props.onSave(string, this.props.group);
this.setState({
value: '',
});
} |
JavaScript | render() {
return (
<input
className="user-input"
id={this.props.id}
placeholder={this.props.placeholder}
onBlur={this._save}
onChange={this._onChange}
onKeyDown={this._onKeyDown}
value={this.state.value}
group={this.props.group}
autoFocus
/>
);
} | render() {
return (
<input
className="user-input"
id={this.props.id}
placeholder={this.props.placeholder}
onBlur={this._save}
onChange={this._onChange}
onKeyDown={this._onKeyDown}
value={this.state.value}
group={this.props.group}
autoFocus
/>
);
} |
JavaScript | function create(text) {
const id = text; // Unique stuff, so no need to actually use that awful (default) id generator of the starter kit
if (!_.find(_groups, (group) => group.text === text)) {
_groups[id] = {
id: id,
users: [],
text: text,
};
// else {return error and handle on frontend (this is replacing the API) }
}
} | function create(text) {
const id = text; // Unique stuff, so no need to actually use that awful (default) id generator of the starter kit
if (!_.find(_groups, (group) => group.text === text)) {
_groups[id] = {
id: id,
users: [],
text: text,
};
// else {return error and handle on frontend (this is replacing the API) }
}
} |
JavaScript | function updateAll(updates) {
for (const id in _groups) {
if (_groups.hasOwnProperty(id)) {
update(id, updates);
}
}
} | function updateAll(updates) {
for (const id in _groups) {
if (_groups.hasOwnProperty(id)) {
update(id, updates);
}
}
} |
JavaScript | _save() {
const value = this.state.value;
const string = value.charAt(0).toUpperCase() + value.slice(1);
this.props.onSave(string, this.state.group);
this.setState({
value: '',
group: this.state.group,
});
} | _save() {
const value = this.state.value;
const string = value.charAt(0).toUpperCase() + value.slice(1);
this.props.onSave(string, this.state.group);
this.setState({
value: '',
group: this.state.group,
});
} |
JavaScript | render() {
return (
<input
className="group-input"
id={this.props.id}
placeholder={this.props.placeholder}
onBlur={this._save}
onChange={this._onChange}
onKeyDown={this._onKeyDown}
value={this.state.value}
autoFocus={true}
/>
);
} | render() {
return (
<input
className="group-input"
id={this.props.id}
placeholder={this.props.placeholder}
onBlur={this._save}
onChange={this._onChange}
onKeyDown={this._onKeyDown}
value={this.state.value}
autoFocus={true}
/>
);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.