Eclipse, JavaScript, UTF-8, and tabs (on a mac) - javascript

I ran a few javascript files thru my spaces2tabs converter (ps I was porting to coffeescript which is why I needed tabs - have since abandoned coffeescript)
public static String convertSpacesToTabs(String str, int spacesPerTab) {
assert (spacesPerTab >= 1);
StringBuilder builder = new StringBuilder();
for (int i = 0; i = 0) {
//System.out.println("old: " + oldIdx + " new: " + newIdx);
sb.append(str.substring(oldIdx, newIdx));
sb.append('\t');
oldIdx = newIdx + toFind.length();
newIdx = str.indexOf(toFind, oldIdx);
}
sb.append(str.substring(oldIdx, str.length()));
return sb.toString();
}
Worked like a charm: replaced spaces with tabs. Looks perfect in TextMate, runs fine, etc etc. Perfectly valid UTF-8
The ONLY issue comes up in eclipse, where it is a mess.
It seems like eclipse cannot deal with the \t's I inserted. When initially opening the files, eclipse shows a strange character and flags these tabs with the message "Invalid Character" delete this token. When I go to the project properties under Resource I changed text version to utf-8 and the strange characters go away, but the error message doesn't!
Is there an easy way to make eclipse happy?

Seems like a bug in eclipse... no fix as far as I'm aware...

Related

Can not push HTML block into the android html page

I am getting a HTML block from server and want to push it into a html page in android application.
A sample html coming from server (this is the exact output with crlf etc. printed in logcat):
<ul>
<li>217</li>
<li>214</li>
</ul>
This is how I pass the output to the application html page:
runJavaScript("setHTML('"+ html +"')");
public void runJavaScript(final String code){
webview.post(new Runnable() {
#Override
public void run() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(code, null);
}else {
webview.loadUrl("javascript:" + code);
}
}
});
}
and this is the Javascript setHTML function inside the html page which is being called from android:
function setHTML(html){
$("#result").html(html);
}
this is the error:
"Uncaught SyntaxError: Invalid or unexpected token", source:
file:///android_asset/html/en/result.html (1)
I have tried debugging the project by replacing the HTML block with a simple word and it works. I think HTML characters like quotation or crlf may produce the error but I don't want to escape them (I dont want to set pure text but real html). How should I change current codes? thanks.
I guess, it's too late and doesn't answer your question exactly, as you don't want to escape any characters (I'm not sure why though), but maybe it will help somebody.
In my case, before running
runJavaScript("setHTML('"+ html +"')");
I had to escape all single quotation marks and it was enough.
html = html.replace("'", "\\'");

Filenames containing diacritics are not displayed properly using Javascript in NodeJs

So, after having not programmed for 23 years, I decided to start learning Javascript.
I am trying to write a program to read through my music files and create a HTML page based on the files found in a specific directory.
It goes well until I hit filenames containing diacritics in it (like é, ü, ø etc).
For Example: André Hazes turns into : André Hazes
For Example: Andrea Bocelli & Sarah Brightman - Time to Say Goodbye [Con Te Partirò] (single) turn into Andrea Bocelli & Sarah Brightman - Time to Say Goodbye [Con Te PartiroÌ€] (single)
The link I have created doesn't work anymore
The command I use to create the HTML statement is:
<td>${item.vFilename}</td>
This is the code I use to read the files from the filesystem. I work on a Mac, OS Catalina, so basically an Unix variant.
// List all files in a directory in Node.js recursively in a synchronous fashion
var ReadDirFiles = function(pdir, pfilelist) {
files = vFileSystem.readdirSync(pdir,"utf-8");
filelist = pfilelist;
files.forEach(function(file) {
if (vFileSystem.statSync(pdir + '/' + file).isDirectory()) {
filelist = ReadDirFiles(pdir + '/' + file, filelist);
}
else {
vstats = vFileSystem.statSync(pdir + '/' + file);
// debug info
// console.log(vstats);
filelist.push({vFilename: file, vDir: pdir, vBirthtime: formatDate(vstats.birthtime), vSize: vstats.size});
}
});
return filelist;
};
This is the statement I use to write the output to disk and it turns out the problem is in the write statement:
fs.writeFileSync(buildPathHtml.buildPathHtml(), html);
When the output is written back to disk, the conversion of the diacritics happens.
Anyone knows the trick how to work diacritics?
Try using encoding and decoding functions in your script. There are many functions doing this in Javascript, just use what you need. For a complete encoding/decoding you can use (or only copy & paste) into your script the code suggested in https://www.strictly-software.com/htmlencode/. There is a little encoding Javascript library doing the job (encoder.js).
Maybe your file system isn't utf8 based. I read somewhere it's Western for Mac.

Running an Executable file from an ASP.NET web application

I am trying to create a web application that can read certain files (logs) provided by the users and then Use the LogParser 2.2 exe by microsoft to parse the logs and provide the requested output.
The idea i have is to run the Local LogParser.exe present in the Users system and then use the same generated output to ready my output.
I don not know if this approach is correct , However i am trying to do the same and somewhere my code is not correctly being followed and i am not able to find any output/Error .
My code segment is as follows :
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string fileName = #"C:\Program Files (x86)\Log Parser 2.2\LOGPARSER.exe";
string filename = "LogParser";
string input = " -i:IISW3C ";
string query = " Select top 10 cs-ur-stem, count(cs-ur-stem) from " + TextBox1.Text + " group by cs-uri-stem order by count(cs-ur-stem)";
string output = " -o:DATAGRID ";
string argument = filename + input + query + output;
ProcessStartInfo PSI = new ProcessStartInfo(fileName)
{
UseShellExecute = false,
Arguments = argument,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = false
};
Process LogParser = Process.Start(PSI);
LogParser.Start();
}
catch (Exception Prc)
{
MessageBox.Show(Prc.Message);
}
I might be doing something wrong , but can someone point me in correct direction ? Can Javascript ActiveX control may be the way forward ?
All the help is appreciated
(( I am making it as an internal application for my organisation and it is assumed that the log parser will be present in the computer this web application is being used )0
Thanks
Ravi
Add a reference to Interop.MSUtil in your project and then use the COM API as described in the help file. The following using statements should allow you to interact with LogParser through your code:
using LogQuery = Interop.MSUtil.LogQueryClass;
using FileLogInputFormat = Interop.MSUtil.COMTextLineInputContextClass;
Then you can do something like:
var inputFormat = new FileLogInputFormat();
// Instantiate the LogQuery object
LogQuery oLogQuery = new LogQuery();
var results = oLogQuery.Execute(yourQuery, inputFormat);
You have access to a bunch of predefined input formats and output formats (like IIS and W3C)), so you can pick the one that best suits your needs. Also, you will need to run regsvr on LogParser.dll on the machine you are executing on if you have not installed LogParser. The doc is actually pretty good to get you started.

What's the best method to EXTRACT product names given a list of SKU numbers from a website?

I have a problem.
I have a list of SKU numbers (hundreds) that I'm trying to match with the title of the product that it belongs to. I have thought of a few ways to accomplish this, but I feel like I'm missing something... I'm hoping someone here has a quick and efficient idea to help me get this done.
The products come from Aidan Gray.
Attempt #1 (Batch Program Method) - FAIL:
After searching for a SKU in Aidan Gray, the website returns a URL that looks like below:
http://www.aidangrayhome.com/catalogsearch/result/?q=SKUNUMBER
... with "SKUNUMBER" obviously being a SKU.
The first result of the webpage is almost always the product.
To click the first result (through the address bar) the following can be entered (if Javascript is enabled through the address bar):
javascript:{document.getElementsByClassName("product-image")[0].click;}
I wanted to create a .bat file through Command Prompt and execute the following command:
firefox http://www.aidangrayhome.com/catalogsearch/result/?q=SKUNUMBER javascript:{document.getElementsByClassName("product-image")[0].click;}
... but Firefox doesn't seem to allow these two commands to execute in the same tab.
If that worked, I was going to go to http://tools.buzzstream.com/meta-tag-extractor, paste the resulting links to get the titles of the pages, and export the data to CSV format, and copy over the data I wanted.
Unfortunately, I am unable to open both the webpage and the Javascript in the same tab through a batch program.
Attempt #2 (I'm Feeling Lucky Method):
I was going to use Google's &btnI URL suffix to automatically redirect to the first result.
http://www.google.com/search?btnI&q=site:aidangrayhome.com+SKUNUMBER
After opening all the links in tabs, I was going to use a Firefox add-on called "Send Tab URLs" to copy the names of the tabs (which contain the product names) to the clipboard.
The problem is that most of the results were simply not lucky enough...
If anybody has an idea or tip to get this accomplished, I'd be very grateful.
I recommend using JScript for this. It's easy to include as hybrid code in a batch script, its structure and syntax is familiar to anyone comfortable with JavaScript, and you can use it to fetch web pages via XMLHTTPRequest (a.k.a. Ajax by the less-informed) and build a DOM object from the .responseText using an htmlfile COM object.
Anyway, challenge: accepted. Save this with a .bat extension. It'll look for a text file containing SKUs, one per line, and fetch and scrape the search page for each, writing info from the first anchor element with a .className of "product-image" to a CSV file.
#if (#CodeSection == #Batch) #then
#echo off
setlocal
set "skufile=sku.txt"
set "outfile=output.csv"
set "URL=http://www.aidangrayhome.com/catalogsearch/result/?q="
rem // invoke JScript portion
cscript /nologo /e:jscript "%~f0" "%skufile%" "%outfile%" "%URL%"
echo Done.
rem // end main runtime
goto :EOF
#end // end batch / begin JScript chimera
var fso = WSH.CreateObject('scripting.filesystemobject'),
skufile = fso.OpenTextFile(WSH.Arguments(0), 1),
skus = skufile.ReadAll().split(/\r?\n/),
outfile = fso.CreateTextFile(WSH.Arguments(1), true),
URL = WSH.Arguments(2);
skufile.Close();
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
// returns a DOM root object
function fetch(url) {
var XHR = WSH.CreateObject("Microsoft.XMLHTTP"),
DOM = WSH.CreateObject('htmlfile');
WSH.StdErr.Write('fetching ' + url);
XHR.open("GET",url,true);
XHR.setRequestHeader('User-Agent','XMLHTTP/1.0');
XHR.send('');
while (XHR.readyState!=4) {WSH.Sleep(25)};
DOM.write(XHR.responseText);
return DOM;
}
function out(what) {
WSH.StdErr.Write(new Array(79).join(String.fromCharCode(8)));
WSH.Echo(what);
outfile.WriteLine(what);
}
WSH.Echo('Writing to ' + WSH.Arguments(1) + '...')
out('sku,product,URL');
for (var i=0; i<skus.length; i++) {
if (!skus[i]) continue;
var DOM = fetch(URL + skus[i]),
anchors = DOM.getElementsByTagName('a');
for (var j=0; j<anchors.length; j++) {
if (/\bproduct-image\b/i.test(anchors[j].className)) {
out(skus[i]+',"' + anchors[j].title.trim() + '","' + anchors[j].href + '"');
break;
}
}
}
outfile.Close();
Too bad the htmlfile COM object doesn't support getElementsByClassName. :/ But this seems to work well enough in my testing.

How to use xpath in Selenium RC with JavaScript?

I am using Selenium RC with IE 6 and XPath locators are terribly
slow.
So I am trying to see if javascript-xpath actually speeds up things.
But could not find enough/clear documentation on how to use native x-
path libraries.
I am doing the following:
protected void startSelenium (String testServer, String appName, String testInBrowser){
selenium = new DefaultSelenium("localhost", 4444, "*" +testInBrowser, testServer+ "/"+ appName + "/");
echo("selenium instance created:"+selenium.getClass());
selenium.start();
echo("selenium instance started..." + testServer + "/" + appName +"/");
selenium.runScript("lib/javascript-xpath-latest-cmp.js");
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("true");
}
This results in speed improvement of XPath locator but the
improvements are not consistent. On some runs the time taken for a
locator is halved; while sometimes its randomly high.
Am I missing any configuration step here? Would be great if someone
who has had success with this could share their views and approach.
Thanks,
Nirmal
Solution:
protected void startSelenium (String testServer, String appName, String testInBrowser){
selenium = new DefaultSelenium("localhost", 4444, "*" +testInBrowser, testServer+ "/"+ appName + "/");
echo("selenium instance created:"+selenium.getClass());
selenium.start();
echo("selenium instance started..." + testServer + "/" + appName +"/");
selenium.useXpathLibrary("javascript-xpath");
}
I implemented this myself and I only had to do selenium.useXpathLibrary("javascript-xpath"). In my tests, the javascript xpath was about 7x faster on IE 8. Haven't really tested on anything else, but we only use it for IE.
I have never done this but think that you may need to do something like
//Add the library to the page since runScript just does an eval on the JS
selenium.runScript("document.body.append(document.createElement('script')).src = 'path/to/lib');");
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("true");
You will need to add the library to the page and then load it.
However, I would recommend using CSS Selectors instead of XPath Selectors as they are a lot faster in Selenium. You can see how to use different locator strategies here. I have seen tests become at least twice as fast as the original XPath.

Categories

Resources