How to read abc.txt.gz file in react js? - reactjs

hi i am having problem to read a .gz file compressed by php code:
i am using following function in php for compressing in .gz in php i am able to uncompress,
$compressed = gzcompress('Compress me', 9);
but I dont know if there is any way to read .gz file in react
js*. I am new to this. Thanks in advance.

From this article:
const fs = require('fs');
const zlib = require('zlib');
const fileContents = fs.createReadStream('./abc.txt.gz');
const writeStream = fs.createWriteStream('./abc.txt');
const unzip = zlib.createGunzip();
fileContents.pipe(unzip).pipe(writeStream);
You have to install the zlib module.
This code is assuming that the file to be executed is located in the same directory as abc.txt.gz. It creates a file called abc.txt which is the unzipped version.

use zlib for compress and decompress buffer,
fetch your compressed string by your php and call my unzipMe function
base of this function on base64 string, if you fetch except base64 then change unzipMe.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
var zlib = require("zlib");
function App() {
const [decodeStr, setDecodeStr] = React.useState("");
var utf8ArrayToStr = (function() {
var charCache = new Array(128); // Preallocate the cache for the common single byte chars
var charFromCodePt = String.fromCodePoint || String.fromCharCode;
var result = [];
return function(array) {
var codePt, byte1;
var buffLen = array.length;
result.length = 0;
for (var i = 0; i < buffLen; ) {
byte1 = array[i++];
if (byte1 <= 0x7f) {
codePt = byte1;
} else if (byte1 <= 0xdf) {
codePt = ((byte1 & 0x1f) << 6) | (array[i++] & 0x3f);
} else if (byte1 <= 0xef) {
codePt =
((byte1 & 0x0f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else if (String.fromCodePoint) {
codePt =
((byte1 & 0x07) << 18) |
((array[i++] & 0x3f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else {
codePt = 63; // Cannot convert four byte code points, so use "?" instead
i += 3;
}
result.push(
charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt))
);
}
return result.join("");
};
})();
const unzipMe = base64gz => {
// if your data not a base64 then comment this line
let compressData = atob(base64gz);
compressData = compressData.split("").map(function(e) {
return e.charCodeAt(0);
});
let binData = new Uint8Array(compressData);
zlib.gunzip(binData, function(err, dezipped) {
const str = utf8ArrayToStr(dezipped);
setDecodeStr(str);
});
};
const gzStr = "H4sIAAAAAAAA//NIzcnJV3BKTErM1gEAVJXqUQwAAAA=";
unzipMe(gzStr);
return (
<div className="App">
<h1>Coded string : {gzStr}</h1>
<hr />
<h2>Decoded string : {decodeStr}</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I used this site for testing compress string : Compress Str to gz
Answer output: HERE

Related

if the command used does not contain a valid hex code

if (command === "hex")
{ let hex = args[0]
if(!hex) return message.reply("Please specify a hex code!")
function hexToRgb(hex) {
if (hex.charAt(0) === '#') hex = hex.substring(1)
if(!hexToRgb(hex)) return message.reply("Not a valid hex.")
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
let embed = new Discord.MessageEmbed()
.setTitle("Hex Code")
.setColor(hex)
.addFields(
{
name: `RGB`,
value: hexToRgb(hex) + ``
}
)
message.channel.send({embeds: [embed]})
}
Here is my above code for the hex command. I would like the bot to send a message that it's unable to convert hex to color if the user is using an invalid hex code (e.g. #GGGGGG) or a non-hex code (e.g. "Hello"). How could I achieve that?
You can use regex. This simple function will return whether or not it is a valid hex code
String.prototype.isHex = function() {
return ( this.match(/#?[a-f0-9]+/i)?.[0] || false )
}
And run it like this
'#ffffff'.isHex() //'#ffffff'
'Hello'.isHex() //false
'#gggggg'.isHex() //false
You can use a RegExp (#[A-Za-z0-9_]{6}) to validate the string as a hexadecimal value preceded by a #
function isHex(str) {
return !!str.match(/#[A-Za-z0-9_]{6}/).length;
}
if (!isHex('some value')) return message.reply("Not a valid hex.")

Read content from PDF using React Native

I am trying to read text from PDF file using expo and React Native. I used the below code to read but it's not working. On click of a button i use the DocumentPicker to select the PDF file and then i wanted to extract the text from the document alone. I am trying to create a app to read out the text for me.
But i am not able to do that. Thanks in advance.
loadText = async()=>{
//Alert.alert("load text triggered");
let result = await DocumentPicker.getDocumentAsync({});
if(result.type == 'success') {
// alert(result.uri);
let contents = await FileSystem.readAsStringAsync(result.uri);
//console.warn('content', contents);
if(contents.length > 0){
//let res = base64.fromByteArray(this.stringToUint8Array(contents));
//alert("t" + res);
this.setState({textToBeRead : this.atob(contents)});
alert("test" + this.state.textToBeRead);
}
}
};
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}

create my nribin code for logistf ,does it really work?

i need to creat my own nribin code , it can be used for logistf package outcome, i maybe work,please give me some advise!!!
i change z.std = mdl.std$x[,-1] to z.std = mdl.std$x
and cancle: link = mdl.std$family[[2]] and family=binomial(link),
the whole code is:
nribin_LTY <-
function (event=NULL, mdl.std=NULL, mdl.new=NULL, z.std=NULL, z.new=NULL, p.std=NULL, p.new=NULL,
updown='category', cut=NULL, link='logit', niter=1000, alpha=0.05, msg=TRUE) {
##
## type of calculation
flag.mdl = !is.null(mdl.std) && !is.null(mdl.new)
flag.prd = !is.null(z.std) && !is.null(z.new)
flag.rsk = !is.null(p.std) && !is.null(p.new)
##
## check standard & new model
if (flag.mdl) {
if (is.null(event)) event = as.numeric(mdl.std$y)
if (is.null(mdl.std$x) || is.null(mdl.new$x))
stop("\n\nmodel object does not contain predictors. pls set x=TRUE for model calculation.\n\n")
z.std = mdl.std$x
z.new = mdl.new$x
mdl.std = glm(event ~ ., data=as.data.frame(cbind(event, z.std)))
mdl.new = glm(event ~ ., data=as.data.frame(cbind(event, z.new)))
} else if (flag.prd) {
mdl.std = glm(event ~ ., data=as.data.frame(cbind(event, z.std)))
mdl.new = glm(event ~ ., data=as.data.frame(cbind(event, z.new)))***
message("\nSTANDARD prediction model:")
print(summary(mdl.std)$coef)
message("\nNEW prediction model:")
print(summary(mdl.new)$coef)
} else if (!flag.mdl && !flag.prd && !flag.rsk) {
stop("\n\neither one of 'event, z.std, z.new', 'event, p.std, p.new', and 'mdl.std, mdl.new' should be specified.\n\n")
}
if (is.null(cut))
stop("\n\n'cut' is empty")
objs = list(mdl.std, mdl.new, z.std, z.new, p.std, p.new)
##
## DH & DL
wk = get.uppdwn.bin(event, objs, flag.mdl, flag.prd, flag.rsk, updown, cut, link, msg=msg)
upp = wk[[1]]
dwn = wk[[2]]
ret = list(mdl.std=mdl.std, mdl.new=mdl.new, p.std=wk[[3]], p.new=wk[[4]], up=upp, down=dwn, rtab=wk[[5]], rtab.case=wk[[6]], rtab.ctrl=wk[[7]])
##
## point estimation
message("\nNRI estimation:")
est = nribin.count.main(event, upp, dwn)
message("Point estimates:")
result = data.frame(est)
names(result) = 'Estimate'
row.names(result) = c('NRI','NRI+','NRI-','Pr(Up|Case)','Pr(Down|Case)','Pr(Down|Ctrl)','Pr(Up|Ctrl)')
print(result)
##
## interval estimation
if (niter > 0) {
message("\nNow in bootstrap..")
ci = rep(NA, 14)
N = length(event)
samp = matrix(NA, niter, 7)
colnames(samp) = c('NRI','NRI+','NRI-','Pr(Up|Case)','Pr(Down|Case)','Pr(Down|Ctrl)','Pr(Up|Ctrl)')
for (b in 1:niter) {
f = as.integer(runif(N, 0, N)) + 1
objs = list(mdl.std, mdl.new, z.std[f,], z.new[f,], p.std[f], p.new[f])
wk = get.uppdwn.bin(event[f], objs, flag.mdl, flag.prd, flag.rsk, updown, cut, link, msg=FALSE)
upp = wk[[1]]
dwn = wk[[2]]
samp[b,] = nribin.count.main(event[f], upp, dwn)
}
ret = c(ret, list(bootstrapsample=samp))
ci = as.numeric(apply(samp, 2, quantile, c(alpha/2, 1-alpha/2), na.rm=TRUE, type=2))
se = as.numeric(apply(samp, 2, sd))
message("\nPoint & Interval estimates:")
result = as.data.frame(cbind(est, se, matrix(ci, ncol=2, byrow=TRUE)))
names(result) = c('Estimate', 'Std.Error', 'Lower', 'Upper')
row.names(result) = c('NRI','NRI+','NRI-','Pr(Up|Case)','Pr(Down|Case)','Pr(Down|Ctrl)','Pr(Up|Ctrl)')
print(result)
}
invisible(c(list(nri=result), ret))
}
It is need to add variable matrix to logistf outcome,such as:
x.std=as.matrix(thromb2[,c(8,9,10,14,21,22,24,25,26)])
mstd = logistf(formula=fml.std, firth = FALSE,
data = thromb2, x=TRUE)
mstd =backward(mstd)
mstd$x <- x.std

Props value based on a stored cookie

Based on a specific value from a stored cookie (selectedRetailerId) the source (API endpoint) is different.
I'm trying to store the value of the cookie in a variable called retailer_id and use that to make sure the correct endpoint is called.
Here's what I'm trying...
<OTHER CODE IS REDACTED>
ReactDOM.render(
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var retailer_id = getCookie(selectedRetailerId);
<DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
document.getElementById('deliveryOptionsContainer')
)
But this returns a Uncaught SyntaxError. Probably because this piece of code should not be in ReactDOM.render.
Uncaught SyntaxError: http://localhost:8000/src/app.js: Unexpected token (130:2)
128 | }
129 |
> 130 | var retailer_id = getCookie(selectedRetailerId);
| ^
131 |
132 | <DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
133 | document.getElementById('deliveryOptionsContainer')
What is the right way to do this with React?
Try this:
// Defined somewhere outside ReactDOM.render (I'd recommend a helpers.js file)
// If you move it out of this file, be sure to import / require it
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
ReactDOM.render(
<DeliveryOptionsTable source={"http://<REDACTED>/delivery_options/" + getCookie(selectedRetailerId)} />,
document.getElementById('deliveryOptionsContainer')
)

Write list of files into a js file using npm

I'd like to have a script for npm that did the following:
Gets a list of files inside a folder (and subfolders)
Write it into a JS file, with the following format:
module.exports = [
"folder/filename.png",
"folder/subfolder/filename.png"
];
I'm currently doing it like this using the cli in Linux:
echo 'module.exports = [' | tee files.js && find . -name "*png" | sed s:"./":" '": | sed s:".png":".png',": | tee files.js --append && echo '];' | tee files.js --append
Which is a bit contrived and not really cross platform. Are there any npm packages that provide similar functionality? I'm kinda lost on it.
Well don't I feel silly. Had never used node directly but it was trivial to write a script to do this.
#!/usr/bin/env node
var fs = require('fs');
var list = [];
function traverse(folder) {
var files = fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
if (files[i].indexOf('.png') > -1 || files[i].indexOf('.jpg') > -1) {
list.push(folder + "/" + files[i]);
console.log(i + folder + "/" + files[i]);
} else {
var path = folder + "/" + files[i];
if (fs.lstatSync(path).isDirectory()) {
traverse(path);
}
}
}
}
function start() {
traverse('./images');
var string = "module.exports = [\n";
for (var i = 0; i < list.length; i++) {
string += " '" + list[i];
if (list[i] !== list[list.length - 1]) {
string += "',\n";
} else {
string += "'\n];"
}
}
fs.writeFile("./src/assets.js", string, function (err) {
if (err) {
return console.log(err);
}
console.log("Assets file was updated!");
});
}
start();

Resources