1569659348

How to Create your own image classifier with Angular and Tensorflow

If you a JS developer that was always amazed by things Data Scientist doing with Machine learning and Artifical intelligence. Check out this blog and learn how you can create your own image classifiers using Angular, Javascript and Tensorflow in less than a few minutes!

AI (Artificial intelligence) and ML are definitely the biggest buzzwords of the last few years.

It feels like everyone talks about AI all around. But feelings are not facts, so, I’ve checked google trends to witness the fact that those two terms are kept raising:

Somehow, it always feels for me like this topic reserved for only data scientists, python developers or anyone else or are much smarter than me. So, I’ve checked the related queries at google trends:

No frontend, no javascript, no Angular. Mostly Python.

I have to admit, I always was amazed by the thing people doing with AI and as a front end developer, I always thought to myself why can’t we do AI in JS?

What is AI?

The theory and development of computer systems able to perform tasks normally requiring human intelligence, such as visual perception, speech recognition, decision-making and translation between Languages

And in other words: everything that computers do, but, needs the intelligence of a human.

Examples?

Siri, Alexa, Tesla, even Netflix use AI-based concepts to recommend your next tv show.

How does it work?

Believe it or not, it’s based in biology. Our mind is full of Neurons, which getting the inputs from our senses and generating the output through the axon. The important fact is — that, this is what creates the intelligence part of our brain.

Now, let’s try to take this thing, and convert it into a mathematical model.
How can we implement a Neuron using code in the most simple way?
It’s probably a node which getting some inputs and generating them into one output.

In most of the cases, one Neuron wouldn’t be enough for creating the prediction model we want. So we actually converting it into a neuron network which looks like this:

Any input value getting weight on the nodes, and by running some activation function we getting the output on the second edge.
But, let’s say we know that the output we got is not the expected one, o we need to recalculate the weights on the nodes so the model will fit our example. We actually pump up the numbers again for the same example so we will get the excepted result on our next iteration. This process called the training, and that’s how our model is getting improving every-time we adding more data into it.

One of the most efficient ways to create those neuron networks is a technology called TensorFlow.

And almost over a year ago Google announces Tensorflow.js!
At first, I thought Tensorflow.js is sort of a binding to the Tensorflow which is written in C, you have to download and install it on your machine. But, the fact is TensorFlow.js is a complete re-write of Tensorflow, in…JS!

Is JS strong enough to calculate a complex model?

If you asking yourself how the browser can do such mathematical process in a reasonable time? Thanks to a technology called WebGL we can run our JS code using our graphics card memory, which is much stronger and faster than our RAM memory.

we actually can do machine learning in the browser, without any dependency!

Image classifiers

One of the most exciting concepts related to AI is image classifiers.

I was always amazed by the ability of a computer system to understand and classify images as humans do.

Let’s take facebook example — “Someone added a photo you might be in” feature was mind-blowing for me, how the heck they know?!

We just said we can do the same in the browser? Let’s do it!

We’re going to use a pre-trained model, called “mobilenet”. The reason it’s called mobile net is that this model is designed for mobile devices, it loads really fast compared to other prediction models.

We’re gonna create 2 examples:

• Upload an image, and let the browser classify wheat’s in it.
• Wire up our webcam, and let the browser classify what’s we see in the webcam.

Image upload classifier

Step 1: Install TensorFlow & Mobilenet

``````npm i @tensorflow/tfjs
npm I @tensorflow-models/mobilenet
``````

Step 2: Import mobile net in your component

``````import * as mobilenet from '@tensorflow-models/mobilenet';
``````

Step 3: Load the mobilenet model

Let’s load the model OnInit and also add loading indication:

``````@Component({
selector: 'app-image-classfier-upload',
templateUrl: './image-classfier-upload.component.html',
styleUrls: ['./image-classfier-upload.component.scss']
})
export class ImageClassfierUploadComponent implements OnInit {

model: any;
loading: boolean;

constructor() { }

async ngOnInit() {
this.loading = true;
this.model = await mobilenet.load();
this.loading = false;
}

}
``````

Step 4: Prepare the HTML

Now — let’s add our input file section, along with the loading indication to the template:

``````<div class="cont d-flex justify-content-center align-items-center flex-column">

<div class="custom-file">
<input type="file" class="custom-file-input" (change)="fileChange(\$event)">
<label class="custom-file-label">Select File</label>
</div>

<div *ngIf="loading">
<img src="./assets/loading.gif">
</div>

</div>
``````

Step 5: Implement the fileChange() function

I’m adding the `imgSrc` class property which I’ll get from the FileReader, to show the image uploaded preview.

``````async fileChange(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();

reader.readAsDataURL(file);

reader.onload = (res: any) => {
this.imgSrc = res.target.result;

};
}
}
``````

Step 6: Classify the uploaded image

I’ve got the `imgSrc`, now I can run the `model.classify()` method and get the model predictions:

``````     setTimeout(async () => {
this.predictions = await this.model.classify(this.img.nativeElement);
});Ï
``````

Now, let’s also update the template to show the predictions:

``````<div class="list-group">
<div class="list-group-item" *ngFor="let item of predictions">
{{item.className}} - {{item.probability | percent}}
</div>
</div>
``````

And the result:

Everything works! and we’ve just created our first image classifier with only JavaScript!

Webcam classifier

Mobilenet classification can perform not only on static images, we actually can classify and predict live video stream!

Let’s add an HTML5`video` tag to our template:

``````<video autoplay muted width="300px" height="300px" #video></video>
``````

Now, In order to wire our webcam, we have to set the stream. Let’s first get a hold of the video element with `@ViewChild`:

``````@ViewChild('video') video: ElementRef;
``````

And implement the `AfterViewInit` life cycle:

``````async ngAfterViewInit() {
const vid = this.video.nativeElement;

if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then((stream) => {
vid.srcObject = stream;

})
.catch((err0r) => {
console.log('Something went wrong!');
});
}
}
``````

Few things to notice here:

1. Since we’re changing DOM elements we’ve better use the AfterViewInit life cycle.
2. We’re checking if the user got the navigator.mediaDevices.getUserMedia to make sure we support all browsers.
3. We got a promise out of the getUserMedia function which contains the stream, and we set the video `nativeElement.srcObject` to this stream, and with that, we can see ourselves:

The last thing - Let’s run the `classify()` method every 3 seconds on the webcam stream:

``````setInterval(async () => {
this.predictions = await this.model.classify(this.video.nativeElement);
}, 3000);
``````

And the result:

I’ve checked a remote control, a wallet, and a cell phone. You can see that the classifier actually succeed to classify those items!

It’s not 100% accurate, but still very impressive!

Let’s summarise what we just learned:

• You don’t have to be a data scientist to do AI any more!
• TensorFlow.js is an independent package, you can run it in the browser with a matter of a 1 simple import
• Is the future of FE developers is taking part in building AI-based prediction models? I’ll put my money on that :)

If you enjoyed this article, please share it with others who may enjoy it as well.!

Thanks for reading!

This post was originally published here

#angular #javascript #tensorflow #machine-learning #artificial-intelligence

1653123600

EasyMDE - Markdown Editor

This repository is a fork of SimpleMDE, made by Sparksuite. Go to the dedicated section for more information.

A drop-in JavaScript text area replacement for writing beautiful and understandable Markdown. EasyMDE allows users who may be less experienced with Markdown to use familiar toolbar buttons and shortcuts.

In addition, the syntax is rendered while editing to clearly show the expected result. Headings are larger, emphasized words are italicized, links are underlined, etc.

EasyMDE also features both built-in auto saving and spell checking. The editor is entirely customizable, from theming to toolbar buttons and javascript hooks.

Try the demo

Install EasyMDE

Via npm:

``````npm install easymde
``````

Via the UNPKG CDN:

``````<link rel="stylesheet" href="https://unpkg.com/easymde/dist/easymde.min.css">
<script src="https://unpkg.com/easymde/dist/easymde.min.js"></script>
``````

Or jsDelivr:

``````<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
``````

How to use

Loading the editor

After installing and/or importing the module, you can load EasyMDE onto the first `textarea` element on the web page:

``````<textarea></textarea>
<script>
const easyMDE = new EasyMDE();
</script>
``````

Alternatively you can select a specific `textarea`, via JavaScript:

``````<textarea id="my-text-area"></textarea>
<script>
const easyMDE = new EasyMDE({element: document.getElementById('my-text-area')});
</script>
``````

Editor functions

Use `easyMDE.value()` to get the content of the editor:

``````<script>
easyMDE.value();
</script>
``````

Use `easyMDE.value(val)` to set the content of the editor:

``````<script>
easyMDE.value('New input for **EasyMDE**');
</script>
``````

Configuration

Options list

• autoDownloadFontAwesome: If set to `true`, force downloads Font Awesome (used for icons). If set to `false`, prevents downloading. Defaults to `undefined`, which will intelligently check whether Font Awesome has already been included, then download accordingly.
• autofocus: If set to `true`, focuses the editor automatically. Defaults to `false`.
• autosave: Saves the text that's being written and will load it back in the future. It will forget the text when the form it's contained in is submitted.
• enabled: If set to `true`, saves the text automatically. Defaults to `false`.
• delay: Delay between saves, in milliseconds. Defaults to `10000` (10 seconds).
• submit_delay: Delay before assuming that submit of the form failed and saving the text, in milliseconds. Defaults to `autosave.delay` or `10000` (10 seconds).
• uniqueId: You must set a unique string identifier so that EasyMDE can autosave. Something that separates this from other instances of EasyMDE elsewhere on your website.
• timeFormat: Set DateTimeFormat. More information see DateTimeFormat instances. Default `locale: en-US, format: hour:minute`.
• text: Set text for autosave.
• autoRefresh: Useful, when initializing the editor in a hidden DOM node. If set to `{ delay: 300 }`, it will check every 300 ms if the editor is visible and if positive, call CodeMirror's `refresh()`.
• blockStyles: Customize how certain buttons that style blocks of text behave.
• bold: Can be set to `**` or `__`. Defaults to `**`.
• code: Can be set to ````` or `~~~`. Defaults to `````.
• italic: Can be set to `*` or `_`. Defaults to `*`.
• unorderedListStyle: can be `*`, `-` or `+`. Defaults to `*`.
• scrollbarStyle: Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models.
• element: The DOM element for the `textarea` element to use. Defaults to the first `textarea` element on the page.
• forceSync: If set to `true`, force text changes made in EasyMDE to be immediately stored in original text area. Defaults to `false`.
• hideIcons: An array of icon names to hide. Can be used to hide specific icons shown by default without completely customizing the toolbar.
• indentWithTabs: If set to `false`, indent using spaces instead of tabs. Defaults to `true`.
• initialValue: If set, will customize the initial value of the editor.
• previewImagesInEditor: - EasyMDE will show preview of images, `false` by default, preview for images will appear only for images on separate lines.
• imagesPreviewHandler: - A custom function for handling the preview of images. Takes the parsed string between the parantheses of the image markdown `![]( )` as argument and returns a string that serves as the `src` attribute of the `<img>` tag in the preview. Enables dynamic previewing of images in the frontend without having to upload them to a server, allows copy-pasting of images to the editor with preview.
• insertTexts: Customize how certain buttons that insert text behave. Takes an array with two elements. The first element will be the text inserted before the cursor or highlight, and the second element will be inserted after. For example, this is the default link value: `["[", "](http://)"]`.
• horizontalRule
• image
• link
• table
• lineNumbers: If set to `true`, enables line numbers in the editor.
• lineWrapping: If set to `false`, disable line wrapping. Defaults to `true`.
• minHeight: Sets the minimum height for the composition area, before it starts auto-growing. Should be a string containing a valid CSS value like `"500px"`. Defaults to `"300px"`.
• maxHeight: Sets fixed height for the composition area. `minHeight` option will be ignored. Should be a string containing a valid CSS value like `"500px"`. Defaults to `undefined`.
• onToggleFullScreen: A function that gets called when the editor's full screen mode is toggled. The function will be passed a boolean as parameter, `true` when the editor is currently going into full screen mode, or `false`.
• parsingConfig: Adjust settings for parsing the Markdown during editing (not previewing).
• allowAtxHeaderWithoutSpace: If set to `true`, will render headers without a space after the `#`. Defaults to `false`.
• strikethrough: If set to `false`, will not process GFM strikethrough syntax. Defaults to `true`.
• underscoresBreakWords: If set to `true`, let underscores be a delimiter for separating words. Defaults to `false`.
• overlayMode: Pass a custom codemirror overlay mode to parse and style the Markdown during editing.
• mode: A codemirror mode object.
• combine: If set to `false`, will replace CSS classes returned by the default Markdown mode. Otherwise the classes returned by the custom mode will be combined with the classes returned by the default mode. Defaults to `true`.
• placeholder: If set, displays a custom placeholder message.
• previewClass: A string or array of strings that will be applied to the preview screen when activated. Defaults to `"editor-preview"`.
• previewRender: Custom function for parsing the plaintext Markdown and returning HTML. Used when user previews.
• promptURLs: If set to `true`, a JS alert window appears asking for the link or image URL. Defaults to `false`.
• promptTexts: Customize the text used to prompt for URLs.
• image: The text to use when prompting for an image's URL. Defaults to `URL of the image:`.
• link: The text to use when prompting for a link's URL. Defaults to `URL for the link:`.
• uploadImage: If set to `true`, enables the image upload functionality, which can be triggered by drag and drop, copy-paste and through the browse-file window (opened when the user click on the upload-image icon). Defaults to `false`.
• imageMaxSize: Maximum image size in bytes, checked before upload (note: never trust client, always check the image size at server-side). Defaults to `1024 * 1024 * 2` (2 MB).
• imageAccept: A comma-separated list of mime-types used to check image type before upload (note: never trust client, always check file types at server-side). Defaults to `image/png, image/jpeg`.
• imageUploadFunction: A custom function for handling the image upload. Using this function will render the options `imageMaxSize`, `imageAccept`, `imageUploadEndpoint` and `imageCSRFToken` ineffective.
• The function gets a file and `onSuccess` and `onError` callback functions as parameters. `onSuccess(imageUrl: string)` and `onError(errorMessage: string)`
• imageUploadEndpoint: The endpoint where the images data will be sent, via an asynchronous POST request. The server is supposed to save this image, and return a JSON response.
• if the request was successfully processed (HTTP 200 OK): `{"data": {"filePath": "<filePath>"}}` where filePath is the path of the image (absolute if `imagePathAbsolute` is set to true, relative if otherwise);
• otherwise: `{"error": "<errorCode>"}`, where errorCode can be `noFileGiven` (HTTP 400 Bad Request), `typeNotAllowed` (HTTP 415 Unsupported Media Type), `fileTooLarge` (HTTP 413 Payload Too Large) or `importError` (see errorMessages below). If errorCode is not one of the errorMessages, it is alerted unchanged to the user. This allows for server-side error messages. No default value.
• imagePathAbsolute: If set to `true`, will treat `imageUrl` from `imageUploadFunction` and filePath returned from `imageUploadEndpoint` as an absolute rather than relative path, i.e. not prepend `window.location.origin` to it.
• imageCSRFToken: CSRF token to include with AJAX call to upload image. For various instances like Django, Spring and Laravel.
• imageCSRFName: CSRF token filed name to include with AJAX call to upload image, applied when `imageCSRFToken` has value, defaults to `csrfmiddlewaretoken`.
• imageCSRFHeader: If set to `true`, passing CSRF token via header. Defaults to `false`, which pass CSRF through request body.
• imageTexts: Texts displayed to the user (mainly on the status bar) for the import image feature, where `#image_name#`, `#image_size#` and `#image_max_size#` will replaced by their respective values, that can be used for customization or internationalization:
• sbInit: Status message displayed initially if `uploadImage` is set to `true`. Defaults to `Attach files by drag and dropping or pasting from clipboard.`.
• sbOnDragEnter: Status message displayed when the user drags a file to the text area. Defaults to `Drop image to upload it.`.
• sbOnDrop: Status message displayed when the user drops a file in the text area. Defaults to `Uploading images #images_names#`.
• sbProgress: Status message displayed to show uploading progress. Defaults to `Uploading #file_name#: #progress#%`.
• sbOnUploaded: Status message displayed when the image has been uploaded. Defaults to `Uploaded #image_name#`.
• sizeUnits: A comma-separated list of units used to display messages with human-readable file sizes. Defaults to `B, KB, MB` (example: `218 KB`). You can use `B,KB,MB` instead if you prefer without whitespaces (`218KB`).
• errorMessages: Errors displayed to the user, using the `errorCallback` option, where `#image_name#`, `#image_size#` and `#image_max_size#` will replaced by their respective values, that can be used for customization or internationalization:
• noFileGiven: The server did not receive any file from the user. Defaults to `You must select a file.`.
• typeNotAllowed: The user send a file type which doesn't match the `imageAccept` list, or the server returned this error code. Defaults to `This image type is not allowed.`.
• fileTooLarge: The size of the image being imported is bigger than the `imageMaxSize`, or if the server returned this error code. Defaults to `Image #image_name# is too big (#image_size#).\nMaximum file size is #image_max_size#.`.
• importError: An unexpected error occurred when uploading the image. Defaults to `Something went wrong when uploading the image #image_name#.`.
• errorCallback: A callback function used to define how to display an error message. Defaults to `(errorMessage) => alert(errorMessage)`.
• renderingConfig: Adjust settings for parsing the Markdown during previewing (not editing).
• codeSyntaxHighlighting: If set to `true`, will highlight using highlight.js. Defaults to `false`. To use this feature you must include highlight.js on your page or pass in using the `hljs` option. For example, include the script and the CSS files like:
`<script src="https://cdn.jsdelivr.net/highlight.js/latest/highlight.min.js"></script>`
`<link rel="stylesheet" href="https://cdn.jsdelivr.net/highlight.js/latest/styles/github.min.css">`
• hljs: An injectible instance of highlight.js. If you don't want to rely on the global namespace (`window.hljs`), you can provide an instance here. Defaults to `undefined`.
• markedOptions: Set the internal Markdown renderer's options. Other `renderingConfig` options will take precedence.
• singleLineBreaks: If set to `false`, disable parsing GitHub Flavored Markdown (GFM) single line breaks. Defaults to `true`.
• sanitizerFunction: Custom function for sanitizing the HTML output of Markdown renderer.
• shortcuts: Keyboard shortcuts associated with this instance. Defaults to the array of shortcuts.
• showIcons: An array of icon names to show. Can be used to show specific icons hidden by default without completely customizing the toolbar.
• spellChecker: If set to `false`, disable the spell checker. Defaults to `true`. Optionally pass a CodeMirrorSpellChecker-compliant function.
• inputStyle: `textarea` or `contenteditable`. Defaults to `textarea` for desktop and `contenteditable` for mobile. `contenteditable` option is necessary to enable nativeSpellcheck.
• nativeSpellcheck: If set to `false`, disable native spell checker. Defaults to `true`.
• sideBySideFullscreen: If set to `false`, allows side-by-side editing without going into fullscreen. Defaults to `true`.
• status: If set to `false`, hide the status bar. Defaults to the array of built-in status bar items.
• Optionally, you can set an array of status bar items to include, and in what order. You can even define your own custom status bar items.
• styleSelectedText: If set to `false`, remove the `CodeMirror-selectedtext` class from selected lines. Defaults to `true`.
• syncSideBySidePreviewScroll: If set to `false`, disable syncing scroll in side by side mode. Defaults to `true`.
• tabSize: If set, customize the tab size. Defaults to `2`.
• theme: Override the theme. Defaults to `easymde`.
• toolbar: If set to `false`, hide the toolbar. Defaults to the array of icons.
• toolbarTips: If set to `false`, disable toolbar button tips. Defaults to `true`.
• direction: `rtl` or `ltr`. Changes text direction to support right-to-left languages. Defaults to `ltr`.

Options example

Most options demonstrate the non-default behavior:

``````const editor = new EasyMDE({
autofocus: true,
autosave: {
enabled: true,
uniqueId: "MyUniqueID",
delay: 1000,
submit_delay: 5000,
timeFormat: {
locale: 'en-US',
format: {
year: 'numeric',
month: 'long',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
},
},
text: "Autosaved: "
},
blockStyles: {
bold: "__",
italic: "_",
},
unorderedListStyle: "-",
element: document.getElementById("MyID"),
forceSync: true,
hideIcons: ["guide", "heading"],
indentWithTabs: false,
initialValue: "Hello world!",
insertTexts: {
horizontalRule: ["", "\n\n-----\n\n"],
image: ["![](http://", ")"],
link: ["[", "](https://)"],
table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
},
lineWrapping: false,
minHeight: "500px",
parsingConfig: {
allowAtxHeaderWithoutSpace: true,
strikethrough: false,
underscoresBreakWords: true,
},
placeholder: "Type here...",

previewClass: "my-custom-styling",
previewClass: ["my-custom-styling", "more-custom-styling"],

previewRender: (plainText) => customMarkdownParser(plainText), // Returns HTML from a custom parser
previewRender: (plainText, preview) => { // Async method
setTimeout(() => {
preview.innerHTML = customMarkdownParser(plainText);
}, 250);

return "Loading...";
},
promptURLs: true,
promptTexts: {
image: "Custom prompt for URL:",
link: "Custom prompt for URL:",
},
renderingConfig: {
singleLineBreaks: false,
codeSyntaxHighlighting: true,
sanitizerFunction: (renderedHTML) => {
// Using DOMPurify and only allowing <b> tags
return DOMPurify.sanitize(renderedHTML, {ALLOWED_TAGS: ['b']})
},
},
shortcuts: {
drawTable: "Cmd-Alt-T"
},
showIcons: ["code", "table"],
spellChecker: false,
status: false,
status: ["autosave", "lines", "words", "cursor"], // Optional usage
status: ["autosave", "lines", "words", "cursor", {
className: "keystrokes",
defaultValue: (el) => {
el.setAttribute('data-keystrokes', 0);
},
onUpdate: (el) => {
const keystrokes = Number(el.getAttribute('data-keystrokes')) + 1;
el.innerHTML = `\${keystrokes} Keystrokes`;
el.setAttribute('data-keystrokes', keystrokes);
},
}], // Another optional usage, with a custom status bar item that counts keystrokes
styleSelectedText: false,
sideBySideFullscreen: false,
syncSideBySidePreviewScroll: false,
tabSize: 4,
toolbar: false,
toolbarTips: false,
});
``````

Toolbar icons

Below are the built-in toolbar icons (only some of which are enabled by default), which can be reorganized however you like. "Name" is the name of the icon, referenced in the JavaScript. "Action" is either a function or a URL to open. "Class" is the class given to the icon. "Tooltip" is the small tooltip that appears via the `title=""` attribute. Note that shortcut hints are added automatically and reflect the specified action if it has a key bind assigned to it (i.e. with the value of `action` set to `bold` and that of `tooltip` set to `Bold`, the final text the user will see would be "Bold (Ctrl-B)").

Additionally, you can add a separator between any icons by adding `"|"` to the toolbar array.

Toolbar customization

Customize the toolbar using the `toolbar` option.

Only the order of existing buttons:

``````const easyMDE = new EasyMDE({
toolbar: ["bold", "italic", "heading", "|", "quote"]
});
``````

All information and/or add your own icons

``````const easyMDE = new EasyMDE({
toolbar: [
{
name: "bold",
action: EasyMDE.toggleBold,
className: "fa fa-bold",
title: "Bold",
},
"italics", // shortcut to pre-made button
{
name: "custom",
action: (editor) => {
// Add your own code
},
className: "fa fa-star",
title: "Custom Button",
attributes: { // for custom attributes
id: "custom-id",
"data-value": "custom value" // HTML5 data-* attributes need to be enclosed in quotation marks ("") because of the dash (-) in its name.
}
},
"|" // Separator
// [, ...]
]
});
``````

Put some buttons on dropdown menu

``````const easyMDE = new EasyMDE({
toolbar: [{
name: "heading",
action: EasyMDE.toggleHeadingSmaller,
className: "fa fa-header",
title: "Headers",
},
"|",
{
name: "others",
className: "fa fa-blind",
title: "others buttons",
children: [
{
name: "image",
action: EasyMDE.drawImage,
className: "fa fa-picture-o",
title: "Image",
},
{
name: "quote",
action: EasyMDE.toggleBlockquote,
className: "fa fa-percent",
title: "Quote",
},
{
name: "link",
action: EasyMDE.drawLink,
className: "fa fa-link",
title: "Link",
}
]
},
// [, ...]
]
});
``````

Keyboard shortcuts

EasyMDE comes with an array of predefined keyboard shortcuts, but they can be altered with a configuration option. The list of default ones is as follows:

Here is how you can change a few, while leaving others untouched:

``````const editor = new EasyMDE({
shortcuts: {
"toggleOrderedList": "Ctrl-Alt-K", // alter the shortcut for toggleOrderedList
"toggleCodeBlock": null, // unbind Ctrl-Alt-C
"drawTable": "Cmd-Alt-T", // bind Cmd-Alt-T to drawTable action, which doesn't come with a default shortcut
}
});
``````

Shortcuts are automatically converted between platforms. If you define a shortcut as "Cmd-B", on PC that shortcut will be changed to "Ctrl-B". Conversely, a shortcut defined as "Ctrl-B" will become "Cmd-B" for Mac users.

The list of actions that can be bound is the same as the list of built-in actions available for toolbar buttons.

Advanced use

Event handling

You can catch the following list of events: https://codemirror.net/doc/manual.html#events

``````const easyMDE = new EasyMDE();
easyMDE.codemirror.on("change", () => {
console.log(easyMDE.value());
});
``````

Removing EasyMDE from text area

You can revert to the initial text area by calling the `toTextArea` method. Note that this clears up the autosave (if enabled) associated with it. The text area will retain any text from the destroyed EasyMDE instance.

``````const easyMDE = new EasyMDE();
// ...
easyMDE.toTextArea();
easyMDE = null;
``````

If you need to remove registered event listeners (when the editor is not needed anymore), call `easyMDE.cleanup()`.

Useful methods

The following self-explanatory methods may be of use while developing with EasyMDE.

``````const easyMDE = new EasyMDE();
easyMDE.isPreviewActive(); // returns boolean
easyMDE.isSideBySideActive(); // returns boolean
easyMDE.isFullscreenActive(); // returns boolean
easyMDE.clearAutosavedValue(); // no returned value
``````

How it works

EasyMDE is a continuation of SimpleMDE.

SimpleMDE began as an improvement of lepture's Editor project, but has now taken on an identity of its own. It is bundled with CodeMirror and depends on Font Awesome.

CodeMirror is the backbone of the project and parses much of the Markdown syntax as it's being written. This allows us to add styles to the Markdown that's being written. Additionally, a toolbar and status bar have been added to the top and bottom, respectively. Previews are rendered by Marked using GitHub Flavored Markdown (GFM).

SimpleMDE fork

I originally made this fork to implement FontAwesome 5 compatibility into SimpleMDE. When that was done I submitted a pull request, which has not been accepted yet. This, and the project being inactive since May 2017, triggered me to make more changes and try to put new life into the project.

Changes include:

• FontAwesome 5 compatibility
• Guide button works when editor is in preview mode
• Links are now `https://` by default
• Small styling changes
• Support for Node 8 and beyond
• Lots of refactored code
• Links in preview will open in a new tab by default
• TypeScript support

My intention is to continue development on this project, improving it and keeping it alive.

Hacking EasyMDE

You may want to edit this library to adapt its behavior to your needs. This can be done in some quick steps:

1. Follow the prerequisites and installation instructions in the contribution guide;
2. Do your changes;
3. Run `gulp` command, which will generate files: `dist/easymde.min.css` and `dist/easymde.min.js`;
4. Copy-paste those files to your code base, and you are done.

Contributing

Want to contribute to EasyMDE? Thank you! We have a contribution guide just for you!

Author: Ionaru
Source Code: https://github.com/Ionaru/easy-markdown-editor
License: MIT license

1655630160

Installation

Install via pip:

``\$ pip install pytumblr``

Install from source:

``````\$ git clone https://github.com/tumblr/pytumblr.git
\$ cd pytumblr
\$ python setup.py install``````

Usage

Create a client

A `pytumblr.TumblrRestClient` is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

``````client = pytumblr.TumblrRestClient(
'<consumer_key>',
'<consumer_secret>',
'<oauth_token>',
'<oauth_secret>',
)

client.info() # Grabs the current user information``````

Two easy ways to get your credentials to are:

1. The built-in `interactive_console.py` tool (if you already have a consumer key & secret)
2. The Tumblr API console at https://api.tumblr.com/console
3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

``````client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post``````

Blog Methods

``````client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog``````

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

• state - a string, the state of the post. Supported types are published, draft, queue, private
• tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
• tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
• date - a string, the customized GMT that you want
• format - a string, the format that your post is in. Support types are html or markdown
• slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

``````#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
tweet="Woah this is an incredible sweet post [URL]",
data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
caption="## Mega sweet kittens")``````

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

``````#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")``````

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

``````#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")``````

Creating a link post

• title - a string, the title of post that you want. Supports HTML entities.
• url - a string, the url that you want to create a link post for.
• description - a string, the desciption of the link that you have
``````#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
description="Search is pretty cool when a duck does it.")``````

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

``````#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])``````

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

``````#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")``````

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

``````#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")``````

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

``````client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")``````

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

``client.reblog(blogName, id=125356, reblog_key="reblog_key")``

Deleting a post

Deleting just requires that you own the post and have the post id

``client.delete_post(blogName, 123456) # Deletes your post :(``

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

``client.create_text(blogName, tags=['hello', 'world'], ...)``

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

``data = client.notes(blogName, id='123456')``

The results include a timestamp you can use to make future calls.

``data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])``

Tagged Methods

``````# get posts with a given tag
client.tagged(tag, **params)``````

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need `pyyaml` installed to run it, but then it's just:

``\$ python interactive-console.py``

and away you go! Tokens are stored in `~/.tumblr` and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

``python setup.py test``

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

1597647163

Laravel 7/6 Create Thumbnail from Image | Intervention Image Thumbnail

Laravel create thumbnail from image. Here, i will show you how to upload image and create thumbnail of uploaded image in laravel using intervention package.

Also using laravel intervention image thumbnai, you can resize the image size in laravel.

Laravel intervention image upload with Thumbnail and save to storage

1. Install Laravel App
2. Setup Database
3. Install laravel intervention image thumbnail
4. Generate migration file and model
5. Make Route For Save and Display Image And Thumbnail
6. Create Controller For Store Image & Thumbnail
7. Create Blade View
8. Make Folder
9. Start Development Server

https://www.tutsmake.com/laravel-intervention-image-upload-using-ajax/

#laravel intervention image thumbnail #laravel create thumbnail from image #create thumbnail of image laravel 7/6 #laravel 7. x and 6. x - image upload with create thumbnail image

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

1. Installing Node.js and npm
2. Installing Angular CLI
3. Creating workspace
4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

• Node.js
• npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

1. npm -v

Installing Angular CLI

• Open Terminal/Command Prompt
• To install Angular CLI, run the below command:
1. npm install -g @angular/cli

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

• Using CLI
• Using Visual Studio Code
1. Using CLI

To create a workspace:

• Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
• Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
1. Ng new YourAppName

• After running this command, it will prompt you to select from various options about the CSS and other functionalities.

• To leave everything to default, simply press the Enter or the Return key.

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

1623139838

Transfer Learning on Images with Tensorflow 2 – Predictive Hacks

In this tutorial, we will provide you an example of how you can build a powerful neural network model to classify images of **cats **and dogs using transfer learning by considering as base model a pre-trained model trained on ImageNet and then we will train additional new layers for our cats and dogs classification model.

The Data

We will work with a sample of 600 images from the Dogs vs Cats dataset, which was used for a 2013 Kaggle competition.

#python #transfer learning #tensorflow #images #transfer learning on images with tensorflow #tensorflow 2