Repeat a sequence of codes [closed] - sequence

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<div class="zoom_img">
<img alt="1.jpg" src="1.jpg">
<img alt="2.jpg" src="2.jpg">
<img alt="3.jpg" src="3.jpg">
<img alt="4.jpg" src="4.jpg">
<img alt="5.jpg" src="5.jpg">
</div>
I have to add almost 100 pics in this order. So just wondering how to use the for loop to do the job easily :)

with JQuery on client side
var img;
for (var i = 1; i < 10; i++){
img = '<img alt="' + i + '.jpg" src="' + i + '.jpg">';
$(".zoom_img" ).add( img);
}

you need some kind of server language. For example in php.
<?php
$numOfPhotos = 10; //some value.
$html = "<div class='zoom_img'>";
for ($i = 0; $i < $numOfPhotos; $i++)
{
$html = $html . "<a href='" . $i . "jpg'><img alt='" . $i . "jpg'></a>";
}
$html = $html . "</div>";
?>
<html>
<body>
<!-- Put your normal html -->
<?php echo $html; ?> <!-- this will insert the html created dynamically -->
</body>
</html>

If you don't have a server language, and just want to pregenerate this easily:
Open a terminal, start python (type 'python') and type in:
for x in range (0, 100):
print '<img alt="%d.jpg" src="%d.jpg">' %(x, x, x)
replacing 100 with whatever number you want to go to. It will print out the code.
Edit: added front carrot to print

Related

Razor-Pages - HTML markup

Following the answer on this post I was using #:<div class="col-md-6">
Problems
The Formatting gets all messed up:
The intellicode gets all messed up (I only deleted the paragraph on the second #:)
Also, my if (i == (Model.CellsNotStarted.Count - 1) && i % 2 != 0) won't work when using the #:; it will always go on the else. If I don't use the #: markup, and if I, for instance put all my html in a if/else instead of only the <div> tag it will work with no problems.
My question is:
Is the #: markup viable? If so, what am I doing wrong. If not what is the alternative (that does not imply putting my entire code in an if/else)
PS: I know I should not post images of code, but I wanted to show the format and syntax errors.
There are neater ways to manage conditions within your Razor code. It's difficult to provide a full example because you don't provide the full code, but you can do this, for example:
<div class="col-md-#(i+1 == Model.CellsNotStarted.Count && i % 2 ! = 0 ? "12" : "6")">
Whenever you are tempted to use a remainder operator (%) in Razor, you should also consider whether a GroupBy would be better. It most often is, as I was shown in this question: Building tables with WebMatrix
You can try to use js to set html.Here is a demo:
<div id="myDiv"></div>
<script>
$(function () {
var html = "";
if ("#(Model.CellsNotStarted != null)"=="True")
{
for (var i = 0; i <#Model.CellsNotStarted.Count; i++)
{
if (i == (#Model.CellsNotStarted.Count - 1) && i % 2 != 0)
{
html += '<div class="col-md-12">';
}
else
{
html += '<div class="col-md-6">';
}
html += i+'</div>';
}
}
$("#myDiv").html(html);
})
</script>
result:

How can I enhance the quality of images generated from PDF?

We use TYPO3 9.5.13, GraphicsMagick 1.3.29, Ghostscript 9.27, BK2K\\BootstrapPackage 11.0.1
Using PDFs as normal images is no problem.
But now I want a 'preview' of the PDFs in full column width (~1000px). And although the PDF has a high resolution, the generated Image has a width of 595px only and any text is nearly unreadable.
The problem occurs with Image-CEs like in the uploads CE, which I want to enhance:
each time I want the image using the full column width it renders in a bad resolution and the image seems distorted.
here a small area from the generated image:
and the same area from the PDF as shown in PDF-reader:
The fluid part:
<img loading="lazy"
src="{f:uri.image(image: file, cropVariant: 'default', maxWidth: 1100)}"
width="{bk2k:lastImageInfo(property: 'width')}"
height="{bk2k:lastImageInfo(property: 'height')}"
intrinsicsize="{bk2k:lastImageInfo(property: 'width')}x{bk2k:lastImageInfo(property: 'height')}"
title="{file.properties.title}"
alt="{file.properties.alternative}">
which results in something like:
<img loading="lazy"
src="/fileadmin/_processed_/3/2/csm_Warum_D-Arzt_6afd8ad8d4.png"
intrinsicsize="595x842"
title=""
alt=""
width="595"
height="842">
Edit:
In case of using this FLUID:
<img loading="lazy"
src="{f:uri.image(image: file, cropVariant: 'default', width: 1100)}"
width="{bk2k:lastImageInfo(property: 'width')}"
height="{bk2k:lastImageInfo(property: 'height')}"
intrinsicsize="{bk2k:lastImageInfo(property: 'width')}x{bk2k:lastImageInfo(property: 'height')}"
title="{file.properties.title}"
alt="{file.properties.alternative}">
I get:
<img loading="lazy"
src="/fileadmin/_processed_/3/2/csm_Warum_D-Arzt_2ffb63b15f.png"
intrinsicsize="1100x1557"
title=""
alt=""
width="1100"
height="1557">
the image is bigger (and overflow the container) but the quality is worse the same, notice the bigger pixels:
Actually, a PDF is NOT an image. It is a container format which can contain vectors and images with different colorspaces and dimensions. A bitmap image has fixed dimensions width, height, density, a PDF not. Originally, it was created and optimized to work for printers, not for screens.
TYPO3 reflects that with a message in the backend:
IMHO, there is no perfect way of handling PDFs to behave like images, as you know the output format, but not the input format (properly). Two ways to get acceptable results:
Extend content elements or create new ones and add a second image slot for PDF preview images. Create the preview images yourself with a graphical program.
Write your own viewhelper and create your own thumbnails
Solution 1 will lead to more work for editors. Would be no best practise for me.
I would go with an own viewhelper.
Add your own render type for PDFs:
<f:switch expression="{file.type}">
<f:case value="5">
<f:render partial="Media/Type/Pdf" arguments="{file: file, dimensions: dimensions, data: data, settings: settings}" />
</f:case>
<f:defaultCase>
<f:render partial="Media/Type/Image" arguments="{file: file, dimensions: dimensions, data: data, settings: settings}" />
</f:defaultCase>
</f:switch>
Partial Media/Type/Pdf
{namespace cv=Conversion\HelperUtils\ViewHelpers}
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:ce="http://typo3.org/ns/TYPO3/CMS/FluidStyledContent/ViewHelpers" data-namespace-typo3-fluid="true">
<cv:forEachPdfThumbnail document="{file}" pages="1" as="pdfPreviewPage">
<f:image src="{pdfPreviewPage}" alt="" />
</cv:forEachPdfThumbnail>
</html>
ViewHelper:
This viewhelper convert multiple pages from a PDF, using the CommandUtility::imageMagickCommand. You can raise the density to a higher value to improve quality.
As mentioned, this viewhelper was developed a few years ago and could be improved (e.g. saving to fileadmin/processed instead of typo3temp. Feel free to clone and improve: https://github.com/conversion1/t3-pdfthumbnailviewhelper/blob/master/ForEachPdfThumbnailViewHelper.php
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
$templateVariableContainer = $renderingContext->getVariableProvider();
/** #var \TYPO3\CMS\Core\Resource\FileReference $document */
$document = $arguments['document'];
$pages = explode(',', str_replace(' ', '', $arguments['pages']));
$colorspace = TRUE === isset($GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace']) ? $GLOBALS['TYPO3_CONF_VARS']['GFX']['colorspace'] : 'RGB';
$absFilePath = GeneralUtility::getFileAbsFileName($document->getOriginalFile()->getPublicUrl());
$destinationPath = 'typo3temp/';
$destinationFilePrefix = 'pdf-prev_' . $document->getOriginalFile()->getNameWithoutExtension();
$destinationFileExtension = 'png';
$output = '';
foreach ($pages as $pageNumber) {
if($pageNumber > 0) {
$pageNumber = intval($pageNumber);
} else {
$pageNumber = 1;
}
$destinationFileSuffix = '_page-' . $pageNumber;
$absDestinationFilePath = GeneralUtility::getFileAbsFileName($destinationPath . $destinationFilePrefix . $destinationFileSuffix . '.' . $destinationFileExtension);
$imgArguments = '-colorspace ' . $colorspace;
$imgArguments .= ' -density 300';
$imgArguments .= ' -sharpen 0x.6';
$imgArguments .= ' "' . $absFilePath . '"';
$imgArguments .= '['. intval($pageNumber - 1) .']';
$imgArguments .= ' "' . $absDestinationFilePath . '"';
if(!file_exists($absDestinationFilePath)) {
$command = CommandUtility::imageMagickCommand('convert', $imgArguments);
CommandUtility::exec($command);
}
$thumbnail = substr($absDestinationFilePath, strlen(Environment::getPublicPath()));
$templateVariableContainer->add($arguments['as'], $thumbnail);
$output .= $renderChildrenClosure();
$templateVariableContainer->remove($arguments['as']);
}
return $output;
}
Edit:
A third way: You can use a JavaScript library to generate thumbnails on the fly. E.g. https://github.com/mozilla/pdf.js

Simple Yahoo Weather Api Not Working

I was using a simple code which includes a yahoo api code to get just the weather from my city and put in on my web page, however, i just read that yahoo public api is no longer working and i dont know how can a i get this code to work, i have a yahoo account, i created an api and i dont know how to proceed since here. If somebody can help me this is the code:
<?php
/*Clima*/
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}else{
$zipcode = 'ARMA0056';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=c');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$clima = <<<END
<span>{$current['temp']}°C</span>
END;
}
}else{
$clima = '<h1>No results found, please try a different zip code.</h1>';
}
/*Clima*/
?>
just replace http://weather.yahooapis.com with http://xml.weather.yahoo.com. credits to https://forum.rainmeter.net/viewtopic.php?f=13&t=23010
xml.weather.yahoo.com was the solution, but the URL does not seem to be working anymore. Im now using yahoos query to get the XML i.e."https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2489314"
This seems to be the same XML with the exception of "results" added to the tree.
Yahoo recently updated the way they handle requests. It used to be just over any connection, but now to make it more secure and easier to handle, they recently opted into sending all requests over OAuth1. Use the sample code they provide on their page and get the information from the request over JSON.
See https://developer.yahoo.com/weather/ for more information.
YAHOO changed some rules about api;
I made following class working for me... hope works for you;
$fcast=$phpObj->query->results->channel->item->forecast; change this line for other items...
<?php
date_default_timezone_set('CET');
class weatherfc{
public $result;
function weather($city){
$BASE_URL = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="'.$city.'") and u="c"';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
//var_dump($phpObj);
$weatherd='<div> Weather In '.$city.'<br>';
$fcast=$phpObj->query->results->channel->item->forecast;
foreach($fcast as $witem){
$fdate=DateTime::createFromFormat('j M Y', $witem->date);
$weatherd.= '<div class="days">';
$weatherd.= '<div class="item"><div>'.$fdate->format('d.m').' '.$witem->day.'</div><div class="image" style="width:90px !important; height:65px !important;"><img src="http://us.i1.yimg.com/us.yimg.com/i/us/nws/weather/gr/'.$witem->code.'d.png" width=90></div></div>';
$weatherd.= '<div><span>'.$witem->high.'°C</span>';
$weatherd.= '<span>'.$witem->low.'°C</span></div></div>';
};
$this->result=$weatherd;
}
}
$h= new weatherfc;
$h->weather("Antalya,Turkey");
echo $h->result;
?>
<style>
.days{
width:90px;
font-size:12px;
float:left;
font-family:Arial, Helvetica, sans-serif;
border:#999 1px dotted;
}
</style>

Is there a working sample of the Google custom search rest API?

I need to create a screen which automates Google search.
I know JavaScript and I'm trying to get GSE works.
I have a search engine and an API key.
The problem is Google's documentation is cyclic i.e. pages point to each other.
There is no working sample from where I can start my research.
Please help if you know of a working sample.
The documents I have read are:
cselement-devguide
introduction
I know this is an old question, but here is what I did to make the API results formatted like the Google Site Search used to give since they are ending the paid accounts and will have ads now. The API way has an option to pay still for over 100 searches per day, so going with that but had to format the results still, and used the existing one to build the css to do similar styling also.
Search form going to this page is just a simple:
<form action="search-results.htm" id="cse-search-box">
<div>
<input class="" name="q" type="text">
<input class="" type="submit">
</div>
</form>
and then the search results page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>JSON/Atom Custom Search API Example</title>
<!--<link href="default.css" rel="stylesheet" type="text/css">-->
<link href="google.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="gsc-result-info" id="resInfo-0"></div>
<hr/>
<div id="googleContent"></div>
<script>
//Handler for response from google.
function hndlr(response) {
if (response.items == null) {
//Sometimes there is a strange thing with the results where it says there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
//So if we get to the invalid one, send them back a page.
window.location.replace("searchresults.htm?start=" + (start - 10) + "&q=" + query);
return;
}
//Search results load time
document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
//Clear the div first, CMS is inserting a space for some reason.
document.getElementById("googleContent").innerHTML = "";
//Loop through each item in search results
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var content = "";
content += "<div class='gs-webResult gs-result'>" +
"<table class='gsc-table-result'><tbody><tr>";
//Thumbnail image
if (item.pagemap.cse_thumbnail != null)
content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
"<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
//Link
content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
//File format for PDF, etc.
if (item.fileFormat != null)
content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
//description text and URL text.
content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
"<br/></td></tr></tbody></table></div>";
document.getElementById("googleContent").innerHTML += content;
}
//Page Controls
var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
console.log(totalPages);
var currentPage = Math.floor(start / 10 + 1);
console.log(currentPage);
var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
//Page change controls, 10 max.
for (var x = 1; x <= totalPages && x<=10; x++) {
pageControls += "<div class='gsc-cursor-page";
if (x === currentPage)
pageControls += " gsc-cursor-current-page";
var pageLinkStart = x * 10 - 9;
pageControls+="'><a href='search-results.htm?start="+pageLinkStart+"&q="+query+"'>"+x+"</a></div>";
}
pageControls += "</div></div></div>";
document.getElementById("googleContent").innerHTML += pageControls;
}
//Get search text from query string.
var query = document.URL.substr(document.URL.indexOf("q=") + 2);
var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
if (start === "1&" || document.URL.indexOf("start=") === -1)
start = 1;
//Load the script src dynamically to load script with query to call.
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourApikeyhere&cx=yoursearchengineidhere&start="+start+"&q=" +query +"&callback=hndlr";
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
</script>
</body>
</html>

errors not showing

I have an issue with my php photo upload script. When I upload a file that exceeds 2mb, it won't show that error when I click upload..yet it's there in my script..any idea why this is? For ex. I uploaded a .wma file and It was 2.38MB..that exceeds the limit..but yet it just says "file type not allowed" why didn't it show the exceeds 2mb error as well?
Here is my script:
<?php
include 'init.php';
if(!logged_in()){
header('Location: index.php');
exit();
}
include 'template/header.php';
?>
<h3>Upload Image</h3>
<?php
if(isset($_FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];
$errors = array();
if (empty($image_name) || empty($album_id)){
$errors[] = 'Something is missing';
} else {
if(in_array($image_ext, $allowed_ext) === false){
$errors[] = 'File type not allowed';
}
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
if(album_check($album_id) === false){
$errors[] = 'Couldn\'t upload to that album';
}
}
if(!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
// upload image
}
}
$albums = get_albums();
if(empty($albums)){
echo '<p>You don\'t have any albums. Create an album</p>';
} else {
?>
<form action="" method="post" enctype="multipart/form-data">
<p>Choose a file:<br /><input type="file" name="image" /></p>
<p>
Choose an album:<br />
<select name="album_id">
<?php
foreach ($albums as $album){
echo '<option value="', $album['id'], '">', $album['name'], '</option>';
}
?>
</select>
</p>
<p><input type="submit" value="Upload" /></p>
</form>
<?php
}
include 'template/footer.php';
?>
Thanks again for all of the patience with my probably easy posts for a lot of you more experienced programmers out there!
-TechGuy24
As per code, it should, if uploaded file size is >2mb. However, computers never make mistake but the human and thus debugging is important.
Just replace the code
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
with debug statements
if($image_size > 2097152){
echo "in if, image size=".$image_size;
$errors[] = 'Maximum file size is 2MB';
} else {
echo "in else, image size=".$image_size;
}
This is just a first step of debugging. It may or may not fix the real cause. Let us know the output.
Edit after comment:
Put that code in the starting of the file.
echo "files<pre>";
print_r($_FILES);
echo "</pre>imgsz=".$_FILES['image']['size'];
What is the output. I guess it might include
[error] => 1
If it show error=1, Check http://php.net/manual/en/features.file-upload.errors.php
That mean your upload_max_filesize in php.ini is set to 2MB or less. As soon as person upload file bigger than that, it never reach your code as PHP reject the file by default.
To fix that, open php.ini and increase the limit of upload_max_filesize.
Edit 3 after comment
Change
if($image_size > 2097152){
to
if($_FILES['image']['error']==1){
That will fix the issue.