I am stuck in reactjs.
I have a function in which there is an array containing some values, but when I want to access that array in render function and pass it using props to another function, it returns a blank array.
what should I do to resolve this problem?
Like this:
In Function:
this.usersAnswerXML = ["ID0", "ID1", "ID2"]
In Render:
this.usersAnswerXML = []
Here is my code, what am I doing wrong?
handleSplitContentClick(contentId, selectionType) {
let isCorrect
if (selectionType == 'selected') {
const index = this.correctAnswers.indexOf(contentId);
if (index > -1) {
this.userCorrectAnswers.push(contentId);
if (this.correctAnswers.length === this.userCorrectAnswers.length &&
this.userUncorrectAnswer.length == 0) {
isCorrect = this.correct
} else {
isCorrect = this.incorrect
}
} else {
this.userUncorrectAnswer.push(contentId);
isCorrect = this.incorrect
}
} else if (selectionType == 'disselected') {
const index = this.correctAnswers.indexOf(contentId);
if (index > -1) {
this.userCorrectAnswers.splice(index, 1);
isCorrect = this.incorrect
} else {
this.userUncorrectAnswer.splice(index, 1);
if (this.correctAnswers.length === this.userCorrectAnswers.length &&
this.userUncorrectAnswer.length == 0) {
isCorrect = this.correct
} else {
isCorrect = this.incorrect
}
}
}
this.userAnswerXML = this.userCorrectAnswers.join(',')
this.usersAnswerXMLs = this.userAnswerXML + ',' +
this.userUncorrectAnswer.join(',')
this.usersAnswerXML = this.usersAnswerXMLs.split(',')
console.log(this.usersAnswerXML)
if (window.uaXML) {
this.userAnswerXML = window.uaXML
console.log(this.userAnswerXML + "data")
}
// this.usersAnswerXML = window.uaXML
console.log(window.uaXML)
this.userAnswerXML = "<smans type='4'><div id='textID0' userAns='" +
this.usersAnswerXML + "'></div></smans>"
$("#special_module_user_xml").val(this.userAnswerXML )
console.log(this.usersAnswerXML)
}
} // Editor's note: this is an extra curly brace
render() {
if (this.props.remedStatus) {
console.log(this.usersAnswerXML)
console.log("inside remed")
return (
<HotspotRemed
xml={this.receivedXML}
userXml={this.usersAnswerXML}
correctAnswer ={this.ansString}
type={this.splitType}
/>
)
} else {
return (
<div className="previewtemplate" style ={template}>
{this.templateArea(this.state.templateType)}
</div>
);
}
}
} // Editor's note: another extra curly brace
} // Editor's note: another one again
I am trying to decrypt my openssl_seal stored values.
My PHP code:
public static function multiEncrypt( string $data, array $publicKeys ) : ?array
{
foreach ($publicKeys as $cert)
{
if (false === openssl_get_publickey( $cert )) {
Log::getInstance()->error('multiEncrypt : invalid pubkey ; ' . openssl_error_string());
return null;
}
}
$encryptedData = null;
$encryptedKeys = [];
$initVector = self::getInitVector( self::SEAL_CIPHER );
$result = openssl_seal(
$data,
$encryptedData,
$encryptedKeys,
$publicKeys,
self::SEAL_CIPHER,
$initVector
);
if (false === $result)
return null;
$encodedData = base64_encode( $encryptedData );
$encodedKeys = [];
foreach ($encryptedKeys as $key) {
$encodedKeys[] = base64_encode($key);
}
return [
'keys' => $encodedKeys,
'data' => $encodedData
];
}
and my client-side code:
function decrypt(privkey, blob, key)
{
var byteKey = forge.pki.privateKeyFromPem(privkey);
var usrPubKey = forge.pki.publicKeyFromPem(publicKey);
//var genPubKey = forge.pki.rsa.setPublicKey(byteKey.n, byteKey.e);
/*if (usrPubKey !== genPubKey) {
error('Your private key does not match the public key we have of you.');
return;
}*/
console.log('Decoding key..');
var decodedKey = atob(key);
console.log('Decrypting key..');
var contractUserKey = byteKey.decrypt(decodedKey);
console.log(contractUserKey);
console.log(contractUserKey.decrypt(blob));
}
However I keep getting 'forge.min.js:4068 Uncaught Error: Encryption block is invalid.'. Is there something I am missing here?
I have make cookies in java script page but when used in the Controller page it shows null and i Check in the browser cookies is also created so please help me for this ......
<script>
#Html.Raw(ViewBag.CallJSFuncOnPageLoad)
function IPDetction()
{
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
var items = [];
$.each(data, function (key, val)
{
if (key == 'city') {
document.cookie = "DetectedCityName=" + val;
}
if (key == 'region') {
document.cookie = "DetectedRegionName=" + val;
}
});
});
}
</script>
#{
string DetectedCityName = "Toronto";
try
{
RateMadnessfinal.DataModel.RateMadnessdbEntities db = new RateMadnessfinal.DataModel.RateMadnessdbEntities();
DetectedCityName = HttpContext.Current.Request.Cookies["DetectedCityName"].Value;
var getCityID = db.Macities.Where(c => c.CityName.Contains(DetectedCityName)).ToList();
if ((getCityID != null) && (getCityID.Count > 0))
{
DetectedCityName = getCityID.FirstOrDefault().CityName;
}
else
{
DetectedCityName = "Toronto";
}
}
catch (Exception e)
{
DetectedCityName = "Toronto";
}
}
I get this data as an ajax response:
{
"idArray" = (
"99516",
"99518",
"97344",
"97345",
"98425"
);
"frame" = {
"size" = {
"width" = "8";
"height" = "8";
};
"origin" = {
"x" = "244";
"y" = "345";
};
};
},
This is just a portion of the Data, but it continues in the same format.
I don't have access to the source of the files that generate this data.
Is this a known format or something custom?
Since people tend to throw regular expressions at everything, even things that can not be parsed with regular expressions (ie. non-regular languages): I've written a proof-of-concept parser for this data format:
$input = '{
"idArray" = (
"99516",
"99518",
"97344",
"97345",
"98425"
);
"frame" = {
"size" = {
"width" = "8";
"height" = "8";
};
"origin" = {
"x" = "244";
"y" = "345";
};
};
}';
echo json_encode(parse($input));
function parse($input) {
$tokens = tokenize($input);
$index = 0;
$result = parse_value($tokens, $index);
if ($result[1] !== count($tokens)) {
throw new Exception("parsing stopped at token " . $result[1] . " but there is more input");
}
return $result[0][1];
}
function tokenize($input) {
$tokens = array();
$length = strlen($input);
$pos = 0;
while($pos < $length) {
list($token, $pos) = find_token($input, $pos);
$tokens[] = $token;
}
return $tokens;
}
function find_token($input, $pos) {
$static_tokens = array("=", "{", "}", "(", ")", ";", ",");
while(preg_match("/\s/mis", substr($input, $pos, 1))) { // eat whitespace
$pos += 1;
}
foreach ($static_tokens as $static_token) {
if (substr($input, $pos, strlen($static_token)) === $static_token) {
return array($static_token, $pos + strlen($static_token));
}
}
if (substr($input, $pos, 1) === '"') {
$length = strlen($input);
$token_length = 1;
while ($pos + $token_length < $length) {
if (substr($input, $pos + $token_length, 1) === '"') {
return array(array("value", substr($input, $pos + 1, $token_length - 1)), $pos + $token_length + 1);
}
$token_length += 1;
}
}
throw new Exception("invalid input at " . $pos . ": `" . substr($input, $pos - 10, 20) . "`");
}
// value is either an object {}, an array (), or a literal ""
function parse_value($tokens, $index) {
if ($tokens[$index] === "{") { // object: a list of key-value pairs, glued together by ";"
$return_value = array();
$index += 1;
while ($tokens[$index] !== "}") {
list($key, $value, $index) = parse_key_value($tokens, $index);
$return_value[$key] = $value[1];
if ($tokens[$index] !== ";") {
throw new Exception("Unexpected: " . print_r($tokens[$index], true));
}
$index += 1;
}
return array(array("object", $return_value), $index + 1);
}
if ($tokens[$index] === "(") { // array: a list of values, glued together by ",", the last "," is optional
$return_value = array();
$index += 1;
while ($tokens[$index] !== ")") {
list($value, $index) = parse_value($tokens, $index);
$return_value[] = $value[1];
if ($tokens[$index] === ",") { // last, is optional
$index += 1;
} else {
if ($tokens[$index] !== ")") {
throw new Exception("Unexpected: " . print_r($tokens[$index], true));
}
return array(array("array", $return_value), $index + 1);
}
}
return array(array("array", $return_value), $index + 1);
}
if ($tokens[$index][0] === "value") {
return array(array("string", $tokens[$index][1]), $index + 1);
}
throw new Exception("Unexpected: " . print_r($tokens[$index], true));
}
// find a key (string) followed by '=' followed by a value (any value)
function parse_key_value($tokens, $index) {
list($key, $index) = parse_value($tokens, $index);
if ($key[0] !== "string") { // key must be a string
throw new Exception("Unexpected: " . print_r($key, true));
}
if ($tokens[$index] !== "=" ) {
throw new Exception("'=' expected");
}
$index += 1;
list($value, $index) = parse_value($tokens, $index);
return array($key[1], $value, $index);
}
The output is:
{"idArray":["99516","99518","97344","97345","98425"],"frame":{"size":{"width":"8","height":"8"},"origin":{"x":"244","y":"345"}}}
Notes
the original input has a trailing ,. I've removed that character. It will throw an error (more input) if you put it back.
This parser is naive in the sense that it tokenizes all input before it starts parsing. This is not good for large input.
I've not added escape detection for strings in the tokenizer. Like: "foo\"bar".
This was a fun exercise. If you have any questions let me know.
Edit: I see this is a JavaScript question. Porting the PHP to JavaScript shouldn't be too hard. The list($foo, $bar) = func() is equivalent to: var res = func(); var foo = res[0]; var bar = res[1];
Try using this function with the response text as a parameter:
function getJsonData(str){
str = str.replace(/,/g, '') //remove ,
.replace(/\(/g, '[') //replace (
.replace(/\[/g)', ']') //replace )
.replace(/;/g, ',') //replace ;
.replace(/=/g, ':'); //replace :
return JSON.parse(str);
}
This is an edit made by #SamSal
function getJsonData(str){
str = str.replace(/\(/g, '[') //replace (
.replace(/\)/g, ']') //replace )
.replace(/;\n\s+}/g, '}') //replace ;} with }
.replace(/;/g, ',') //replace remaining ; with ,
.replace(/=/g, ':'); //replace :
return JSON.parse(str);
}
Is this a known format or something custom?
It is a custom format, that looks a little bit like JSON without actually being JSON.
Hi iam using "Combinator" its a plugin for compressing js and css .
Combinator link and steps
According to the docs
they said add following line to views or layout
<?php $combinator->add_libs('js', array('jquery'));?>
<?php $combinator->add_libs('css', array('styles'));?>
but how do i add single css file instead of these entire css ?
helper class code:
<?php
class CombinatorHelper extends Helper {
var $Vue = null;
var $libs = array('js' => array(), 'css' => array());
var $inline_code = array('js' => array(), 'css' => array());
var $basePath = null;
var $cachePath = null;
// default conf
private $__options = array(
'js' => array(
'path' => '/js',
'cachePath' => '/js',
'enableCompression' => true
),
'css' => array(
'path' => '/css',
'cachePath' => '/css',
'enableCompression' => false,
'compression' => 'high_compression' // Can be "high_compression", "highest_compression", "low_compression", or "default"
)
);
function __construct($options = array()) {
$this->__options['js'] = !empty($options['js'])?am($this->__options['js'], $options['js']):$this->__options['js'];
$this->__options['css'] = !empty($options['css'])?am($this->__options['css'], $options['css']):$this->__options['css'];
$this->Vue =& ClassRegistry::getObject('view');
$this->__options['js']['path'] = $this->clean_path($this->__options['js']['path']);
$this->__options['js']['cachePath'] = $this->clean_path($this->__options['js']['cachePath']);
$this->__options['css']['path'] = $this->clean_path($this->__options['css']['path']);
$this->__options['css']['cachePath'] = $this->clean_path($this->__options['css']['cachePath']);
$this->basePath['js'] = WWW_ROOT.$this->__options['js']['path'];
$this->cachePath['js'] = WWW_ROOT.$this->__options['js']['cachePath'];
$this->basePath['css'] = WWW_ROOT.$this->__options['css']['path'];
$this->cachePath['css'] = WWW_ROOT.$this->__options['css']['cachePath'];
}
function scripts($type) {
switch($type) {
case 'js':
$cachefile_js = $this->generate_filename('js');
return $this->get_js_html($cachefile_js);
case 'css':
$cachefile_css = $this->generate_filename('css');
return $this->get_css_html($cachefile_css);
default:
$cachefile_js = $this->generate_filename('js');
$output_js = $this->get_js_html($cachefile_js);
$cachefile_css = $this->generate_filename('css');
$output_css = $this->get_css_html($cachefile_css);
return $output_css."\n".$cachefile_js;
}
}
private function generate_filename($type) {
$this->libs[$type] = array_unique($this->libs[$type]);
// Create cache folder if not exist
if(!file_exists($this->cachePath[$type])) {
mkdir($this->cachePath[$type]);
}
// Define last modified to refresh cache if needed
$lastmodified = 0;
foreach($this->libs[$type] as $key => $lib) {
$lib = $this->clean_lib_list($lib, $type);
if(file_exists($this->basePath[$type].'/'.$lib)) {
$lastmodified = max($lastmodified, filemtime($this->basePath[$type].'/'.$lib));
}
$this->libs[$type][$key] = $lib;
}
$hash = $lastmodified.'-'.md5(serialize($this->libs[$type]).'_'.serialize($this->inline_code[$type]));
return 'cache-'.$hash.'.'.$type;
}
private function get_js_html($cachefile) {
if(file_exists($this->cachePath['js'].'/'.$cachefile)) {
return '<script src="'.'/'.$this->__options['js']['cachePath'].'/'.$cachefile.'" type="text/javascript"></script>';
}
// Get the content
$file_content = '';
foreach($this->libs['js'] as $lib) {
$file_content .= "\n\n".file_get_contents($this->basePath['js'].'/'.$lib);
}
// If compression is enable, compress it !
if($this->__options['js']['enableCompression']) {
App::import('Vendor', 'jsmin/jsmin');
$file_content = trim(JSMin::minify($file_content));
}
// Get inline code if exist
// Do it after jsmin to preserve variable's names
if(!empty($this->inline_code['js'])) {
foreach($this->inline_code['js'] as $inlineJs) {
$file_content .= "\n\n".$inlineJs;
}
}
if($fp = fopen($this->cachePath['js'].'/'.$cachefile, 'wb')) {
fwrite($fp, $file_content);
fclose($fp);
}
return '<script src="'.'/'.$this->__options['js']['cachePath'].'/'.$cachefile.'" type="text/javascript"></script>';
}
private function get_css_html($cachefile) {
if(file_exists($this->cachePath['css'].'/'.$cachefile)) {
return '<link href="'.'/'.$this->__options['css']['cachePath'].'/'.$cachefile.'" rel="stylesheet" type="text/css" >';
}
// Get the content
$file_content = '';
foreach($this->libs['css'] as $lib) {
$file_content .= "\n\n".file_get_contents($this->basePath['css'].'/'.$lib);
}
// Get inline code if exist
if(!empty($this->inline_code['css'])) {
foreach($this->inline_code['css'] as $inlineCss) {
$file_content .= "\n\n".$inlineCss;
}
}
// If compression is enable, compress it !
if($this->__options['css']['enableCompression']) {
App::import('Vendor', 'csstidy', array('file' => 'class.csstidy.php'));
$tidy = new csstidy();
$tidy->load_template($this->__options['css']['compression']);
$tidy->set_cfg('sort_selectors', FALSE);
$tidy->set_cfg('sort_properties', FALSE);
$tidy->parse($file_content);
$file_content = $tidy->print->plain();
}
if($fp = fopen($this->cachePath['css'].'/'.$cachefile, 'wb')) {
fwrite($fp, $file_content);
fclose($fp);
}
return '<link href="'.'/'.$this->__options['css']['cachePath'].'/'.$cachefile.'" rel="stylesheet" type="text/css" >';
}
function add_libs($type, $libs) {
switch($type) {
case 'js':
case 'css':
if(is_array($libs)) {
foreach($libs as $lib) {
$this->libs[$type][] = $lib;
}
}else {
$this->libs[$type][] = $libs;
}
break;
}
}
function add_inline_code($type, $codes) {
switch($type) {
case 'js':
case 'css':
if(is_array($codes)) {
foreach($codes as $code) {
$this->inline_code[$type][] = $code;
}
}else {
$this->inline_code[$type][] = $codes;
}
break;
}
}
private function clean_lib_list($filename, $type) {
if (strpos($filename, '?') === false) {
if (strpos($filename, '.'.$type) === false) {
$filename .= '.'.$type;
}
}
return $filename;
}
private function clean_path($path) {
// delete the / at the end of the path
$len = strlen($path);
if(strrpos($path, '/') == ($len - 1)) {
$path = substr($path, 0, $len - 1);
}
// delete the / at the start of the path
if(strpos($path, '/') == '0') {
$path = substr($path, 1, $len);
}
return $path;
}
}
?>
Have you tried this?
<?php $combinator->add_libs('js', array('jquery', 'other_lib', 'third_lib'));?>
By the way, if you are implementing the Combinator plugin right now in your app, I suggest you to use Mark Story's AssetCompress Plugin which is more up to date and well documented.