instruction stringlengths 0 30k ⌀ |
|---|
null |
This example is not a good example, because `java.lang.NullPointerException` could be just anything - and therefore one can't even tell by such example, what the culprit or remedy to it would by. Usually one has to check for files not being checked in into version-control, if they're indeed present, which already catches most of the possible issues. |
{"OriginalQuestionIds":[12199757],"Voters":[{"Id":11082165,"DisplayName":"Brian61354270"},{"Id":12416453,"DisplayName":"Ch3steR","BindingReason":{"GoldTagBadge":"python"}}]} |
I was trying to write a table with some entries being multi-line using altair, but seem to get into trouble with fixing line spacing. For example:
```
text_df = pd.DataFrame({"a":["very very very very long thing", "very very very very very long thing"]})
text_chart_base = alt.Chart(text_df).transform_window(row_number="row_number()").transform_calculate(
y=f"split(datum.a, ' ')"
).mark_text(align="left", baseline="top"
).encode(y=alt.Y("row_number:N", axis=None, scale=alt.Scale(reverse=True)))
col1 = text_chart_base.encode(text=f"y:N")
col2= text_chart_base.encode(text=f"row_number:N")
col1 | col2
```
gives me overlapping multi-line strings
[![enter image description here][1]][1]
Instead when I make the `row_number` Quantitative with `encode(y=alt.Y("row_number:Q", axis=None, scale=alt.Scale(reverse=True)))`, I get too much space between the strings
[![enter image description here][2]][2]
Is there a way I can get `mark_text` to give the right row spacing between rows? (That is, an output something like the following)
[![enter image description here][3]][3]
[1]: https://i.stack.imgur.com/HHs64.png
[2]: https://i.stack.imgur.com/pOB0f.png
[3]: https://i.stack.imgur.com/ASyQn.png |
So I have been stumped on this for weeks now. I have a web app with this link: https://www.discovry.xyz/ and it loads fine on my own phone on wifi but not on 5G data. The error on safari is: "A server with the specified hostname could not be found". When I have been showing other people it has been hit or miss whether the app loads on their phones if the are not on wifi. The back up url: https://scheinberg.xyz/ loads fine under either circumstance. This is a nextjs app hosted on vercel.
I suspect this may be something funny from Ipv6 vs Ipv4, but the fact it loads for one domain and not the other is confounding.
Some troubleshooting steps I tried:
- removing and re-adding DNS credentials
- transferring my domain to vercel from namecheap |
My app domain does not load on some iPhones on 5G, loads fine otherwise |
|vercel|ipv6|ipv4| |
null |
When I set `multiline` to `true`, on each new line, the content get pushed up, and there is a scroll that I can't disable.
[![enter image description here][1]][1]
In the attempt to fix it, I tried to set to the height of the TextInput to the contentSize height that I get from `onContentSizeChange`, but there was a flicker on new lines.
[![enter image description here][2]][2]
the issue only happens on Android, `scrollEnabled` set to `false` seems to fix it in iOS
Do you have an ideas how can I fix it?
PS: I don't want to set fixed `height` or `maxHeight`, the height should be flexible based on the content of the input
[1]: https://i.stack.imgur.com/t3HtS.gif
[2]: https://i.stack.imgur.com/9yDb1.gif |
I can't make TextInput to auto expand properly in Android |
|android|react-native| |
I understand that a ternary conditional operator can be used to shorten the following:
```
if x > a:
y += 12
else:
y += 10
```
re-written as:
```
y += 12 if x > a else 10
```
Is there something to shorten a statement if it's just the if portion with no else?
i.e.:
```
if x > a:
y += 12
```
can be re-written as:
```
y += 12 if x > a else 0
```
due to decrementing 0 resulting in the same value as the initial value.
But I'm curious if there is an operator that doesn't add an else condition to a simple if statement with no else block. The ternary operator works in this case due to using an equivalent decrementing value of 0 vs. not changing the value in the first place, but having an equivalent operation may not always exist.
I was thinking of something similar to the idea of:
```
y += 12 if x > a
```
even though I know this is syntactically incorrect. |
I am trying to override a riverpod provider for a specifig GoRouter route.
This is my current setup and I am still getting `UnimplementedError` in the `AssessPage`
The provider I want to override
```dart
@Riverpod(dependencies: [])
AssessmentEvent currentEvent(CurrentEventRef ref) => throw UnimplementedError();
```
Creating a ProviderScope for the Page
```dart
class AssessRoute extends GoRouteData {
const AssessRoute(this.assessmentId, this.$extra);
static const path = 'assess';
final AssessmentEvent $extra;
@override
Widget build(BuildContext context, GoRouterState state) {
return ProviderScope(
overrides: [
currentEventProvider.overrideWithValue($extra),
],
child: const AssessPage(),
);
}
}
```
Navigating to the `AssessPage`
```dart
await AssessRoute(item.event).push(context);
```
|
How to override riverpod providers for a page route that has been generated with GoRouter? |
|flutter|dart|riverpod|flutter-go-router|riverpod-generator| |
As you can read in the excellent Robot Framework User Guide, [at this section][1], you can define tags at Test Suite level or at Test Case level.
For example:
```
*** Settings ***
Test Tags this_is_suite_tag
```
```
*** Test Cases ***
My Test Case
[Tags] this_is_test_tag
Log to Console This is just an example
```
To use them, you can run with the options `--include` or `--exclude`.
For example, this would work:
```
robot --include this_is_test_tag the_name_of_test_suite_file.robot
```
And this would cause an error if no other test case would be selected to run:
```
robot --exclude this_is_test_tag the_name_of_test_suite_file.robot
```
The [Robot Framework IDE (RIDE)][2] handles this tags in an easy way, and it may help in your beginner learning path.
[1]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#tagging-test-cases
[2]: https://github.com/robotframework/RIDE |
If you need to invoke an async function within interceptor then the following approach can be followed using the `rxjs` `from` operator.
```
import { MyAuth} from './myauth'
import { from, lastValueFrom } from "rxjs";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: MyAuth) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// convert promise to observable using 'from' operator
return from(this.handle(req, next))
}
async handle(req: HttpRequest<any>, next: HttpHandler) {
// if your getAuthToken() function declared as "async getAuthToken() {}"
const authToken = await this.auth.getAuthToken()
// if your getAuthToken() function declared to return an observable then you can use
// const authToken = await lastValueFrom(this.auth.getAuthToken())
const authReq = req.clone({
setHeaders: {
Authorization: authToken
}
})
return lastValueFrom(next.handle(req));
}
} |
I'm trying to get a basic Web Payments Request API demo to work. As far as I understand, a pop up should show, asking which credit card I would like to use, when I run this code:
<html>
<head>
</head>
<body>
<h1>Pay here</h1>
<script>
if(window.PaymentRequest){
alert("Payment request exists!");
const supportedPaymentMethods = [ {
supportedMethods: ["basic-card"]
}
];
const paymentDetails = {
total: {
label: "Total Cost",
amount: {
currency: "GBP",
value: 1
}
}
};
const options = {};
const paymentRequest = new PaymentRequest(
supportedMethods, paymentDetails, options
);
paymentRequest.show();
}
</script>
</body>
</html>
But not much happens. What does happen is that the alert message shows up. I'm just trying to get the basics working. I don't believe this code will send money to anyone because no account is mentioned. I hope to make the next step. Please help! |
I am getting lots of errors when building react native app in Xcode |
|xcode|react-native|npm| |
null |
I am struggling with gtsummary.
Essentially I am trying to make a table with 2 different variables, one is organism one is resistance markers.
Currently both of these variables are character variables. When I made them factor variables it made the table even worse.
I am only trying to include certain organisms which I have already assigned to a vector. As my graph currently looks it is including the correct organisms.
My problem is that there is a column which is labelled ****. This column is essentially counting the organisms without any resistance markers. Those cells in the spreadsheet are just empty.
My questions:
1. Is it possible to delete the column with ****, i think I can show the rest of the data ok without that column
2. Could i rename the column to Nil detected? I have tried to use (modify_header(**** = "**Nil detected**"). But this didnt work. I tried replacing the one entitled CPE in case it was an issue with it being special characters but that didnt help.
```
GNRs_resistance %>%
filter(Organism %in% gramnegativerods) %>%
tbl_summary(include= c(Organism, Resistance.markers),
by = Resistance.markers,
statistic = Organism ~ "{n} ({p}%)") %>%
add_overall() %>%
modify_header(all_stat_cols() ~ "**{level}**<br>n = {n}")
```
[enter image description here](https://i.stack.imgur.com/dfbzr.png) |
Struggling with gtsummary and "empty" data |
|r|gtsummary| |
null |
How to put images in your Gist URL:
1. UPLOAD your image to a site like imgur.com for free, then get the hot-link.
2. Add a file and give it a markdown extension `.md` and use markdown image syntax:
```

``` |
i have being building a telegram bot with nodejs where people can send in a url of a tweet and if it contains a media of type video. it downloads it and sends it to the user. Thats the purpose, which i already completed.
The problem i have is with setting a paywall on this bot account so that after 2 or 3 request, the user interacting with the bot have to make a payment to continue.
so i used the [sendInvoice](https://core.telegram.org/bots/api#sendinvoice) method.
FYI, i'm not using any external librarys, i'm directly interacting with the telegram api endpoints.
I'm using stripe for payments in test mode. the problem i have is as you can see this picture:
[This is whats happening/showing after some time](https://i.stack.imgur.com/Vm69E.png)
After i send the invoice, then the user clicks the pay button and adds all the necessary card details then after hitting the pay. it keeps buffering and then time outs.
I also tried the [createInvoiceLink](https://core.telegram.org/bots/api#createinvoicelink) method and the same thing happened.
Ofcourse its some mistake in my solution, but i dont know where that is. May be i have to use a webhook or something to catch the checkout initiation/completion. but how can i let the Telegram api know about my payment webhook path (assuming something like that exists).
The only one i found is the method [setWebhook](https://core.telegram.org/bots/api#setwebhook) which is an alternative approach for polling. And that is what i am doing locally with ngrok.
A Part of my code, this is an abstract version of the functionality:
```
const app = express();
const port = 3000;
const botToken = process.env.TELEGRAM_BOT_TOKEN;
app.use(bodyParser.json());
// Webhook endpoint that recieved incoming messages (exposed via ngrok)
app.post(`/bot${botToken}`, async (req, res) => {
const { message } = req.body;
console.log({ message });
if (message && message.text) {
const chatId = message.chat.id;
const messageText = message.text;
// after successfull 3 responses from the bot, send an invoice
const invoiceRes = await sendInvoice(
chatId,
"Premium Subscription",
"Unlock premium content with a subscription.",
"premium_subscription",
process.env.PROVIDER_TOKEN,
"subscription",
"USD",
[{ label: "Subscription", amount: 1000 }],
);
console.log(JSON.stringify(invoiceRes, null, 2));
}
res.status(200).end();
});
async function sendInvoice(
chatId,
title,
description,
payload,
providerToken,
startParameter,
currency,
prices,
) {
const apiUrl = `https://api.telegram.org/bot${botToken}/sendInvoice`;
const invoice = {
chat_id: chatId,
title: title,
description: description,
payload: payload,
provider_token: providerToken,
start_parameter: startParameter,
currency: currency,
prices: prices,
};
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(invoice),
});
const data = await response.json();
// console.log(data);
return data;
} catch (error) {
console.error("There was a problem sending the invoice:", error);
return error.message;
}
}
```
I googled a lot to find some answers, there isnt anything specified in the [payment section of the docs](https://core.telegram.org/bots/payments) either rather than getting the provider token (not anything specifically if i have to do on the stripe account dashboard like adding a webhook endpoint, even if that was the case how would telegram know that is the webhook it should communicate too)
I have been mentioning webhook a lot, because in my mind i am assuming that is my missing solution. if it isnt i'm sorry for doing so. I don't have much experience with stripe or building a telegram bot.
I hope i could get some help with this problem. even a small guidance will be enough if you are busy. just something i can go with that's all i ask. |
With .NET SDK you can create `ServiceBusMessageBatch`. When creating a batch, `CreateMessageBatchOptions` can be passed it to specify the maximum batch size. For example
var options = new CreateMessageBatchOptions { MaxSizeInBytes = 1_024 };
using var messageBatch = await sender.CreateMessageBatchAsync();
Will construct a batch of up to 1,024 bytes. When not specified, by default, a batch will be the maximum message size for the namespace tier used, 256KB for Standard and 100 MB for Premium. |
null |
I have a opencart 2.3 store and I have downloaded a extension that shows all products on one page, it creates a category called All and displays all products in that category.
It's working all ok but I would like to have the product filter displayed in the left column so it's the same as the other categories.
For example the category here https://www.beechwoodsolutions.co.uk/sites/simply-heavenly-foods/index.php?route=product/category&path=271 has the product filter in the left column.
On the all products category page here https://www.beechwoodsolutions.co.uk/sites/simply-heavenly-foods/index.php?route=product/category&path=-1 I would like to have the product filter displayed.
The extension I downloaded is https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=29713.
I have contacted the developer but don't think they are active anymore so was seeing if anyone was able to help please.
I think it might be to do with the following section of code but not 100% sure
foreach ($results as $result) {
if ($result['category_id']==-1)
continue;
//foreach ($results as $result) {
$filter_data = array(
'filter_category_id' => $result['category_id'],
'filter_sub_category' => true
);
$data['categories'][] = array(
'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url)
);
} |
"How to Resolve 'Could not find or load main class' Error when Running Java Code to Generate Sub-classes in Specific Directory" |
i use Quarkus 3.4.2 with Camel 4.0.0, and combo :
setHeader(xxx").xpath("exp",String.class,headerName) works.
But into Quarkus 3.8.2 with camel 4.4.0 not works ...but not deprecated information... ? |
apache camel : cxf [4.0.0 -> 4.4.0] setHeader(xxx").xpath("exp",String.class,headerName) dont work..but not deprecated indication |
|camel-cxf| |
The basic idea is to postprocess `git log --name-status` with whatever per-commit info you want and look for the first occurrence of names you're interested in. The all-of-them version:
```
git log --name-status --pretty=%ci | awk -F$'\t' '
NF==1 { stamp=$0; next }
!seen[$2]++ { print stamp,$0 }
' | sort -t$'\t' -k2,2
```
and as always season to taste. Are you running on spinning rust? I do that on the SDL default checkout with a cheap ssd it takes 0.548s, so more than a hundred times faster. But then, it's doing 1500+ times fewer walks through history so there's that. |
Need to import a file depending upon the option selected from the previous screen.
Using react-navigation to get the import details.
```
/* Taking path information from previous screen. */
const{
exam_info
} = route.params;
/* State to store the data. */
const[data,setData]=useState([]);
/* Conditionally importing. */
useEffect(() => {
if (exam_info) {
import(exam_info)
.then((dataFromDb) => {
setData(dataFromDb.default);
});
}
}, [])
```
Made sure that exam_info has the valid import path and is in STRING format.
Error: Invalid call at import statement.
When tried with explicit typed string within the same file, it works.
```
/* Taking some information from previous screen. */
const{
exam_info
} = route.params;
/* State to store the data. */
const[data,setData]=useState([]);
/* Conditionally importing database. */
useEffect(() => {
if (exam_info) {
const typedPathName = '../../database/previous_year/previous23';
const pathName = `${typedPathName}`;
import(pathName)
.then((dataFromDb) => {
setData(dataFromDb.default);
});
}
}, [])
```
The above code works, but need to import data depending on what user selects in previous screen.
Thanks in advance for any solution you can provide. |
Dynamically evaluated named import in react/javascript |
|javascript|react-native|react-hooks|react-navigation|javascript-import| |
null |
There's a [Manage limited inventory with Checkout](https://docs.stripe.com/payments/checkout/managing-limited-inventory) documentation page that explains that Stripe Checkout supports both manual and timed session expiration.
Timed session expiration must be between 30 minutes and 24 hours at the time of writing, so for your use case you'll need to manually expire the checkout session. |
I am refreshing my knowledge using Sololearn App.
I have the following code that does not run.
Could someone please explain to me why?
```
#include <iostream>
#include <string>
using namespace std;
void add(int a, int b) {
cout << a + b<< endl;
}
void add(float a, float b) {
cout << a + b;
}
int main() {
//calling
add(5,6);
add(1.2, 6.5);
return 0;
}
```
[Sololearn Screenshot](https://i.stack.imgur.com/KCfXN.png) |
|javascript|payment|payment-request-api| |
The `results` Mongo collection contains the following documents:
```json
[
{
"id": 1,
"failures": [
{
"level": "BASIC",
"message": "failure",
},
{
"level": "BASIC",
"message": "failure",
},
{
"level": "WARNING",
"message": "failure",
},
],
"rules": ["X", "Y"]
},
{
"id": 2,
"failures": [
{
"level": "BASIC",
"message": "failure",
},
{
"level": "WARNING",
"message": "failure",
}
],
"rules": ["X"]
},
{
"id": 3,
"failures": [],
"rules": ["X", "Y"]
},
]
```
I would like to create a Mongo query that selects the documents matching the provided IDs, counts the level of each elements of the failures array into a object, and project the rules property.
Given the collection above, and when providing as input the IDs [1, 2, 3], this should be the expected output:
```json
[
{
"id": 1,
"counts": {
"BASIC": 2,
"WARNING": 1
}
"rules": ["X", "Y"]
},
{
"id": 2,
"counts": {
"BASIC": 1,
"WARNING": 1
},
"rules": ["X"]
},
{
"id": 3,
"counts": {},
"rules": ["X", "Y"]
},
]
```
This is the Mongo query I am building:
```
db.collection.aggregate([
{
$match: {
"id": {
$in: [
1,
2,
3
]
}
}
},
{
$unwind: {
path: "$failures",
preserveNullAndEmptyArrays: true
}
},
{
$group: {
_id: {
id: "$id",
level: "$failures.level"
},
count: {
$sum: 1
},
rules: {
$first: "$rules"
}
}
},
{
$group: {
_id: "$_id.id",
count: {
$push: {
k: "$_id.level",
v: "$count"
}
},
rules: {
$first: "$rules"
}
}
},
{
$project: {
"_id": 0,
"id": "$_id.id",
"count": {
$arrayToObject: "$count"
},
"rules": 1
}
}
])
```
However, this query fails when applying the `$arrayToObject` operator with the following error:
```
$arrayToObject requires an object keys of 'k' and 'v'
```
This is because documents with no elements in the failures array have no key "k" when pushing the "_id.level" property.
How can I fall back on an empty object if any of these keys are not present?
Thanks in advance. |
My problem was due to the enter character in the description attribute, it was difficult to find it, but I solved the problem. You can check that your own ldap attributes are entered correctly. |
I'm working with the PrestaShop 8 API and struggling to find the API endpoint for fetching product return details. I need to get information like return ID, associated order ID, product details, quantity, and the return status for returns in my store.
Does anyone know which API endpoint in PrestaShop 8 can be used for retrieving this information? I've checked the general order-related endpoints without luck. Any examples or pointers to the documentation would be really helpful.
Thanks for any help you can provide!
|
How to retrieve product/order return information via PrestaShop 8 API? |
I hope someone can help me with my problem, I wanted to install the apk of a game that I had a long time ago but I get an error for duplicate permission, I guess it stayed even after deleting the game and now it won't let me install a newer version
I tried to search the entire cell phone for the permission but couldn't find it. |
INSTALL_FAILED_DUPLICATE_PERMISSION: Package |
|installation|apk|android-permissions| |
null |
I am trying to track a users face in Flutter and draw a green rectangle over this using CustomPainter. This is the [FacePainter which I used][1]. The issue I am having is, it takes one picture at the start and copies the image onto the screen with the detected face and thats all. [![The image below is a copied emulated camera above the real emulated camera (if that makes sense) and this happends once the face detection is done.][2]][2]
My code starts off doing
`_initializeControllerFuture = _controller.initialize().then((_) {
_controller.startImageStream((CameraImage image) {
_processCameraImage(image, widget.camera);`
It correctly identifies the face but the there is an issue with the image that is sent to CustomPainter. Since I have a CameraImage, I now need to convert this into an ui.Image for CustomPainter. So I do a conversion from yuv420 to rbga8888, in this order.
List<Uint8List> getPlanes(CameraImage availableImage) {
List<Uint8List> planes = [];
for (int planeIndex = 0; planeIndex < 3; planeIndex++) {
Uint8List buffer;
int width;
int height;
if (planeIndex == 0) {
width = availableImage.width;
height = availableImage.height;
} else {
width = availableImage.width ~/ 2;
height = availableImage.height ~/ 2;
}
buffer = Uint8List(width * height);
int pixelStride = availableImage.planes[0].bytesPerPixel!;
int rowStride = availableImage.planes[0].bytesPerRow;
int index = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
buffer[index++] =
availableImage.planes[0].bytes[i * rowStride + j * pixelStride];
}
}
planes.add(buffer);
}
return planes;
}
and then once this is done, the plane is passed into
Uint8List yuv420ToRgba8888(List<Uint8List> planes, int width, int height) {
final yPlane = planes[0];
final uPlane = planes[1];
final vPlane = planes[2];
final Uint8List rgbaBytes = Uint8List(width * height * 4);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int yIndex = y * width + x;
final int uvIndex = (y ~/ 2) * (width ~/ 2) + (x ~/ 2);
final int yValue = yPlane[yIndex] & 0xFF;
final int uValue = uPlane[uvIndex] & 0xFF;
final int vValue = vPlane[uvIndex] & 0xFF;
final int r = (yValue + 1.13983 * (vValue - 128)).round().clamp(0, 255);
final int g =
(yValue - 0.39465 * (uValue - 128) - 0.58060 * (vValue - 128))
.round()
.clamp(0, 255);
final int b = (yValue + 2.03211 * (uValue - 128)).round().clamp(0, 255);
final int rgbaIndex = yIndex * 4;
rgbaBytes[rgbaIndex] = r.toUnsigned(8);
rgbaBytes[rgbaIndex + 1] = g.toUnsigned(8);
rgbaBytes[rgbaIndex + 2] = b.toUnsigned(8);
rgbaBytes[rgbaIndex + 3] = 255; // Alpha value
}
}
return rgbaBytes;
}
and the final processing is this
Future<ui.Image> createImage(
Uint8List buffer, int width, int height, ui.PixelFormat pixelFormat) {
final Completer<ui.Image> completer = Completer();
ui.decodeImageFromPixels(buffer, width, height, pixelFormat,
(ui.Image img) {
completer.complete(img);
});
return completer.future;
}
I also convert the CameraImage into Input Input using the _inputImageFromCameraImage in the [official docs][3]
Im not sure if its something to do with the way Im rotation the image here
InputImage? _inputImageFromCameraImage(
CameraImage image, CameraDescription camera) {
final sensorOrientation = camera.sensorOrientation;
InputImageRotation? rotation;
var rotationCompensation =
_orientations[_controller.value.deviceOrientation];
if (rotationCompensation == null) return null;
if (camera.lensDirection == CameraLensDirection.front) {
rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
} else {
rotationCompensation =
(sensorOrientation - rotationCompensation + 360) % 360;
}
rotation = InputImageRotationValue.fromRawValue(rotationCompensation) ??
InputImageRotation.rotation0deg;
final format = InputImageFormatValue.fromRawValue(image.format.raw) ??
InputImageFormat.nv21;
final inputImageData = InputImageMetadata(
size: ui.Size(image.width.toDouble(), image.height.toDouble()),
rotation: rotation,
format: format,
bytesPerRow: image.planes[0].bytesPerRow,
);
final plane = image.planes.first;
final inputImage = InputImage.fromBytes(
bytes: plane.bytes,
metadata: inputImageData,
);
return inputImage;
}
once the processing of the images is done, its passed into CustomPainter like so
CameraPreview(_controller),
if (_currentImage != null)
CustomPaint(
painter: FacePainter(_currentImage!, _detectedFaces),
),
I believe it might be to do with the way the image is being rotated, but Im completely lost which part is making the image too green and how to get the Painter to draw on the stream instead. Any help is appreciated
[1]: https://github.com/Snehal-Singh174/google_ml_kit_features/blob/main/lib/screens/painter/face_painter.dart#L18
[2]: https://i.stack.imgur.com/8koLa.png
[3]: https://pub.dev/packages/google_mlkit_commons |
Way to get CustomPainter to track face in Camera Flutter MLKit |
|flutter|face-recognition|google-mlkit| |
your loop is the issue, change it to::
for ele in x_str:
if ele.endswith('4'):
print(ele)
Because the loop is for each, you don't need the index |
Okay, I seem to have fixed the issues!
First, I had to switch to a dataset that specifically marks when a recession starts and ends. Luckily, FRED uses data published by the NBER: https://www.nber.org/research/data/us-business-cycle-expansions-and-contractions, and I generated this dataset from it, which included the dates I needed, and had the class of data I needed to avoid the error with transform.
recessions.df = read.table(textConnection(
"Peak, Trough
1960-04-01, 1961-02-01
1969-12-01, 1970-11-01
1973-11-01, 1975-03-01
1980-01-01, 1980-07-01
1981-07-01, 1982-11-01
1990-07-01, 1991-03-01
2001-03-01, 2001-11-01
2007-12-01, 2009-06-01
2020-02-01, 2020-04-01"), sep=',',
colClasses=c('Date', 'Date'), header=TRUE)
Here's the new command, which generates the graph I need!
#Initial plot
p <- ggplot(df, aes(date, fedfunds, group = 1, color="red"))+
geom_rect(data = recessions.df, aes(fill = "Recession Bands", xmin = Peak, xmax = Trough, ymin = -Inf, ymax = +Inf), alpha = 0.5, inherit.aes = FALSE)+ geom_line( size=1.2, alpha=1, linetype=2)+
geom_line( data = df, aes(x = date, y = taylor_rule, color="blue"), size=1.2, alpha=1, linetype=1)+
ggtitle("The Taylor (1993) rule for the US and the Fed Funds rate, 1960-2023")+
xlab("Year") + ylab("Interest Rate and Taylor Rate")+
ylim(-5,20)+
scale_color_hue('Graph Legend', labels = c("Taylor Rule", "Federal Funds Rate"))+
theme(legend.position="bottom")+
scale_fill_manual('Legend', values = 'pink', guide = guide_legend(override.aes = list(alpha = 1)))
p
Graph is here: [![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/PHAt2.png |
in short, the difference is when POST request (e.g carrying form data) hits a 301 moved permanently, user has to fill the form again(because browser converts the method to GET). But if the POST request hits 308 permanent redirect user is not required to fill the form again |
It is because when you are using for loops like you did, `ele` will contain the string itself. You can't use it to access the elements of the list. You can use it directly as an string.
x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))
for ele in x_str:
if ele[-1] == "4":
print(ele)
If you want to have access using indices, you can use `range` inside for loop :
x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))
for i in range(len(x_str)):
if x_str[i][-1] == "4":
print(ele)
Altough there is no need to convert your int array to str array. You can find these numbers by dividing them by `10`.
x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
for num in x:
if num%10 == 4:
print(num)
If you don't want to use for-loops you can find these numbers using `lambda` and `filter` :
x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
result = list(filter(lambda num: num%10==4,x))
`result` will be a list that contains `[44, 4, 34, 94]`. |
I'm facing the same problem right now and I'm using this workaround:
ds.groupByKey(x => x.id)
.mapGroups((key, iter) => {...})
.flatMap(identity)
|
You can use `rxjs pairwise` for that
HTML
----
<form [formGroup]="dateForm">
<mat-form-field style="margin-right: 10px;">
<input matInput [matDatepicker]="picker" formControlName="startdate" placeholder="Start date"/>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput [matDatepicker]="picker2" formControlName="enddate" placeholder="End date"/>
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</form>
TS
----
dateForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.dateForm = this.formBuilder.group({
startdate: [null, Validators.required],
enddate: [null, Validators.required],
});
}
ngOnInit(): void {
this.dateForm.valueChanges.pipe(
startWith({ oldValue: null, newValue: null }),
distinctUntilChanged(),
pairwise(),
map(([oldValue, newValue]) => { return { oldValue, newValue } })
)
.subscribe({
next: (val) => {
console.log(val)
}
});
}
[Here is the stackblitz][1]
[1]: https://stackblitz.com/edit/angular-ivy-pktoy7?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fmain.ts
Have in mind that this is just basic example explaining how you can do that, but its not complete, to begin with you should add some types here. To `formControls`, to `rxjs`, etc...
Additionally, I just took whatever porject and implemented staff, this is moduleless |
Please notice that if you are trying to access values from an object with properties, a propertie like this creates an infinite loop of access and this is what crashes your app in debugging. In this case, the get returns the same Name property, and this returns Name, and so on:
public String Name {
get { return this.Name; }
set {
if (value is null)
this.name = string.Empty;
else
this.name = value;
}
}
Make sure you don't have properties like that, instead you can create a private variable for storing the name
private String name = string.Empty;
public String Name {
get { return this.name; }
set {
if (value is null)
this.name = string.Empty;
else
this.name = value;
}
} |
I have been trying to convert the TensorFlow code into pytorch ,facing the problem ,what to use tf.keras.layer.Layer in pytorch ,Here below is the code ,could any pls help me out with this part?
```python
"""
Objective wrapper and utils to build a function to be optimized
"""
import itertools
import tensorflow as tf
import numpy as np
from ..commons import find_layer
from ..types import Union, List, Callable, Tuple, Optional
from .losses import dot_cossim
class Objective:
"""
Use to combine several sub-objectives into one.
Each sub-objective act on a layer, possibly on a neuron or a channel (in
that case we apply a mask on the layer values), or even multiple neurons (in
that case we have multiples masks). When two sub-objectives are added, we
optimize all their combinations.
e.g Objective 1 target the neurons 1 to 10 of the logits l1,...,l10
Objective 2 target a direction on the first layer d1
Objective 3 target each of the 5 channels on another layer c1,...,c5
The resulting Objective will have 10*5*1 combinations. The first input
will optimize l1+d1+c1 and the last one l10+d1+c5.
Parameters
----------
model
Model used for optimization.
layers
A list of the layers output for each sub-objectives.
masks
A list of masks that will be applied on the targeted layer for each
sub-objectives.
funcs
A list of loss functions for each sub-objectives.
multipliers
A list of multiplication factor for each sub-objectives
names
A list of name for each sub-objectives
"""
def __init__(self,
model: tf.keras.Model,
layers: List[tf.keras.layers.Layer],
masks: List[tf.Tensor],
funcs: List[Callable],
multipliers: List[float],
names: List[str]):
self.model = model
self.layers = layers
self.masks = masks
self.funcs = funcs
self.multipliers = multipliers
self.names = names
def __add__(self, term):
if not isinstance(term, Objective):
raise ValueError(f"{term} is not an objective.")
return Objective(
self.model,
layers=self.layers + term.layers,
masks=self.masks + term.masks,
funcs=self.funcs + term.funcs,
multipliers=self.multipliers + term.multipliers,
names=self.names + term.names
)
def __sub__(self, term):
if not isinstance(term, Objective):
raise ValueError(f"{term} is not an objective.")
term.multipliers = [-1.0 * m for m in term.multipliers]
return self + term
def __mul__(self, factor: float):
if not isinstance(factor, (int, float)):
raise ValueError(f"{factor} is not a number.")
self.multipliers = [m * factor for m in self.multipliers]
return self
def __rmul__(self, factor: float):
return self * factor
def compile(self) -> Tuple[tf.keras.Model, Callable, List[str], Tuple]:
"""
Compile all the sub-objectives into one and return the objects
for the optimisation process.
Returns
-------
model_reconfigured
Model with the outputs needed for the optimization.
objective_function
Function to call that compute the loss for the objectives.
names
Names of each objectives.
input_shape
Shape of the input, one sample for each optimization.
"""
# the number of inputs will be the number of combinations possible
# of the objectives, the mask are used to take into account
# these combinations
nb_sub_objectives = len(self.multipliers)
# re-arrange to match the different objectives with the model outputs
masks = np.array([np.array(m, dtype=object) for m in itertools.product(*self.masks)])
masks = [tf.cast(tf.stack(list(masks[:, i])), tf.float32) for i in
range(nb_sub_objectives)]
# the name of each combination is the concatenation of each objectives
names = np.array([' & '.join(names) for names in
itertools.product(*self.names)])
# one multiplier by sub-objective
multipliers = tf.constant(self.multipliers)
def objective_function(model_outputs):
loss = 0.0
for output_index in range(0, nb_sub_objectives):
outputs = model_outputs[output_index]
loss += self.funcs[output_index](
outputs, tf.cast(masks[output_index], outputs.dtype))
loss *= multipliers[output_index]
return loss
# the model outputs will be composed of the layers needed
model_reconfigured = tf.keras.Model(self.model.input, [*self.layers])
nb_combinations = masks[0].shape[0]
input_shape = (nb_combinations, *model_reconfigured.input.shape[1:])
return model_reconfigured, objective_function, names, input_shape
```
I have tried to convert the code torch and expecting the same out as TensorFlow code |
null |
i am currently an apprentice an pretty new to delphi so i apologize if there is something obvious i'm missing. And i have to note i have to work with a 22 years old lagacy code with approx 600k lines so that could be an error factor as well :D
I was tasked to code a way to save all currently open Forms with their properties like size, position and window state and then restoring it after reopening the program. For that i decided to add in the FormCloseQuery in the Main Form a procedure which goes through all Forms and writes their data (if Visible true) in a .ini File. Works pretty great so far and this is how it looks like:
```
procedure SaveFormInformation();
var
i : Integer;
form : TForm;
iniFile : TIniFile;
begin
iniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'FormInfo.ini');
try
for i := 0 to Screen.FormCount - 1 do
begin
form := Screen.Forms[i];
if form.Visible then
begin
iniFile.WriteInteger(form.Name, 'Width', form.Width);
iniFile.WriteInteger(form.Name, 'Height', form.Height);
iniFile.WriteInteger(form.Name, 'Left', form.Left);
iniFile.WriteInteger(form.Name, 'Top', form.Top);
iniFile.WriteBool(form.Name, 'Visible', form.Visible);
iniFile.WriteBool(form.Name, 'IsMaximized', form.WindowState = wsMaximized)
end;
end;
finally
iniFile.Free;
end;
end;
```
And in the end the .ini File it looks like this:
```
[F_Main]
Width=719
Height=542
Left=600
Top=305
Visible=1
IsMaximized=0
[F_PartList]
Width=1126
Height=716
Left=71
Top=301
Visible=1
IsMaximized=0
```
Now to my problem... the restoring.
At first i tried the same way with Screen.FormCount and if Visible, read the .ini File and replace the values. That only worked partially because we have so many forms (masks), we decided to not initialize some of the forms in the beginning because perfomance.
Then i decided to turn things around and include a loop which reads the .ini and only changes whats written there. But before it changes the properties it looks if the form exists in the first place and creates it when not there. This part does not work the way i intent it to. The if statement - lookup works:
```
if Application.FindComponent(Sections[i]) as TForm = nil then
```
But the Application.CreateForm() doen't.
It seems like it cannot find the classes with their respective names alone. Thankfully we have a naming convention here so every TForm starts with F_ and every TFormClass with TF_ so it should theoretically be possible.
Here the procedure of RestoreForms():
```
procedure RestoreForms();
var
i : Integer;
iniFile : TIniFile;
form : TForm;
FormClass : TFormClass;
Sections : TStringList;
begin
iniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'FormInfo.ini');
Sections := TStringList.Create;
try
IniFile.ReadSections(Sections);
for i := 0 to Sections.Count -1 do
begin
{form := Application.FindComponent(Sections[i]) as TForm;
if not Assigned(form) then
begin
FormClass := TFormClass(GetClass('T' + Sections[i]));
Application.CreateForm(FormClass, form);
form.Free;
end;}
//Since not all Forms are initialized in the beginning this bit
//does it for you. If the Form is nil then create Form
if Application.FindComponent(Sections[i]) as TForm = nil then
begin
//FormClass := TFormClass(FindClass('T' + Sections[i]));
FormClass := TFormClass(GetClass('T' + Sections[i]));
form := Application.FindComponent(Sections[i]) as TForm;
Application.CreateForm(FormClass, form);
form.Free;
end;
//this puts the current read form of the ini File in a TForm Object
//to then change its properties
form := Application.FindComponent(Sections[i]) as TForm;
with form do
begin
form.Top := IniFile.ReadInteger(form.Name, 'Top', Top);
form.Left := IniFile.ReadInteger(form.Name, 'Left', Left);
form.Height := IniFile.ReadInteger(form.Name, 'Height', Height);
form.Width := IniFile.ReadInteger(form.Name, 'Width', Width);
if iniFile.ReadBool(form.Name, 'IsMaximized', WindowState = wsMaximized) then
form.WindowState := wsMaximized
else
form.WindowState := wsNormal;
form.Position := poDesigned;
if not (Sections[i] = 'F_Main') then
form.Visible := IniFile.ReadBool(form.Name, 'Visible', Visible);
end;
end;
finally
Sections.Free;
form.Free;
iniFile.Free;
end;
end;
```
Currently the code "opens" the program but no Form will be seen. Only Services in Taskmanager can free me of the process ^^"
I also thought about saving their Window States of all open Forms in their respective FormClass itself, but since we have like 1k Forms / Masks this task is close to impossible.
I hope you guys can give me some pointers or ideas since neither google nor stackoverflow nor AI could give me any answers as of now. |
Save Form Properties in File and then restore those Properties after reopening |
|forms|delphi| |
null |
i have being building a telegram bot with nodejs where people can send in a url of a tweet and if it contains a media of type video. it downloads it and sends it to the user. Thats the purpose, which i already completed.
The problem i have is with setting a paywall on this bot account so that after 2 or 3 request, the user interacting with the bot have to make a payment to continue.
so i used the [sendInvoice](https://core.telegram.org/bots/api#sendinvoice) method.
FYI, i'm not using any external librarys, i'm directly interacting with the telegram api endpoints.
I'm using stripe for payments in test mode. the problem i have is as you can see this picture:
[This is whats happening/showing after some time](https://i.stack.imgur.com/Vm69E.png)
After i send the invoice, then the user clicks the pay button and adds all the necessary card details then after hitting the pay. it keeps buffering and then time outs.
I also tried the [createInvoiceLink](https://core.telegram.org/bots/api#createinvoicelink) method and the same thing happened.
Ofcourse its some mistake in my solution, but i dont know where that is. May be i have to use a webhook or something to catch the checkout initiation/completion. but how can i let the Telegram api know about my payment webhook path (assuming something like that exists).
The only one i found is the method [setWebhook](https://core.telegram.org/bots/api#setwebhook) which is an alternative approach for polling. And that is what i am doing locally with ngrok.
A Part of my code, this is an abstract version of the functionality:
```
const app = express();
const port = 3000;
const botToken = process.env.TELEGRAM_BOT_TOKEN;
app.use(bodyParser.json());
// Webhook endpoint that receives incoming messages (exposed via ngrok)
app.post(`/bot${botToken}`, async (req, res) => {
const { message } = req.body;
console.log({ message });
if (message && message.text) {
const chatId = message.chat.id;
const messageText = message.text;
// after successfull 3 responses from the bot, send an invoice
const invoiceRes = await sendInvoice(
chatId,
"Premium Subscription",
"Unlock premium content with a subscription.",
"premium_subscription",
process.env.PROVIDER_TOKEN,
"subscription",
"USD",
[{ label: "Subscription", amount: 1000 }],
);
console.log(JSON.stringify(invoiceRes, null, 2));
}
res.status(200).end();
});
async function sendInvoice(
chatId,
title,
description,
payload,
providerToken,
startParameter,
currency,
prices,
) {
const apiUrl = `https://api.telegram.org/bot${botToken}/sendInvoice`;
const invoice = {
chat_id: chatId,
title: title,
description: description,
payload: payload,
provider_token: providerToken,
start_parameter: startParameter,
currency: currency,
prices: prices,
};
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(invoice),
});
const data = await response.json();
// console.log(data);
return data;
} catch (error) {
console.error("There was a problem sending the invoice:", error);
return error.message;
}
}
```
I googled a lot to find some answers, there isnt anything specified in the [payment section of the docs](https://core.telegram.org/bots/payments) either rather than getting the provider token (not anything specifically if i have to do on the stripe account dashboard like adding a webhook endpoint, even if that was the case how would telegram know that is the webhook it should communicate too)
I have been mentioning webhook a lot, because in my mind i am assuming that is my missing solution. if it isnt i'm sorry for doing so. I don't have much experience with stripe or building a telegram bot.
I hope i could get some help with this problem. even a small guidance will be enough if you are busy. just something i can go with that's all i ask. |
I faced the same issue where I trained a contrastive learning model and I want to get the output of that model and use it to train another model. I notice that Pytorch Lightning seems to fine-tune that encoder model when I train the second model. [Repo][1] says that by default `training_step` converts everything there to training mode.
So I initialised my model as global and then passed it to the training step. Like this,
global model
model = model.to('cuda')
encoder_out = model(normal_image)
`model` is loaded as `global` before the second model is defined and passed to the training step as a global model.
I hope that this might help you.
[1]: https://discuss.pytorch.org/t/why-not-use-model-eval-in-training-step-method-on-lightning/122425/4 |
The code below was taught in my Data Structures and Algorithms class. I am currently reviewing it in preparation for exams. The code, by the lecturer, works well.
```
#include<iostream>
#define size 34
using namespace std;
int i,j,n;
int array[size];
void getvalues(){
cout<<"how many values ";
cin>>n;
cout<<"enter values ";
for(i=0; i<n; i++){
cin>>array[i];
}
}
void display(){
for(i=0; i<n; i++){
cout<<array[i]<<" ";
}
}
void merge(int array[], int low, int mid, int high){
i=low; //low of first half
j=mid+1; //low of second half
int k=low; // LOW for temporary new sorted array that we will form
int temp[n];
// Its like while low of each list <= high
while(i<=mid && j<=high){ //?????????????????????????????
// if array at i < array at j...
if(array[i] < array[j]){
temp[k] = array[i]; // set array at k to be equal to array at i
i++; //move foward by one
k++; //move foward byone
}
else // if array at j < array at i...
{
temp[k]=array[j]; // set array at k to be equal to array at j instead
k++; //move foward by one
j++; //move foward by one
}
}
//mop remaining values
while(i<=mid){
temp[k]=array[i];
i++;
k++;
}
while(j<=high){
temp[k]=array[j];
k++;
j++;
}
//copy to original array
for(i=low; i<k; i++)
array[i]=temp[i];
}
void mergesort(int array[], int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
mergesort(array, low, mid);
mergesort(array, mid+1, high);
// Merge them to get sorted output.
merge(array, low, mid, high);
}
}
int main(){
getvalues();
mergesort(array, 0, n-1);
display();
}
```
However, I do not understand the purpose of the last 2 while loops within the merge (not mergesort) function. I thought just 1 would be enough.
Could someone kindly explain to me why we need 2 extra while loops?
**Help with testing**
I also need help on how to test the result after the first while loop is exited. How can I print that result? I have tried using the display() function amongs other methods that return weird results or simply do not work. May I also get help with that?
Below is the "weird result" I get after trying to use display to print after the first while loop in merge function. It even results in a distortion of the result since the array is not sorted. How can I test-print in c++?
[running the program after test-printing](https://i.stack.imgur.com/cJYTz.png)
|
Purpose of last 2 while loops in the merge algorithm of merge sort sorting technique |
null |
I have this javascript code which is supposed to create a screenshot of the `image-container` div and send it to a new php script:
html2canvas(image-container).then(function (canvas) {
canvas.toBlob(function (blob) {
jQuery.ajax({
url:"//domain.com/wp-admin/admin-ajax.php",
type: "POST",
data: {action: "addblobtodb", image: blob},
success: function(id) {
console.log("Succesfully inserted into DB: " + id);
}
});
The php code that is called in the `admin-ajax.php` file is shown below. It tries to insert the image blob in the `test_images` table, which I created myself. It is asimple MySql table with an ID and image_data:
function add_poster_to_db() {
global $wpdb;
$image = $_POST['image'];
ob_start();
// Insert een nieuwe rij aan de test_poster_images db
$wpdb->insert('test_images', array(
'image_data' => $image,
));
$db_id = $wpdb->insert_id;
wp_send_json( $db_id );
die();
}
When calling this javascript code, the following errors are shown:
[![error][1]][1]
How can I insert the blob in the Wordpress table?
[1]: https://i.stack.imgur.com/CZkro.png |
TypeError: Failed to execute 'arrayBuffer' on 'Blob': Illegal invocation - Insert blob into database |
|javascript|php|ajax|wordpress|html2canvas| |
Since .Net 4.5, the preferred way to implement data validation is to implement [`INotifyDataErrorInfo`][1] (example from [Technet][2], example from [MSDN (Silverlight)][3]).
Note: `INotifyDataErrorInfo` replaces the obsolete `IDataErrorInfo`.
The new framework infrastructure related to the `INotifyDataErrorInfo` interface provides many advantages like
- support of multiple errors per property
- custom error objects and customization of visual error feedback (e.g. to adapt visual cues to the custom error object)
- asynchronous validation using async/await
----------
How `INotifyDataErrorInfo` works
================================
When the `ValidatesOnNotifyDataErrors` property of `Binding` is set to `true`, the binding engine will search for an `INotifyDataErrorInfo` implementation on the binding source and subscribe to the [`INotifyDataErrorInfo.ErrorsChanged`][4] event.
If the `ErrorsChanged` event of the binding source is raised and `INotifyDataErrorInfo.HasErrors` evaluates to `true`, the binding engine will invoke the [`INotifyDataErrorInfo.GetErrors(propertyName)`][5] method for the actual source property to retrieve the corresponding error message and then apply the customizable validation error template to the target control to visualize the validation error.
By default a red border is drawn around the element that has failed to validate.
In case of an error, which is when `INotifyDataErrorInfo.HasErrors` returns `true`, the binding engine will also set the attached [`Validation`][6] properties on the binding target, for example `Validation.HasError` and `Validation.ErrorTemplate`.
To customize the visual error feedback, we can override the default template provided by the binding engine, by overriding the value of the attached `Validation.ErrorTemplate` property (see example below).
The described validation procedure only executes when `Binding.ValidatesOnNotifyDataErrors` is set to `true` on the particular data binding and the `Binding.Mode` is set to either `BindingMode.TwoWay` or `BindingMode.OneWayToSource`.
How to implement `INotifyDataErrorInfo`
=======================================
The following examples show three variations of property validation using
1) `ValidationRule` (class to encapsulate the actual data validation implementation)
2) lambda expressions (or delegates)
3) validation attributes (used to decorate the validated property).
Of course, you can combine all three variations to provide maximum flexibility.
The code is not tested. The snippets should all work, but may not compile due to typing errors. This code is intended to provide a simple example on how the `INotifyDataErrorInfo` interface could be implemented.
----------
Preparing the view
------------------
**MainWindow.xaml**
To enable the visual data validation feedback, the [`Binding.ValidatesOnNotifyDataErrors`][9] property must be set to `true` on each relevant `Binding` i.e. where the source of the `Binding` is a validated property. The WPF framework will then show the control's default error feedback.
**Note:** to make this work, the **`Binding.Mode` must be either `OneWayToSource` or `TwoWay`** (which is the default for the `TextBox.Text` property):
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<!-- Important: set ValidatesOnNotifyDataErrors to true to enable visual feedback -->
<TextBox Text="{Binding UserInput, ValidatesOnNotifyDataErrors=True}"
Validation.ErrorTemplate="{DynamicResource ValidationErrorTemplate}" />
</Window>
The following is an example of a custom validation error template.
The default visual error feedback is a simple red border around the validated element. In case you like to customize the visual feedback e.g., to allow showing error messages to the user, you can define a custom `ControlTemplate` and assign it to the validated element (in this case the `TextBox`) via the attached property [`Validation.ErrorTemplate`][10] (see above).
The following `ControlTemplate` enables showing a list of error messages that are associated with the validated property:
[![enter image description here][11]][11]
<ControlTemplate x:Key="ValidationErrorTemplate">
<StackPanel>
<Border BorderBrush="Red"
BorderThickness="1">
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="AdornedElement" />
</Border>
<Border Background="White"
BorderBrush="Red"
Padding="4"
BorderThickness="1,0,1,1"
HorizontalAlignment="Left">
<ItemsControl ItemsSource="{Binding}" HorizontalAlignment="Left">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ErrorContent}"
Foreground="Red"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</StackPanel>
</ControlTemplate>
----------
The view model is responsible for validating its own properties to ensure the data integrity of the model.
I recommend moving the implementation of `INotifyDataErrorInfo` into a base class (e.g. an abstract `ViewModel` class) together with the `INotifyPropertyChanged` implementation and let all your view models inherit it. This makes the validation logic reusable and keeps your view model classes clean.
You can change the example's implementation details of `INotifyDataErrorInfo` to meet requirements.
1 Data validation using `ValidationRule`
------------------------
**ViewModel.cs**
When using [`ValidationRule`][7], the key is to have separate `ValidationRule` implementations for each property or rule.
Extending `ValidationRule` is optional. I chose to extend `ValidationRule` because it already provides a complete validation API and because the implementations can be reused with binding validation if necessary.
Basically, the result of the property validation should be a `bool` to indicate fail or success of the validation and a message that can be displayed to the user to help him to fix his input.
All we have to do in case of a validation error is to generate an error message, add it to a private string collection to allow our `INotifyDataErrorInfo.GetErrors(propertyName)` implementation to return the proper error messages from this collection and raise the `INotifyDataErrorInfo.ErrorChanged` event to notify the WPF binding engine about the error:
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
// Example property, which validates its value before applying it
private string userInput;
public string UserInput
{
get => this.userInput;
set
{
// Validate the value
bool isValueValid = IsPropertyValid(value);
// Optionally reject value if validation has failed
if (isValueValid)
{
this.userInput = value;
OnPropertyChanged();
}
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
this.ValidationRules = new Dictionary<string, IList<ValidationRule>>();
// Create a Dictionary of validation rules for fast lookup.
// Each property name of a validated property maps to one or more ValidationRule.
this.ValidationRules.Add(nameof(this.UserInput), new List<ValidationRule>() { new UserInputValidationRule() });
}
// Validation method.
// Is called from each property which needs to validate its value.
// Because the parameter 'propertyName' is decorated with the 'CallerMemberName' attribute.
// this parameter is automatically generated by the compiler.
// The caller only needs to pass in the 'propertyValue', if the caller is the target property's set method.
public bool IsPropertyValid<TValue>(TValue propertyValue, [CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
_ = ClearErrors(propertyName);
if (this.ValidationRules.TryGetValue(propertyName, out List<ValidationRule> propertyValidationRules))
{
// Apply all the rules that are associated with the current property
// and validate the property's value
IEnumerable<object> errorMessages = propertyValidationRules
.Select(validationRule => validationRule.Validate(propertyValue, CultureInfo.CurrentCulture))
.Where(result => !result.IsValid)
.Select(invalidResult => invalidResult.ErrorContent);
AddErrorRange(propertyName, errorMessages);
return !errorMessages.Any();
}
// No rules found for the current property
return true;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional method to check if a particular property has validation errors
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
// The WPF binding engine will listen to this event
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// This implementation of GetErrors returns all errors of the specified property.
// If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
// This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnumerable<object>)errors
: new List<object>();
// Returns 'true' if the view model has any invalid property
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
// Maps a property name to a list of ValidationRules that belong to this property
private Dictionary<string, IList<ValidationRule>> ValidationRules { get; }
}
**UserInputValidationRule.cs**
This example validation rule extends [`ValidationRule`][7] and checks if the input starts with the '@' character. If not, it returns an invalid [`ValidationResult`][8] with an error message that can be displayed to the user to help him to fix his input.
public class UserInputValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (!(value is string userInput))
{
return new ValidationResult(false, "Value must be of type string.");
}
if (!userInput.StartsWith("@"))
{
return new ValidationResult(false, "Input must start with '@'.");
}
return ValidationResult.ValidResult;
}
}
2 Data validation using lambda expressions and delegates
----------------------------------------
As an alternative approach, the `ValidationRule` can be replaced (or combined) with delegates to enable the use of Lambda expressions or Method Groups.
The validation expressions in this example return a tuple containing a boolean to indicate the validation state and a collection of `string` error objects for the actual messages. Since all error object related properties are of type `object`, the expressions can return any custom data type, in case you need more advanced error feedback and `string` is not a sufficient error object. In this case, we must also adjust the validation error template, to enable it to handle the data type.
**ViewModel.cs**
// Example uses System.ValueTuple
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
// This property is validated using a lambda expression
private string userInput;
public string UserInput
{
get => this.userInput;
set
{
// Validate the new property value.
bool isValueValid = IsPropertyValid(value,
newValue => newValue.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." }));
// Optionally, reject value if validation has failed
if (isValueValid)
{
// Accept the valid value
this.userInput = value;
OnPropertyChanged();
}
}
}
// Alternative usage example property, which validates its value
// before applying it, using a Method Group.
private string userInputAlternative;
public string UserInputAlternative
{
get => this.userInputAlternative;
set
{
// Use Method Group
if (IsPropertyValid(value, IsUserInputValid))
{
this.userInputAlternative = value;
OnPropertyChanged();
}
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
}
// The validation method for the UserInput property
private (bool IsValid, IEnumerable<object> ErrorMessages) IsUserInputValid(string value)
{
return value.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." });
}
// Example uses System.ValueTuple
public bool IsPropertyValid<TValue>(
TValue value,
Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate,
[CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
_ = ClearErrors(propertyName);
// Validate using the delegate
(bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>());
if (!validationResult.IsValid)
{
AddErrorRange(propertyName, validationResult.ErrorMessages);
}
return validationResult.IsValid;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional method to check if a particular property has validation errors
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
// The WPF binding engine will listen to this event
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// This implementation of GetErrors returns all errors of the specified property.
// If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
// This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnumerable<object>)errors
: new List<object>();
// Returns 'true' if the view model has any invalid property
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
}
----------
3 Data validation using `ValidationAttribute`
-------------------------------------------
This is an example implementation of `INotifyDataErrorInfo` with [`ValidationAttribute`][12] support e.g., [`MaxLengthAttribute`][13]. This solution combines the previous Lambda version to additionally support validation using a Lambda expression/delegate simultaneously.
While validation using a lambda expression or a delegate must be explicitly invoked by calling the `TryValidateProperty` method in the properties setter, the attribute validation is executed implicitly from the `OnPropertyChanged` event invocator (as soon the property was decorated with validation attributes):
**ViewModel.cs**
// Example uses System.ValueTuple
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
private string userInput;
// Validate property using validation attributes
[MaxLength(Length = 5, ErrorMessage = "Only five characters allowed.")]
public string UserInput
{
get => this.userInput;
set
{
// Optional call to 'IsPropertyValid' to combine attribute validation
// with a delegate
bool isValueValid = IsPropertyValid(value, newValue => newValue.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." }));
// Optionally, reject value if validation has failed
if (isValueValid)
{
this.userInput = value;
}
// Triggers checking for validation attributes and their validation,
// if any validation attributes were found (like 'MaxLength' in this example)
OnPropertyChanged();
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
this.ValidatedAttributedProperties = new HashSet<string>();
}
// Validate property using decorating attributes.
// Is invoked by 'OnPropertyChanged' (see below).
private bool IsAttributedPropertyValid<TValue>(TValue value, string propertyName)
{
this.ValidatedAttributedProperties.Add(propertyName);
// The result flag
bool isValueValid = true;
// Check if property is decorated with validation attributes
// using reflection
IEnumerable<Attribute> validationAttributes = GetType()
.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
?.GetCustomAttributes(typeof(ValidationAttribute)) ?? new List<Attribute>();
// Validate using attributes if present
if (validationAttributes.Any())
{
var validationContext = new ValidationContext(this, null, null) { MemberName = propertyName };
var validationResults = new List<ValidationResult>();
if (!Validator.TryValidateProperty(value, validationContext, validationResults))
{
isValueValid = false;
AddErrorRange(validationResults.Select(attributeValidationResult => attributeValidationResult.ErrorMessage));
}
}
return isValueValid;
}
public bool IsPropertyValid<TValue>(
TValue value,
Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate = null,
[CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
ClearErrors(propertyName);
// Validate using the delegate
(bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>());
if (!validationResult.IsValid)
{
// Store the error messages of the failed validation
AddErrorRange(validationResult.ErrorMessages);
}
bool isAttributedPropertyValid = IsAttributedPropertyValid(value, propertyName);
return isAttributedPropertyValid && validationResult.IsValid;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
this.ValidatedAttributedProperties.Remove(propertyName);
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// Returns all errors of a property. If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnuemrable<object>)errors
: new List<object>();
// Returns if the view model has any invalid property
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Check if IsAttributedPropertyValid Property was already called by 'IsValueValid'.
if (!this.ValidatedAttributedProperties.Contains(propertyName))
{
_ = IsAttributedPropertyValid(value, propertyName);
}
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
// Track attribute validation calls
private HashSet<string> ValidatedAttributedProperties { get; }
}
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2
[2]: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx
[3]: https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ee652637(v=vs.95)#examples
[4]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.errorschanged?view=net-5.0#remarks
[5]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.geterrors?view=net-5.0#remarks
[6]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation?view=windowsdesktop-6.0
[7]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationrule?view=netcore-3.1#examples
[8]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationresult?view=netcore-3.1#examples
[9]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.binding.validatesonnotifydataerrors?view=net-5.0#remarks
[10]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation.errortemplate?view=net-5.0#remarks
[11]: https://i.stack.imgur.com/CjikQ.png
[12]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?view=netcore-3.1
[13]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netcore-3.1 |
private void register (String username, String email, String password) {
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(task -> {
if (task.isSuccessful()){
FirebaseUser firebaseUser = auth.getCurrentUser();
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("users").child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id",userid);
hashMap.put("username",username);
hashMap.put("imageURL","default");
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
} else{
Toast.makeText(RegisterActivity.this, "You can't register with this email and password", Toast.LENGTH_SHORT).show();
}
});
Users are not showing in my database after registering using this code.
|
|api|prestashop|e-commerce| |
>But, receiving is not working at all. Nothing is happening. This copied directly from RxJS website
- Create a service (e.g., `WebsocketService`) to manage the WebSocket connection. This service will handle connecting, sending, and receiving messages.
***websocket.service.ts :***
```ts
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
const WS_ENDPOINT = 'wss://your-webpubsub-url'; // Replace with your actual Web PubSub URL
@Injectable({ providedIn: 'root' })
export class WebsocketService {
private ws: WebSocketSubject<any>;
constructor() {}
public connect(): void {
this.create();
}
private create() {
if (this.ws) {
this.ws.unsubscribe();
}
this.ws = webSocket<any>(WS_ENDPOINT);
this.ws.subscribe(); // Start listening for messages
}
public close() {
if (this.ws) {
this.ws.unsubscribe();
}
}
public sendMessage(message: any) {
this.ws.next(message);
}
}
```
- Inject the `WebsocketService` into the Angular components where you want to use WebSocket communication.
- Subscribe to the `messages$` observable to receive WebSocket messages. Handle incoming messages as needed.
***app.component.ts :***
```ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { WebsocketService } from '../websocket.service'; // Adjust the path
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit, OnDestroy {
private messagesSubscription: Subscription;
constructor(private websocketService: WebsocketService) {}
ngOnInit(): void {
this.websocketService.connect();
this.messagesSubscription = this.websocketService.messages$.subscribe({
next: (message: any) => {
console.log('Received message:', message);
// Handle the message as needed
},
error: (error: Error) => {
console.error('WebSocket error:', error);
},
complete: () => {
console.log('WebSocket connection closed');
},
});
}
ngOnDestroy() {
this.messagesSubscription.unsubscribe();
this.websocketService.close();
}
}
```
- Unsubscribe from the WebSocket subscription when the component is destroyed (in `ngOnDestroy`).
**Connection status :**

**Receive messages :**
 |
null |
I want to connect a ansible virtual machine to a cisco switch. When I try the command `ssh myuser@192.168.xxx.xxx` from my ansible manager, the connection is successfull but when I try to run a playbook from this same ansible manager I've this error:
`ssh connection failed: Failed to authenticate public key: Socket error: disconnected`.
Does anyone have any idea what's wrong?
My playbook task with the command `ansible-playbook -i inventaire.ini cisco.yml --user myuser --ask-pass`:
```
---
- name: show version
ios_command:
commands:
- show version
register: output
- name: print output
debug:
var: output.stdout_lines
```
My variables:
```
ansible_network_os=ios
ansible_user=user-ansible
ansible_password=xxx
ansible_connection=network_cli
```
I've already try to create the ssh connection as [this example](https://networklessons.com/uncategorized/ssh-public-key-authentication-cisco-ios). But without result. |
How do I ask for admin rights when executing the code for this code?
For example, I have a program that creates a shortcut to a directory and it will be compiled via pkg into an .exe file:
```javascript
const fs = require("fs");
const path = require("path");
fs.symlink(path.resolve("path/to/directory"), path.resolve("path/to/shortcut"), console.log);
```
Maybe there is some library or something else to request these rights directly from the code, or something else? |
How to request administrator rights? |
|javascript|node.js|permissions|exe|pkg| |
There is so much wrong with your dynamic SQL that I won't list it. And I won't comment on your design, it doesn't sound optimal, but as say the problem is a more complex than described its hard to comment.
Anyway, with what you have provided you can do the following:
- You can loop through all categories to avoid having to manually code them
- At a row level you need to `CONCAT` the values to create a dynamic string
- At a multi-row level you need to `STRING_AGG` the rows to build a single rows
```
/* Dummy Table Creation */
DECLARE @DummyWeightageTable TABLE (
Category varchar(50)
, Fieldname varchar(50)
, Weightage real
);
INSERT INTO @DummyWeightageTable
VALUES
('Sniper', 'Eyesight', 40),
('Sniper', 'BMI', 10),
('Sniper', 'Height', 10),
('Sniper', 'Skill', 20),
('Fighter', 'Eyesight', 10),
('Fighter', 'BMI', 30),
('Fighter', 'Height', 20);
/* Actual Functionality */
DECLARE @Category TABLE (
Category varchar(50)
, Done bit NOT NULL DEFAULT(0)
);
INSERT INTO @Category (Category)
SELECT Category
FROM @DummyWeightageTable
GROUP BY Category;
-- Dynamic SQL must use nvarchar
DECLARE @sql NVARCHAR(MAX), @delta NVARCHAR(MAX), @CurrentCategory varchar(50);
WHILE EXISTS (SELECT 1 FROM @Category WHERE Done = 0) BEGIN
SELECT TOP 1 @CurrentCategory = Category FROM @Category WHERE Done = 0;
SET @sql = 'SELECT Emp_Id, ';
-- Do below step for all rows
-- First concat the values required from each row
-- Then string_agg then into a single string
SELECT @delta = STRING_AGG(CONCAT('(', Weightage, ' * ISNULL(', Fieldname, ',0))'), ' + ')
FROM @DummyWeightageTable
WHERE Category = @CurrentCategory;
SET @sql = @sql + @delta + ' from MyDataTable1;';
-- This is how you debug dynamic SQL
PRINT @sql;
--EXEC sp_executesql @sql;
UPDATE @Category SET Done = 1 WHERE Category = @CurrentCategory;
END;
```
Returns:
```
SELECT Emp_Id, (10 * ISNULL(Eyesight,0)) + (30 * ISNULL(BMI,0)) + (20 * ISNULL(Height,0)) from MyDataTable1;
SELECT Emp_Id, (40 * ISNULL(Eyesight,0)) + (10 * ISNULL(BMI,0)) + (10 * ISNULL(Height,0)) + (20 * ISNULL(Skill,0)) from MyDataTable1;
```
[DBFiddle](https://dbfiddle.uk/09XpG0iS) |
I have a sveltekit app in which i use gunjs as a db with user auth etc...
(This error problem didnt exist before i added gunjs auth)
The problem now is that when i use vercel to deploy the app it throws this (500: INTERNAL_SERVER_ERROR):
`Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"Error: Cannot find module './lib/text-encoding'\nRequire stack:\n- /var/task/node_modules/gun/sea.js","reason":{"errorType":"Error","errorMessage":"Cannot find module './lib/text-encoding'\nRequire stack:\n- /var/task/node_modules/gun/sea.js","code":"MODULE_NOT_FOUND","requireStack":["/var/task/node_modules/gun/sea.js"],"stack":["Error: Cannot find module './lib/text-encoding'","Require stack:","- /var/task/node_modules/gun/sea.js"," at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)"," at Module._load (node:internal/modules/cjs/loader:975:27)"," at exports.b (/var/task/___vc/__launcher/chunk-5UAC7W5H.js:1:1033)"," at /var/task/___vc/__launcher/bridge-server-BGIDXK2J.js:1:1443"," at Function.Re (/var/task/___vc/__launcher/bridge-server-BGIDXK2J.js:1:1809)"," at e.<computed>.L._load (/var/task/___vc/__launcher/bridge-server-BGIDXK2J.js:1:1413)"," at Module.require (node:internal/modules/cjs/loader:1225:19)"," at require (node:internal/modules/helpers:177:18)"," at USE (/var/task/node_modules/gun/sea.js:5:17)"," at /var/task/node_modules/gun/sea.js:189:44"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: Error: Cannot find module './lib/text-encoding'","Require stack:","- /var/task/node_modules/gun/sea.js"," at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)"," at process.emit (node:events:529:35)"," at emit (node:internal/process/promises:149:20)"," at processPromiseRejections (node:internal/process/promises:283:27)"," at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}`
It works when i run it locally with `npm run dev`
My db init looks like this:
`import { writable } from 'svelte/store';
import Gun from "gun"
import "gun/sea"
import "gun/axe"
export const db = new Gun();
export const user = db.user().recall({sessionStorage: true});
export const username = writable('');
user.get('alias').on((v:string) => username.set(v))
db.on('auth', async() => {
const alias = await user.get('alias');
username.set(alias)
})`
When i look into the node_modules/gun/lib folder the text-encoding module is the only one which has a folder instead of the .js module file, in the folder there is the index.js file which contains the modules code... but this should not be the problem...
Maybe i create the db the wrong way idk...?
I tried installing the text-encoding module which simply resulted in more errors, i tried diffrent gunjs versions which changed nothing, i fixed the node version to 18.20 which also changed nothing...
Please help :/ |
|c++|algorithm|data-structures|merge|mergesort| |
null |
The IsShuttingDown property is an internal static property of the Application class therefore you can access to value it with the below code
var isShuttingDownProp = typeof(Application).GetProperty("IsShuttingDown", BindingFlags.Static | BindingFlags.NonPublic);
var isShuttingDown = isShuttingDownProp.GetValue(Application.Current, null); |
An easy way to generate splash screen and app icon is to use [Ionic][1] VSCode Extension.
1. Step 1 - Install the extension and reload VSCode.
2. Step 2 - Go to Ionic tab from the left side panel in VSCode.
3. Step 3 - Go to `Configuration` -> `Splash Screen and Icon`.
4. Follow the steps and click `Rebuild`.
[![Rebuild step][2]][2]
[1]: https://marketplace.visualstudio.com/items?itemName=ionic.ionic
[2]: https://i.stack.imgur.com/2NIjk.png |
You should sort the list of integers in descending order and then iterate through it, adding each number to the list with the smaller current sum, like the following:
```python
import random
intList = []
for i in range(10):
intList.append(random.randint(10, 200))
listX = []
listY = []
intList.sort(reverse=True)
sumX = 0
sumY = 0
for num in intList:
if sumX <= sumY:
listX.append(num)
sumX += num
else:
listY.append(num)
sumY += num
print(f"listx = {listX} \nlisty = {listY}\n sum x = {sumX}, y = {sumY}")
```
## Edit
To ensure that both lists have exactly 5 elements and maintain balanced lengths, you can modify the algorithm to distribute the numbers based on the lengths of the lists. If one list has fewer than 5 elements, prioritize it adding numbers to that list until it reaches 5 elements.
Try this:
```python
import random
intList = [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]
listX = []
listY = []
intList.sort(reverse=True)
sumX = 0
sumY = 0
for num in intList:
if len(listX) < 5:
listX.append(num)
sumX += num
elif len(listY) < 5:
listY.append(num)
sumY += num
elif sumX <= sumY:
listX.append(num)
sumX += num
else:
listY.append(num)
sumY += num
print(f"listx = {listX} \nlisty = {listY}\n sum x = {sumX}, y = {sumY}")
```
|
I wish to merge `df1` and `df2` to `df3` and keep order. my demo code add `sort=False` but it not work as expected.
```
import pandas as pd
data1 = [
['4A', 1],
['3B', 2],
['2C', 3],
['1D', 4],
]
data2 = [
['2C',9],
['4A',3],
['6F',2],
['5G',1]
]
df1 = pd.DataFrame(data1,columns=['name','value'])
df2 = pd.DataFrame(data2,columns=['name','value'])
df3 = pd.merge(df1,df2,how='outer',on='name',sort=False)
df3 = df3.rename({'value_x': 'v1','value_y':'y2'},axis=1)
print(df1)
print(df2)
print(df3)
```
Output:
```
name value
0 4A 1
1 3B 2
2 2C 3
3 1D 4
name value
0 2C 9
1 4A 3
2 6F 2
3 5G 1
name v1 y2
0 1D 4.0 NaN
1 2C 3.0 9.0
2 3B 2.0 NaN
3 4A 1.0 3.0
4 5G NaN 1.0
5 6F NaN 2.0
```
Expected output:
```
name v1 y2
0 4A 1.0 3.0
1 3B 2.0 NaN
2 2C 3.0 9.0
3 1D 4.0 NaN
4 6F NaN 2.0
5 5G NaN 1.0
``` |
|android|firebase-realtime-database|firebase-authentication| |
null |
null |
My workaround was to use JsonConverter and handle each subclass seperately
```dart
class GeometryObjectConverter implements JsonConverter<GeometryObject, Map<String, dynamic>> {
const GeometryObjectConverter();
@override
GeometryObject fromJson(Map<String, dynamic> json) =>
switch (json["type"]) {
"circle" => Circle.fromJson(json),
"dot" => Dot.fromJson(json),
"line" => Line.fromJson(json),
_ => throw UnimplementedError(json["type"])
};
@override
Map<String, dynamic> toJson(GeometryObject object) =>
switch (object.runtimeType) {
Circle => (object as Circle).toJson()..["type"]="circle",
Dot => (object as Dot).toJson()..["type"]="dot",
Line => (object as Line).toJson()..["type"]="line",
_ => throw UnimplementedError(object.runtimeType.toString()),
};
}
``` |
I got a new Laravel project but it showing the following error and it is not letting me run it using php artisan serve I tried using composer self-update too but it is not working....
> php artisan serve
Here's the error =>
PHP Fatal error: During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1349
Stack trace:
#0 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8192, 'Return type of ...', 'C:\\xampp\\htdocs...', 1349)
#1 C:\xampp\htdocs\fitway\vendor\composer\ClassLoader.php(576): include('C:\\xampp\\htdocs...')
#2 C:\xampp\htdocs\fitway\vendor\composer\ClassLoader.php(427): Composer\Autoload\{closure}('C:\\xampp\\htdocs...')
#3 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\helpers.php(110): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp...')#4 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(130): collect(Array)
#5 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(106): Illuminate\Foundation\PackageManifest->build()
#6 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(89): Illuminate\Foundation\PackageManifest->getManifest()
#7 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('aliases')
#8 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\RegisterFacades.php(26): Illuminate\Foundation\PackageManifest->aliases()
#9 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(230): Illuminate\Foundation\Bootstrap\RegisterFacades->bootstrap(Object(Illuminate\Foundation\Application))
#10 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(310): Illuminate\Foundation\Application->bootstrapWith(Array)
#11 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(127): Illuminate\Foundation\Console\Kernel->bootstrap()
#12 C:\xampp\htdocs\fitway\artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#13 {main} in C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\Collection.php on line 11
In Collection.php line 11:
During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Support\Collection::offsetExists($key) should either be compatib
le with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in
C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1349
Stack trace:
#0 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\Collection.php(11): Illuminate\Foundation\Bootstrap\HandleExceptions->handle
Error(8192, 'Return type of ...', 'C:\\xampp\\htdocs...', 1349)
#1 C:\xampp\htdocs\fitway\vendor\composer\ClassLoader.php(576): include('C:\\xampp\\htdocs...')
#2 C:\xampp\htdocs\fitway\vendor\composer\ClassLoader.php(427): Composer\Autoload\{closure}('C:\\xampp\\htdocs...')
#3 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Support\helpers.php(110): Composer\Autoload\ClassLoader->loadClass('Illuminate\\Supp
...')
#4 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(130): collect(Array)
#5 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(106): Illuminate\Foundation\PackageManifest->build()
#6 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(89): Illuminate\Foundation\PackageManifest->getManife
st()
#7 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\PackageManifest.php(78): Illuminate\Foundation\PackageManifest->config('a
liases')
#8 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\RegisterFacades.php(26): Illuminate\Foundation\PackageManifest-
>aliases()
#9 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(230): Illuminate\Foundation\Bootstrap\RegisterFacades->bo
otstrap(Object(Illuminate\Foundation\Application))
#10 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(310): Illuminate\Foundation\Application->bootstrapWit
h(Array)
#11 C:\xampp\htdocs\fitway\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(127): Illuminate\Foundation\Console\Kernel->bootstrap
()
#12 C:\xampp\htdocs\fitway\artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony
\Component\Console\Output\ConsoleOutput))
#13 {main}
Please tell me how can I resolve it.
I have tried changing the Php version in the .env file as well but it is not working either.
Chatgpt or Gemini have not been much of help either.... |
null |
if you don’t need to process output as it happens, but can wait for the process to end, use this:
await proc.wait()
output = await proc.stdout.read()
IMHO, you should really only use proc.communicate to send stdin to the process. |
Introduce a `ExecStartPost` which health-checks the service, this checks marks the health of binary. `systemd` will not mark the service healthy until `ExecStartPost` is complete.
```
[Service]
ExecStart=/path/to/slowservice
# Ensures that we only mark the service active once it passes a health-check
ExecStartPost=/bin/bash -c "while ! curl -m 1 https://localhost:8443/admin; do sleep 0.1; done"
```
In your case, `ExecStartPost` can do something similar to the other dependent service. |