This uses Wolfram Alpha API to get planes nearby, then display it. How can I remove the plane direction and the phrase 'Slant distance'?
My code (PHP):
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value)
{
echo $key;
foreach($value as $value1){
echo $value1;
echo " ";
}
}
Sample output below:
slant distance ENY flight 3278
14 miles NNW Frontier Airlines flight 72
44 miles N American Airlines flight 1241
15 miles NW American Airlines flight 396
23 miles W Atlantic Southeast Airlines flight 6104
49 miles SSE
What I want it to look like:
Frontier flight 3278
Airlines flight 72
American Airlines flight 1241
American Airlines flight 396
Atlantic Southeast Airlines flight 6104
How's this?
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
You didn't mention the hr's in your desired output but those should be easy enough for you to remove.
Updated (untested because I deleted the file after answering):
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
}
}
?>
olivr3000,
Somehow I did manage to screw up my edit above and didn't include the code that finally worked for my testing.
Here is the code with my edits
You can see it in action at
http://hdreports.com/test/testjson.php
and the source is
http://hdreports.com/test/testjson.txt
Here it is and it works. Sorry for the delay in getting it posted here correctly.
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
echo $key.'<BR>';
}
?>
Olivr3000 here is an update. I tried to edit Chris85 code to post this yesterday but my edit did not get published. I changed the final foreach to output the airline data as you requested
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
}
}
?>
which gives this HTML result
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
American Airlines flight 1046<BR>N929FD<BR>
ENY flight 3238<BR>
Southwest Airlines flight 2477<BR>
American Airlines flight 2352<BR>
Your data structure changed at some point between the last answer and this. If this continues to happen these will never work.
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
foreach ($lines as $line) {
if(preg_match('~^(.*?)\s+(flight\s+\d+)~', $line, $matches)){
echo $matches[1] . ' ' . $matches[2] . "\n";
}
}
?>
Output via my shell....
United Airlines flight 1274
Delta Air Lines flight 2389
Mesa Airlines flight 3734
United Airlines flight 569
Shuttle America flight 3473
United Airlines flight 1274
Delta Air Lines flight 2389
Mesa Airlines flight 3734
United Airlines flight 569
Shuttle America flight 3473
Related
i'm trying to convert DOCX to html, after search on google i can find this simple library as this convertor from https://github.com/xylude/Docx-to-HTML/blob/master/docx_reader.php , but that couldn't detect footnote on pages and i'm trying to add that to this library,
how can i detect styled text or simple text is/are footnote? that have special style?
<?php
class Docx_reader {
private $fileData = false;
private $errors = array();
private $styles = array();
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
foreach ($children->style as $s) {
$attr = $s->attributes('w', true);
if (isset($attr['styleId'])) {
$tags = array();
$attrs = array();
foreach (get_object_vars($s->rPr) as $tag => $style) {
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$styles[(String)$attr['styleId']] = array('tags' => $tags, 'attrs' => $attrs);
}
}
$this->styles = $styles;
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
return $data;
}
$zip->close();
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function to_html() {
if ($this->fileData) {
$xml = simplexml_load_string($this->fileData);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
$html = '<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title></title><style>span.block { display: block; }</style></head><body>';
foreach ($children->body->p as $p) {
$style = '';
$startTags = array();
$startAttrs = array();
if($p->pPr->pStyle) {
$objectAttrs = $p->pPr->pStyle->attributes('w',true);
$objectStyle = (String) $objectAttrs['val'];
if(isset($this->styles[$objectStyle])) {
$startTags = $this->styles[$objectStyle]['tags'];
$startAttrs = $this->styles[$objectStyle]['attrs'];
}
}
if ($p->pPr->spacing) {
$att = $p->pPr->spacing->attributes('w', true);
if (isset($att['before'])) {
$style.='padding-top:' . ($att['before'] / 10) . 'px;';
}
if (isset($att['after'])) {
$style.='padding-bottom:' . ($att['after'] / 10) . 'px;';
}
}
$html.='<span class="block" style="' . $style . '">';
$li = false;
if ($p->pPr->numPr) {
$li = true;
$html.='<li>';
}
foreach ($p->r as $part) {
//echo $part->t;
$tags = $startTags;
$attrs = $startAttrs;
foreach (get_object_vars($part->pPr) as $k => $v) {
if ($k = 'numPr') {
$tags[] = 'li';
}
}
foreach (get_object_vars($part->rPr) as $tag => $style) {
//print_r($style->attributes());
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$openTags = '';
$closeTags = '';
foreach ($tags as $tag) {
$openTags.='<' . $tag . '>';
$closeTags.='</' . $tag . '>';
}
$html.='<span style="' . implode(';', $attrs) . '">' . $openTags . $part->t . $closeTags . '</span>';
}
if ($li) {
$html.='</li>';
}
$html.="</span>";
}
//Trying to weed out non-utf8 stuff from the file:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $html);
return $html . '</body></html>';
exit();
}
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}
i have this code made in PHP , i integrated a css code by <<<HTML using variable $style the style shows up 3 times in the back of images for the gallerys, i suspect 3 times it shows up because of the number of the images, my wish was to show up only once.
i don't get it what it shows up by the number of images ? !
<?php
if( ! defined( 'CMSFUTURE' ) ) {
die( "Hacking attempt!" );
}
$style = <<<HTML
<style>
.gallerypro{padding:5px 5px 0 5px;height: 120px; width: 543px; background-color: rgb(220,220,220); border:1px solid grey; box-shadow: 7px 8px 20px -5px rgba(0,0,0,0.47);}
</style>
HTML;
$distr_charset = "utf-8";
$self_id ='';
$homeUrl = $config['http_home_url'];
$rootPath = $_SERVER['DOCUMENT_ROOT'];
$fullpath = $rootPath."/uploads/jmgallery/";
include ('engine/api/api.class.php');
if($dle_module == "showfull") {
$id = $_GET['newsid'];
$getCg = $dle_api->load_table($table="dle_jmgallery", $fields="id", $where="id > 0", $multirow="false", $start="0", $limit="0", $sort="", $sort_order="");
$having = FALSE;
foreach($getCg as $g){
if($g['id'] == $id){$having = TRUE;}
}
if($having == TRUE){
$getGal = $dle_api->load_table($table="dle_jmgallery", $fields="*", $where="id > 0", $multirow="true", $start="0", $limit="0", $sort="", $sort_order="");
foreach($getGal as $carousel){
$sizeW = $carousel['sizew'];
$sizeH = $carousel['sizeh'];
$dist = $carousel['distance'];
$self_id = $carousel['id'];
if($self_id == $id){
$mask = "*.jpg";
$idN = $fullpath.$id."/";
$mask = $idN.$mask;
if($sizeH == "0"){$sizeH = $sizeW; }
foreach (glob($mask) as $filename) {
$fileRname = substr($filename, -14);
$picSizeW = $sizeW * 2;
$img = "<img src='/uploads/jmgallery/$id/$fileRname' width='".$picSizeW."px' />";
$galery .= "$style<div class='gallerypro'><a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>"; } $xJ ="Computer repair"; $xJ = iconv("UTF-8", "UTF-8", $xJ); $galery .="<a href='$sitename' style='display:none; '>$xJ</a></div>";
echo $galery."<br clear='left' />";
}
}
}
$having = FALSE;
}
?>
This is the result i get :
See in the background of images ? that style is from variable $style declared above , and used in :
$galery .= "$style<div class='gallerypro'><a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>"; } $xJ ="Computer repair"; $xJ = iconv("UTF-8", "UTF-8", $xJ); $galery .="<a href='$sitename' style='display:none; '>$xJ</a></div>";
Move $style out of foreach statement.
If you place it inside foreach, it will displayed as many as foreach loop.
I don't know why you used to many foreach.
Just another suggestion, make up your code for better debugging. You also need to know about how to place a container/wrapper for your element.
See update of your code.
<?php
if( ! defined( 'CMSFUTURE' ) ) {
die( "Hacking attempt!" );
}
$style = <<<HTML
<style>
.gallerypro{padding:5px 5px 0 5px;height: 120px; width: 543px; background-color: rgb(220,220,220); border:1px solid grey; box-shadow: 7px 8px 20px -5px rgba(0,0,0,0.47);}
</style>
HTML;
$distr_charset = "utf-8";
$self_id ='';
$homeUrl = $config['http_home_url'];
$rootPath = $_SERVER['DOCUMENT_ROOT'];
$fullpath = $rootPath."/uploads/jmgallery/";
include ('engine/api/api.class.php');
if($dle_module == "showfull") {
$id = $_GET['newsid'];
$getCg = $dle_api->load_table($table="dle_jmgallery", $fields="id", $where="id > 0", $multirow="false", $start="0", $limit="0", $sort="", $sort_order="");
$having = FALSE;
foreach($getCg as $g){
if($g['id'] == $id){$having = TRUE;}
}
if($having == TRUE){
$getGal = $dle_api->load_table($table="dle_jmgallery", $fields="*", $where="id > 0", $multirow="true", $start="0", $limit="0", $sort="", $sort_order="");
$galerry = $style."<div class='gallerypro'>";
foreach($getGal as $carousel){
$sizeW = $carousel['sizew'];
$sizeH = $carousel['sizeh'];
$dist = $carousel['distance'];
$self_id = $carousel['id'];
if($self_id == $id){
$mask = "*.jpg";
$idN = $fullpath.$id."/";
$mask = $idN.$mask;
if($sizeH == "0"){$sizeH = $sizeW; }
foreach (glob($mask) as $filename) {
$fileRname = substr($filename, -14);
$picSizeW = $sizeW * 2;
$img = "<img src='/uploads/jmgallery/$id/$fileRname' width='".$picSizeW."px' />";
$galery .= "<a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>";
}
$xJ ="Computer repair";
$xJ = iconv("UTF-8", "UTF-8", $xJ);
$galery .="<a href='$sitename' style='display:none; '>$xJ</a>";
}
}
$gallery .= "</div>";
echo $gallery;
}
$having = FALSE;
}
?>
I have small matrix of +-100 points/values, results of test and their distances (0-10, 10 is the closest) to each other: http://vis.arcs.cz.
I would like to visualize it in 2D to quickly find a groups of close values. So I need to process this matrix and get the coordinates of points in 2D.
The way is propably multidimensional scaling but I wasnt able to find an algorithm, library or extension nor use the math formulas into PHP code.
Im googling last two days and the closest results of it is
http://www.php.net/manual/en/lapack.leastsquaresbysvd.php - ?
(cant share more links as novice)
I'll be grateful for any solution applicable in php project (compiled MathLab code in C++...).
index.php:
<?php
require("data.php");
require("Mds.php");
$mds = new Mds();
$mds->prepareData($data);
//cislo udava pocet iteraci algoritmu,
//idealne by melo mit hodnotu pocetUzlu na druhou, prakticky muze byt o dost mensi, 5 az 10 krat pocet uzlu.
$mds->scale(100);
//mira splneni podminek - vraci cislo < mensi nez 1. Cim blizsi k 1, tim lepe vyhovuji vzdalenosti
//z vypocteneho rozlozeni zadanym vzdalenostem.
//v nemetrickych datech ovsem dochazi rychle k poklesu az do zapornych hodnot, protoze ve 2D neexistuje
//pro nektere body zadne spravne misto.
echo $mds->getRSquared();
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "MDS",
fontFamily: "arial black",
fontColor: "black"
},
axisX: {
title:"",
titleFontFamily: "arial"
},
axisY:{
title: "",
titleFontFamily: "arial",
titleFontSize: 12
},
data: [
{
type: "scatter",
toolTipContent: "<span style='"'color: {color};'"'><strong>{name}</strong></span> x: {y}, y: {y}",
dataPoints:
<?php
echo $mds->printCoords('{x: %X, y: %Y, name: "%LABEL"}');
?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 600px; width: 600px;">
</div>
mds.zip
</body>
</html>
data.php:
$data = array(
array ("Jablko", "Voda", 2),
array("Jablko", "Ohen", 7),
array("Jablko", "Cervena", 3),
array("Jablko", "Zelena", 2),
array("Voda", "Ohen", 8),
array("Voda", "Cervena", 8),
array("Voda", "Zelena", 2),
array("Ohen", "Cervena", 1),
array("Ohen", "Zelena", 5),
array("Cervena", "Zelena", 3)
);
Mds.php:
<?php
class Mds {
//node - pole tvaru [[x, y, label], ...]
public $nodes = array();
//tvaru [source][target]=distance
public $givenDistances = array();
public $currentDistances = array();
public function prepareData($data) {
$nodesMap = array();
$xxxx = 10000;
$xxx= 1000;
// $xxxx = 5000;
// $xxx = 600;
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
if(!isset($nodesMap[$source])) {
$nodesMap[$source] = true;
$this->nodes[]=array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $source);
}
if(!isset($nodesMap[$target])) {
$nodesMap[$target] = true;
$this->nodes[]= array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $target);
}
}
//vytvori matici pro ulozeni vzdalenosti
foreach($this->nodes as $node) {
$this->givenDistances[$node[2]] = array();
$this->currentDistances[$node[2]] = array();
}
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
$distance = $link[2];
$this->givenDistances[$source][$target] = $distance;
$this->givenDistances[$target][$source] = $distance;
}
}
protected function countCurrentDistances() {
$mean = 0;
$i = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$dist = sqrt(($nodeB[0]-$nodeA[0])*($nodeB[0]-$nodeA[0]) + ($nodeB[1]-$nodeA[1])*($nodeB[1]-$nodeA[1]));
$this->currentDistances[$nodeA[2]][$nodeB[2]] = $dist;
if($nodeA[2]!==$nodeB[2]) {
$mean += $this->givenDistances[$nodeA[2]][$nodeB[2]];
}
}
}
// echo "<pre>";
// var_dump($this->currentDistances);
// echo "</pre>";
$check = array();
$nodesCount = count($this->nodes);
$this->mean = $mean/($nodesCount*$nodesCount);
}
public function getRSquared() {
$this->countCurrentDistances();
$sum = 0;
$SStot = 0;
$SSres = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$aLab = $nodeA[2];
$bLab = $nodeB[2];
if($aLab===$bLab) {
continue;
}
$given = $this->givenDistances[$aLab][$bLab];
$computed = $this->currentDistances[$aLab][$bLab];
$SSres+=(($given-$computed)*($given-$computed));
$SStot+= ($given-$this->mean)*($given-$this->mean);
}
}
return 1 - ($SSres/$SStot);
}
protected function iterate($inverseCoefStrenth=1) {
for($i=0; $i<count($this->nodes); $i++) {
$nodeA = $this->nodes[$i];
$move = array(0,0);
$moves = 0;
for($j=0; $j<count($this->nodes); $j++) {
if($j===$i) {
continue;
}
$nodeB = $this->nodes[$j];
$dist = $this->givenDistances[$nodeA[2]][$nodeB[2]];
$AB = array($nodeB[0]-$nodeA[0], $nodeB[1]-$nodeA[1]);
$lAB = sqrt(($AB[0]*$AB[0])+($AB[1]*$AB[1]));
$coef = ($lAB - $dist)/$lAB;
$AA1 = array($AB[0]*$coef, $AB[1]*$coef);
$moves++;
$move[0]+=$AA1[0];
$move[1]+=$AA1[1];
}
if($moves>0) {
$resultingMoveX = $move[0]/($moves*$inverseCoefStrenth);
$resultingMoveY = $move[1]/($moves*$inverseCoefStrenth);
$this->nodes[$i][0]+=$resultingMoveX;
$this->nodes[$i][1]+=$resultingMoveY;
}
}
}
public function scale($iterations, $coefIncrease=0) {
$basicCoef=1;
for($i=0; $i<$iterations; $i++) {
$this->iterate($basicCoef);
//echo $this->getRSquared();
//echo " | ";
$basicCoef+=$coefIncrease;
}
}
public function coordsAsString() {
$coords = array();
foreach($this->nodes as $node) {
$coords[]="[{$node[0]}, {$node[1]}]";
}
$res = join(", ",$coords);
return "[$res]";
}
public function printCoords($pattern='[%X,%Y,"%LABEL"]') {
$coords = array();
foreach($this->nodes as $node) {
$x = $node[0];
$y = $node[1];
$label = $node[2];
$res = str_replace('%X', $x, $pattern);
$res = str_replace('%Y', $y, $res);
$res = str_replace('%LABEL', $label, $res);
$coords[]=$res;
}
$res = join(", ",$coords);
return "[$res]";
}
public function pointsCoords() {
$coords = array();
foreach($this->nodes as $node) {
$res['x'] = round($node[0]*100);
$res['y'] = round($node[1]*100);
$res['label'] = $node[2];
$coords[] = $res;
}
return $coords;
}
}
Tag System I'm Using (Link)
Simply put the inline tag is never replaced by the cloud
I have my JS loading in from a folder (links confirmed)
<script type="text/javascript" src="/jquery/jqquery-1.7.2.js"></script>
<script type="text/javascript" src="/jquery/jqcloud-1.0.1.js"></script>
<link rel="stylesheet" href="/jquery/jqcloud.css" type="text/css" media="screen">
and then i use some PHP to generate the tag array
<script type="text/jscript">
var word_list = [
<?
foreach ($array as $key => $value) {
if ($value == $average) { $weight = 2;}
else if ($value > $average) { $weight = 3;}
else if ($value < $average) { $weight = 1;}
if (strlen($key) > 1 ){
echo "{text: \"".$key."\", weight:".$weight.", url: \"http://myurl.com/tags/".$key."\", title: \"".$value."\"}";
$total -= 1;
if ($total == 0) echo ",";
}
}
?>
];
$(document).ready(function() {
$("#wordcloud").jQCloud(word_list);
});
Yet all i have is an empty div in my tag section
http://jsfiddle.net/K28Mc/ Functioning example
The problem appears to be that you never close your array:
var word_list = [ // <-Note this character..
<?
foreach ($array as $key => $value) {
if ($value == $average) { $weight = 2;}
else if ($value > $average) { $weight = 3;}
else if ($value < $average) { $weight = 1;}
if (strlen($key) > 1 ){
echo "{text: \"".$key."\", weight:".$weight.", url: \"http://myurl.com/tags/".$key."\", title: \"".$value."\"}";
$total -= 1;
if ($total == 0) echo ",";
}
}
?>
}; //<------- Right here, you fail to close the array. This should be a ]. I have a feeling this is breaking everything else.
$(document).ready(function() {
$("#wordcloud").jQCloud(word_list);
});
foreach ($result['keywords'] AS $k => $keyword )
{
$font_size = rand(10, 25);
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma", "Roman", "Modern");
shuffle($fonts);
$randomFont = array_shift($fonts);
echo ' ' . '<span style="font-family:' . $randomFont . '; font-size:'.$font_size.'px;">' . $keyword['name'] . ' </span>';
}
Given a font CSS string such as this:
font:italic bold 12px/30px Georgia, serif;
or
font:12px verdana;
I want to convert it to its long hand format i.e:
font-style: italic; font-weight: bold;
Here is my miserable attempt: http://pastebin.com/e3KdMvGT
But of course it doesn't work for the second example since its expecting things to be in order, how can I improve it?
Here is a function which should do the work. The problem lies in the font-style, font-variant and font-weight properties and the value "normal" as you can read in the css specs ([[ <'font-style'> || <'font-variant'> || <'font-weight'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] | caption | icon | menu | message-box | small-caption | status-bar | inherit).
$testStrings = array('12px/14px sans-serif',
'80% sans-serif',
'x-large/110% "New Century Schoolbook", serif',
'x-large/110% "New Century Schoolbook"',
'bold italic large Palatino, serif ',
'normal small-caps 120%/120% fantasy',
'italic bold 12px/30px Georgia, serif',
'12px verdana');
foreach($testStrings as $font){
echo "Test ($font)\n<pre>
";
$details = extractFull($font);
print_r($details);
echo "
</pre>";
}
function extractFull($fontString){
// Split $fontString. The only area where quotes should be found is around font-families. Which are at the end.
$parts = preg_split('`("|\')`', $fontString, 2, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$chunks = preg_split('` `', $parts[0], NULL, PREG_SPLIT_NO_EMPTY);
if(isset($parts[1])){
$chunks[] = $parts[1] . $parts[2];
}
$details = array();
$next = -1;
// Manage font-style / font-variant / font-weight properties
$possibilities = array();
$fontStyle = array('italic', 'oblique');
$fontVariant = array('small-caps');
$fontWeight = array('bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900');
// First pass on chunks 0 to 2 to see what each can be
for($i = 0; $i < 3; $i++){
$possibilities[$i] = array();
if(!isset($chunks[$i])){
if($next == -1){
$next = $i;
}
continue;
}
if(in_array($chunks[$i], $fontStyle)){
$possibilities[$i] = 'font-style';
}
else if(in_array($chunks[$i], $fontVariant)){
$possibilities[$i] = 'font-variant';
}
else if(in_array($chunks[$i], $fontWeight)){
$possibilities[$i] = 'font-weight';
}
else if($chunks[$i] == 'normal'){
$possibilities['normal'] = 1;
}
else if($next == -1){
// Used to know where other properties will start at
$next = $i;
}
}
// Second pass to determine what real properties are defined
for($i = 0; $i < 3; $i++){
if(!empty($possibilities[$i])){
$details[$possibilities[$i]] = $chunks[$i];
}
}
// Third pass to set the properties which have to be set as "normal"
if(!empty($possibilities['normal'])){
$properties = array('font-style', 'font-variant', 'font-weight');
foreach($properties as $property){
if(!isset($details[$property])){
$details[$property] = 'normal';
}
}
}
if(!isset($chunks[$next])){
return $details;
}
// Extract font-size and line height
if(strpos($chunks[$next], '/')){
$size = explode('/', $chunks[$next]);
$details['font-size'] = $size[0];
$details['line-height'] = $size[1];
$details['font-family'] = $chunks[$next+1];
}
else if(preg_match('`^-?[0-9]+`', $chunks[$next]) ||
in_array($chunks[$next], array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'))){
$details['font-size'] = $chunks[$next];
$details['font-family'] = $chunks[$next+1];
}
else{
$details['font-family'] = $chunks[$next];
}
return $details;
}
here my attempt
function rewriteFont($short) {
$short = str_replace("font:","",$short);
$values = explode(" ", $short);
$length = count($values);
$familyLength = 0;
for($i = 0; $i < $length; $i++) {
$currentValue = $values[$i];
if($currentValue == 'italic' || $currentValue == 'oblique' ) {
echo "font-style:{$currentValue};";
}
else if($currentValue == 'small-caps') {
echo "font-variant:{$currentValue};";
}
else if ($currentValue == 'bold' || $currentValue == 'bolder' || $currentValue == 'lighter' || is_numeric($currentValue) ) {
echo "font-weight:{$currentValue};";
}
else if (strpos($currentValue, "px") || strpos($currentValue, "em") || strpos($currentValue, "ex")|| strpos($currentValue, "pt")
|| strpos($currentValue, "%") || $currentValue == "xx-small" || $currentValue == "x-small" || $currentValue == "small"
|| $currentValue == "medium" || $currentValue == "large" || $currentValue == "x-large" || $currentValue == "xx-large") {
$sizeLineHeight = explode("/", $currentValue);
echo "font-size:{$sizeLineHeight[0]};";
if(isset($sizeLineHeight[1])) {
echo "line-height:{$sizeLineHeight[1]};";
}
}
else {
if($familyLength == 0) {
echo "font-family:{$currentValue} ";
}
else {
echo $currentValue;
}
$familyLength++;
}
}
}
Following the specs, I'd do the following code. It works with all examples from the specs. You can see it here : http://codepad.viper-7.com/ABhc22
function font($s){
$fontStyle = array('normal', 'italic', 'oblique', 'inherit');
$fontVariant = array('normal', 'small-caps','inherit');
$fontSize = array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large');
$fontWeight = array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit');
$s = str_replace('font: ', '', $s);
$array = explode(' ', $s);
$count = count($array);
$sizeFound = false;
$final = array();
$final['font-style'] = 'normal';
$final['font-variant'] = 'normal';
$final['font-weight'] = 'normal';
for($i = 0; $i < $count; $i++){
$cur = $array[$i];
if($sizeFound){
$final['font-family'] = isset($final['font-family']) ? $final['font-family'].$cur : $cur;
}else if(strripos($cur,'%') !== false || strripos($cur,'px') !== false || in_array($cur, $fontSize)){
$sizeFound = true;
$size = explode('/', $cur);
if(count($size) > 1){
$final['font-size'] = $size[0];
$final['line-height'] = $size[1];
}else
$final['font-size'] = $size[0];
}else{
if(in_array($cur, $fontStyle))
$final['font-style'] = $cur;
if(in_array($cur, $fontVariant))
$final['font-variant'] = $cur;
if(in_array($cur, $fontWeight))
$final['font-weight'] = $cur;
}
}
$ret = '';
foreach($final as $prop => $val)
$ret .= $prop.': '.$val.';';
return $ret;
}
I guess it can be optimised. :)
You could look at CSSTidy, whose code is open-source and try to reverse engineer it.