Use regular expressions in javascript to manage source files - javascript

I am making my first steps coding with JavaScript and also playing with a webgl library called Three.js.
After see some tutorials and make some experiments I finally made this: https://dl.dropboxusercontent.com/u/15814455/Monogram.html.
As you can see in my code, the object reflects randomly a group of 6 images that I have in a folder of 13 images.
var numberOfImages = 13, images = [];
for (var i = 1; i <= numberOfImages; i++) {
images.push('sources/instagram/image' + i + ".jpg");
}
var urls = images.sort(function(){return .6 - Math.random()}).slice(0,6);
var reflectionCube = THREE.ImageUtils.loadTextureCube( urls );
reflectionCube.format = THREE.RGBFormat;
The thing is that each time I upload an Instagram picture, it will be saved in that folder called instagram.
Now my problem is that, if I upload for example, 10 images to the folder I have to change this line of code: var numberOfImages = 13 to this var numberOfImages = 23.
So I am looking for a way to modify my code and not to set a limit of number of images. So I could upload images in the folder and then automatically see them in my 3d object.
I've been reading on internet and I found that I can use something called regular expressions in my code to solve this problem.
I would like to know if using regular expressions is a real solution. Is it worth to learn regular expressions to solve this problem?
Do you have some suggestion? There is another solution? Maybe its something simple and I should write a different line of code, but if it's something more complicated and I should learn some language I would like to learn the right language.

First off, if you are going to be programming at length in pretty much any language, it will be worth knowing regular expressions and how/when to use them so it's will be useful to learn them.
If this was a client/server problem where you controlled the server, the usual way to solve this problem is that the server would scan the file system on the server and it would tell the client how many images to prepare for.
If you have to solve this entirely on the client, then you can't directly scan the file system from the client, but you can request increasing file numbers and you can see (asynchronously) when you stop getting successful loading of images. This is not particularly easy to code because the response will be asynchronous, but it could be done.
Here's a scheme for preloading images and finding out where they stopped preloading successfully:
function preloadImages(srcs, callback) {
var img, imgs = [];
var remaining = srcs.length;
var failed = [];
function checkDone() {
--remaining;
if (remaining <= 0) {
callback(failed);
}
}
for (var i = 0; i < srcs.length; i++) {
img = new Image();
img.onload = checkDone;
img.onerror = img.onabort = function() {
failed.push(this.src);
checkDone();
}
img.src = srcs[i];
imgs.push(img);
}
}
var maxNumberOfImages = 30, images = [];
for (var i = 1; i <= maxNumberOfImages; i++) {
images.push('sources/instagram/image' + i + ".jpg");
}
preloadImges(images, function(failed) {
var regex = /(\d+)\.jpg$/;
var nums = failed.map(function(item) {
var matches = item.match(regex);
return parseInt(matches[1], 10);
}).sort();
var numImages = nums[0];
// now you know how many good images there are
// put your code here to use that knowledge
});
Note: This does use a regular expression to parse the image number out of a URL.
It would be possible to code this without a preset limit, but it would be more work. You'd probably request images 10 at a time and if you didn't get any errors, then request the next block of 10 until you found the first failure.

Related

Scrape multiple JavaScript-based websites in R

These are my first steps in programming and I'm trying to learn as much as I can before bothering you guys. But right now I'm pretty much stuck after trying several ways (thought of by myself or found online).
What I'm trying to do now is saving multiple whole JavaScript pages to further work with them in R. As far as I understood this is just possible using phantomjs. I've managed to get a code loading the page. But I'm struggling with the loop:
writeLines("var page = new WebPage();
var fs = require('fs');
for (i = 101; i <= 150; i++) {
page.open('http://understat.com/match/' + i, function (status) {
just_wait();
});
function just_wait() {
setTimeout(function() {
fs.write('match' + i + '.html', page.content, 'w');
phantom.exit();
}, 2500);
}
}
", con = "scrape.js")
js_scrape <- function(
js_path = "scrape.js",
phantompath = "/Users/Marek/Documents/Programmierung/Startversuche/phantomjs-2.1.1/bin/phantomjs"){
lines <- readLines(js_path)
command = paste(phantompath, js_path, sep = " ")
system(command)
}
js_scrape()
It's just saving the last page of the loop. Reading other threads I understood that the problem is that phantomJS is asynchronous and is pretty much closing the pages before they have been loaded. But I could not work a way around, so it's saving all of the pages in different files.

javascript illustrator copy pdf documents and stack them issue

I'm looking for a way to copy pdf documents and stack them resized (I think resize works as duplicate, so once this works I will be able to complete my script).
I've been using .duplicate for now, and I can only manage to copy 1 item[0] on the same doc. Besides if I copy element by element I won't be able to replace them easily that's why I want to copy the whole document
I'm opening every script I find to understand a possible method.
Syntax is ok
var targetFile = app.documents.add(); //this is my output file - it is created
folder = Folder.myDocuments; //this paragraph works for now
sourceFolder = folder.selectDlg("source");
for ( i = 0; i < files.length; i++ ){
var sourceDoc = app.open(files[i]);
var doc = app.activeDocument;
for (l = 0; l < doc.pageItems.length; l++) { //corrected error
doc.pageItems[i].selected = true;
}
var mySel = app.activeDocument.selection; //this paragraph need rework
newItem = mySel[0].duplicate(targetFile); //mysel.duplicate(targetFile) is not a function
// MAIN ERROR
}
I use ESTK and notepad++ and have checked the variable, nothing obviously wrong during F10 debug. Using Jongware's CHM reference guide and some github tutorial but they tend to help for single operation script. My goal is to have script without GUI to reduce errors and time to proceed
Thank you for your time
EDIT: spotted an error with i used two times in a loop
Simple self solution:
var mySel = app.activeDocument.selection;
app.executeMenuCommand('copy');
targetFile.activate();
newItem = app.executeMenuCommand('paste');

Loading a Random Caption from a text file using Javascript and Displaying via HTML

I am trying to load a random caption every time my page is loaded. I have a separate text file and contained on each line is a string. I am new to both html and Javascript, as you will see.
HTML:
<div class="centerpiece">
<h1>DEL NORTE BANQUEST</h1>
<p class="caption"><script src = "js/caption.js"></script><script>getCaption();</script></p>
<a class="btn" id="browse-videos-button" href="#video-list">Browse Videos<br><img src="img/arrow-down.svg"style="width:15px;height:15px;"></a>
</div>
Javascript:
function getCaption()
{
var txtFile = "text/captions.txt"
var file = new File(txtFile);
file.open("r"); // open file with read access
var str = "";
var numLines = 0; //to get the range of lines in the file
while (!file.eof)
{
// read each line of text
numLines += 1;
}
file.close();
file.open("r");
var selectLine = Math.getRandomInt(0,numLines);//get the correct line number
var currentLine = 0;
while(selectLine != currentLine)
{
currentLine += 1;
}
if(selectLine = currentLine)
{
str = file.readln();
}
file.close();
return str;
}
Text in Source File:
We talked yesterday
Freshman boys!
5/10
I'm having a heart attack *pounds chest super hard
The site is for my highschool cross country team in case the text file was confusing.
I am unfamiliar with most syntax and was unable to see if by iterating through the file with a loop if i needed to reset somehow which is why I opened and closed the file twice. Here is a jsfiddle of the specific caption I am trying to change and what my function is in Javascript.
https://jsfiddle.net/7cre9qqj/
If you need more code to work with please let me know and any critiques you may have please dont hold back if it looks like a mess, I am trying to learn after all! Thank you for your help!
The File API allows access to the file system on the client side, so it's not really suited to what you want to do. It's also only allowed to be used in very specific circumstances.
A simple solution is to just run an AJAX request to populate your quote. The AJAX call can read the file on your server, then it's simple to split the contents of the file by line, and pick a random line to display. Since you're open to jQuery, the code is pretty simple:
$.get("text/captions.txt")).then(function(data) {
var lines = data.split('\n');
var index = Math.floor(Math.random() * lines.length);
$("#quote").html(lines[index]);
});
Here's a fiddle that demonstrates it in full; every time it runs it will load a random quote: https://jsfiddle.net/s1w8x4ff/

Issue queuing HTML5 FileReader()s to be read later

I'm currently working on a Google Chrome app that will allow users to open image files for viewing.
What I found was that it was far too hurtful to performance to read many files concurrently, so I decided to make a queue, and a limit as to how many files can be read concurrently.
However, the issue I am facing is with my file reading function, readFile(file).
At one point, files stop being read, and I am left with 3 readers, and all the remaining files still in the queue. This is the result:
I have rewritten and omitted some parts of the JavaScript and CSS to make it web browser ready, and here is the JSFiddle.
Here is the function in its entirety, along with some of the variables associated within the function:
var data = [], readers = [];
function readFile(file){
if(readers.length >= 4){
//if there are already 4 files being read concurrently
queue.push(file);
}else{
//Note: remove last reader, first from queue
var item = document.createElement('div');
item.innerHTML = '<img/>Loading...';
fileList.appendChild(item);
readers.push(new FileReader());
var currentReader = readers[readers.length-1]; //get the last reader
currentReader.addEventListener('error',function(){
});
currentReader.addEventListener('load',function(event){
var result = this.result||event.target.result;
var img = item.getElementsByTagName('img')[0];
var tmp = new Image();
tmp.src = result;
data.push({
"file":file,
"name":file.name,
"ext":file.name.substring(file.name.lastIndexOf(".")),
"item":item,
"img":result,
"thumb":img
});
tmp.addEventListener('load',function(){
canvas2.width = canvas2.height = thumbnailDimension;
ctx2.drawImage(this,0,0,canvas2.width,canvas2.height);
img.src = canvas2.toDataURL('image/webp','.1');
setTimeout(function(){
if(queue.length){
readFile(queue[0]);
queue.splice(0,1);
}
readers.splice(readers.length-1,1);
},1000);
});
});
currentReader.readAsDataURL(file);
}
}
For my app, I want to read the files, resize a canvas, and draw the images onto it to make thumbnails for a side panel. For that reason, the temporary image, img, must be loaded before the next file can be read (to prevent things from being added to the queue twice). As you can see, I set a one second delay, but I am still having an issue.
Thank you all for your helpful answers in advance. If you would like to reproduce the problem I am having for yourself, just select a LOT of image files. I chose 168 JPG files (each around 500-600k).
Update: 1/7/2015 11:39am EST: I did some inspecting and found that the tmp would stop firing it's onload event. Maybe it's bad to have one event listener inside of another? If so, how could I achieve getting the thumbnails to load at a proper time?
#RickyAYoder, seems there is an error on the page. Run debugger on your browser (Chrome is the best!) to see if there are any other errors. I see launchData is not defined in your code:
function onLaunch(){
if(!(launchData && launchData.items && launchData.items[0])) return;
for(var x = 0; x < launchData.items.length; x++){
//iterate through files passed to app
launchData.items[x].entry.file(function(file){
});
}
Draw();
}
onLaunch();
can you check to see if it is defined somewhere??

getting pictures into an array in javascript

im kinda new to javascript i mean i know the syntax but not so much the libraries.
i need some help to get some files (pictures) from a folder into an arry lets say:
var[] pictures = ?;
(the folder is in my project and contain some pictures)
so i can loop over them and diplay them on the page i did some search but i didnt find any guide on how to do this.
i realy want to understand on how to do this for future projects even a link to known guid you guys know we will be a big help.
if it help im using asp.net.
Well, there are a lot of ways to approach the problem, to me what you can do is (if you don't know the location of the images beforehand) make a service that returns the src of every image, store that in an array, and then show them in the page.
I believe you are using jQuery so you can make an ajax request like this:
jQuery.ajax({
url: /*path to*/"Service.asmx/getSources"
//options, check documentation
});
then, from asp, make a new service (Service.asmx in my case) and create a method that returns the location of the pictures (in my case the method is called getSources)
I recommend you use JSON (and jQuery.getJSON() method) so you can return a List<string>.
Lastly you can iterate or store the sources in an array, I'll put an example with the getJSON method
var sources = []
jQuery.getJSON("Service.asmx/getSources", function(data) {
for(var i = 0, len = data.length; i<len ; i++) {
sources.push(data[i]);//store every source in the array
}
});
once you have the sources you can display them like this fiddle
Tell me if it helped or if you need another solution.
If you want an array of pictures just to display them later, you can simply use:
var sources = [
"path/to/yourImage1.jpg",
"path/to/yourImage2.jpg",
// ...
"path/to/yourImageN.jpg",
];
var pics = [];
for(var i = 0; i < sources.length; i++) {
var pic = new Image();
pic.src = sources[i];
pics[i] = pic;
}

Categories

Resources