Wednesday, October 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Dart thinks variable is marked final when it is not

Posted: 20 Oct 2021 09:31 AM PDT

I'm getting this error:

The final variable 'hasFocus' can only be set once. Try making 'hasFocus' non-final.dartassignment_to_final_local

I'm getting the error on this line here hasFocus = isFocused;

Code below shows hasFocus is not final, so why the error?

import 'package:flutter/material.dart';  import 'package:flutter/services.dart';  import 'package:flutter_riverpod/flutter_riverpod.dart';  import 'package:font_awesome_flutter/font_awesome_flutter.dart';  import 'package:reactive_forms/reactive_forms.dart';  import 'package:vepo/src/presentation/common/constants/length.dart';  import 'package:vepo/src/presentation/widgets/form_fields/date_time_range_field/date_time_range_picker_field.dart';  import 'package:vepo/src/presentation/widgets/form_fields/duration_field/duration_field_vm.dart';  import 'package:vepo/src/presentation/widgets/interactive_non_form_widgets/buttons/icon_buttons/icon_button/icon_button_widget.dart';    class VpDurationField extends ReactiveFormField<Duration, Duration> {    VpDurationField(        {required this.formControlName,        required this.context,        required this.hintText,        this.labelText,        this.textColor,        this.hasFocus = false,        this.textAlign = TextAlign.left,        this.form,        this.onSubmitted,        this.key,        this.textInputAction = TextInputAction.done,        this.nextField,        this.validationMessages,        this.onFocusChange})        : super(              key: key,              formControlName: formControlName,              validationMessages: validationMessages,              showErrors: (control) => control.invalid,              builder: (ReactiveFormFieldState<Duration, Duration> field) {                final vm = context.read(durationFieldVmProvider);                  return Container(                    height: LENGTH_7,                    child: FocusScope(                        child: Focus(                      onFocusChange: (isFocused) {                        hasFocus = isFocused;                        if (onFocusChange != null) {                          onFocusChange(isFocused);                        }                      },                      child: TextField(                        controller: vm.textEditingController,                        onTap: () => vm.showDurationField(context),                        keyboardType: TextInputType.datetime,                        enableInteractiveSelection: false,                        focusNode: AlwaysDisabledFocusNode(),                        decoration: InputDecoration(                            hintText: hintText,                            errorMaxLines: 3,                            suffixIconConstraints: const BoxConstraints(                              minWidth: 2,                              minHeight: 2,                            ),                            suffixIcon: VpIconButton(                                icon: Icon(                              FontAwesomeIcons.calendarPlus,                              color: Theme.of(context).colorScheme.primary,                            )),                            alignLabelWithHint: true,                            labelStyle: TextStyle(                                height: 0,                                fontSize: 18.0,                                color:                                    Theme.of(context).colorScheme.primaryVariant),                            labelText: labelText,                            counterText: ''),                      ),                    )));              });      final TextAlign textAlign;    final String hintText;    final String formControlName;    final String? labelText;    final void Function(bool)? onFocusChange;    final void Function()? onSubmitted;    final Color? textColor;    final BuildContext context;    bool hasFocus;    Map<String, String> Function(AbstractControl<Duration>)? validationMessages;      /// This is only required when setting the next field to focus on.    final FormGroup? form;    Key? key;      /// This is only required when setting the next field to focus on.    final String? nextField;      /// This is to be 'next' if not the last field, and 'done' when is the last field.    final TextInputAction textInputAction;  }  

Comparing different functions for centrality measures in R

Posted: 20 Oct 2021 09:31 AM PDT

I have a non-weighted graph and wish to calculate 'betweenness centrality'.

However, I realise that qgraph's centrality_auto() and igraph's betweenness() produced different betweenness scores for the same nodes. Is this normal?

For qgraph, I used centrality <- centrality_auto(g1), where g1 is a graph object

For igraph, I used centrality <- betweenness(g2), where g2 is a network object

g2 = network(edgelist,directed=T) #network object  g1 = asIgraph(g2) #graph object  

Both centrality measures produce a betweenness centrality, but values turned out to be different.

Is there a way for me to customize ligatures on VS Code?

Posted: 20 Oct 2021 09:31 AM PDT

I would love to update my font ligatures, help - they are inconsistent throughout the app. Are they language specific?

include Dataset in R Package

Posted: 20 Oct 2021 09:31 AM PDT

I have successfully created a package that is available in CRAN. I include 2 different datasets in my package. But when I run any dataset function. For example:

Warning message:  In data(Rho) : data set 'Rho' not found  

appears. Its help files are working only. I have tried the solutions which are available Loading dataset in R here. But no solution. One more thing, I found that in data folder there is only Rho.rda and in data-raw there is more than one dataset. where no dataset is working. Kindly help.

one-to-many relationship with sequelize

Posted: 20 Oct 2021 09:30 AM PDT

I have 2 tables, users and users_signature where the signature takes several applications and I need to make a select according to the application.

Models:

user

const { INTEGER } = require('sequelize');  const Sequelize = require('sequelize');  const database = require('../../config/db');  const User_has_signature = require('./user_has_signature');     const Usuario = database.define('usuario', {      usu_id: {          type: Sequelize.INTEGER,          autoIncrement: true,          allowNull: false,          primaryKey: true      },      usu_rg: {          type: Sequelize.STRING,      },  },  {      freezeTableName: true,      createdAt: false,      updatedAt: false,  });  User.hasMany(User_has_signature, {as: 'user_has_signature'});    module.exports = User;  

User_has_signature

const { INTEGER } = require('sequelize');  const Sequelize = require('sequelize');  const database = require('../../config/db');     const User_has_signature = database.define('user_has_signature', {      usu_has_signature_id: {          type: Sequelize.INTEGER,          autoIncrement: true,          allowNull: false,          primaryKey: true      },      user_usu_id: {          type: Sequelize.STRING,      },      signature_aplicativo_signature_aplicativo_id: {          type: Sequelize.STRING,      },      signature_type_signature_type_id: {          type: Sequelize.STRING,      },  },  {      freezeTableName: true,      createdAt: false,      updatedAt: false,  });  User_has_signature.associate = (models) => {      User_has_signature.belongsTo(models.User,        { foreignKey: 'user_usu_id', as: 'users' });    };  module.exports = User_has_signature;  

Controller

UserController

const User = require("../../model/user/user")  const User_has_signature = require("../../model/user/user_has_signature")    async index(req, res){          const user = await User.findAll({              include: [{                model: User_has_signature,                foreignKey: 'user_usu_id',                through: {                  where: {signature_ttype_signature_type_id: 3}                }              }]            })          res.status(200).json(user)          return      }  

The error that is returning to me in the terminal is: (node:15168) UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: user_has_signature is associated to usuario using an alias. You must use the 'as' keyword to specify the alias within your include statement

Why ML kit libs are heaver than they mentioned in the documentation?

Posted: 20 Oct 2021 09:30 AM PDT

I am trying to integrate ML kit text recognition (com.google.mlkit:text-recognition) in my application. In the document it is stating app size impact is

About 4 MB per architecture

enter image description here

But unfortunately it is heavier than mentioned in the documentation (https://developers.google.com/ml-kit/vision/text-recognition/v2/android).

Any idea why this happening?

How to implement tool tip in quill editor toolbar

Posted: 20 Oct 2021 09:30 AM PDT

We are using "quill": "1.3.7" version of quill editor in Ionic 4 application. We need to show tool tip for toolbar options. Is there any possible to enable tooltip for toolbar options.Here attached the quill editor sample screen for your reference.

NextJs + MaterialUI - prop 'className' did not match

Posted: 20 Oct 2021 09:30 AM PDT

I have tried multiple solutions that were suggested in MaterialUI and NextJS official examples and forums with no luck. My page is unable to use my MUI styles on the first render and I keep getting this error:

Warning: Prop `className` did not match. Server: "makeStyles-image-3 makeStyles-image-5" Client: "makeStyles-image-4 makeStyles-image-7"  

My _document.tsx:

import React from 'react';  import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document';  import { ServerStyleSheets } from '@material-ui/core/styles';    export default class MyDocument extends Document {      render() {          return (              <Html lang="en">                  <Head>                      <meta charSet="utf-8" />                      <link rel="icon" href="/favicon.ico" />                  </Head>                  <body>                      <Main />                      <NextScript />                  </body>              </Html>          );      }        static async getInitialProps(ctx: DocumentContext) {          const sheets = new ServerStyleSheets();          const originalRenderPage = ctx.renderPage;            ctx.renderPage = () =>              originalRenderPage({ enhanceApp: (App) => (props) => sheets.collect(<App {...props} />) });            const initialProps = await Document.getInitialProps(ctx);            return { ...initialProps, styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()] };      }  }  

My _app.tsx:

import '../styles/globals.css';  import type { AppProps } from 'next/app';  import React, { useEffect } from 'react';  import { CssBaseline, ThemeProvider } from '@material-ui/core';  import Head from 'next/head';  import { theme } from '../src/app/theme';    const App: React.FC<AppProps> = ({ Component, pageProps }) => {      useEffect(() => {          const jssStyles = document.querySelector('#jss-server-side');          console.log(jssStyles?.parentElement?.removeChild(jssStyles));          jssStyles?.parentElement?.removeChild(jssStyles);      }, []);        return (          <React.Fragment>              <Head>                  <title>My App</title>                  <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />              </Head>              <ThemeProvider theme={theme}>                  <CssBaseline />                  <Component {...pageProps} />              </ThemeProvider>          </React.Fragment>      );  };    export default App;  

The solutions I've tried:

https://github.com/mui-org/material-ui/blob/0ff9cb54a9/examples/nextjs-with-typescript/README.md

https://github.com/hadnazzar/nextjs-with-material-ui/blob/master/README.md

Also many from StackOverflow similar posts (though none of the answers helped, so please do not mark this as a duplicate).

Used packages versions:

    "@material-ui/core": "^4.12.3",      "next": "11.1.2",      "react": "17.0.2",  

Is there anything that I'm missing here?

JS Add to array with Spread Operator if non-NULL - Expression Syntax

Posted: 20 Oct 2021 09:31 AM PDT

I need to get an array resulting from the original array props.ids and conditionally (if not NULL) the variable selectedId appended. The following works, but the syntax doesn't look right. I need the selectedId && to check for non-NULL, and if so add selectedId. Is there a better syntax for this small expression?

const [selectedId, setSelectedId] = useState(null);    obj = {          'exclude':[...props.ids, selectedId && selectedId]}        }   

How can I remove a background just behind text?

Posted: 20 Oct 2021 09:31 AM PDT

I have a background image and on top of it, I have an overlay and on top of that I have some text. I want to remove the overlay just behind the text. For example I have a div with height 100vh and width 100% with a background image. I have overlay on top it which covers the entire image. I have a capital A in the centre whose color is transparent. I want to remove the overlay for that text so that the overlay is there for the entire image but for that letter it's background is the background image that is behind it without the overlay.

How can I install gfortran libopenblas-dev liblapack-dev on Windows 10?

Posted: 20 Oct 2021 09:31 AM PDT

I'm trying to install scipy libray with pip but I got many errors on command line , one of these error is :

   raise NotFoundError(msg)    numpy.distutils.system_info.NotFoundError: No BLAS/LAPACK libraries found.    To build Scipy from sources, BLAS & LAPACK libraries need to be installed.    See site.cfg.example in the Scipy source directory and    https://docs.scipy.org/doc/scipy/reference/building/index.html for details.  

However, To resolve this issue , I found many solution that describe how to avoid these problems .

One of solution that I've found is to install these libraries before install scipy :

sudo apt-get install gfortran libopenblas-dev liblapack-dev  sudo pip install scipy==1.2.1  

Source : https://github.com/scipy/scipy/issues/9005

This solution will works on Windows , but I didn't found how can I install these packages on Windows , What can I do in this case?

I need to make the sum of an column in javascript

Posted: 20 Oct 2021 09:31 AM PDT

This is html code that i can't edit :

    <table class="table table-hover">        <thead>          <tr>            <th scope="col">#</th>            <th scope="col">Expense name</th>            <th scope="col">Value per unity (lei)</th>          </tr>        </thead>        <tbody>          <tr>            <th scope="row">1</th>            <td>Water</td>            <td class="expense">62</td>          </tr>          <tr>            <th scope="row">2</th>            <td>Netflix subscription</td>            <td class="expense">49.50</td>          </tr>          <tr>            <th scope="row">3</th>            <td>Juice</td>            <td class="expense">16.40</td>          </tr>          <tr>            <th scope="row">4</th>            <td>New phone</td>            <td class="expense">2599</td>          </tr>        </tbody>      </table>      <h2>          Total expenses this month (lei):          <div id="total-expenses"></div>      </h2>  

My question is : How do i do that in code(javascript)? I have something in my head but i don t know how to write that. What i have in head is: i declare variable for expenses,or using this queryselector(but i don t know how to point at specific td, because i have 2 td's in 1 tr) and after i can make a function with sum of that column, but i don't know how to write that in code. Can someone help me

Need help to solve nodejs module.exports throws error

Posted: 20 Oct 2021 09:30 AM PDT

I have user route as below and I am importing controller in user.routes.js

//user.routes.js    const express = require('express')  const router = express.Router()  const userController = require('../controllers/user.controller')    router.get('/info', userController.getUser)    module.exports = router  

Below is how I have declared user controller

//user.controller.js    const {wrapController} = require("../ErrorHandlers/catchError");  const {Api404Error} = require("../ErrorHandlers/apiErrors");    function userController() {      const controller = {          getUser(req, res) {              throw Api404Error('User not found.')          }      }      wrapController(controller)      return controller  }    module.exports = userController  

But I am getting this error.

Route.get() requires a callback function but got a [object Undefined]  

I am new to Nodejs. Thanks for helping.

How to put an If Statement inside a Text widget ? - Flutter

Posted: 20 Oct 2021 09:30 AM PDT

Is it possible to use if statements in a Text() widget? I want to display a text only if browns, blacks and whites are true, and I want to display another text only if yellows, blacks and whites are true. Both have the same text style.

First text:

'Proporção: $browns agutis : $blacks pretos : $whites albinos'  

Second text:

'Proporção: $yellows dourados : $blacks pretos : $browns chocolates'  

My code (only with first text yet):

children: [              Text(                //add if statements here ?                'Proporção: $browns agutis : $blacks pretos : $whites albinos',                 style: TextStyle(                    fontFamily: 'courier',                    fontSize: 20.0,                    fontWeight: FontWeight.bold,                    height: 2.5,                    letterSpacing: 0.7),              ),],  

Pass datas to another component in Vuejs?

Posted: 20 Oct 2021 09:30 AM PDT

I have this filter function (belongs a List component), then I need to pass the results to another component, to fill my DataTable:

async filtroVariaveis () {                  try {                      this.loading = true;                        this.variaveis = await this.variaveisService.listVariables();                        let idGrupos = null;                      if (!this.grupos[0] && this.maquinaSelecionada[0]) {                          idGrupos = this.gruposOpcoes.map(m => m.id);                      }                        if (!this.grupos[0] && !this.maquinaSelecionada[0] && this.areaSelecionada[0]) {                          const idMaquinas = this.maquinasOpcoes.map(m => m.id);                          const grupo = this.gruposOpcoes.filter(a => idMaquinas.includes(a.id_maquina));                            idGrupos = grupo.map(a => a.id);                      }                        if (this.grupos[0]) {                          idGrupos = this.grupos.map(g => g.id);                      }                        const tipos = this.tipoVariavel.map(t => t === "Analógica" ? t = "ANALOGICA" : "DIGITAL");                      const tag = this.tagInput || this.variaveis.map(t => t.tag);                      const descricao = this.descricaoInput || this.variaveis.map(d => d.descricao);                        this.filtroAplicado = ((await this.variaveisService.listVariables(idGrupos, tipos, tag, descricao)) || []);                  } catch (err) {                      console.log(err);                  }  

this.variaveisService is my Axios services that communicates with my API.

My List component:

<template>  <two-cards>          <template #header>              <h4 class="card-title">Filtros</h4>              <slot>                  <router-link                      to="/variaveis/add"                      class="btn btn-success text-white align-self-center"                  >                  Adicionar variável                  </router-link>              </slot>          </template>          <template #one>              <form class="mt-2" @submit.prevent="filtroVariaveis">                  <div class="form-row">                      <div class="col form-group col-sm-6">                          <label for="data-final">Tag: </label>                          <b-form-input                              v-model="tagInput"                              id="data-final"                              input-class="bg-white"                          ></b-form-input>                      </div>                      <div class="col form-group col-sm-6">                          <label for="data-inicial">Descrição: </label>                          <b-form-input                              v-model="descricaoInput"                              id="data-inicial"                              input-class="bg-white"                          ></b-form-input>                      </div>                  </div>                  <div class="form-row">                      <div class="form-group col-sm-3">                          <label class="mt-2">Área </label>                              <vue-multi-select                                  class="multi-100"                                  v-model="areaSelecionada"                                  @input="checarArea"                                  search                                  historyButton                                  :options="{ multi: false, labelName: 'nome' }"                                  :selectOptions="areasOpcoes"                                  :btnLabel="() => areaSelecionada[0] ? areaSelecionada[0].nome : 'Selecione'"                              />                      </div>                      <div class="form-group col-sm-3">                          <label class="mt-2">Máquina </label>                              <vue-multi-select                                  class="multi-100"                                  v-model="maquinaSelecionada"                                  :disabled="!areaSelecionada[0]"                                  @input="checarMaquina"                                  search                                  historyButton                                  :options="{ multi: true, labelName: 'nome' }"                                  :selectOptions="maquinasOpcoes"                                  :btnLabel="() => customLabel(maquinaSelecionada)"                              />                      </div>                      <div class="form-group col-sm-3">                          <label class="mt-2">Grupo </label>                              <vue-multi-select                                  class="multi-100"                                  v-model="grupos"                                  search                                  historyButton                                  :options="{ multi: true }"                                  :selectOptions="gruposOpcoes"                                  :btnLabel="() => customLabel(grupos)"                              />                      </div>                      <div class="form-group col-sm-3">                          <label class="mt-2">Tipo</label>                              <vue-multi-select                                  class="multi-100"                                  v-model="tipoVariavel"                                  search                                  historyButton                                  :options="{ multi: true }"                                  :selectOptions="tiposOpcoes"                                  :btnLabel="() => customLabel(tipoVariavel)"                              />                      </div>                  </div>                  <div class="d-flex justify-content-end tcs-card-footer-action">                      <button                          class="btn btn-success tcs-btn"                          type="search"                      >                          <SearchIcon />                      </button>                  </div>              </form>          </template>          <template #two>              <GenericList                  title="variáveis"                  :linhas="linhas"                  data-table-state-name="Variável"                  add-route="add_variavel"                  edit-route="edit_variavel"                  :cols="['#', 'Tag', 'Descrição', 'Tipo']"                  :cols-name="['id', 'tag', 'descricao', 'tipo']"                  :cols-map="i => [i.id, i.tag, i.descricao, i.tipo]"              />          </template>      </two-cards>  </template>    computed: {              linhas () {                  return this.lista.map((row) => ({                      href: { name: this.editRoute, params: { id: row.id }},                      cols: this.colsMap(row)                  }));              }          },  

My GenericList component, where I need to put this datas:

<template>      <div>          <DataTable              scroll              :async="pagination"              :loading="loading"              :colunas="parsedCols"              :linhas="linhas"              :errMsg="errMsg"              :state="dataTableState"              @state-change="setStateDataTable"          >              <template #results-page v-if="pagination">                  <select                      class="custom-select ml-1"                      :value="results"                      @input="changeResults"                      data-cy="resultados-pagina"                  >                      <option value="10">10 por página</option>                      <option value="20">20 por página</option>                      <option value="50">50 por página</option>                      <option value="100">100 por página</option>                      <option v-if="canShowAllResults" value="-1">                          Mostrar todos                      </option>                  </select>              </template>              <template v-for="col in cols" v-slot:[col]="{ value, item }">                  <slot :name="col" :value="value" :item="item">                      <router-link                          v-if="value && value.rota && value.nome && value.id"                          :to="{ name: value.rota, params: { id: value.id } }"                          title="Ir para a edição"                          >                          <edit-icon size="16" /> {{ value.nome }}</router-link                      >                  </slot>              </template>          </DataTable>          <Paginator              :page="page"              :pages="pages"              :count="count"              :disabled="loading"              :first="first"              :last="last"              @paginate="paginate"          />      </div>  </template>  

Generic List props:

props: {      loading: Boolean,        title: {          type: String,          required: true      },        addRoute: {          type: String,          required: true      },        editRoute: {          type: String,          required: true      },        dataTableStateName: {          type: String,          required: true      },        lista: {          type: Array      },        linhas: {          type: Array      },        cols: {          type: Array,          required: true      },        colsMap: {          type: Function,          required: true      },        colsName: {          type: Array,          required: true      },        canShowAllResults: {          type: Boolean,          default: false      },        showInativos: {          type: Boolean,          default: false      }  },  

I dont know how to fill this DataTable, someone can helps me?

Prevent cross-site scripting attacks when using innerHTML in JavaScript

Posted: 20 Oct 2021 09:31 AM PDT

I have an ajax call that returns the below HTML markup:

<select id="City" name="City"><option value="New York">Current</option></select>  

I am assigning the HTML markup (referred as "data") using innerHtml as shown below:

var cityDiv = document.createElement('div');  cityDiv.id = 'CityDiv';  cityDiv.innerHTML = data;  

How to prevent cross-site scripting when using innerHtml? TextContent and innerText properties doesn't work as HTML markup contains more than text.

Using printf to print out the time before running a program in Crontab giving an "invalid directive" error

Posted: 20 Oct 2021 09:30 AM PDT

I am running Ubuntu 21.10 and trying to setup a crontab task.

I want the date and time to be printed to the console before the task starts all of which get's logged to a log file.

This is what I have currently.

{ printf "\%(\%Y-\%m-\%d \%H:\%M:\%S)T  Started Task\n"; <run task> } >> /path/to/log/file  

When I type printf "%(%Y-%m-%d %H:%M:%S)T Started Task\n" I get the expected output:

2021-10-20 15:22:03 Started Task

However, in the crontab I know you have to escape out the "%" with \. Except even after escaping out all the % I end up with a error :

/bin/sh: 1: printf: %(: invalid directive

No matter how a try and format the crontab I still end up with the same error.

If anyone know what I have done wrong please help me, thank you.

My specific cronjob is as follows:

0 * * * * { printf "\%(\%Y-\%m-\%d \%H:\%M:\%S)T  Updating Certs\n"; sudo certbot renew  --post-hook "systemctl reload nginx.service postfix.service dovecot.service"; } >> /home/ubuntu/logs/certbot.log  

How to create a summarize new row from a pandas Dataframe and add it back to the same Dataframe for only specific columns

Posted: 20 Oct 2021 09:31 AM PDT

I have the below pandas dataframe.

d = {'id1': ['85643', '85644','8564312','8564314','85645','8564316','85646','8564318','85647','85648','85649','85655'],'ID': ['G-00001', 'G-00001','G-00002','G-00002','G-00001','G-00002','G-00001','G-00002','G-00001','G-00001','G-00001','G-00001'],'col1': [1, 2,3,4,5,60,0,0,6,3,2,4],'Goal': [np.nan, 56,np.nan,89,73,np.nan ,np.nan ,np.nan, np.nan, np.nan, 34,np.nan ], 'col2': [3, 4,32,43,55,610,0,0,16,23,72,48],'col3': [1, 22,33,44,55,60,1,5,6,3,2,4],'Name': ['aasd', 'aasd','aabsd','aabsd','aasd','aabsd','aasd','aabsd','aasd','aasd','aasd','aasd'],'Date': ['2021-06-13', '2021-06-13','2021-06-13','2021-06-14','2021-06-15','2021-06-15','2021-06-13','2021-06-16','2021-06-13','2021-06-13','2021-06-13','2021-06-16']}    dff = pd.DataFrame(data=d)  dff       id1     ID     col1 Goal   col2    col3   Name      Date  0   85643   G-00001 1   NaN     3       1     aasd      2021-06-13  1   85644   G-00001 2   56.0000 4       22    aasd      2021-06-13  2   8564312 G-00002 3   NaN     32      33    aabsd     2021-06-13  3   8564314 G-00002 4   89.0000 43      44    aabsd     2021-06-14  4   85645   G-00001 5   73.0000 55      55    aasd      2021-06-15  5   8564316 G-00002 60  NaN     610     60    aabsd     2021-06-15  6   85646   G-00001 0   NaN     0       1     aasd      2021-06-13  7   8564318 G-00002 0   NaN     0       5     aabsd     2021-06-16  8   85647   G-00001 6   NaN     16      6     aasd      2021-06-13  9   85648   G-00001 3   NaN     23      3     aasd      2021-06-13  10  85649   G-00001 2   34.0000 72      2     aasd      2021-06-13  11  85655   G-00001 4   NaN     48      4     aasd      2021-06-16  

I want to summarize some of the columns and add them back to the same datframe based on some ids in the "id1" column. Also, I want to give a new name to the "ID" column when we add that row. for example, I have some "id1" column slices.

#Based on below "id1" column ids I want to summarize only "col1","col2","col3",and "Name" columns. #Then I want to add that row back to the same dataframe and give a new id for "ID" column.   b65 = ['85643','85645', '85655','85646']  b66 = ['85643','85645','85647','85648','85649','85644']  b67 = ['8564312','8564314','8564316','8564318']  # I want to aggregate sum for col1,col2 and If possible col3 with average. Otherwise it also with sum.  # So final dataframe look like below       id1     ID     col1 Goal   col2    col3   Name      Date  0   85643   G-00001 1   NaN     3       1     aasd      2021-06-13  1   85644   G-00001 2   56.0000 4       22    aasd      2021-06-13  2   8564312 G-00002 3   NaN     32      33    aabsd     2021-06-13  3   8564314 G-00002 4   89.0000 43      44    aabsd     2021-06-14  4   85645   G-00001 5   73.0000 55      55    aasd      2021-06-15  5   8564316 G-00002 60  NaN     610     60    aabsd     2021-06-15  6   85646   G-00001 0   NaN     0       1     aasd      2021-06-13  7   8564318 G-00002 0   NaN     0       5     aabsd     2021-06-16  8   85647   G-00001 6   NaN     16      6     aasd      2021-06-13  9   85648   G-00001 3   NaN     23      3     aasd      2021-06-13  10  85649   G-00001 2   34.0000 72      2     aasd      2021-06-13  11  85655   G-00001 4   NaN     48      4     aasd      2021-06-16  12          b65     10          106     61    aasd  13          b66     17          169     67    aasd  14          b67     67          685     142   aabsd       #I was tried to do it in groupby and pandas pivot table and didn't get to work. Any suggestion would be appreciated.  Thanks in advance!  

How to remove an object from a db? [duplicate]

Posted: 20 Oct 2021 09:31 AM PDT

I tried to make a remove method of an object on a table of my databse for a wpf projet, while using C#, EF6 and XAML. I tried several different variation of it my last one. The error that VS throw me is the following one:

System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'

    private void btnSupprimer_Click(object sender, RoutedEventArgs e)              {                  var empASupprimer = ListViewEmployes.SelectedItems[0] as Employe;                        if (empASupprimer == null)                  {                      return;                  }                  else                  {                  using (var x = new ScriptBDEntity())                  {                      x.Employes.Attach(empASupprimer);                      x.Employes.Remove(empASupprimer);                                           x.SaveChanges();                      loadlistview();                      MessageBox.Show("Vous avez supprimer l'employé:" + empASupprimer);                  }           }          }  

How to make a function that creates a column with combined observations

Posted: 20 Oct 2021 09:30 AM PDT

I am obviously new to data cleaning and I am having trouble cleaning a survey export. This is how my data frame looks in raw form.

Var1          Colname1  Colname2  Colname3  Var2  Observation1  NA        NA        Val1      Val_1  Observation2  NA        Val2      NA        Val_1  Observation3  Val3      NA        NA        Val_1  Observation4  Val4      Val5      NA        Val_2  Observation5  NA        NA        Val6      Val_2  

I would like to have my data cleaned to look like this:

Var1         SubVar1 Var2  Observation1 Val1    Val_1  Observation2 Val2    Val_1  Observation3 Val3    Val_1  Observation4 Val4    Val_2  Observation4 Val5    Val_2  Observation5 Val6    Val_2  

I have tried to remove NA values:

df1 <- na.omit(c(Colname1, Colname2, Colname3))  

The problem is that it will delete all rows because there is an NA in every row. I have also tried to concatenate the values and then use the separate_rows() function, but that will only work with observations that only have one value in one column. For observations that contain values in multiple columns (see Observation4), this will not work.

Thanks for any help you guys can provide!

Sed & awk to replace string from JSON output

Posted: 20 Oct 2021 09:30 AM PDT

I am executing below command to get particular string from json output , here I am grepping with string "uri" which prints all the required fields.

# curl -X GET --insecure -H "$(cat /token/.bearer_header)" http://localhost:3000/api/search?query=% |  sed -e   's/Iq2Lbqy660Nh_RP4z9jUhPZ1CZw/''/g' | awk -v RS=',"' -F: '/^uri/ {print $2}'     % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                   Dload  Upload   Total   Spent    Left  Speed  100  2410    0  2410    0     0  40166      0 --:--:-- --:--:-- --:--:-- 40847  "ab/any-dashboard"  "ab/many-dashboard"  "ab/too-dashboard"  "ab/maximum-dashboard"  "ab/minimum-dashboard"  

now I want to replace for example "ab/any-dashboard" to only any-dashboard, which means above command should print like below

any-dashboard  many-dashboard  too-dashboard  maximum-dashboard  minimum-dashboard  

can anyone help me here I tried several things with sed but not getting exact result, and I dont have knowledge in JQ.

Regards, SAM

How to ensure that parameters have been called by name and not by position?

Posted: 20 Oct 2021 09:31 AM PDT

I'm maintaining a package centered on a single function with a few mandatory parameters, along with a lot of optional parameters.

As my function matures, the order of optional parameters is changing, and therefore calling them by order will lead to breaking changes.

I would like to throw a warning/error (not sure what is best) if these latter parameters are called by position rather than by name.

Here is some pseudo-code with expected output:

crosstable = function(data, cols=NULL, ..., by=NULL, opt1=FALSE, opt2=FALSE, opt3=FALSE){      warn_if_unnamed(by)      stop_if_unnamed(opt1)      stop_if_unnamed(opt2)      stop_if_unnamed(opt3)      doStuff(data, cols, by, opt1, opt2, opt3)  }  crosstable(mtcars, c(cyl, am), by=vs, opt3=TRUE) #OK  crosstable(mtcars, c(cyl, am), by=vs, TRUE)      #error as `opt1` might become `opt56` in the future  crosstable(mtcars, c(cyl, am), vs, opt2=TRUE)    #warning (?) as `by` will not move but it would be clearer  

How can I achieve this?

EDIT:

Thanks to @user2554330 and to some other SO post (here), I finally got it working, although it won't work if used with a pipe:

warn_if_unnamed <- function(argname){      .call = sys.call(-1)      f = get(as.character(.call[[1]]), mode="function", sys.frame(-2))      mc = names(as.list(match.call(definition=f, call=.call))) #https://stackoverflow.com/a/17257053/3888000      sc = names(as.list(.call))      if(argname %in% mc && !argname %in% sc){          warning(argname," is referenced by position, not name")      }  }  myfun = function(x, y=NULL, opt1=FALSE, opt2=FALSE, opt3=FALSE){      warn_if_unnamed("opt1")      warn_if_unnamed("opt2")      warn_if_unnamed("opt3")      invisible()  }  myfun(1, 2)  myfun(1, 2, T, opt2=1)  #> Warning in warn_if_unnamed("opt1"): opt1 is referenced by position, not name  myfun(1, 2, opt1=T, 1, opt3)  #> Warning in warn_if_unnamed("opt2"): opt2 is referenced by position, not name  #> Warning in warn_if_unnamed("opt3"): opt3 is referenced by position, not name  myfun(1, 2, opt2=T, 1, opt3)  #> Warning in warn_if_unnamed("opt1"): opt1 is referenced by position, not name  #> Warning in warn_if_unnamed("opt1"): opt3 is referenced by position, not name  

Created on 2021-10-20 by the reprex package (v2.0.1)

I'll probably make some refactoring to gather the warnings into a single one though.

PS: The last line looks like a bug in reprex().

Perl remove same value back to back with splice

Posted: 20 Oct 2021 09:31 AM PDT

I am trying to remove, the same values twice in an array, it is located back to back, this is my code

@{$tmp_h->{'a'}} = qw/A B B C/;    print Dumper ($tmp_h);    my $j = 0;  foreach my $cur (@{$tmp_h->{'a'}}) {    if ($cur eq 'B') {      splice(@{$tmp_h->{'a'}}, $j, 1);    }      $j++;  }    print Dumper $tmp_h;  

However what got is,

$VAR1 = {            'a' => [                     'A',                     'B',                     'B',                     'C'                   ]          };  $VAR1 = {            'a' => [                     'A',                     'B',                     'C'                   ]          };  

I am expecting both 'B' to be removed in this case, what could possibly went wrong?

How to import a csv with multiple data into different dataframes?

Posted: 20 Oct 2021 09:30 AM PDT

Here is the csv that i have as an input:

enter image description here

I would like to create 3 dataframes for each variable: BEL AIR - feeder_30 - MANGUIER, BEL_TC_30_TR3_MW and BEL AIR - feeder_30 - MTOA. It will have Date value as an index and Valeur as values.

I tried this :

data_adms = pd.read_csv(full_path,sep=';',index_col=False, header=6)  

But it gets rid of the name of nom du point distant. And the timestamp is not the same between rows.

Does somebody have an idea how can I properly proceed?

Calculate the (average) time a product is in stock

Posted: 20 Oct 2021 09:31 AM PDT

I'm trying to calculate the time a product is in our stockroom. I accomplished sofar a calculation of the amount of days between the 'restocked_date' and the 'shipment_date'.

This looks fine. I used the following code:

tijd in magazijn = IF( OR(voorraad[restocked_date] <= voorraad[shipment_date], voorraad[shipment_date] > 2021-06-30), DATEDIFF(voorraad[restocked_date], voorraad[shipment_date], DAY), DATEDIFF(voorraad[restocked_date], TODAY(),DAY))  

Now I want this to be the average. Which I also accomplished by using this code:

Gemiddelde in magazijn per EAN = AVERAGEX( KEEPFILTERS(VALUES('voorraad'[EAN])), CALCULATE(AVERAGE('voorraad'[tijd in magazijn])))  

The part that's making this difficult for me, is:
I want the average just to be calculated over the items which have a 'restocked_date' of 1 july 2021 or later. So in the example there should be an average of 40 (rounded from 39,5) instead of 26.

spreadsheet showing all input

When I get rid of all the specifics in a row, my average comes up with this so far:

the average with only EAN in the table

This is the result when using the solution given by Ryan B. Unfortunately not what I'm looking for.

The outcome with the solution from Ryan B.

Android Studio: Could not compile settings file

Posted: 20 Oct 2021 09:31 AM PDT

I`m trying to open project on reinstalled Android studio and get this error. When trying make a new project also get this error.

FAILURE: Build failed with an exception.    * Where:  Settings file 'C:\Users\STES\AndroidStudioProjects\TuBelleza\settings.gradle'    * What went wrong:  Could not compile settings file 'C:\Users\STES\AndroidStudioProjects\TuBelleza\settings.gradle'.  > startup failed:    General error during semantic analysis: Unsupported class file major version 60        java.lang.IllegalArgumentException: Unsupported class file major version 60      at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:196)      at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:177)      at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:163)      at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:284)      at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)      at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)      at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)      at java.base/java.lang.Thread.run(Thread.java:831)  

How do I enable cloning over SSH for a Gitlab runner?

Posted: 20 Oct 2021 09:30 AM PDT

I am having some trouble cloning large repositories over HTTP on my Windows Gitlab runner. I've tried several methods to do shallow clones or disable clone compression. Still no luck.

Cloning the same repository over SSH works great as a temporary solution and I would like to get this working on our Gitlab CI process.

The issue now stands where I have no idea how to use SSH as a clone method for the gitlab-multi-runner. It just seems to use HTTP as a default, and my only options regarding cloning is whether it will do a full clone or a fetch.

CI/CD Display

Can someone explain how I could get that clone/fetch to work on a runner over SSH instead of HTTP?

Gitlab Version: GitLab Community Edition 8.10.7

Thanks!

StyleCop.Analyzers: Disable SA1633 & SA1652

Posted: 20 Oct 2021 09:30 AM PDT

I have already consulted the configuration documentation, but couldn't find anything.

I want to disable both of the following rules:

SA1633: The file header is missing or not located at the top of the file.  SA1652: Enable XML documentation output.  

My stylecop.json looks like this:

{    "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",    "settings": {      "orderingRules": {        "usingDirectivesPlacement": "outsideNamespace"      }    }  }  

Any ideas?

How to get Google-glog output in console?

Posted: 20 Oct 2021 09:31 AM PDT

I am using a framework for convolutional neural networks called caffe and its output in console is provided by Google-glog. However when I try to save the output to a file using the following commands:

sh train_imagenet.sh | tee output.txt  

or

sh train_imagenet.sh > output.txt  

And I get a void file and the output does not save to the file. So I want to know how to retrieve this output. Thanks in advance.

How do I import CSV file into a MySQL table?

Posted: 20 Oct 2021 09:31 AM PDT

I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

CREATE TABLE 'CSVImport' (id INT);  ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);  ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);  ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);  ...  ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);  ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);  

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;  Query OK, 2023 rows affected, 65535 warnings (0.08 sec)  Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256  SELECT * FROM CSVImport;  | NULL             | NULL        | NULL           | NULL | NULL               |   ...  

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

LOAD DATA INFILE "/home/paul/clientdata.csv"  INTO TABLE CSVImport  COLUMNS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '"'  ESCAPED BY '"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;  

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.

No comments:

Post a Comment