Preformatting HTML and displaying it in template - syntax-highlighting

I got some text in markdown format, I want to return it to my template so it can be displayed as html. For this I have defined a Handlebars helper:
Handlebars.registerHelper('markdown_highlight', function (options) {
var converter = new Showdown.converter();
var res = '';
var html =converter.makeHtml(options.fn(this));
var high = hljs.highlightAuto(html).value;
res += high;
return res;
});
The result comes out formatted but it is displayed directly as html:
pre><code> class Foo(object): def __init__(self, i, j): self.i, self.j = i, j def __str__(self): return “(%d, %d)” % (self.i, self.j) def __setitem__(self, idx, v): if idx == 0: self.i = v elif idx == 1: self.j = v else: raise RuntimeError(“Index out of bounds [0,1]”) </code></pre> <p>Make a subclass of Foo, named Bar, that implements the special methods <strong>eq</strong> and <strong>repr</strong>, such that the following code works: </p> <pre><code>&gt;&gt;&gt; f = Bar(1,2)age 3 &gt;&gt;&gt; g = Bar(2,2) &gt;&gt;&gt; f == g False &gt;&gt;&gt; g == eval(repr(g)) True &gt;&gt;&gt; g[0] = 1 &gt;&gt;&gt; f == g True </code></pre>
What's happening in the helper function is not so important, but someone might be able to help explain how I can make sure the returned html is displayed as html.

Are you are saying that the html is escaped?
If so use the {{{ & }}} instead of {{ & }} in you template. Eg.
{{{markdown_highlight markdown_snippet}}}`
https://stackoverflow.com/a/7173159/236564

Instead of
return res;
Try:
return new Handlebars.SafeString(res);

Template['timeline-item'].rendered = ->
d = #find 'code'
if d
hljs.highlightBlock d
i use these code, this can make hljs work.
and in your template, warp your template context in {{{content}}}.

Related

How to correctly use Distributed Data Parallel when customizing 'parameters' in the model ?

I have customized a parameter in my model:
self.params = list(self.backbone.parameters())
for head in self.headlist:
self.params += list(head.parameters())
When I wrap my model with DDP, an error occurs when defining the optimizer
optimizer = optim.SGD(model.params, lr=FLAGS.lr, momentum=FLAGS.momentum, weight_decay=FLAGS.weight_decay)
AttributeError 'DistributedDataParallel' object has no attribute 'params '
I think the error is probably caused by my customized "self.params"
Is the following code correct:
model = torch.nn.parallel.DistributedDataParallel(model,device_ids=local_rank)
model_without_ddp = model.module
**
optimizer = optim.SGD(model_without_ddp.params, lr=FLAGS.lr, momentum=FLAGS.momentum, weight_decay=FLAGS.weight_decay)
Or is there any simpler code?
###################################
The detailed definition of the network is as follows:
class multiheadModel():
def __init__(self, num_heads, device, model_name):
self.device = device
self.num_heads = num_heads # global+K
if model_name == 'fcn8s':
self.backbone = VGG16_FCN8s(num_classes=19, backbone=1, head=0).to(device)
self.headlist = [VGG16_FCN8s(num_classes=19, backbone=0, head=1).to(device) for i in range(num_heads)]
self.model = VGG16_FCN8s(num_classes=19).to(device)
for name, param in self.backbone.named_parameters():
if ('conv3' in name) or ('conv4' in name):
param.requires_grad = True
else:
param.requires_grad = False
elif model_name == 'deeplab':
self.backbone = Res_Deeplab(num_classes=19, backbone=1, head=0).to(device)
self.headlist = [Res_Deeplab(num_classes=19, backbone=0, head=1).to(device) for i in range(num_heads)]
self.model = Res_Deeplab(num_classes=19).to(device)
for name, param in self.backbone.named_parameters():
if 'layer3' in name:
param.requires_grad = True
else:
param.required_grad = False
else:
print('ERROR : wrong model name')
sys.exit()
self.params = list(self.backbone.parameters())
for head in self.headlist:
self.params += list(head.parameters())
self.loss_fn = None
#self.k2head = {0:2,1:1,2:0,3:0,4:0,5:4,6:4,7:5}
#self.k2head = {0:2,1:1,2:0,3:0,4:0,5:3,6:3,7:4}
self.k2head = {0:2,1:1,2:0,3:0,4:3,5:3,6:4}
# set train and eval mode
def train(self):
self.backbone.train()
for head in self.headlist:
head.train()
def eval(self):
self.backbone.eval()
for head in self.headlist:
head.eval()
def computePredLoss(self, rgb, lbl, k):
x = self.backbone(rgb)
head_id = list(range(self.num_heads))
head_id.remove(self.k2head[k])
input_size = rgb.size()[2:]
loss = 0
for i in head_id:
pred = self.headlist[i](x)
pred = F.interpolate(pred, size=input_size, mode='bilinear', align_corners=True)
loss += self.loss_fn(pred, lbl)
return pred, loss
def forward(self, input):
output = {}
if "label" in input:
self.train()
pred,loss = self.computePredLoss(input['rgb'], input['label'], input['k'])
output['pred'], output['loss']=pred, loss
else:
self.eval()
x = self.backbone(input['rgb'])
k = -1
if "k" in input:
k = self.k2head[input['k']]
pred = self.headlist[k](x)
input_size = input['rgb'].size()[2:]
pred = F.interpolate(pred, size=input_size, mode='bilinear', align_corners=True)
output['pred'] = pred
return output
def validate(self, loader, k=-2):
self.eval()
if k!=-2:
val_metrics = StreamSegMetrics(19)
val_metrics.reset()
with torch.no_grad():
for i, (batch, rgb_batch) in enumerate(loader):
rgb_batch = rgb_batch.to(device=self.device, dtype=torch.float)
batch = batch.to(device=self.device, dtype=torch.int64)
input_size = rgb_batch.size()[2:]
x = self.backbone(rgb_batch)
pred = self.headlist[k](x)
pred = F.interpolate(pred, size=input_size, mode='bilinear', align_corners=True)
preds = pred.detach().max(dim=1)[1].cpu().numpy()
targets = batch.cpu().numpy()
val_metrics.update(targets, preds)
score = val_metrics.get_results()
else:
val_metrics = [StreamSegMetrics(19) for i in range(self.num_heads)]
for metric in val_metrics:
metric.reset()
with torch.no_grad():
for i, (batch, rgb_batch) in enumerate(loader):
rgb_batch = rgb_batch.to(device=self.device, dtype=torch.float)
batch = batch.to(device=self.device, dtype=torch.int64)
input_size = rgb_batch.size()[2:]
x = self.backbone(rgb_batch)
for k in range(self.num_heads):
pred = self.headlist[k](x)
pred = F.interpolate(pred, size=input_size, mode='bilinear', align_corners=True)
preds = pred.detach().max(dim=1)[1].cpu().numpy()
targets = batch.cpu().numpy()
val_metrics[k].update(targets, preds)
score = [val_metrics[k].get_results() for k in range(self.num_heads)]
return score
def getHeadPaths(self, model_path, iteration=-1):
head_paths = []
if '_iter' in model_path:
base_path = model_path.split('_iter')[0]
else:
base_path = model_path.split('.pth')[0]
if iteration==-1:
for i in range(self.num_heads-1):
head_paths.append(base_path+'_except_g'+chr(97+i)+'.pth')
head_paths.append(model_path)
else:
for i in range(self.num_heads-1):
head_paths.append(base_path+'_except_g'+chr(97+i)+'_iter'+str(iteration)+'.pth')
head_paths.append(base_path+'_iter'+str(iteration)+'.pth')
return head_paths
def save(self, model_path, iteration=-1):
self.model.load_state_dict(self.backbone.state_dict(), strict=False)
head_paths = self.getHeadPaths(model_path, iteration)
for i in range(self.num_heads):
self.model.load_state_dict(self.headlist[i].state_dict(), strict=False)
torch.save(self.model.state_dict(), head_paths[i])
def load(self, model_path):
iteration = -1
if '_iter' in model_path:
iteration = int(model_path.split('_iter')[1].split('.pth')[0])
self.model.load_state_dict(torch.load(model_path))
self.backbone.load_state_dict(self.model.state_dict(), strict=False)
head_paths = self.getHeadPaths(model_path, iteration)
existance = 1
for path in head_paths:
if os.path.isfile(path)==False:
existance = 0
if existance==1:
print('loading from multiheads')
for i in range(self.num_heads):
self.model.load_state_dict(torch.load(head_paths[i]))
self.headlist[i].load_state_dict(self.model.state_dict(), strict=False)
else:
print('loading from singlehead')
for i in range(self.num_heads):
self.model.load_state_dict(torch.load(head_paths[-1]))
self.headlist[i].load_state_dict(self.model.state_dict(), strict=False)
def __call__(self, input):
return self.forward(input)

InDesign Text Modification Script Skips Content

This InDesign Javascript iterates over textStyleRanges and converts text with a few specific appliedFont's and later assigns a new appliedFont:-
var textStyleRanges = [];
for (var j = app.activeDocument.stories.length-1; j >= 0 ; j--)
for (var k = app.activeDocument.stories.item(j).textStyleRanges.length-1; k >= 0; k--)
textStyleRanges.push(app.activeDocument.stories.item(j).textStyleRanges.item(k));
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
But there are always some ranges where this doesn't happen. I tried iterating in the forward direction OR in the backward direction OR putting the elements in an array before conversion OR updating the appliedFont in the same iteration OR updating it a different one. Some ranges are still not converted completely.
I am doing this to convert the Devanagari text encoded in glyph based non-Unicode encoding to Unicode. Some of this involves repositioning vowel signs etc and changing the code to work with find/replace mechanism may be possible but is a lot of rework.
What is happening?
See also: http://cssdk.s3-website-us-east-1.amazonaws.com/sdk/1.0/docs/WebHelp/app_notes/indesign_text_frames.htm#Finding_and_changing_text
Sample here: https://www.dropbox.com/sh/7y10i6cyx5m5k3c/AAB74PXtavO5_0dD4_6sNn8ka?dl=0
This is untested since I'm not able to test against your document, but try using getElements() like below:
var doc = app.activeDocument;
var stories = doc.stories;
var textStyleRanges = stories.everyItem().textStyleRanges.everyItem().getElements();
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
A valid approach is to use hyperlink text sources as they stick to the genuine text object. Then you can edit those source texts even if they were actually moved elsewhere in the flow.
//Main routine
var main = function() {
//VARS
var doc = app.properties.activeDocument,
fgp = app.findGrepPreferences.properties,
cgp = app.changeGrepPreferences.properties,
fcgo = app.findChangeGrepOptions.properties,
text, str,
found = [], srcs = [], n = 0;
//Exit if no documents
if ( !doc ) return;
app.findChangeGrepOptions = app.findGrepPreferences = app.changeGrepPreferences = null;
//Settings props
app.findChangeGrepOptions.properties = {
includeHiddenLayers:true,
includeLockedLayersForFind:true,
includeLockedStoriesForFind:true,
includeMasterPages:true,
}
app.findGrepPreferences.properties = {
findWhat:"\\w",
}
//Finding text instances
found = doc.findGrep();
n = found.length;
//Looping through instances and adding hyperlink text sources
//That's all we do at this stage
while ( n-- ) {
srcs.push ( doc.hyperlinkTextSources.add(found[n] ) );
}
//Then we edit the stored hyperlinks text sources 's texts objects contents
n = srcs.length;
while ( n-- ) {
text = srcs[n].sourceText;
str = text.contents;
text.contents = str+str+str+str;
}
//Eventually we remove the added hyperlinks text sources
n = srcs.length;
while ( n-- ) srcs[n].remove();
//And reset initial properties
app.findGrepPreferences.properties = fgp;
app.changeGrepPreferences.properties = cgp;
app.findChangeGrepOptions.properties =fcgo;
}
//Running script in a easily cancelable mode
var u;
app.doScript ( "main()",u,u,UndoModes.ENTIRE_SCRIPT, "The Script" );

CkEditor text align : left plugin = style='text-align:left'

Hello I am using Ckeditor 4.5.10, I am facing an issue with internal left align plugin. Default left align just remove style attribute from selected tag. What I need, it should be like this <p style='text-align:left'>test</p>
however it is doing like this <p>test</p>
if someone can help me for this thing
Please replace this function inside ckeditor.js and inline text align left start working:-
g.prototype = {
exec: function(a) {
var c = a.getSelection(),
b = a.config.enterMode;
if (c) {
for (var h = c.createBookmarks(), d = c.getRanges(), e = this.cssClassName, g, f, k = a.config.useComputedState, k = void 0 === k || k, m = d.length - 1; 0 <= m; m--)
for (g = d[m].createIterator(), g.enlargeBr = b != CKEDITOR.ENTER_BR; f = g.getNextParagraph(b == CKEDITOR.ENTER_P ? "p" : "div");)
if (!f.isReadOnly()) {
f.removeAttribute("align");
f.removeStyle("text-align");
f.setStyle("text-align", this.value);
//console.log(this.value);
var l = e && (f.$.className = CKEDITOR.tools.ltrim(f.$.className.replace(this.cssClassRegex, ""))),
p = this.state == CKEDITOR.TRISTATE_OFF && (!k || n(f, !0) != this.value);
e ? p ? f.addClass(e) : l || f.removeAttribute("class") : p && f.setStyle("text-align", this.value)
}
a.focus();
a.forceNextSelectionCheck();
c.selectBookmarks(h)
}
},
refresh: function(a, c) {
var b = c.block || c.blockLimit;
this.setState("body" != b.getName() && n(b, this.editor.config.useComputedState) == this.value ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF)
}
};
I have included this line in above function:- f.setStyle("text-align",
this.value);
I had the same problem with CKEditor4. I managed to solve it by using a custom build. First of all, you have to be familiar with CKEditor4 custom build process. If you are, you can continue, if not, it is highly recommended to follow the instruction:
The development repository of CKEditor 4
If you are here, it means that you are familiar with the custom build process of CKEditor4. In order to address this problem, we should modify the Justify plugin. You have to edit the file in plugins/justify/plugin.js path, and replace
} else if ( apply && isAllowedTextAlign ) {
With
} else {
In other words, you have to get rid of the condition of setting the text-align CSS style.

Don't see images on my buttons if I create them with a loop

I'm trying to make a program in Python 3.3.0 to train with Tkinter, but when I try to put images on buttons which are created in a loop, I obtain a few buttons that don't work (I can't click on them and they don't have images), and the last one is working and with the image on it. Here there's the code:
elenco = [immagine1, immagine2, immagine3, immagine 4]
class secondWindow:
def __init__(self):
self.secondWindow = Tk()
self.secondWindow.geometry ('500x650+400+30')
class mainWindow:
def __init__(self):
self.mainWindow = Tk()
self.mainWindow.geometry ('1100x650+100+10')
self.mainWindow.title('MainWindow')
def Buttons(self, stringa):
i = 0
for _ in elenco:
if stringa in _.lower():
j = int(i/10)
self.IM = PIL.Image.open (_ + ".jpg")
self.II = PIL.ImageTk.PhotoImage (self.IM)
self.button = Button(text = _, compound = 'top', image = self.II, command = secondWindow).grid(row = j, column = i-j*10)
i += 1
def mainEnter (self):
testoEntry = StringVar()
self.mainEntry = Entry(self.mainWindow, textvariable = testoEntry).place (x = 900, y = 20)
def search ():
testoEntry2 = testoEntry.get()
if testoEntry2 == "":
pass
else:
testoEntry2 = testoEntry2.lower()
mainWindow.Buttons(self, testoEntry2)
self.button4Entry = Button (self.mainWindow, text = 'search', command = search).place (x = 1050, y = 17)
MW = mainWindow()
MW.mainEnter()
mainloop()
If I try to create buttons in a loop without images, they work:
def Buttons(self, stringa):
i = 0
for _ in elenco:
if stringa in _.lower():
j = int(i/10)
self.button = Button(text = _, command = secondWindow).grid(row = j, column = i-j*10)
i += 1
And if I try to create a button with an image but not in a loop, it works too:
im = PIL.Image.open("immagine1.jpg")
ge = PIL.ImageTk.PhotoImage (im)
butt = Button(text = 'immagine', compound = 'top', image = ge, command = secondWindow).grid(row = 0, column = 0)
Let's say you have images named "image-i.png", i=0,..,9.
When I execute the following code (with python 3.5) I obtain ten working buttons with image and text:
from tkinter import Tk, Button, PhotoImage
root = Tk()
images = []
buttons = []
for i in range(10):
im = PhotoImage(master=root, file="image-%i.png" % i)
b = Button(root, text="Button %i" % i, image=im, compound="left",
command=lambda x=i: print(x))
b.grid(row=i)
images.append(im)
buttons.append(b)
root.mainloop()

How to iterate two arrays in CoffeeScript

I'm trying to rewrite example from classic book "JavaScript: The Good Parts" in CoffeeScript via list comprehensions:
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)
(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = “http://www.ora.com:80/goodparts?q#fragment”;
var result = parse_url.exec(url);
var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
var blanks = ' ';
var i;
for (i = 0; i < names.length; i += 1) {
document.writeln(names[i] + ':' +
blanks.substring(names[i].length), result[i]);
}
I can't get how to write loop and stuck with this code:
console.log "#{name}: " for name in names
I imagine you are trying to do something Like this
parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/
url = 'http://www.ora.com:80/goodparts?q#fragment'
result = parse_url.exec(url)
names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash']
alert "#{names[i]}: #{result[i]}" for i in [0..names.length-1]
In case someone comes here actually needing to iterate two arrays at the same time, this works:
for [course_event, remote_event] in zip(course.events, remote.events)
course_event.lessons = remote_event.lessons if event.lessons_need_updating
zip() is from here:
zip = () ->
lengthArray = (arr.length for arr in arguments)
length = Math.min(lengthArray...)
for i in [0...length]
arr[i] for arr in arguments

Resources