I have embedded two images in this svg, but the images doesn't show up. What's wrong with what I did?
http://dl.dropbox.com/u/5363697/whirl_browserready.svg
MORE INFORMATION:
I do the image embedding with the following code, in case it helps:
xpath_expr = '//*[#{1}="{0}"]'.format(layername, INKSCAPE_XPATH('label') )
layer_el = svg_doc.xpath( xpath_expr,
namespaces = NE_NS_MAP
)[0]
obj_id = layer_el.attrib['id']
# Keep it safe somewhere, now export that little element as an image
output_el = tempfile.NamedTemporaryFile(
suffix='_temp.svg' )
cmd_line = [
'inkscape',
'--export-id=' + obj_id,
'--export-id-only',
'--export-area-drawing',
'--export-dpi=90', # Change here if required
'--export-png=' + output_el.name,
REL_SIMPLIFIED_LOCATION
]
subprocess.check_call( cmd_line )
# Now load back the file, as a 'buffer'
whole_file = output_el.read()
assert len( whole_file ) > 0
bf = base64.b64encode( whole_file )
# Change that 'g' element by an 'image' element
g_element = etree.Element(SVG('image') )
g_element.attrib[XLINK('href')] = "data:image/png;base64," + bf
(width, height) = get_object_size( obj_id )
print(width,height)
g_element.attrib[SVG('width')] = str( width )
g_element.attrib[SVG('height')] = str( height )
svg_doc.replace( layer_el, g_element )
It turned-out that the prefix
g_element.attrib[SVG('width')] = str( width )
in the width attribute is not required (the attribute itself is). Said prefix was causing Inkscape to strip the attribute from the document in a posterior post-processing step.
Related
I am trying to read series of dicom images from a folder named as series 8.below is code to read series of dicom images from a particular folder.i am getting error index exceeds matrix dimensions at info = dicominfo(fullfile(fileFolder,fileNames{1})).
clear all;
close all;
clc;
fileFolder = fullfile(pwd, 'series 8');
files = dir ( fullfile (fileFolder, '*.dcm'));
fileNames = {files.name};
%examine file header (metadata , from dicom stack)
info = dicominfo(fullfile(fileFolder,fileNames{1}))
%extract size info from metadata
voxelsize = [info.PixelSpacing;info.SliceThickness];
%read one file to get size
I = dicomread(fullfile(fileFolder,fileNames{1}))
classI = class(I);
sizeI = size(I);
numImages = length(fileNames);
%read slice images populate 3d matrix
hWaitBar = waitbar(0,'reading dicom files');
%create array
mri= zeroes(info.rows , info.columns , numImages , classI )
for i=length(fileNames):-1:1
fname = fullfile(fileFolder, fileNames{i});
mri(:,:,i) = unit16(dicomread(fname));
waitbar((length(fileNames)-i+1)/length(fileNames))
end
delete(hWaitBar);
Below two options that will do it. In the first you create a loop around your whole approach and as filenames is zero when there is no dcm file the loop will not get executed. The second option tests whether files is empty and if so it is not executed.
clear all;
close all;
clc;
fileFolder = fullfile(pwd, 'series 8');
files = dir ( fullfile (fileFolder, '*.dcm'));
fileNames = {files.name};
%examine file header (metadata , from dicom stack)
for i=length(fileNames):-1:1
if (i == 1)
info = dicominfo(fullfile(fileFolder,fileNames{i}));
%extract size info from metadata
voxelsize = [info.PixelSpacing;info.SliceThickness];
%read one file to get size
I = dicomread(fullfile(fileFolder,fileNames{i}));
classI = class(I);
sizeI = size(I);
numImages = length(fileNames);
%read slice images populate 3d matrix
hWaitBar = waitbar(0,'reading dicom files');
%create array
mri= zeroes(info.rows , info.columns , numImages , classI );
else
fname = fullfile(fileFolder, fileNames{i});
mri(:,:,i) = unit16(dicomread(fname));
waitbar((length(fileNames)-i+1)/length(fileNames))
end
end
delete(hWaitBar);
the second
clear all;
close all;
clc;
fileFolder = fullfile(pwd, 'series 8');
files = dir ( fullfile (fileFolder, '*.dcm'));
fileNames = {files.name};
%examine file header (metadata , from dicom stack)
if ~isempty(files)
info = dicominfo(fullfile(fileFolder,fileNames{1}))
%extract size info from metadata
voxelsize = [info.PixelSpacing;info.SliceThickness];
%read one file to get size
I = dicomread(fullfile(fileFolder,fileNames{1}))
classI = class(I);
sizeI = size(I);
numImages = length(fileNames);
%read slice images populate 3d matrix
hWaitBar = waitbar(0,'reading dicom files');
%create array
mri= zeroes(info.rows , info.columns , numImages , classI )
for i=length(fileNames):-1:1
fname = fullfile(fileFolder, fileNames{i});
mri(:,:,i) = unit16(dicomread(fname));
waitbar((length(fileNames)-i+1)/length(fileNames))
end
delete(hWaitBar);
end
In VIM it is possible to highlight a character only if the line goes over a certain length, for example:
Can this be done in Sublime Text 2 or 3? I know there's a setting to display rulers but I find them a bit distracting sometimes.
javiervd
Can this be done in Sublime Text 2 or 3?
Save the following script #:
/Packages/Highlight Long Lines/highlight_long_lines.py
import sublime, sublime_plugin
class highlight_long_lines( sublime_plugin.EventListener ):
def on_modified_async( self, view ):
#▒▒▒▒▒▒▒▒ Settings ▒▒▒▒▒▒▒▒#
maxLength = 80
scope = "Invalid"
firstCharacter_Only = False
view.erase_regions( "LongLines" )
indentationSize = view.settings().get( "tab_size" )
indentation_IsSpace = view.settings().get( "translate_tabs_to_spaces" )
document = sublime.Region( 0, view.size() )
lineRegions = view.lines( document )
invalidRegions = []
for region in lineRegions:
text = view.substr( region )
text_WithoutTabs = text.expandtabs( indentationSize )
if text_WithoutTabs.isspace():
tabOffset = 0
else:
tabCount = text.count( " " )
tabDifference = len( text_WithoutTabs ) - len( text )
tabOffset = tabDifference
lineLength = ( region.end() - region.begin() ) - tabOffset
if lineLength > maxLength:
highlightStart = region.begin() + ( maxLength - tabOffset )
if firstCharacter_Only == True:
highlightEnd = highlightStart + 1
else:
highlightEnd = region.end()
invalidRegion = sublime.Region( highlightStart, highlightEnd )
invalidRegions.append( invalidRegion )
if len( invalidRegions ) > 0:
view.add_regions( "LongLines", invalidRegions, scope )
Variable Settings:
maxLength affects the length that lines will highlight after.
scope affects the color of the highlighted regions.
You can use any scope from your active .tmTheme file ( color scheme ).
firstCharacter_Only affects the extent of the highlighted regions.
If set to True, only the character at the 81st position will be highlighted.
If set to False, all characters after the 80th position will be highlighted.
You could just search for this regular expression:
(?<=.{80}).+
It would be navigable and on-demand.
You can extend(copy-rename and use) the syntax highlight and add a rule with this specific case!
you can add a regex similar to this:
<key>charAt</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>match</key>
<string>(?<=^.{21})(.)</string>
<key>name</key>
<string>invalid.illegal.bad-comments-or-CDATA.html</string>
</dict>
</array>
</dict>
where 21 is the position to highlight
I am wondering if there is a out of the box way, or a plugin that can achieve the following behaviour in SublimeText3.
I would like to put the caret at a certain line. And then select all the text until another line number. The amount of lines should be variable.
For example put the caret on 10 and then expand selection to line 21 or line 104.
I hate having to hold down key or use the mouse for this action.
I wrote a simple plugin that allows you to enter a line to select until via an input_panel:
Features:
works bidirectionally
respects the current selection
only executes if there is a single selection
Setup Info:
# GitHub
Code:
import sublime, sublime_plugin
class SelectToLineCommand( sublime_plugin.TextCommand ):
def run( self, edit ):
window = self.view.window()
selections = self.view.sel()
if len( selections ) != 1:
return
self.currentSelection = selections[0]
if self.currentSelection.a > self.currentSelection.b:
self.currentSelection = sublime.Region( self.currentSelection.b, self.currentSelection.a )
window.show_input_panel( "Select To Line Number", "", self.get_LineNumber, None, None )
def get_LineNumber( self, userInput ):
lineToRow_Offset = 1
row = int( userInput ) - lineToRow_Offset
selectionEnd_Row = self.view.text_point( row, 0 )
currentSelection = self.currentSelection
if selectionEnd_Row >= currentSelection.b:
selectionStart = currentSelection.a
selectionEnd = self.view.line( selectionEnd_Row ).b
elif selectionEnd_Row < currentSelection.a:
selectionStart = currentSelection.b
selectionEnd = self.view.line( selectionEnd_Row ).a
newSelection = sublime.Region( selectionStart, selectionEnd )
self.view.selection.clear()
self.view.selection.add( newSelection )
I am using R to extract tweets and analyse their sentiment, however when I get to the lines below I get an error saying "Object of type 'closure' is not subsettable"
scores$drink = factor(rep(c("east"), nd))
scores$very.pos = as.numeric(scores$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
Full code pasted below
load("twitCred.Rdata")
east_tweets <- filterStream("tweetselnd.json", locations = c(-0.10444, 51.408699, 0.33403, 51.64661),timeout = 120, oauth = twitCred)
tweets.df <- parseTweets("tweetselnd.json", verbose = FALSE)
##function score.sentiment
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
# Parameters
# sentences: vector of text to score
# pos.words: vector of words of postive sentiment
# neg.words: vector of words of negative sentiment
# .progress: passed to laply() to control of progress bar
scores = laply(sentences,
function(sentence, pos.words, neg.words)
{
# remove punctuation
sentence = gsub("[[:punct:]]", "", sentence)
# remove control characters
sentence = gsub("[[:cntrl:]]", "", sentence)
# remove digits?
sentence = gsub('\\d+', '', sentence)
# define error handling function when trying tolower
tryTolower = function(x)
{
# create missing value
y = NA
# tryCatch error
try_error = tryCatch(tolower(x), error=function(e) e)
# if not an error
if (!inherits(try_error, "error"))
y = tolower(x)
# result
return(y)
}
# use tryTolower with sapply
sentence = sapply(sentence, tryTolower)
# split sentence into words with str_split (stringr package)
word.list = str_split(sentence, "\\s+")
words = unlist(word.list)
# compare words to the dictionaries of positive & negative terms
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
# get the position of the matched term or NA
# we just want a TRUE/FALSE
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
# final score
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress )
# data frame with scores for each sentence
scores.df = data.frame(text=sentences, score=scores)
return(scores.df)
}
pos = readLines(file.choose())
neg = readLines(file.choose())
east_text = sapply(east_tweets, function(x) x$getText())
scores = score.sentiment(tweetseldn.json, pos, neg, .progress='text')
scores()$drink = factor(rep(c("east"), nd))
scores()$very.pos = as.numeric(scores()$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
# how many very positives and very negatives
numpos = sum(scores$very.pos)
numneg = sum(scores$very.neg)
# global score
global_score = round( 100 * numpos / (numpos + numneg) )
If anyone could help with as to why I'm getting this error it will be much appreciated. Also I've seen other answeres about adding '()' when referring to the variable 'scores' such as scores()$.... but it hasn't worked for me. Thank you.
The changes below got rid of the error:
x <- scores
x$drink = factor(rep(c("east"), nd))
x$very.pos = as.numeric(x$score >= 2)
x$very.neg = as.numeric(x$score <= -2)
I have a simple captcha,I want to recognize the picture.
the picture is like:
I want to use the tesseract. http://code.google.com/p/tesseract-ocr/
but the tesseract only can use on the clear picture.
so I should preprocess the pic.
the preprocess code is:
im = Image.open('test.png')
# text = image_to_string(im)
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(4)
img = img.convert("RGBA")
width,height = im.size
# pixdata = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if im.getpixel((x,y)) != (0,0,0):
im.putpixel((x,y),(255,255,255) )
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if y<2 or y>(img.size[1]-3):
continue
if im.getpixel((x, y))[0]==255 and im.getpixel((x, y+2))[0]==0 and im.getpixel((x, y-1))[0]==0:
im.putpixel((x, y),(0,0,0))
# else:
# continue
list(im.getdata())
im.show()
after the process,the pic is like:
so I failed. can anyone give me some tips?
I know how to remove the line if the line is a pixel width,but the line here is not consistent.