how to pass second params as ' ' without suffix and prefix in i18n on reactJS? Posted: 08 Jun 2022 06:27 PM PDT import i18n from 'i18next'; import detector from 'i18next-browser-languagedetector'; import { initReactI18next } from 'react-i18next'; import translationEn from '~/lang/data/translation_en.json'; import translationKo from '~/lang/data/translation_ko.json'; const resources = { en: { translation: translationEn, }, ko: { translation: translationKo, }, }; i18n .use(detector) .use(initReactI18next) .init({ resources, fallbackLng: 'en', debug: true, keySeparator: false, interpolation: { escapeValue: false, prefixEscaped: undefined, suffixEscaped: undefined, }, react: { transEmptyNodeValue: '!null', transSupportBasicHtmlNodes: true, transKeepBasicHtmlNodesFor: ['br', 'strong', 'i'], }, }); export default i18n; {"common_confirm_message_save_data_to_transfer": "Saving data to transfer to {{test.data}}"} <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> const test = { data: 'PC', }; <p className='para'>{t('data_to_transfer', 'test')}</p> I'd like to pass the second params like this {t('data_to_transfer', 'test')} but every documentation only explaining like below.. {t('data_to_transfer', {{test.data}})} plz gimme advice abt this |
PyQt - not showing instance of FigureCanvasQTAgg on QtWidget of TabPane Posted: 08 Jun 2022 06:27 PM PDT I'm continuing project described more in that question: PyQt - can't read Excel file Basically my code looks like this right now: # This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import csv import sys import numpy as np from PyQt6 import QtWidgets from PyQt6.QtWidgets import QDialog, QApplication, QFileDialog, QTableWidget, QTableWidgetItem, QTabWidget, QWidget from PySide6.QtCore import Slot, SIGNAL from PyQt6.uic import loadUi import pandas as pd from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure class MplCanvas(FigureCanvasQTAgg): def __init__(self, parent=None, width=12, height=5, dpi=100): fig = Figure(figsize=(width, height), dpi=100) self.axes = fig.add_subplot(111) super(MplCanvas, self).__init__(fig) class MainWindow(QDialog): def __init__(self, parent=None): super(MainWindow, self).__init__(parent=parent) self.initUI() def initUI(self): loadUi('gui.ui', self) self.btnShow.setEnabled(False) self.btnLoad.setEnabled(False) self.btnBrowse.clicked.connect(self.browseFiles) self.btnLoad.clicked.connect(self.loadExcelData) self.btnClean.clicked.connect(self.cleanData) self.btnShow.clicked.connect(self.showGraphs) @Slot() def browseFiles(self): fname = QFileDialog.getOpenFileName(self, 'Open a file', 'C:\\', "Excel (*.xls *.xlsx)") self.filename.setText(fname[0]) self.btnLoad.setEnabled(True) @Slot() def loadExcelData(self): column_names = ["Action", "TimeOfFailure", "ReverseRankR", "S(i)", "Cdf", "Ppf", "LogTime"] df = pd.read_excel(self.filename.text(), "Sheet1", names=column_names) if df.size == 0: return self.tableExcelData.setRowCount(df.shape[0]) self.tableExcelData.setColumnCount(df.shape[1]) self.tableExcelData.setHorizontalHeaderLabels(df.columns) for row in df.iterrows(): values = row[1] for col_index, value in enumerate(values): tableItem = QTableWidgetItem(str(value)) self.tableExcelData.setItem(row[0], col_index, tableItem) self.btnLoad.setEnabled(False) self.btnShow.setEnabled(True) @Slot() def cleanData(self): self.btnLoad.setEnabled(True) self.btnShow.setEnabled(False) self.tableExcelData.setRowCount(0) self.tableExcelData.setColumnCount(0) @Slot() def showGraphs(self): timeOfDays = [] cdf = [] ppf = [] logTime = [] for row in range(self.tableExcelData.rowCount()): isFailure = False for column in range(self.tableExcelData.columnCount()): value = self.tableExcelData.item(row, column) if(column == 0 and str(value.text()) == 'F'): isFailure = True if isFailure == True: if(column == 1): #TimeOfDays value = int(value.text()) timeOfDays.append(value) elif(column == 4): #CDF value = float(value.text()) cdf.append(value) elif(column == 5): value = float(value.text()) ppf.append(value) elif(column == 6): value = float(value.text()) logTime.append(value) print(timeOfDays) print(cdf) print(ppf) print(logTime) #fig = Figure(figsize=(12,5), dpi=100) #firstSubplot = fig.add_subplot(111) #firstSubplot.scatter(timeOfDays, ppf, '*') #firstSubplot.plot(timeOfDays, ppf) #fig.show() #plt.plot(timeOfDays, ppf) #plt.show() try: canvasFig = MplCanvas() canvasFig.axes.scatter(timeOfDays, ppf, s=5, color='red') canvasFig.axes.plot(timeOfDays, ppf) canvasFig.draw() self.tabFirstGraph.setCentralWidget(canvasFig) except Exception as e: print('Error: ' + str(e)) #canvas = FigureCanvasTkAgg(fig, master=self) #canvas.get_tk_widget().pack() #canvas.draw() # Press the green button in the gutter to run the script. if __name__ == '__main__': app = QApplication(sys.argv) mainWindow = MainWindow() mainWidget = QtWidgets.QStackedWidget() mainWidget.addWidget(mainWindow) mainWidget.show() sys.exit(app.exec()) # See PyCharm help at https://www.jetbrains.com/help/pycharm/ I'm trying to generate two graphs (now it's code for only creation of one): try: canvasFig = MplCanvas() canvasFig.axes.scatter(timeOfDays, ppf, s=5, color='red') canvasFig.axes.plot(timeOfDays, ppf) canvasFig.draw() self.tabFirstGraph.setCentralWidget(canvasFig) # except Exception as e: print('Error: ' + str(e)) I tried to create another TabPane ("tabFirstGraph" as name of this object) and set canvas figure object to fill this QWidget instance. But I'm getting constantly this error: Error: 'QWidget' object has no attribute 'setCentralWidget' I assumed already that problem is with line above (QWidget, QTableWidget don't have this method). But how can I show my canvas figure graph on "First Graph" Tab Pane? Thanks in advance for your all answers. :) |
Android Studio: How to reset auto increment after deleting a row Posted: 08 Jun 2022 06:26 PM PDT I am using SQLite and Android Studio to create a todo list app. It takes in the item, urgency and adds it to the database, displays it, and there is an option to delete. The issue I am having is, that once I delete all the rows in the database, the auto-increment does not reset, therefore it will not allow me to delete any new rows since it cannot recgonize the id. The table in the database is as follows: CREATE TABLE todo_table (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, item TEXT, urgent INTEGER); Delete method public Integer deleteTodo(long id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete(TABLE_NAME, id + " = ?", new String[] {Long.toString(id)}); } The item onClickListener myList.setOnItemLongClickListener((p, b, pos, id) -> { todo = list.get(pos); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Do you want to delete this item?") .setMessage("The selected row is: " + pos) .setPositiveButton("Yes", (click, arg) -> { //deleting the rows in the database Integer deletedRows = myOpener.deleteTodo(pos); //Removing that item position from the array list.remove(pos); //Notifying the adapter myAdapter.notifyDataSetChanged(); //Toast message to say if the delete was successful if (deletedRows > 0) { Toast.makeText(MainActivity.this, "Item# " + pos + " deleted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Item# " + pos + " not deleted", Toast.LENGTH_LONG).show(); } Is there a way I can reset the auto-increment id after delete? Thank you, |
Is it possible get web element by clicking or knowing coordinates? (JavaFX, webview...) Posted: 08 Jun 2022 06:26 PM PDT I need to get the JSObject or Element object to know their attributes. My last target is identify the clicked web element with any attribute (class, id...). Then I could interact that element again. Anyone knows if its possible? After a google research I am not very confident... |
LibreOffice Writer 7.2.7.2 page style change affects earlier page styles Posted: 08 Jun 2022 06:26 PM PDT I am using LibreOffice Writer 7.2.7.2.(x64). I create a new blank document, and insert a page break, giving me two pages. I go to the header of the first page, then press F-11 to open Styles, then go to Page Styles. Then I double-click "First Page". The first page's header takes on the style "Header (First Page)", as expected. Then I go to the header of the second page, and from Page Styles, double click "Left page". At this point, the second page's header style now says "Header (default page style)", and the style for the first page now says "Header (Left Page)". Why does changing the header style for page 2 affect page 1? (And how is anyone supposed to control styles if you can't tell what page you are going to be affecting?) I have searched diligently for some explanation of how page styles work, read the LibO chapter on controlling page styles, and cannot grasp how setting a style for a later page could/should affect earlier pages. Is there any explanation for this incredibly frustrating behavior? Thank you. |
Is there a way to save a bool to a file so when accessed later it can be read and changed? Posted: 08 Jun 2022 06:26 PM PDT Ok so I am building a Bug Tracker, and I am writing this in C++, and I have an idea that asks the user if they have solved it, if they haven't the bool will be false, if they have the bool is true. How can I save it to a .dat file that will let C know that in their project that bug has been resolved? |
Best way to delete a bracket pair in xcode Posted: 08 Jun 2022 06:25 PM PDT Vstack{ Zstack{ print("I just wanna delete this Zstack") } } - I warp a code snippit in a closure
- hours later I hate it
- take me 30s to take it out
|
How can I split string in R from first square bracket and last round bracket? Posted: 08 Jun 2022 06:25 PM PDT I am dealing with legal citations. I want to split the citations into four parts. The citation is in general format as follows: ABC v. DEF [Year] citation data (Authority) So, I want to split it into four parts - ABC v. DEF, Year, citation data, and authority. The problem is that the first part (i.e., ABC v. DEF)might have additional round brackets, while the third part (i.e., citation data) might have additional square and/or round brackets. For example, in this following case "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) [2013] 33 taxmann.com 424/60 SOT 118 (URO) (Mum. Trib.)" The first part is "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation)" , second part is "2013" , third part is "33 taxmann.com 424/60 SOT 118 (URO)" and the last part is "Mum. Trib." I am unable to come up with the right regex to do this. Can anyone help me with this one? |
The size of tensor a (m) must match the size of tensor b (n) Posted: 08 Jun 2022 06:24 PM PDT I'm trying the below which is intended to obtain a model that takes a batch of sequences and output the ranks/orders of each sequence. import random import string import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from transformers import AutoModel, AutoTokenizer def collate(batch): max_x = max(batch, key=lambda item: item[0].shape[0])[0].shape[0] max_y = max(batch, key=lambda item: item[0].shape[1])[0].shape[1] ids, masks, orders = [], [], [] for _id, mask, order in batch: x_pad = max_x - _id.shape[0] y_pad = max_y - _id.shape[1] ids.append(np.pad(_id, ((0, x_pad), (y_pad, 0)))) masks.append(np.pad(mask, ((0, x_pad), (y_pad, 0)))) orders.append(np.pad(order, [0, x_pad])) return ( torch.tensor(np.stack(ids)), torch.tensor(np.stack(masks)), torch.tensor(np.stack(orders)), ) class ListwiseDataset(Dataset): def __init__(self, text, tokenizer): self.tokenizer = tokenizer self.text = text self.max_length = max(self.text, key=len) def __getitem__(self, item): example = self.text[item] tokens = self.tokenizer.batch_encode_plus( example, add_special_tokens=True, return_token_type_ids=True, return_tensors='np', padding=True, ) return ( tokens['input_ids'], tokens['attention_mask'], np.arange(len(example)) / len(example), ) def __len__(self): return len(self.text) class BertBase(nn.Module): def __init__(self, bert_head): super(BertBase, self).__init__() self.bert_head = bert_head self.dense = nn.Sequential( nn.Dropout(0.2), nn.Linear(768, 64), nn.Dropout(0.2), nn.Linear(64, 1), ) def forward(self, *args): x = self.bert_head(*args)[0] x = self.dense(x) return torch.sigmoid(x) def train_step(model, train_loader, device): model.train() for i, batch in enumerate(tqdm(train_loader), start=1): ids = batch[0].to(device) masks = batch[1].to(device) y = batch[2].to(device) y_pred = model(ids, masks) # this fails if __name__ == '__main__': pretrained_model = 'distilbert-base-uncased' cache_dir = 'transformers-cache' head = AutoModel.from_pretrained(pretrained_model, cache_dir=cache_dir) tokenizer = AutoTokenizer.from_pretrained(pretrained_model, cache_dir=cache_dir) model = BertBase(head) text = [ [ ''.join( random.choice(string.ascii_letters + 10 * ' ') for _ in range(random.randint(50, 150)) ) for _ in range(random.randint(10, 100)) ] for _ in range(100) ] dataset = ListwiseDataset(text, tokenizer) train_loader = DataLoader(dataset, 4, True, collate_fn=collate) if torch.cuda.is_available(): _device = torch.device('cuda') else: _device = torch.device('cpu') train_step(model, train_loader, _device) However, it fails due to the resulting batch shapes being unexpected somewhere: Some weights of the model checkpoint at distilbert-base-uncased were not used when initializing DistilBertModel: ['vocab_projector.bias', 'vocab_layer_norm.bias', 'vocab_layer_norm.weight', 'vocab_transform.weight', 'vocab_projector.weight', 'vocab_transform.bias'] - This IS expected if you are initializing DistilBertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model). - This IS NOT expected if you are initializing DistilBertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). 0%| | 0/25 [00:00<?, ?it/s] Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1491, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/user/Library/Application Support/JetBrains/PyCharm2022.1/scratches/scratch.py", line 103, in <module> train_step(model, train_loader, _device) File "/Users/user/Library/Application Support/JetBrains/PyCharm2022.1/scratches/scratch.py", line 78, in train_step y_pred = model(ids, masks) File "/usr/local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/Users/user/Library/Application Support/JetBrains/PyCharm2022.1/scratches/scratch.py", line 67, in forward x = self.bert_head(*args)[0] File "/usr/local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/usr/local/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py", line 566, in forward inputs_embeds = self.embeddings(input_ids) # (bs, seq_length, dim) File "/usr/local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/usr/local/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py", line 132, in forward embeddings = word_embeddings + position_embeddings # (bs, max_seq_length, dim) RuntimeError: The size of tensor a (89) must match the size of tensor b (96) at non-singleton dimension 2 |
Is there a CSS parser for Python to see applied styles to each tag in HTML? Posted: 08 Jun 2022 06:23 PM PDT My Python Scrapy code is crawling through each HTML tag and I need to find CSS styles that are applied to each tag/element. I've been using Selenium but it's very resource-intensive and need to find another solution. Are there any Python libraries (i.e. tinycss, cssutils and etc.) that can handle these tasks? This is the HTML example. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>My HTML</title> </head> <body> <p class="p-styles">My paragraph</p> </body> </html> And below is the CSS file .p-styles { font-size: large; color: black; } The ask is to get all styles (i.e. font-size: large, color: black) from ".p-styles" style when crawling to the p tag. |
Julia global variable throws UndefVarError Posted: 08 Jun 2022 06:23 PM PDT The following code fails. global Θ=1.0 function f(a) c=sin(a+θ) return c end f(1) UndefVarError: θ not defined Stacktrace: [1] f(a::Int64) @ Main ./In[1]:3 [2] top-level scope @ In[1]:6 [3] eval @ ./boot.jl:373 [inlined] [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String) @ Base ./loading.jl:1196 It has no reason to fails. Why this is incorrect?? If this doesn't work, I can say that people can't do anything using Julia. |
Question about hatch function using pyautocad Posted: 08 Jun 2022 06:25 PM PDT I encounter a question about the Hatch function of pyautocad (python 3.9.7). Here is my code. from pyautocad import Autocad, APoint, aDouble acad = Autocad(create_if_not_exists=True) acad.prompt('Echo\n') pattern_type = 0 pattern_name = "ANSI31" hatchObj = acad.model.AddHatch(pattern_type, pattern_name, True) hatchObj.LinetypeScale = 6 hatchObj.PatternScale = 2 center = APoint(200, 0) radius = 150 circle1 = acad.model.AddCircle(center, radius) hatchObj.AppendOuterLoop(circle1) I tried to hatch a circle in AutoCAD by using pyautocad commands. But I got the COMError : COMError: (-2147352567, 'Exception occurred.', ('Invalid object array', 'AutoCAD.Application', 'C:\Program Files\Autodesk\AutoCAD 2021\HELP\OLE_ERR.CHM', -2145320837, None)) Does anyone encounter the same question but get solutions? |
Free hosting github in react Posted: 08 Jun 2022 06:26 PM PDT I've created a website in React.js and Node.js. I'd like to launch it with a free hosting github. I've done publishing my website with gh-pages. However, it doesn't show anything. I found a reason because my App.js has just Route like below. function App() { return ( <Router> <Routes> <Route path="/test" element={<Main/>}/> <Route path="/" element={<Home/>}/> <Route path="/me" element={<Me/>}/> </Routes> </Router> ); } How can I show my Home page? Should I put all codes in the app.js? |
How to create a column of Maps in SQL Posted: 08 Jun 2022 06:27 PM PDT I essentially have an SQL table that is similar to  And I want to create a table that looks like:  where essentially each cell in the map column contains a map where the key is the receiver ID and the value is the Quantity from the first table. How would I go about doing this using SQL. I know I have to use some function like map_from_entries() but I am not sure how. The actual table I want to operate on is a lot more complicated but this simplified version still revolves around the same principle. |
Add conditional filter in JSX Posted: 08 Jun 2022 06:25 PM PDT What is the best way to add optional filters based on a condition? For instance, consider the following code fragment: <Menu> {itemGroupLevels.map(group) = [ this.props.itemTypes .filter((x) => x.group_level === group) .filter((x) => x.article_type_code !== "GRAL") {Permission.TEACHER?filter((x) => !x.article_type_code.includes('BACKPACK','LUNCH')):null} .map((value) => ( ])} </Menu> How can I add the last filter depending on a condition such as if the user has specific permission to avoid including BACKPACK and LUNCH just if the user is a teacher: {Permission.TEACHER?filter((x) => !x.article_type_code.includes('BACKPACK','LUNCH')):null} Otherwise, I do not need to add the filter and just leave the two previous filters. Thanks for your help |
How to efficiently add a sorted List into another sorted List? Posted: 08 Jun 2022 06:23 PM PDT I'm having trouble determining the most efficient way of doing this in Dart. If have two lists that in sorted descending order, List<int> messages = [10, 5, 4, 1]; List<int> newMessages = [5, 3, 2]; How can I add newMessages to messages so that messages now looks like messages = [10, 5, 5, 4, 3, 2, 1]; |
Php Artisan and Tinker not finding laravel project classes Posted: 08 Jun 2022 06:26 PM PDT I happened to open two instances of Laragon at the same time. After that php artisan migrate started throwing strange errores like "Interface not found" when that interface is actually there and was correctly imported. Tried different migrations and also throws random errors. I even tried with an old (already migrated) migration, copy pasted the code and it also didn't work. Always related to classes/interfaces not being found. I've just noted that a simple test: <?php use App\Book; use Illuminate\Database\Migrations\Migration; class BookTest extends Migration { public function up() { echo Book::HARDCOVER; } } doesn't work; it says: 'Class 'App\Book' not found' . The book class is there and was imported from phpstorm with a simple click. So, php artisan isn't finding any of my project classes. I've just confirmed that tinker can't find the classes either. Ok, I've just noticed that if I change in the book class the namespace to '\App\Models\Store' (where the file actually is) and I do from tinker something like \App\Models\Store\Book::HARDCOVER, then it actually works. The thing I don't get is why it's now (suddenly) needing me to update the name space to work... |
How do I store the JSON response such that I can use it in other functions (React & JS)? Posted: 08 Jun 2022 06:24 PM PDT fetchData.js -> File where we fetch the data. This file is later imported and the functions will be used to display the fetched data. import { weatherAPIConfig } from "../weatherAPIConfig" export async function fetchWeatherForecast(cityName) { let URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=${weatherAPIConfig.key}` try { const fetchWeatherForecast = await fetch(URL) const weatherForecastJSON = await fetchWeatherForecast.json() return weatherForecastJSON } catch (error) { console.log("Could not find given city"); return "Could not find given city" } } export function getWeatherDescription(weatherForecastJSON) { return weatherForecastJSON.weather[0].description; } export function getWeatherTemperature(weatherForecastJSON) { return weatherForecastJSON.main.temp } export function getWeatherWindSpeed(weatherForecastJSON) { return weatherForecastJSON.wind.speed; } export function getWeatherHumidity(weatherForecastJSON) { return weatherForecastJSON.main.humidity } Row.js -> The file where the temperature etc. is displayed in div import React from 'react' import {getWeatherDescription, getWeatherHumidity, getWeatherTemperature, getWeatherWindSpeed, fetchWeatherForecast} from '../../functions/fetchData' import { weatherAPIConfig } from '../../weatherAPIConfig'; function Row() { return ( <div> <div>API-key: {weatherAPIConfig.key}</div> <div>Result: {getWeatherDescription(fetchWeatherForecast("London"))}</div> </div> ) } export default Row; ........................................................................................ |
list of nested dictionary to multiindex pandas Posted: 08 Jun 2022 06:24 PM PDT I'm getting a query to Tableau back in the form of a list of nested dictionaries, with lists inside of the values. I'm wondering if it's possible to blow this out in a general way. I'm trying to turn this r = [{'name': 'TestWorkbook', 'embeddedDatasources': [{'name': 'Test1', 'id':'uuid1'}, {'name': 'Test2', 'id': 'uuid2'}], 'upstreamDatasources': [{'name': 'Test1', 'id': 'uuid1'}]}, {'name': 'TestWorkbook2', 'embeddedDatasources': [{'name': 'OtherTest', 'id': 'uuid3'}], 'upstreamDatasources': []}] into pd.DataFrame({('name', 'name'):['TestWorkbook', 'TestWorkbook', 'TestWorkbook2'], ('embeddedDatasources', 'name'): ['Test1', 'Test2', 'OtherTest'], ('embeddedDatasources', 'id'): ['uuid1', 'uuid2', 'uuid3'], ('upstreamDatasources', 'name'): ['Test1', None, None], ('upstreamDatasources', 'id'): ['uuid1', None, None], }) I can do it brute force but I have to do it for every query I give that I want. (The name/name bit is simply because it doesn't have multiple levels). Even if there was a step that would get me 80% there, I would love. Edit pretty sure what I'm looking for is pd.json_normalize but will update with actual answer. |
ForEach Did Not Work On ArrayList Inside ConcurrentHashMap [closed] Posted: 08 Jun 2022 06:23 PM PDT I have a ConcurrentHashMap public static final ConcurrentHashMap<String, ArrayList<MyInterface>> ALERT_BY_MMSI_MAP = new ConcurrentHashMap(); Why ArrayList.forEach() return nothing while ArrayList.get(x) successfully get the MyInterface object. ALERT_BY_MMSI_MAP.forEach((s, iSwAlerts) -> { System.out.println("ID : " + s); iSwAlerts.forEach(iSwAlert -> { // this doesn't worked System.out.println(iSwAlert.getName()); }); System.out.println(iSwAlerts.get(0).getName()); // this worked }); Any point I missed? |
New to learning CSS Animation! Animation is changing color, but not moving to the left Posted: 08 Jun 2022 06:23 PM PDT This is the code that I have so far, the color changes like it is supposed to. But the animation for moving does not work and stays in the same position. Not sure what I am missing. div { height: 50px; width: 50%; background: blue; margin: 50px auto; border-radius: 5px; postion: relative; } #square { animation-name: first; animation-duration: 4s; } @keyframes first { 0% { background-color: blue; top: 0px; left: 0px; } 50% { background-color: green; top: 25px; left: 25px; } 100% { background-color: yellow; top: -25px; left: -25px; } } |
missing org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory Posted: 08 Jun 2022 06:24 PM PDT Whenever I try to run the spring application in VSCodium, VSCodium complains about org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory and don't run, the application runs normally through java -jar applicationName Gradle is the used build automation tool Environment Operating System: Debian GNU/Linux 10 (buster) x86_64 JDK version: jdk1.8.0_291 Visual Studio Codium version: 1.67.2 Java extension version: 1.7.0 Java Debugger extension version: 0.41.0 Where is the error message: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. [Error - 09:14:55] 7 de jun de 2022 09:14:55 Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ls.core". org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory java.lang.NoClassDefFoundError: org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory at org.eclipse.m2e.jdt.internal.launch.MavenRuntimeClasspathProvider.resolveClasspath(MavenRuntimeClasspathProvider.java:167) at org.eclipse.jdt.internal.launching.RuntimeClasspathProvider.resolveClasspath(RuntimeClasspathProvider.java:68) at org.eclipse.jdt.launching.JavaRuntime.resolveRuntimeClasspath(JavaRuntime.java:1662) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.computeClassPath(ResolveClasspathsHandler.java:232) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.computeClassPath(ResolveClasspathsHandler.java:211) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.resolveClasspaths(ResolveClasspathsHandler.java:74) at com.microsoft.java.debug.plugin.internal.JavaDebugDelegateCommandHandler.executeCommand(JavaDebugDelegateCommandHandler.java:62) at org.eclipse.jdt.ls.core.internal.handlers.WorkspaceExecuteCommandHandler$1.run(WorkspaceExecuteCommandHandler.java:215) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.jdt.ls.core.internal.handlers.WorkspaceExecuteCommandHandler.executeCommand(WorkspaceExecuteCommandHandler.java:205) at org.eclipse.jdt.ls.core.internal.handlers.JDTLanguageServer.lambda$4(JDTLanguageServer.java:526) at org.eclipse.jdt.ls.core.internal.BaseJDTLanguageServer.lambda$0(BaseJDTLanguageServer.java:75) at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642) at java.base/java.util.concurrent.CompletableFuture$Completion.exec(CompletableFuture.java:479) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183) Caused by: java.lang.ClassNotFoundException: org.eclipse.m2e.core.embedder.IMavenExecutionContextFactory cannot be found by org.eclipse.m2e.jdt_2.0.0.20220523-1537 at org.eclipse.osgi.internal.loader.BundleLoader.generateException(BundleLoader.java:529) at org.eclipse.osgi.internal.loader.BundleLoader.findClass0(BundleLoader.java:524) at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:416) at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:168) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ... 19 more [Error - 09:14:55] 7 de jun de 2022 09:14:55 Error in calling delegate command handler org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory java.lang.NoClassDefFoundError: org/eclipse/m2e/core/embedder/IMavenExecutionContextFactory at org.eclipse.m2e.jdt.internal.launch.MavenRuntimeClasspathProvider.resolveClasspath(MavenRuntimeClasspathProvider.java:167) at org.eclipse.jdt.internal.launching.RuntimeClasspathProvider.resolveClasspath(RuntimeClasspathProvider.java:68) at org.eclipse.jdt.launching.JavaRuntime.resolveRuntimeClasspath(JavaRuntime.java:1662) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.computeClassPath(ResolveClasspathsHandler.java:232) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.computeClassPath(ResolveClasspathsHandler.java:211) at com.microsoft.java.debug.plugin.internal.ResolveClasspathsHandler.resolveClasspaths(ResolveClasspathsHandler.java:74) at com.microsoft.java.debug.plugin.internal.JavaDebugDelegateCommandHandler.executeCommand(JavaDebugDelegateCommandHandler.java:62) at org.eclipse.jdt.ls.core.internal.handlers.WorkspaceExecuteCommandHandler$1.run(WorkspaceExecuteCommandHandler.java:215) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.jdt.ls.core.internal.handlers.WorkspaceExecuteCommandHandler.executeCommand(WorkspaceExecuteCommandHandler.java:205) at org.eclipse.jdt.ls.core.internal.handlers.JDTLanguageServer.lambda$4(JDTLanguageServer.java:526) at org.eclipse.jdt.ls.core.internal.BaseJDTLanguageServer.lambda$0(BaseJDTLanguageServer.java:75) at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642) at java.base/java.util.concurrent.CompletableFuture$Completion.exec(CompletableFuture.java:479) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183) Caused by: java.lang.ClassNotFoundException: org.eclipse.m2e.core.embedder.IMavenExecutionContextFactory cannot be found by org.eclipse.m2e.jdt_2.0.0.20220523-1537 at org.eclipse.osgi.internal.loader.BundleLoader.generateException(BundleLoader.java:529) at org.eclipse.osgi.internal.loader.BundleLoader.findClass0(BundleLoader.java:524) at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:416) at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:168) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ... 19 more Where is the gradle.build file: /* * This file was generated by the Gradle 'init' task. */ plugins { id 'java' id 'maven-publish' id "org.springframework.boot" version "2.5.2" id "io.spring.dependency-management" version "1.0.11.RELEASE" } jar { manifest { attributes( 'Main-Class': 'com.sti.sigproj.SigprojApplication' ) } } repositories { mavenLocal() maven { url = uri('https://repo.maven.apache.org/maven2/') } } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.2' implementation 'org.springframework.boot:spring-boot-starter-validation:2.5.2' implementation 'org.springframework.boot:spring-boot-starter-web:2.5.2' implementation 'org.flywaydb:flyway-core:7.7.3' implementation 'org.springframework.boot:spring-boot-starter-security:2.5.2' implementation 'org.springframework.security.oauth:spring-security-oauth2:2.5.1.RELEASE' implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.6.6' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client:2.5.2' implementation 'org.modelmapper.extensions:modelmapper-spring:2.3.0' implementation 'commons-codec:commons-codec:1.15' implementation 'io.jsonwebtoken:jjwt:0.7.0' implementation 'org.springframework.boot:spring-boot-starter-mail:2.5.2' implementation 'io.springfox:springfox-swagger2:2.9.2' implementation 'io.springfox:springfox-swagger-ui:2.9.2' implementation('com.github.javafaker:javafaker:1.0.2') { exclude module: 'snakeyaml' } runtimeOnly 'com.h2database:h2:1.4.200' runtimeOnly 'org.springframework.boot:spring-boot-devtools:2.5.2' runtimeOnly 'org.postgresql:postgresql:42.2.22' testImplementation 'org.flywaydb.flyway-test-extensions:flyway-spring-test:5.0.0' testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.2' testImplementation 'org.springframework.security:spring-security-test:5.5.1' testImplementation 'org.junit.vintage:junit-vintage-engine:5.7.2' } group = 'com.sti.sigproj' version = '0.0.1-SNAPSHOT' description = 'sigproj-backend' java.sourceCompatibility = JavaVersion.VERSION_1_8 publishing { publications { maven(MavenPublication) { from(components.java) } } } tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } test { useJUnitPlatform() } test.testLogging { exceptionFormat "full" } task stage(type: Copy, dependsOn: [clean, build]) { from jar.archivePath into project.rootDir rename { 'app.jar' } } stage.mustRunAfter(clean) |
Interpolating an array into a Javascript Postgres query Posted: 08 Jun 2022 06:23 PM PDT So I'm working in Node.js and using the 'pg' npm module. I'm trying to check to see if the contents of an array are contained within an array that's stored in a Postgres table (the order doesn't matter to me--it should return true if there is a 1:1 element ration between arrays). The Postgres query looks like this: let getComFromMembers = `SELECT * FROM ComTable WHERE (members @> ($1) AND members <@ ($1))` In my javascript, I'm calling it like this: let results = await client.query(getComFromMembers, [numberMembers]); numberMembers is an array that was originally pulled from Postgres, and then mapped to a number array: let postgresArray = [] // query tables and populate postgresArray with .push() let numberArray = postgresArray.map(Number) For some reason, I'm not getting anything back from 'results'. As an example, in the case where numberArray would be an array with elements 1, 2, and 3, look below. To get it to work I need to query directly into my database: SELECT * FROM ComTable WHERE (members @> '{1,2,3}' AND members <@ '{1,2,3}') |
Angular app: es2020 migration from es2015 Posted: 08 Jun 2022 06:26 PM PDT I have just updated my app to Angular 12 and am trying to use es2020. For some reason I am still getting errors when my app builds because it seems the app is still trying to use es2015: node_modules/typescript/lib/lib.es2015.promise.d.ts:33:34 [ng] 33 new <T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>; [ng] ~~~~~~~~~~~~~~~~~~~~~~~~~ [ng] An argument for 'value' was not provided. I've updated tsconfig.json to reflect es2020: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "inlineSources": true, "declaration": false, "sourceRoot": "/", "module": "es2020", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2020", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2020", "dom" ] }, "exclude": [ "node_modules", "**.*.spec.ts", "plugins/**" ] } EDIT: When I serve my app I also see the following: [ng] Compiling @angular/core : es2015 as esm2015 [ng] Compiling @ionic-native/core : module as esm5 [ng] Compiling @angular/common : es2015 as esm2015 [ng] Compiling @angular/cdk/collections : es2015 as esm2015 [ng] Compiling @ionic-native/splash-screen : module as esm5 [ng] Compiling @ionic-native/barcode-scanner : module as esm5 [ng] Compiling @ionic-native/status-bar : module as esm5 [ng] Compiling @angular/platform-browser : es2015 as esm2015 [ng] Compiling @angular/cdk/platform : es2015 as esm2015 Lastly, I am already using Typescript 4.3.5 in my package.json . But I have not explicitly installed any new typings since making the change. What do I do next to allow the change to es2020? |
Invalid Python SDK in PyCharm Posted: 08 Jun 2022 06:24 PM PDT Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Python 3.11 interpreter. I did completely uninstall PyCharm, as well as all my python installations and reinstalled everything. I also went through the "Repair IDE" option in PyCharm. I also removed and recreated all virtual environments. When I run "cmd" and type 'python' then python 3.10.1 opens without a problem. This morning, I installed a new antivirus software that did some checks and deleted some "unnecessary files" - maybe it is related (antivirus software is uninstalled again). |
How to add marquee text on items of NavigationView? Posted: 08 Jun 2022 06:27 PM PDT The names of my items are quite long, so I would like to make sure that their names scroll horizontally. I have searched on several SO posts, but I have not found a solution to my problem But I can't, I tried this: my activity_main.xml : <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:singleLine="true" app:headerLayout="@layout/nav_header" app:menu="@menu/menuDrawer"> </com.google.android.material.navigation.NavigationView> My XML "menuDrawer": <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_welcome" android:icon="@drawable/ic_folder_black_24dp" android:title="@string/menu_welcome" /> <item android:id="@+id/nav_dataset1" android:icon="@drawable/ic_folder_black_24dp" android:title="@string/menu_dataset1"/> <item android:id="@+id/nav_dataset2" android:icon="@drawable/ic_folder_black_24dp" android:title="@string/menu_dataset2" /> <item android:id="@+id/nav_dataset3" android:icon="@drawable/ic_folder_black_24dp" android:title="@string/menu_dataset3" /> </group> My java : private AppBarConfiguration mAppBarConfiguration; private TextView tvDataset1; private TextView tvDataset2; private TextView tvDataset3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_deroulant); Toolbar toolbar = findViewById(R.id.toolbar); tvDataset1 = this.findViewById(R.id.nav_dataset1); tvDataset1.setSelected(true); setSupportActionBar(toolbar); DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.nav_dataset1, R.id.nav_dataset2, R.id.nav_dataset3) .setDrawerLayout(drawer) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); } But no change, does anyone have an idea ? Please help EDIT : I tried to override this : <?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android"> <CheckedTextView android:id="@+id/design_menu_item_text" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:drawablePadding="@dimen/design_navigation_icon_padding" android:gravity="center_vertical|start" android:textAppearance="@style/TextAppearance.AppCompat.Body2" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:focusable="true" android:focusableInTouchMode="true"/> <ViewStub android:id="@+id/design_menu_item_action_area_stub" android:inflatedId="@+id/design_menu_item_action_area" android:layout="@layout/design_menu_item_action_area" android:layout_width="wrap_content" android:layout_height="match_parent" /> </merge> I have some changes : AFTER the override:  BEFORE the override :  |
Error when scaffolding identity in server side Blazor project Posted: 08 Jun 2022 06:26 PM PDT I'm working on a server-side Blazor application which was created with the "Individual User Accounts" option selected for Authentication. I now want to customise the login page however when I select to add the Identity pages via scaffolding I receive the below error and I'm not sure where to start in terms of troubleshooting. Failed to compile the project in memory .OnInitializedAynsc() no suitable method found to overrirde The above error is listed for each page within my project.  |
Visual Studio code Organize imports feature Posted: 08 Jun 2022 06:27 PM PDT On version 1.23 of visual studio code, the 'Organize imports' feature was added. This is a very helpful feature as it handles the imports itself, but I'd like to be able to configure it. The functionalities I'd like to know if are available for this feature are: - Is it possible to configure the order the imports are sorted? I'd like to configure external libraries (angular, rxjs) before my local imports
- Also, is it possible to add a line breaker between imports of different sources?
- On my project I have a max-line lenght configuration, but the import plugin doesn't seem to respect this. Shouldn't it?
I'm asking this questions because there is no configuration information available on VSCode page, only informing this is available. Thanks! |
How to run eb init specifying node.js version 8? Posted: 08 Jun 2022 06:24 PM PDT I run eb init and deploy, I get the node.js version 6, how can I specify that I want node.js version 8 when executing eb init command? |
Are document-oriented databases meant to replace relational databases? Posted: 08 Jun 2022 06:26 PM PDT Recently I've been working a little with MongoDB and I have to say I really like it. However it is a completely different type of database then I am used. I've noticed that it is most definitely better for certain types of data, however for heavily normalized databases it might not be the best choice. It appears to me however that it can completely take the place of just about any relational database you may have and in most cases perform better, which is mind boggling. This leads me to ask a few questions: - Are document-oriented databases being developed to be the next generation of databases and basically replace relational databases completely?
- Is it possible that projects would be better off using both a document-oriented database and a relational database side by side for various data which is better suited for one or the other?
- If document-oriented databases are not meant to replace relational databases, then does anyone have an example of a database structure which would absolutely be better off in a relational database (or vice-versa)?
|
No comments:
Post a Comment