Graphql conditional where Query

I am Using Graphql to fetch data from api with some Where condition. In that, i need to check whether a field is not null and if so then i need to check for some key is present in that object and write the where query.

My Graphql query is as follows:
query Orders{
orders(limit:500 where:”(store(key in (“store1″,”store2”))) and (state(key in (“state1″,”state2″)))”){
total
count
results {
id
origin
store{
key
}
state{
key
id
}
}
}
}

if i run the above query i am getting error as below
“message”: “Malformed parameter: where: The field ‘key’ does not exist.”,
“path”: [
“orders”
],
This is because the object state is null in some of the results and so , i need to check for the key if the state object is not null.

I tried state!=null but this doesn’t work.
Any ideas or suggestions?

Upload image to array of base64

I want to make a upload image and preview, want to make all selected images to base64 and create an array from it, but after onload and array.push array return empty, any idea what’s wrong? I’m using this code in reactjs but for demo to share you I managed to use jQuery

function handleImage(e) {
  let image = e.target.files;
  let result = [...image];
  let array = [];

  result && result.map(function(img, i) {
    let fileReader = new FileReader();
    fileReader.readAsDataURL(img);
    fileReader.onload = () => {
      array.push(fileReader.result);
    }
  })
  console.log(array) // return empty!
}

$('input[type="file"]').change(function(e) {
  handleImage(e)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" onChange="handleImage" />

How can I add ‘Read more’ and ‘Read less’ functionality for long text in R Shiny?

I am trying to add ‘Read more’ or ‘Read less’ functionality for long text in my Shiny app. My knowledge related to JS/ html is limited, so if there is any assist regarding communicating information between shiny, js or html that would be helpful.

I was referring this tutorial but not able to understand how to implement the same in the shiny app.

Thanks in advance.

What is `values` in firefox web console?

I was playing around firefox web console before I encountered this strange behaviour. I cannot recall window.values or sth from web standard, and it is not a website-specific, so I guess it must be from the web console itself:

the values

But what is it and what is it for, and where can I find a document for that ?

Using JS function returning dynamic in Kotlin JS within the default Promise constructor results in ClassCastException

I got this error when trying to transform gapi calls into Promises, but I suppose calls to other functions may result in the same issue. First, I added the library as a script in the page:

script(src = "https://apis.google.com/js/platform.js") {
    async = true
    defer = true
}

next, I fetched gapi object from window:

import kotlinx.browser.window
import org.w3c.dom.get

val gapi = window["gapi"]

finally, I used the load function like so:

import kotlin.js.Promise

fun loadGapi() = Promise<Unit> { resolve, _ ->
    gapi.load("client:auth2") { resolve(Unit) }
}

giving me a warning in the IDE:

IDE warning: Implicit (unsafe) cast from dynamic to Unit

This resulted in the following error when called inside a page:

Uncaught (in promise) ClassCastException {message: undefined, cause: undefined, name: ‘ClassCastException’, stack: ‘ClassCastExceptionn at THROW_CCE (http://localh… (http://localhost:3000/static/app.js:4930:14)’}

Why is node-sass being built when I upgrade from npm6 to npm7?

My app uses sass, not node-sass. node-sass is nowhere in my package-lock.json.

When I try to npm install with npm7, it fails with the below error.

What’s going on- is node-sass a dev dependency of something else and being built?

npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-sass
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c node scripts/build.js
npm ERR! npm ERR! Building: /opt/local/bin/node /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! npm ERR!   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.3.6"' -I/Users/john/.node-gyp/14.18.3/include/node -I/Users/john/.node-gyp/14.18.3/src -I/Users/john/.node-gyp/14.18.3/deps/uv/include -I/Users/john/.node-gyp/14.18.3/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/eval.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/eval.o ../src/libsass/src/eval.cpp
### above line repeated many times
npm ERR! npm ERR!

How to get only one random element from object?

My model.py is this.

class Country(models.Model):
    country_name = models.CharField(max_length=200)
    country_fact = models.CharField(max_length=1000)
    country_capital = models.CharField(max_length=100)
    country_flags = models.ImageField(upload_to='flags')

View.py is this

def index(request):
    country = Country.objects.all()
    return render(request,'index.html',{'country':country})

I’m retrieving those data in HTML by using this

{% for count in country %}
 <img src="{{ count.country_flags.url }}">

This retrieves all the country images from the database(I’m using Postgresql). I want to retrieve only one random country flag from the database. How can I achieve this? Thanks for the help.

Map array of objects and change one property with a function that calls an API. I keep getting promise pending

I have to loop through an array of objects and modify one single property in each object. I modify this property with a function that connects to the Twitter API. My problem is that I must be using async and await wrongly because I am getting a promise pending.

This is my code:

getProfile:(req,res)=>{
        try {
           const userId=req.params.id 
           const profile=db.query('SELECT * FROM profiles WHERE user_id=?',
        [userId],async (err,result)=>{

            if(err) return res.status(404).send(err)

            const profiles= await result.map(  obj=>{

                const container={}
                container['name']=obj.profile_name
                container['desc']=obj.profile_desc
                container['twitter']=  connectTwitt.getTwitt(obj.twitt)//calls to api
                return  container
            })
            console.log(profiles)// promise pending
            res.send(profiles)

This is the structure of the array of object that I am mapping:

[
 {profile_name:`Elon Musk`, profile_desc:'enterpreneur',twitt:636465}
]

dayjs – not a function

I’m passing two dayjs date to Vars.date global variables.

var dayjs = require("dayjs") for import

const date1 = Vars.date
const date2 = Vars.date
let diff = date1.diff(date2, 'month')
console.log('diff' + diff)

error: TypeError: date1.diff is not a function

I am unable to use diff and get methods, always ‘not a function’

What did I miss?

Javascript Ajax returning Undefined

Here my code first

Javascript code

function ajaxrequsern(str) {
  if (str.length == 0) {
    document.getElementById("errorusername").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        try {
          var data = JSON.parse(this.responceText);
          document.getElementById("errorusername").innerHTML = data.m;
        } catch (err) {
          document.getElementById("errorusername").innerHTML = err;
        }
      }
    };
    let url = "example.com/register/'?>ajax?username=" + str;
    xmlhttp.open("GET", url, true);
    //xmlhttp.getResponseHeader("Content-type","application/x-www-from-urlencoded"); // ajaxrequsern("meo");
    xmlhttp.send();
  }
}

PHP code of Ajax file

<?php
header('Content-Type: application/json');
header('Acess-Control-Allow-Origin: *');
$error=" ";
if(isset($_GET['username'])){
    $ajaxun=$_GET['username'];
    if(strlen($ajaxun)<=3){
        $error="Username must contain more than 3 chracter";
    } else{
        $$error="ok";
    }
}
echo json_encode(array('m' => $error));
//echo $error;
?>

I tried both json or direct but getting response undefined, although I check php file working fine, please help

How to get the names of all involved computed CSS custom properties of a given HTML element with JavaScript?

In JavaScript/DOM there’s getComputedStyle to get access to all the computed style properties of a given element and then there’s getComputedStyle(...).getPropertyValue(...) the get the actual value of a computed style property.

But how do I get the names of all involved custom properties (those that start with ‘–‘)? TYVMIA

React map object as array?

I know its possible to map an array of some sort like so:

{sumArray.map((summary, index) => (
    <Col className="stat-element" key={index}>
        
    </Col>
))}

However I want to map a single object by each of its properties:

const [summary, setSummary] = useState([{rank: 0}, {trending: 0}, {totalTaskCompleted: 0}, {avgTaskCorrect: 0}, {avgTaskTime: 0 }]);

    useEffect(() => {
        if (parentToChild){
            console.log(parentToChild)
            const result = Object.values(parentToChild);
            setSummary(result);
            console.log(result);
        }

      }, [])

However on output this strips the properties title, how do I make it retain the properties name so I can display each within the following? :

{summary.map((property, index) => (
    <Col className="stat-element" key={index}>
        {index} {propertyname} {property}
    </Col>
))}

Why does the DOMParser cease to exist outside of this if statement?

I am using the DOMParser() to create a new Document Object Model from a remote webpage so that I can make an in-browser web scraper. This is the code that I have to retrieve the remote webpage.

function getDOM(url){
  // Variables
      let dom = new Document;
      let xhr = new XMLHttpRequest();
      let cors = "https://cors-anywhere.herokuapp.com/"

  // Create and send the XMLHttpRequest
      xhr.open('GET', cors + url, true);

      // xhr.responseType = 'document'; // This was necessary but then i changed 
      // the way i was accomplishing things and it isnt necessary anymore, I do not 
      // know why.

  // This loads the xhr request into a new DOMParser
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
              dom = new DOMParser().parseFromString(xhr.responseText, 'text/html')

              // This line of code is capable of printing the value of the "productTitle"
              // element to the console, but if i try this same line of code outside of 
              // this if statement it returns an error saying "cannot read 
              // properties of null" 
              console.log(dom.getElementById('productTitle').innerText);
          }
      }

  // This sends the request to the specified url
      xhr.send(null)

  //Returns the new DOMParser to the product class 
      return dom;
}

The issue is that i cannot manipulate or access any of the contents of the “dom” object outside of the if statement that the
“dom = new DOMParser().parseFromString(xhr.responseText, ‘text/html’)” exists in. Shouldn’t the parsed document be assigned to the “dom” element and accessible in the rest of the function? I am accessing the data successfully in the if statement through the “dom” object that I have assigned the results of the DOMParser() to.

Whether to clone an object for a prototype

What is the difference between the following two ways to define a prototype, and is one more correct than the other?

// prototype
const animal = {
    breathe() {console.log('The animal is breathing.')},
}
// construtor
function Dog(name) {
    this.name = name;
}

Dog.prototype = animal; // without Object.create()

let a = new Dog('Annie');
a.breathe();
// prototype
const animal = {
    breathe() {console.log('The animal is breathing.')},
}
// construtor
function Dog(name) {
    this.name = name;
}

Dog.prototype = Object.create(animal); // with Object.create

let a = new Dog('Annie');
a.breathe();

Why would one be more preferable over the other (especially if it is a const object)?

The way to keep the alert display when viewing the production web page

I’m trying to create a program to keep the alert display when viewing the production web page.

For example, I have two pages as follows:

Only when viewing the PROD page, I’d like to display the alert that covers the content. Please see the image I attached.
alert

As I’m beginner of programing, I have no idea how to realize it. Could anyone give me an advice for this? I have basic knowledges of HTML/CSS/Java/JS.

Thank you!