How to add another block after exact block in Slate.js editor? - slate.js

This code changes type of the block with matched text.
How to add another block AFTER this one in Slate.js?
import {Range} from 'slate';
import {blockTypes} from 'core/slate-types';
export default function autoreplaceHeading(node, matched, change) {
const matchedLength = matched[0].length;
return change
.setBlocks(blockTypes.HEADING)
.deleteAtRange(
Range.create({
anchorKey: node.key,
focusKey: node.key,
anchorOffset: matched.index,
focusOffset: matched.index + matchedLength
})
);
}

Related

CouchDB: View to return only certain documents?

I have (tried) to write a view to identify documents with an "otherCauseForRelease" attribute AND that attribute is actually populated. My View code is:
function (doc) {
if(doc.payload.otherCauseForRelease.length > 5); emit(doc.payload.otherCauseForRelease);
}
However, the return set includes documents with attribute values like "" (an open double-quotation followed by a close double-quotation). How can I exclude these documents from my results?
Try with this one here :
function (doc) {
if(doc.payload.otherCauseForRelease.length > 5)
emit(doc.payload.otherCauseForRelease);
}
You basically add an extra ; at the end of your if. Doing so, it didn't consider the next statement as the body of the if.
Another example with curly braces:
function (doc) {
if(doc.payload.otherCauseForRelease.length > 5){
emit(doc.payload.otherCauseForRelease);
}
}

Matching parameters of a function with Regex

What I have so far: \w+\(((".+")|(\d+))+\)I'm not sure how to go about matching more than one paramter separated by a comma. How can I capture the parameters (and function names) of the following test cases?
scroll("foo")
scroll("foo",55)
scroll("foo","bar")
scroll("foo","bar",55)
scroll(55)
scroll(55,"foo")
scroll(55, 13,"foo","bar")
For example, in the last one the groups must be scroll, 55, 13, "foo", and "bar".
Edit: Language is AS3
Try this lengthy regex:
(\"?\w+\"?)\((\"?\w+\"?)(?:[,\s]+(\"?\w+\"?))?(?:[,\s]+(\"?\w+\"?))?(?:[,\s]+(\"?\w+\"?))?\)?
The code above is set to capture up to five parameters. You can adjust that by adding/removing this code (?:[,\s]+(\"?\w+\"?))? based on your needs.
Demo: https://regex101.com/r/o1RRSG/1
i hope i'm in right way
you want to split for example
this: scroll ( 55, 13, "foo", "bar" )
to its function name and arguments like
this: scroll ( 55, 13, "foo", "bar" )
a better result of expression:
i just assume additional white spaces for more accuracy
the regex fot would be :
[^\t (,)]
Okay, you may not like it, but it's flawless as long as you have ExternalInterface backed with JS available. And it's funny. (While doing this with reg exps is the opposite of fun.)
The idea is to let JS do its eval. The manual says you have to pass a function name to ExternalInterface.call(), which is not true: pass just any code that evaluates to a function reference. This way you can inject any JS code into the page where your SWF resides (which is why AllowScriptAccess is such a terribly dangerous attribute).
public class Test extends Sprite
{
public function Test()
{
var test = "scroll(55, 13,\"foo\",\"bar\", \"now(), we are \\\"screwed\\\")\")";
trace(test);
var details = parseFunctionCall(test);
trace(details[0]);
for (var i = 1; i<details.length; i++) {
trace("\t"+i+": "+typeof(details[i])+" "+details[i]);
}
}
private function parseFunctionCall(input:String):Array
{
if (ExternalInterface.available) {
var split:RegExp = /^(\w+)\((.+)\)$/;
var info = split.exec(input);
var inject = "(function(){return ["+info[2]+"];})";
var params = ExternalInterface.call(inject);
params.unshift(info[1]);
return params;
}
return null;
}
}
/*
Output:
scroll
1: number 55
2: number 13
3: string foo
4: string bar
5: string now(), we are "screwed")
*/

iText: Can PdfTemplate of one Document object be used in another Document Object?

I am using iText2.1.2 and my requirement is to use the template created from Document1 object onto Document2 object.
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestITextTemplate {
public TestITextTemplate() {
super();
}
public static final String DEST = "D:\\Doc1.pdf";
public static final String DEST1 = "D:\\Doc2.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new TestITextTemplate().createPdf();
}
public void createPdf() {
try {
//1st Document Object.
Document document = new Document();
FileOutputStream fos = new FileOutputStream(DEST);
PdfWriter writer = PdfWriter.getInstance(document, fos);
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template =
contentByte.createTemplate(document.getPageSize().getWidth(), document.getPageSize().getHeight());
Graphics2D g2 =
template.createGraphicsShapes(document.getPageSize().getWidth(), document.getPageSize().getHeight());
template.setLineWidth(Float.parseFloat(2 + "") * 0.72f);
g2.drawString("Test String", 100, 120);
g2.dispose();
contentByte.addTemplate(template, 0, 0);
writer.releaseTemplate(template);
document.close();
//2nd Document Object.
Document document1 = new Document();
FileOutputStream fos1 = new FileOutputStream(DEST1);
PdfWriter writer1 = PdfWriter.getInstance(document1, fos1);
document1.open();
PdfContentByte contentByte1 = writer1.getDirectContent();
PdfTemplate template1 =
contentByte1.createTemplate(document1.getPageSize().getWidth(), document1.getPageSize().getHeight());
Graphics2D g21 =
template1.createGraphicsShapes(document1.getPageSize().getWidth(), document1.getPageSize().getHeight());
template1.setLineWidth(Float.parseFloat(1 + "") * 0.72f);
g21.draw(new Line2D.Double(0, 120, 400, 120));
g21.dispose();
contentByte1.addTemplate(template, 0, 0);//Adding template of 1st Document object to 2nd Document object.
contentByte1.addTemplate(template1, 50, 50);
writer1.releaseTemplate(template);
writer1.releaseTemplate(template1);
document1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When the contents of the template1 is added after adding the template to the contentByte1, the contents of template is being overwritten by template1.
Is this not possible? How should this work ideally?
Thanks in advance.
When you create the first PdfTemplate instance (template), you create a dependency on the first PdfWriter.
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(...);
This dependency is necessary because you're adding content to the template object that requires resources. These resources are written to the writer object as you go.
As soon as you close your first Document instance (document.close();), the writer is also closed. The template is released implicitly (you didn't have to do this explicitly) and you're done.
Then you create a second PdfTemplate instance (template1), and you create a dependency on a second PdfWriter (writer1). Again you add content to the PdfTemplate and again resources are written to the PdfWriter. These resources are all correctly referenced when you add to the content of writer1.
However: you are also trying to add template to the content of writer1. Common sense should tell you that his cannot work: the resources needed for template are written to writer. They are not present in writer1. Without the resources written to writer, you can never correctly add template to writer1.
The best way to work around this, is to create a small single-page in-memory PDF file with the resource you want to reuse. Reuse that small single-page using a PdfImportedPage object.

Cascading - regex parser - wrong number of fields

Starting to play with Cascading on Amazon EMR, have managed to get it running BUT falling at a fairly simple hurdle and I was hoping someone could shed some light on it.
My code:
import java.util.Properties;
import cascading.flow.Flow;
import cascading.flow.FlowDef;
import cascading.flow.hadoop.HadoopFlowConnector;
import cascading.pipe.Pipe;
import cascading.property.AppProps;
import cascading.scheme.hadoop.TextLine;
import cascading.tap.Tap;
import cascading.tap.hadoop.Hfs;
import cascading.tuple.Fields;
import cascading.operation.regex.RegexParser;
import cascading.pipe.Each;
import cascading.tap.SinkMode;
public class Main
{
public static void
main( String[] args )
{
String inPath = args[ 0 ];
String outPath = args[ 1 ];
Properties properties = new Properties();
AppProps.setApplicationJarClass( properties, Main.class );
HadoopFlowConnector flowConnector = new HadoopFlowConnector( properties );
// create the source tap
TextLine sourceScheme = new TextLine(new Fields("line"));
Tap inTap = new Hfs( sourceScheme, inPath );
// create the sink tap
TextLine sinkScheme = new TextLine( new Fields("custid", "movieids"));
Tap outTap = new Hfs( sinkScheme, outPath, SinkMode.REPLACE );
Fields filmFields = new Fields("custid", "movieids");
String filmRegex = "([0-9]:*[,.]*)";
RegexParser parser = new RegexParser(filmFields, filmRegex);
Pipe importPipe = new Each("import", new Fields("line"), parser, Fields.RESULTS );
// connect the taps, pipes, etc., into a flow
Flow parsedFlow = new HadoopFlowConnector(properties).connect(inTap, outTap, importPipe);
// run the flow
parsedFlow.start();
parsedFlow.complete();
}
}
My input (no empty lines):
1:2
2:4
5:1
3:9
My output:
Task TASKID="task_201305241444_0003_m_000000" TASK_TYPE="MAP" TASK_STATUS="FAILED" FINISH_TIME="1369408133954" ERROR="cascading\.tuple\.TupleException: operation added the wrong number of fields, expected: ['custid', 'movieids'], got result size: 1
at cascading\.tuple\.TupleEntryCollector\.add(TupleEntryCollector\.java:82)
at cascading\.operation\.regex\.RegexParser\.onFoundGroups(RegexParser\.java:168)
at cascading\.operation\.regex\.RegexParser\.operate(RegexParser\.java:151)
at cascading\.flow\.stream\.FunctionEachStage\.receive(FunctionEachStage\.java:99)
at cascading\.flow\.stream\.FunctionEachStage\.receive(FunctionEachStage\.java:39)
at cascading\.flow\.stream\.SourceStage\.map(SourceStage\.java:102)
at cascading\.flow\.stream\.SourceStage\.run(SourceStage\.java:58)
at cascading\.flow\.hadoop\.FlowMapper\.run(FlowMapper\.java:127)
at org\.apache\.hadoop\.mapred\.MapTask\.runOldMapper(MapTask\.java:441)
at org\.apache\.hadoop\.mapred\.MapTask\.run(MapTask\.java:377)
at org\.apache\.hadoop\.mapred\.Child$4\.run(Child\.java:255)
at java\.security\.AccessController\.doPrivileged(Native Method)
at javax\.security\.auth\.Subject\.doAs(Subject\.java:396)
at org\.apache\.hadoop\.security\.UserGroupInformation\.doAs(UserGroupInformation\.java:1132)
at org\.apache\.hadoop\.mapred\.Child\.main(Child\.java:249)
The reg ex checks out fine at http://regexpal.com/
Thanks a lot
Duncan
You get an exception because your regular expression yields one result, where two result fields are excepted (namely "custid" and "movieids"), because the regular expression contains just a single group (...).
If you just want to split at the colon, either use an expression with 2 groups, for example:
String filmRegex = "(\\d):(\\d)";
or \d+, respectively, if your numbers can have more than one digit.
Or, more easily, just split the input data into its fields automatically when reading from the file by using a TextDelimited input scheme:
Scheme sourceScheme = new TextDelimited(new Fields("custid", "movieids"), ":");

Magento: Get product id in php block for available in list.phtml

I'm trying to get an attribute for it to be listed on list.phtml, the form that is being made is as follows:
I created a module on the Block and created a function which captures the attribute:
protected function getPreOrder()
{
$productId = $this->getRequest()->getParam('id');
$product = Mage::getModel('catalog/product')->load($productId);
$preOrder = $product->getNewsFromDate();
$preOrder = substr($preOrder, 0, 10);
return $preOrder;
}
public function getViewList()
{
if(strtotime(date('Y-m-d')) <= strtotime($this->getPreOrder()))
{
return true;
} else {
return false;
}
}
However, nothing is returned. I also did this same method to view.phtml and it worked perfectly. That goes for a file before the function getChildHtml() phtml, is not being edited list.phtml
That makes sense to create a loop, but the loop is already list.phtml!
What would be the way?
I thank you.
Have you debugged your block function to see if the product id is correct and if its loading the model correctly ??
Also debug the template list.phtml to check if its correctly loading the block type ?
get_class($this);
and see what class type is it.