rotating text with fade-in - text

I currently have this code for displaying random customer testimonials.
I would like to replace the random function with a code that will display the quotes by their order and then repeat them.
<html style="direction:rtl;">
<DIV id=textrotator style="FONT: 16px arial ; text-align:right; WIDTH: 100%; COLOR: rgb(255,255,255)"></DIV>
<body bgcolor="#FFFFFF" alink="#FFFFFF" vlink="#FFFFFF" topmargin="0" leftmargin="0" rightmargin="0">
<script type = "text/javascript">
var hexinput = 255; // initial color value.
quotation = new Array()
quotation[0] = "text1"
quotation[1] = "text2"
quotation[2] = "text3"
function fadingtext()
{
if(hexinput >111)
{
hexinput -=11; // increase color value
document.getElementById("textrotator").style.color="rgb("+hexinput+","+hexinput+","+hexinput+")"; // Set color value.
setTimeout("fadingtext()",200); // 200ms per step
}
else
{
hexinput = 255; //reset hex value
}
}
function changetext()
{
if(!document.getElementById){return}
var which = Math.round(Math.random()*(quotation.length - 1));
document.getElementById("textrotator").innerHTML = quotation[which];
fadingtext();
setTimeout("changetext()",8000);
}
window.onload = changetext();
</script>

You need to make your index global. Throw which outside of the function and then just increment it, make sure to wrap when you get to the end.
This is the replacement for the "changetext" function:
var which = 0;
function changetext()
{
which += 1;
if (which >= quotation.length)
{
which = 0;
}
document.getElementById("textrotator").innerHTML = quotation[which];
fadingtext();
setTimeout("changetext()",8000);
}

Related

transferring the remained array objects from one component to the other during mapping of an array

i have an array of objects in react i want to map these object on a first component in react but i fixed the height of first component to 300px when the array size complete i want to shift the remain objects to the second component and map the remained objects in the second component please help.
let arrayOfObjects = [{title: "karim"}, {title:"fawad"},{title: "karim"}, {title:"fawad"},{title: "karim"}, {title:"fawad"},{title: "karim"}, {title:"fawad"}];
let firstComponent = <div height="300px">
arrayOfObjects.map(e)=><div height="100px">{e.title}</div>
</div>;
let secountComponent = <div height="300px"></div>
Couldn't you just do the math before you use map to calculate the number of objects you want to select from the array, and then use slice?
So instead of
arrayOfObjects.map(e)=><div height="100px">{e.title}</div>
Do this
arrayOfObjects.slice(0,3).map(e)=><div height="100px">{e.title}</div>
and then use slice again to put the remaining data in a separate component.
arrayOfObjects.slice(3).map(e)=><div height="100px">{e.title}</div>
You could even calculate the values for slice programmatically, and replace the value 3 with the value of the first component height, divided by the height of each title
By the way, I think you need to put the map function into curly brackets {} in order for the JSX to render correctly, otherwise it will just print the text of your function.
You can slice an array and place each sublist in
separate component
--Edit
As items might have different height and a different approach is needed.
That means items should be grouped into chunks as long as their sum height doesn't exceed specified value.
Example
let arrayOfObjects = [{
title: "karim"
}, {
title: "fawad"
}, {
title: "karim"
}, {
title: "fawad"
}, {
title: "karim"
}, {
title: "fawad"
}, {
title: "karim"
}, {
title: "fawad"
}];
const random = (from, to) => Math.floor(Math.random() * (to - from) + from);
const randomStyle = () => {
return {
height: random(70, 130),
background: `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`
}
}
arrayOfObjects = arrayOfObjects.map(pr => ({...pr, style: randomStyle()}));
const FixedComponent = ({height, items}) => {
const computedHeight = `${height}px`;
return <div className="fixed" style={{height: computedHeight}}>
{items.map(({title, style}, id) => <div className="item" key={id} style={style}>{title}</div>)}
</div>
}
const App = () => {
const [items, setItems] = React.useState([]);
React.useEffect(() => {
setItems(arrayOfObjects);
},[]);
const renderComponents = function*() {
let bucket = [];
let sumOfHeights = 0;
const maxHeight = 300;
let id = 1;
for(let item of items) {
const height = item.style.height;
if(maxHeight > sumOfHeights + height) {
bucket = [...bucket, item];
sumOfHeights = sumOfHeights + height;
continue;
}
const items = [...bucket];
yield (<FixedComponent key={id} height={maxHeight} items={items}></FixedComponent>);
bucket = [];
id = id + 1;
sumOfHeights = 0;
}
id = id + 1;
yield (<FixedComponent key={id} height={maxHeight} items={bucket}></FixedComponent>);
}
return <div>
{[...renderComponents()]}
</div>
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);
html, body {
margin: 0;
box-sizing: border-box;
}
.fixed {
padding: .5rem;
border: 1px solid black;
}
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.8.7/polyfill.js"></script>
<div id="root"></div>

How to print all the tasks in AnyGantt

I am printing the AnyGantt chart using the print API, but all I can print is the part I am viewing, kind of a snapshot of the current screen.
Is there an option to somehow print all the items present in the gantt (at least vertically, something like scrolling down the chart and capturing all the items, event if they are not visible at the moment) in the visible time range?
Thank you.
This can be implemented with a few code tricks. The idea is to expand the chart's div container to show all existing rows in gantt chart, then print it, and finally collapse the container's div back. Unfortunately, there's no other solution for this now. The snippet below may not work in stackoverflow playground. I will leave a link to the same sample in AnyChart Playground which provides printing features.
anychart.onDocumentReady(function () {
// The data used in this sample can be obtained from the CDN
// https://cdn.anychart.com/samples/gantt-charts/activity-oriented-chart/data.js
anychart.data.loadJsonFile('https://cdn.anychart.com/samples/gantt-charts/activity-oriented-chart/data.json', function (data) {
var stage = anychart.graphics.create("container");
// create data tree
var treeData = anychart.data.tree(data, 'as-table');
// create project gantt chart
var chart = anychart.ganttProject();
// set data for the chart
chart.data(treeData);
// set start splitter position settings
chart.splitterPosition(370);
// get chart data grid link to set column settings
var dataGrid = chart.dataGrid();
// set first column settings
dataGrid.column(0)
.title('#')
.width(30)
.labels({hAlign: 'center'});
// set second column settings
dataGrid.column(1)
.labels()
.hAlign('left')
.width(180);
// set third column settings
dataGrid.column(2)
.title('Start Time')
.width(70)
.labels()
.hAlign('right')
.format(function () {
var date = new Date(this.actualStart);
var month = date.getUTCMonth() + 1;
var strMonth = (month > 9) ? month : '0' + month;
var utcDate = date.getUTCDate();
var strDate = (utcDate > 9) ? utcDate : '0' + utcDate;
return date.getUTCFullYear() + '.' + strMonth + '.' + strDate;
});
// set fourth column settings
dataGrid.column(3)
.title('End Time')
.width(80)
.labels()
.hAlign('right')
.format(function () {
var date = new Date(this.actualEnd);
var month = date.getUTCMonth() + 1;
var strMonth = (month > 9) ? month : '0' + month;
var utcDate = date.getUTCDate();
var strDate = (utcDate > 9) ? utcDate : '0' + utcDate;
return date.getUTCFullYear() + '.' + strMonth + '.' + strDate;
});
// calculate height
var traverser = treeData.getTraverser();
var itemSum = 0;
var rowHeight = chart.defaultRowHeight();
while (traverser.advance()){
if (traverser.get('rowHeight')) {
itemSum += traverser.get('rowHeight');
} else {
itemSum += rowHeight;
}
if (chart.rowStroke().thickness != null) {
itemSum += chart.rowStroke().thickness;
} else {
itemSum += 1;
}
}
itemSum += chart.headerHeight();
//customize printing
var menu = chart.contextMenu();
menu.itemsFormatter(function(items) {
items['print-chart'].action = function() {
document.getElementById('container').style.height = String(itemSum) + 'px';
setTimeout(function() {
chart.print();
setTimeout(function() {
document.getElementById('container').style.height = '100%';
},5000);
},1000);
}
return items;
});
chart.container(stage).draw();
chart.zoomTo(951350400000, 954201600000);
});
});
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<link href="https://cdn.anychart.com/releases/8.2.1/fonts/css/anychart-font.min.css" rel="stylesheet"/>
<link href="https://cdn.anychart.com/releases/8.2.1/css/anychart-ui.min.css" rel="stylesheet"/>
<script src="https://cdn.anychart.com/releases/8.2.1/js/anychart-bundle.min.js"></script>
<div id="container"></div>
We are glad to notify that we have created a JS module for printing large Gantt charts. You can get the link to the module and sample of using it in the comment below.
This module exports enableLargeGanttPrint({Object: chart}) function, which gets the chart instance and implements printing functionality. To print the chart executes right mouse click on the chart and choose 'print' option. This will call standard browser print for prepared Gantt chart.

Grunt insert string after pattern in file

I'm building a custom task for grunt that finds a particular font, and basically outputs a definition that uses a PHP variable for configuring that particular font.
It uses underscore and postcss.
It groups all CSS selectors that use that font, and outputs a string similar to this one:
selector1, selector2, selector3 {
font-family: <?php echo $font_1 ?>, Font 2, Font 3, Font 4;
}
Here is the code for the custom task:
// Extract configurable font data
// ======================================================================
grunt.registerTask('extractfontdata', 'Extract configurable properties', function () {
console.log('Extracting configurable font data');
var match = /Myriad Pro/gim;
var contents = grunt.file.read('assets/css/leadscon.css');
var css = postcss(function (css) {
var findings = {};
css.eachDecl(function (decl) {
if (decl.value.match( match ) && decl.parent.selector !== undefined) {
var fonts = decl.value.replace(/(\r\n|\n|\r|"|')/gm, "").split(',');
var prop = _.find(fonts, function(font) { return font.match(match) });
var finding = findings[ prop ] = findings[ prop ] || {};
finding.selectors = finding.selectors || [];
finding.fontstack = finding.fontstack || [];
finding.selectors.push( decl.parent.selector.replace(/(\r\n|\n|\r|"|'|\s)/gm, "").split(',') );
finding.fontstack.push( fonts );
finding.selectors = _(finding.selectors).chain().flatten().uniq().value();
finding.fontstack = _(finding.fontstack).chain().flatten().uniq().value();
}
});
var result = '';
var j = 0;
for ( var font in findings ) {
findings[font].fontstack.every(function(f, i) {
if (f.match(font)) {
findings[font].fontstack[i] = '<?php echo $font_' + j++ + ' ?>';
}
});
result += findings[font].selectors.join(',') + ' { font-family: ' + findings[font].fontstack.join(',') + ' } ';
}
console.log(result);
// Now insert result into header.php
}).process(contents);
});
This currently, will set result to:
body,.footer-widget.widget_nav_menu.widget-title
{
font-family: <?php echo $font_0 ?>, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6,.widget.widget-title,.widget_lc_cta,.header-widget.widget_lc_events.events,.widget_accordion_widget.accordion-widget.resp-tabs-container>.resp-accordion,article.single>.article-header.breadcrumbs,article.single>.article-header.meta
{
font-family: <?php echo $font_1 ?>, Open Sans Condensed, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
I've added this code to header.php:
<style>
/* extractfontdata */
</style>
Now, how do I find the string "extractfontdata" in header.php, and insert result after it?
Well in case anyone is wondering, this worked for me:
// Now insert result into header.php
var header = grunt.file.read('header.php').split('\n');
var line_1 = _.indexOf(header, _(header).find(function(el) { return el.match(/extractfontdata/i) }) );
var line_2 = _.indexOf(header, _(header).find(function(el) { return el.match(/endextractfontdata/i) }));
var start = Math.min(line_1, line_2) + 1;
var end = Math.max(line_1, line_2);
var num = Math.min((end - start), 0);
header.splice(start, num, result);
for ( var i = start-2; i <= end+2; i++) {
console.log(header[i]);
}
grunt.file.write('header.php', header.join('\n'));

Given a polygon in latitude and longitude and a set of points, determine which points lie inside

Given a set of latlon points that make up a polygon, and a set of latlon points, how can I determine which points lie inside. The polygon may be up to 100km across and the error could be a few hundred meters (i.e. points inside or outside can fail or be included incorrectly at the edges). The polygons and points won't be near the poles. Can I treat the latlon points as 2d, or do I need to convert them to a projection of some kind? Circles are easy but I wonder if the error will be too great for a 100km wide polygon?
I plan to do this in C++ but the language doesn't matter.
Here is the (javascript) code from Openlayers to do it
/**
* Method: containsPoint
* Test if a point is inside a polygon. Points on a polygon edge are
* considered inside.
*
* Parameters:
* point - {<OpenLayers.Geometry.Point>}
*
* Returns:
* {Boolean | Number} The point is inside the polygon. Returns 1 if the
* point is on an edge. Returns boolean otherwise.
*/
containsPoint: function(point) {
var numRings = this.components.length;
var contained = false;
if(numRings > 0) {
// check exterior ring - 1 means on edge, boolean otherwise
contained = this.components[0].containsPoint(point);
if(contained !== 1) {
if(contained && numRings > 1) {
// check interior rings
var hole;
for(var i=1; i<numRings; ++i) {
hole = this.components[i].containsPoint(point);
if(hole) {
if(hole === 1) {
// on edge
contained = 1;
} else {
// in hole
contained = false;
}
break;
}
}
}
}
}
return contained;
}
Complete file can be found at Openlayers at Github
To get the idea behind this.components have a look at Collection.js
update:
In OpenLayers a polygon is a collection of linear rings. the containsPoint functon of this can be found at LinearRing.js
You can view actual demo here
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Check If Point Exist in a Polygon - Google Maps API v3</title>
<script type="text/javascript" src="http://www.the-di-lab.com/polygon/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map;
var boundaryPolygon;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(26.038586842564317, 75.06787185438634),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
google.maps.Polygon.prototype.Contains = function (point) {
// ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
var crossings = 0,
path = this.getPath();
// for each edge
for (var i = 0; i < path.getLength() ; i++) {
var a = path.getAt(i),
j = i + 1;
if (j >= path.getLength()) {
j = 0;
}
var b = path.getAt(j);
if (rayCrossesSegment(point, a, b)) {
crossings++;
}
}
// odd number of crossings?
return (crossings % 2 == 1);
function rayCrossesSegment(point, a, b) {
var px = point.lng(),
py = point.lat(),
ax = a.lng(),
ay = a.lat(),
bx = b.lng(),
by = b.lat();
if (ay > by) {
ax = b.lng();
ay = b.lat();
bx = a.lng();
by = a.lat();
}
if (py == ay || py == by) py += 0.00000001;
if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
if (px < Math.min(ax, bx)) return true;
var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
return (blue >= red);
}
};
google.maps.event.addListener(map, 'click', function (event) {
if (boundaryPolygon != null && boundaryPolygon.Contains(event.latLng)) {
alert("in")
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
} else {
alert("out")
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
}
});
}
function drawPolygon() {
initialize();
var boundary = '77.702866 28.987153, 77.699776 28.978594 ,77.735996 28.974164 ,77.719946 28.99346 ,77.713423 28.994361 ,77.711706 28.990382 ';
var boundarydata = new Array();
var latlongs = boundary.split(",");
for (var i = 0; i < latlongs.length; i++) {
latlong = latlongs[i].trim().split(" ");
boundarydata[i] = new google.maps.LatLng(latlong[1], latlong[0]);
}
boundaryPolygon = new google.maps.Polygon({
path: boundarydata,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: 'Red',
fillOpacity: 0.4
});
google.maps.event.addListener(boundaryPolygon, 'click', function (event) {
document.getElementById("spnMsg").innerText = '';
if (boundaryPolygon.Contains(event.latLng)) {
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
} else {
document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
}
});
map.setZoom(14);
map.setCenter(boundarydata[0]);
boundaryPolygon.setMap(map);
}
</script>
</head>
<body onload="initialize();drawPolygon();">
<form id="form1" runat="server">
<h3>Check If Point Exist in a Polygon</h3>
<h3>click on the polygon and out side the polygon for testing</h3>
<span id="spnMsg" style="font-family: Arial; text-align: center; font-size: 14px; color: red;">this is message</span>
<br />
<br />
<div id="map-canvas" style="width: auto; height: 500px;">
</div>
</form>
</body>
</html>
you can view more demos may be use full to you here
http://codeace.in/download/gmap/
you can download all the demo
by click on the file
"googlemap.zip" given in the index

Combining user seleted and auto generated colors in flot

I would like to use both the user selected and auto generated data series coloring in combination such that when a new data series is added colors are auto generated but all other data series already plotted will remain the same color.
When first adding a new data series, I leave the color option empty so that a color is auto assigned.
When re-plotting I extract color information from the an existing plot before re-plotting
I then look at the resulting color map and reassign the same color to the corresponding data series when re-plotting.
The problem is that when I add data series serially in this way with a call to $.plot between each data series addition, I end up with multiple data series assigned to the same color.
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Color Test Harness</title>
<script src="./lib/jquery.js"></script>
<!--[if IE lte 8]><script src="../lib/excanvas.js"></script><![endif]-->
<script src="./lib/jquery.flot.js"></script>
</head>
<body>
<h1>Test graph</h1>
<div id="graph1" style="width:600px;height:300px;"></div>
<script type="text/javascript">
$(function() {
var data = [ [1, 2], [2, 3], [4, 1] ];
var plot = $.plot($("#graph1"), {}, {});
function findColors() {
var c = {};
if(plot != null) {
var series = plot.getData();
for(var i = 0; i < series.length; i++) {
var aSeries = series[i];
c[aSeries.label] = aSeries.color;
}
}
return c;
}
var all_data = [];
for(var i = 0; i < 5; i++) {
var colors = findColors();
var dataObj = { 'label' : "data" + i, 'data' : data };
all_data.push(dataObj);
for(var j = 0; j < all_data.length; j++) {
if(colors.hasOwnProperty(all_data[j].label)) {
all_data[j].color = colors[all_data[j].label];
}
}
plot = $.plot($("#graph1"), all_data, {});
}
})
</script>
</body>
</html>
How can I get the color generator to make sure it uses a color that isn't already pre allocated to one of the other data series?
The colors are just numbers, an index really. So when you are doing the findColors() thing, make an object that tracks which colors are already in use (i.e. right now you have label -> color, also make one that is just color -> 1). Then, later when you are creating new series, have a little function that goes through your colorsUsed object and looks for an unassigned color index:
var colors = findColors();
var colorsUsed = findUsedColors(colors);
function findUsedColors(c){
var cu = {};
$.each(c,function(k,v){
cu[v] = 1;
});
return cu;
}
function findUnassignedColor(cu){
for (var i=0;i<2000;i++){
if (!cu[i]){
cu[i] = 1;
return i;
}
}
}
// then later, when assigning a color
for(var j = 0; j < all_data.length; j++) {
if(colors.hasOwnProperty(all_data[j].label)) {
all_data[j].color = colors[all_data[j].label];
} else {
all_data[j].color = findUnassignedColor(colorsUsed);
}
}

Resources