instruction stringlengths 0 30k ⌀ |
|---|
While adding CGO_ENABLED=0 to commands like `go test` can work,<br>
the editor still keeps warning at top of go files all the time.
Just add to top of your C/C++ source files, like:
```c
//go:build ignore
```
Links:<br>
\- https://pkg.go.dev/cmd/go#hdr-Build_constraints<br>
\- https://zhuanlan.zhihu.com/p/566878192<br>
\- https://github.com/fritx/mixed-playground/blob/main/strings/2129.%20%E5%B0%86%E6%A0%87%E9%A2%98%E9%A6%96%E5%AD%97%E6%AF%8D%E5%A4%A7%E5%86%99.cc |
Getting the below warning when connecting to Mongo Atlas. Though the warning is there connection is successful and able to access the database. I need to know how to get rid of this warning message
CryptographyDeprecationWarning: This version of cryptography contains a temporary pyOpenSSL fallback path. Upgrade pyOpenSSL now.
I tried updating the pyOpenSSL to the latest version but still getting the warning. |
I developed a website using GoHighLevel web builder. The survey form is embedded into it. Using JavaScript/jQuery I can manipulate all of the elements. The generated value is displayed in the target input field. However, it keeps resetting to empty values on clicking previous pages and on form submission.
It seems GHL is using Nuxt. |
How to modify the form fiels values in a GHL website? |
|nuxt.js| |
I have a subform called "test_subform" with source control to a query named "my_query". my_query has 10 fields. I am trying to dynamically connect my "test_subform" to the following:
SQLText = "SELECT SampleID, Station, SampleDate, lake_name, riverCode, " & strParameters & " " & _
"FROM lake_parameters WHERE (Station IN (" & strPondName & "))ORDER BY SampleDate DESC;"
It works if I try to link the record source like this:
Forms!Results!lake_parameters_subform.Form.RecordSource = SQLText
However, I want to connect my test_subform through Source Object instead like below so I can
get only the desired fields created automatically with SQLText on my test_subform:
Me.lake_parameters_subform.SourceObject = SQLText
But I get an error here. How can I set my test_subform dynamically to a source object?
Error I get:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/FcrEw.png |
How to dynamically set the object source to a subform |
|vba|database|ms-access-2016| |
I am new to node.js and i was trying to make a interactive website for my CNN Project but got this error. help me out guys
```
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:68:19)
at Object.createHash (node:crypto:138:10)
at module.exports (D:\Potato-disease-Major-1\frontend\node_modules\webpack\lib\util\createHash.js:135:53)
at NormalModule._initBuildHash (D:\Potato-disease-Major-1\frontend\node_modules\webpack\lib\NormalModule.js:417:16)
at D:\Potato-disease-Major-1\frontend\node_modules\webpack\lib\NormalModule.js:452:10
at D:\Potato-disease-Major-1\frontend\node_modules\webpack\lib\NormalModule.js:323:13
at D:\Potato-disease-Major-1\frontend\node_modules\loader-runner\lib\LoaderRunner.js:367:11
at D:\Potato-disease-Major-1\frontend\node_modules\loader-runner\lib\LoaderRunner.js:233:18
at context.callback (D:\Potato-disease-Major-1\frontend\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
at D:\Potato-disease-Major-1\frontend\node_modules\babel-loader\lib\index.js:59:103 {
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
```
i tried reinntalling the modules, but got the same result |
My page: https://galina.xyz/makiyazh/oshibki-pri-makiyazhe/
HTML:
```html
<figure class="n-spin-container wp-block-image size-full">
<img loading="lazy" width="390" height="500" src="https://galina.xyz/wp-content/uploads/2019/10/neve-food-mag-20.jpg" alt="" class="wp-image-68">
</figure>
```
CSS:
```css
.n-spin-container {
width: 100%;
height: 100%;
transition: border-radius 1s ease-out;
border-radius: 60% 40% 30% 70% / 60% 30% 70% 40%;
}
```
[![enter image description here][1]][1]
I have failed to make this egg shape image frame to rotate slowly. The image itself is fixed. Only the vignette should be rotating. What can try next?
[1]: https://i.stack.imgur.com/qWYuc.png |
My issue was indeed simple and stupid. The environment variable I used was overriding `/api/v1`, and in the `.env` file I had only put `api/v1` without the first `/`. |
null |
You could then :
- use `multiprocessing` library,
- create two parallelize functions to deal separately with chunks
The general idea is to create a separate process for each function, and deal with chunks one by one inside each function-process.
To my mind this is a simple way to keep control on differential treatment speeds related to both functions.
**Proposed code**
```python
import numpy as np
from multiprocessing import Pool
def fun_1(args):
y1_i, y2_i = args
return y1_i + y2_i
def fun_2(args):
y1_i, y2_i = args
return sum(y1_i * y2_i)
def separate_process(func, y1, y2, num_pool):
"""Separated process to deal chunks with one function at a time"""
# Create a pool of workers
pool = Pool(num_pool)
# Divide the data into chunks for treatment
# (good thing to do with large datasets)
### Assuming len(y1) = len(y2)
chunk_size = len(y1) // num_pool
chunks_y1 = [y1[i:i + chunk_size] for i in range (0, len(y1), chunk_size)]
chunks_y2 = [y2[i:i + chunk_size] for i in range (0, len(y2), chunk_size)]
# Apply function for each chunk in parallel
results = pool.map(func, zip(chunks_y1, chunks_y2))
# Avoid 'float' exception
results = [result.tolist() if isinstance(result, np.ndarray) else [result] for result in results]
# Close the pool
pool.close()
# Wait for the process to finish to keep control
pool.join()
# Concatenation : chunks treatment strategy is not supposed to be visible at the end
return results
depth = np.linspace(5000, 6000, 2001)
y1 = np.random.random(len(depth))
y2 = np.random.random(len(depth))
num_pool = 2
fun_1_res = separate_process(fun_1, y1, y2, num_pool)
fun_2_res = separate_process(fun_2, y1, y2, num_pool)
print(len(fun_1_res))
### 3
print(len(fun_2_res))
### 3
``` |
Found it, seems like Vuex sets DevTools to true by default, just had to set it to false:
```
const store = createStore({
devtools: false,
})
``` |
On tiles you can set either a andorid resource id or a image byte array. In your case, if the image is dynamic (is not set as a internal resource) you need to convert it to byte array and then set it.
(I recommend for you to convert the image to byte array outside the tile service, in the editor activity for example, to save resources and battery)
I got a code for converting drawable into byte array, in case u want:
```
private byte[] toByteArray(Drawable d) {
try {
final Bitmap b = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(b);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
d.draw(canvas);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
} catch (Exception e) {
return null;
}
}
```
To convert the byte[] to string you can:
```
pricate String byteArrayToString(ByteArrayOutputStream s) {
return Base64.getEncoder().encodeToString(s.toByteArray());
}
private byte[] stringToByteArray(String s) {
return s == null ? new byte[0] : Base64.getDecoder().decode(s);
}
```
Then you can set it on tile in the "onResourcesRequest":
```
@NonNull
@Override
protected ListenableFuture<ResourceBuilders.Resources> onResourcesRequest(@NonNull RequestBuilders.ResourcesRequest requestParams) {
final ResourceBuilders.Resources.Builder resources = new ResourceBuilders.Resources.Builder();
//Your code to get the byte array
resources.addIdToImageMapping(
ID,
new ResourceBuilders.ImageResource.Builder()
.setInlineResource(
new ResourceBuilders.InlineImageResource.Builder()
.setData(
//BYTE ARRAY HERE <<
).setFormat(ResourceBuilders.IMAGE_FORMAT_UNDEFINED) //This is required unless you know the format, I recommend leaving this way
.setHeightPx(SIZE * 2) //2 for better quality
.setWidthPx(SIZES * 2) //2 for better quality
.build()
).build()
);
return Futures.immediateFuture(resources.setVersion(VERSION).build());
}
```
Then you set the image using its ID...
**Edit:**
The libraries I use
```
implementation "androidx.wear.tiles:tiles:1.1.0"
implementation "androidx.wear.tiles:tiles-material:1.1.0"
implementation "androidx.concurrent:concurrent-futures:1.1.0"
implementation "com.google.guava:guava:31.0.1-android"
``` |
Error with firebase deploy --prefix $RESOURCE_DIR run lint giving functions/functions |
|firebase|npm|google-cloud-functions| |
I'm trying to integrate a existing DLL project (3rd party dependencies) to Blank UWP. The Blank App project build fine but throws error when it is lauched.
In Event Viewer, log suggests Error code: The app didn't start.. Activation phase: COM ActivateExtension.
Below is the artticle about "How to: Use existing C++ code in a Universal Windows Platform app" which states that UWP Apps run in a protected environment. As a result, many Win32, COM, and CRT API calls that might compromise platform security aren't allowed. The /ZW compiler option can detect such calls and generate an error. You can use the App Certification Kit on your application to detect code that calls disallowed APIs. For more information, see Windows App Certification Kit****.
https://learn.microsoft.com/en-us/cpp/porting/how-to-use-existing-cpp-code-in-a-universal-windows-platform-app?view=msvc-170
does that mens DLL project can't be integrated? |
UWP Blank app throws error code: The app didn't start.. Activation phase: COM ActivateExtension |
|uwp|c++-winrt| |
In VS code, if you have navigated away from an ephemeral tab using the "Ctrl + Tab" shortcut, The default keybinding helping you to go to your ephemeral file once navigated away is is "Ctrl + Shift + Tab" on Windows and Linux, and "Cmd + Shift + Tab" on macOS.
This allows you to navigate back and forth between previosly activated tabs,even if some of them are ephemeral.
You can also customize the keybindings in VS code according to your preferences by going to the "File" menu, selecting "Preferences," and then choosing "Keyboard Shortcuts." In the keyboard shortcuts editor, you can search for specific commands, modify existing keybindings, or define your own custom shortcuts. |
{"OriginalQuestionIds":[56327864],"Voters":[{"Id":1509264,"DisplayName":"MT0","BindingReason":{"GoldTagBadge":"oracle"}}]} |
Just create a batch file that has the address of the database you want to open and add this one-line of code:
```
Call Shell ("The batch file address")
``` |
I'm a seasoned developer but new to Go. The documentation I have found is not straightforward. I'm used to Java, Scala and Python, but Go is new to me. I'm trying to create a library in Go, and I'm in the first steps of creating the project structure. When I run `go build` it tells me there are "no Go files in ...". This is a pure library and I don't want a main file. Is there a way to achieve this or is a main file required no matter what?
Finding documentation and looking at sample projects. I do have files and I have run some tests with a main file in place, but as soon as I delete the main file it's when I get a bit lost on how to build it correctly. |
How to build a Go Library without a main |
In django whenever i use Datetime.datetime.now() a runtime warning :
`enter code here received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active` is displayed , i want to supress this warning or basically tell django to ignore this warning, is there a change i can make in the settings file to tell django to ignore the naive datetime field warning
eg:
b = User.objects.create()
b.start = datetime.datetime.now()
b.save()
runtime warning : `received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active`
tried : setting `USE_TZ = False` in settings.py |
null |
I suspect you are getting an uncaught `Exception` from your code:
config.write(config_file)
The `write()` method takes no arguments as it writes to the last read file.
Try changing that line to:
config.write()
In fact, you don't need the code:
with open('registration.ini', 'w') as config_file:
|
You can clip the Composable with `Modifier.clip(shape)` as following:
Card(
modifier = modifier
.clip(shape = shape)
.shadow(elevation = 0.dp, spotColor = Color.Transparent, shape = shape),
elevation = 16.dp,
shape = shape,
backgroundColor = MaterialTheme.colors.surface
)
This works whenever you set shadow manually, without the elevation on card, as you set the boundaries for the following `Modifier` - meaning you put the clip modifier before any other, in our case the shadow `Modifier`. |
Execution of multiple goals from the CLI is now supported in Maven 3.3.1+
mvn exec:java@first-cli
mvn exec:java@second-cli
Where first-cli/second-cli are the execution ids.
[Apache Maven 3.3.1 Features](https://blog.soebes.io/posts/2015/03/2015-03-17-apache-maven-3-dot-3-1-features/)
For your example the commands would be
```
mvn myplugin:mygoal@process-cats
mvn myplugin:mygoal@process-dogs
``` |
Traceback (most recent call last):
File "C:\Users\Tariq\Downloads\Blank-main\Blank\env\Scripts\process.py", line 9, in <module>
import pyaes
ModuleNotFoundError: No module named 'pyaes'
288 INFO: PyInstaller: 6.5.0, contrib hooks: 2024.3
288 INFO: Python: 3.12.2
307 INFO: Platform: Windows-10-10.0.19045-SP0
Script file 'loader-o.py' does not exist.
Can anyone help me, i dont know anythink about python
I installed pyaes already but nothing changes
|
Is the django-cors-headers exclusive to the DRF? If not, why am I getting an error 403 if I am not using DRF in my project?
I already configured the django-cors-header package.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:8000',
] |
ERROR 403 in Django even after configuring the django-cors-headers package |
|django| |
null |
null |
**Try This**
$(function () {
$('#txtDateTimePicker').datetimepicker({
format: 'd/m/Y h:i A',
formatTime: 'h:i A',
step: 15, // Set the minute step to 15 minutes
value: new Date()
});
}); |
First of all, you need to make sure that the binding is set up correctly using double quotes:
```xml
<Border
BackgroundColor="{Binding MyBorderBackgroundColor}">
<Label Text=“Hello World” />
</Border>
```
Then, I would recommend using the `Color` type in the ViewModel instead of a `string` since there is no implicit conversion between those types. That's how I am doing it in my own apps, too.
So, you could change your code to the following and define the color in a variety of different ways (the list is not final):
```c#
[ObservableProperty]
Color myBorderBackgroundColor;
//...
public void Init()
{
// use hex value
MyBorderBackgroundColor = Color.FromArgb("#FF0000");
// parse string
MyBorderBackgroundColor = Color.Parse("Red");
// use RGB
MyBorderBackgroundColor = Color.FromRgb(255,0,0);
// use named color
MyBorderBackgroundColor = Colors.Red;
//...
}
```
You can find more information about Colors in the [official documentation][1].
[1]: https://learn.microsoft.com/dotnet/maui/user-interface/graphics/colors |
for me it was generated .mdx and .stories file and it has issue in importing them, once i deleted the files it worked fine |
[example of the problem I got](https://drive.google.com/file/d/1YWocJ6xWAxQhLaCOyT9fmQnU41SD9U4E/view?usp=drivesdk)
code from the problematic program
```
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as imglib;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:camera/camera.dart';
import 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';
import 'package:flutter_face_api/face_api.dart' as Regula;
import '../conn/getFoto.dart';
String nama = "-";
String pin = "-";
String instruk = "Scanning...";
String _similarity = "nil";
var takenPicture;
var takenPicturePath;
int camNum = 1;
double persenCocok = 0;
bool faceUp = false;
bool faceDown = false;
bool faceRight = false;
bool faceLeft = false;
bool faceCenter = false;
class AbsenFoto extends StatefulWidget {
const AbsenFoto({super.key});
@override
State<AbsenFoto> createState() => _AbsenFotoState();
}
class _AbsenFotoState extends State<AbsenFoto> {
List<CameraDescription>? cameras;
CameraController? controller;
var faceDetector;
late List<Face> _faces;
Color topBar = Color.fromRGBO(22, 149, 0, 1.0);
Color dataBackgroundColor = Color.fromRGBO(152, 136, 136, 1.0);
Color switchCameraButtonColor = Color.fromRGBO(3, 217, 254, 1.0);
Color batalButton = Color.fromRGBO(234, 0, 1, 1.0);
@override
void initState() {
camInit();
_facesInit();
getFoto().gettingFoto();
super.initState();
}
@override
void dispose() {
faceDetector.close();
controller?.dispose();
faceUp = false;
faceDown = false;
faceRight = false;
faceLeft = false;
faceCenter = false;
instruk = "Scanning...";
super.dispose();
}
@override
Widget build(BuildContext context) {
setState(() {
getNama();
});
return Scaffold(
appBar: AppBar(
title: Text(
"Absensi Mangusada",
),
backgroundColor: topBar,
foregroundColor: CupertinoColors.white,
),
body: Padding(
padding: EdgeInsets.only(top: 20),
child: SingleChildScrollView(
child: Center(
child: Column(
children: [
Container(
height: 380,
width: 240,
child: showCam(),
),
SizedBox(
height: 50,
),
Text(
instruk,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
SizedBox(
height: 16,
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: dataBackgroundColor,
),
height: 100,
width: 310,
padding: EdgeInsets.only(top: 30, left: 16),
child: Align(
alignment: Alignment.centerLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 8,
),
Text(
nama,
style: TextStyle(color: CupertinoColors.white),
),
Text(
pin,
style: TextStyle(color: CupertinoColors.white),
),
],
),
),
),
SizedBox(
height: 16,
),
ElevatedButton(
onPressed: () async {
if (camNum == 0) {
camNum = 1;
await updateController(cameras![camNum]);
} else if (camNum == 1) {
camNum = 0;
await updateController(cameras![camNum]);
}
},
child: Text("SWITCH CAMERA"),
style: ButtonStyle(
backgroundColor:
MaterialStatePropertyAll(switchCameraButtonColor),
foregroundColor:
MaterialStatePropertyAll(CupertinoColors.white),
minimumSize: MaterialStateProperty.all(
Size(310, 60),
),
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
SizedBox(
height: 16,
),
ElevatedButton(
onPressed: () {
if (mounted) {
controller!.dispose();
faceUp = false;
faceDown = false;
faceRight = false;
faceLeft = false;
faceCenter = false;
}
Navigator.pushReplacementNamed(context, '/absen');
},
child: Text("BATAL"),
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(batalButton),
foregroundColor:
MaterialStatePropertyAll(CupertinoColors.white),
minimumSize: MaterialStateProperty.all(
Size(310, 60),
),
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
],
),
),
),
),
);
}
camInit() async {
cameras = await availableCameras();
if (cameras != null) {
controller = CameraController(cameras![1], ResolutionPreset.high, imageFormatGroup: Platform.isAndroid ? ImageFormatGroup.nv21 : ImageFormatGroup.bgra8888, enableAudio: false);
await controller!.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
} else {
print("NO any camera found");
}
}
showCam() {
if (controller == null) {
return Center(child: Text("Loading Camera..."),);
} else if (!controller!.value.isInitialized) {
return Center(child: CircularProgressIndicator(),);
} else {
return Stack(
children: [
CameraPreview(controller!),
FutureBuilder<List<Face>>(
future: _detectFaces(),
builder: (context, snapshot) {
return Container();
}
),
],
);
}
}
_facesInit() {
final FaceDetectorOptions options = FaceDetectorOptions(
enableClassification: true,
enableTracking: true,
enableLandmarks: true,
enableContours: true,
performanceMode: FaceDetectorMode.accurate
);
faceDetector = FaceDetector(options: options);
}
updateController(CameraDescription description) {
controller?.dispose().then((value) async {
setState(() {});
controller = CameraController(description, ResolutionPreset.high, imageFormatGroup: Platform.isAndroid ? ImageFormatGroup.nv21 : ImageFormatGroup.bgra8888, enableAudio: false);
controller?.initialize().then((_) {
setState(() {});
});
});
}
Future<List<Face>> _detectFaces() async {
takenPicture = await controller?.takePicture();
takenPicturePath = takenPicture.path;
final inputImage = InputImage.fromFilePath(takenPicture!.path);
_faces = await faceDetector.processImage(inputImage);
setState(() {
if (_faces.isEmpty) {
instruk = "Wajah tidak terdeteksi";
} else {
instruk = "Scanning...";
if (faceUp == false) {
instruk = "Hadap ke atas";
_faces.single.headEulerAngleX! >= 20 ? faceUp = true : faceUp = false ;
} else if (faceDown == false) {
instruk = "Hadap ke bawah";
_faces.single.headEulerAngleX! <= -20 ? faceDown = true : faceDown = false ;
} else if (faceRight == false) {
instruk = "Toleh ke kanan";
_faces.single.headEulerAngleY! <= -20 ? faceRight = true : faceRight = false ;
} else if (faceLeft == false) {
instruk = "Toleh ke kiri";
_faces.single.headEulerAngleY! >= 20 ? faceLeft = true : faceLeft = false ;
} else if (faceCenter == false) {
instruk = "Lihat ke depan";
(_faces.single.headEulerAngleY! >= -5 && _faces.single.headEulerAngleY! <= 5) && (_faces.single.headEulerAngleX! >= -5 && _faces.single.headEulerAngleX! <= 5)
? faceCenter = true : faceCenter = false ;
} else {
instruk = "Harap tunggu...\nTahan Posisi Anda";
}
}
});
if (faceUp == true && faceDown == true && faceRight == true && faceLeft == true && faceCenter == true) {
instruk = "Harap tunggu...\nTahan Posisi Anda";
compareFace();
if (persenCocok >= 95) {
await controller?.pausePreview();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Verifikasi Liveness Berhasil!"),
content: Text('Anda asli!\nWajah anda $_similarity sama dengan yang ada di server'),
actions: [
TextButton(
onPressed: () {
setState(() {
faceUp = false;
faceDown = false;
faceRight = false;
faceLeft = false;
faceCenter = false;
});
Navigator.pushNamedAndRemoveUntil(context, "/home", (route) => false);
},
child: Text("OK"),
)
],
);
}
);
} else if (_similarity == "error") {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Verifikasi Liveness Berhasil!"),
content: Text('Anda asli!\nTetapi wajah anda tidak sama dengan gambar yang ada di server'),
actions: [
TextButton(
onPressed: () {
setState(() {
faceUp = false;
faceDown = false;
faceRight = false;
faceLeft = false;
faceCenter = false;
});
Navigator.pushNamedAndRemoveUntil(context, "/home", (route) => false);
},
child: Text("OK"),
)
],
);
}
);
} else {
instruk = "Harap tunggu...\nTahan Posisi Anda";
}
}
return _faces;
}
compareFace() async {
var image1 = Regula.MatchFacesImage();
var image2 = Regula.MatchFacesImage();
imglib.Image? FileImage1 = imglib.decodeImage(File(takenPicturePath).readAsBytesSync());
imglib.Image? FileImage2 = imglib.decodeImage(File(getFoto().getPathPhoto()).readAsBytesSync());
List<int> image1Bytes = imglib.encodePng(FileImage1!);
List<int> image2Bytes = imglib.encodePng(FileImage2!);
image1.bitmap = base64Encode(image1Bytes);
image1.imageType = Regula.ImageType.PRINTED;
image2.bitmap = base64Encode(image2Bytes);
image2.imageType = Regula.ImageType.PRINTED;
if (image1.bitmap == null ||
image1.bitmap == "" ||
image2.bitmap == null ||
image2.bitmap == "") return 0;
var request = await Regula.MatchFacesRequest();
request.images = [image1, image2];
Regula.FaceSDK.matchFaces(jsonEncode(request)).then((value) {
var response = Regula.MatchFacesResponse.fromJson(json.decode(value));
Regula.FaceSDK.matchFacesSimilarityThresholdSplit(
jsonEncode(response!.results), 0.75)
.then((str) {
var split = Regula.MatchFacesSimilarityThresholdSplit.fromJson(
json.decode(str));
setState(() {
_similarity = split!.matchedFaces.isNotEmpty
? ("${(split.matchedFaces[0]!.similarity! * 100).toStringAsFixed(2)}%")
: "error";
persenCocok = split.matchedFaces.isNotEmpty
? (split.matchedFaces[0]!.similarity! * 100)
: 0;
});
});
});
return _similarity;
}
getNama() async {
final prefs = await SharedPreferences.getInstance();
nama = prefs.get("user").toString();
pin = prefs.get("pin").toString();
}
}
```
I tried running the code on Android and it successfully displayed the camera and face scanning.
and when I type the code on the iOS device the camera is spamming taking photos and flashing on the iPhone screen
I hope everything can run smoothly like on Android |
Bug known when scanning face, the camera spamming take photo and doing flashing on screen on iPhone |
|ios|flutter|face-recognition| |
null |
I install postgres in centos7.9
Follow the document steps
https://www.hostinger.com/tutorials/how-to-install-postgresql-on-centos-7/
Encountered the following issues
```
sudo systemctl start postgresql.service
Job for postgresql.service failed because the control process exited with error code. See "systemctl status postgresql.service" and "journalctl -xe" for details.
```
```
sudo systemctl status postgresql.service
● postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Wed 14:56:24 CST; 27s ago
Process: 27102 ExecStartPre=/usr/bin/postgresql-check-db-dir ${PGDATA} (code=exited, status=127)
VM-20-7-centos systemd[1]: Starting PostgreSQL database server...
VM-20-7-centos systemd[1]: postgresql.service: control process exited, code=exited status=127
VM-20-7-centos systemd[1]: Failed to start PostgreSQL database server.
VM-20-7-centos systemd[1]: Unit postgresql.service entered failed state.
VM-20-7-centos systemd[1]: postgresql.service failed.
```
```
sudo journalctl -xe
Mar 13 14:56:24 VM-20-7-centos systemd[1]: Unit postgresql.service entered failed state.
Mar 13 14:56:24 VM-20-7-centos systemd[1]: postgresql.service failed.
Mar 13 14:56:24 VM-20-7-centos polkitd[702]: Unregistered Authentication Agent for unix-process:27096:45009466 (system bus name :1.1559, object path /org/freedesktop/PolicyKit1/Au
Mar 13 14:56:24 VM-20-7-centos sudo[27095]: pam_unix(sudo:session): session closed for user root
Mar 13 14:56:52 VM-20-7-centos sudo[27219]: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/systemctl status postgresql.service
Mar 13 14:56:52 VM-20-7-centos sudo[27219]: pam_unix(sudo:session): session opened for user root by root(uid=0)
Mar 13 14:56:52 VM-20-7-centos sudo[27219]: pam_unix(sudo:session): session closed for user root
Mar 13 14:57:01 VM-20-7-centos crond[27255]: PAM unable to dlopen(/usr/lib64/security/pam_access.so): /lib64/libnsl.so.1: symbol __nss_hash, version GLIBC_PRIVATE not defined in f
Mar 13 14:57:01 VM-20-7-centos crond[27255]: PAM adding faulty module: /usr/lib64/security/pam_access.so
Mar 13 14:57:01 VM-20-7-centos crond[27255]: PAM unable to dlopen(/usr/lib64/security/pam_unix.so): /lib64/libc.so.6: version `GLIBC_2.25' not found (required by /lib64/libcrypt.s
Mar 13 14:57:01 VM-20-7-centos crond[27255]: PAM adding faulty module: /usr/lib64/security/pam_unix.so
Mar 13 14:57:01 VM-20-7-centos crond[27255]: (root) PAM ERROR (Module is unknown)
Mar 13 14:57:01 VM-20-7-centos crond[27255]: (root) FAILED to authorize user with PAM (Module is unknown)
Mar 13 14:57:04 VM-20-7-centos kernel: device eth0 entered promiscuous mode
Mar 13 14:57:05 VM-20-7-centos kernel: device eth0 left promiscuous mode
Mar 13 14:57:46 VM-20-7-centos sshd[27418]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=157.245.199.76 user=root
Mar 13 14:57:46 VM-20-7-centos sshd[27418]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root"
Mar 13 14:57:48 VM-20-7-centos sshd[27418]: Failed password for root from 157.245.199.76 port 42952 ssh2
Mar 13 14:57:48 VM-20-7-centos sshd[27418]: Connection closed by 157.245.199.76 port 42952 [preauth]
Mar 13 14:58:01 VM-20-7-centos crond[27491]: PAM unable to dlopen(/usr/lib64/security/pam_access.so): /lib64/libnsl.so.1: symbol __nss_hash, version GLIBC_PRIVATE not defined in f
Mar 13 14:58:01 VM-20-7-centos crond[27491]: PAM adding faulty module: /usr/lib64/security/pam_access.so
Mar 13 14:58:01 VM-20-7-centos crond[27491]: PAM unable to dlopen(/usr/lib64/security/pam_unix.so): /lib64/libc.so.6: version `GLIBC_2.25' not found (required by /lib64/libcrypt.s
Mar 13 14:58:01 VM-20-7-centos crond[27491]: PAM adding faulty module: /usr/lib64/security/pam_unix.so
Mar 13 14:58:01 VM-20-7-centos crond[27491]: (root) PAM ERROR (Module is unknown)
Mar 13 14:58:01 VM-20-7-centos crond[27491]: (root) FAILED to authorize user with PAM (Module is unknown)
```
sudo systemctl start postgresql.service can be good |
install postgres on centos |
|postgresql|centos7| |
null |
I'll assume you are working in a PostgreSQL environment. Simply can do it like this:
SELECT * FROM table WHERE null = any(column1)
or if null equals to empty string, just change it correspondingly
SELECT * FROM table WHERE '' = any(column1)
See the documentation [here][1] for more
[1]: https://www.postgresql.org/docs/current/arrays.html |
```
import json
dict = {
"epapconfig": {
"suffix": "Enter Choice: ",
"Display": {
"suffix": "Press return to continue..."
},
"Security": {
"suffix": "Enter Choice: ",
"Timeout": {
"suffix": "Enter Choice: ",
"Display": {
"suffix": "Press return to continue..."
}
}
}
},
"epapdev": {
"suffix": "]$ "
},
"su": {
"suffix": "Password: "
},
"root": {
"suffix": "]# "
}
}
r=json.dumps(dict)
data = json.loads(r)
print(data['epapconfig']['Display']['suffix'])
``` |
You can't. That's the concept of a managed service. As of today, I could not find this parameter exposed in AWS. Maybe in the future |
try this,
1. Convert the number to string format using str() function.
2. Using string slicing, reverse the number.
3. Check if the reversed number matches the original number.
num = int(input("Enter number : " ))
reverse = int(str(num)[::-1])
if num == reverse:
print("Palindrome")
else:
print("Not Palindrome") |
Since you're using a reactive approach with `Flux`, you should not be blocking with the `while` statement. Instead, you should chain your reactive operations.
`expand` is used to perform repeat queries until we have collected all the required data, applying the scrollContinue operation only if there's still data left according to the comparison of total and current size.
Some modification of your code, not surely runnable though.
```java
public Flux<ELKModel> getByTradeDateBetween(LocalDateTime from, LocalDateTime to) {
NativeSearchQueryBuilder sourceBuilder = new NativeSearchQueryBuilder();
sourceBuilder.withQuery(
QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery(TRADE_DATE).gte(from).lte(to)));
sourceBuilder.withPageable(PageRequest.of(0, SINGLE_QUERY_SIZE));
NativeSearchQuery query = sourceBuilder.build();
return elasticsearchSupport.scrollStart(query, ELKModel.class)
.expand(wrapper -> {
if (wrapper.getTotal() > wrapper.getCurrentSize()) {
return elasticsearchSupport.scrollContinue(wrapper.getScrollId(), ELKModel.class)
.map(ELKModelWrapper::valueFrom);
} else {
return Flux.empty();
}
})
.flatMap(wrapper -> Flux.fromIterable(wrapper.getResults()));
}
``` |
{"Voters":[{"Id":22180364,"DisplayName":"Jan"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":6463558,"DisplayName":"Lin Du"}],"SiteSpecificCloseReasonIds":[13]} |
I am getting the error in captcha generation {} org.apache.axis.AxisFault: (404)Not Found while generating captcha using webservice.
I am using Springboot 2.6.3 and java 1.8
I have checked that in my maven dependency library folder axis-1.4.jar is presented and in org.apache.axis AxisFault.class file also there. |
error in captcha generation {} org.apache.axis.AxisFault: (404)Not Found Spring Boot Application |
|spring-boot|captcha|apache-axis|webservice-client| |
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":6463558,"DisplayName":"Lin Du"}]} |
I dont think so javascript works like that sir, a **javascript script doesn't work when you place it in some kind of object (div in this case**) instead it is always **supposed to be put at the end of the HTML page** (before the body ending tag usually) and it works accordingly what you have written inside it.
**Here you are considering javascript as a html object (just live divs ,paragraphs ,header tags etc.) but it isn't like that**.
I can help you more if you can **provide your Javascript code** and **tell me what you are trying to code more clearly** .
***I don't know why so many of you are giving me downvotes, I have clearly answered his question, he is a beginner, please stop this toxic behaviour. Instead of giving me downvotes, why don't you answer his question itself.*** |
null |
null |
null |
null |
null |
null |
i have a tflite model that takes image as input and predict its class label. but when i am using this code,there is an error like this
NullReferenceException: Object reference not set to an instance of an object
TensorFlowLite.Interpreter..ctor (System.Byte[] modelData, TensorFlowLite.InterpreterOptions options) (at ./Packages/com.github.asus4.tflite/Runtime/Interpreter.cs:71)
TensorFlowLite.Interpreter..ctor (System.Byte[] modelData) (at ./Packages/com.github.asus4.tflite/Runtime/Interpreter.cs:60)
ImageClassifier.LoadModelAndLabels (System.String modelPath, System.String labelPath) (at Assets/Samples/Detection/Scripts/PythonBridge.cs:58)
ImageClassifier.Start () (at Assets/Samples/Detection/Scripts/PythonBridge.cs:28)
I have used tensorflow lite from here [Github](https://github.com/asus4/tf-lite-unity-sample)
this is my program code .cs
```
using UnityEngine;
using TensorFlowLite;
using System.IO;
using System.Linq;
using UnityEngine.Networking;
using System.Collections;
public class ImageClassifier : MonoBehaviour
{
// Serialized fields to set from the Unity Editor
[SerializeField] private string modelFileName = "project.tflite";
[SerializeField] private string labelFileName = "class_labels.txt";
[SerializeField] private Texture2D inputImage;
private Interpreter interpreter;
private string[] labels;
private float[] imgData; // Flatten the image data array
private float[,] output;
void Start()
{
string modelPath = Path.Combine(Application.streamingAssetsPath, modelFileName);
string labelPath = Path.Combine(Application.streamingAssetsPath, labelFileName);
Debug.Log("Model path: " + modelPath);
Debug.Log("Label path: " + labelPath);
if (!LoadModelAndLabels(modelPath, labelPath))
{
Debug.LogError("Failed to load model and labels.");
return;
}
// Load image from previous scene and preprocess it
string imagePath = DisplayCapturedImage.imagePath;
Debug.Log("Image path: " + imagePath);
if (!string.IsNullOrEmpty(imagePath))
{
StartCoroutine(LoadImageAndRunInference(imagePath));
}
else
{
Debug.LogError("Image path is not set or is empty.");
}
}
private bool LoadModelAndLabels(string modelPath, string labelPath)
{
Debug.Log("Loading model from path: " + modelPath);
if (File.Exists(modelPath))
{
byte[] modelData = File.ReadAllBytes(modelPath);
if (modelData == null || modelData.Length == 0)
{
Debug.LogError("Model data is null or empty");
return false;
}
interpreter = new Interpreter(modelData);
interpreter.AllocateTensors();
}
else
{
Debug.LogError("Model file not found at " + modelPath);
return false;
}
Debug.Log("Loading labels from path: " + labelPath);
if (File.Exists(labelPath))
{
labels = File.ReadAllLines(labelPath)
.Select(s => s.Trim())
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
else
{
Debug.LogError("Label file not found at " + labelPath);
return false;
}
Debug.Log("Model and labels loaded successfully");
int outputCount = interpreter.GetOutputTensorInfo(0).shape[1];
output = new float[1, outputCount];
return true;
}
IEnumerator LoadImageAndRunInference(string imagePath)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture("file://" + imagePath);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError(www.error);
}
else
{
Texture2D texture = DownloadHandlerTexture.GetContent(www);
PreprocessImage(texture);
RunInference();
}
}
void PreprocessImage(Texture2D image)
{
// Resize image to the model input size
Texture2D resizedImage = Resize(image, 224, 224);
int height = resizedImage.height;
int width = resizedImage.width;
int channels = 3; // Assuming the model expects a 3-channel RGB image
imgData = new float[height * width * channels]; // Flatten the image data array
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color color = resizedImage.GetPixel(x, y);
// Normalize pixel values to [0, 1] if needed
int i = (y * width + x) * channels;
imgData[i + 0] = color.r;
imgData[i + 1] = color.g;
imgData[i + 2] = color.b;
}
}
// Dispose of the resized image to free up memory
Destroy(resizedImage);
}
Texture2D Resize(Texture2D source, int newWidth, int newHeight)
{
source.filterMode = FilterMode.Bilinear;
RenderTexture rt = RenderTexture.GetTemporary(newWidth, newHeight);
rt.filterMode = FilterMode.Bilinear;
RenderTexture.active = rt;
Graphics.Blit(source, rt);
Texture2D result = new Texture2D(newWidth, newHeight);
result.ReadPixels(new Rect(0, 0, newWidth, newHeight), 0, 0);
result.Apply();
RenderTexture.active = null;
RenderTexture.ReleaseTemporary(rt);
return result;
}
void RunInference()
{
interpreter.SetInputTensorData(0, imgData);
interpreter.Invoke();
float[] outputData = new float[output.GetLength(1)]; // Flatten the output array
interpreter.GetOutputTensorData(0, outputData);
int predictedIndex = GetPredictedIndex(outputData);
string predictedLabel = labels[predictedIndex];
Debug.Log($"Predicted class: {predictedLabel}");
}
int GetPredictedIndex(float[] probabilities)
{
int predictedIndex = 0;
float maxProbability = probabilities[0];
for (int i = 1; i < probabilities.Length; i++)
{
if (probabilities[i] > maxProbability)
{
maxProbability = probabilities[i];
predictedIndex = i;
}
}
return predictedIndex;
}
void OnDestroy()
{
if (interpreter != null)
{
interpreter.Dispose();
interpreter = null;
}
}
}
```
this is interpreter.cs which is giving error
```
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using TfLiteInterpreter = System.IntPtr;
using TfLiteInterpreterOptions = System.IntPtr;
using TfLiteModel = System.IntPtr;
using TfLiteTensor = System.IntPtr;
namespace TensorFlowLite
{
/// <summary>
/// Simple C# bindings for the experimental TensorFlowLite C API.
/// </summary>
public class Interpreter : IDisposable
{
public struct TensorInfo
{
public string name { get; internal set; }
public DataType type { get; internal set; }
public int[] shape { get; internal set; }
public QuantizationParams quantizationParams { get; internal set; }
public override string ToString()
{
return string.Format("name: {0}, type: {1}, dimensions: {2}, quantizationParams: {3}",
name,
type,
"[" + string.Join(",", shape) + "]",
"{" + quantizationParams + "}");
}
}
private TfLiteModel model = IntPtr.Zero;
private TfLiteInterpreter interpreter = IntPtr.Zero;
private readonly InterpreterOptions options = null;
private readonly GCHandle modelDataHandle;
private readonly Dictionary<int, GCHandle> inputDataHandles = new Dictionary<int, GCHandle>();
private readonly Dictionary<int, GCHandle> outputDataHandles = new Dictionary<int, GCHandle>();
internal TfLiteInterpreter InterpreterPointer => interpreter;
public Interpreter(byte[] modelData) : this(modelData, null) { }
public Interpreter(byte[] modelData, InterpreterOptions options)
{
modelDataHandle = GCHandle.Alloc(modelData, GCHandleType.Pinned);
IntPtr modelDataPtr = modelDataHandle.AddrOfPinnedObject();
model = TfLiteModelCreate(modelDataPtr, modelData.Length);
if (model == IntPtr.Zero) throw new Exception("Failed to create TensorFlowLite Model");
this.options = options ?? new InterpreterOptions();
interpreter = TfLiteInterpreterCreate(model, options.nativePtr);
if (interpreter == IntPtr.Zero) throw new Exception("Failed to create TensorFlowLite Interpreter");
}
public virtual void Dispose()
{
if (interpreter != IntPtr.Zero)
{
TfLiteInterpreterDelete(interpreter);
interpreter = IntPtr.Zero;
}
if (model != IntPtr.Zero)
{
TfLiteModelDelete(model);
model = IntPtr.Zero;
}
options?.Dispose();
foreach (var handle in inputDataHandles.Values)
{
handle.Free();
}
foreach (var handle in outputDataHandles.Values)
{
handle.Free();
}
modelDataHandle.Free();
}
public virtual void Invoke()
{
ThrowIfError(TfLiteInterpreterInvoke(interpreter));
}
public int GetInputTensorCount()
{
return TfLiteInterpreterGetInputTensorCount(interpreter);
}
public void SetInputTensorData(int inputTensorIndex, Array inputTensorData)
{
if (!inputDataHandles.TryGetValue(inputTensorIndex, out GCHandle tensorDataHandle))
{
tensorDataHandle = GCHandle.Alloc(inputTensorData, GCHandleType.Pinned);
inputDataHandles.Add(inputTensorIndex, tensorDataHandle);
}
IntPtr tensorDataPtr = tensorDataHandle.AddrOfPinnedObject();
TfLiteTensor tensor = TfLiteInterpreterGetInputTensor(interpreter, inputTensorIndex);
ThrowIfError(TfLiteTensorCopyFromBuffer(tensor, tensorDataPtr, Buffer.ByteLength(inputTensorData)));
}
public unsafe void SetInputTensorData<T>(int inputTensorIndex, in ReadOnlySpan<T> inputTensorData)
where T : unmanaged
{
fixed (T* dataPtr = inputTensorData)
{
IntPtr tensorDataPtr = (IntPtr)dataPtr;
TfLiteTensor tensor = TfLiteInterpreterGetInputTensor(interpreter, inputTensorIndex);
ThrowIfError(TfLiteTensorCopyFromBuffer(
tensor, tensorDataPtr, inputTensorData.Length * UnsafeUtility.SizeOf<T>()));
}
}
public unsafe void SetInputTensorData<T>(int inputTensorIndex, in NativeArray<T> inputTensorData)
where T : unmanaged
{
IntPtr tensorDataPtr = (IntPtr)NativeArrayUnsafeUtility.GetUnsafePtr(inputTensorData);
TfLiteTensor tensor = TfLiteInterpreterGetInputTensor(interpreter, inputTensorIndex);
ThrowIfError(TfLiteTensorCopyFromBuffer(
tensor, tensorDataPtr, inputTensorData.Length * UnsafeUtility.SizeOf<T>()));
}
public void ResizeInputTensor(int inputTensorIndex, int[] inputTensorShape)
{
ThrowIfError(TfLiteInterpreterResizeInputTensor(
interpreter, inputTensorIndex, inputTensorShape, inputTensorShape.Length));
}
public void AllocateTensors()
{
ThrowIfError(TfLiteInterpreterAllocateTensors(interpreter));
}
public int GetOutputTensorCount()
{
return TfLiteInterpreterGetOutputTensorCount(interpreter);
}
public void GetOutputTensorData(int outputTensorIndex, Array outputTensorData)
{
if (!outputDataHandles.TryGetValue(outputTensorIndex, out GCHandle tensorDataHandle))
{
tensorDataHandle = GCHandle.Alloc(outputTensorData, GCHandleType.Pinned);
outputDataHandles.Add(outputTensorIndex, tensorDataHandle);
}
IntPtr tensorDataPtr = tensorDataHandle.AddrOfPinnedObject();
TfLiteTensor tensor = TfLiteInterpreterGetOutputTensor(interpreter, outputTensorIndex);
ThrowIfError(TfLiteTensorCopyToBuffer(tensor, tensorDataPtr, Buffer.ByteLength(outputTensorData)));
}
public unsafe void GetOutputTensorData<T>(int outputTensorIndex, in Span<T> outputTensorData)
where T : unmanaged
{
fixed (T* dataPtr = outputTensorData)
{
IntPtr tensorDataPtr = (IntPtr)dataPtr;
TfLiteTensor tensor = TfLiteInterpreterGetOutputTensor(interpreter, outputTensorIndex);
ThrowIfError(TfLiteTensorCopyToBuffer(
tensor, tensorDataPtr, outputTensorData.Length * UnsafeUtility.SizeOf<T>()));
}
}
public TensorInfo GetInputTensorInfo(int index)
{
TfLiteTensor tensor = TfLiteInterpreterGetInputTensor(interpreter, index);
return GetTensorInfo(tensor);
}
public TensorInfo GetOutputTensorInfo(int index)
{
TfLiteTensor tensor = TfLiteInterpreterGetOutputTensor(interpreter, index);
return GetTensorInfo(tensor);
}
/// <summary>
/// Returns a string describing version information of the TensorFlow Lite library.
/// TensorFlow Lite uses semantic versioning.
/// </summary>
/// <returns>A string describing version information</returns>
public static string GetVersion()
{
return Marshal.PtrToStringAnsi(TfLiteVersion());
}
private static string GetTensorName(TfLiteTensor tensor)
{
return Marshal.PtrToStringAnsi(TfLiteTensorName(tensor));
}
protected static TensorInfo GetTensorInfo(TfLiteTensor tensor)
{
int[] dimensions = new int[TfLiteTensorNumDims(tensor)];
for (int i = 0; i < dimensions.Length; i++)
{
dimensions[i] = TfLiteTensorDim(tensor, i);
}
return new TensorInfo()
{
name = GetTensorName(tensor),
type = TfLiteTensorType(tensor),
shape = dimensions,
quantizationParams = TfLiteTensorQuantizationParams(tensor),
};
}
protected TfLiteTensor GetInputTensor(int inputTensorIndex)
{
return TfLiteInterpreterGetInputTensor(interpreter, inputTensorIndex);
}
protected TfLiteTensor GetOutputTensor(int outputTensorIndex)
{
return TfLiteInterpreterGetOutputTensor(interpreter, outputTensorIndex);
}
protected static void ThrowIfError(Status status)
{
switch (status)
{
case Status.Ok:
return;
case Status.Error:
throw new Exception("TensorFlowLite operation failed.");
case Status.DelegateError:
throw new Exception("TensorFlowLite delegate operation failed.");
case Status.ApplicationError:
throw new Exception("Applying TensorFlowLite delegate operation failed.");
case Status.DelegateDataNotFound:
throw new Exception("Serialized delegate data not being found.");
case Status.DelegateDataWriteError:
throw new Exception("Writing data to delegate failed.");
case Status.DelegateDataReadError:
throw new Exception("Reading data from delegate failed.");
case Status.UnresolvedOps:
throw new Exception("Ops not found.");
default:
throw new Exception($"Unknown TensorFlowLite error: {status}");
}
}
#region Externs
#if UNITY_IOS && !UNITY_EDITOR
internal const string TensorFlowLibrary = "__Internal";
#elif UNITY_ANDROID && !UNITY_EDITOR
internal const string TensorFlowLibrary = "libtensorflowlite_jni";
#else
internal const string TensorFlowLibrary = "libtensorflowlite_c";
#endif
// TfLiteStatus
public enum Status
{
Ok = 0,
Error = 1,
DelegateError = 2,
ApplicationError = 3,
DelegateDataNotFound = 4,
DelegateDataWriteError = 5,
DelegateDataReadError = 6,
UnresolvedOps = 7,
}
// TfLiteType
public enum DataType
{
NoType = 0,
Float32 = 1,
Int32 = 2,
UInt8 = 3,
Int64 = 4,
String = 5,
Bool = 6,
Int16 = 7,
Complex64 = 8,
Int8 = 9,
Float16 = 10,
Float64 = 11,
Complex128 = 12,
UInt64 = 13,
Resource = 14,
Variant = 15,
UInt32 = 16,
UInt16 = 17,
}
public struct QuantizationParams
{
public float scale;
public int zeroPoint;
public override string ToString()
{
return string.Format("scale: {0} zeroPoint: {1}", scale, zeroPoint);
}
}
[DllImport(TensorFlowLibrary)]
private static extern unsafe IntPtr TfLiteVersion();
[DllImport(TensorFlowLibrary)]
private static extern unsafe TfLiteInterpreter TfLiteModelCreate(IntPtr model_data, int model_size);
[DllImport(TensorFlowLibrary)]
private static extern unsafe void TfLiteModelDelete(TfLiteModel model);
[DllImport(TensorFlowLibrary)]
private static extern unsafe TfLiteInterpreter TfLiteInterpreterCreate(
TfLiteModel model,
TfLiteInterpreterOptions optional_options);
[DllImport(TensorFlowLibrary)]
private static extern unsafe void TfLiteInterpreterDelete(TfLiteInterpreter interpreter);
[DllImport(TensorFlowLibrary)]
private static extern unsafe int TfLiteInterpreterGetInputTensorCount(
TfLiteInterpreter interpreter);
[DllImport(TensorFlowLibrary)]
private static extern unsafe TfLiteTensor TfLiteInterpreterGetInputTensor(
TfLiteInterpreter interpreter,
int input_index);
[DllImport(TensorFlowLibrary)]
private static extern unsafe Status TfLiteInterpreterResizeInputTensor(
TfLiteInterpreter interpreter,
int input_index,
int[] input_dims,
int input_dims_size);
[DllImport(TensorFlowLibrary)]
private static extern unsafe Status TfLiteInterpreterAllocateTensors(
TfLiteInterpreter interpreter);
[DllImport(TensorFlowLibrary)]
private static extern unsafe Status TfLiteInterpreterInvoke(TfLiteInterpreter interpreter);
[DllImport(TensorFlowLibrary)]
private static extern unsafe int TfLiteInterpreterGetOutputTensorCount(
TfLiteInterpreter interpreter);
[DllImport(TensorFlowLibrary)]
private static extern unsafe TfLiteTensor TfLiteInterpreterGetOutputTensor(
TfLiteInterpreter interpreter,
int output_index);
[DllImport(TensorFlowLibrary)]
private static extern unsafe DataType TfLiteTensorType(TfLiteTensor tensor);
[DllImport(TensorFlowLibrary)]
private static extern unsafe int TfLiteTensorNumDims(TfLiteTensor tensor);
[DllImport(TensorFlowLibrary)]
private static extern int TfLiteTensorDim(TfLiteTensor tensor, int dim_index);
[DllImport(TensorFlowLibrary)]
private static extern uint TfLiteTensorByteSize(TfLiteTensor tensor);
[DllImport(TensorFlowLibrary)]
private static extern unsafe IntPtr TfLiteTensorName(TfLiteTensor tensor);
[DllImport(TensorFlowLibrary)]
private static extern unsafe QuantizationParams TfLiteTensorQuantizationParams(TfLiteTensor tensor);
[DllImport(TensorFlowLibrary)]
private static extern unsafe Status TfLiteTensorCopyFromBuffer(
TfLiteTensor tensor,
IntPtr input_data,
int input_data_size);
[DllImport(TensorFlowLibrary)]
private static extern unsafe Status TfLiteTensorCopyToBuffer(
TfLiteTensor tensor,
IntPtr output_data,
int output_data_size);
#endregion
}
}
```
I used some debugs to check the problem. it is printing this
Model path: D:/MainProject/github/tf-lite-unity-sample-master/Assets/StreamingAssets\project.tflite
UnityEngine.Debug:Log (object)
ImageClassifier:Start () (at Assets/Samples/Detection/Scripts/PythonBridge.cs:25)
Label path: D:/MainProject/github/tf-lite-unity-sample-master/Assets/StreamingAssets\class_labels.txt
UnityEngine.Debug:Log (object)
ImageClassifier:Start () (at Assets/Samples/Detection/Scripts/PythonBridge.cs:26)
Loading model from path: D:/MainProject/github/tf-lite-unity-sample-master/Assets/StreamingAssets\project.tflite
UnityEngine.Debug:Log (object)
ImageClassifier:LoadModelAndLabels (string,string) (at Assets/Samples/Detection/Scripts/PythonBridge.cs:49)
ImageClassifier:Start () (at Assets/Samples/Detection/Scripts/PythonBridge.cs:28)
But model is not loaded succesfully |
Tensorflow Lite error Unity : NullReferenceException: Object reference not set to an instance of an object |
|c#|unity-game-engine|tensorflow-lite| |
null |
how do you launched the long and short entry?
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void
Look that the ID must match when you invoque the strategy.close(""...)
Ej:
if long_condition
strategy.entry("Long",...)
if close_condition
strategy.close("Long",...)
For more deep analysis please create and post a [Minimal Reproductible Example][1]
[1]: https://stackoverflow.com/help/minimal-reproducible-example |
I get a similar non result with "GetAllConfigurationDataAsync" but the code below, using other methods of the WebsiteResource class, works for me:
var armClient = host.Services.GetRequiredService<ArmClient>();
var resource = new ResourceIdentifier(resourceId);
var website = armClient.GetWebSiteResource(resource);
var connectionStrings = await website.GetConnectionStringsAsync();
foreach (var prop in connectionStrings.Value.Properties)
{
Console.WriteLine($"{prop.Key}:{prop.Value.Value}");
}
var applicationSettings = await website.GetApplicationSettingsAsync();
foreach (var appSetting in applicationSettings.Value.Properties)
{
Console.WriteLine($"{appSetting.Key}:{appSetting.Value}");
} |
It seems like the problem is related to a specific range of Next.js versions rather than an issue with TON Connect.
To resolve this, you have to update or rollback the NextJS version:
Next.js 14.0.1 or earlier — works
Related link https://github.com/ton-connect/sdk/issues/117 |
The below query generates statements to move tables from the "public" schema to "new_schema".
**Update source schema(here: public) and target schema(here: new_schema) accordingly.**
SELECT 'ALTER TABLE ' || quote_ident(schemaname) || '.'
|| quote_ident(tablename) || ' SET SCHEMA new_schema;'
FROM pg_tables
WHERE schemaname = 'public';
**Sample Output:**
+--------------------------------------------------+
| ?column? |
+--------------------------------------------------+
| ALTER TABLE public.error SET SCHEMA new_schema; |
| ALTER TABLE public.error1 SET SCHEMA new_schema; |
| ALTER TABLE public.error2 SET SCHEMA new_schema; |
| ALTER TABLE public.test SET SCHEMA new_schema; |
+--------------------------------------------------+ |
how do you've launched the long and short entry?
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void
Look that the ID must match when you invoque the strategy.close(""...)
Ej:
if long_condition
strategy.entry("Long",...)
if close_condition
strategy.close("Long",...)
For more deep analysis please create and post a [Minimal Reproductible Example][1]
[1]: https://stackoverflow.com/help/minimal-reproducible-example |
I want to create a Snackbar in flutter. I want it to have borders on all 4 corners and have a border width with a different color only at bottom side.
[enter image description here][1]
I couldn't find a way to add both the properties together.
Can someone suggest a way to do it without using external flutter libraries or a Container inside content parameter of the snackbar widget?
I am able to create only one of the required properties separately.
1. I am able to apply border width at bottom with color.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
var snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
shape: const Border(
bottom: BorderSide(
color: Colors.green
width: 4,
content: Flex(
direction: Axis.horizontal,
children: [
Padding(
padding:
const EdgeInsets.only(right: 12),
child:
Icon(Icons.add),
),
Text(
"Toast message",
),
],
),
);
<!-- end snippet -->
[SnackBar with bottom border width][2]
2. I am able to apply corner radius at all 4 corners.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
var snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
shape: const RoundedRectangleBorder(
borderRadius: 8,
),
content: Flex(
direction: Axis.horizontal,
children: [
Padding(
padding:
const EdgeInsets.only(right: 12),
child:
Icon(Icons.add)
),
Text(
"Toast message",
),
],
),
);
<!-- end snippet -->
[Snackbar with border radius][3]
I want to apply both properties together but I am unable to it.
[1]: https://i.stack.imgur.com/opvJS.jpg
[2]: https://i.stack.imgur.com/doAxz.jpg
[3]: https://i.stack.imgur.com/k6GUG.jpg |
Replace your code with this.I have refactor some code like moved you answer1 array to top so you can access your answers. They way you were doing it would be out of memory because of it's scope.
@IBOutlet weak var number1: UILabel!
@IBOutlet weak var number2: UILabel!
@IBOutlet weak var number3: UILabel!
let randomInt1 = Int.random(in: 1..<10)
let randomInt2 = Int.random(in: 1..<10)
var answer1 = [Int]()
@IBAction func StartButton(_ sender: Any) {
number1.text = String(randomInt1)
number2.text = String(randomInt2)
answer1.append(randomInt1 + randomInt2)
} |
> I have created an ASP.Net core (net 8) web application using visual
> studio 2022.
>
> I have set up windows authentication and authorisation to check if
> users exist in an AD group and log them in without having to submit
> credentials.
Well, its hard to infer how did you configured your windows authentication, as you haven't shared with us and that's really important to check.
However, even if you set in `AD group` but if within your project `launchSettings.json` doesn't allowed `"windowsAuthentication": true` you might encounter that issue. So please double check that.
Within your `launchSettings.json`, you should have following configuration:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:3067",
"sslPort": 44358
}
}
[![enter image description here][1]][1]
Beside that, you might need to check your [NegotiateDefaults.AuthenticationScheme][2] configuration because this is also prerequisite for windows authentication.
**Note:** Please make sure you have enabled `windowsAuthentication` to true. In addition, [please refer to this official document.][3]
[1]: https://i.stack.imgur.com/tXYQ5.png
[2]: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-8.0&tabs=visual-studio#iisiis-express
[3]: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-8.0&tabs=visual-studio |
How to supress naive datetime warning in django |
|python|django|datetime| |
Forgot to change the interpreter, the code works fine with those particular versions. |
{"Voters":[{"Id":23799442,"DisplayName":"Kouam Brice"}]} |
This is my code to read the csv file asynchronoulsy using ReadLineAsync() function from the [StreamReader][1] class but it reads first line only of the [csv file][2]
private async Task ReadAndSendJointDataFromCSVFileAsync(CancellationToken cancellationToken) {
Stopwatch sw = new Stopwatch();
sw.Start();
string filePath = @ "/home/adwait/azure-iot-sdk-csharp/iothub/device/samples/solutions/PnpDeviceSamples/Robot/Data/Robots_data.csv";
using(StreamReader oStreamReader = new StreamReader(File.OpenRead(filePath))) {
string sFileLine = await oStreamReader.ReadLineAsync();
string[] jointDataArray = sFileLine.Split(',');
// Assuming the joint data is processed in parallel
var tasks = new List < Task > ();
// Process joint pose
tasks.Add(Task.Run(async () => {
var jointPose = jointDataArray.Take(7).Select(Convert.ToSingle).ToArray();
var jointPoseJson = JsonSerializer.Serialize(jointPose);
await SendTelemetryAsync("JointPose", jointPoseJson, cancellationToken);
}));
// Process joint velocity
tasks.Add(Task.Run(async () => {
var jointVelocity = jointDataArray.Skip(7).Take(7).Select(Convert.ToSingle).ToArray();
var jointVelocityJson = JsonSerializer.Serialize(jointVelocity);
await SendTelemetryAsync("JointVelocity", jointVelocityJson, cancellationToken);
}));
// Process joint acceleration
tasks.Add(Task.Run(async () => {
var jointAcceleration = jointDataArray.Skip(14).Take(7).Select(Convert.ToSingle).ToArray();
var jointAccelerationJson = JsonSerializer.Serialize(jointAcceleration);
await SendTelemetryAsync("JointAcceleration", jointAccelerationJson, cancellationToken);
}));
// Process external wrench
tasks.Add(Task.Run(async () => {
var externalWrench = jointDataArray.Skip(21).Take(6).Select(Convert.ToSingle).ToArray();
var externalWrenchJson = JsonSerializer.Serialize(externalWrench);
await SendTelemetryAsync("ExternalWrench", externalWrenchJson, cancellationToken);
}));
await Task.WhenAll(tasks);
}
sw.Stop();
_logger.LogDebug(String.Format("Elapsed={0}", sw.Elapsed));
}
}
Basically, the csv file has 10128 lines. I want to read the latest line which gets added to the csv file.
How do I do it?
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-8.0
[2]: https://github.com/addy1997/azure-iot-sdk-csharp/blob/main/iothub/device/samples/solutions/PnpDeviceSamples/Robot/Data/Robots_data.csv |
How to read the latest line from the csv file using ReadLineAsync method?? |
|c#|csv| |
**1st way:**
double data[] = { 4.74, 0.58 , 2.7,5.12 , 9.73 , 2.7,0.56 , 9.6 , 2.7,9.1, 0.96 , 2.7,0.57 , 1.07 , 2.7,8.85 ,8.8 , 2.7 };
arma::mat anchorCoords(data, 6, 3, false);
**2nd way:**
arma::mat anchorCoords;
anchorCoords
<< 4.74 << 0.58 << 2.7 << endr
<< 5.12 << 9.73 << 2.7 << endr
<< 0.56 << 9.6 << 2.7 << endr
<< 9.1 << 0.96 << 2.7 << endr
<< 0.57 << 1.07 << 2.7 << endr
<< 8.85 << 8.8 << 2.7;
|
[Some site](https://dequeuniversity.com/rules/axe/4.8/button-name) published the following. Indicated a few solutions, one is the `title` attribute.
> The button-name rule has five markup patterns that pass test criteria:
> ``` <button id="text">Name</button>
>
> <button id="al" aria-label="Name"></button>
>
> <button id="alb" aria-labelledby="labeldiv"></button> <div
> id="labeldiv">Button label</div>
>
> <button id="combo" aria-label="Aria Name">Name</button>
>
> <button id="buttonTitle" title="Title"></button> ``` |
I am trying to write a python script that calculates the area within a matplotlib contour and sums the variable within that same contour in order to calculate the volume and transport within a velocity field.
I have so far tried this method (native to matplotlib and the shoelace method) however I haven't had any success in integrating the two areas outlined in my contour plot

```python
cc_cont = ax1.contour(X,Y,CC_vel,levels=[int(np.nanmax(CC_vel)*CC_percentage)],colors='k')
plt.clabel(cc_cont, inline=True, fontsize=15)
for c in cc_cont.collections:
polygon = c.get_paths()[0]
vertices = polygon.vertices
# print(np.shape(vertices))
area = 0.5 * np.abs(np.dot(vertices[:, 0], np.roll(vertices[:, 1], 1)) - np.dot(vertices[:, 1], np.roll(vertices[:, 0], 1))) # Shoelace formula
ax1.add_patch(Polygon(vertices, color='red', alpha=0.6))
print(f'Area within contour: {area}')
variable_sum = np.sum(CC_vel[(X >= min(vertices[:, 0])) & (X <= max(vertices[:, 0])) & (Y >= min(vertices[:, 1])) & (Y <= max(vertices[:, 1]))]) # Sum variable within contour
print(f'Sum of variable within contour: {variable_sum}')
``` |
Integrating within a matplotlib contour |
I am getting an `Object.dispatchError` when I run my unit test for my custom `useFetch` hook.
The hook:
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
const apiCall = async () => {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`Error - ${res.status}`);
const json = await res.json();
setData(json);
setError(null);
} catch (err) {
setError(`useFetch Error!`);
} finally {
setLoading(false);
}
};
apiCall();
}, [url]);
return { data, loading, error };
};
export default useFetch;
My unit test:
import { renderHook, waitFor } from "@testing-library/react";
import useFetch from './useFetch';
it('Should handle no URL provided', async () => {
const { result } = renderHook(() => useFetch());
await waitFor(() => {
expect(result.current.error).toBe("useFetch Error!");
});
});
The error:
console.error
Error: AggregateError
at Object.dispatchError (jsdom\living\xhr\xhr-utils.js:63:19)
at Request.<anonymous> (jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:655:18)
at Request.emit (node:events:531:35)
at ClientRequest.<anonymous> (jsdom\lib\jsdom\living\helpers\http-request.js:121:14)
at ClientRequest.emit (node:events:519:28)
at Socket.socketErrorListener (node:_http_client:492:9)
at Socket.emit (node:events:519:28)
at emitErrorNT (node:internal/streams/destroy:169:8)
at emitErrorCloseNT (node:internal/streams/destroy:128:3)
at processTicksAndRejections (node:internal/process/task_queues:82:21) undefined
Maybe it is my `waitFor()` in the unit test that is not written correctly?
How should I unit test my custom hook?
Cheers!
StackBlitz: [useFetch Custom Hook][1]
(Although, how you can run unit tests in stackblitz is beyond me...)
[1]: https://stackblitz.com/edit/vitejs-vite-nnsfq2?file=src%2Fhooks%2FuseFetch.js |
|java|mysql|jdbc| |
I have an extremely weird situation on my machine debugging my application.
macOS: 14.4 (23E214) - 16GB RAM
PyCharm: PyCharm 2023.3.5 (Community Edition)
Python3.10
PyCharm was reinstalled twice without an effect on the outcome.
I am locally debugging with databricks.connect fetching some data (batch 1000 rows one after another) and then I am transforming the data into local objects (330) each has like 20 fields - so nothing memory intense etc. Activity Monitor also shows no abnormalities.
The fun part are those lines:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
def set_value_fast(self, twin_id: str, key: str, value: str):
if self.row_item_dict is None:
dummy_row = create_row_from_schema(self._schema)
self.row_item_dict = dummy_row.asDict()
self.row_item_dict[self._primary_key] = twin_id
self.row_item_dict[key] = value # self._assign_value_based_on_data_type(key, value)
else:
self.row_item_dict[key] = value # self._assign_value_based_on_data_type(key, value)
<!-- end snippet -->
It does not crash and creates my dictionary as expected. If I am using the commented function instead - please do not comment an the date conversion I have just tried millions of things as I thought that this is the reason for the issue somehow.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
self.row_item_dict[key] = self._assign_value_based_on_data_type(key, value)
def _assign_value_based_on_data_type(self, key, value):
for time_stamp_column in self._time_stamp_columns:
if key == time_stamp_column:
try:
print(f"twinId: {self.twin_id} key: {key} value: {value}")
if value is None or value == '':
return None
if len(value.split('.')) > 1 and len(value.split('.')[1]) > 3:
# If microseconds are present, truncate to milliseconds
date_string = '.'.join(value.split('.')[:2])[:23] # Truncate to milliseconds
# Convert date string to datetime
datetime_obj = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f')
# Set timezone to UTC
datetime_obj = datetime_obj.replace(tzinfo=timezone.utc)
return datetime_obj
except Exception as e:
print("An error occurred:", e)
return value
<!-- end snippet -->
when starting with debug this immediately happens on the output:
twinId: XXXX#ZZZZ key: createdAt value: 2021-04-03T02:06:57.606Z
/usr/local/Cellar/python@3.10/3.10.13_2/Frameworks/Python.framework/Versions/3.10/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 2 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '
When I just run the code without debugger then I am getting all objects converted without any issues?
Can anyone give me a hint what could cause this behavior as I really have no idea any more what to do.
I hope I provided all necessary information, if you require more info please let me know.
Thanks,
Andre
|
I want to create feature information based only on the similarity information of each drug, but is it possible to use the method using truncated PCA without any abnormalities?
If there is a problem, what are the other ways?
I've tried embedding using random walk, but I'm looking for other ways because I don't seem to get the results I want. |
How to get Feature from Drug's Similarity matrix? |
|charts|embedding|feature-engineering| |
null |
I know that this question was already asked. But I would like open it again, if there are any updates. I have problem with bundle size with using `react-icons`. Docs says to use `@react-icons/all-files` but there's problem that there are not all icons. I liked that library, because it saved me a lot of time, but now, when I figure out that problem with bundle size causes that library, it became kinda useless. Why only this library has so big size...
Babel.config.js
```
module.exports = {
presets: [
[
"@babel/preset-env",
{
"useBuiltIns": "entry",
"modules": false
}
],
"@babel/preset-react",
"@babel/preset-typescript"
]
}
```
webpack.js
```
module: {
rules: [
{
test: /\.(ts|tsx|js|mjs|jsx)$/,
exclude: /nodeModules/,
use: {
loader: "babel-loader"
}
},
...
```
This bundle size is really ridiculous so I'm thinking of hiring a graphic designer to create my own icons. |
React icons increase bundle size |
|reactjs|webpack|react-icons| |
According to the `Route` component's [`shouldRevalidate`][1] prop there are several ways the route data is revalidated.
> There are several instances where data is revalidated, keeping your UI
> in sync with your data automatically:
>
> * After an [`action`][2] is called from a [`<Form>`][3].
> * After an [`action`][2] is called from a [`<fetcher.Form>`][4]
> * After an [`action`][2] is called from [`useSubmit`][5]
> * After an [`action`][2] is called from a [`fetcher.submit`][4]
> * When an explicit revalidation is triggered via [`useRevalidator`][6]
> * When the [URL params][7] change for an already rendered route
> * When the URL Search params change
> * When navigating to the same URL as the current URL
The `useRevalidator` hook is the likely choice for your use case.
> This hook allows you to revalidate the data for any reason. React
> Router automatically revalidates the data after actions are called,
> but you may want to revalidate for other reasons like when focus
> returns to the window.
```javascript
import { useRevalidator } from "react-router-dom";
...
const revalidator = useRevalidator();
...
const callback = () => revalidator.revalidate();
...
```
Another trivial method is to initiate a navigation action to the current route, i.e. "navigating to the same URL as the current URL".
```javascript
import { useNavigate } from "react-router-dom";
...
const navigate = useNavigate();
...
const callback = () => navigate(".", { replace: true });
...
```
[1]: https://reactrouter.com/en/main/route/should-revalidate
[2]: https://reactrouter.com/en/main/route/action
[3]: https://reactrouter.com/en/main/components/form
[4]: https://reactrouter.com/en/main/hooks/use-fetcher
[5]: https://reactrouter.com/en/main/hooks/use-submit
[6]: https://reactrouter.com/en/main/hooks/use-revalidator
[7]: https://reactrouter.com/en/main/route/route#dynamic-segments |
You can build two masks, one to identify the Role change, and one to identify the difference of index above threshold (with [`diff`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.diff.html)). Then combine the masks with `|` before running the `cumsum`:
```
m1 = df.Role!= df.Role.shift()
m2 = df['Index'].diff().gt(5)
out = df.groupby((m1|m2).cumsum()).agg(
Role = ('Role', 'first'),
Name = ('Name', ' '.join),
Grade = ('Grade', 'mean')
).reset_index(drop=True)
```
Output:
```
Role Name Grade
0 Provider Alex William Juan 6.666667
1 Provider Pedro 4.500000
2 Client George 8.000000
3 Provider Mark 9.400000
4 Client James 8.100000
5 Transporter Anthony 9.500000
6 Transporter Jason 7.000000
```
Intermediates:
```
Index Role Name Grade m1 m2 m1|m2 cumsum
0 1 Provider Alex 7.0 True False True 1
1 2 Provider William 7.5 False False False 1
2 7 Provider Juan 5.5 False False False 1
3 15 Provider Pedro 4.5 False True True 2
4 25 Client George 8.0 True True True 3
5 26 Provider Mark 9.4 True False True 4
6 37 Client James 8.1 True True True 5
7 39 Transporter Anthony 9.5 True False True 6
8 50 Transporter Jason 7.0 False True True 7
``` |
{"OriginalQuestionIds":[77898909],"Voters":[{"Id":13625293,"DisplayName":"Dhafin Rayhan"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]} |