Tuesday, April 19, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to do class balancing with Pandas?

Posted: 19 Apr 2022 02:57 AM PDT

I have 2 classes, 0 and 1. I have a csv file with header "sentence,label". The problem is that my dataset is not balanced at all. It has 1000 1's and 9000 0's. I would like to have almost the same number of rows with each class. Is there any way in Pandas that does that? For example, one of the ways would be to copy each row of label 1 multiple times, but I do not know how. I would like to have a most possible balanced dataframe at the end.

Script. Delete temp mozilla firefox

Posted: 19 Apr 2022 02:57 AM PDT

The point is that I have to create a script for my school that deletes all the temporary ones from Mozilla Firefox, with a batch script in Windows 10. The most complex thing about this is that the mozilla path has a folder that has a different "Prefix" on each computer, in my case it is wvbrz602.default-release. (Ruta completa sería: C:\Users\dmarmol\AppData\Local\Mozilla\Firefox\Profiles\wvbrz602.default-release)

What I have done has been a loop that iterates for each user and stores it in the variable in which it iterates "%%a" In this way I obtain each user, once each user is obtained, I do a dir obtaining the prefix of the containing folder of the Firefox profile of each user in a .txt document (Since the prefix is ​​different for each user) After that prefix obtained in the .txt of each user I add it to a variable (The problem is that, apparently they don't like it) And finally I make a del of the temporary of each user.

This is my code:

*@ECHO on

SETLOCAL EnableDelayedExpansion

rem TASKKILL /F /IM mozilla.exe /T

for /f %%a in ('dir c:\Users /b') do>%%a.txt (

dir /b "C:\Users%%a\AppData\Local\Mozilla\Firefox\Profiles*.default-release"

set /p contenedorFor=<"%%a".txt

del C:\Users%%a\AppData\Local\Mozilla\Firefox\Profiles%contenedorFor%\cache2

) exit /b 0*

I show a snapshot of the exit the code. https://i.stack.imgur.com/Lfe2p.png

I hope can find the solution with they help. :)

Regards.

React multicheckbox how can I set defaultCheck?

Posted: 19 Apr 2022 02:57 AM PDT

I have a from 2 steps. Second step is about options about car. I have multi checkboxes. When I changed to page to first and then again second, I want to see checked which I choosed firstly. When I click to back button I saved array of checkboxes to localStorage. I used useEffect to get them, and then I used it for defaultCheck. It is working. When I add new option, it is working, updating array. NO. when I want to remove defaultChecked, array is not updating. Could you help me about it?

 useEffect(() => {      const storedOptions = JSON.parse(localStorage.getItem("carOptions"));      if (storedOptions) {        setSelectedOptions(storedOptions.options);       }    }, []);      const onChangeHandler = (e) => {        const isChecked = e.target.checked;          if (isChecked) {        setSelectedOptions((oldArray) => [...oldArray, e.target.value]);      } else {        setSelectedOptions((prevState) =>          prevState.filter((prevItem) => prevItem !== e.target.value)        );      }    };  

How do automatically measure memory consumption during the tests in VisualStudio?

Posted: 19 Apr 2022 02:56 AM PDT

I have a lot of tests based on the Google Test framework. All tests were built in Release mode, and when I manually run the separate test under the "Visual Studio" on "Diagnostic Tool Window" (Ctrl+Alt+F2) in the "Process Memory" chart I can see the maximum heap memory consumption. Is there exist way, to log memory consumption automatically for each running test? All I need to know is the maximum amount of memory that each test used during the execution.

Send email when Appwrite database gets update

Posted: 19 Apr 2022 02:56 AM PDT

How to trigger notification on Appwrite when a record is added to my database? The same function exists in Firebase, but in the paied plan .

I don't know how to fix it ;/

Posted: 19 Apr 2022 02:56 AM PDT

let target; (!args[0]) ? (target = message.member) : (target = message.mentions.members.first() || message.guild.members.cache.get(args[0]))

if (!target) { const uzy = await message.guild.members.fetch({ query: ${args[0]}, limit: 1 }) target = uzy }

console.log(target.user.tag)

Cannot read properties of undefined (reading 'tag')

Search through laravel relationship with filtered date

Posted: 19 Apr 2022 02:56 AM PDT

i search data 1 (this exist in database) within date range of 13-04-2022 to 14-04-2022 (there is no data in this date range). From this query that i used on my controller still return the data that contains a keyword that i search for (data 1). What i wanted is to return collection of data with the range of the date filter (which is nothing since i dont have any data from that date range). How to solve this problem? is there any best practices that i could implement for this search within the filtered date? this is my back-end :

$rekans = Rekan::query()                      ->join('dokters','dokters.id','=','rekans.dokter_id')                      ->join('pasiens','pasiens.id','=','rekans.pasien_id')                      ->join('penyakits','penyakits.id','=','rekans.dokter_id')                      ->join('treatments','treatments.id','=','rekans.treatment_id');        if(request('from_date')){          $rekans->whereDate('rekans.created_at','>=',request('from_date'));      }      if(request('to_date')){          $rekans->whereDate('rekans.created_at','<=',request('to_date'));      }      if(request('search')){          $rekans->where('berat','LIKE','%'.request('search').'%')              ->orWhere('rekan_inv','LIKE','%'.request('search').'%')              ->orWhere('suhu','LIKE','%'.request('search').'%')              ->orWhere('hasil_pemeriksaan','LIKE','%'.request('search').'%')              ->orWhere('anamnesa','LIKE','%'.request('search').'%')              ->orWhere('pengobatan','LIKE','%'.request('search').'%')              ->orWhere('kasus','LIKE','%'.request('search').'%')              ->orWhere('dokters.nama_dokter','LIKE','%'.request('search').'%')              ->orWhere('pasiens.nama','LIKE','%'.request('search').'%')              ->orWhere('penyakits.nama_penyakit','LIKE','%'.request('search').'%')              ->orWhere('treatments.nama_treatment','LIKE','%'.request('search').'%');      }  

this is my sql

select * from `rekans` inner join `dokters` on `dokters`.`id` = `rekans`.`dokter_id` inner join `pasiens` on `pasiens`.`id` = `rekans`.`pasien_id` inner join `penyakits` on `penyakits`.`id` = `rekans`.`dokter_id` inner join `treatments` on `treatments`.`id` = `rekans`.`treatment_id` where date(`rekans`.`created_at`) >= ? and date(`rekans`.`created_at`) <= ? and `berat` LIKE ? or `rekan_inv` LIKE ? or `suhu` LIKE ? or `hasil_pemeriksaan` LIKE ? or `anamnesa` LIKE ? or `pengobatan` LIKE ? or `kasus` LIKE ? or `dokters`.`nama_dokter` LIKE ? or `pasiens`.`nama` LIKE ? or `penyakits`.`nama_penyakit` LIKE ? or `treatments`.`nama_treatment` LIKE ? order by `rekans`.`created_at` desc  

Refresh token is working, but showing error message- React Native

Posted: 19 Apr 2022 02:56 AM PDT

I am struggling to find out the issue with my refresh token mechanism. I have a some problem that I can't fix. Refresh token is working, but it showing an alert 'somthingWentWrong' but the application is still in a good state and working properly.

Here is my code, please tell me where is my mistake?

import axios from 'axios';  import config from './env';  import { Alert } from 'react-native';  import { Constants, storeData } from '@utils';  import { store } from '@data/store';  import { t } from 'i18next';        enum StatusCode {  BadRequest = 400,  Unauthorized = 401,  Fobbiden = 403,  NotFound = 404,  NotAllowed = 405,  Conflict = 409,  ServerError = 500,  

}

const getErrorMessage = (error: any): string => {  if (error?.request?.responseURL?.includes('Authentication/signin') && error?.request === StatusCode.Fobbiden) {      return t('invalidEmailOrPassword');  } else if (error?.response?.data) {      return error.response.data;  } else if (error?.response?.data?.length) {      return error.response.data;  } else {      return t('somethingWentWrong');  }  

};

export const createAxios = () => {  const baseURL = config.apiUrl;  const token = store.getState()?.auth?.token;  const refreshToken = store.getState()?.auth?.refreshToken;  let headers: any = { 'Content-Type': 'application/json' };  if (token) {      headers = { ...headers, Authorization: `Bearer ${token}` };  }  const instance = axios.create({ baseURL, headers });    instance.interceptors.response.use(      (res) => Promise.resolve(res.data),      async (error) => {          if (error?.request?.status === StatusCode.Unauthorized) {              try {                  const body = { token: token, refreshToken: refreshToken };                  const _instance = axios.create({ baseURL: config.apiUrl, headers: headers });                  const tokenResponse = await _instance.post(config.token_url, body);                  if (tokenResponse) {                      await store.dispatch({ type: '[AUTH] SET_TOKEN', payload: tokenResponse?.data?.accessToken });                      await store.dispatch({ type: '[AUTH] SET_REFRESH_TOKEN', payload: tokenResponse?.data?.refreshToken });                      await storeData(Constants.asyncKeys.AUTH_TOKEN, tokenResponse?.data?.accessToken);                      await storeData(Constants.asyncKeys.REFRESH_TOKEN, tokenResponse?.data?.refreshToken);                      headers.Authorization = 'Bearer ' + tokenResponse?.data?.accessToken;                      error.config.headers.Authorization = 'Bearer ' + tokenResponse?.data?.accessToken;                      const failedResponse = await axios.request(error.config);                      if (failedResponse) {                          return failedResponse.data;                      }                  }                  // eslint-disable-next-line no-shadow              } catch (error: any) {                  error.request.status && Alert.alert(t('error'), getErrorMessage(error));              }                return Promise.reject(error?.response);          }          return Promise.reject(error?.response);      },  );    return instance;  

};

Redis multi Key or multi Hash field

Posted: 19 Apr 2022 02:56 AM PDT

i have about 300k row data like this Session:Hist:[account]

Session:Hist:100000

Session:Hist:100001

Session:Hist:100002

.....

Each have 5-10 childs [session]:[time]

b31c2a43-e61b-493a-b8d4-ff0729fe89de:1846971068807

5552daa2-c9f6-4635-8a7c-6f027b4aa1a3:1846971065461

.....

I have 2 options:

  1. Using Hash, key is Session:Hist:[account], field is [session], value is [time]
  2. Using Hash flat all account, key is Session:Hist, field is [account]:[session], value is [time]

My Redis have 1 master, 4-5 Slave, so the question is which options is better for performance, thanks for your help!

Is it possible to somehow define create_thread in PyCord

Posted: 19 Apr 2022 02:56 AM PDT

Hello I encountered the error 'Message' object has no attribute 'create_thread' Code:

@commands.command()  async def sugesstion(self, ctx, *,sugestia):      await ctx.message.delete()      embed = discord.Embed(colour = 0xFFA500)       embed.set_author(name=f' {ctx.message.author}', icon_url = f'{ctx.author.avatar_url}')      embed.add_field(name = 'Member,', value = f'{sugestia}')       embed.set_footer(text="Apples")          msg = await ctx.send(embed=embed)       await msg.add_reaction('✔️')       await msg.add_reaction('➖')            await msg.create_thread(name="Comments", auto_archive_duration=MAX)  

Undefined reference errors in Qt Creator | OpenCV

Posted: 19 Apr 2022 02:56 AM PDT

I linked OpenCV to Qt Creator with the help of this guide. However while compiling a simple code to read and display the image, I am getting undefined reference errors.

test.pro

QT       += core gui    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets    CONFIG += c++11    TARGET = opencvtest  TEMPLATE = app  # You can make your code fail to compile if it uses deprecated APIs.  # In order to do so, uncomment the following line.  DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0    SOURCES += \      main.cpp \      mainwindow.cpp    HEADERS += \      mainwindow.h    FORMS += \      mainwindow.ui    INCLUDEPATH += D:\opencv\build\include    LIBS += D:\opencv-build\bin\libopencv_core320.dll  LIBS += D:\opencv-build\bin\libopencv_highgui320.dll  LIBS += D:\opencv-build\bin\libopencv_imgcodecs320.dll  LIBS += D:\opencv-build\bin\libopencv_imgproc320.dll  LIBS += D:\opencv-build\bin\libopencv_features2d320.dll  LIBS += D:\opencv-build\bin\libopencv_calib3d320.dll      # Default rules for deployment.  qnx: target.path = /tmp/$${TARGET}/bin  else: unix:!android: target.path = /opt/$${TARGET}/bin  !isEmpty(target.path): INSTALLS += target  

mainwindow.cpp

#include "mainwindow.h"  #include "ui_mainwindow.h"  #include <opencv2/core/core.hpp>  #include <opencv2/highgui/highgui.hpp>  MainWindow::MainWindow(QWidget *parent)      : QMainWindow(parent)      , ui(new Ui::MainWindow)  {      ui->setupUi(this);      cv::Mat image = cv::imread("img101.jpg", 1);         cv::namedWindow("My Image");         cv::imshow("My Image", image);  }    MainWindow::~MainWindow()  {      delete ui;  }    

main.cpp

#include "mainwindow.h"    #include <QApplication>    int main(int argc, char *argv[])  {      QApplication a(argc, argv);      MainWindow w;      w.show();      return a.exec();  }    

These are the errors I am getting while building the file. Using Windows 10, MinGW 7.3.0 32-bit C and C++ compiler.

React - Module not found, For packages inside the installed packages, when requirting express

Posted: 19 Apr 2022 02:56 AM PDT

Hello I tried to install the express package in a react project But when I import the package inside the app.js using:

const app = require("express");  

I get 30 errors all saying

Module not found Error: Can't resolve 'x'  

where x are differnt packages like zlib, querystring, path, crypto, fs, stream ....

This is the app.js code when I run it without the require line it works fine

import logo from './logo.svg';  import './App.css';  const app = require("express");    function App() {    return (      <div className="App">        <header className="App-header">          <img src={logo} className="App-logo" alt="logo" />          <p>            Edit <code>src/App.js</code> and save to reload.          </p>          <a            className="App-link"            href="https://reactjs.org"            target="_blank"            rel="noopener noreferrer"          >            Learn React          </a>        </header>      </div>    );  }    export default App;  

And inside my package.json file in my dependencies I do have: "express": "^4.17.3"

I even tried to create a new blank project for this and I had the same problem

Use CSS filter: invert(1) to show black image on white background

Posted: 19 Apr 2022 02:57 AM PDT

I have a circle graphics to span across half black & half white background color generated by CSS. I would like to have the effects that the colors in the area of the circle covered turns white to black, and turns black to white (invert the color). The effects should look like this:

enter image description here

However, the white background color side is incorrect right now. How can I modify the codes in order to make the white area covered by the circle turns black?

p.s. in the real scenario, the circle will be replaced by a complex shape.

Here is the snippet:

.bg {    background-image: linear-gradient(90deg, black 50%, white 50%);  }    svg {    filter: invert(1);  }
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />    <div class="container-fluid">    <div class="row">      <div class="col-12 bg bg-white">        <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%">    <circle cx="50" cy="50" r="30" fill="black" />  </svg>      </div>    </div>  </div>

How i can positioning the placeholder in the dropdown MultiSelect input (photo below)

Posted: 19 Apr 2022 02:57 AM PDT

Figma drop down multiselect design

return (      <div className="drop-down-container" ref={ref}>          {label && labelText}          <div className="drop-down">              <input                  type="text"                  className="drop-down-input"                  placeholder={placeholder}                  onChange={handleSearch}                  onClick={() => setShowDropDown(!showDropDown)}              />              <img src={arrow} alt=""/>              {selectedItems.length > 0 && (                  <div className="selected-container">                      {selectedItems.map((item, index) => (                          <div key={index} className="selected-item">                              <p>{item.text}</p>                              <img                                  src={close}                                  className="close-icon"                                  onClick={() => onSelectItem(item)}                              />                          </div>                      ))}                  </div>              )}          </div>          {showDropDown && (              <ul className="drop-down-items">                  {optionList}              </ul>          )}      </div>  );  

above jsx layout code react, thanks for any ideas It is possible to change the position depending on the number of selected items

What actually is int in int main void in c?

Posted: 19 Apr 2022 02:57 AM PDT

#include<stdio.h>  #include<conio.h>    int main(){      printf("hello world");  }  

What actually does int do to the main function? Is it similar to the data type int? What does conio.h do?

Determining types of memory used by Spring Boot application causing an OOM kill

Posted: 19 Apr 2022 02:57 AM PDT

I have a container running on Kubernetes with a Spring Boot application. The code configures a few REST controllers and saves some data to an H2 file through JPA. I'd say the main dependencies here are:

  • spring-boot-starter-jersey:2.6.6
  • spring-boot-starter-data-jpa:2.6.6

When monitoring memory utilization, I can see that it is increasing very slowly and eventually causes an OOM kill. Some relevant configuration of the container/JVM:

  • Container's requests and limits for memory: 400Mi
  • JDK 17.0.2
  • -Xms134217728
  • -Xmx134217728
  • -XX:MaxDirectMemorySize=16m
  • -XX:MaxMetaspaceSize=128m
  • -XX:MinMetaspaceFreeRatio=10

I extracted some Prometheus metrics when the container first started:

jvm_memory_committed_bytes{area="heap",id="Tenured Gen",} 8.9522176E7  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'profiled nmethods'",} 1.7891328E7  jvm_memory_committed_bytes{area="heap",id="Eden Space",} 3.5782656E7  jvm_memory_committed_bytes{area="nonheap",id="Metaspace",} 1.08003328E8  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'non-nmethods'",} 2555904.0  jvm_memory_committed_bytes{area="heap",id="Survivor Space",} 4456448.0  jvm_memory_committed_bytes{area="nonheap",id="Compressed Class Space",} 1.4614528E7  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'non-profiled nmethods'",} 4784128.0  

And also after the container had been running for about a week:

jvm_memory_committed_bytes{area="heap",id="Tenured Gen",} 8.9522176E7  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'profiled nmethods'",} 3.3554432E7  jvm_memory_committed_bytes{area="heap",id="Eden Space",} 3.5782656E7  jvm_memory_committed_bytes{area="nonheap",id="Metaspace",} 1.15933184E8  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'non-nmethods'",} 2555904.0  jvm_memory_committed_bytes{area="heap",id="Survivor Space",} 4456448.0  jvm_memory_committed_bytes{area="nonheap",id="Compressed Class Space",} 1.4680064E7  jvm_memory_committed_bytes{area="nonheap",id="CodeHeap 'non-profiled nmethods'",} 2.2544384E7    jvm_buffer_memory_used_bytes{id="mapped - 'non-volatile memory'",} 0.0  jvm_buffer_memory_used_bytes{id="mapped",} 0.0  jvm_buffer_memory_used_bytes{id="direct",} 185594.0  

From these, it seems to me that there's no leak in the memory managed by the JVM. I also checked /sys/fs/cgroup/memory/memory.stat inside the container when it was near the limit:

cache 3649536  rss 411545600  rss_huge 0  mapped_file 249856  swap 0  pgpgin 67578153  pgpgout 67476787  pgfault 242802886  pgmajfault 15  inactive_anon 32768  active_anon 411631616  inactive_file 2465792  active_file 1044480  unevictable 0  hierarchical_memory_limit 419430400  hierarchical_memsw_limit 9223372036854771712  total_cache 3649536  total_rss 411545600  total_rss_huge 0  total_mapped_file 249856  total_swap 0  total_pgpgin 0  total_pgpgout 0  total_pgfault 0  total_pgmajfault 0  total_inactive_anon 32768  total_active_anon 411631616  total_inactive_file 2465792  total_active_file 1044480  total_unevictable 0  

I can only guess that something is using native memory in the JVM (no other process is running inside the container), but is there any way I can determine if this is the case?

Laravel exception while checking if a collection is empty

Posted: 19 Apr 2022 02:56 AM PDT

In my laravel application I'm trying to check if a collection is empty.

if($companies->isNotEmpty())          {              $getAuthUser_CompanyId = $companies->first()->id;                $employeeID_ExistsCompany= CompanyUser::whereExists(function ($query) use ($getAuthUser_CompanyId,$employee_Id) {                  $query->select(DB::raw(1))                      ->from('users')                      ->where('company_user.user_id', '=',$employee_Id)                      ->where('company_id', '=', $getAuthUser_CompanyId);              })              ->get();                if(!$employeeID_ExistsCompany)              abort(403);          }  

I am using laravel's collect([])->isNotEmpty(); to check that.

But when I try to run this, it gives me following exception...

message: "Undefined array key 0"

How can I check if this collection is not empty? I'm using laravel 9

Update

My companies collection looks like this

Illuminate\Database\Eloquent\Collection {#2770    #items: array:1 [      0 => App\Company {#2778        #connection: "mysql"        #table: "companies"        #primaryKey: "id"        #keyType: "int"        +incrementing: true        #with: []        #withCount: []        +preventsLazyLoading: false        #perPage: 15        +exists: true        +wasRecentlyCreated: false        #escapeWhenCastingToString: false        #attributes: array:25 [          "id" => 635          "uuid" => "283c18b514"          "name" => "apple"          "email" => "ceo@apple.co"          "phone_number" => "6149297830"          "website" => "https://www.apple.co"          "country_id" => 232          "state" => "California"          "postal_code" => ""          "house_number" => ""          "street" => ""          "city" => "Menlo Park"          "chamber_of_commerce" => null          "vat_number" => null          "lat" => 37.4529598          ....  

C# Foreach Usage

Posted: 19 Apr 2022 02:56 AM PDT

I want to use 2 variables and iterate over different objects with a single line foreach, If I wanted to do it with python I could use as follows.

<div>          @(for firstSong, secondSong Model.Web.OrderBy(p=>p.ListOrder()) )          {          <div class="item">             <div class="row">                firstSong.Name             </div>             <div class="row2">                secondSong.Name             </div>          </div>          }          </div>        <div>  

but I want to do the same thing with c#, how can I do it?

@foreach(var song in Model.Web.OrderBy(p=>p.ListOrder())  {  <div class="item">     <div class="row">        song.Name     </div>     <div class="row2">        song.Name     </div>  </div>  }  </div>  

How to load an external font in p5js?

Posted: 19 Apr 2022 02:56 AM PDT

I tried changing the font in P5.js to a Minecraft font, like in the reference with loadFont(). The font file 'MinecraftRegular-Bmg3.otf' is in the same folder as Index.html and sketch.js.

My code:

let minecraft;  function preload() {  minecraft = loadFont('MinecraftRegular-Bmg3.otf');  }    function setup() {  createCanvas(windowWidth, windowHeight);  }    function draw() {  background(44, 47, 51);  text("Test", 50, 50);  }    function windowResized() {  resizeCanvas(windowWidth, windowHeight);  }  

Now the problem, when I'm trying to load Index.html, it's just showing "Loading..." and in the console it's printing out three error messages:

Access to XMLHttpRequest at 'file:///C:/Users/User/Desktop/p5jsProjects/test/MinecraftRegular-Bmg3.otf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

Font could not be loaded ./MinecraftRegular-Bmg3.otf

GET file:///C:/Users/User/Desktop/p5jsProjects/test/MinecraftRegular Bmg3.otf net::ERR_FAILED

Does anyone have an idea how to fix this, or how I can load a font differently?

Edit: I don't want to make my own web server or something, because the code is on my own pc. And I think I will have to start the web server when ever I start my pc, to just visit my website.

Also, I tried uploading the font file to google drive and then using the download link in 'loadFont()'. Then the console is saying, that:

No 'Access-Control-Allow-Origin' header is present on the requested resource.  

Problem : Delete PVC (Persistent Volume Claim) Kubernetes Status Terminating

Posted: 19 Apr 2022 02:57 AM PDT

Basically, I have a problem deleting my spoc-volume-spoc-ihm-kube-test PVC I tried with:

kubectl delete -f file.yml  kubectl delete PVC  

but I get every time the same Terminating Status. Also, when I delete the PVC the console is stuck in the deleting process.

Capacity: 10Gi Storage Class: rook-cephfs Access Modes: RWX

Here is the status in my terminal:

kubectl get pvc NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE spoc-volume-spoc-ihm-kube-test Terminating pvc-- 10Gi RWX rook-cephfs 3d19h

Thank You for your answers, Stack Community :)

How to create a dropdown menu with sections? [duplicate]

Posted: 19 Apr 2022 02:56 AM PDT

I'm trying to create something like below, what's the best way to create those sections inside dropdown with Flutter?

enter image description here

CdpVersionFinder findNearestMatch WARNING: Unable to find an exact match for CDP version 100, so returning the closest version found: 99 with Selenium

Posted: 19 Apr 2022 02:57 AM PDT

I created a bunch of scripts which worked fine in December 2021. I'm running them now and a few of them execute and pass but suddenly the execution stops and it shows the scripts are failed and skipped as follows:

test_Footer__BrokenImage is PASSED    Starting ChromeDriver 100.0.4896.60 (6a5d10861ce8de5fce22564658033b43cb7de047-refs/branch-heads/4896@{#875}) on port 62727  Only local connections are allowed.  Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.  ChromeDriver was started successfully.  Apr 19, 2022 12:03:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession  INFO: Detected dialect: W3C  Apr 19, 2022 12:03:45 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  WARNING: Unable to find an exact match for CDP version 100, so returning the closest version found: 99  Apr 19, 2022 12:03:45 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  INFO: Found CDP implementation for version 100 of 99  test__BrokenImage is FAILED  

Maven dependency:

<dependency>      <groupId>org.seleniumhq.selenium</groupId>      <artifactId>selenium-java</artifactId>      <version>4.1.3</version>  </dependency>  

My chrome version is 100.0.4896.127 Chrome driver version is 100.0.4896.60

Appreciate if anyone could help.

Use dropdown selection in URL

Posted: 19 Apr 2022 02:57 AM PDT

I'm following the answer here to use the selection from a dropdown in a URL. I am using asp.net core, using:

asp-page="/Page" asp-page-handler="Action"  

To do the redirect

The script below (from the link above) works great, except if you select an item from the dropdown then select a different one (and on and on), it appends both to the URL.

<script>  $("[name=selectedAnalyst]").on("change", function () {      var analystId = $(this).val();      var accept = $(this).closest('td').next().find("a")[0];      var oldUrl = accept.href;      var newUrl = oldUrl + "&analystid=" + analystId;      $(accept).attr("href", newUrl);  })  

I tried scrubbing the parameter in question (using params.delete) but it's not working:

<script>  $("[name=selectedAnalyst]").on("change", function () {      var analystId = $(this).val();      var accept = $(this).closest('td').next().find("a")[0];      var oldUrl = accept.href;      let params = new URLSearchParams(oldUrl.search);        params.delete('analystid')      var newUrl = oldUrl + "&analystid=" + analystId;        $(accept).attr("href", newUrl);  })  

Is there a way to get the above script to work how I envision, or a better way to do this?

Thank you

Sending push notification to windows 10 systems

Posted: 19 Apr 2022 02:56 AM PDT

i want when a certain logic is met on a server for it to send toast notifications to multiple workstations on a closed lan using python.

I am able to easily generate toast notifications on a system locally using win10toast but i want to able to send the notification over a local network to another system.

So from what i have understood, i have to use wns, i did find python-wns but it is really light on explanation, if there is a good write up of how to use it that would be excellent. is there another package better suited for this.

my other idea which for some reason seems really dumb but might work is, on all the workstations have them check a file on the server constantly as soon as the file gets populated, just do a local toast.(i am not sure why this is dumb but feels like it)

How to automate outlook with python [closed]

Posted: 19 Apr 2022 02:56 AM PDT

I need to respond to an approval email which sent from power automate approval action.

Any advice.

Regex to match emojis that can be validly combined with skin tone modifiers?

Posted: 19 Apr 2022 02:56 AM PDT

The JS code to detect emojis (in the usual sense of the term "emoji") is simply:

let str = "...";  if(/\p{Extended_Pictographic}/u.test(str)) {    // do something  }  

Is there some equivalently simple way to detect emojis that can have skin tone modifiers validly added to them?

A key requirement is that I don't have to update the regex over the years as more emojis are added, or existing emojis become skin-tone-able. Basically I'm wondering if there's something like a Skin Unicode property escape, or some other elegant and future-proof solution.


Notes:

  • It must work without DOM access (i.e. server-side, workers, etc.).
  • Note that the goal is not to detect skin tone modifiers, but to detect emojis that can validly have a skin tone modifier added to it - e.g. the regex/function should match 👶 (doesn't have skin tone modifier, but it is valid to add one to it).
  • I want to emphasise that a big-old-bunch-of-unicode-ranges regex that's not future-proof does not fit the requirements of my particular use case. But not that a bunch of Unicode ranges is if it's future proof.
  • This question appears to be similar when considering the title, but upon reading the body of the question, it's asking a different question.

How to disable clicks on DotView?

Posted: 19 Apr 2022 02:56 AM PDT

I am using a custom view from here. I want to disable user interactions with the view pager 2 using this:

binding.viewPager2.setUserInputEnabled(false);  

But, it moves when I click on a dot of that view. I tried to disable that using this:

binding.dotsView.setEnabled(false);  

But, that does not seem to work.

Then how can we disable clicks on it?

Multiple records update validation with the entire data set

Posted: 19 Apr 2022 02:57 AM PDT

Currently, I have an endpoint that allows the update of multiple records. Before saving the changes to the database I need to validate the data that is being sent from the front end.

I am having an issue with some kinds of validations that require checks against all the other records in the database table. (Ex: ate intervals overlaps/gaps, unique pairs checks).

In these cases when I try to do the validations I have two sets of data

  1. The data sent from the front end that are stored in memory/variable.
  2. The data on the database.

For the validations to be run correctly I need a way to merge the data in memory(the updated records) with the data in a database(original records + other data that is not currently being updated).

Is there a good way of doing this that does not require loading everything on the memory and merging both datasets there?

Another idea I am thinking of is to open a database transaction set the new data to the database and then when executing the gaps/overlap check queries use dirty read. I don't know if this is a good approach though.

Extra notes:
I am using Oracle as a database and Dapper to communicate with it. The tables that need validation usually hold millions of records. The same issue is for the create endpoint.

Another example
I am trying to create entities. The create endpoint is called and it has these data on the body (date format dd/mm/yyy): | StartDate | EndDate | | -------- | -------------- | | 01/01/2022| 05/01/2022 | | 10/01/2022| 11/01/2022 | | 12/01/2022| 15/01/2022 |

In database I have these records saved: |Id| StartDate | EndDate | |-| -------- | -------------- | |1| 06/01/2022| 09/01/2022 | |2| 16/01/2022| 20/01/2022 |

I need to check if there are any gaps between the dates. If there are I need to send a warning to the user(data in the database can be invalid - the application has old data and I can't do anything about that at the moment).

The way I check for this right now is like by using the SQL below

WITH CTE_INNERDATA AS(      SELECT s.STARTDATE, s.ENDDATE        FROM mytable s      WHERE FK = somefkvalue      UNION ALL       SELECT :StartDt AS STARTDATE, :EndDt AS ENDDATE FROM DUAL -- this row contains the data from one of the rows that came form the front-end  ),  CTE_DATA AS (      SELECT ctid.STARTDATE, ctid.ENDDATE, LAG(ctid.ENDDATE, 1) OVER (ORDER BY ctid.STARTDATE) AS PREV_ENDDATE FROM CTE_INNERDATA ctid  )  SELECT COUNT(1) FROM cte_data ctd  WHERE PREV_ENDDATE IS NOT NULL  AND PREV_ENDDATE < STARTDATE  

Using this SQL query when validating the third row (12/01/2022 - 15/01/2022) there will be a gap between dates 09/01/2022 and 12/01/2022. This issue would be fixed if instead of using union with a single row, to use it with all the rows send from the front-end but I can't figure out a way to do something like that.

How can create merge adapter class in android kotlin

Posted: 19 Apr 2022 02:56 AM PDT

How can create merge adapter class in android Kotlin

i have two class one class contain header other class contain image card how can create merge adapter class in kotlin

Movie card adapter

class MovieCardAdapter (private var image:IntArray):RecyclerView.Adapter<MovieCardAdapter.CardViewHolder>(){      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {      val itemView = LayoutInflater.from(parent.context).inflate(R.layout.movie_cardview,parent,false)        return CardViewHolder(itemView)  }    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {      holder.movieImage.setImageResource(image[position])      holder.movieImage.setOnClickListener { view ->          val intent = Intent(view.context, MovieDetailsActivity::class.java)          intent.putExtra("samples",image[position] )          view.context.startActivity(intent)      }  }    override fun getItemCount(): Int {      return image.size  }    class CardViewHolder(itemView: View) :RecyclerView.ViewHolder(itemView){      val movieImage : ImageView = itemView.findViewById(R.id.movieImage)      val numberOfTrailer : TextView = itemView.findViewById(R.id.number_of_trailer)  } }  

Header adapter

class HeaderAdapter(private var section:String): RecyclerView.Adapter<HeaderAdapter.HeaderViewHolder>(){  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder {      val view = LayoutInflater.from(parent.context)          .inflate(R.layout.headerview, parent, false)      return HeaderViewHolder(view)  }    override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) {      holder.headerTxt.text = section      holder.headerLayout.setOnClickListener { view ->          val intent = Intent(view.context, GridLayoutDisplayActivity::class.java)          intent.putExtra("samples", section )          view.context.startActivity(intent)      }  }    override fun getItemCount() = 1    class HeaderViewHolder(view: View) : RecyclerView.ViewHolder(view){       val headerTxt: TextView = itemView.findViewById(R.id.headerTxt)       val headerLayout: View = itemView.findViewById(R.id.section_click)  } }  

fragment

val movieCardAdapter = MovieCardAdapter(image)      val headerAdapter = HeaderAdapter("On Web")      binding.imageCardRecycleview.adapter = headerAdapter  

Android: Issue with transparent activity

Posted: 19 Apr 2022 02:56 AM PDT

Recently, on one of our production apps, transparent activity has stopped working. By this I mean that it became a black background instead of transparent. When I set activity's background color to solid one (i.e. red, green etc.), it's applied w/o issues. Probably the issue was caused by migration to AndroidX, but I don't have evidences for this.

After many hours of debugging, testing and reading through related SO topics, I was finally able to identify circumstances, under which the issue is happening.

My test environment is a very simple clean project with two activities (you can check full code under the link).

Conditions for working state

I'm able to make second activity transparent only if my 'themes.xml' file is very simple. You can see first activity in the background:

enter image description here

Conditions for non-working state

It's enough to add a simple style, even without items inside and with no parents, to cause background to be black instead of transparent:

enter image description here

Here is my 'themes.xml':

<resources xmlns:tools="http://schemas.android.com/tools">      <!-- Base application theme. -->      <style name="Theme.MyApplication" parent="Theme.AppCompat.Light">          <item name="android:windowBackground">@android:color/white</item>      </style>        <style name="Transparent" parent="Theme.AppCompat.Dialog">          <item name="android:windowNoTitle">true</item>          <item name="android:windowBackground">@android:color/transparent</item>          <item name="android:colorBackgroundCacheHint">@null</item>          <item name="android:windowIsTranslucent">true</item>          <item name="android:windowAnimationStyle">@android:style/Animation</item>          <item name="android:windowTranslucentStatus">true</item>          <item name="android:statusBarColor">@android:color/transparent</item>      </style>        <!--    By removing this style I can make transparent activity to work -->      <style name="ScrollViewStyle" />    </resources>  

And 'AndroidManifest.xml':

<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.example.myapplication">        <application          android:allowBackup="true"          android:icon="@mipmap/ic_launcher"          android:label="@string/app_name"          android:roundIcon="@mipmap/ic_launcher_round"          android:supportsRtl="true"          android:theme="@style/Theme.MyApplication">          <activity              android:name=".SecondActivity"              android:label="@string/title_activity_second"              android:theme="@style/Transparent" />          <activity              android:name=".MainActivity"              android:label="@string/title_activity_first">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                    <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>      </application>    </manifest>  

I hope someone will be able to help me getting technical explanation of this strange behavior.

No comments:

Post a Comment