Angular 5 custom pipe - node.js

I am new to Angular and facing this issue.
I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.
This is my code:
my-component.ts
this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
var convert = String.fromCharCode(chars1[k]); // convert into base64
this.imgIn = this.imgIn + convert;
}
this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);
Has anyone else experienced this, please help me?

I highly suggest you to take a look at the docs, it's really easy to understand and gives you a good amount of information that you might need to create your custom pipe, Here's the link to the official docs: Angular - Pipes

If your snippet of code already does what you want, then moving to a custom pipe is pretty straight forward. You just need to bind your array of decimal and use a pipe that converts it exactly like you do now. Something like:
Pipe:
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({
name: 'base64'
})
export class Base64Pipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any,){
let imgIn="";
for (var k = 0; k < value.length; k++) {
var convert = String.fromCharCode(value[k]); // convert into base64
imgIn += convert;
}
let base64Url =this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + imgIn);
return base64Url;
}
}
And you'd use it like so: [src]="yourDecimalCodeArray | base64"
Here's a Stackblitz to illustrate.
Keep in mind that using this.sanitizer.bypassSecurityTrustResourceUrl mean you have to bind safely (Safe value must use [property]=binding after bypass security with DomSanitizer).
Hope this helps.

Related

Actionscript Take Input and compare to an Int

I'm trying to take an input from the user using an Input Text field, this data is a number. I want the user to input the correct number (in this case 1) and then print out yay.
However, i can't get it to work. Any help is much appreciated.
I assume the issue is to do with comparing an int and a string, but honestly im not sure anymore.
import flash.events.MouseEvent;
import flash.text.TextField;
var dayVar:String = dayInput.text;
var dayNum:Number = Number(dayVar);
stop();
button3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void
{
if(dayNum == 1) {
trace("yay");
} else {
trace("nay");
}
}
You will have to update your dayVal and/or dayNum after user has given input. So in this minimal case you can simply:
function mouseDownHandler3(event:MouseEvent):void{
if(Number(dayInput.text)==1) {
trace("yay");
} else {
trace("nay");
}
}
Other possibilites would be listening Event.CHANGE for the text input, or KeyboardEvent to update your variables, but in this case the MouseEvent handler does the job easier.
You can use restriction property for text field input like this:
dayInput.restrict = "0-9";
This should omit to type only digits.

Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

I'm having an error when the second client is connected. My code comparing the two clients current position by p5.Vector.dist() and there's an error, here it is.
And the line in p5.Vector.dist(p5.js:25914) is
p5.Vector.prototype.dist = function (v) {
var d = v.copy().sub(this); //This is the exact line where the error says from
return d.mag();
};
This is my code;
Client side;
//I use for loop to see all the contain of otherCircles
for(var x = 0; x < otherCircles.length; x++){
if(otherCircles[x].id != socket.id){ //To make sure i won't compare the client's data to its own because the data of all connected client's is here
console.log(otherCircles[x].radius); //To see if the data is not null
if(circle.eat(otherCircles[x])){
if(circle.radius * 0.95 >= otherCircles[x].radius){
otherCircles.splice(x,1);
console.log('ATE');
} else if(circle.radius <= otherCircles[x].radius * 0.95){
zxc = circle.radius;
asd = zxc;
circle.radius = null;
console.log('EATEN');
}
}
}
}
//Here's the eat function of the circle
function Circle(positionX,positionY,radius){
//The variables of Circle()
this.position = createVector(positionX, positionY);
this.radius = radius;
this.velocity = createVector(0, 0);
//Here's the eat function
this.eat = function(other) {
var distance = p5.Vector.dist(this.position, other.position); //Heres where the error
if (distance < this.radius + (other.radius * 0.25)) { //Compare there distance
return true;
} else {
return false;
}
}
}
The otherCircles[] contains;
And that is also the output of the line console.log(otherCircles[x].radius);.
I don't think the server side would be necessary because it only do is to receive the current position and size of the client and send the other clients position and size to. All there datas stored in otherCircles(). The line console.log(otherCircles[x].radius); result is not null, so I know there's data where being compared to the clients position, why I'm having an error like this.
It's going to be pretty hard to help you without an MCVE, but I'll try to walk you through debugging this.
You've printed otherCircles[x].radius, which is a good start. But if I were you, I'd want to know much more about otherCircles[x]. What variables and functions does it contain? I'd start by googling "JavaScript print function names of object" and try to figure out exactly what's in that object. What is the value of otherCircles[x].position?
From there, I'd also want to make sure that otherCircles[x].position is defined and an instance of p5.Vector. Does it have a copy() function?
I might also step through the code with a debugger- every browser has one, and you should become familiar with using it.
If you still can't get it work, then please post an MCVE that we can run by copy-pasting it. That means no server code, just hard-code your values so we can see the same error. I'd bet you find your problem while trying to narrow it down to a small example. But if not, we'll go from there. Good luck.

How to get the number of clicks on a link from wikipedia?

Now we have the code that scrapes the links in an article. We need also the number of clicks on a link. Can some one help?
Sow far we have this code:
String[] articles = {"Abdominal_pain"};
void setup() {
for (int i = 0; i < articles.length; i++) {
String article = articles[i];
String start = "20160101"; // YYYYMMDD
String end = "20170101"; // YYYYMMDD
// documentation: https://wikimedia.org/api/rest_v1/?doc#!/Pageviews_data/get_metrics_pageviews_per_article_project_access_agent_article_granularity_start_end
// >> https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&meta=&titles=Albert+Einstein&pllimit=500
String query = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&meta=&titles="+article+"&pllimit=500";
String[] lines = loadStrings(query);
for (int j = 0; j < lines.length; j++) {
String line = lines[j];
if (line.contains("\"title\":")) {
println(line);
// java string split
}
}
}
}
The query you're using apparently gives you a bunch of articles that your main article "Abdominal_pain" links to.
You need to go a step further and loop through all of those links. You can make your life a lot easier by using JSONObjects instead of parsing Strings like you're currently doing. Check out the loadJSONArray() function for more info, but basically you'd do this:
JSONArray links = loadJSONArray(query);
for (int i = 0; i < values.size(); i++) {
JSONObject link = values.getJSONObject(i);
String title = link.getString("title");
//fetch the info for that title
}
Once you have the title, you can then fetch the information for that page. An example query url is https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Abdominal_pain/daily/20151010/20151012 which returns this JSON:
{"items":[{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101000","access":"all-access","agent":"all-agents","views":1134},{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101100","access":"all-access","agent":"all-agents","views":1160},{"project":"en.wikipedia","article":"Abdominal_pain","granularity":"daily","timestamp":"2015101200","access":"all-access","agent":"all-agents","views":1313}]}
You'll have to do some aggregating to get the totals, or maybe the total is somewhere else in the API.
You're going to have to do a little bit of research on exactly what the API can return. Reading through the documentation is a big part of programming. Luckily the Wikipedia API has great documentation, and that's where you should be looking.
I'd recommend trying something out and posting another question, along with an MCVE, if you get stuck. Good luck.
See also: How to use Wikipedia API to get the page view statistics of a particular page in wikipedia?

JSON format list in couchDB

I am writing a list for couchDB. All the documentation I have read assumes you would want to return data in html or plain text. I, however, need it to be returned in JSON format, in exactly the same way that a view would return (the application I am writing relies on this).
What is the correct way to have a list return its data in JSON format?
Try toJSON(), see the example.
You need to format your output with send to mimmic a JSON output. Here is an example of how we do that in a real case:
function(head, req) {
start({"headers": {"Content-Type": "application/json"}});
var keys = {};
while (row = getRow()) {
//Code goes here
send("{\"rows\":[");
var init = true;
for (var key in keys) {
if (init) {
send("\n");
init = false;
}
else send(",\n");
send("{\"key\": " + key + ",\"value\":");
send("{\"first_val\":" + val1);
send(", \"second_val\":" + val2);
send(", \"third_val\":" + val3 + "}}");
}
send("\n]}");
}
In this way, the output of the list has the same format as the underlying view.

Actionscript deserialize Strings into objects

is there a way to deserialize strings to objects in actionscript:
i.e.
var str:String = "{ id: 1, value: ['a', 500] }";
should be made into an appropriate actionscript object.
this is not json, since the keys are not wrapped in quotes.
Ok, for that type of data pattern, there's not a nice way that I know of to do this. going off the assumption you can't affect the data to make it more JSON-like ... here's off the top of my head what I would conceptually try:
var str:String = "{ id:1, value:['a', 500] }";
// strip off the { and } characters since we've nothing nice to do that for us...
var mynewString:String = str.slice(1, str.length - 1);
var stringItems:Array = mynewString.split(",");
var obj:Object = new Object();
for (var i in stringItems)
{
var objProps:Array = stringItems[i].split(":");
// kill off the quotes here
obj[props[0]] = objProps[1].slice(1, objProps[1].length - 1);
if ( obj[props[0]].indexOf('[') == 0 ) {
// remove [ and ] if there
var maybeStrArray:String = obj[props[0]].slice(1, str.length - 1);
// right now assume we're an array based on our inbound data
var strArr:Array = maybeStrArray.split(",");
obj[props[0]] = strArr;
}
}
Something like that or similar to it anyway. Yes, it's crude, and absolutely it could be fashioned in a way that is more flexible (such as move the string to array convert to its own function so I could use it elsewhere). It's just the first thing that conceptually came to mind as an answer.
Try that, tweak around with it and see if it helps.
You can use as3corelib library for JSON deserialization. It's really not worth spending your time on writing own implementation (except you wish so).

Resources