Formatting MDX programmatically using prettier - prettier

I would like to format MDX using prettier.
It's working on the playground, but I'm having trouble to get it running programmatically. In my code i get an unchanged result (no error, but not formatted)
Here is what i am doing:
import prettier from "prettier/esm/standalone.mjs";
const markdownParser = require("prettier/parser-markdown");
var formatted = prettier.format(content, {
parser: "mdx",
plugins: [markdownParser],
});
The following works on the playground, but NOT with my current code.
# Hello World
<div class="test" >
Hello
</div>

The problem was that i also had to add the parser for babel.
prettier/parser-babel

Related

How to have correctly rendered mathematical equations in bookdown::gitbook when self_contained = TRUE?

I'm writing a GitBook style bookdown document consisting of several Rmd files, in which I use the option self_contained = TRUE to make self-contained HTML pages (so that later I could distribute them as HTML files instead of multiple files with the HTML pages separate from the pictures displayed on them). When I tried to put mathematical equations using the $ $ tags, I got something like [WARNING] Could not convert TeX math '\frac{1}{\sum_{i=1}^{S} p_{i}^2}', rendering as TeX and the equations were not rendered correctly.
I saw from here that MathJax may not work when self_contained = TRUE, and from here that MathJax is needed to render math in HTML. Indeed, I always get a warning like MathJax doesn't work with self_contained when not using the rmarkdown "default" template, and the equations were rendered correctly if I use self_contained = FALSE.
So, I wonder if it is possible to render math correctly in GitBook style bookdown document while self_contained = TRUE.
I had the same issue and found a partial solution. Right in the index.Rmd after the yaml header, I included this chunk:
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
var src = "true";
if (src === "" || src === "true") src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML";
if (location.protocol !== "file:") if (/^https?:/.test(src)) src = src.replace(/^https?:/, "");
script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$', '$']],
displayMath: [['$$', '$$']],
}
});
</script>
Now, the html-output renders the equations but there are two caveats:
Display equations (with $$ . $$) do work fine, but some of the inline equations ($ . $) exhibit differing styles: In my case, some equations show up in the warnings ("Could not convert TeX math") and look normal. The remaining inline equations have a slightly different look.
On Firefox and Safari the equations render correctly, on Chrome unfortunately not (I did not try other browsers).
Hope that helps a bit!

Regex for extracting only the Youtube Embedment URL in Angular 5

I think it is not very convenient for an user the get this link here:
https://www.youtube.com/embed/GmvM6syadl0
Because YouTube provides an entire code snipped like so:
<iframe width="560" height="315" src="https://www.youtube.com/embed/GmvM6syadl0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
It would be a lot better if the user could take the code snippet above and my program is just going to extract the url for him.
Any ideas how to go about this? I'm usually not very good at extracting data from elaborate strings, what I would like to end up with is something like this:
let yTLink = extractYoutubeLinkfromIframe(providedInput);
extractYoutubeLinkfromIframe(iframeTag) {
// do fancy regex stuff
}
If you will have a format like that iFrame you could use split and I did it using the follwoing code:
extractYoutubeLinkfromIframe(iframeTag) {
let youtubeUrl = iframeTag.split('src');
youtubeUrl = youtubeUrl[1].split('"');
return youtubeUrl[1];
}
First we split by the src, so, we will separte the iFrame string, after that, we split by quote ", to get just the part that we need as the link is with "[link]", we get the first position that will indicate that we want to get the link.

HTML Form returns nothing to clipboard when copying text field value using Selenium Python?

I'm doing a particular automation task using python selenium (currently using mac system)- and for some reason my webElement.text returns nothing for a text field i'd like to copy. Hence I'm trying to copy paste the values, but for whatever reason, the .send_keys works (as I'm able to see values being entered, the cursor moving etc, but after the command+c step, I dont have the values in my clipboard. I tried pasting the clipboard contents via xerox module and it retrieves only the stuff I'd previously copied manually- my selenium driven clipboard content is not seen. I'm wondering how to get around this issue?
/code
from selenium.webdriver.common.keys import Keys
import xerox
elem = browser.find_elements_by_name("callback_url_0")[0]
#elem.send_keys("bar") # for testing purposes, and it works
elem.send_keys(Keys.CONTROL, 'a') #highlight all in box
elem.send_keys(Keys.CONTROL, 'c') #copy
#elem.send_keys(Keys.CONTROL, 'v') #
#xerox.copy()
xerox.paste() #this pastes my old system junk, nothing from the webdriver session
I've even tried Key.COMMAND as I'm on a mac, but nothing changed. Any way to get around or even hack around this issue?
UPDATE:
So, the issue is that I'm working with a text field where in, I'm able to send_keys and type text, but am not able to get its content, both by webDriver Element.text as well as copy paste using above described method. My goal is to get its content and process it further in my script. What could be the issue here and what can I really try to get around this?
UPDATE:
Using command chaining (answer below) perform copy and paste. But my clipboard has no content i.e., returns blank value. The same as the .text method. What could be the issue? Something with the form?
Here's my form html:
<div class="row">
<div class="col-sm-12">
<input app-vast-url-validate="" type="url" class="input-full-width ng-valid-required ng-valid-vast-url ng-dirty ng-touched ng-valid ng-valid-url" id="callback_url_0" name="callback_url_0" ng-model="callback.url" placeholder="Enter Callback URL" ng-keyup="onAddCallbackFormControl($event, callback)" required="" style="">
</div>
</div>
UPDATE:
So I am instead choosing to right click and copy through the context menu as none of the methods seem to be working. However even with the context menu I’m unable to hit copy either through Keys.DOWN_ARRAY or send_keys(‘c’,’c’). I really need to pick up that data- any suggestions welcome- either hacks and workarounds or understanding what’s really going on here?
You could try actions for this :
key_down(value, element=None)
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
key_up(value, element=None)
Releases a modifier key.
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
For more reference you can follow this link :
WebDriver API
Update :
Here is my HTML :
<html>
<head>
<title>
Stack over flow
</title>
</head>
<body>
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
In this page there are two input box I'm sending some keys to first check box and then I'm doing CTRL+A followed by CTRL+C.
Then Clicking on second input box and pasting the same value.
Here is the code :
driver.find_element_by_name('fname').send_keys("Deepak")
actions = ActionChains(driver)
actions.key_down(Keys.LEFT_CONTROL).send_keys('a').keyUp(Keys.LEFT_CONTROL).build().perform()
actions.keyDown(Keys.LEFT_CONTROL).sendKeys("c").keyUp(Keys.LEFT_CONTROL).build().perform()
time.sleep(2)
element = driver.find_element_by_name('lname')
element.click()
element.send_Keys(Keys.chord(Keys.CONTROL, "v"), "");
Assuming you are using Safari I've raised this with apple back in March.
https://bugreport.apple.com/web/?problemID=38222248 (though you'll not be able to see this bug as they are not shown to other users).
I was using:
mac OS: High Sierra 10.13.3
Safari Technology Preview: Release 50 (Safari 11.2, WebKit 13606.1.5)
Selenium-java: 3.7.1
JDK: 1.8.0_161
I tried lots of alternatives to get the copy event (COMMAND+C) to trigger, without success, including:
input.sendKeys(Keys.COMMAND, "c");
Using Keys.CONTROL, Keys.META and the ctrl+insert rather than COMMAND.
I got acknowledgment by email that my bug report had been looked at but nothing since then.
I didn't find a workaround other than extracting the text from the multiple webelements individually and combining it to create the entire string as if it had been copied with a ctrl+a and ctrl+c.
I'll update this issue if I ever hear back from apple.
This was my demo code from the bug. Before running the script, pre populate the OS clipboard with some known text (just highlight and copy some text by hand)
package com.sas.aft.overview;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
public class Demo {
public static void main(String[] args) throws InterruptedException {
SafariOptions options = new SafariOptions();
options.setUseTechnologyPreview(true);
WebDriver webDriver = new SafariDriver(options);
webDriver.navigate().to("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea");
webDriver.switchTo().frame("iframeResult");
Thread.sleep(1000);
WebElement input = webDriver.findElement(By.cssSelector("textarea"));
input.click();
Thread.sleep(1000);
new Actions(webDriver).keyDown(Keys.COMMAND).sendKeys("a").keyUp(Keys.COMMAND).perform();
Thread.sleep(1000);
new Actions(webDriver).keyDown(Keys.COMMAND).sendKeys("c").keyUp(Keys.COMMAND).perform();
Thread.sleep(1000);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
try {
System.out.print("Clipboard: " + (String)contents.getTransferData(DataFlavor.stringFlavor) + "\n");
} catch (UnsupportedFlavorException | IOException ex) {
//ignore
}
webDriver.quit();
}
}
UPDATE ON SAFARI BUG
The bug I raised:
38222248 Command key does not work with copy for safaridriver with selenium automation
Was updated by Apple on 2nd July '18 with this comment:
A solution is under investigation. We will follow up with you again when it is available.
Was updated by Apple on 17th July '18 with this comment:
We believe this issue has been resolved in the latest macOS 10.14 beta
Although this probably isn’t the elegant or right way to go about things but I managed to get the job done ie copy paste using browser automation. So the HTML input field returned null, so I resorted to copy paste. Command + A wasn’t working so resorted to manually selecting key_down left shift and pressing right_arrow like 300 times to select my full text using Action chaining. Command + C wasn’t working then, so I tried the context_menu which again worked but I couldn’t select copy option from the menu both by send_keys(‘c’) twice or by arrow_down six times. Instead I found a helpful trick on Mac (not sure about Linux or win) that let’s you copy with control and insert. Did that worked like a charm. My xerox.paste() has the content from the page as copied by selenium and I can proceed now to process that Data. Thank you all

React change string to component (multiple)

I want to make custom grammar like Wiki and how can I do it in React and without dangerouslySetInnerHTML?
For example:
"hello this is simple string [linkToSomewhere] {this is where bold goes}"
becomes
<div>
hello this is simple string <Link where="linktoSomewhere"/> <Bold string="this is where bold goes"/>
</div>
like this
I found way to parse custom markdown to array but found no way to insert it as react component array is like
link[0] = "linkToSomewhere"
bold[0] = "this is where Bold goes"
Thank you in advance!
There are a few Markdown libraries available for React. Check out:
react-markdown: https://rexxars.github.io/react-markdown/
react-remarkable: https://github.com/acdlite/react-remarkable
And here's a whole host of other libraries that can translate your Markdown document into a nicely rendered HTML: https://react.rocks/tag/Markdown
And in order to learn the Markdown syntax, there are a few cheat sheets available, such as:
http://assemble.io/docs/Cheatsheet-Markdown.html
https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf

Extract texts until certain patterns on Scrapy

I'm trying to scrape certain contents from a webpage using Scrapy.
The html element looks like below.
'<p>\n 阪急宝塚線\xa0/\xa0石橋駅\xa0徒歩1分\n (<a href="javascript:void(0);" style="cursor:pointer;" onclic
k=\'window.open("http://athome.ekiworld.net/?id=athome&to=asso 302 ワンルーム&to_near_station1=25824&to_near_time1=1&to_near_traffic1=徒歩 1 分");return false;\'>電車ルート案内</a>)\n
</p>'
My goal is to extract only this part "阪急宝塚線\xa0/\xa0石橋駅\xa0徒歩1分\n".
I tried to use .re() with response and I thought ^(.+?<a) would work since it succeeded parsing on https://regex101.com/. But on scrapy shell, it doesn't parse anything (gives me []).
Could someone help me with this?
I use Python3/scrapy1.3.0.
Thanks!
import re
text = '''<p>\n 阪急宝塚線\xa0/\xa0石橋駅\xa0徒歩1分\n (<a href="javascript:void(0);" style="cursor:pointer;" onclic
k=\'window.open("http://athome.ekiworld.net/?id=athome&to=asso 302 ワンルーム&to_near_station1=25824&to_near_time1=1&to_near_traffic1=徒歩 1 分");return false;\'>電車ルート案内</a>)\n
</p>'''
re.search(r'\n.+?\n', text).group()
out:
'\n 阪急宝塚線\xa0/\xa0石橋駅\xa0徒歩1分\n'