instruction stringlengths 0 30k ⌀ |
|---|
TypeScript: Type checking while parsing an arbitrary JSON that is typed/ |
|json|typescript|parsing|typechecking| |
I have controller and service with it. I call service method and if error occur inside what should i do?
First, I just throw exception and handle them in exception middleware.
Second, I write a custom Either monad, and if exception should be, I return Either.Error(Object that contains error info). Or if all work correct, I return Either.Success(Value).
Third, I write a abstract class Service, and all services must inherit from it. In that class I declare some static methods that return one info object(like IActionResult in controllers). And after it same scheme like in second variant.
What's best practice? Maybe my options are bad at all.
Each of the options presented has cons and pros for me, but which is better in your opinion? Maybe you have another solution? |
Generating wakeup and Error frame In LIN bus using CAPL script in Canoe tool |
|automated-tests|capl|canoe|automotive| |
null |
**i'm trying to make an archive website for a school project, and while i followed a bunch of different tutorials it seems like something is just not clicking, because nothing gets added to the database (ALTHOUGH files get added to the file they're supposed to go to)
here's the code that's supposed to link the input page to the database:**
```
<?php
include ('config.php');
if(isset($_POST['upload']))
{
$TITLE= $_POST['title'];
$NAMES= $_POST['names'];
$DESCRIPTION= $_POST['description'];
$FILE= $_FILES ['file'];
$file_location = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_up = "files/".$file_name;
$insert = "INSERT INTO projects ('title', 'names', 'description', 'file') VALUES('$TITLE', '$NAMES', '$DESCRIPTION', '$file_up')";
if(move_uploaded_file($file_location, './files/'.$file_name))
{
echo "<script>alert('تمت إضافة المشروع بنجاح!') </script>";
}
else{
echo "<script>alert('جرب مرة أخرى') </script>";
}
header('location: archive.php');
}
?>
```
**the config.php code:**
```
<?php
$servername= 'sql211.infinityfree.com';
$username= 'if0_36063631';
$password= 'zm4UGYGlSxhNB';
$database= 'if0_36063631_projects';
$conn=new mysqli($servername, $username, $password, $database);
?>
```
**if anyone figures the problem out please explain it in simple terms "^^**
|
form input doesn't get sent into the data base |
|php|mysqli| |
null |
{"Voters":[{"Id":5389997,"DisplayName":"Shadow"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":20860,"DisplayName":"Bill Karwin"}],"SiteSpecificCloseReasonIds":[18]} |
I followed [this guide](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider) to implement Firebase App Check in my Next.js (v14) project :
``` javascript
// firebase/app.js
import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
};
export const app = initializeApp(firebaseConfig);
// add this condition to prevent 'document is not defined' error on SSR
if (typeof window !== "undefined") {
initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(
process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY
),
isTokenAutoRefreshEnabled: true,
});
}
```
When I run my project locally or in production i get these errors :
``` javascript
POST https://content-firebaseappcheck.googleapis.com/v1/projects/xxx/apps/xxx:exchangeRecaptchaV3Token?key=xxx 400 (Bad Request)
```
``` javascript
@firebase/app-check: AppCheck: Requests throttled due to 400 error. Attempts allowed again after 00m:02s (appCheck/throttled).
```
When I inspect the network tab of the browser I can see this response for the request :
``` javascript
{
"code": 400,
"message": "App not registered: 1:123xxxxx.", // I made sure this is the right Firebase app id
"status": "FAILED_PRECONDITION"
}
```
reCAPTCHA verification cannot be processed.
The problem is that my app is properly registered on Firebase :
[](https://i.stack.imgur.com/31gM7.png)
As well as my website key from reCAPTCHA Enterprise API in the Google Cloud console :
[](https://i.stack.imgur.com/18w0Q.png)
Note that Realtime Database is already implemented in the same project and working fine.
Thanks for your help.
EDIT : I was able to reproduce the issue in an [empty repo](https://github.com/pierre-phil/next.js_firebase_starter?tab=readme-ov-file) with a new Firebase project, so I might be missing something regarding the configuration of App Check.
**Repo of the reproduction** : https://github.com/pierre-phil/next.js_firebase_starter?tab=readme-ov-file |
this is error message:
First:
```
Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 1463, in wsgi_app
response = self.full_dispatch_request()
```
Second:
`GET500921B1.1 sChrome 123 ``https://flask-selenium-app-qs6rhz6vcq-du.a.run.app/`
I created a dynamic website scraper using Selenium and Flask. It works fine locally, but when I configure it with Docker and upload it to Google Run, the error above appears.
The current requirements.txt is as follows: There is no need for anything else since it is simply a simple scraping of one page.
```
flask==3.0.2
beautifulsoup4==4.12.3
selenium==4.19.0
gunicorn==21.2.0
```
When configuring the container, Python was version 3.12.
I changed it to work by setting the port to 8080.
I also ran wsgi.py as shown below.
```
if __name__ == "__main__":
app.run(port=8080)
```
The same goes for Docker.
```
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8080", "wsgi:app"] app.run(port=8080)
``` |
This hastily coded Python script for Windows may be of assistance:
<!-- language: py -->
# bintail.py -- reads a binary file, writes initial contents to stdout,
# and writes new data to stdout as it is appended to the file.
import time
import sys
import os
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
# Time to sleep between file polling (seconds)
sleep_int = 1
def main():
# File is the first argument given to the script (bintail.py file)
binfile = sys.argv[1]
# Get the initial size of file
fsize = os.stat(binfile).st_size
# Read entire binary file
h_file = open(binfile, 'rb')
h_bytes = h_file.read(128)
while h_bytes:
sys.stdout.write(h_bytes)
h_bytes = h_file.read(128)
h_file.close()
# Loop forever, checking for new content and writing new content to stdout
while 1:
current_fsize = os.stat(binfile).st_size
if current_fsize > fsize:
h_file = open(binfile, 'rb')
h_file.seek(fsize)
h_bytes = h_file.read(128)
while h_bytes:
sys.stdout.write(h_bytes)
h_bytes = h_file.read(128)
h_file.close()
fsize = current_fsize
time.sleep(sleep_int)
if __name__ == '__main__':
if len(sys.argv) == 2:
main()
else:
sys.stdout.write("No file specified.") |
The existing code renders. However, when I remove `Router` from line 2 as an import, even though it's not being used, it breaks.
*Correction: The page still renders when I remove Router. However, it just displays a blank page. When I inspect it, I no longer get anything in the <div id="root"> tags.*
When I compile, of course I get "Line 2:27: 'Router' is defined but never used no-unused-vars"
Why is this? Or does anyone have any insight?
```jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import HomePage from './HomePage';
import PlanTripPage from './PlanTripPage';
import NavBar from './NavBar';
import ItineraryPage from './ItineraryPage';
import './App.css';
function App() {
return (
<div>
<NavBar />
<Routes>
<Route exact path="/" element={<HomePage />} />
<Route path="/plan-trip" element={<PlanTripPage />} />
<Route path="/itinerary" element={<ItineraryPage />} />
</Routes>
</div>
);
}
export default App;
```
Here is my index file.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
```
|
What should i use Exceptions or Monads for handle if service occur a problem? |
|c#|exception|monads| |
null |
I write code for the ESP32 microcontroller.
I set up a class named "dmhWebServer".
This is the call to initiate my classes:
An object of the dmhFS class is created and I give it to the constructor of the dmhWebServer class by reference.
```
#include <dmhFS.h>
#include <dmhNetwork.h>
#include <dmhWebServer.h>
void setup()
{
// initialize filesystems
dmhFS fileSystem = dmhFS(SCK, MISO, MOSI, CS); // compiler is happy I have an object now
// initialize Activate Busy Handshake
dmhActivateBusy activateBusy = dmhActivateBusy();
// initialize webserver
dmhWebServer webServer(fileSystem, activateBusy); // compiler also happy (call by reference)
}
```
The class dmhFS has a custom constructor (header file, all good in here):
```
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#include <LittleFS.h>
#include <dmhPinlist.h>
#ifndef DMHFS_H_
#define DMHFS_H_
class dmhFS
{
private:
// serial peripheral interface
SPIClass spi;
String readFile(fs::FS &fs, const char *path);
void writeFile(fs::FS &fs, const char *path, const char *message);
void appendFile(fs::FS &fs, const char *path, const char *message);
void listDir(fs::FS &fs, const char *dirname, uint8_t levels);
public:
dmhFS(uint16_t sck, uint16_t miso, uint16_t mosi, uint16_t ss);
void writeToSDCard();
void saveData(std::string fileName, std::string contents);
String readFileSDCard(std::string fileName);
};
#endif
```
Header file of the dmhWebServer class (not the whole thing):
```
public:
dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake);
};
```
This is the constructor of the dmhWebServer class:
```
#include <dmhWebServer.h>
#include <dmhFS.h>
#include <dmhActivateBusy.h>
// This is the line where the compiler throws an error ,character 85 is ")"
dmhWebServer::dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake)
{
// webserver sites handlers
setupHandlers();
dmhActivateBusy abh = activateBusyHandshake;
dmhFS sharedFileSystem = fileSystem;
// start web server, object "server" is instantiated as private member in header file
server.begin();
}
```
My compiler says: "src/dmhWebServer.cpp:5:85: error: no matching function for call to 'dmhFS::dmhFS()'"
Line 5:85 is at the end of the constructor function declaration
This is my first question on stackoverflow since only lurking around here :) I try to clarify if something is not alright with the question.
I checked that I do the call by reference in c++ right. I am giving the constructor "dmhWebServer" what he wants. What is the problem here? |
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
I want to open a file for reading and writing if it exists, or if not, create it and open it for writing.
The following code
```
FILE *file = fopen(argv[file_position], "r+");
if (!file)
file = fopen(argv[file_position], "w");
```
causes the error `file_name: Bad file descriptor`.
What is the cause of the error and how to avoid it? |
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
I have a table in which I want to show the names of columns which contain unique values and aren't null. In other words I want to display the candidate keys from the table. Note that while creating the table, the UNIQUE or NOT NULL constraint may or may not have been provided for the required columns.
My thought process was to somehow check if `COUNT(DISTINCT columnn_name) = COUNT(*)' for every column in the table, and print the column names for which the condition is true. But I don't know how to write this in a query.
Any help is appreciated, thanks!
EDIT: This is a homework question. The question just showed us a table and told us to identify potential candidate keys in the table using a query. The reason I want to do it dynamically/automatically is that if I do the count=count for every column and then manually see which ones it is true for, I might as well just see which columns are distinct and not null, which makes this approach seem wrong. |
I'm asking how are labels managed by C.
EX:
if (false)
label: printf("HELLO ");
printf("WORLD ");
goto label;
Prints WORLD HELLO on GCC
is it undefined behavior? (the label definition isn't handled as an instruction by the compiler)
Otherweise I'd expect some kind of error like "encountered undefined label" |
C6067 and other warnings with numbers 6000+ are Code Analysis warnings and are not associated with the compiler warnings.
As suggested in the comments, [`/analyze /analyze:external-`](https://learn.microsoft.com/en-us/cpp/build/reference/analyze-code-analysis?view=msvc-170) enables Code Analysis warnings in your files only while compiling.
|
The easiest way is to use the index of the rows you need:
ids=which(df$Hospital %in% c('Other', 'Missing', 'Total') #which rows should be at the bottom of a dataframe
df2=df[ids,] # create temporaty dataframe with this rows only;
df=df[-c(ids),] #remove them from your dataframe
df=rbind(df,df2) # append this rows to the bottom.
|
I had a similar issue in the past when working on my localhost database. The solution was to set the manual proxy configuration of the Android emulator.
https://i.stack.imgur.com/LWsvG.png
You must write your own localhost address in hostname field. |
Labels are neither instructions or constants. They are there own construct. However, a label can only be *applied* to a statement.
The syntax for a **labled statement** is specified in section 6.8.1p1 of the C standard as follows:
> *labeled-statement:*
> - *identifier* : *statement*
> - `case` *constant-expression* : *statement*
> - `default` : *statement*
In the above, the "identifier" in the first case is a named label. Labels have their own namespace separate from struct/union tags, members, or other identifiers. Labels also have *function scope*, meaning they can be used anywhere in the function where they are defined.
So your example (as well as the ones you deleted) are all valid because labels have function scope. |
I have some named ranges in an excel file which I need to merge. The column names vary but most have DATE and Code. I cannot put them as tables in excel, they need to remain as a named range as I don't want to risk excel filling columns down with formulas. The problem is the headers need to be extracted as technically it's the second row.
Anyhow, I have got as far as expanding the tables but I've not been able to align the columns from the different tables. To explain below is where I've got to (commas are the delimeters)
Step: #"Recorder Columns":
name, content
Events1, table
Events2, table
Table for Events1 consists of this data:
Column1, Column2, Column3, Column4
DATE, FIRST NAME, SURNAME, CODE
1/2/24, John, Smith, 3
Table for Events2 consists of this data:
Column1, Column2, Column3
DATE, FULL NAME, CODE
1/3/24, Peter Smith, 2
I want to merge both tables. I need to ignore the first row as the headers are the second row. The end result needs to look like the below.
Name, DATE, FIRST NAME, SURNAME, FULL NAME, CODE
Events1, 1/2/24, John, Smith, null, null, 3
Events2, 1/3/24, null, null, Peter Smith, 2
In reality there are many more tables, all headers are guarantied row 2 and they will have DATE, CODE but all the other fields may vary and the order may be different
This is the code so far which expands all the data from the tables but I've failed to work out how to get the headers and then merge / align them all.
```
let
Source = Excel.CurrentWorkbook(),
#"Merged Queries" = Table.NestedJoin(Source, {"Name"}, Events_List, {"NamedRanges"}, "Events_List", JoinKind.Inner),
#"Removed Columns" = Table.RemoveColumns(#"Merged Queries", {"Events_List"}),
#"Reordered Columns" = Table.ReorderColumns(#"Removed Columns", {"Name", "Content"}),
// Expand the "Content" column to reveal the tables
ExpandContent = Table.ExpandTableColumn(#"Reordered Columns", "Content", Table.ColumnNames(#"Reordered Columns"[Content]{0}))
in
ExpandContent
```
That delivers:
Name, Column1, Column2, Column3, Column4
Events1, DATE, FIRST NAME, SURNAME, Code
Events1, 1/2/24, John, Smith, 3
Events2, DATE, FULL NAME, CODE
Events2, 1/3/24, Peter Smith, 2
as mentioned above I need to get to
Name, DATE, FIRST NAME, SURNAME, FULL NAME, CODE
Events1, 1/2/24, John, Smith, null, null, 3
Events2, 1/3/24, null, null, Peter Smith, 2
Thanks for any guidance. |
how to draw this curve on bottom navigation using flutter I don know to how make it with flutter I know to make bottom navigation bar but this curve no idea I hope some advise there is the image I hope some tutorial
[enter image description here](https://i.stack.imgur.com/P8zeG.png)
|
how to draw this curve on bottom navigation |
|flutter| |
null |
The existing code renders. However, when I remove `Router` from line 2 as an import, even though it's not being used, it breaks.
*Correction: The page still renders when I remove Router. However, it just displays a blank page. When I inspect it, I no longer get anything in the **div id="root"** tags.*
When I compile, of course I get "Line 2:27: 'Router' is defined but never used no-unused-vars"
Why is this? Or does anyone have any insight?
```jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import HomePage from './HomePage';
import PlanTripPage from './PlanTripPage';
import NavBar from './NavBar';
import ItineraryPage from './ItineraryPage';
import './App.css';
function App() {
return (
<div>
<NavBar />
<Routes>
<Route exact path="/" element={<HomePage />} />
<Route path="/plan-trip" element={<PlanTripPage />} />
<Route path="/itinerary" element={<ItineraryPage />} />
</Routes>
</div>
);
}
export default App;
```
Here is my index file.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
```
|
A better solution would be to call this function after scanning and before calling another activity :
public void stopEmdkManager(){
if (this.emdkManager != null) {
this.emdkManager.release();
this.emdkManager = null;
}
} |
{"Voters":[{"Id":1431720,"DisplayName":"Robert"},{"Id":354577,"DisplayName":"Chris"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[18]} |
{"Voters":[{"Id":20287183,"DisplayName":"HangarRash"},{"Id":354577,"DisplayName":"Chris"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[18]} |
{"Voters":[{"Id":2864275,"DisplayName":"Iłya Bursov"},{"Id":9095551,"DisplayName":"Beppe C"},{"Id":2275490,"DisplayName":"Vickel"}],"SiteSpecificCloseReasonIds":[16]} |
1. Can we use interfaces in DDD Domain Modelling(if Possible is it advisable)?
The reason why I was asking is that I was trying to find the best way to model the data below.
The backstory is that in my App I need to communicate with Different renderers one renderer I am sending data over TCP and in the other I am writing data to a File.
Is it good practice to have different types of Objects In a collection in Json? Or would be better to Split the Data of One Json with the ID and Type I would then make another trip to the database/API using the Id from the first json so that I can get all the 'rendererDatas'.
If the below Json is up to standard what's the best way to model this in DDD?
[
{
"id": "859b6427-a84a-4ac7-1234-21864cf46c86",
"name": "string",
"description": "string",
"rendererDatas": [
{
"id": "ea0e7e36-ffe0-6543-83f0-23d46968b2aa",
"name": "string",
"DataType": "Viz",
"description": "string",
"IPAddress": "123.123.123",
"rendererAttributes": [{"FirstName": "John", "Number": "8"}]
},
{
"id": "ea0e7e36-6543-6543-83f0-23d46968b2aa",
"name": "string",
"DataType": "Ventuz",
"description": "string",
"FilePath": "C:\Data",
"Payload": "Json payload with Firstname and Number"
}
]
}
] |
Getting error number 3464 data type mismatch in ms access vba |
|sql|vba|ms-access| |
Your second attempt is fairly close, but you need to create a *separate* `XMLHttpRequest` object for *each* request, within the inline-invoked function expression, see the relocated line with the `***` comment:
```
var idArray = ['1', '2', '3', '4', '5'];
for(var i = 0;i < idArray.length;i++) {
(function(i) {
var xhr = new XMLHttpRequest(); // ***
xhr.open('PUT', 'https://www.example.com/url/' + idArray[i]);
xhr.setRequestHeader('Authorization', authorizationToken);
xhr.send(null);
var test = setInterval(function () {
if(xhr.readyState != 4) {
//someCode
} else {
clearInterval(test);
}
}, 1000);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status != 200) {
//someCode
}
}
}
})(i);
}
```
Technically, since you don't use `i` anywhere in the callbacks you're creating in there, you don't need to pass `i` in and take it as a parameter to the IIFE (but with that ES5-level syntax, you do need the IIFE so that you have separate `xhr`s).
In ES2015+, there's no need for the IIFE anymore, just use `let` and `const`:
```
const idArray = ["1", "2", "3", "4", "5"];
for (const id of idArray) {
const xhr = new XMLHttpRequest();
xhr.open("PUT", "https://www.example.com/url/" + id);
xhr.setRequestHeader("Authorization", authorizationToken);
xhr.send(null);
const test = setInterval(() => {
if (xhr.readyState !== 4) {
//someCode
} else {
clearInterval(test);
}
}, 1000);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status !== 200) {
//someCode
}
}
};
}
```
These days I'd probably use [`fetch`][1] instead of XHR as well.
----
Side note: Not sure what the interval timer is for there, so I've left it, but your `onreadystatechange` handler *will* get called, no need to back it up with a timer.
[1]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
|
Setting track color doesn't seem to be supported by SwiftUI yet.
Here's a solution using `UIViewRepresentable`
```
struct ClearTrackProgressView: UIViewRepresentable {
let value: Float
let animated: Bool
func makeUIView(context: Context) -> UIProgressView {
let progressView = UIProgressView()
progressView.trackTintColor = .clear
return progressView
}
func updateUIView(_ uiView: UIProgressView, context: Context) {
uiView.setProgress(value, animated: animated)
}
}
```
Note: I added `animated` to control the animation. You can remove it if you don't need it. |
Sort the intervals, once by start point, once by end point.
Now, given an interval, perform a binary search using the start point in the intervals sorted by end point. The index you get tells you how many non-overlapping intervals come before: All intervals that end before your interval starts are non-overlapping.
Do the same for the end point: Do a binary search in the array of intervals sorted by start point. All intervals that start after your interval ends are non-overlapping.
All other intervals either start before your interval ends, but after it has started, or end after your interval starts, but start before it.
Do this for every interval, sum the results. Make sure to halve, to not count intervals twice. This looks as follows:
Overall you get O(n log n): Two sorts, O(n) times two O(log n) binary searches.
Now observe that half of this is not even needed - if A and B are two non-overlapping intervals, it suffices if B counts the intervals before it, including A; A doesn't need to count the intervals after it. This lets us simplify the solution further; you just need to sort the end points to be able to count the intervals before an interval, and of course we now don't need to halve the resulting sum anymore:
```python
# Counting the intervals before suffices
def count_non_overlapping_pairs(intervals):
ends = sorted(interval[1] for interval in intervals)
def count_before(interval):
return bisect_left(ends, interval[0])
return sum(map(count_before, intervals))
```
(Symmetrically, you could also just count the intervals after an interval.) |
I write code for the ESP32 microcontroller.
I set up a class named "dmhWebServer".
This is the call to initiate my classes:
An object of the dmhFS class is created and I give it to the constructor of the dmhWebServer class by reference. For my error see the last code block that I posted. The other code block could explain the way to where the error shows up.
```
#include <dmhFS.h>
#include <dmhNetwork.h>
#include <dmhWebServer.h>
void setup()
{
// initialize filesystems
dmhFS fileSystem = dmhFS(SCK, MISO, MOSI, CS); // compiler is happy I have an object now
// initialize Activate Busy Handshake
dmhActivateBusy activateBusy = dmhActivateBusy();
// initialize webserver
dmhWebServer webServer(fileSystem, activateBusy); // compiler also happy (call by reference)
}
```
The class dmhFS has a custom constructor (header file, all good in here):
```
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#include <LittleFS.h>
#include <dmhPinlist.h>
#ifndef DMHFS_H_
#define DMHFS_H_
class dmhFS
{
private:
// serial peripheral interface
SPIClass spi;
String readFile(fs::FS &fs, const char *path);
void writeFile(fs::FS &fs, const char *path, const char *message);
void appendFile(fs::FS &fs, const char *path, const char *message);
void listDir(fs::FS &fs, const char *dirname, uint8_t levels);
public:
dmhFS(uint16_t sck, uint16_t miso, uint16_t mosi, uint16_t ss);
void writeToSDCard();
void saveData(std::string fileName, std::string contents);
String readFileSDCard(std::string fileName);
};
#endif
```
Header file of the dmhWebServer class (not the whole thing):
```
public:
dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake);
};
```
This is the constructor of the dmhWebServer class:
```
#include <dmhWebServer.h>
#include <dmhFS.h>
#include <dmhActivateBusy.h>
// This is the line where the compiler throws an error ,character 85 is ")"
dmhWebServer::dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake)
{
// webserver sites handlers
setupHandlers();
dmhActivateBusy abh = activateBusyHandshake;
dmhFS sharedFileSystem = fileSystem;
// start web server, object "server" is instantiated as private member in header file
server.begin();
}
```
My compiler says: "src/dmhWebServer.cpp:5:85: error: no matching function for call to 'dmhFS::dmhFS()'"
Line 5:85 is at the end of the constructor function declaration
This is my first question on stackoverflow since only lurking around here :) I try to clarify if something is not alright with the question.
I checked that I do the call by reference in c++ right. I am giving the constructor "dmhWebServer" what he wants. What is the problem here? |
Yes, the answer was the access token all along, i made another access token(classic) but which is for repo---full control of private repositories---, i know it's stupid, it took me 2 hours to know this. |
Future<String> deleteDbCreateDbDirectory() async {
final databasePath = await getDatabasesPath();
final path = join(databasePath, "you_db_name");
// make sure the folder exists
// ignore: avoid_slow_async_io
if (await Directory(dirname(path)).exists()) {
await deleteDatabase(path);
await File(path).delete();
} else {
try {
await Directory(dirname(path)).create(recursive: true);
} catch (e) {
// ignore: avoid_print
//print(e);
}
}
////print("path: $path");
return path;
}
**Based on sqlite** |
How to use Interfaces in Domain Modelling DDD |
|domain-driven-design| |
I want to make a brick breaking game with Arduino. I want the ball to break and bounce whichever brick it hits above, but this does not happen with the code I wrote, where is my mistake?
```
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET 4
#define potPin A0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int paletBas = SCREEN_WIDTH / 2;
int paletBas_e = SCREEN_WIDTH / 2;
int palet_g = 20;
int palet_y = 4;
int topBoyut = 2;
int topX = SCREEN_WIDTH / 2;
int topX_e = SCREEN_WIDTH / 2;
int topY = SCREEN_HEIGHT - 25;
int topY_e = SCREEN_HEIGHT - 25;
int topDX = 1;
int topDY = -1;
int tugla_g = 12;
int tugla_y = 5;
int toplamTugla = SCREEN_WIDTH / (tugla_g + 2);
int t_Sira = 3;
bool tugla[3][20];
boolean game = true;
void setup()
{
Serial.begin(9600);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
tuglaVar();
}
void loop()
{
if(game)
{
tuglaCiz();
paletCiz();
topCiz();
paletHareket();
topHareket();
boolean palet_kontrol = paletKontrol();
boolean tugla_kontrol = tuglaKontrol();
if(tugla_kontrol)
{
tuglaCiz();
}
}
}
void tuglaVar()
{
for (int i = 0; i < t_Sira; i++) {
for (int j = 0; j < toplamTugla; j++) {
tugla[i][j] = true;
}
}
}
boolean tuglaKontrol()
{
int topSol = topX - topBoyut; // Topun sol koordinatı
int topSag = topX + topBoyut; // Topun sağ koordinatı
int topUst = topY - topBoyut; // Topun üst koordinatı
int topAlt = topY + topBoyut; // Topun alt koordinatı
for (int i = 0; i < t_Sira; i++) {
for (int j = 0; j < toplamTugla; j++) {
if (tugla[i][j]) {
int tuglaX = j * (tugla_g + 2);
int tuglaY = i * (tugla_y + 2);
if(topAlt >= tuglaY && topUst <= tuglaY + tugla_g){
if(topSag >= tuglaX && topSol <= tuglaX + tugla_y){
tugla[i][j] = false;
topDY = -topDY;
return true;
}
}
}
}
}
return false; // Çarpışma olmadığını bildir
}
void tuglaCiz()
{
for (int i = 0; i < t_Sira; i++) {
for (int j = 0; j < toplamTugla; j++) {
int tuglaX;
int tuglaY;
if (tugla[i][j]) {
tuglaX = j * (tugla_g + 2);
tuglaY = i * (tugla_y + 2);
display.fillRect(tuglaX, tuglaY, tugla_g, tugla_y, WHITE);
}
else{
display.fillRect(tuglaX, tuglaY, tugla_g, tugla_y, BLACK);
}
}
}
display.display();
}
void paletHareket()
{
int potValue = analogRead(potPin);
paletBas_e = paletBas;
paletBas = map(potValue, 0, 1023, 0, SCREEN_WIDTH - palet_g);
}
boolean paletKontrol()
{
if (topX >= paletBas && topX <= paletBas + palet_g && topY >= SCREEN_HEIGHT - 8 - topBoyut) {
topDY = -topDY; // Palete çarptığında yön değiştir
return true;
}
return false;
}
void paletCiz()
{
display.fillRect(paletBas_e, SCREEN_HEIGHT - 8, palet_g, palet_y, BLACK);
display.fillRect(paletBas, SCREEN_HEIGHT - 8, palet_g, palet_y, WHITE);
}
void topHareket()
{
topX_e = topX;
topY_e = topY;
topX += topDX; // Topu sağa doğru hareket ettir
topY += topDY; // Topu yukarıya doğru hareket ettir
if (topX >= SCREEN_WIDTH - topBoyut || topX <= topBoyut) {
topDX = -topDX; // Duvarlara çarpınca yön değiştir
}
if (topY <= topBoyut) {
topDY = -topDY; // Tavana çarpınca yön değiştir
}
}
void topCiz()
{
display.fillCircle(topX_e, topY_e, topBoyut, BLACK);
display.fillCircle(topX, topY, topBoyut, WHITE);
}
```
I want to make a brick breaking game with Arduino. I want the ball to break and bounce whichever brick it hits above, but this does not happen with the code I wrote, where is my mistake? |
Power Query / M Code, extract a list of tables into one main table, some column headers same but some different and in different order (and in row 2) |
|excel|append|powerquery|named-ranges| |
To manage and print the grid you'll want to use a 2d list. Additionally you should store the battleship alphabet as one string instead of a list of characters, and you don't need to be case specific. Also you should take input 1-10 and not 0-9 because the game uses 1-10 and not 0-9 like normal list indices.
turns = 10
alphabet = "ABCDEFGHIJ"
def create_grid():
return [[" # " for _ in range(10)] for _ in range(10)]
def print_grid(grid):
print(" " + " ".join(alphabet))
for i, row in enumerate(grid, start=1):
print(f"{i: >2} " + "".join(row))
print("\n")
def get_user_choice():
rowx = input("Choose a letter (A-J): ").upper()
rowy = input("Enter a number (1-10): ")
return rowx, rowy
def is_valid_choice(rowx, rowy):
return rowx in alphabet and rowy.isdigit() and 1 <= int(rowy) <= 10
def update_grid(grid, rowx, rowy):
x = alphabet.index(rowx)
y = int(rowy) - 1 # Adjust for 0-indexed grid
if grid[y][x] == " # ":
grid[y][x] = " X "
return True
return False
def game_screen():
grid = create_grid()
print_grid(grid)
while True:
rowx, rowy = get_user_choice()
if is_valid_choice(rowx, rowy) and update_grid(grid, rowx, rowy):
print(f"You chose {rowx}{rowy}")
print_grid(grid)
else:
print("Please choose a valid point (A-J/1-10) or an unchosen cell.\n")
game_screen()
|
As the detailed analysis of the issues with your code is given in the answer by *trincot*, this supplementary response tries to simplify the explanation and provides along with an example of binary tree to traverse also more details about the approach using the logical operators `and` and `or` which in Python don't return True/False as value but a value of one of the components of the expression.
**The actual root of the issue you describe is to expect that the initial call of the traverse function will return you the found node** except the case of the root node where there is no recursion. **This does not work as expected because in your code the values returned by the deeper level recursion function calls simply go nowhere** and don't propagate upwards to the calling function.
Notice that the code in your question *always* traverses the entire tree. I have adjusted it a bit to stop further search at the found node and solved also the issue of not returning the found node using a global variable, which is in my eyes a simpler to understand approach than smart usage of the return values as suggested by *trincot*.
Further explanations are provided as comments in the code below:
```
import collections
foundNode=None
def inorderTraversal1(node, tval):
global foundNode
if node is not None and foundNode is None:
print( node.val )
if(node.val==tval):
print("nodeValue = ", node.val)
print("nodeType", type(node))
foundNode=node
else: # the node has other node.val as tval, so check its sub-nodes:
inorderTraversal1(node.left,tval)
if foundNode is None:
inorderTraversal1(node.right,tval)
def inorderTraversal2( root, tval ):
return root and (
# NOTICE that logical and does not return True/False but the first component
# which evaluates to False, or the last component if all evaluate to True
root if root.val == tval else (
inorderTraversal2(root.left, tval)
or
inorderTraversal2(root.right,tval)
# NOTICE that logical or does not return True/False but the first item
# which evaluates to True, or the last item if all evaluate to False
)
)
BTnode = collections.namedtuple('BTnode', ['left', 'right', 'val'])
root=BTnode( val='0',
left=BTnode( val='01',
left=BTnode( val='011',
left=BTnode( val='0111', left=None, right=None ),
right=BTnode( val='0112',
left=BTnode(val='01121', left=None, right=None ),
right=BTnode( val='01122', left=None, right=None )
)
),
right=BTnode( val='012', left=None, right=None )
),
right=BTnode( val='02',
left=BTnode( val='021', left=None, right=None ),
right=BTnode( val='022', left=None, right=None )
)
)
foundNode=None; inorderTraversal1(root, '022') # !!! WATCH OUT !!!
# ^-- initialize `foundNode=None` in front of every call
# of `inorderTraversal1()`
print(foundNode)
print( " ----- " )
print( inorderTraversal2(root, '022') )
print("===============")
foundNode=None; inorderTraversal1(root, '01122')
print(foundNode)
print( " ----- " )
print( inorderTraversal2(root, '01122') )
```
which outputs:
```
> cd /home/o/oOo/O@@/stackoverflow
> python3 -u "BTree.py"
0
01
011
0111
0112
01121
01122
012
02
021
022
nodeValue = 022
nodeType <class '__main__.BTnode'>
BTnode(left=None, right=None, val='022')
-----
BTnode(left=None, right=None, val='022')
===============
0
01
011
0111
0112
01121
01122
nodeValue = 01122
nodeType <class '__main__.BTnode'>
BTnode(left=None, right=None, val='01122')
-----
BTnode(left=None, right=None, val='01122')
> exit status: 0
``` |
Coding a two-dimensional, dynamically allocated array of `int` is a non-trivial task. If you use a _double pointer_, there are significant memory allocation details. In particular, you need to check every allocation attempt, and, if any one fails, back out of the ones that didn't fail, without leaking memory. And, finally, to take a term from the C++ lexicon, you need to provide some equivalent of the _Rule of Three_ functions used by a C++ _RAII_ class.
A two-dimensional array of `int` with `n_rows` and `n_cols` should probably be allocated with a single call to `malloc`. For the program in the OP, you might have:
```lang-c
char *str = "1255555555555555";
const size_t n_rows = strlen(str);
const size_t n_cols = 2;
int (*data)[n_cols] = malloc(n_rows * sizeof (*data));
```
Variable `data` is a _pointer to an array of 2 `int`s_, i.e., it is a pointer to a row in the OP's two-dimensional array. `sizeof(*data)`, therefore, is the size of one row. Multiplying by `n_rows` gives you the size of the entire array, which is the size allocated by `malloc`. So, `malloc` allocates the entire array, and variable `data` picks up a pointer to the first row.
See this [Stack Overflow question](https://stackoverflow.com/q/36794202/22193627) for an fuller explanation of this C idiom.
The program in the OP, however, does not use this idiom. It takes the _double pointer_ route, and allocates an _array of pointers to int_. The elements in such an array are `int*`. Thus, the array is an _array of pointers to rows_, where each row is an _array of `int`_. The argument to the `sizeof` operator, therefore, must be `int*`.
```lang-c
int** data = malloc(n_rows * sizeof (int*)); // step 1.
```
Afterwards, you run a loop to allocate the columns of each row. Conceptually, each row is an array of `int`, with `malloc` returning a pointer to the first element of each row.
```lang-c
for (size_t r = 0; r < n_rows; ++r)
data[r] = malloc(n_cols * sizeof int); // step 2.
```
The program in the OP errs in step 1.
```lang-c
// from the OP:
ret = (int **)malloc(sizeof(int) * len); // should be sizeof(int*)
```
Taking guidance from the [answer by @Eric Postpischil](https://stackoverflow.com/a/78248309/22193627), this can be coded as:
```lang-c
int** ret = malloc(len * sizeof *ret);
```
The program below, however, uses (the equivalent of):
```lang-c
int** ret = malloc(len * sizeof(int*));
```
#### Fixing memory leaks
The program in the OP is careful to check each call to `malloc`, and abort the allocation process if any one of them fails. After a failure, however, it does not call `free` to release the allocations that were successful. Potentially, therefore, it leaks memory. It should keep track of the row where a failure occurs, and call `free` on the preceding rows. It should also call `free` on the original array of pointers.
There is enough detail to warrant refactoring the code to create a separate header with functions to manage a two-dimensional array. This separates the business of array management from the application itself.
Header `tbx.int_array2D.h`, defined below, provides the following functions.
- _Struct_ – `struct int_array2D_t` holds a `data` pointer, along with variables for `n_rows` and `n_cols`.
- _Make_ – Function `make_int_array2D` handles allocations, and returns a `struct int_array2D_t` object.
- _Free_ – Function `free_int_array2D` handles deallocations.
- _Clone_ – Function `clone_int_array2D` returns a _deep copy_ of a `struct int_array2D_t` object. It can be used in initialization expressions, but, in general, should not be used for assignments.
- _Swap_ – Function `swap_int_array2D` swaps two `int_array2D_t` objects.
- _Copy assign_ – Function `copy_assign_int_array2D` replaces an existing `int_array2D_t` object with a _deep copy_ of another. It performs allocation and deallocation, as needed.
- _Move assign_ – Function `move_assign_int_array2D` deallocates an existing `int_array2D_t` object, and replaces it with a _shallow copy_ of another. After assignment, it zeros-out the source.
- _Equals_ – Function `equals_int_array2D` performs a _deep comparison_ of two `int_array2D_t` objects, returning `1` when they are equal, and `0`, otherwise.
```lang-c
#pragma once
// tbx.int_array2D.h
#include <stddef.h>
struct int_array2D_t
{
int** data;
size_t n_rows;
size_t n_cols;
};
void free_int_array2D(
struct int_array2D_t* a);
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols);
struct int_array2D_t clone_int_array2D(
const struct int_array2D_t* a);
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b);
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b);
// end file: tbx.int_array2D.h
```
#### A trivial application
With these functions, code for the application becomes almost trivial.
I am not sure why the OP wrote his own version of `strlen`, but I went with it, changing only the type of its return value.
```lang-c
// main.c
#include <stddef.h>
#include <stdio.h>
#include "tbx.int_array2D.h"
size_t ft_strlen(char* str)
{
size_t count = 0;
while (*str++)
count++;
return (count);
}
struct int_array2D_t parray(char* str)
{
size_t len = ft_strlen(str);
struct int_array2D_t ret = make_int_array2D(len, 2);
for (size_t r = ret.n_rows; r--;) {
ret.data[r][0] = str[r] - '0';
ret.data[r][1] = (int)(len - 1 - r);
}
return ret;
}
int main()
{
char* str = "1255555555555555";
struct int_array2D_t ret = parray(str);
for (size_t r = 0; r < ret.n_rows; ++r) {
printf("%d %d \n", ret.data[r][0], ret.data[r][1]);
}
free_int_array2D(&ret);
}
// end file: main.c
```
#### Source code for `tbx.int_array2D.c`
Function `free_int_array2D` has been designed so that it can be used for the normal deallocation of an array, such as happens in function `main`, and also so that it can be called from function `make_int_array2D`, when an allocation fails.
Either way, it sets the `data` pointer to `NULL`, and both `n_rows` and `n_cols` to zero. Applications that use header `tbx.int_array2D.h` can check the `data` pointer of objects returned by functions `make_int_array2D`, `clone_int_array2D`, and `copy_assign_int_array2D`. If it is `NULL`, then the allocation failed.
```lang-c
// tbx.int_array2D.c
#include <stddef.h>
#include <stdlib.h>
#include "tbx.int_array2D.h"
//======================================================================
// free_int_array2D
//======================================================================
void free_int_array2D(struct int_array2D_t* a)
{
for (size_t r = a->n_rows; r--;)
free(a->data[r]);
free(a->data);
a->data = NULL;
a->n_rows = 0;
a->n_cols = 0;
}
//======================================================================
// make_int_array2D
//======================================================================
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols)
{
struct int_array2D_t a = {
malloc(n_rows * sizeof(int*)),
n_rows,
n_cols
};
if (!n_rows || !n_cols)
{
// If size is zero, the behavior of malloc is implementation-
// defined. For example, a null pointer may be returned.
// Alternatively, a non-null pointer may be returned; but such
// a pointer should not be dereferenced, and should be passed
// to free to avoid memory leaks. – CppReference
// https://en.cppreference.com/w/c/memory/malloc
free(a.data);
a.data = NULL;
a.n_rows = 0;
a.n_cols = 0;
}
else if (a.data == NULL) {
a.n_rows = 0;
a.n_cols = 0;
}
else {
for (size_t r = 0; r < n_rows; ++r) {
a.data[r] = malloc(n_cols * sizeof(int));
if (a.data[r] == NULL) {
a.n_rows = r;
free_int_array2D(&a);
break;
}
}
}
return a;
}
//======================================================================
// clone_int_array2D
//======================================================================
struct int_array2D_t clone_int_array2D(const struct int_array2D_t* a)
{
struct int_array2D_t clone = make_int_array2D(a->n_rows, a->n_cols);
for (size_t r = clone.n_rows; r--;) {
for (size_t c = clone.n_cols; c--;) {
clone.data[r][c] = a->data[r][c];
}
}
return clone;
}
//======================================================================
// swap_int_array2D
//======================================================================
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
struct int_array2D_t t = *a;
*a = *b;
*b = t;
}
//======================================================================
// copy_assign_int_array2D
//======================================================================
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->data != b->data) {
if (a->n_rows != b->n_rows || a->n_cols != b->n_cols) {
free_int_array2D(a);
*a = make_int_array2D(b->n_rows, b->n_cols);
}
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
a->data[r][c] = b->data[r][c];
}
}
}
}
//======================================================================
// move_assign_int_array2D
//======================================================================
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
if (a->data != b->data) {
free_int_array2D(a);
*a = *b;
b->data = NULL;
b->n_rows = 0;
b->n_cols = 0;
}
}
//======================================================================
// equals_int_array2D
//======================================================================
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->n_rows != b->n_rows ||
a->n_cols != b->n_cols) {
return 0;
}
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
if (a->data[r][c] != b->data[r][c]) {
return 0;
}
}
}
return 1;
}
// end file: tbx.int_array2D.c
```
|
`publishDir` works by emitting items in the process `output` declaration to the path provided. You haven't provided an output declaration for either process, so it doesn't think there is anything to publish.
Also, unless you're using it for checkpointing, you don't need the output from `FastQC` for `Trimmomatic`, you can get the two processes to run in parallel.
Don't use `joinPath` or any absolute path in your processes. That's not what Nextflow is designed for, and often will lead to errors. Plus, by putting an absolute path in the output declaration, you're telling the process to look in the output directory for the file generated in the process. Use `publishDir` to emit files.
The `file` operator is deprecated. Use `path` instead. The [documentation](https://www.nextflow.io/docs/latest/getstarted.html) is amazing for nextflow. It's a steep learning curve, but it's very good at describing how things work.
So here is an updated script:
```
process FastQC {
tag "Running FastQC on ${sampleid}"
publishDir {
path: "${params.fastqc_dir}/${fastq.baseName}",
move: 'move',
}
input:
tuple val(sampleid), path(fastq)
output:
path("*.html")
script:
"""
fastqc ${fastq}
"""
}
process Trimmomatic {
tag "Trimming ${sampleid}"
publishDir {
path: "${params.trimmed_dir}",
move: 'copy',
}
input:
tuple val(sampleid), path(fastq)
output:
path("*_trimmed.fastq.gz")
script:
"""
java -jar ${params.trimmomatic_jar} PE -threads 4 \
${fastq} ${sampleid}_trimmed.fastq.gz")} \
${sampleid}_unpaired.fastq.gz")} \
${sampleid}_unpaired.fastq.gz")}
"""
}
```
In the workflow, you shouldn't need to tell the processes to iterate over each element. This is the default behaviour of the tool. I've added some commands to the channel generation to highlight some redundancy you can add.
```
Channel
.fromPath(${params.fastq_dir}/*{.fastq.gz,.fq.gz,.fastq,.fq})
.map { it -> tuple( it.simpleName, it ) }
.ifEmpty { error "Cannot find any fastq files in ${params.fastq_dir}" }
.set { fastq_files }
workflow {
FastQC(fastq_files)
Trimmomatic(fastq_files)
}
```
EDIT: Missed some of the absolute paths. Updated input to be a tuple instead since it's better at handing names this way and adjusted tags. |
You cannot call React hooks outside React components or custom React hooks. I suggest moving the `useNavigate` hook call and auth state change listener into `AppRouter` and hoisting the `BrowserRouter` to the index file to wrap `AppRouter` to provide it the routing context.
Example:
App:
```jsx
import React from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import 'react-dates/lib/css/_datepicker.css';
import configureStore from "./store/configureStore";
import 'normalize.css/normalize.css';
import { startSetExpenses } from "./actions/expenses";
import './styles/styles.scss';
import AppRouter from "./routers/AppRouter";
import { auth } from './firebase/firebase';
const root = createRoot(document.getElementById("app"));
const store = configureStore();
const jsx = (
<Provider store={store}>
<BrowserRouter>
<AppRouter />
</BrowserRouter>
</Provider>
);
const loadingComponent = <div><p>Loading...</p></div>;
root.render(loadingComponent);
store.dispatch(startSetExpenses())
.then(() => {
root.render(jsx);
})
.catch((error) => {
console.error("Error fetching expenses:", error);
});
```
AppRouter:
```jsx
import React from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';
import { onAuthStateChanged } from "firebase/auth";
import LoginPage from '../components/LoginPage';
import Header from '../components/Header';
import NotFound from '../components/NotFound';
import EditExpense from '../components/EditExpense';
import AddExpense from '../components/AddExpense';
import ExpenseDashboardPage from '../components/ExpenseDashboard';
import HelpPage from '../components/HelpPage';
const AppRouter = () => {
const navigate = useNavigate();
React.useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
console.log("LoggedIN");
navigate("/dashboard");
} else {
console.log("LoggedOUT");
navigate("/");
}
});
return unsubscribe;
}, []);
return (
<>
<Header />
<Routes>
<Route path="/" element={<LoginPage />} />
<Route path="/dashboard" element={<ExpenseDashboardPage />} />
<Route path="/create" element={<AddExpense />} />
<Route path="/edit/:id" element={<EditExpense />} />
<Route path="/help" element={<HelpPage />} />
<Route path="*" element={<NotFound />} />
</Routes>
</>
);
};
export default AppRouter;
``` |
How can I break bricks? |
|arduino|arduino-uno| |
null |
Optimizing Selenium script for faster execution |
I'm trying to set up a little python script showing me e.g. my current CPU temperature. I imported psutil to do so. As mentioned in the [psutil documentation](https://psutil.readthedocs.io/en/latest/), I tried the command `psutil.sensors_temperatures(fahrenheit=False)`. Nevertheless the only output of the programme is `{}`.
Did I make a mistake or could this be a problem caused by the temperature sensor of my CPU?
Operating system: Ubuntu 22.04.4 LTS
Python version: 3.10.12
Thanks for your advices! |
psutil.sensors.temperatures() only delivers {} |
|python|ubuntu|psutil| |
null |
This is because the `key` (first argument of `useSWR`) is tied to the [cache key](https://swr.vercel.app/docs/arguments).<br>
If any value in this array is updated, a new http request will be triggered.
In your example, the key is `[SERVICESADDR.EVENT, dataToRequest]` and `dataToRequest` object is recreated at each render, that's why you get an infinite service call.
You can pass the `token` and the `id` to key and create the `FormData` object in the `fetcher` function
```
const EventDetail = ({ params }: { params: { id: string } }) => {
const id: string = params.id;
const [cookies] = useCookies(["token"]);
const token = cookies.token;
const { data, error, isLoading } = useSWR(
[SERVICESADDR.EVENT, token, id],
fetcher,
);
return <div>{id}</div>;
};
```
```
export const fetcher = ([url, token, id]: [
url: string,
token: string,
id: string
]) => {
const formData = new FormData();
formData.append("id", id);
return fetch(url, {
method: "POST",
body: formData,
headers: {
Authorization: `Bearer ${token}`,
"Accept-Language": "pt",
Accept: "/*",
},
}).then((res) => res.text());
}
``` |
After drop_na it shows 0 obs. of 68 variables:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
After drop_na I don't see any results in the Table except dates. This was not the case when I tried it before, I could see the values in the table.
```r
> library(tidyverse)
> WDI_GDP <- read_csv("C:/Users/ASYA/Desktop/P_Data_Extract_From_World_Development_Indicators/b0351889-13b3-4cbe-a5c0-a2dd9d633eab_Data.csv")
> library(tidyverse)
> WDI_GDP <- read_csv("C:/Users/ASYA/Desktop/P_Data_Extract_From_World_Development_Indicators/b0351889-13b3-4cbe-a5c0-a2dd9d633eab_Data.csv")
> WDI_GDP <- WDI_GDP %>%
+ mutate(across(contains("[YR"), ~na_if(.x,"..")) %>%
+ mutate(across(contains("[YR"), as.numeric)))
> WDI_GDP <- drop_na(WDI_GDP)
>
```
![enter image description here][4]
[1]: https://i.stack.imgur.com/oqjo8.png
[2]: https://i.stack.imgur.com/elrGR.png
[3]: https://i.stack.imgur.com/txJEv.png
[4]: https://i.stack.imgur.com/R7nfg.png |
Here is an example to break a string into multiple lines in a @dataclass for use with QT style sheets. The end of each line needs to be terminate in double quote followed by a slash, except for the last line. Indentation of the start of each line is also critical.
`@dataclass
class button_a:
i: str = "QPushButton:hover {background: qradialgradient(cx:0, cy:0, radius:1,fx:0.5,fy:0.5,stop:0 white, stop:1 green);"\
"color:qradialgradient(cx:0, cy:0, radius:1,fx:0.5,fy:0.5,stop:0 yellow, stop:1 brown);"\
"border-color: purple;}"
` |
This package doesn't support Laravel 10 and is deprecated as stated in the package's Github readme.
> This package is deprecated because all supported Laravel versions now include the CORS middleware in the core.
Check this link from the Laravel docs for info on how you can configure CORS
https://laravel.com/docs/10.x/routing#cors |
# I have this code that opens a window for a phone I want when it doesn't open that window and send me the result send ussd to fronend in react native
```
class UssdModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "UssdModule"
}
@ReactMethod
fun openUssdDialog(ussdCode: String) {
val encodedUssdCode = Uri.encode(ussdCode)
val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$encodedUssdCode"))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
currentActivity?.startActivity(intent)
}
}
``` |
ussd reader in Recket Native module |
|android|reactjs|react-native|kotlin|ussd| |
null |
Try setting DoubleBuffered property to true. DoubleBuffered is a boolean property that "gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker. Some controls in WinAPI do not expose the DoubleBuffered property. Therefore, you might have to use the **Type.InvokeMember** as I have shown in the following piece of code in which I have taken the DataGridView control as an example.
typeof(DataGridView).InvokeMember
(
"DoubleBuffered",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,
null,
myDataGridViewObject, // This is a variable of the object you are trying to set this property for.
new object[] { true }
);
The syntax of Type.InvokeMember is as follows.
public object? InvokeMember
(
string name,
System.Reflection.BindingFlags invokeAttr,
System.Reflection.Binder? binder,
object? target,
object?[]? args
);
**Do not forget to add namespaces as needed.** |
You cannot train a word2vec on a dozen tokens (words in your sentence). You need thousands to milion tokens |
I have Ionic 7, Angular, Standalone app. I am currently trying to implement linking anonymous account to registered/loggedin account.
First scenario is a user who doesn't have any registered account below. This works fine and I can see anonymous account merged with newly generated account.
const anonymousUser: User = this.auth.currentUser!
const credential = EmailAuthProvider.credential(email,password)
return linkWithCredential(anonymousUser, credential)
Problem is when this user logout and they try to log back in. When user navigates to the app after logout, we still generate anonymous credential. When we try to use above to link credential with existing user, I get following error:
> FirebaseError: Firebase: Error (auth/email-already-in-use)
How can I handle the login situation where user is trying to log back in and we want to link this to existing anonymous account? Is this even possible?
|
I have a parser written on puppeteer, where i download a file, so how to use this downloaded file in js code?
const puppeteer = require('puppeteer');
```(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: false,
args: ['--start-maximized']
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('');
await page.type('#username', '');
await page.type('#password', '');
await page.click('#loginbtn');
await page.click('.aalink.stretched-link');
setTimeout(async () => {
await browser.close();
3000);
})();```
Please help me to fix this |
How to save downloaded by parser file into js buffer? |
|javascript|puppeteer|buffer| |
null |
I have a json like
[
{
"url": "https://drive.google.com/file/d/1tO-qVknlH0PLK9CblQsyd568ZiptdKff/view?usp=share_link",
"title": "– Flexibility"
},
{
"url": "https://drive.google.com/open?id=11_sR8X13lmPcvlT3POfMW3044f3wZdra",
"title": "– Pronouns"
}
]
I got it using `curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}' | jq -s '.'`.
I have a command in my machine named `unescape_html`, a python scipt to unescape the html (replace – with appropriate character).
How can I apply this function on each of the titles using `jq`.
For example:
I want to run:
unescape_html "– Flexibility"
unescape_html "– Pronouns"
The expected output is:
[
{
"url": "https://drive.google.com/file/d/1tO-qVknlH0PLK9CblQsyd568ZiptdKff/view?usp=share_link",
"title": "– Flexibility"
},
{
"url": "https://drive.google.com/open?id=11_sR8X13lmPcvlT3POfMW3044f3wZdra",
"title": "– Pronouns"
}
]
**Update 1:**
If `jq` doesn't have that feature, then i am also fine that the command is applied on `rg`.
I mean, can i run `unescape_html` on `$2` on the line:
rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}'
Any other bash approach to solve this problem is also fine. The point is, i need to run `unescape_html` on `title`, so that i get the expected output. |
|bash|jq|ripgrep| |
I am creating a memoization example with a function that adds up / averages the elements of an array and compares it with the cached ones to retrieve them in case they are already stored.
In addition, I want to store only if the result of the function differs considerably (passes a threshold e.g. 5000 below).
I created an example using a decorator to do so, the results using the decorator is slightly slower than without the memoization which is not OK, also is the logic of the decorator correct ?
My code is attached below:
import time
import random
from collections import OrderedDict
def memoize(f):
cache = {}
def g(*args):
sum_key_arr = sum(args[0])
print(sum_key_arr)
if sum_key_arr not in cache:
for key, value in OrderedDict(sorted(cache.items())).items():# key in dict cannot be an array so I use the sum of the array as the key
if abs(sum_key_arr - key) <= 5000:#threshold is great here so that all values are approximated!
#print('approximated')
return cache[key]
else:
#print('not approximated')
cache[sum_key_arr] = f(args[0],args[1])
return cache[sum_key_arr]
return g
@memoize
def aggregate(dict_list_arr,operation):
if operation == 'avg':
return sum(dict_list_arr) / len(list(dict_list_arr))
if operation == 'sum':
return sum(dict_list_arr)
return None
t = time.time()
for i in range(200,150000):
res = aggregate(list(range(i)),'avg')
elapsed = time.time() - t
print(res)
print(elapsed)
UPDATE: I tried to involve an id key (that captues the list content) while now using a dict as input, here's below the changes made to the code:
import time
import random
from collections import OrderedDict
def memoize(f):
cache = {}
def g(*args):
key_arr = list(args[0].keys())[0]
if key_arr not in cache:
for key, value in OrderedDict(sorted(cache.items())).items():# key in dict cannot be an array so I use the sum of the array as the key
if abs(int(key_arr) - int(key)) <= 5000:#threshold is great here so that all values are approximated!
print('approximated')
return cache[key]
else:
print('not approximated')
cache[key_arr] = f(args[0])
return cache[key_arr]
return g
#@memoize
def aggregate(dict_list_arr):
#if operation == 'avg':
return sum(list(dict_list_arr.values())[0]) / len(list(dict_list_arr.values())[0])
# if operation == 'sum':
# return sum(dict_list_arr)
# None
t = time.time()
for i in range(200,15000):
res = aggregate({str(1+i):list(range(i))})
elapsed = time.time() - t
print(res)
print(elapsed)
|
Method 1:- Try to remove imports of 'dart:js_interop' as it may be imported by default in many of your project files.
Method 2:- NOTE that this import are certainly due to usage of StreamBuilder in your app , so try to use any alternative widgets to do the same work inorder to solve your problem if NOT solved by first method. . |
I have a dataframe with 55049 rows and 667 columns in it.
>Sample dataframe structure as follows:
```code Python
data = {
'g1': [1],
'g2': [2],
'g3': [3],
'st1_1': [1],
'st1_2': [1],
'st1_3': [1],
'st1_4': [1],
'st1_5': [5],
'st1_6': [5],
'st1_7': [5],
'st1_8': [5],
'st1_Next_1': [8],
'st1_Next_2': [8],
'st1_Next_3': [8],
'st1_Next_4': [8],
'st1_Next_5': [9],
'st1_Next_6': [9],
'st1_Next_7': [9],
'st1_Next_8': [9],
'st2_1': [2],
'st2_2': [2],
'st2_3': [2],
'st2_4': [2],
'st2_5': [2],
'st2_6': [2],
'st2_7': [2],
'st2_8': [2],
'ft_1': [1],
'ft_2': [0],
'ft_3': [1],
'ft_4': [1],
'ft_5': [1],
'ft_6': [0],
'ft_7': [0],
'ft_8': [1]
}
df = pd.DataFrame(data)
print(df)
```
To get my desired output I have the following code where I am using `pd.wide_to_long`
```Python code
ilist = ['g1','g2','g3']
stublist = ['st1','st1_Next','st2','ft']
df_long = pd.wide_to_long(
df.reset_index(),
i=['index']+ilist ,
stubnames= stublist,
j='j', sep='_').reset_index()
df_long = df_long[df_long['ft']==1]
```
Above code is working in fine with expected results.
> I perfromed this wide_to_long to apply the filter `df_long[df_long['ft']==1]`. which means ft_1 need to apply for all _1, ft_2 for all _2.....and so for all _8.
> Problem is to perform wide_to_long operation it took around 2 mins, Since I have 800+ source files to process the whole process is taking 1600 mins which is quite high.
I Am looking for any alternative suggestions to transpose the data.
I have Tried [this][1] but didn't work for me with much differenece.
[1]: https://github.com/pandas-dev/pandas/issues/49174
> As @sammywemmy suggested, I have tried below code. But output is missing `st1_Next`.
```python
ilist = ['g1','g2','g3']
stublist = ['st1','st1_Next','st2','ft']
df_pvot = df.pivot_longer(index=ilist,names_to=stublist,names_pattern=stublist)
print(df_pvot)
```
Output is missing st1_Next and data clubbing with st1 Instead of new column.
```
Output:
g1 g2 g3 st1 st2 ft
0 1 2 3 1 2.0 1.0
1 1 2 3 1 2.0 0.0
2 1 2 3 1 2.0 1.0
3 1 2 3 1 2.0 1.0
4 1 2 3 5 2.0 1.0
5 1 2 3 5 2.0 0.0
6 1 2 3 5 2.0 0.0
7 1 2 3 5 2.0 1.0
8 1 2 3 8 NaN NaN
9 1 2 3 8 NaN NaN
10 1 2 3 8 NaN NaN
11 1 2 3 8 NaN NaN
12 1 2 3 9 NaN NaN
13 1 2 3 9 NaN NaN
14 1 2 3 9 NaN NaN
15 1 2 3 9 NaN NaN
````
|
yea,list can't use index method directly。
should used linear search to catch 'Name' == 'Empty'。
|
```
import urequests as requests
# Google OAuth 2.0 authorization endpoint
AUTH_URI = "https://accounts.google.com/o/oauth2/auth"
# Your client ID and scope
CLIENT_ID = "220352837780-bf38n8g0vp9p13gr6j6j0vgq2q5u0996.apps.googleusercontent.com"
SCOPE = "https://www.googleapis.com/auth/calendar.readonly"
# Perform OAuth 2.0 authorization flow
def authorize():
redirect_uri = "https://sites.google.com/view/redirect-url-project3"
auth_url = "{}?client_id={}&response_type=token&scope={}&redirect_uri={}".format(AUTH_URI, CLIENT_ID, SCOPE, redirect_uri)
print("Open this URL in your browser and grant permission:", auth_url)
print(redirect_uri)
return auth_url
def extract_access_token(auth_url):
# Find the start and end index of the access token in the auth_url
start_index = auth_url.find("access_token=")
if start_index != -1:
start_index += len("access_token=")
end_index = auth_url.find("&", start_index)
if end_index == -1:
end_index = len(auth_url)
access_token = auth_url[start_index:end_index]
print("Access Token:", access_token)
return access_token
else:
print("Access token not found in redirect URI.")
return None
# Main function
def main():
auth_url = authorize()
access_token = extract_access_token(auth_url)
# Use the access token to make authenticated requests to the Google Calendar API
if access_token:
headers = {"Authorization": "Bearer " + access_token}
response = requests.get("YOUR_CALENDAR_API_ENDPOINT", headers=headers)
if response.status_code == 200:
print("Calendar API response:", response.json())
else:
print("Failed to fetch calendar events:", response.text)
if __name__ == "__main__":
main()
```
I have the redirect url set up and i am getting the access token in the redirect url, but some how in my code i am not able to get the same thing
since I am using raspberry pico W I do not have access to many libraries in micropython, I need solution to this problem |
I have a parser written on puppeteer, where i download a file, so how to use this downloaded file in js code?
```const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: false,
args: ['--start-maximized']
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('');
await page.type('#username', '');
await page.type('#password', '');
await page.click('#loginbtn');
await page.click('.aalink.stretched-link');
setTimeout(async () => {
await browser.close();
3000);
})();```
Please help me to fix this |
I have a parser written on puppeteer, where i download a file, so how to use this downloaded file in js code?
```const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: false,
args: ['--start-maximized']
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('');
await page.type('#username', '');
await page.type('#password', '');
await page.click('#loginbtn');
await page.click('.aalink.stretched-link');
setTimeout(async () => {
await browser.close();
3000);
})();
```
Please help me to fix this |
I'm attempting to recreate aspects of The Binding of Isaac in Unity (just as a learning exercise, not the entire game). I've created a script to enable Isaac to move using the WASD keys and to shoot tears with the arrow keys. While the WASD movement works perfectly, pressing the arrow keys causes Isaac to both move and shoot at the same time. Ideally, the arrow keys should only be used to fire tears and not to move Isaac. I'm seeking assistance to resolve this issue. Apologies if this seems like a simple question, and sorry for bad english
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IsaacMovements : MonoBehaviour
{
public float speed = 40f;
public Rigidbody2D projectilePrefab;
public float projectileSpeed = 10f;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component is not attached to the GameObject.");
}
}
// Update is called once per frame
void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow) ||
Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow))
{
Shoot();
}
}
void Move()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector2 movement = new Vector2(horizontalInput, verticalInput).normalized;
rb.velocity = movement * speed;
}
void Shoot()
{
if (Input.GetKey(KeyCode.LeftArrow))
Fire(Vector2.left);
else if (Input.GetKey(KeyCode.RightArrow))
Fire(Vector2.right);
else if (Input.GetKey(KeyCode.UpArrow))
Fire(Vector2.up);
else if (Input.GetKey(KeyCode.DownArrow))
Fire(Vector2.down);
}
void Fire(Vector2 direction)
{
Rigidbody2D projectileInstance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
projectileInstance.velocity = direction * projectileSpeed;
}
}
```
I tried changing the code extensively throughout the process, but nothing seemed to work. I also attempted to use different keys for shooting instead of the arrow keys, but I still didn't get the desired result. |
In order to accomplish this we would use a generic type constraint.
This is in fact how the type parameters of the language provided utility types `Parameters<T>` and `ReturnType<T>` are themselves specified and thus produce the error you receive.
In order to instantiate a generic type, say `ReturnType<T>`, with our type parameter, our type parameter must constrained at least as restrictively as the type parameter named `T` in `ReturnType<T>`.
By looking at the declaration of `ReturnType<T>`, as provided by the containing `lib` file, we can determine the minimum constraint we must apply to our own type and also find an example of the proper syntax for expressing said constraint.
type ReturnType<T extends (...args: any[]) => any> =
// details
Don't worry about the implementation (after the `=`) as that is a broader topic. In this situation, we will focus on the constraints of `T` specificied using the `extends` keyword at the declaration of `T`.
Therefore, in order to pass the `T` declared by `BoundThunk<T>` to `ReturnType<T>` we must constrain it to meet the requirements above (note that `Parameters<T>` has identical constraints).
type BoundThunk<T extends (...args: any[]) => any> =
(...args: Parameters<T>) => ReturnType<ReturnType<T>>;
However, our requirements for `T` are actually _more_ restrictive because we apply `ReturnType<T>` twice, `ReturnType<ReturnType<T>>`, implying that `T` is a higher order function, in this case a function that returns a function.
We will therefore refine our constraint accordingly
type BoundThunk<T extends (...args: any[]) => (...args: any[]) => any> =
(...args: Parameters<T>) => ReturnType<ReturnType<T>>;
Via the above adjustment, which further constrains `T` to be some function which returns another function, we allow ourselves to write `ReturnType<ReturnType<T>>`. |
I'm working on an Eclipse RCP project managed with Maven and Tycho. I've encountered a conflicting lifecycle mapping metadata error in Eclipse. The error message states:
Conflicting lifecycle mapping metadata (project packaging type="eclipse-plugin"): Mapping defined in 'org.eclipse.m2e.pde.connector_2.1.600.20240202-2240 \[693\]' and 'org.sonatype.tycho.m2e_0.10.0.20220926-1324 \[701\]'. To enable full functionality, remove the conflicting mapping and run Maven-\>Update Project Configuration. pom.xml /ecu-configurator-core line 13 Maven Project Build Lifecycle Mapping Problem
I understand this conflict is between the m2e connector for PDE and Tycho. How can I resolve this conflict, and how can I locate the \`org.eclipse.m2e.pde.connector\` plugin to consider its removal? Which plugin should be removed to fix this, and what are the implications of removing each?
Additionally, what are the specific features provided by the Eclipse PDE (Plugin Development Environment) that I might lose if I remove the m2e PDE connector? I couldn't find \`org.eclipse.m2e.pde.connector\` in the Eclipse marketplace or installed plugins list.
Any guidance or resources for resolving these lifecycle mapping conflicts would be greatly appreciated.Or how can I build a multi Eclipse plugin project. |
How to Resolve Conflicting Lifecycle Mapping in Eclipse for Tycho and PDE |
|maven|eclipse-plugin|eclipse-rcp| |
null |
i have this script on groovy. I want to generate an html file to reuse it as a variable in other steps of the workflow.
this is my script where i create the html:
```
def html = ''
execution.setVariable("note_read", "unknown")
def table = '<table style="border-width: 0px; border-image: initial; background: #d9d9d9; font: 12px Arial, sans-serif; width: 100%; height: 172px; border-color: #dddddd initial #dddddd initial; border-style: solid initial solid initial;">'
def endtable = '</table>'
def tbody = '<tbody>'
def endtbody = '</tbody>'
def riga (nomeriga, valoreriga) {
def var = '<tr style="height: 17px;">'
var = var+'<td style="padding: 3px 5px; width: 33%; vertical-align: text-top; height: 17px;">'
var = var+'<strong>'+nomeriga+'</strong> : '+valoreriga+'</td>'
var = var+'</tr>'
println "${var}
return var
}
def create_table_ambito1 () {
def t = t+table
t=t+tbody
t=t+riga('Ambito di competenza :','${so_type}')
t=t+riga('Descrizione :','${so_desc}')
t=t+riga('Ha svolto in passato un ruolo di Amministratore di Sistema Operativo?','${so_ruolop}')
if(${so_ruolop} == 'SI')
{
t=t+riga('Descrizione ruolo svolto in passato','${so_ruolopDesc}')
}
t=t+riga('Certificazioni Tecniche a supporto della richiesta :','${so_cert}')
if(${so_cert} == 'SI'){
t=t+riga('Descrizione Certificazioni Tecniche a supporto della richiesta :','${so_cert_desc}')
}
t=t+riga('Ha seguito un corso di formazione?', '${so_corsi}')
if(${so_corsi} == 'SI') {
t=t+riga('Descrizione corsi svolti','${so_corsi_desc}')
}
t=t+endtbody
t=t+endtable
println(${t}
return t
}
if(${so} == 'amm_so'){
create_table_ambito1()
html = html+create_table_ambito1()
}
execution.setVariable("note_read",html)
```
But when i run the workflow, flowable return this error:
`Caused by: javax.script.ScriptException: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.$() is applicable for argument types: (Script16$_run_closure1) values: [Script16$_run_closure1@6fd12dde]
2024-02-23 17:54:31 Possible solutions: is(java.lang.Object), any(), get(java.lang.String), any(groovy.lang.Closure), tap(groovy.lang.Closure), use([Ljava.lang.Object;)
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:164) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at java.scripting/javax.script.AbstractScriptEngine.eval(Unknown Source) ~[java.scripting:na]
2024-02-23 17:54:31 at org.flowable.common.engine.impl.scripting.ScriptingEngines.evaluate(ScriptingEngines.java:111) ~[flowable-engine-common-6.8.0.jar:6.8.0]
2024-02-23 17:54:31 ... 119 common frames omitted
2024-02-23 17:54:31 Caused by: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.$() is applicable for argument types: (Script16$_run_closure1) values: [Script16$_run_closure1@6fd12dde]
2024-02-23 17:54:31 Possible solutions: is(java.lang.Object), any(), get(java.lang.String), any(groovy.lang.Closure), tap(groovy.lang.Closure), use([Ljava.lang.Object;)
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:334) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:161) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 ... 121 common frames omitted
2024-02-23 17:54:31 Caused by: groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.$() is applicable for argument types: (Script16$_run_closure1) values: [Script16$_run_closure1@6fd12dde]
2024-02-23 17:54:31 Possible solutions: is(java.lang.Object), any(), get(java.lang.String), any(groovy.lang.Closure), tap(groovy.lang.Closure), use([Ljava.lang.Object;)
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.callGlobal(GroovyScriptEngineImpl.java:418) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.access$100(GroovyScriptEngineImpl.java:89) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl$3.invokeMethod(GroovyScriptEngineImpl.java:317) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at org.codehaus.groovy.vmplugin.v8.IndyInterface.selectMethod(IndyInterface.java:346) ~[groovy-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(IndyInterface.java:318) ~[groovy-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 at Script16.run(Script16.groovy:49) ~[na:na]
2024-02-23 17:54:31 at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:331) ~[groovy-jsr223-4.0.3.jar:4.0.3]
2024-02-23 17:54:31 ... 122 common frames omitted
2024-02-23 17:54:31`
Am i missing something or i wrote wrong any methods in Groovy? This is my first script, sorry for my english.
Am i missing something or i wrote wrong any methods in Groovy?
i've checked and tried to modify the strings like above but the error persist.
i want to assign to "html" the html generated by the script.
but this is my first script in groovy and i don't understand the error generated by flowable, sorry for my english.
|
Flowable - Groovy script evaluation failed error |
|html|groovy|flowable| |
null |
Hi all and thank you for being a part of this community.
I am working on this website
[orangecountymovers.com](https://orangecountymovers.com/) and the render delay and LCP is pretty slow. I've tried preloading elements in hero slider, signed up for siteground premium CDN, cleaned up CSS, and while it improved a bit, it's still pretty bad. Can someone chime in? Thank you!
Added CDN premium on Siteground
Added preload to hero banner elements
Removed unused CSS
|