Case insensitive by searching for the data in a table in Vue.js

I have the following:

<v-text-field
        v-model="search"
        append-icon="mdi-magnify"
        label= "Buscar"
        single-line
        hide-details
        :style="{color: '#000'}"
        class = "container-derecha"
        @input="handleSearch"
></v-text-field>
<v-card class="table">
        <v-card-title class="v-card-title">
          <v-spacer></v-spacer>
        </v-card-title>
        <v-data-table
          :headers="tableHeaders"
          :items="tableItems"
          :items-per-page="15"
          :search="search"
          class="elevation-1"
          :style="getTableHeight()"
        ></v-data-table>
</v-card>

The idea is to filter the table data by means of a search. I want the search to be case insensitive.

I’m trying it using the @input="handleSearch" method in <v-text-field>. In ‘this.search’ is stored what I type in the search. In ‘this.tableItems’ are the table data, which ‘item.nivel’ is the one that has to be case insensitive.

handleSearch() {
    this.$store.state.nameSearch = this.search.toLowerCase().normalize("NFD").replace(/[u0300-u036f]/g, "");

    const arrResultsSearch = [];
    
    let searchValue = this.search.toLowerCase();
    searchValue = searchValue.normalize("NFD").replace(/[u0300-u036f]/g, "");

    this.tableItems = filterData(this.config.sources, this.config.filters).filter((item: any) => {
      const itemValue = item.nivel.toLowerCase().normalize("NFD").replace(/[u0300-u036f]/g, "");
      return itemValue.includes(this.$store.state.nameSearch);

    });

    eventBus.$emit("PopulateReportInforme", this.tableItems, this.tableHeaders);
}

Can anyone help? thank you!

Multiple dock icons for single Electron app?

My Electron app has two modes, let’s call them A and B.*

When switching between the two modes, I’m creating a new BrowserWindow and changing the dock icon (see “What I’ve Tried” below).

Is there a way to make it so that when a user right-clicks > “Keep in Dock” on MacOS in Mode A it creates a distinct docked app icon that launches the app into mode A, and vice versa for mode B?

I.e. is it possible to have multiple docked icons for a single Electron app?


*: The modes A and B essentially boots the same React app, where A is a stripped-down version of the app. Some users prefer to only use the stripped down version, which is why I want to enable docking separate versions of the app. And I don’t want to bundle A as a separate app since the user needs to be able to switch between the two modes inside the app’s UI.

What I’ve tried

let windowA;
let windowB;

const bootInModeA = () => {
  windowA = new BrowserWindow({
    ...,
    icon: 'iconA.png',
  })

  // Change dock icon.
  const realmImage = nativeImage.createFromPath(getAssetPath('iconA.png'));
  app.dock.setIcon(realmImage);
};

const bootInModeY = () => {
  // Vice versa.
};

const bootApp = () => {
  // Create a throwaway window so the main process remains open.
  const throwawayWindow = new BrowserWindow({
    show: false,
  });

  if (isModeA) {
    windowB.close()
    bootInModeA();
  } else {
    windowA.close()
    bootInModeB();
  }

  throwawayWindow.close();
}

The problem is that right-click > “Keep in Dock” pins the same app icon and provides me with no information about what version of the app they want to keep pinned.

I could create a custom “Keep in Dock” MenuItem that stores the last mode with electron-store, however this doesn’t allow two different dock icons.

Any pointers appreciated.

How can I fill my new shapes red after using this.matter.add.fromVertices

I am making a small game which cuts objects in half.

I need the new shapes created to be filled in red, however it is not working.

Lines 94-99 are where the new shape is created, and hopefully filled in red…

line 99 is where I am currently working!

I have tried to use .render.fillStyle to make the shapes red, but this is not working. Any help would be greatly appreciated!

enter image description here

let level1;
window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 600,
            height: 700
        },
        scene: scene1,
        physics: {
            default: "matter",
            matter: {
                gravity: {
                    y: 0
                },
                debug: true,
            }
        }
    }
    level1 = new Phaser.Game(gameConfig);
    window.focus();

}
class scene1 extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }

    
    create(){

        this.matter.world.update30Hz();
        this.matter.world.setBounds(10, 10, level1.config.width - 20, level1.config.height - 10);
        let rect = this.add.rectangle(level1.config.width / 2, level1.config.height / 2, 600, 100, 0xff0000);
        this.matter.add.gameObject(rect);
        this.lineGraphics = this.add.graphics();
        this.input.on("pointerdown", this.startDrawing, this);
        this.input.on("pointerup", this.stopDrawing, this);
        this.input.on("pointermove", this.keepDrawing, this);
        this.isDrawing = false;
        this.add.text(13, 11, 'Level 1',{fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif'});


    }

    startDrawing(){
        this.isDrawing = true;
    }
    keepDrawing(pointer){
        if(this.isDrawing){
            this.lineGraphics.clear();
            this.lineGraphics.lineStyle(1, 0xff0000);
            this.lineGraphics.moveTo(pointer.downX, pointer.downY);
            this.lineGraphics.lineTo(pointer.x, pointer.y);
            this.lineGraphics.strokePath();
        }
    }
    stopDrawing(pointer){
        this.lineGraphics.clear();
        this.isDrawing = false;
        let bodies = this.matter.world.localWorld.bodies;
        let toBeSliced = [];
        let toBeCreated = [];
        for(let i = 0; i < bodies.length; i++){
            let vertices = bodies[i].parts[0].vertices;
            let pointsArray = [];
            vertices.forEach(function(vertex){
                pointsArray.push(vertex.x, vertex.y)
            });
            let slicedPolygons = PolyK.Slice(pointsArray, pointer.downX, pointer.downY, pointer.upX, pointer.upY);
            if(slicedPolygons.length > 1){
                toBeSliced.push(bodies[i]);
                slicedPolygons.forEach(function(points){
                    toBeCreated.push(points)

                })

            }
        }
        toBeSliced.forEach(function(body){
            this.matter.world.remove(body)
        }.bind(this))
        toBeCreated.forEach(function(points){
            let polyObject = [];
            for(let i = 0; i < points.length / 2; i ++){
                polyObject.push({
                    x: points[i * 2],
                    y: points[i * 2 + 1]
                })
            }
            let sliceCentre = Phaser.Physics.Matter.Matter.Vertices.centre(polyObject)
            let slicedBody = this.matter.add.fromVertices(sliceCentre.x, sliceCentre.y, polyObject, {
                isStatic: false
            });

            slicedBody.render.fillStyle = 0xff0000;

            this.add.text(13, 11, 'Level 1 Complete!',{fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif'});

        }.bind(this))
    }
};



Wrong result value( forecastCumulativeUnderOverSpendCurrent) when any variable contains a negative value

My code and values of a b and c in this case:

const a = (Number((Number($('#tdTotalExpectedIncomeCurrent').data("val")) || 0).toFixed(2))); //1051234.14
const b = (Number((Number($('#tdCumulativeUnderOverSpendPrevious').data("val")) || 0).toFixed(2)));//-581805.11
const c = (Number((Number($('#numCurrentForecastedTotal').data("val")) || 0).toFixed(2)));//469429.03

let forecastCumulativeUnderOverSpendCurrent = (a + (b)) - c;

//forecastCumulativeUnderOverSpendCurrent should be 0 but I get a diffent value.
        

enter image description here

RxJS first operator

I am new to RxJS. I was reading about first operator and understood that it returns the first element from a list/array/sequence or the first element which matches the given predicate.

I have written the below code

new Observable<number[]>(s => {s.next([1,2,3,4]);}).pipe(first()).subscribe({
      next: (response) => console.log(response) // prints [1,2,3,4]
    })

I was expecting that since my observable is emitting an array and the first operator would only return the first value to the subscribe’s next function and 1 would be printed. Instead the complete array is printed.

from([1,2,3,4]).pipe(first()).subscribe({next: (res) => console.log(res)}) // prints 1

This code works as expected.

How are these two blocks of code different? Can anyone please explain?

NodeJS code gives Error message “unexpected token ‘<'"

I coded a Node.js application a year ago that ran fine. But today when I try to run it using the command “node app.js”, I get the error message

    <div>
    ^

SyntaxError: Unexpected token '<'

From this code

render() {
  return (
    <div>
      <GlobalStyle/>
      <Header />
      <Switch>
        <Route exact path='/' component={HomePage} />
        <Route path='/shop' component={ShopPage} />
        <Route exact path='/checkout' component={CheckoutPage} />
        <Route exact path='/contact' component={ContactPage}/>
        <Route
          exact
          path='/signin'
          render={() =>
            this.props.currentUser ? (
              <Redirect to='/' />
            ) : (
              <SignInAndSignUpPage />
            )
          }
        />
      </Switch>
    </div>
  );
}
}

Angular Ag-Grid – How to display array of object values comma separated

[
    {
        "processId": 1,
        "crIds": [
            {
                "crId": "10000112",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000112"
            },
            {
                "crId": "10000114",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000114"
            }
        ]
    }
        ]
    }
]

this.colDeps = [
        {
            "colId": "processId",
            "headerName": "ID",
            "field": "processId",
            "filter": false,
            "floatingFilter": false,
            "minWidth": 30,
            "maxWidth": 30,
            "width": 40,
            "cellRenderer": "agGroupCellRenderer"
        },
        {
            "colId": "crIds",
            "headerName": "CR ID",
            "field": "crIds",
            "filter": false,
            "floatingFilter": false,
            "minWidth": 170,
            "width": 170 
        }

]

I’m using ag-grid and I’ve an array of object & I need to display id & CR ID. I’m displaying Id, but for CR ID I need to display hyperlink with text as crId and link as url.

How to assign a promise response to a global variable and use across

I have the below piece of code in my angularjs controller.

var vm = this;
vm.list= [];

function getList() {
$http.get('/product/code').then(function (response) {
  if (response) {
    vm.list= response.data;
    console.log('vm.list inside promise', vm.list); // I will get the data here
  }
 });
 }

getList(); 

console.log('vm.list outside promise', vm.list); // I cannot get the data here outside .then

How can we assign the promise response to a global variable here and used across the js file? I tried with async and await but nots works exactly what I need.

Suitescript: why would I get different behavior with identical copies of the same script with a different name?

I am working with a script to update the memo line on amortization journal entries. I had it working in a sandbox account and tried to make some changes that never worked out. I scrapped that idea and when I reloaded the original script, it throws an error every time. I saved the script with a new name, deleted the old deployment, re-uploaded everything, and it worked fine. CompareDiff says the files are identical. Now when trying to implement the script in production, I get the error always. I’ve tried uploading the script countless times with different names, deleting it and the corresponding deployment between each attempt…I understand the script just fine but I don’t understand what netsuite is doing with it to get different results from identical .js files.

I don’t know what else to try

Remove Express Session from Mongodb after destroy

I am not sure what I am doing wrong.

I believe I followed the instructions to creating and connecting express-session to a store as shown below:

function getSessionStoreURL() {
    const env = app.get("env");
    if (env === "development") {
        return process.env.DEV_DB;
    }
    return process.env.PROD_DB;
}

app.use(
    session({
        secret: SESSIONS_SECRET,
        resave: false,
        saveUninitialized: false,
        cookie: { secure: true },
        store: MongoStore.create({ mongoUrl: getSessionStoreURL() })
    })
);

Here is the function that creates the session after login:

function createNewUserSession(req, userId, moreUserData) {
    try {
        const session = req.session;
        session.userId = userId;
        session.moreUserData = moreUserData;
        session.save();
        //...Some async code omitted for code brevity
    } catch (e) { }
}

Yet, when I explicitly call the following on password change, the session is destroyed somehow but when I checked my mongodb the session object is still there. So technically it was never destroyed in the store.

async destroySession(req) {
    req.session.destroy((err) => {
        if (err) {
            console.log('Error destroying session:', err);
        } else {
            console.log('Session destroyed');
        }
    });
}

Below are my packages:

"connect-mongo": "^5.0.0",
"express-session": "^1.17.3",

And please note that sessions are only created during login on my site. Not just by mere site visiting.

So, please what do I do to ensure once req.session.destroy is called, it should also immediately delete the session object from mongodb.

Closing parent jsp when response is pushed

I’m opening a jsp(child jsp) from another jsp(parent jsp) using window.open() in the same parent frame. The child jsp pushes a zip to the client using ServletOutputStream in HttpServletResponse. When the response is pushed i.e after the save dialog box appearing I want the parent window also to close.
But it’s not happening. Anybody with any suggested workaround?

Thanks in advance .

When using Vue Router, I am experiencing a situation where it is not functioning properly

Vue: 3.3.4
Vue Router: 4.x
I have defined constantRoutes and asyncRoutes in my router. asyncRoutes is dynamically added based on the user’s role. However, I am encountering a strange situation where the ‘porfile’ method defined in constantRoutes is identical to the ‘wage’ method defined in asyncRoutes, but it is not functioning as expected.
enter image description here
When I click “个人中心”/”profile”, it works fine.

But when I click “工资管理”/”Wage”, it throws an error.

This is the code for defining my router:

const Layout = () => import('@/layout/index.vue')
const Wage = () => import('@/views/Admin/Wage/index.vue')

export const constantRoutes = [
  {
    path: '/',
    redirect: '/dashboard',
    hidden: true,
    component: Layout,
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        name: 'Dashboard',
        meta: { title: 'Dashboard' }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    hidden: true
  },
  {
    path: '/profile',
    redirect: '/profile/index',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/profile/index.vue'),
        name: 'Profile',
        meta: { title: '个人中心' }
      }
    ]
  }
];

export const asyncRoutes = [
  {
    path: '/wage',
    redirect: '/wage/index',
    component: () => import('@/layout/index.vue'),
    meta: { roles: ['finance staff'] },
    children: [
      {
        path: 'index',
        component: Wage,
        name: 'Wage',
        meta: { title: '工资管理' }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
});

export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
  });
  router.resolve = newRouter.resolve;
}

export default router;

Here is the code for dynamically adding routes:

import { defineStore } from 'pinia';
import { constantRoutes, asyncRoutes } from '../router';

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: []
  }),
  actions: {
    SET_ROUTES(routes) {
      this.routes = routes;
      this.routes = constantRoutes.concat(routes);
    },

    generateRoutes(roles) {
      return new Promise((resolve) => {
        let accessedRoutes;
        if (roles.includes('finance staff')) {
          console.log(asyncRoutes)
          accessedRoutes = asyncRoutes || [];
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
          console.log('accessedRoutes', accessedRoutes)
        }
        this.SET_ROUTES(accessedRoutes);
        resolve(accessedRoutes);
      });
    },

    async addRoutesToRouter(router, roles) {
      //get dynamic routes
      const routes = await this.generateRoutes(roles);
      //Recursively add routes
      const addRouteRecursive = (route) => {
        if (route.children) {
          route.children.forEach((child) => addRouteRecursive(child));
        }

        router.addRoute(route);
      };

      routes.forEach((route) => addRouteRecursive(route));
    }
  }
});

In fact, /profile in constantRoutes is working fine, but /wage in asyncRoutes is not functioning properly.

How to set codemirror to highlight multiple languages in Django admin?

For one of my pet projects, I needed to use syntax highlighting for one of the TextField fields. Codemirror is great for this. After trying several “django-batteries” with widgets, I decided to abandon external dependencies and install codemirror myself.

Models have TbTemplate with fields for describing templates. From there, the backend takes templates for rendering, and the TextField itself with the template is szJinjaCode.

I do it like this.

admin.py:

class TemplateAdminForm(forms.ModelForm):
    class Meta:
        model = TbTemplate
        fields = "__all__"
        widgets = {
            'szJinjaCode': forms.Textarea(attrs={'class': 'jinja2-editor'})
        }


# Template admin
@admin.register(TbTemplate)
class AdminTemplate(admin.ModelAdmin):
    class Media:
        # set for codemirror ON
        css = {
            'all': (
                # '/static/codemirror-5.65.13/doc/docs.css',
                '/static/codemirror-5.65.13/lib/codemirror.css',
                '/static/codemirror-5.65.13/addon/hint/show-hint.css',
                '/static/codemirror-5.65.13/addon/lint/lint.css',
                '/static/codemirror-5.65.13/theme/rubyblue.css',
            )
        }
        js = (
            '/static/codemirror-5.65.13/lib/codemirror.js',
            '/static/codemirror-5.65.13/addon/hint/show-hint.js',
            '/static/codemirror-5.65.13/addon/hint/xml-hint.js',
            '/static/codemirror-5.65.13/addon/hint/html-hint.js',
            '/static/codemirror-5.65.13/mode/xml/xml.js',
            '/static/codemirror-5.65.13/mode/javascript/javascript.js',
            '/static/codemirror-5.65.13/mode/css/css.js',
            '/static/codemirror-5.65.13/mode/htmlmixed/htmlmixed.js',
            '/static/codemirror-5.65.13/mode/jinja2/jinja2.js',
            # '/static/codemirror-5.65.13/addon/runmode/colorize.js',
            # '/static/codemirror-5.65.13/addon/hint/html-hint.js',
            # '/static/codemirror-5.65.13/addon/lint/lint.js',
            # '/static/codemirror-5.65.13/addon/lint/html-lint.js',
            '/static/js/codemirror/init_jinja2.js'
        )

    # set form TemplateAdminForm
    form = TemplateAdminForm
    # other description for admin TbTemplate
    # ...
    # ...

As you can see from the code, you also need to run the initialization file /static/js/codemirror/init_jinja2.js into statics-files. Actually, he took from the recipe and changed it a little:

/static/js/codemirror/init_jinja2.js

(function(){
    var $ = django.jQuery;
    $(document).ready(function(){
        $('.jinja2-editor').each(function(idx, el){
            function getSelectedRange() {
                return { from: editor.getCursor(true), to: editor.getCursor(false) };
            }
            var editor = CodeMirror.fromTextArea(el, {
                lineNumbers: true,
                tabSize: 2,
                // mode: 'text/html',
                mode: 'text/jinja2',
                gutters: ['CodeMirror-lint-markers'],
                theme: 'rubyblue',
                lint: true,
            });
            CodeMirror.commands["selectAll"](editor);
            var range = getSelectedRange();
            editor.autoFormatRange(range.from, range.to);
            range = getSelectedRange();
            editor.commentRange(false, range.from, range.to);
        });
    });
})();

We start, and everything works. The highlighting of Jinja2-tags and variables works more precisely. If you change mode: 'text/jinja2' to mode: 'text/html' in init_jinja2.js, the html-code will be highlighted, but the Jinja2-markup will not be highlighted… I want both codes to be highlighted. Even better if you also highlight CSS, JavaScript and JSON. How to make codemirror highlight it all at the same time?

P.S. The option suggests itself — to take the necessary “mod” files from the /static/codemirror-5.65.13/mode/ directory into codemirror and assemble your own “mode” from them, but this is a crippling solution for codemirror itself. When it is codemirror-updated, everything will collapse and this home-made “mod” will have to be reassembled. This, it seems to me, is wrong. I would like to turn on several “mod” (backlight modes) at the same time in a regular way. How?

Typescript unable to do false check on unassigned object

I’m trying to convert the following js into typescript but I’m having an issue with checking my account object as it is unassigned so the code won’t build:

const accounts = state.msalInstance.getAllAccounts();
let account;

if (accounts.length) {
  account = accounts[0];
} else {
  await state.msalInstance
    .handleRedirectPromise()
    .then(redirectResponse => {
      if (redirectResponse !== null) {
        account = redirectResponse.account;
      } else {
        state.msalInstance.loginRedirect();
      }
    })
    .catch(error) => {
      console.error(`Error during authentication: ${error}`);
    });
}

if (account) {}

The above works fine in js so I have converted it to the following ts, but now the final if won’t compile as I’m trying to use the account variable before anything has been assigned to it:

const accounts = state.msalInstance.getAllAccounts();
let account: object;

if (accounts.length) {
  account = accounts[0];
} else {
  await state.msalInstance
    .handleRedirectPromise()
    .then((redirectResponse: {
      account: object;
    }) => {
      if (redirectResponse !== null) {
        account = redirectResponse.account;
      } else {
        state.msalInstance.loginRedirect();
      }
    })
    .catch((error: {
      name: string;
    }) => {
      console.error(`Error during authentication: ${error}`);
    });
}

if (account) {
  // this won't compile anymore as account isn't assigned
}

How do I change the account object so I can see if it is null or undefined? I tried setting it specifically as null but it says that I can’t set an object to null.

MaxListenersExceededWarning in angular application

Suddenly I have started experiencing this warning in my angular application while running or creating the build.

(node:25132) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 open listeners added to [_0x273c75]. Use emitter.setMaxListeners() to increase limit

I tried updating my packages and npm version but it didn’t work.