django - markdown and codehilite - django

I'm not sure if I am doing something wrong, but I can't get codehilite to generate code properly, example:
from markdown import markdown
self.content_html = markdown(self.content, ['codehilite'])
and I'm using this C# from wikipedia to test
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string.
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass.
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
and the result is
<p>public class GenericList<T>
{
void Add(T input) { }
}</p>
<p>class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();</p>
<div class="codehilite"><pre> <span class="c1">// Declare a list of type string.</span>
<span class="nx">GenericList</span><span class="o"><</span><span class="kt">string</span><span class="o">></span> <span class="n">list2</span> <span class="o">=</span> <span class="nb">new</span> <span class="nx">GenericList</span><span class="o"><</span><span class="kt">string</span><span class="o">></span><span class="p">();</span>
<span class="c1">// Declare a list of type ExampleClass.</span>
<span class="nx">GenericList</span><span class="o"><</span><span class="nx">ExampleClass</span><span class="o">></span> <span class="n">list3</span> <span class="o">=</span> <span class="nb">new</span> <span class="nx">GenericList</span><span class="o"><</span><span class="nx">ExampleClass</span><span class="o">></span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
<p>}</p>
As you can see, it didn't mark first few lines, and then started with comment // Declare a list of type string. What's wrong?

you should use pygments.
then try putting a :::<language> block up in your markdown before the block of code so it knows how to interpret it.
I wrote a article series about using markdown pygments to create a django blog that may be helpfull as well.
EDIT (this is whats up i think)
you need 4 spaces preceding each line of code for codehilite to pick up on it. ALSO, the first and last lines of code need a \n before and after, your code cannot be butted up against regular text (not indented by 4 spaces). ALSO, your code cannot be embedded into a bulleted list

Related

apache freemarker - render a list as a table

Good morning everyone,
I was wondering if someone can help me to get this done? I'm trying to render an ArrayList as a table using Apache Freemarker.
Imagine the following code (java):
public static void main(String[] args) throws Exception {
// freemarker
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setDirectoryForTemplateLoading(new File("./src/"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
;
Template temp = cfg.getTemplate("template.ftl");
Map m = Collections.singletonMap("names", Arrays.asList("foo", "bar", "baz", "qux", "quux",
"corge", "grault", "garply", "waldo", "fred",
"plugh", "xyzzy", "thud"
));
//
Writer out = new OutputStreamWriter(System.out);
temp.process(m, out);
}
With this template:
<Start>
<#list 0..names?size-1 as i>
${names[i]}
</#list>
<end>
It Will be outputed like this:
<Start>
foo
bar
baz
qux
quux
corge
grault
garply
waldo
fred
plugh
xyzzy
thud
<end>
I was wondering if it was possible with freemarker to have it in columns:
<Start>
foo bar baz
qux quux corge
grault garply waldo
fred plugh xyzzy
thud
<end>
Any idea? Any suggestion is more than welcome.
?chunk can slice up a sequence to smaller sequences (see https://freemarker.apache.org/docs/ref_builtins_sequence.html#ref_builtin_chunk), so with the example of a HTML table you could do this:
<table>
<#list names?chunk(3) as row>
<tr>
<#list row as name><td>${name}</td></#list>
</tr>
</#list>
</table>

Angular/Typescript RegExp enum

Looking to create an enum for some regex to store in my application to allow for code reuse.
Eg:
export enum Regex {
ONE_DANK_REGEX = /^[dank]+$/g,
FIVE_OUT_OF_SEVEN = /^[meme]{5,7}$/g
}
But:
By not using string literals, I get the TS90010 error: Type RegExpis not assignable to type Regex.
By using string literals, I can't use these in a pattern attribute on my inputs
Eg.
<input ngModel="..." pattern="{{FIVE_OUT_OF_SEVEN}}" .../>
Is this the right way of going about doing this?
You cannot assign a RegExp to an enum, an enum can either be numeric or string-based.
So when it comes to storing the RegExp you have two options:
Option A - store the RegExp as string in an enum
enum RegExpEnum {
ONE_DANK_REGEX = "^[dank]+$",
FIVE_OUT_OF_SEVEN = "^[meme]{5,7}$"
}
Option B - store the RegExp in a class/variable
class RegexClass {
public static readonly ONE_DANK_REGEX = /^[dank]+$/g;
public static readonly FIVE_OUT_OF_SEVEN = /^[meme]{5,7}$/g;
}
In both ways you need to get a reference to the containing enum or class in your component. Which can be achieved by assigning it to a local variable.
#Component({ ... })
public class MyComponent {
availableRegex = RegExpEnum; // or RegexClass
}
Then you can access it in the html part of your component.
<input [(ngModel)]="name" [pattern]="availableRegex.ONE_DANK_REGEX"/>
DEMO
Enum will support only strings and Number.
If you wanted to store regular expressions, you need to use static class
export class RegularExpression
{
public static ALPHA_CHARACTERS: RegExp = /([^A-Za-z])+/g;
}
Usage
'Your_* Name'.replace(RegularExpression.ALPHA_CHARACTERS, '');
Prefer the option A mentioned on the currently accepted answer and use it as below the code:
export enum Regex {
ONE_DANK_REGEX = "^[dank]+$",
FIVE_OUT_OF_SEVEN = "^[meme]{5,7}$",
}
public readonly regOne = new RegExp(Regex.ONE_DANK_REGEX, "g");
This gives some flexibility when create the regular expression object.

Call method from other template after rendering

Using Meteor I got a template which consists of 2 other templates A & B.
A got a <select> Tag and B got a <canvas> on which something will drawn depending on the select of template A.
When the selection changes, A should call someMethod` of B, and this method should get some data from the db and then draw the canvas. How can I achieve this behaviour?
Simply using Template.B.someMethod = function (bla) ... and then in the JS of A calling Template.B.someMethod(hi) causes an error because someMethod accesses the DOM canvas Element of B which is not rendered when A changes for the first time at the loading.
What would be a fitting way to call the method? Or should I merge the two templates together?
no need to combine A and B templates. the purpose of the parent here is to coordinate data changes between A and B. i.e. you won't be calling functions on B, but rather giving it the data it needs so it can respond.
P (the parent) can push into A a function that A calls when its data changes via the select. P can then push that data into B through Meteor's normal reactivity. B can then respond to that change.
e.g.
<template name="P">
{{A changeHandler=getChangeHandler}}
{{B selection=selectedData}}
</template>
P.js:
Template.P.onCreated(function() {
this.data = new ReactiveVar();
});
Template.P.helpers({
getChangeHandler() {
let template = Template.instance();
return function(data) {
template.data.set(data);
}
},
selectedData() {
return Template.instance().data.get();
}
});
A.js:
Template.A.onCreated({
this.changeHandler = new ReactiveVar(Template.currentData().changeHandler); // i think this is right
});
and whenever A data changes:
let changeHandlerFn = template.changeHandler.get();
if (_.isFunction(changeHandlerFn)) {
changeHandlerFn(updatedData);
}
Besides #zim's answer, you can also use a variation of https://stackoverflow.com/a/43687311/5108796:
HTML (actually Spacebars)
<template name="Parent">
{{> Child1 sharedVar1=sharedVar}}
{{> Child2 sharedVar2=sharedVar}}
</template>
JavaScript
import { ReactiveVar } from 'meteor/reactive-var';
// Just initialize the variable. Could also be within the scope of a template.
var myReactiveVar = new ReactiveVar();
Template.Parent.helpers({
// This is what will be sent to Child1 and Child2.
sharedVar: function () {
return myReactiveVar;
}
});
Template.Child1.events({
'change select': function (event, template) {
// This will trigger a re-execution of Child2 autorun.
template.data.sharedVar1.set(myNewValue);
}
});
Template.Child2.onCreated(function () {
var sharedVar2 = this.data.sharedVar2;
this.autorun(function () {
// As usual, this is reactive.
var newValue = sharedVar2.get();
// Perform some operation using newValue…
});
});
(of course you can split these into several JS files)

Regex as associative array key?

I'm working on a very performance dependent portion of my code in D. For this, I want to have an associative array mapping my data to a Regex so that I can use it later.
When I try to do this, it gives me the error, index is not a type or expression. How can I use this regex as my array key?
Edit: For code, here's what I'm trying to define in my class:
View[Regex] m_routes;
I want that so that I can add the routes like below:
void add(string route, View view)
{
auto regex = regex(route.key, [ 'g', 'i' ]);
if (regex in m_routes)
throw new Exception(format(`Route with path, "%s", is already assigned!`, route));
m_routes[regex] = view;
}
This would then allow me to check the regex against a route, without having to rebuild each one, shown in this method:
View check(string resource)
{
foreach (route; m_routes.byKeyValue())
{
auto match = matchAll(resource, route.key);
// If this regex is a match
// return the view
if (!match.empty)
{
return route.value;
}
}
return null;
}
Any help would be appreciated, thank you!
It seems std.regex.Regex is an alias that takes a type parameter:
(from std.regex.package, line 289 in release 2.071.0)
public alias Regex(Char) = std.regex.internal.ir.Regex!(Char);
In other words, you'll need to specify the char type for the regex. For string, that'd be char:
View[Regex!char] m_routes;

knockoutjs - custom template is binded with parent content

I have a problem using knockoutjs with custom template bindings.
Suppose I have a HTML body like this:
<div id="1">
<div data-bind="template:{name: '2', data: data}"></div>
</div>
<div id="2">
<h3 data-bind="text: caption"></h3>
</div>
JS code looks like this:
var ViewModel2 = function () {
this.caption = ko.observable("Caption");
}
var ViewModel1 = function () {
this.data = new ViewModel2();
}
ko.applyBindings(new ViewModel1(), document.getElementById("1"));
If we test this code, everything will work just fine;
See JSFiddle example: http://jsfiddle.net/4eTWW/33/
Now suppose we want to make our custom template binding. We'll use 'templatex' binding instead of 'template'.
In HTML we need to change just one line:
<div data-bind="templatex:{name: '2', data: data}"></div>
Next, let's add custom template binding to JS:
/*Custom binding*/
ko.bindingHandlers.templatex = {
init: function (element) {
ko.bindingHandlers.template.init.apply(this, arguments);
},
update: ko.bindingHandlers.template.update
}
See: http://jsfiddle.net/4eTWW/35/
But in this case we have an error, saying that it can't find 'caption' in the model.
Now let's add template {} to html bindings:
<div data-bind="template: {}, templatex:{name: '2', data: data}"></div>
See: http://jsfiddle.net/4eTWW/36/
And now everything works just fine.
It seems that while binding parent div it can't determine that child div is a template.
So how can I mark it as a template in my custom template binder?
Thanks.
You have wrong update handler, change to this:
ko.bindingHandlers.templatex= {
init: function(element) {
// do things
return ko.bindingHandlers.template.init.apply(this, arguments);
},
update: function(element) {
return ko.bindingHandlers.template.update.apply(this, arguments);
}
}
Here is working fiddle: http://jsfiddle.net/vyshniakov/4eTWW/39/
I don't think you can use a custom binding to create a new template engine. You need to register your custom engine with ko.setTemplateEngine().
From the knockoutjs source:
If you want to make a custom template engine,
[1] Inherit from the ko.templateEngine class (like ko.nativeTemplateEngine does)
[2] Override 'renderTemplateSource', supplying a function with this signature:
function (templateSource, bindingContext, options) {
// - templateSource.text() is the text of the template you should render
// - bindingContext.$data is the data you should pass into the template
// - you might also want to make bindingContext.$parent, bindingContext.$parents,
// and bindingContext.$root available in the template too
// - options gives you access to any other properties set on "data-bind: { template: options }"
//
// Return value: an array of DOM nodes
}
[3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
function (script) {
// Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
// For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
}
This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
and then you don't need to override 'createJavaScriptEvaluatorBlock'.
Example: http://jsfiddle.net/6pStz/ (see Note 7 on this page)