Angular 8+ event stoppropogation

I have a viewChild element which I show/hide by assigning a boolean value to it.

<div #acc class="user-info" [ngClass]="{'showDropdown': accountDropdownService.userDropdownIsVisible}">
  <div class="user-name">
    <div class="color-1 full-name">{{userdata.FirstName}} {{userdata.LastName}}</div>
    <div class="opened-eye-icon color-6__fm icon-icon_visible_off"
         [class]="balanceService.showBalance ? 'icon-icon_visible_off' : 'icon-icon_visible'"
         (click)="balanceService.toggleBalanceVisibility()"></div>
  </div>
  <div class="user-id color-6__fm">{{'General.Id'}}: <span><strong>{{userdata.Id}}</strong></span></div>
</div>

and its .ts file

@ViewChild('acc') public acc: ElementRef;

this.renderer.listen('window', 'click', (e: Event) => {
      if (e.target !== this.acc.nativeElement) {
        console.log('outside');
        console.log(e.target);
      }
    });

I need to hide viewChild element when I clicking outside of it, but when I click on its child elements like user-name or user-id its also understand as an outside click.

How can I prevent this when I’m clickin on div’s children elements?

Send Array after Loop

I try to make a list with products that I send to the client, but the res.send gets executed before the loop has finished.

Do you have any suggestions? Async/await doesn’t seem to work

Here is my code:

const Outfits = require("../models/Outfits");
const Products = require("../models/Products");


module.exports = (req, res) => {
    Outfits.find({ outfitId: req.params.id }, async (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            let productList = [];
            await productIds.map((e) => {
                Products.find({ id: e }, (error2, product) => {
                    if (error2) {
                        res.status(400).json({
                            status: "fail",
                        });
                    } else {
                        console.log(product);
                        productList.push(product);
                    }
                });
            });
            console.log(productList);
            res.status(200).json({
                status: "success",
                body: productList,
            });
        }
    });
};

Thank you very much!

Call onSelect callback for Air datepicker from Jest unit tests

I am writing a wrapper on top of Air-datepicker in React.js for our component library. I have chosen to pass/override ‘onSelect’ hook while passing the options to Datepicker while instantiating.

While writing the unit test using Jest and react-testing-library, I am not able to invoke onSelect handler through the event mechanism. The steps I am following:

  1. rendered the component.
  2. picked the text input component (a React component) using screen API.
  3. Fired focusIn event on text input, so that date picker will be displayed.
  4. Next, I am trying to select datepicker-cell.
  5. Next I am trying to fire the click event on datepicker-cell.
  6. If I put the breakpoint in onSelect hook, the control never comes to this hook.

Could you please help, how can I solve this issue?

Hamburger Menu position in React Native

i am trying to move the hamburger menu from left to right in react native. Unfortunately I can’t.
Can anyone help me please …? This is the code:

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { DrawerActions } from '@react-navigation/native';
import pageArticle from "./pages/article";
import pageFeed from "./pages/feed";

const Drawer = createDrawerNavigator();

const MyDrawer = () => {
  return (
    <Drawer.Navigator 
        initialRouteName="Feed"
        screenOptions={{
            drawerPosition: 'right',
        }}
    >
        <Drawer.Screen name="Feed" component={pageFeed}
        
        />
        <Drawer.Screen name="Article" component={pageArticle} />
    </Drawer.Navigator>
  );
}

export default function App() {
  return (  
    <NavigationContainer>
        <MyDrawer />
    </NavigationContainer>
    
  );
}

With the command drawerPosition: ‘right’, I can put the drawer on the right but not the hamburger menu.

Please… Help me…

jalali calendar for YITH Event Tickets for WooCommerce plugin

recently, I am using YITH Event Tickets for WooCommerce for a customer. The problem is my WordPress calendar is Jalali calendar (the WordPress language is Also Persian) but the plugin uses Gregorian calendar in the backend and admin panel, so when I set the date in Jalali type (like : 1400-10-05) every event would be set for 600 years Ago. How can I use the Jalali calendar for the backend?

Thanks in advance.

enter image description here

JavaScript for loop that alternates two constants

I’ve been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I’m completely stuck. I’m “able” to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array…), but not with two separate constants.
Could anyone offer some help?

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  let result = "";
  for (let i = 0; i < num; i++) {
    result += i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
  }
  return result;
}
console.log(repeteFrases(2));

Using Tone.js to add filters to an existing audio stream

I was able to add filters to an existing audio stream using the biquadfilter but was interested in trying to use Tone.js instead. But I’m having issues connecting everything together. I keep getting a DomException when trying to connect the filter to an audioContext.

function addFilter(fq) {

    var audioCtx = new (window.AudioContext || window.webkitAudioContext);
    var mediaElem = document.getElementById('myAudioElement');

    //Tone.context = audioCtx;
    Tone.context.createMediaElementSource(mediaElem)

    const bqfilter = new Tone.Filter(fq, 'lowpass').toDestination();

    Tone.connect(bqfilter, audioCtx.destination);
    //bqfilter.chain(audioCtx.destination)
});

The error message is just DomException when I try to connect or chain the filter to the audioCtx.destination. This seems to follow most of the other examples I’ve found online so I’m not sure why this is throwing an exception.

Can’t return user total presence.status of Global

I want to retrieve all my users of all guilds where my bot is used at.
What i need is a total(global) of these :

presence?.status == "offline")
presence?.status == "online")
presence?.status == "DND")
presence?.status == "bots")

well what i did is this and it returned 0 :

let userCount = message.client.users.cache.filter(member => member.presence?.status == "offline").size
    console.log("total",userCount)

If i want to return everyone as a total(global) that works normal:

let userCount = message.client.users.cache.size;
console.log("total",userCount)

any idea how to do this? i’m on v13

regards

Loading “many” related models eagerly with a “between” predicate

I have a model with “termStart” and “termEnd” dates. The rows in the table will have disjoint time ranges; that is, there won’t be overlaps. I’ve established a many-to-one relationship successfully, and now I want to do an eager load (a join) to the “many” table with a predicate that picks the row whose start-end range includes the current date. I think I need to do that with something like:

const model1s = parent.getModel1s({
    include: "model2",
    where: // something
});

I know that there’s a between operator, but I cannot find any information on exactly how it works, or how it works when I am checking two dates in the table with a single date in the query (as opposed to checking a single date in the table with a range in the query).

I’m only a few days into using Sequelize so this may be obvious. I’ve been going in circles through the documentation and I can’t find anything. If there’s a way of even supplying a raw SQL predicate fragment, that’d be fine by me; I know how to do it in SQL of course.

A related question is this: is there a way to go through the .getSomethings() method that establishing a many-to-one relationship creates, but do so such that Sequelize knows that the join will involve a single row? In other words, because my date ranges do not overlap, the “between” comparison (however it ends up working) is guaranteed to find either zero or one “model2” rows.

I know I could do this with a separate .findOne() call, but of course I’d prefer to do a single query to get all the model1 instances without having to do separate queries for each one of those.

Filtering an object array with another array

I am having a filtering problem..

objArray is the array that needs to be filtered.
selectedNames is an array that contains the values that I want to find in objArray.
I need to fetch all objects that have one or more values from selectedNames in their “names” property (an array) .

The output I am trying to get is :

let result = [{names:["A","B","C","D"]},
              {names:["A","B"]},
              {names:["A","D"]}
             ]

Here is a simplified version of my code:

let objArray = [{names:["A","B","C","D"]},
                {names:["C","D"]},
                {names:["C","D","E"]},
                {names:["A","B"]},
                {names:["A","D"]}
               ]

let selectedNames = ["A","B"]

result = this.objArray .filter(obj => {
   return this.selectedNames.includes(obj.names)
}


My code seems to work fine if names attribute was a single value and not an array. But I can’t figure out how to make it work on an array.

Any help is more than welcome

How should I organize method-like functions for Redux’s plain object states?

Say I am dealing with 2D vectors, 3D vectors and matrices (and probably more data types) in my app, and I have to do math operations on them.

If not restricted to plain objects, I could define classes and organize those operations as methods:

class Vec2 {
  ...
  add(other: Vec2) -> Vec2 { ... }
  withZ(z: number) -> Vec3 {
    return new Vec3(this.x, this.y, z);
  }
  // returns (a, b, c), where ax + by + c = 0 is the line going through this and other
  line(other: Vec2) -> Vec3 {
    return this.withZ(1).cross(other.withZ(1));
  }
  ...
}
...
class Matrix {
  ...
  add(other: Matrix) -> Matrix { ... }
  mul(other: Matrix) -> Matrix { ... }
  ...
}

However, with Redux I should store them as serializable objects, so:

  • Vec2 is [number, number]
  • Vec3 is [number, number, number]
  • Matrix is number[][]

With all the methods separated from the data, I have to rewrite them as conventional functions working on those plain data, but how should I organize all those method-like functions?

I have come up with 3 plans by far:

  1. Put all functions at the same level, with good old C-style naming (or some ad-hoc naming):

    type Vec2 = [number, number]; // similar for Vec3 & Matrix
    export function vec2Add ...
    export function vec2WithZ ...
    export function vec2Line(v1: Vec2, v2: Vec2) -> Vec3 {
      // so nostalgic writing code like this!
      return vec3Cross(vec2WithZ(v1, 1), vec2WithZ(v2, 1));
    }
    ...
    export function matrixAdd ...
    export function matrixMul ...
    

    Another downside shows up when importing those functions, I have to explicitly list every function used (rather than a single #include in C).

  2. Wrap plain data in rich objects, do the computation, and unwrap

    type Vec2 = [number, number];  // plain data
    class Vec2 { ... }  // rich object
    // FIXME name clash
    
    // reducer be like:
    const somePoint = new Vec2(state.somePoint);
    const newLines = action.newPoints.map((p) => somePoint.line(new Vec2(p)));
    if (...) {
      return { ...state, lines: newLines.map((l) => l.plainData()), ... };
    }
    ...
    

    This looks pretty nice (and quite like what math.js does), except for the naming: I have to name both the plain type and the class. Unfortunately I am not sure which one I should name as simplly Vec2 (and make the other type name more verbose).

  3. Group functions in namespaces (global objects, classes or even modules):

    // using object
    export const Vec2Op = {
      add: ...
      withZ: ...
      line: ...
    };
    
    // using class
    export class MatrixOp {
      static add ...
      static mul ...
    }
    

    This also makes the code quite verbose.

Is there a better way of organizing those functions?

How to open cart on Add to Cart event?

I’m trying to open the modal cart when I add a product to it on a Single Product page. This is the website I’m working on:

https://nueva.coronadeolivo.com/

I’ve tried many different things, like changing “aria-open” to true and adding a few classes to the cart; but nothing seems to work.

Any ideas how I might do this?

This is the element I’m targeting:

<a id="elementor-menu-cart__toggle_button" href="#" class="elementor-menu-cart__toggle_button elementor-button elementor-size-sm" aria-expanded="false">
            <span class="elementor-button-text"><span class="woocommerce-Price-amount amount"><bdi>74.95<span class="woocommerce-Price-currencySymbol">€</span></bdi></span></span>
            <span class="elementor-button-icon" data-counter="1">
                <i class="eicon"></i>
                <span class="elementor-screen-only">Cart</span>
            </span>
        </a>

crate a dict of lists of objects by lodash keyBy

I have a long list of objects. They look like this:

[{id: 1, brand: 'apple', user:'aa', name:'bb'},
{id: 2, brand: 'apple', user:'cc', name:'dd'},
{id: 3, brand: 'samsung', user:'ee', name:'ff'},
{id: 4, brand: 'samsung', user:'gg', name:'hh'},
{id: 5, brand: 'netflix', user:'ii', name:'jj'},
{id: 6, brand: 'super', user:'kk', name:'ll'},

Using Typescript, I wish to create a dictionary, where the key is brand, and the value is a list of all the items with that brand. so the result of the list above would be:

{
'apple':[{id: 1, brand: 'apple', user:'aa', name:'bb'}, id: 2, brand: 'apple', user:'cc', name:'dd'}],
'samsung':[{id: 3, brand: 'samsung', user:'ee', name:'ff'}, {id: 4, brand: 'samsung', user:'gg', name:'hh'}],
'netflix': [{id: 5, brand: 'netflix', user:'ii', name:'jj'}],
'super': [{id: 6, brand: 'super', user:'kk', name:'ll'}]
}

The order of the items in the list does not matter. I tried using _.keyBy(store.catalog, 'brand') but it left me with only one item for each brand, so for this example I lost two objects.

Returning a file from memory to a view for a user to download from an internal URL C#/js

I want to load a file from a URL into memory in a controller and pass it back to the user in the view

This is what I have

public class TickController : ApiController{
    [Route("api/Download")]
    [HttpPost]
    public async Task<StreamContent> Download([FromBody]string url){
        
        WebRequest request = FtpWebRequest.Create(url);
        using (WebResponse response = request.GetResponse())
        {
            //load file into stream
            Stream responseStream = response.GetResponseStream();
        }
        
        //return file to view
    }


This is what the above function is called by;

    async downloadAttach(URL: any) {
            window.open(await WebApiManager.post('Download', URL));
        }

}

However I havent been able to work out how to force it to download on the users side when they click a HTML button

I have seen solutions that work with ControllerBase and Web.MVC. But as shown above I am using ApiController class so I cannot use those methods.

Any help would be appreciated.

Is there any react package for gauge charts with resposive width and height also should have scale(with ticks) and that takes both -ve and +ve values?

I am trying to find a gauge-chart-package for my react project that has few inbuilt features.

For example,

  1. It should have a responsive container. Which should fit in any container with any window size.
  2. It should have a scale with tagged values or a custom scale, and it should be within the circle rather than outside the circle.
  3. It must accept both negative and positive values. As in, from 1 in the middle to negative and positive values on its sides, ending with zero. (Similar to a power factor value gauge chart)

I did locate a couple of packages that produce gauge-charts, but they are useless to me. Here are the ones I received, as well as the reason why I rejected them!!

  1. react-gauge-chart and react-advanced-gauge-chart –> Has amazing animations, vibrant design, and also responsive just that it doesn’t have a scale so rejected. (Would love to work on a fork to add these extra features (Please forgive me. I am very new to creating packages)).
  2. react-d3-speedometer –> Same here but I did find value segments but the other problems are still consistent.
  3. react-gauge-ultimate –> No Scale, etc..

One crazy thing I that I found the exact thing that I wanted on the Syncfusion website but it’s not free and I need this stuff for free!!.

I would appreciate it if anybody can suggest or help me on the same for developing the same.

Thank you very much!!