instruction stringlengths 0 30k ⌀ |
|---|
|python|pycharm|cpython|micropython|raspberry-pi-pico| |
null |
I have two tables: Schedules and Tasks, with a one-to-one relation
```
class Schedule extends Model
{
public function task() {
return $this->belongsTo(Task::class, 'task_id');
}
```
And the Task model has a one-to-many relation with Spatie Roles with a task_role pivot table:
```
class Task extends Model
{
public function roles() {
return $this->belongsToMany(Role::class);
}
```
How can I make a query that retrieves all schedules associated with cards with permission for the logged in user?
For example:
Tasks:
| id | name |
| -------- | -------------- |
| 1| task1|
| 2| task2 |
| 3| task3 |
task_role:
| task_id | role_id |
| -------- | -------------- |
| 1| 1|
| 2| 3 |
| 3| 1|
Schedule:
| id| name | task_id |
| -------- | -------------- |-|
| 1| schedule1|1
| 2| schedule2|1
| 3| schedule3|5
Spatie model_has_roles:
| role_id| model_type| model_id|
| -------- | -------------- |-|
| 1| App\Models\User|2
| 2| App\Models\User|1
| 3| App\Models\User|5
When user2 is logged in he should be able to see only schedule 1 and 2. |
I am having hard time wrapping my head around types and references in rust. For eg., I have this code:
let my_arr = [3, 5, 4, 88, 77];
let my_slice1 = &my_arr;
let my_slice2: &[i32] = &my_arr;
IDE suggests my_slice1 is of type &[i32, 5] ie reference type to array of type [i32, 5].
If this suggestion is correct, then my_slice1 and my_slice2 are of different types even though they have been assigned same value(&my_arr).
Is some implicit conversion happening for my_slice2? |
Different types even though same value assigned |
|rust| |
**Notifications work differently in (Android and iOS) and (Foreground and background).**
> 1. Notifications within Android depend on the **notification channel
setup and channel ID passed** in the payload.
> 2. Notification customization within iOS depends on the **sound file
passed in the payload**.
If you want to set the sound for two different types of notifications in Android, you first need to **create two separate channels and pass the channel ID** with the specific sound while triggering the notification from the backend.
Here is the step-by-step instructions.
**Step 1: Add the Sound File into the IOS resources and Android raw Folder.**
**Step 2: Setup keep.xml File Under Raw Folder.**
[Click here to see the code][1]
**Step 3: Setup show notification channel function for Foreground.**
AndroidNotificationChannel? channel;
if (message.notification?.body == "You have one Booking Request") {
channel = AndroidNotificationChannel(
'Sound', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.high,
sound: RawResourceAndroidNotificationSound(
message.notification?.android?.sound),
playSound: true,
);
} else {
channel = const AndroidNotificationChannel(
'normal', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.high,
playSound: true,
);
}
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
Here **Sound** and **normal** are channel ID. There are channels created for different sounds "Sound" and "normal",
> 1. Within **Sound** channel ID, the customized sound will ring
> 2. Within **normal** channel ID, the system default ring will ring when a notification comes.
You can set up many more channels based on your needs There is no limit to creating a channel.
**Note:** Within Android, **once a channel is created from a channel ID, it remains in the same configuration until the application is uninstalled**. Different channel ID can lead to different channel configurations. But remains the same for one channel ID. When the application is in the kill state and a notification arrives from the same channel ID, it automatically takes over the channel ID's configuration like sound, icon, and other customizations from the channel that was created. And there is no need to create a channel ID in iOS
**Step 4: Update your payload from where the notification is created.**
const message = {
token: token,
notification: {
title,
body,
},
apns: {
headers: {
"apns-priority": "10",
},
payload: {
aps: {
sound:
body != "You have one Booking Request"
? "default"
: "ringtone.wav",
},
},
},
android: {
priority: "high",
notification: {
channelId:
body != "You have one Booking Request" ? "normal" : "Sound",
},
},
data: {
click_action,
},
};
From this code, you can extract the example that
1. within iOS you need to **conditionally pass a sound file** to the
notification client. If you want to play the default notification
you need to pass the word "default".
2. And within Android, you specifically need to **pass the channel ID** to
customize the notification. As you can see in the code sound and
normal are being conditionally passed.
You can integrate two different or more than two types of sound notifications by replacing this **body != "You have one Booking Request" ? "normal" : "Sound"** with a condition as per your requirement.
Boom, now a different notification sound is working whether the app is closed or open
[1]: https://i.stack.imgur.com/cTuxt.png |
Since you only want the side menu to show when a left-to-right drag happens on the first tab view, I would suggest applying the drag gesture to the content of view 1 only. And since we are talking about a left-to-right drag, it is probably reasonable to expect it to start on the left-side of the screen. In fact, I would expect that many users will probably "pull" the menu from near the left edge, if they know it's there.
The example below uses an overlay that covers just the left-side of view 1. The width of the overlay is half the width of the menu. The overlay has an opacity of 0.001, which makes it effectively invisible, but this allows it to be used for capturing the drag gesture.
Here is how the (white) overlay would look if the opacity would be 0.5 instead of 0.001:

When a drag gesture is detected that starts on the overlay and continues for a minimum of one-quarter of the menu width, the menu is brought into view. Any drag gesture from right-to-left that begins in the uncovered part of the view (on the right) will be handled by the `TabView` in the usual way.
When the menu is showing, the overlay expands to cover the full width of the menu, so that any drag that starts over the menu can be detected. Here is how it looks when the opacity is 0.5 instead of 0.001:

The menu can be hidden again with a drag gesture from right-to-left that begins over the menu. A small part of view 1 is still visible on the right and the menu can also be hidden by tapping in this area. However, if a right-to-left drag gesture begins in this area then it is handled by the `TabView`. This allows view 2 to be brought into view without having to close the menu first.
Views 2 and 3 are not impacted by the overlay on view 1, so drag gestures are handled by the `TabView` in the normal way with these views.
The updated example is shown below. Some more notes:
- A `GeometryReader` is used to measure the width of the screen, instead of using the first window scene as you were doing before. A `GeometryReader` also works on an iPad when split screen is used.
- `MainView` is now integrated into `FeedBaseView`, but view 1 has been factored out as a separate view. The side-menu view is unchanged, but I gave it a capitalized name (which is more conventional).
- You were applying a blur to view 1 when the menu is showing. This causes the background color of the screen to show through at the edges, so when the background is white, the edges get brighter. To mask this on the left edge where it is connected to the menu, a `zIndex` and also a shadow effect are applied to the menu.
- I found that `.animation` modifiers did not seem to work when applied to the content of view1. I don't know why not, but suspect that it may be because the view is nested inside a `TabView`. However, animations work fine when changes are applied `withAnimation`.
- I didn't understand what the first responder calls were doing in your original code so I stripped these out. If you really need them then hopefully it is clear where to put them back in.
```swift
struct View1WithMenu: View {
let screenWidth: CGFloat
let sideBarWidth: CGFloat
@State var showMenu: Bool = false
@GestureState var dragOffset: CGFloat = 0
private func revealFraction(sideBarWidth: CGFloat) -> CGFloat {
showMenu ? 1 : max(0, min(1, dragOffset / (sideBarWidth / 2)))
}
init(screenWidth: CGFloat) {
self.screenWidth = screenWidth
self.sideBarWidth = screenWidth - 90
}
var body: some View {
HStack(spacing: 0) {
SideMenu()
.frame(width: sideBarWidth)
.shadow(
color: Color(white: 0.2),
radius: revealFraction(sideBarWidth: sideBarWidth) * 10
)
.zIndex(1) // to cover the blur at the edge
ZStack {
Color.blue
Text("tab 0")
}
.frame(width: screenWidth)
.blur(radius: revealFraction(sideBarWidth: sideBarWidth) * 4)
.overlay {
Color.black
.opacity(revealFraction(sideBarWidth: sideBarWidth) * 0.2)
.onTapGesture {
if showMenu {
UIImpactFeedbackGenerator(style: .light).impactOccurred()
withAnimation { showMenu = false }
}
}
}
}
.offset(x: showMenu ? sideBarWidth / 2 : -sideBarWidth / 2)
.offset(x: dragOffset)
.overlay(alignment: .leading) {
Color.white
.opacity(0.001) //Change to 0.1 to see it
.frame(width: sideBarWidth + (showMenu ? sideBarWidth / 2 : 0))
.gesture(
DragGesture(minimumDistance: 1)
.updating($dragOffset) { value, state, trans in
let minOffset = showMenu ? -sideBarWidth : 0
let maxOffset = showMenu ? 0 : sideBarWidth
state = max(minOffset, min(maxOffset, value.translation.width))
}
.onEnded { value in
withAnimation {
showMenu = value.translation.width >= sideBarWidth / 4
}
}
)
}
.onDisappear {
showMenu = false
}
}
}
struct FeedBaseView: View {
@State var selection: Int = 0
var body: some View {
GeometryReader { proxy in
TabView(selection: $selection) {
View1WithMenu(screenWidth: proxy.size.width)
.tag(0)
ZStack {
Color.red
Text("tab 1")
}
.tag(1)
ZStack {
Color.green
Text("tab 2")
}
.tag(2)
}
.tabViewStyle(.page)
}
}
}
```
 |
I'm looking for an equivalent to x86/64's FTZ/DAZ instructions found in <immintrin.h>, but for M1/M2/M3. Also, is it safe to assume that "apple silicon" equals ARM? |
How to flush denormal numbers to zero for apple silicon? |
|apple-silicon|denormal-numbers| |
I want to install pydantic_core package in Pythonista app on iOS.
I have installed stash in Pythonista. Than I run stash and do:
pip install pydantic_core
I get the following error message:
```
15:03 Sun 31 Mar
StaSh
Console
stash: `C
KeyboardInterrupt: Exit: 0
StaSh v0.7.5 on python 3.10.4
Warning: you are running StaSh in python3. Some commands may not work correctly in python3.
Please help us improve StaSh by reporting bugs on github.
Tip: Improve script-compatibility with the monkeylord command
[~/Documents]$ pip install pydantic_core
site-packages/stash/bin/pip.py:35: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
from distutils.util import convert_path
Querying PyPI ...
Downloading package ...
Opening: https://files.pythonhosted.org/packages/27/2a/af32a000af1affa8998a442d79841f4ad1a6408cc8ca0c00a5be2390124677f/
pydantic_core-2.17.0.tar.gz
Save as: /private/var/mobile/Containers/Data/Application/24B05C11-9B6C-439F-A409-20E212C33565/tmp/pydantic_core-2.17.0.tar.gz
(379628 bytes)
[==================================================] 100.00% | 370.7KiB
stash: `C
KeyboardInterrupt: Exit: 0
Extracting archive file ...
Archive extracted.
Running setup file ...
FileNotFoundError(2, 'No such file or directory')
Failed to run setup.py
Fall back to directory guessing ...
Error: Cannot locate packages. Manual installation required.
stash: `C
KeyboardInterrupt: Exit: 1
[~/Documents]$
```
Any ideas how to make it work? I was able to install some other packages like ‘openai’ ‘type_extensions’ and ‘pedantic’ using stash and ‘pip install’. |
How to install pydantic_core in Pythonista? |
|pip|pydantic|pythonista| |
null |
I want to design python web scraping code to scrape these data (https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page).
Here is the code:
```
import os
import requests
import random
import time
import pyarrow.parquet as pq
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from fake_useragent import UserAgent
# URL de la page contenant les liens vers les datasets
base_url = "https://d37ci6vzurychx.cloudfront.net/trip-data/"
response = requests.get(base_url)
soup = BeautifulSoup(response.text, "html.parser")
# Chemin où enregistrer les fichiers
download_directory = "C:/Users/flosr/Engineering/Blent.ai Project/datas"
# Fonction pour télécharger un fichier avec un en-tête utilisateur aléatoire et une pause aléatoire
def download_file(url, file_path):
user_agent = UserAgent().random
headers = {"User-Agent": user_agent}
time.sleep(random.uniform(1, 3)) # Ajouter une pause aléatoire entre 1 et 3 secondes
response = requests.get(url, headers=headers)
with open(file_path, "w") as f:
f.write(response.content)
# Parcourir chaque section contenant les liens pour chaque année
for section in soup.find_all("div", class_="faq-answers"):
year = section.find_previous_sibling("div", class_="faq-questions").text.strip()
print(f"Downloading datasets for year {year}...")
# Créer un sous-répertoire pour chaque année
year_directory = os.path.join(download_directory, year)
os.makedirs(year_directory, exist_ok=True)
# Télécharger les fichiers pour chaque mois de l'année
for link in section.find_all("a"):
file_url = urljoin(base_url, link.get("href"))
filename = os.path.basename(file_url)
file_path = os.path.join(year_directory, filename)
# Télécharger le fichier
print(f"Downloading {filename}...")
download_file(file_url, file_path)
# Convertir le fichier Parquet
pq.write_table(pq.read_table(file_path), file_path.replace('.parquet', '.csv'))
print("Download and conversion complete.")
```
Here is the output :
PS C:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code> & 'c:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code\env\Scripts\python.exe' 'c:\Users\flosr\.vscode\extensions\ms-python.debugpy-2024.2.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '63645' '--' 'C:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code\env\main.py'
Download and conversion complete.
However, nothing appears in the said directory. No error appearing but it still doesnt work. and for some reason it never stops installing dependencies below without any end.
cant try anything if i dont have any error appearing to know whats the problem |
Async functions return a resolved promise if the return statement intends to return a regular value other than a promise.
This return value should be handled with await or via the Promise mechanism.
let res = await myAsyncFunc()
console.log(res)
//or
let res = myAsyncFunc()
res.then((resolved => console.log(resolved))) |
You should see html pages as completely isolated programs. Every time you click a link, or reload a page, the following thing happens:
- the current page is removed
- all the javascript code in the current page stops running
- all the variables your code created, stop existing
then
- the new html page is downloaded, and rendered
- all the javascript files in the new html page are executed, from scratch.
- the code doesn't know anything about what was in the previous page, it doesn't even know what is in other browser tabs.
Your issue comes from the fact that you have two separate html pages. Even though you included the same javascript file in both of them, this does not mean that there is shared data between them. The global variable in the second page will not contain the value set in the first page.
The correct solution for your case should be to pass the data about the image you want to open in the url:
in index.html, modify the urls to be like this:
```html
<div id="extrait">
<a href="gallery.html#1"><img src="assets/image1.jpg" alt="Image 1" onclick="updateIndex(1)"></a>
<a href="gallery.html#2"><img src="assets/image2.jpg" alt="Image 2" onclick="updateIndex(2)"></a>
<a href="gallery.html#3"><img src="assets/image3.jpg" alt="Image 3" onclick="updateIndex(3)"></a>
</div>
```
in the javascript code, you can add some code that as soon as the page loads:
- checks the url, and retieves the hash, which is the part of the url after the # symbol.
- set the current index based on that hash
```js
const galleryImages = document.querySelectorAll('#carousel img');
let currentIndex = 0;
document.addEventListener("DOMContentLoaded", function() {
// Get the hash from the URL
var hash = window.location.hash.substr(1);
// Show the image corresponding to the hash
if (hash) {
currentIndex = Number(hash);
showImage(currentIndex);
}
});
// the rest of your code ...
```
Note that this script is required only in the gallery.html page
|
My Delphi Alexandria program associates certain file extensions in Registry with the Application's Exename, such that Windows shows the right icon. But I am struggling to get my program to notice a request when I double-click on a file of the correct type in Explorer. What I want is to intercept the call depending on its file extension passed through Paramcount and ParaStr(1) etc. How do I set things up in the .dpr file to
- a) notice there is a request for a filename
- b) work out whether the program is already running
- c) pass the parameters on if so, or
- d) start the program with the parameter?
d) is already OK but I don't know how to set up a)
Thanks |
How to detect file open requests from Explorer in Delphi? |
|delphi|file-extension|paramstr| |
I can try to explain it in plain English...
First you should have a look at the [link][1] Jean-Francois Corbett wrote as a comment.
### Definition
(from Wikipedia)
> A system is self-stabilizing if and only if:
>
> - Starting from any state, it is guaranteed that the system will eventually reach a correct state (convergence).
> - Given that the system is in a correct state, it is guaranteed to stay in a correct state, provided that no fault happens (closure).
### Notations
Same as the one on the seminar paper
### Self Stabilizing system
In his paper Dijkstra defines a self stabilizing system as follow:
Consider a circle graph with N+1 nodes. (From 0 to N+1)
Each node can be in different states.
Each node can have different privilege. (for example xS = xR can be a privilege)
At each step if in one node a privilege is present we will apply a certain rule :
if privilege then "what to do" endif
### Legitimate States
He defines a legitimate state to be a state with only one privilege present.
### Conclusion
If you apply the different rules in Dijkstra's paper for the described system you will get a self-stabilizing system. (cf definition.)
i.e. from any state with n privilege presents (even with multiple privileges for one node) you will reach in a finite number of states a state with only one privilege present, and stay in legitimate states after this state. And you will be able to reach any legitimate state.
You can try yourself with a simple example.
### Example for the 4 states solution
Let's take only a bottom node and a top node:
starting point: (upT,xT) = (0,0) and
(upB,xB) = (1,0)
state1: (upT,xT) = (0,0) and
(upB,xB) = (1,1)
only one privilege present on B => legitimate
state2: (upT,xT) = (0,1) and
(upB,xB) = (1,1)
only one privilege present on T => legitimate
state3: (upT,xT) = (0,1) and
(upB,xB) = (1,0)
only one privilege present on B => legitimate
state4: (upT,xT) = (0,0) and
(upB,xB) = (1,0)
only one privilege present on T => legitimate
and here is a result for 3 nodes: bottom (0) middle (1) top (2): I start with 2 privileges (not legitimate state, then once I get into a legitimate state I stay in it):
{0: [True, False], 1: [False, False], 2: [False, True]}
privilege in bottom
privilege in top
================================
{0: [True, True], 1: [False, False], 2: [False, False]}
first privilege in middle
================================
{0: [True, True], 1: [True, True], 2: [False, False]}
privilege in top
================================
{0: [True, True], 1: [True, True], 2: [False, True]}
second privilege in middle
================================
{0: [True, True], 1: [False, True], 2: [False, True]}
privilege in bottom
================================
{0: [True, False], 1: [False, True], 2: [False, True]}
first privilege in middle
================================
{0: [True, False], 1: [True, False], 2: [False, True]}
privilege in top
================================
{0: [True, False], 1: [True, False], 2: [False, False]}
second privilege in middle
================================
{0: [True, False], 1: [False, False], 2: [False, False]}
privilege in bottom
... etc
Here is a small Python [<=2.7] code (I am not very good at python so it's may be ugly) to test the 4 states methods with a system of n nodes, it stops when you find all the legitimate states:
```python
from copy import deepcopy
import random
n=int(raw_input("number of elements in the graph:"))-1
L=[]
D={}
D[0]=[True,random.choice([True,False])]
for i in range(1,n):
D[i]=[random.choice([True,False]),random.choice([True,False])]
D[n]=[False,random.choice([True,False])]
L.append(D)
D1=deepcopy(D)
def nextStep(G):
N=len(G)-1
print G
Temp=deepcopy(G)
privilege=0
if G[0][1] == G[1][1] and (not G[1][0]):
Temp[0][1]=(not Temp[0][1])
privilege+=1
print "privilege in bottom"
if G[N][1] != G[N-1][1]:
Temp[N][1]=(not Temp[N][1])
privilege+=1
print "privilege in top"
for i in range(1,N):
if G[i][1] != G[i-1][1]:
Temp[i][1]=(not Temp[i][1])
Temp[i][0]=True
print "first privilege in ", i
privilege+=1
if G[i][1] == G[i+1][1] and G[i][0] and (not G[i+1][0]):
Temp[i][0]=False
print "second privilege in ", i
privilege+=1
print "number of privilege used :", privilege
print '================================'
return Temp
D=nextStep(D)
while(not (D in L) ):
L.append(D)
D=nextStep(D)
```
[1]: http://en.wikipedia.org/wiki/Self-stabilization
|
How to create beans of the same class for multiple template parameters in Spring |
|java|spring|apache-kafka|spring-bean| |
A modified version of Matteo Antolini's answer:
import 'package:flutter/material.dart';
class ScreenNavigator {
final BuildContext cx;
ScreenNavigator({
required this.cx,
});
navigate(Widget page, Tween<Offset> tween) {
Navigator.push(
cx,
PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) {
return page;
},
transitionDuration: Durations.long1,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
// create CurveTween
const Curve curve = Curves.ease;
final CurveTween curveTween = CurveTween(curve: curve);
// chain Tween with CurveTween
final Animatable<Offset> chainedTween = tween.chain(curveTween);
final Animation<Offset> offsetAnimation =
animation.drive(chainedTween);
return SlideTransition(position: offsetAnimation, child: child);
},
),
);
}
}
class NavigatorTweens {
static Tween<Offset> bottomToTop() {
const Offset begin = Offset(0.0, 1.0);
const Offset end = Offset(0.0, 0.0);
return Tween(begin: begin, end: end);
}
static Tween<Offset> topToBottom() {
const Offset begin = Offset(0.0, -1.0);
const Offset end = Offset(0.0, 0.0);
return Tween(begin: begin, end: end);
}
static Tween<Offset> leftToRight() {
const Offset begin = Offset(-1.0, 0.0);
const Offset end = Offset(0.0, 0.0);
return Tween(begin: begin, end: end);
}
static Tween<Offset> rightToLeft() {
const Offset begin = Offset(1.0, 0.0);
const Offset end = Offset(0.0, 0.0);
return Tween(begin: begin, end: end);
}
}
you can copy+paste it in a file and use it across your app like:
onTap: () {
ScreenNavigator(cx: context)
.navigate(Page(),NavigatorTweens.leftToRight());
},
to have better understanding of page sliding transition, [read the official document][1]
[1]: https://docs.flutter.dev/cookbook/animation/page-route-animation |
I am experiencing the following problem. When I setup an ADC with DMA for 5 channels, I get lower readings than the expected ones.
We have PCBs of the same batch in 3 countries, but only the ones tested in China are failing. At all times the ADC readings read lower than the expected values for all the ADC channels, but the PCBs at the other countries return the expected reading in all channels. All those PCBs are identical and they are driving small motors, have a keypad, have some LEDs UI, and a UART debugging port were we connect a USB to TTL UART cable.
Here is the ADC configuration with DMA (source code attached too):
We have measured the reference voltage and all the expected voltages on ADC input pins (some are fixed and known) and all looking good too. On the other hand, when I sample only one ADC channel in polling mode, I do not get this problem, the voltages read as expected.
For example: the readings of a healthy ADC reading at 10-bit resolution should read something like 914 raw value which will correspond to 3652mV for the battery voltage, as opposed to the lower reading which will be something like 837 raw value which corresponds to 3346mV for the battery voltage.
```c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file adc.c
* @brief This file provides code for the configuration
* of the ADC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "adc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
/* ADC1 init function */
void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV10;
hadc1.Init.Resolution = ADC_RESOLUTION_10B;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hadc1.Init.LowPowerAutoWait = ENABLE;
hadc1.Init.LowPowerAutoPowerOff = ENABLE;
hadc1.Init.ContinuousConvMode = ENABLE;
hadc1.Init.NbrOfConversion = 5;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.DMAContinuousRequests = ENABLE;
hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED;
hadc1.Init.SamplingTimeCommon1 = ADC_SAMPLETIME_160CYCLES_5;
hadc1.Init.SamplingTimeCommon2 = ADC_SAMPLETIME_160CYCLES_5;
hadc1.Init.OversamplingMode = DISABLE;
hadc1.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_LOW;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLINGTIME_COMMON_1;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_2;
sConfig.Rank = ADC_REGULAR_RANK_3;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_3;
sConfig.Rank = ADC_REGULAR_RANK_4;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
sConfig.Rank = ADC_REGULAR_RANK_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspInit 0 */
/* USER CODE END ADC1_MspInit 0 */
/** Initializes the peripherals clocks
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/* ADC1 clock enable */
__HAL_RCC_ADC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA1 ------> ADC1_IN1
PA2 ------> ADC1_IN2
PA3 ------> ADC1_IN3
*/
GPIO_InitStruct.Pin = V_BAT_IN_Pin|I_BAT_IN_Pin|VARIANT_ID_Pin|BOARD_ID_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* ADC1 DMA Init */
/* ADC1 Init */
hdma_adc1.Instance = DMA1_Channel1;
hdma_adc1.Init.Request = DMA_REQUEST_ADC1;
hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_adc1.Init.Mode = DMA_CIRCULAR;
hdma_adc1.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);
/* ADC1 interrupt Init */
HAL_NVIC_SetPriority(ADC1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(ADC1_IRQn);
/* USER CODE BEGIN ADC1_MspInit 1 */
/* USER CODE END ADC1_MspInit 1 */
}
}
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspDeInit 0 */
/* USER CODE END ADC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC_CLK_DISABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA1 ------> ADC1_IN1
PA2 ------> ADC1_IN2
PA3 ------> ADC1_IN3
*/
HAL_GPIO_DeInit(GPIOA, V_BAT_IN_Pin|I_BAT_IN_Pin|VARIANT_ID_Pin|BOARD_ID_Pin);
/* ADC1 DMA DeInit */
HAL_DMA_DeInit(adcHandle->DMA_Handle);
/* ADC1 interrupt Deinit */
HAL_NVIC_DisableIRQ(ADC1_IRQn);
/* USER CODE BEGIN ADC1_MspDeInit 1 */
/* USER CODE END ADC1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file dma.c
* @brief This file provides code for the configuration
* of all the requested memory to memory DMA transfers.
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dma.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure DMA */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Enable DMA controller clock
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file BxADC.c
* @brief Analogue interface with HAL and data conversions
*
******************************************************************************
* @attention
*
* Copyright Statement:
* Copyright (c) Bboxx Ltd 2023
* The copyright in this document, which contains information of a proprietary and confidential nature,
* is vested in Bboxx Limited. The content of this document may not be used for purposes other
* than that for which it has been supplied and may not be reproduced, either wholly or in part,
* nor may it be used by, or its contents divulged to, any other person who so ever without written permission
* of Bboxx Limited.
*
******************************************************************************
*/
/* USER CODE END Header */
//----------------------------------------------------------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------------------------------------------------------
#include <stdbool.h>
#include "adc.h"
#include "stm32g0xx_hal_adc.h"
#include "main.h"
#include "Bboxx.h"
#include "BxMotor.h"
#include "BxADC.h"
#include "BxMessage.h"
#include "BxSerial.h"
//----------------------------------------------------------------------------------------------------------------------
// Defines
//----------------------------------------------------------------------------------------------------------------------
typedef enum {
V_BAT,
I_BAT,
VARIANT_ID,
BOARD_ID,
TEMPERATURE,
NUM_OF_ADC_CH
} ADC_CHS;
//----------------------------------------------------------------------------------------------------------------------
// Variables
//----------------------------------------------------------------------------------------------------------------------
static uint16_t ADCreadings[NUM_OF_ADC_CH];
static uint16_t ADCoffset;
static uint16_t ADCref = ADCREF;
static uint16_t ADCpsuConv = ((ADCREF*(ADCPSUR1+ADCPSUR2))/(ADCMAX*ADCPSUR1)) * RESULTMAG;
static uint16_t ADCiConv = (ADCREF/(ADCIGAIN*ADCISENSER));
extern ADC_HandleTypeDef hadc1;
//----------------------------------------------------------------------------------------------------------------------
// Functions
//----------------------------------------------------------------------------------------------------------------------
void ADC_Initialise(void)
/**
* @brief Initialises all ADC
* @param None
* @retval None
*/
{
HAL_GPIO_WritePin(En3v3A_GPIO_Port, En3v3A_Pin, GPIO_PIN_RESET); // Turn On current amp power
HAL_GPIO_WritePin(En3v3B_GPIO_Port, En3v3B_Pin, GPIO_PIN_RESET); // Turn On IDs (+Motor) power
HAL_ADC_Start_DMA(&hadc1, (uint16_t*)ADCreadings, sizeof(ADCreadings)/sizeof(ADCreadings[V_BAT])); // start ADC conversion
return;
}
void ADC_Calibrate(void)
/**
* @brief Calibrates ADC
* @param None
* @retval None
*/
{
HAL_Delay(2000);
static bool firstTime = true;
// Run once
while (firstTime) {
// Calibrate to a known voltage such as the battery
uint16_t volt = ADC_Get_Voltage();
if (volt > (uint16_t)3750u) {
firstTime = false; // Stop if battery voltage is reached
ADCoffset = ADCreadings[I_BAT]; // Save the run mode current offset
Set_String_Tx_Buffer("calibration done ");
Message_16_Bit_Number(volt);
Set_String_Tx_Buffer(" mV and ");
Message_16_Bit_Number(ADCref);
Set_String_Tx_Buffer(" mV");
Set_String_Tx_Buffer(NEWLINE);
} else {
ADCref++; // Increase gain via adding error to the reference voltage
}
}
}
uint16_t ADC_Remove_Offset(uint16_t RawValue)
/**
* @brief Removes the offset from the ADC circuit
* @param None
* @retval None
*/
{
if(RawValue < ADCoffset)
RawValue =0;
else
RawValue -= ADCoffset;
return RawValue;
}
uint16_t ADC_Convert_Voltage(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into mM
* @param None
* @retval None
*/
{
uint32_t Result =0;
RawValue =ADC_Remove_Offset(RawValue);
ADCpsuConv = ((ADCref*(ADCPSUR1+ADCPSUR2))/(ADCMAX*ADCPSUR1)) * RESULTMAG;
Result =(ADCpsuConv * RawValue); // scale result
Result =(Result>>ADCVARDIVIDE);
return (uint16_t) Result;
}
uint16_t ADC_Convert_Current(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into mA
* @param None
* @retval None
*/
{
uint32_t Result =0;
RawValue =ADC_Remove_Offset(RawValue);
ADCiConv = (ADCref/(ADCIGAIN*ADCISENSER));
Result = (ADCiConv * RawValue);
Result =(Result>>ADCVARDIVIDE);
return (uint16_t) Result;
}
uint16_t ADC_Convert_ID(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into An ID voltage 10*units
* @param None
* @retval None
*/
{
uint16_t Result16 =0; // For Faster calculation
uint32_t Result32 =0; // For higher resolution
RawValue =ADC_Remove_Offset(RawValue); // Needs 32bit calculation
Result32 =(ADCref * RawValue); // scale result
Result16 =(uint16_t)(Result32>>ADCVARDIVIDE); // mV
Result16 += 50; // add 50mV for rounding up
Result16 = Result16/100; // Scale for 10*units
return (uint8_t) Result16;
}
uint16_t ADC_Get_Voltage(void)
/**
* @brief returns the value of the PSU voltage (mV)
* @param None
* @retval None
*/
{
return ADC_Convert_Voltage(ADCreadings[V_BAT]);
}
uint16_t ADC_Get_Current(void)
/**
* @brief returns the current current value (mA)
* @param None
* @retval None
*/
{
return ADC_Convert_Current(ADCreadings[I_BAT]);
}
uint8_t ADC_Get_Variant(void)
/**
* @brief returns the Variant as defined by R68//R70 in 10*units
* @param None
* @retval None
*/
{
return ADC_Convert_ID(ADCreadings[VARIANT_ID]);
}
uint8_t ADC_Get_BoardID(void)
/**
* @brief returns the ID as defined by R67//R71 in 10*units
* @param None
* @retval None
*/
{
return ADC_Convert_ID(ADCreadings[BOARD_ID]);
}
uint16_t ADC_Get_Temperature(void)
/**
* @brief returns the Temp in 100*C
* @param None
* @retval None
*/
{
return ADCreadings[TEMPERATURE];
}
void ADC_Print_Raw(void)
/**
* @brief Prints the Raw ADC data in serial terminal
* @param None
* @retval None
*/
{
Set_String_Tx_Buffer("ADCref== ");
Message_16_Bit_Number(ADCref);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCpsuConv== ");
Message_16_Bit_Number(ADCpsuConv);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCiConv== ");
Message_16_Bit_Number(ADCiConv);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCoffset== ");
Message_16_Bit_Number(ADCoffset);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCvoltageRAW== ");
Message_16_Bit_Number(ADCreadings[V_BAT]);
Set_String_Tx_Buffer("\t\tADCvoltage== ");
Message_16_Bit_Number_Formatted(ADC_Get_Voltage(), BareNumber);
Set_String_Tx_Buffer("mV");
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCcurrentRAW== ");
Message_16_Bit_Number(ADCreadings[I_BAT]);
Set_String_Tx_Buffer("\t\tADCcurrentRAW== ");
Message_16_Bit_Number_Formatted(ADC_Get_Current(), BareNumber);
Set_String_Tx_Buffer("mA");
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCvariantRAW== ");
Message_16_Bit_Number(ADCreadings[VARIANT_ID]);
Set_String_Tx_Buffer("\t\tADCvariant== ");
Message_16_Bit_Number_Formatted(ADC_Get_Variant(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCboardIDRAW== ");
Message_16_Bit_Number(ADCreadings[BOARD_ID]);
Set_String_Tx_Buffer("\t\tADCboardID== ");
Message_16_Bit_Number_Formatted(ADC_Get_BoardID(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("Temperature== ");
Message_16_Bit_Number_Formatted(ADC_Get_Temperature(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("En3v3A== ");
Message_8_Bit_Number(HAL_GPIO_ReadPin(En3v3A_GPIO_Port, En3v3A_Pin));
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("En3v3B== ");
Message_8_Bit_Number(HAL_GPIO_ReadPin(En3v3B_GPIO_Port, En3v3B_Pin));
Set_String_Tx_Buffer(NEWLINE);
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
//ADC_Print_Raw();
}
//----------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------< end of file >----------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
```
[1]: https://i.stack.imgur.com/P1fOj.png
[2]: https://i.stack.imgur.com/CxRQa.png
[3]: https://i.stack.imgur.com/z33wz.png
[4]: https://i.stack.imgur.com/MyD57.png
[5]: https://i.stack.imgur.com/RaEIj.png |
For RFC 9110, the current HTTP Semantics spec as of 2024-03-31, responses with the following statuses MUST NOT contain content:
## [Informational 1xx](https://datatracker.ietf.org/doc/html/rfc9110#name-informational-1xx)
> A 1xx response is terminated by the end of the header section; it cannot contain content or trailers.
## [204 No Content](https://datatracker.ietf.org/doc/html/rfc9110#name-204-no-content)
> A 204 response is terminated by the end of the header section; it cannot contain content or trailers.
## [205 Reset Content](https://datatracker.ietf.org/doc/html/rfc9110#name-205-reset-content)
> Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate content in a 205 response.
## [304 Not Modified](https://datatracker.ietf.org/doc/html/rfc9110#name-304-not-modified)
> A 304 response is terminated by the end of the header section; it cannot contain content or trailers. |
Laravel spatie permission many to many query |
|laravel|eloquent|permissions| |
My problem is that, after successful login, the session is being created successfully, but redirect is not working. Why? \<br\>
\[route\](<https://i.stack.imgur.com/4Skqa.png>)\<br\>
\[form html\](<https://i.stack.imgur.com/U6prc.png>)
\[authenticationcontrol\](<https://i.stack.imgur.com/gTLvk.png>)
\[login_function\](<https://i.stack.imgur.com/uiDK6.png>)
\[core.js\](<https://i.stack.imgur.com/u8Sec.png>)
I need your help, thank you.\<br\>I've tried make some changes in login function and core.js for arrangement, but it didn't work |
Is there anybody who can help me in node.js authentication? |
|javascript|node.js|node-modules| |
null |
For me, using a .json file rather than a .js file for .eslintrc allowed `eslint .` to operate as it should in a module-based project.
Failed attempts (.eslintrc.js):
```js
export default {
// also tried: export {
// also tried: module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"overrides": [
{
"env": {
"node": true
},
"files": [
".eslintrc.{js,cjs}"
],
"parserOptions": {
"sourceType": "script"
}
}
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
}
}
```
All of the above trigger:
```none
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/.eslintrc.js from /home/me/.nvm/versions/node/v20.11.1/lib/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs not supported.
.eslintrc.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead either rename .eslintrc.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /path/to/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
```
Correct version (rename to .eslintrc.json, remove the `export` syntax and ensure valid JSON):
```json
{
"env": {
// ... same content above onward ...
}
```
package.json:
```json
{
"type": "module",
"devDependencies": {
"eslint": "^8.57.0"
}
}
```
As the above error message indicates, rather than switching to JSON, another option is to keep the `module.exports = { ... }` syntax but rename .eslintrc.js to .eslintrc.cjs.
Removing `"type": "module"` from the package.json and using CJS is also possible, but my project is mostly modules, so I'd have to rename a ton of .js files to .mjs if I used this approach.
[The accepted answer](https://stackoverflow.com/a/70458446/6243352) didn't seem to make a difference in my case. |
{"Voters":[{"Id":243925,"DisplayName":"Tony"},{"Id":157957,"DisplayName":"IMSoP"},{"Id":269970,"DisplayName":"esqew"}]} |
Could someone explain what was the common usage of the `PhantomReference` class before Java 9? This class was introduced at December 1998 in Java 1.2 by Mark Reinhold and it's not clear what was the intention of the author. At September 2017 in Java 9 the `finalize()` method was deprecated and marked for removal but it isn't removed even in Java 22. As an alternative to that deprecated method the `Cleaner` class was added, that uses the `PhantomReference` class internally to free resources without using a reference to the garbage collected object that holds them. Using the `PhantomReference` class directly (i.e. before the `Cleaner` class was introduced) seems to be over complicated. And considering that even the `finalize()` method is rarely used even in code for Java older than Java 9 the `PhantomReference` class seems to be practically never used before Java 9. I can't imagine anyone writing something like the following homemade analogue of the `Cleaner` class instead of implementing just the `finalize()` method before Java 9.
```java
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.*;
class ModernFinalizingObject {
private static final ReferenceQueue<ModernFinalizingObject> referenceQueue = new ReferenceQueue<>();
private static final Set<FinalizingPhantomReference> phantomSet = new HashSet<>();
protected final Collection<AutoCloseable> resources = new LinkedList<>();
{
phantomSet.add(new FinalizingPhantomReference(this, referenceQueue, resources));
}
static {
var th = new Thread(() -> {
while (true) {
try {
var phantomRef = (FinalizingPhantomReference) referenceQueue.remove();
phantomRef.modernFinalize();
phantomSet.remove(phantomRef);
} catch (InterruptedException e) {
throw new RuntimeException("someone is cheating", e);
}
}
});
th.setDaemon(true); // don't block shutting down
th.start();
}
protected <T extends AutoCloseable> T meetResource(T resource) {
resources.add(resource);
return resource;
}
}
class FinalizingPhantomReference extends PhantomReference<ModernFinalizingObject> {
private final Collection<AutoCloseable> resources;
public FinalizingPhantomReference(ModernFinalizingObject referent,
ReferenceQueue<? super ModernFinalizingObject> referenceQueue,
Collection<AutoCloseable> resources) {
super(referent, referenceQueue);
this.resources = resources;
}
public void modernFinalize() {
resources.forEach(r -> {
try {
r.close();
} catch (Exception e) {
// ignore
}
});
}
}
class Resource implements AutoCloseable {
public void doSomething() {
System.out.println("Resource " + hashCode() + " is doing something");
}
@Override
public void close() {
System.out.println("Resource " + hashCode() + " is closed.");
}
}
class ModernFinalizingService extends ModernFinalizingObject {
private Resource resource1 = meetResource(new Resource());
private Resource resource2 = meetResource(new Resource());
public void doSomething() {
System.out.println("Service is doing something...");
resource1.doSomething();
resource2.doSomething();
}
}
class Main {
public static void main(String[] args) throws Exception {
ModernFinalizingService service = new ModernFinalizingService();
service.doSomething();
// make it ready to be collected as a garbage
service = null;
// advice the JVM to run Garbage Collector
System.gc();
// emulate the real work is continuing, giving some time to all the above finalization finishing
Thread.sleep(500);
System.out.println("Bye!");
}
}
``` |
What was the common usage of the PhantomReference class before Java 9? |
`selectedBook = aStoreItems[i];` is never executed. It is dead code. When `return` is executed, the function exits and no other statements in that function are executed.
You should just not have that `selectedBook` variable. Instead *use* what the function returns at the calling side. So in the second part of your code do:
```
const selectedBook = getBookById(bookSelection);
console.log("return is(in add to cart function) " + selectedBook);
```
As a side note, this also defines `selectedBook` as a *local* variable, which is preferable over global variables. |
I have modified the [Ananke](https://themes.gohugo.io/themes/gohugo-theme-ananke/) theme for [Hugo](https://gohugo.io) for my own purposes, the modifications are [here](https://github.com/ltrubov/gohugo-theme-ananke-customizatiion).
The key change was that I wanted a list of linkable tags (that the theme already put at the bottom of every post) to also appear at the top of the `/tags/` page (and also do the same for categories and other taxonomies). In addition, I wanted a count of applicable posts to also show in each tag bubble.
So, I put this code into the template `/layouts/_default/terms.html`:
{{ $taxonomyObject := cond (eq .Data.Plural "tags") .Site.Taxonomies.tags .Site.Taxonomies.categories }}
<div class="measure-wide-l center f4 lh-copy nested-copy-line-height nested-links {{ $.Param "text_color" | default "mid-gray" }}">
{{ .Content }}
<ul class="pa0">
{{ range .Data.Pages }}
<li class="list di">
<a href="{{ .Page.RelPermalink }}" class="link f5 grow no-underline br-pill ba ph3 pv2 mb2 dib black sans-serif">
{{- .Page.Title -}} <span class="f4"><strong> {{ $taxonomyObject.Count .Page.Title }}</strong></span>
</a>
</li>
{{ end }}
</ul>
</div>
(I can add checks for taxonomies other than tags and categories later)
I've also modified the `exampleSite` category to add some tags and categories. However, unlike what most examples and tutorials show, I didn't make all of them single-word lowercase values (if I had, I wouldn't have noticed the issue).
Here's what the result looks like on **macOS** (Sonoma 14.4.1, Intel, go v1.22.1, Hugo v0.124.1):
[![Tags-Mac][1]][1]
[![Categoris-Mac][2]][2]
And here's the what Hugo generates from the same source on **Linux** (Alpine 3.18, x86_64, go v1.20.11, Hugo v0.111.3)
[![Tags-Linux][3]][3]
[![Categories-Linux][4]][4]
The differences are, as you see:
* On Linux, the taxonomy titles are displayed exactly as they are in the source -- capitalized only if the source is capitalized. MacOS applies "Book Title" capitalization rules (words other than `a`, `the`, `and`, etc are capitalized).
* If the taxonomy is capitalized or has a space in the title, the count on Linux is 0.
I see the latter as a more egregious problem than the former, but it'd be nice if all behavior was consistent across OS's.
A part of the solution I've found involves modifying the template entry as follows:
<li class="list di">
{{ $normalizedTerm := replace (lower .Page.Title) " " "-" }}
<a href="{{ .Page.RelPermalink }}" class="link f5 grow no-underline br-pill ba ph3 pv2 mb2 dib black sans-serif">
{{- .Page.Title -}} <span class="f4"><strong> {{ $taxonomyObject.Count $normalizedTerm }}</strong></span>
</a>
</li>
However, if I just change to that, the count will be incorrect **on macOS**.
So why does this happen, and how do I get consistent site generation regardless of what OS I'm doing it from? I don't see a way to determine the OS type inside the template in the Hugo docs (somewhat relevant functionality is [here](https://gohugo.io/functions/os/) and [here](https://gohugo.io/functions/hugo/). And even if that was possible, it's hardly an ideal solution:
* this could be due to different Hugo versions
* this could be specific to the distro/version of Linux I'm using
While one obvious difference is that the Linux file system is case-sensitive, it's not that straightforward, since all files Hugo generates are lowercased without spaces, on both systems. Hugo really generates different HTML from the same code, depending on OS.
So, the two questions are:
1. Why?
2. What do I change to get the same HTML?
[1]: https://i.stack.imgur.com/Kryng.jpg
[2]: https://i.stack.imgur.com/e1r9P.jpg
[3]: https://i.stack.imgur.com/idv0X.jpg
[4]: https://i.stack.imgur.com/LD5vK.jpg |
|java| |
Using Pycharm Community Edition 2023.3.2 with Micropython 1.4.3-2023.3 installed and enabled in Pycharm. I want to utilize the 2 core multithreading on a Raspberry Pi Pico W using the experimental "_thread" library. When I try to use a method from the module, Pycharm says there is no reference to the method, [even though it can find _thread.pyi](https://i.stack.imgur.com/rsAUQ.png)
When I dot search for any available methods, [only 4 dunder methods show up](https://i.stack.imgur.com/Yfwch.png)
I think it's just Pycharm's referencing that is the problem, and the Pico W would still execute the code, but it would be nice to have some kind of reference to double check what I'm doing is in line with the syntax.
I have tried repairing the IDE up to invalidating the caches and restarting. I have also redownloaded and reinstalled the same Micropython version on 2 different devices with the same version of Pycharm. I don't know any further steps of troubleshooting this. |
Got the same error, when trying to upload from local machine. Reason - luck of permissions. Same code on server works fine |
I'm currently working on a react native application, and for one of my features I'll need to create an image from a selection of images chosen by the user. How do I go about generating such an image and storing it in firebase?
Is it possible to do this directly in my application, or would I need to set up an external service for performance reasons? I imagine there are already existing tools for doing this sort of thing, is there one you'd recommend?
Each of the child images to be integrated belongs to a category and would have a well-defined placement in the parent image. For example, if my first child image belongs to category A, then it must be placed at the top left of the parent image and occupy 1/2 of the total height. If the second child image belongs to category B, then it must be placed to the right of the parent image and occupy the full height, etc. etc.
To respect this, I imagine I'd have to enter an x and y position in my parent image for each of my sub-images. |
Create and combine several images into a single image for my react native App |
|reactjs|react-native|image| |
null |
I'm trying to visualize the data coming through the API with Sigma.JS, but I can't always get results. When I tried to visualize the dynamic incoming data without mock data by writing a simple API with Flask, it worked, but this data is slightly different from the real json data of the project, I can't integrate the new incoming data, although I took custom rendering as an example, I couldn't solve it. I will be leaving the json data I will be using below. In the nodes section, the json data is divided into two groups according to the y index in the form of attacker and destination, think of them as SIEM logs. ip is available in the id section, attackType in the label section
```
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sigma.js Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/2.4.0/sigma.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphology/0.25.4/graphology.umd.min.js"></script>
<style>
#container {
width: 100%;
height: 100vh;
background: white;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
const graph = new graphology.Graph();
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
async function fetchAttackTypes() {
try {
const response = await fetch('http://127.0.0.1:5000/data');
const data = await response.json();
return data.attackTypes;
} catch (error) {
console.error('Error:', error);
return [];
}
}
async function renderGraph() {
const attackTypes = await fetchAttackTypes();
shuffleArray(attackTypes);
attackTypes.forEach((type, index) => {
const angle = index * (2 * Math.PI / attackTypes.length);
const x = 200 * Math.cos(angle);
const y = 200 * Math.sin(angle);
graph.addNode(type, { label: type, x, y, size: 10, color: '#00f' });
});
attackTypes.forEach(type => {
const otherNodes = attackTypes.filter(otherType => otherType !== type);
const hasConnections = graph.neighbors(type).length > 0;
if (!hasConnections) {
const randomIndex = Math.floor(Math.random() * otherNodes.length);
const randomType = otherNodes[randomIndex];
graph.addEdge(type, randomType, { color: '#f00' });
}
});
const sigmaInstance = new Sigma(graph, document.getElementById("container"));
sigmaInstance.on('overNode', function(e) {
e.data.node.color = '#f00';
e.data.node.size *= 2;
sigmaInstance.refresh();
});
sigmaInstance.on('outNode', function(e) {
e.data.node.color = '#00f';
e.data.node.size /= 2;
sigmaInstance.refresh();
});
}
renderGraph();
</script>
</body>
</html>
```
nodes.json
```
"nodes": [
{
"color": "blue",
"id": "59.166.0.9",
"label": Exploit,
"size": 10,
"x": 0,
"y": 0
},
{
"color": "blue",
"id": "149.171.126.1",
"label": Fuzzing,
"size": 10,
"x": 0,
"y": 0
},
{
"color": "blue",
"id": "59.166.0.2",
"label": NaN,
"size": 10,
"x": 0,
"y": 1
},
{
"color": "blue",
"id": "149.171.126.7",
"label": NaN,
"size": 10,
"x": 0,
"y": 1
},
{
"color": "blue",
"id": "59.166.0.9",
"label": NaN,
"size": 10,
"x": 0,
"y": 2
},
{
"color": "blue",
"id": "149.171.126.4",
"label": NaN,
"size": 10,
"x": 0,
"y": 2
},
{
"color": "blue",
"id": "59.166.0.0",
"label": NaN,
"size": 10,
"x": 0,
"y": 3
},
{
"color": "blue",
"id": "149.171.126.3",
"label": NaN,
"size": 10,
"x": 0,
"y": 3
}
]
```
edges.json
```
"edges": [
{
"color": "purple",
"id": "e1_1000",
"size": 5,
"source": "175.45.176.1",
"target": "149.171.126.10"
},
{
"color": "purple",
"id": "e1_1001",
"size": 5,
"source": "175.45.176.1",
"target": "149.171.126.10"
},
{
"color": "purple",
"id": "e1_1002",
"size": 5,
"source": "175.45.176.0",
"target": "149.171.126.14"
},
{
"color": "purple",
"id": "e1_1003",
"size": 5,
"source": "149.171.126.18",
"target": "175.45.176.3"
},
{
"color": "purple",
"id": "e1_1004",
"size": 5,
"source": "149.171.126.18",
"target": "175.45.176.3"
},
]
```
[Image of the code I wrote while it is running](https://i.stack.imgur.com/LiH6X.jpg)
[I need to show the incoming data](https://i.stack.imgur.com/pa3sv.png)
Processing the data sent as Json in the backend
```
graph_data = {"nodes": [], "edges": []}
def update_graph_data():
global graph_data
data_iterator = load_data()
for i, data in enumerate(data_iterator):
for index, row in data.iterrows():
if row['attack_cat'] != "nan":
graph_data["nodes"].append({"id": row['srcip'], "label": row['attack_cat'], "x": i, "y": index, "size": 10, "color": "blue"})
graph_data["nodes"].append({"id": row['dstip'], "label": row['attack_cat'], "x": i, "y": index, "size": 10, "color": "blue"})
if i > 0:
graph_data["edges"].append({"id": f"e{i}_{index}", "source": row['srcip'], "target": row['dstip'], "size": 5, "color": "purple"})
time.sleep(1)
``` |
I have a large structure:
```rs
#[derive(Debug)]
pub struct OuterStruct {
pub big_array_0: [u32; 108],
pub big_array_1: std::sync::Mutex<[Option<SomeStruct>; 65536]>,
pub big_array_2: [AtomicUsize; 65536],
}
```
The size of arrays is known at compile time and I will not use a `Vec<_>`.
This current initialization code trigger a stack overflow:
```rs
let manager = Arc::new(OuterStruct{
big_array_0: the_big_array0, // Doesn't explode my stack
big_array_1: std::sync::Mutex::new(std::array::from_fn(|_| None)),
big_array_2: std::array::from_fn(|_| 0.into()),
});
```
So how do I allocate this structure in it's own heap allocation without triggering a stack overflow ?
I prefer not using unsafe code for this and I have `#![deny(invalid_value)]` so some `std::mem::MaybeUninit` based solutions will error (these would cause warnings anyway). |
Why does Hugo generate different taxonomy-related HTML on different OS's? |
|linux|macos|hugo|static-site-generation|hugo-theme| |
I use a 3rd party library which has 4 localized strings I need to overwrite. It's not my library so I have no access to the source code. I do know the reference keys for the 4 strings.
Is there a way, on startup in my code, to overwrite those localized string values? |
How can I overwrite the localization strings in a library |
|c#|.net-core|blazor-server-side| |
I'm working with a game called "Pixels". My goal is to programmatically monitor when trees respawn within the game. A developer provided me with Java code for this, and I've attempted to convert it to Python. I'm able to successfully retrieve my session ID, room ID, and other relevant server details.When I attempt to establish a WebSocket connection, I consistently receive a 502 error. I'm not sure what's causing this.
```
public void openWebSocketAndProcessMessages(String server, String roomId, String sessionId) {
ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient();
client.setMaxFramePayloadLength(2621440);
URI uri = URI.create(
String.format("wss://pixels-server.pixels.xyz/%s/%s?sessionId=%s", server, roomId,
sessionId));
AtomicBoolean firstMessageReceived = new AtomicBoolean(false);
// Capture the start time of the session
Instant sessionStart = Instant.now();
client.execute(uri, session ->
session.receive()
.doOnNext(message -> {
// Check if the first message has been received and send a confirmation message
if (firstMessageReceived.compareAndSet(false, true)) {
System.out.println("First message received, sending confirmation...");
byte[] confirmationBytes = {'\n'}; // Newline character as the confirmation message
session.send(
Mono.just(session.binaryMessage(factory -> factory.wrap(confirmationBytes))))
.subscribe();
}
// Convert the received WebSocketMessage to a byte array (requires proper handling based on actual message type and content)
ByteBuffer buffer = message.getPayload().asByteBuffer();
byte[] messageBytes = new byte[buffer.remaining()];
buffer.get(messageBytes);
String encodedString = new String(Base64.getDecoder().decode(Base64.getEncoder().encodeToString(messageBytes)));
}
```
Websocket connection python code that I am getting 502 error:
```
async def connect_websocket(server, roomid, sessionid):
uri = f"wss://pixels-server.pixels.xyz/{server}/{roomid}?sessionId={sessionid}"
print(uri)
headers = {
"Host": "pixels-server.pixels.xyz",
"Connection": "Upgrade",
"Upgrade": "websocket",
"Origin": "https://play.pixels.xyz",
"Sec-WebSocket-Version": "13",
"Sec-WebSocket-Key": "lAVNhobAP9AaShcdp/BegA==",
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
"User-Agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
"Cookie": "intercom-id-grzhbhyr=e4b3442d-7fbd-4660-b003-9796901fb523; intercom-device-id-grzhbhyr=48118693-0661-4e43-b3b9-e140ae8a692d; _ga=GA1.1.523002009.1710326782; _ga_QGP383C71B=GS1.1.1711873973.8.1.1711874126.0.0.0"
}
async with websockets.connect(uri, extra_headers=headers) as websocket:
while True:
message = await websocket.recv()
print(f"Received message: {message}
")
```
I'm unsure if there are any specific authentication requirements for the WebSocket connection that I might be missing. |
You could have the `-exec` run each line via `bash -c` instead of echoing it to a file to be run later. That would also enable (require, in fact) adjusting your quoting, ultimately allowing a simpler and clearer command. For example:
```
find ./build/html -name '*.html' \
-exec bash -c '../emojize_pngorsvg.py "{}" > "{}.emojized" && mv "{}.emojized" "{}"' \;
```
I took the liberty of some additional simplification, too. Specifically, it is unnecessary to remove the original file before `mv`ing the new one to the original name. Also, the `\(` and `\)` in the original command served no useful purpose, so I dropped them.
Also, I generally pipe `fund`'s output into `xargs` instead of using an `-exec` action. You could consider that, but it probably does not provide enough advantage in this case to justify the conversion. |
This is a great general question that deserves a general answer. Althgouh Stackoverflow is a great place to get answers, I don't believe an answer here no matter how good would be a substitute for more a more substantial reading, courses and hands-on experience. Nonetheless, I will try to be thorough.
Test automation is great topic in software development, and it is an essential part of SecDevOps, and plays a very important role in modern software development. I personally learned about test automation late in my 30 years+ of software development, and a part of me wishes I have taken up writing tests or test-driven software development earlier, and therefore, I encourage you to proceed on this path and take your test automation skills to the next level.
I will assume that the questions of **What is Test Automation?**, and **Why is test automation important?** are clear to you, and I will proceed to the next questions **What to test?** and **When to test?**:
# What to test?
In your question you write and I quote:
> Blockquote
My point is I have no idea how to test if it actually returns SomeScheduleClass as expected. Do I mock the http.client.HTTPResponse object I get from the urlopen? Do I somehow find a way to mock the response.read()? Or do I not have to test this at all and I'm just wasting my time? If so, what should I test here?
This is an essential question. Writing tests for your already existing code is "work" and "takes" time and energy, so the why question is not just a philosophical question but it is also an engineering question. There are several approaches and strategies that Quality Assurance managers, or CI/CD pipelines managers or CIOs would implement or prefer. I will try to list some **strategies** that I hope are useful to address the general **What to test?** question, then I will address the question about the snippet of code you shared.
## Use test driven-development
Test driven development means writing the tests before (or while) you are writing code. This method allows to ensure high test coverage, and also force you to design the code in a way that makes it easy to test.
## Focus on regression tests
If you are not implementing test-driver development, and you don't have high coverage of your code, then you would want to start with writing a test for everytime you discover a bug in the code. The goal of writing these regression tests is to ensure bugs do not resurface after they get fixed. Also writing regression tests slowly increases code coverage until you reach a point where you can switch to test-driven development. If you are already implementing test-driven development, then adding regression tests will cover cases you did not address in previous tests, and will ensure bugs do not resurface upon code refactoring. In other words, Bug fixing means writing test code that reproduce the bug case, then fixing the bug so that the bug is averted and the test passes.
## Focus on the most critical part of your code:
Writing tests is time consuming. If you are going to invest this time in writing tests, then invest time in covering the most essential part of the code, or the most difficult part that is potentially buggy. That will allow you to discover/avert runtime bugs, and might also help you redesign the code so that it is more modular and simpler.
## Write tests for your code
Don't waste your time writing tests for functions of 3rd party packages. Most packages already have tests. Write tests for your code, test all branches of a function, test all functions in a class or module, test all modules. Use a test coverage analysis tool to easily zoom in on code that is not coverage by tests.
## Set a coverage target:
And add a rule such as ensure when code is committed, coverage does not decrease.
## Security driven tests writing:
With this strategy, the goal is to ensure that all edge cases, stress situation, or any security issue is covered. Here you write tests that are designed to break the system, then adjust the code such as the system does not break, or such as the system fails in an expected and controlled way. Every time a security issue is discovered, addressing the issue means writing a test(s) that reproduce it and fixing the code so that the test(s) passes, which is similar to writing regression tests.
## Focus on use cases:
Write tests that covers use cases of your code, or that are driven by the end-users of the code/tool. That way you cover the part related to the user-experience. That can accelerate the speed at which features and fixes are delivered to the end-user, by reducing the development/manual-testing iterations of new features or code fixes.
## What to test in the code snippet:
from urllib.request import urlopen
def fetch_html():
url = "https://example.com"
response = urlopen(url)
dom = response.read()
return SomeScheduleClass(dom)
I will start by writing Unit test for fetch_html, the test should ensure that the function returns an instance of type SomeScheduleClass, and that content of that instance is what is expected from parsing some `dom` with the `SomeScheduleClass`. We are not interested in testing `urllib.request.urlopen` because it is not your code. We are not interested in testing SomeScheduleClass constructor in `test_fetch_html()` because it should be tested in the Unit tests of the class `SomeScheduleClass`.
Now we are interested in controlling the expected outcome of fetch_html, that means we have to control the input of the function. This function uses `urllib.request.urlopen` to get a response from the http server of `example.com` that is the input of the function. To control it and to make sure we can run the test without having to make any http requests to the open internet, we have to mock urllib.request.urlopen(). There are many methods to mock this function, one of them is to define a fixed return value using the `mocker` fixture from `pytest-mock`.
import pytest
from src.schedules import SomeScheduleClass
from src.utils import fetch_html
@pytest.mark.UNIT
def test_fetch_html(mocker):
# mocked html content. It can be re-used when testing SomeScheduleClass
mock_html_content = b"<html>Mock example.com HTML content</html>"
# class to mock the http response class return by urlopen
class MockResponse:
def read(self):
return mock_html_content
mock_response = MockResponse()
# mock urllib.request.urlopen to return mock_response
p = mocker.patch('urllib.request.urlopen', return_value=mock_response)
# call the function to be tested
r = fetch_html()
# assert urlopen was called once with url: https://example.com
p.assert_called_once_with("https://example.com")
# assert the return value is an object of type SomeScheduleClass
assert isinstance(r, SomeScheduleClass)
# some assertions to make sure r contains the exected value
# it should be be extensive since we are not testing SomeScheduleClass
It is clearly evident that this function does not have any error handling and any exception raised will be handled in by the invoking function. So when testing the invoking function, edge cases should be addressed, such as the case that example.com was not reachable, or if example.com returned 4xx or 5xx or something like that.
# When to test?
i.e. when to run the tests, during development, after committing to the branch? on merge requests? on staging? on deployment?
In "The DevOps Handbook" (which I highly recommend), while discussing the "2nd second way, the principles of feedback" the advise is to "Keep pushing quality closer to source" and "to enable optimization for teams downstream". In practicle terms, developers should be able to test their code before committing it (pushing quality closer to source), and any bug in the code should be discovered as soon as possible before it reaches production, the closer the bug is discovered to its source, the better. I would recommend, enabling developers to run all tests before committing code. but that means developers should be able to create production-like environments on their own... there is so much here to discuss.
#
Take a look at [https://requests-mock.readthedocs.io/en/latest/][1]. It is a requests-mock for `pytest` which an (better) alternative to UnitTest. You can learn more about pytest here: [https://docs.pytest.org/en/stable][2].
[1]: https://requests-mock.readthedocs.io/en/latest/
[2]: https://docs.pytest.org/en/stable/
|
If you took a look at `Loaded Configuration File` section in phpinfo() output you would probably see an empty value there which means no php.ini was loaded.
So, my guess you need to create the config file firstly and then you will be able to modify its values.
Here is how your Dockerfile should look like:
```
...
RUN cp /usr/local/etc/php/php.ini-development /usr/local/etc/php/php.ini
RUN sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 604800/g" /usr/local/etc/php/php.ini
RUN sed -i "s/session.cookie_lifetime = 0/session.cookie_lifetime = 604800/g" /usr/local/etc/php/php.ini
...
``` |
Given h, k, and r, the (x, y) values in the circle will satisfy
`h - r <= x <= h + r` and `k - r <= y <= k + r`.
Hence, the simplest way to do this is to use double for-loop with x, and y values in the range.
In the for-loop, you can use `if` to check whether (x - h)^2 + (y - k)^2 <= r^2.
Example code
```gdscript
func get_chunks(h, k, r):
var chunks = []
var min_x = h - r
var max_x = h + r
var min_y = k - r
var max_y = k + r
for x in range(min_x, max_x + 1):
for y in range(min_y, max_y + 1):
if (x - h) * (x - h) + (y - k) * (y - k) <= r * r:
chunks.append(Vector2(x, y))
return chunks
```
Alternatively, you can use a for-loop with x value first, and calculate k ± sqrt(r^2 - (x-h)^2) with floor/ceil functions to find the y's range for the specific x. |
I have this request, on my node.js application :
```js
return new Promise((resolve, reject) => {
const options = {
hostname: 'py', <== docker container
port: 8000,
path: '/resume',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
file
})
}
const req = http.request(options, (res) => {
const body = [];
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log('BODY: ' + chunk);
body.push(chunk);
});
resolve(body);
});
req.on('error', (error) =>{
console.log('problem with request: ' + error.message);
reject(error)
});
req.end();
})
```
And this, on my python app, that I copied from this topic => https://stackoverflow.com/a/65141532/14317753
```python
@app.post("/resume")
async def resume(request: Request):
da = await request.form()
da = jsonable_encoder(da)
print('file', da)
return da
```
But unfortunately, I'm getting a empty file, on Python.
Obviously, I've tried everything : changing the GET request to POST and putting the base64 file body param in the get params, using the `request.json()` and the `request.body()` instead of `request.form()` for the fixes I remember.
Thanks for you help. |
{"Voters":[{"Id":6296561,"DisplayName":"Zoe is on strike"}],"SiteSpecificCloseReasonIds":[18]} |
Is there any way to tell Notepad please do this...
FROM THIS
15.63387,46.42795,1,130,1,210,Sele pri Polskavi
TO THIS
15.63387,46.42795,1,130,1,210
I would like to remove everything after the last , (after number 210)
So that in the end it looks like
15.63387,46.42795,1,130,1,210
Thing is when I try it using Notepad++ with the command
FIND = [[:alpha:]] or [\u\l]
REPLACE = (leave it empty)
It removed all alphabetical charachters but it leaves , signs at the end, which I can remove with .{1}$ but for some reason some lines have empty spaces after , sign.
Some lines have one or more and this command .{1}$ does not work since notepad++ sees empty space as a character and therefore does not remove all the , signs at the end of each line. |
.bashrc not found, but I was able to configure it to start zsh by making the change in the file bash_profile.sh.
C:\Program Files\Git\etc\profile.d/bash_profile.sh
# add ~/.bash_profile if needed for executing ~/.bashrc
if [ -e ~/.bashrc -a ! -e ~/.bash_profile -a ! -e ~/.bash_login -a ! -e
~/.profile ]; then
printf "\n\033[31mWARNING: Found ~/.bashrc but no ~/.bash_profile,
~/.bash_login or ~/.profile.\033[m\n\n"
echo "This looks like an incorrect setup."
echo "A ~/.bash_profile that loads ~/.bashrc will be created for you."
cat >~/.bash_profile <<-\EOF
# generated by Git for Windows
test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc
EOF
fi
# Launch Zsh
if [ -t 1 ]; then
exec zsh
fi
- |
afterly i have a problem to us reslove
then this is error
in todolist(RootComponent), js engine: hermes
ERROR Error: Text strings must be rendered within a <Text> component.
This error is located at:
in text (created by HomeScreen)
in RCTView (created by View)
in View (created by ScrollView)
in RCTScrollView (created by ScrollView)
in ScrollView (created by ScrollView)
in ScrollView (created by Container)
in Container (created by HomeScreen)
in HomeScreen (created by App)
in App
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in todolist(RootComponent), js engine: hermes
[enter image description here](https://i.stack.imgur.com/3DFgQ.png)
i to try to change children but i has been the problem
help me , please , i'm learn creating app with react-native
|
I have a problem with my react-native project |
|react-native|react-navigation| |
null |
First of all, VBA has no sort method. The only way to sort something is to use worksheet functions.
Second, Excell correctly sorts ranges with formulas. You need to estimate the references in those formulas. They can contain references to the same row or absolute references. And all referenced columns should be included in the sorted range.
Pay attention on the SORT function if you don't like to sort the range on place.
If you don't want to sort the range directly on the worksheet, you can use Evaluate method mentioned by Tim, or you can use the next code:
```
Sub adasd()
Dim a As Variant
a = WorksheetFunction.Sort(Range("A1:B4"))
End Sub
```
It works with the snapshot of the range (values).
|
null |
I am experiencing the following problem. When I setup an ADC with DMA for 5 channels, I get lower readings than the expected ones.
We have PCBs of the same batch in 3 countries, but only the ones tested in China are failing. At all times the ADC readings read lower than the expected values for all the ADC channels, but the PCBs at the other countries return the expected reading in all channels. All those PCBs are identical and they are driving small motors, have a keypad, have some LEDs UI, and a UART debugging port were we connect a USB to TTL UART cable.
Here is the ADC configuration with DMA (source code attached too):
[enter image description here][1]
We have measured the reference voltage and all the expected voltages on ADC input pins (some are fixed and known) and all looking good too. On the other hand, when I sample only one ADC channel in polling mode, I do not get this problem, the voltages read as expected.
For example: the readings of a healthy ADC reading at 10-bit resolution should read something like 914 raw value which will correspond to 3652mV for the battery voltage, as opposed to the lower reading which will be something like 837 raw value which corresponds to 3346mV for the battery voltage.
```c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file adc.c
* @brief This file provides code for the configuration
* of the ADC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "adc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
/* ADC1 init function */
void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV10;
hadc1.Init.Resolution = ADC_RESOLUTION_10B;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hadc1.Init.LowPowerAutoWait = ENABLE;
hadc1.Init.LowPowerAutoPowerOff = ENABLE;
hadc1.Init.ContinuousConvMode = ENABLE;
hadc1.Init.NbrOfConversion = 5;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.DMAContinuousRequests = ENABLE;
hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED;
hadc1.Init.SamplingTimeCommon1 = ADC_SAMPLETIME_160CYCLES_5;
hadc1.Init.SamplingTimeCommon2 = ADC_SAMPLETIME_160CYCLES_5;
hadc1.Init.OversamplingMode = DISABLE;
hadc1.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_LOW;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLINGTIME_COMMON_1;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_2;
sConfig.Rank = ADC_REGULAR_RANK_3;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_3;
sConfig.Rank = ADC_REGULAR_RANK_4;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
sConfig.Rank = ADC_REGULAR_RANK_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspInit 0 */
/* USER CODE END ADC1_MspInit 0 */
/** Initializes the peripherals clocks
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/* ADC1 clock enable */
__HAL_RCC_ADC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA1 ------> ADC1_IN1
PA2 ------> ADC1_IN2
PA3 ------> ADC1_IN3
*/
GPIO_InitStruct.Pin = V_BAT_IN_Pin|I_BAT_IN_Pin|VARIANT_ID_Pin|BOARD_ID_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* ADC1 DMA Init */
/* ADC1 Init */
hdma_adc1.Instance = DMA1_Channel1;
hdma_adc1.Init.Request = DMA_REQUEST_ADC1;
hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_adc1.Init.Mode = DMA_CIRCULAR;
hdma_adc1.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);
/* ADC1 interrupt Init */
HAL_NVIC_SetPriority(ADC1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(ADC1_IRQn);
/* USER CODE BEGIN ADC1_MspInit 1 */
/* USER CODE END ADC1_MspInit 1 */
}
}
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspDeInit 0 */
/* USER CODE END ADC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC_CLK_DISABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA1 ------> ADC1_IN1
PA2 ------> ADC1_IN2
PA3 ------> ADC1_IN3
*/
HAL_GPIO_DeInit(GPIOA, V_BAT_IN_Pin|I_BAT_IN_Pin|VARIANT_ID_Pin|BOARD_ID_Pin);
/* ADC1 DMA DeInit */
HAL_DMA_DeInit(adcHandle->DMA_Handle);
/* ADC1 interrupt Deinit */
HAL_NVIC_DisableIRQ(ADC1_IRQn);
/* USER CODE BEGIN ADC1_MspDeInit 1 */
/* USER CODE END ADC1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file dma.c
* @brief This file provides code for the configuration
* of all the requested memory to memory DMA transfers.
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dma.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure DMA */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Enable DMA controller clock
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file BxADC.c
* @brief Analogue interface with HAL and data conversions
*
******************************************************************************
* @attention
*
* Copyright Statement:
* Copyright (c) Bboxx Ltd 2023
* The copyright in this document, which contains information of a proprietary and confidential nature,
* is vested in Bboxx Limited. The content of this document may not be used for purposes other
* than that for which it has been supplied and may not be reproduced, either wholly or in part,
* nor may it be used by, or its contents divulged to, any other person who so ever without written permission
* of Bboxx Limited.
*
******************************************************************************
*/
/* USER CODE END Header */
//----------------------------------------------------------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------------------------------------------------------
#include <stdbool.h>
#include "adc.h"
#include "stm32g0xx_hal_adc.h"
#include "main.h"
#include "Bboxx.h"
#include "BxMotor.h"
#include "BxADC.h"
#include "BxMessage.h"
#include "BxSerial.h"
//----------------------------------------------------------------------------------------------------------------------
// Defines
//----------------------------------------------------------------------------------------------------------------------
typedef enum {
V_BAT,
I_BAT,
VARIANT_ID,
BOARD_ID,
TEMPERATURE,
NUM_OF_ADC_CH
} ADC_CHS;
//----------------------------------------------------------------------------------------------------------------------
// Variables
//----------------------------------------------------------------------------------------------------------------------
static uint16_t ADCreadings[NUM_OF_ADC_CH];
static uint16_t ADCoffset;
static uint16_t ADCref = ADCREF;
static uint16_t ADCpsuConv = ((ADCREF*(ADCPSUR1+ADCPSUR2))/(ADCMAX*ADCPSUR1)) * RESULTMAG;
static uint16_t ADCiConv = (ADCREF/(ADCIGAIN*ADCISENSER));
extern ADC_HandleTypeDef hadc1;
//----------------------------------------------------------------------------------------------------------------------
// Functions
//----------------------------------------------------------------------------------------------------------------------
void ADC_Initialise(void)
/**
* @brief Initialises all ADC
* @param None
* @retval None
*/
{
HAL_GPIO_WritePin(En3v3A_GPIO_Port, En3v3A_Pin, GPIO_PIN_RESET); // Turn On current amp power
HAL_GPIO_WritePin(En3v3B_GPIO_Port, En3v3B_Pin, GPIO_PIN_RESET); // Turn On IDs (+Motor) power
HAL_ADC_Start_DMA(&hadc1, (uint16_t*)ADCreadings, sizeof(ADCreadings)/sizeof(ADCreadings[V_BAT])); // start ADC conversion
return;
}
void ADC_Calibrate(void)
/**
* @brief Calibrates ADC
* @param None
* @retval None
*/
{
HAL_Delay(2000);
static bool firstTime = true;
// Run once
while (firstTime) {
// Calibrate to a known voltage such as the battery
uint16_t volt = ADC_Get_Voltage();
if (volt > (uint16_t)3750u) {
firstTime = false; // Stop if battery voltage is reached
ADCoffset = ADCreadings[I_BAT]; // Save the run mode current offset
Set_String_Tx_Buffer("calibration done ");
Message_16_Bit_Number(volt);
Set_String_Tx_Buffer(" mV and ");
Message_16_Bit_Number(ADCref);
Set_String_Tx_Buffer(" mV");
Set_String_Tx_Buffer(NEWLINE);
} else {
ADCref++; // Increase gain via adding error to the reference voltage
}
}
}
uint16_t ADC_Remove_Offset(uint16_t RawValue)
/**
* @brief Removes the offset from the ADC circuit
* @param None
* @retval None
*/
{
if(RawValue < ADCoffset)
RawValue =0;
else
RawValue -= ADCoffset;
return RawValue;
}
uint16_t ADC_Convert_Voltage(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into mM
* @param None
* @retval None
*/
{
uint32_t Result =0;
RawValue =ADC_Remove_Offset(RawValue);
ADCpsuConv = ((ADCref*(ADCPSUR1+ADCPSUR2))/(ADCMAX*ADCPSUR1)) * RESULTMAG;
Result =(ADCpsuConv * RawValue); // scale result
Result =(Result>>ADCVARDIVIDE);
return (uint16_t) Result;
}
uint16_t ADC_Convert_Current(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into mA
* @param None
* @retval None
*/
{
uint32_t Result =0;
RawValue =ADC_Remove_Offset(RawValue);
ADCiConv = (ADCref/(ADCIGAIN*ADCISENSER));
Result = (ADCiConv * RawValue);
Result =(Result>>ADCVARDIVIDE);
return (uint16_t) Result;
}
uint16_t ADC_Convert_ID(uint16_t RawValue)
/**
* @brief Converts the Raw ADC data into An ID voltage 10*units
* @param None
* @retval None
*/
{
uint16_t Result16 =0; // For Faster calculation
uint32_t Result32 =0; // For higher resolution
RawValue =ADC_Remove_Offset(RawValue); // Needs 32bit calculation
Result32 =(ADCref * RawValue); // scale result
Result16 =(uint16_t)(Result32>>ADCVARDIVIDE); // mV
Result16 += 50; // add 50mV for rounding up
Result16 = Result16/100; // Scale for 10*units
return (uint8_t) Result16;
}
uint16_t ADC_Get_Voltage(void)
/**
* @brief returns the value of the PSU voltage (mV)
* @param None
* @retval None
*/
{
return ADC_Convert_Voltage(ADCreadings[V_BAT]);
}
uint16_t ADC_Get_Current(void)
/**
* @brief returns the current current value (mA)
* @param None
* @retval None
*/
{
return ADC_Convert_Current(ADCreadings[I_BAT]);
}
uint8_t ADC_Get_Variant(void)
/**
* @brief returns the Variant as defined by R68//R70 in 10*units
* @param None
* @retval None
*/
{
return ADC_Convert_ID(ADCreadings[VARIANT_ID]);
}
uint8_t ADC_Get_BoardID(void)
/**
* @brief returns the ID as defined by R67//R71 in 10*units
* @param None
* @retval None
*/
{
return ADC_Convert_ID(ADCreadings[BOARD_ID]);
}
uint16_t ADC_Get_Temperature(void)
/**
* @brief returns the Temp in 100*C
* @param None
* @retval None
*/
{
return ADCreadings[TEMPERATURE];
}
void ADC_Print_Raw(void)
/**
* @brief Prints the Raw ADC data in serial terminal
* @param None
* @retval None
*/
{
Set_String_Tx_Buffer("ADCref== ");
Message_16_Bit_Number(ADCref);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCpsuConv== ");
Message_16_Bit_Number(ADCpsuConv);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCiConv== ");
Message_16_Bit_Number(ADCiConv);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCoffset== ");
Message_16_Bit_Number(ADCoffset);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCvoltageRAW== ");
Message_16_Bit_Number(ADCreadings[V_BAT]);
Set_String_Tx_Buffer("\t\tADCvoltage== ");
Message_16_Bit_Number_Formatted(ADC_Get_Voltage(), BareNumber);
Set_String_Tx_Buffer("mV");
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCcurrentRAW== ");
Message_16_Bit_Number(ADCreadings[I_BAT]);
Set_String_Tx_Buffer("\t\tADCcurrentRAW== ");
Message_16_Bit_Number_Formatted(ADC_Get_Current(), BareNumber);
Set_String_Tx_Buffer("mA");
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCvariantRAW== ");
Message_16_Bit_Number(ADCreadings[VARIANT_ID]);
Set_String_Tx_Buffer("\t\tADCvariant== ");
Message_16_Bit_Number_Formatted(ADC_Get_Variant(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("ADCboardIDRAW== ");
Message_16_Bit_Number(ADCreadings[BOARD_ID]);
Set_String_Tx_Buffer("\t\tADCboardID== ");
Message_16_Bit_Number_Formatted(ADC_Get_BoardID(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("Temperature== ");
Message_16_Bit_Number_Formatted(ADC_Get_Temperature(), BareNumber);
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("En3v3A== ");
Message_8_Bit_Number(HAL_GPIO_ReadPin(En3v3A_GPIO_Port, En3v3A_Pin));
Set_String_Tx_Buffer(NEWLINE);
Set_String_Tx_Buffer("En3v3B== ");
Message_8_Bit_Number(HAL_GPIO_ReadPin(En3v3B_GPIO_Port, En3v3B_Pin));
Set_String_Tx_Buffer(NEWLINE);
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
//ADC_Print_Raw();
}
//----------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------< end of file >----------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
```
[1]: https://i.stack.imgur.com/uHTbV.png |
I'm developing a JavaEE application on Glasfish Application Server. I'm developing so I'm continously deployig/undeploying the application.
Everything worked great until a few hours ago when I got this error while deploying:
GRAVE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
GRAVE: Exception while invoking class org.glassfish.javaee.full.deployment.EarDeployer prepare method
GRAVE: Exception while preparing the app
GRAVE: Could not resolve a persistence unit corresponding to the persistence-unit-ref-name [persistence/decreg-entite] in scope of the module called [declaration-reglementaire-ear#declaration-reglementaire-serviceweb-0.0.3-RELEASE.war]. Please verify your application.
org.glassfish.deployment.common.DeploymentException: Could not resolve a persistence unit corresponding to the persistence-unit-ref-name [persistence/decreg-entite] in scope of the module called [declaration-reglementaire-ear#declaration-reglementaire-serviceweb-0.0.3-RELEASE.war]. Please verify your application.
Does anyone have an idea on how to solve this? |
null |
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i(TAG, "onConnectionStateChange newstate:" + newState + " status:" + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "============>GATT Connect Success!!<=============");
//step 5
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
Log.i(TAG, "onServicesDiscovered(), status = " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services){
UUID serviceUUID = service.getUuid();
Log.i(TAG,"serviceUUID:" + serviceUUID);
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
UUID characteristicUUID = characteristic.getUuid();
Log.i(TAG,"characteristic UUID:" + characteristicUUID);
List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
for (BluetoothGattDescriptor descriptor : descriptors) {
UUID descriptorUUID = descriptor.getUuid();
Log.d(TAG, "Descriptor UUID: " + descriptorUUID.toString());
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mCharUUID.setText("characteristic UUID:" + characteristicUUID);
}
});
gatt.readCharacteristic(characteristic);
//setNotify(characteristic);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
Log.i(TAG,"descriptor != null");
}
}
}
} else {
Log.i(TAG, "onServicesDiscovered status false");
}
setEnableNotify(characteristic, true);
setCharacteristicNotification(characteristic, true);
sendSetting();
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
super.onCharacteristicChanged(gatt, characteristic, value);
String receivedData = new String(value, StandardCharsets.UTF_8);
Log.d(TAG, "Received data: " + receivedData);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if(status == BluetoothGatt.GATT_SUCCESS){
Log.i(TAG,"onCharacteristicWrite status : " + status);
Log.i(TAG,"value write success !!" );
}
else{
Log.i(TAG,"onCharacteristicWrite status : " + status);
Log.w(TAG,"value write false !!");
}
}
};
@SuppressLint("MissingPermission")
public boolean setNotify(BluetoothGattCharacteristic data_char) {
if (0 != (data_char.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
mBluetoothGatt.setCharacteristicNotification(data_char, true);
BluetoothGattDescriptor descriptor = data_char.getDescriptor(
UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
} else if (0 != (data_char.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
mBluetoothGatt.setCharacteristicNotification(data_char, true);
BluetoothGattDescriptor descriptor = data_char.getDescriptor(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
return true;
}
@SuppressLint("MissingPermission")
public boolean setEnableNotify(BluetoothGattCharacteristic data_char, boolean enable) {
mBluetoothGatt.setCharacteristicNotification(data_char, enable);
return true;
}
@SuppressLint("MissingPermission")
private void connectGatt() {
if (mdevice != null)
mBluetoothGatt = mdevice.connectGatt(MainActivity.this, false, mGattCallback);
else
Toast.makeText(MainActivity.this, "Not Bluetooth Device,can't build GATT", Toast.LENGTH_LONG).show();
}
public byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
@SuppressLint("MissingPermission")
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
String characteristicString = characteristic.toString();
Log.i(TAG,"characteristicString : " + characteristicString);
if (mBTAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
As a beginner in Android Studio, I aim to send a hexadecimal command `87` and receive Bluetooth responses.
Currently, I am able to connect to the Bluetooth device, and the `onConnectionStateChange()`, `onServicesDiscovered()`, and `onCharacteristicWrite()` functions are be executed.
However, I cannot receive Bluetooth data, and `onCharacteristicChanged()` is not being invoked. Am I missing any steps or are these code snippets incorrect?
If you could assist me in modifying the code, I would greatly appreciate it. |
To *"limit the number of elements in the following `string_agg()`"*, use [`LIMIT`][1] in a subquery:
<pre><code>SELECT string_agg(tag, ', ') AS tags
FROM (
SELECT DISTINCT tag
FROM tbl
-- ORDER BY tag -- optionally order to get deterministic result
<b>LIMIT 123</b> -- add your limit here
) sub;</code></pre>
The subquery is no problem for performance at all. **On the contrary**, this is typically **faster**, even if you don't impose a maximum number with `LIMIT`, because the group-wise `DISTINCT` in the aggregate function is more expensive than doing it in a subquery for all rows at once.
Or, to get the *"100 most common tags"*:
~~~pgsql
SELECT string_agg(tag, ', ') AS tags
FROM (
SELECT tag
FROM tbl
GROUP BY tag
ORDER BY count(*) DESC
LIMIT 100
) sub;
~~~
[1]: https://www.postgresql.org/docs/current/sql-select.html#SQL-LIMIT |
RecyclerView in Fragment Resets with ViewPager Tab Updated |
Dude, you have a lot of mistakes in the code, and the main thing in the key of the question is that you don't pass the `pattern` to the `input` component.
I created a simple [**example**](https://play.vuejs.org/#eNp9U8Fu2zAM/RVBl7ZAEgPbTplXYB166IBtxbLbtINjM646WdIkKs1g+N9LKXZso0FOpvgeySfxueWfrV3tA/A1z33ppEXmAYO9FVo21jhkD9oGZDtnGna1ytIpFlx9FDrPjiVEpgNCY1WBQCfG8p1xTYooTkXHmLG1g39BOqg+CY4ugOADYgtEcJry17+FePnTvlt0NwOcDc22AdHo203YNhLzrD+mmVk/NM8mWviCoy+N3sl69eyNppu2kS14aRorFbgfFqXRXvA1S0jECqXMy9eUiyIXQ758gvLvmfyzP8Sc4I8OPLg9XeuEYeFqwCN8v/kOB4pPYGOqoIh9AfwJ3qgQNR5pd0FXJHvCS2of0r6krn/5+wOC9sOl0isTs0t8wWl7Xy5cfZT7fvUh1Qnd0SueVn/GKxXspIZHZ6y/To3wv4U126AjPWmsLpp5YrDBmt0Zo6DQKQvOGffN1zNqb4whR3JuLpuvkntWqsJ78lL0xLJ2JlgGChrQdLXeS8SUU2uSOaPuaEz6jMakfJRP+fiZ5SdmHsIZPnq6j6boTCJZFJ1RIz6KVMUW1KQp8c9oOddtSY9SwpNRVfTLm86MtW3aDOtoyf20LI0bp3tb6FPztJ9l42t6RKod1kX1tA8i9j8iLeDNf9i9Aqkvbhg=) for you where everything works.
```
// App.vue
<script setup>
import Input from './Input.vue';
</script>
<template>
<form>
<Input
:required="true"
pattern="([\w]{2,})"
/>
<button>Submit</button>
</form>
</template>
```
```
// Input.vue
<script setup>
defineProps({
type: String,
name: String,
required: Boolean,
errorMsg: String,
pattern: String
})
</script>
<template>
<div class="form-group element">
<input
:type="type"
:name="name"
:required="required"
:pattern="pattern"
class="form-control"
>
<label
:for="name"
class="form-control-placeholder"
>
{{ name }}
</label>
<span class="error-msg">{{ errorMsg }}</span>
</div>
</template>
``` |
How to allocate a structure on heap without stack overflow in Rust? |
|rust|stack-overflow| |
we were given a defined protocol for a project. We were asked to write server and client code using this protocol in Python. I have written server and client code, but I am encountering some errors. Can you help me correct the code?
[[enter image description here](https://i.stack.imgur.com/IB8xh.png)](https://i.stack.imgur.com/0maxY.png)[[enter image description here](https://i.stack.imgur.com/lAbQ0.png)](https://i.stack.imgur.com/njkgf.png)
Server:
```
import socket
import os
def parse_header(header_bytes):
# Parse header information
message_type = (header_bytes[7] >> 7) & 0b1
query_type = (header_bytes[7] >> 5) & 0b11
message_id = header_bytes[7] & 0b11111
timestamp = (header_bytes[6] << 24) | (header_bytes[5] << 16) | (header_bytes[4] << 8) | header_bytes[3]
status_code = (header_bytes[2] >> 5) & 0b111
body_length = header_bytes[1]
return message_type, query_type, message_id, timestamp, status_code, body_length
def handle_client(client_socket):
# Process message received from the client
header = client_socket.recv(8) # Receive 8 bytes of data for the 64-bit header
message_type, query_type, message_id, timestamp, status_code, body_length = parse_header(header)
if query_type == 0b00: # Verify directory existence
# Receive the file path from the client
directory_length = body_length
directory = client_socket.recv(directory_length).decode()
# Check directory existence
if os.path.exists(directory):
status_code = 0b000 # Exist
else:
status_code = 0b001 # Not Exist
# Send the result to the client
header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
client_socket.send(header)
elif query_type == 0b01: # Check file existence
# Receive the file path from the client
file_length = body_length
file_path = client_socket.recv(file_length).decode()
# Check file existence
if os.path.isfile(file_path):
status_code = 0b000 # Exist
else:
status_code = 0b001 # Not Exist
# Send the result to the client
header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
client_socket.send(header)
elif query_type == 0b10: # Determine if an existing file has been modified after a specified timestamp
# Receive file information from the client
file_info_length = body_length
file_info = client_socket.recv(file_info_length).decode()
# Check file existence and timestamp
file_path, timestamp = file_info.split(',')
if os.path.isfile(file_path):
file_timestamp = os.path.getmtime(file_path)
if file_timestamp > int(timestamp):
status_code = 0b010 # Changed
else:
status_code = 0b011 # Not Changed
else:
status_code = 0b001 # Not Exist
# Send the result to the client
header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
client_socket.send(header)
elif query_type == 0b11: # Identify files with a specified extension that have been modified after a given timestamp
# Receive file extension and timestamp information from the client
file_info_length = body_length
file_info = client_socket.recv(file_info_length).decode()
# Check file extension and timestamp
file_extension, timestamp = file_info.split(',')
matching_files = [f for f in os.listdir('.') if f.endswith(file_extension)]
modified_files = []
for file in matching_files:
file_path = os.path.join('.', file)
file_timestamp = os.path.getmtime(file_path)
if file_timestamp > int(timestamp):
modified_files.append(file)
# Send the result to the client
response_message = ','.join(modified_files)
body_length = len(response_message)
header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
client_socket.send(header)
client_socket.send(response_message.encode())
client_socket.close() # Close the connection
def run_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 31369)) # Bind to the specified port
server_socket.listen(1) # Listen for connections
print("Server is listening...")
while True:
client_socket, client_address = server_socket.accept() # Accept the connection
print(f"Connection accepted from {client_address}.")
handle_client(client_socket) # Process the connection
if __name__ == "__main__":
run_server()
```
Client:
```
import socket
import time
def create_header(message_type, query_type, message_id, timestamp, body_length):
# Creating the header
header = bytes([(message_type << 7) | (query_type << 5) | message_id, (timestamp >> 24) & 0xFF, (timestamp >> 16) & 0xFF, (timestamp >> 8) & 0xFF, timestamp & 0xFF, body_length])
return header
def send_query(client_socket, header, body_message=""):
# Sending the query message
client_socket.send(header)
if body_message:
client_socket.send(body_message.encode())
def receive_response(client_socket):
# Receive response from the server
response_header = client_socket.recv(8)
response_body_length = response_header[1]
response_body = client_socket.recv(response_body_length).decode()
return response_header, response_body
def run_client():
server_address = ('localhost', 31369)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_address)
# QUERY 1: Verify directory existence
message_type = 0b0
query_type = 0b00
message_id = 0b00001
timestamp = 0 # Time in seconds, for example: int(time.time())
path = input("Please enter the directory path to check: ")
body_length = len(path)
header = create_header(message_type, query_type, message_id, timestamp, body_length)
send_query(client_socket, header, path)
response_header, response_body = receive_response(client_socket)
print("QUERY 1 Response Header:", response_header)
print("QUERY 1 Response Body:", response_body)
# QUERY 2: Check file existence
message_type = 0b0
query_type = 0b01
message_id = 0b00010
file_path = input("Please enter the file path to check: ")
body_length = len(file_path)
header = create_header(message_type, query_type, message_id, timestamp, body_length)
send_query(client_socket, header, file_path)
response_header, response_body = receive_response(client_socket)
print("QUERY 2 Response Header:", response_header)
print("QUERY 2 Response Body:", response_body)
# QUERY 3: Determine if an existing file has been modified after a specified timestamp
message_type = 0b0
query_type = 0b10
message_id = 0b00011
file_path = input("Please enter the file path to check: ")
timestamp = int(time.time()) # For example: int(time.time()) - 3600 (an hour ago)
file_info = f"{file_path},{timestamp}"
body_length = len(file_info)
header = create_header(message_type, query_type, message_id, timestamp, body_length)
send_query(client_socket, header, file_info)
response_header, response_body = receive_response(client_socket)
print("QUERY 3 Response Header:", response_header)
print("QUERY 3 Response Body:", response_body)
# QUERY 4: Identify files with a specified extension that have been modified after a given timestamp
message_type = 0b0
query_type = 0b11
message_id = 0b00100
file_extension = input("Please enter the file extension to check (e.g., .txt): ")
timestamp = int(time.time()) - 3600 # For example: int(time.time()) - 3600 (an hour ago)
file_info = f"{file_extension},{timestamp}"
body_length = len(file_info)
header = create_header(message_type, query_type, message_id, timestamp, body_length)
send_query(client_socket, header, file_info)
response_header, response_body = receive_response(client_socket)
print("QUERY 4 Response Header:", response_header)
print("QUERY 4 Response Body:", response_body)
client_socket.close()
if __name__ == "__main__":
run_client()
```
|
Python Client-Server Communication with Protocol |
|python|sockets|networking|protocols|serversocket| |
null |
{"Voters":[{"Id":666221,"DisplayName":"diegoveloper"},{"Id":807126,"DisplayName":"Doug Stevenson"},{"Id":209103,"DisplayName":"Frank van Puffelen"}]} |
adb shell dumpsys dropbox --print system_server_watchdog |
I found this iframe code and deleted it which solved the problem for me.
`<iframe id="orderFrame" name="orderFrame" src="#" style="visibility:hidden;width:0px;height:0px;"></iframe>`
Check the iframes. |
# Issue
The issue here is that you have managed to use Javascript's [Comma Operator][1] unintentionally.
> The comma (`,`) operator evaluates each of its operands (from left to
> right) and returns the value of the last operand. This is commonly
> used to provide multiple updaters to a [for][2] loop's afterthought.
In other words, the Javascript compiler/engine is expecting another expression after the last/trailing comma.
```javascript
export const formSlice = createSlice({
name: "form",
initialState,
reducers: {},
extraReducers: builder =>{
builder.getform(pending, (state) => { // <-- expression
state.status = "pending";
}),
builder.getform(pending, (state) => { // <-- expression
state.status = "success";
}),
builder.getform(pending, (state) => { // <-- expression
state.status = "fail";
}),
// <-- missing expected expression
},
});
```
# Solution
The RTK slice's `extraReducers` property is a function and you should either be chaining from the `builder` object or explicitly defining each case.
The `builder` object has an `addCase` function that you should be using as well, `builder.getform` is not a function and would throw an error.
Expected use cases:
```javascript
export const formSlice = createSlice({
name: "form",
initialState,
extraReducers: builder => {
builder
.addCase(getform.pending, (state) => {
state.status = "pending";
})
.addCase(getform.fulfilled, (state) => {
state.status = "success";
})
.addCase(getform.rejected, (state) => {
state.status = "fail";
});
},
});
```
or
```javascript
export const formSlice = createSlice({
name: "form",
initialState,
extraReducers: builder =>{
builder.addCase(getform.pending, (state) => {
state.status = "pending";
});
builder.addCase(getform.fulfilled, (state) => {
state.status = "success";
});
builder.addCase(getform.rejected, (state) => {
state.status = "fail";
});
},
});
```
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for |
I think best would be just to set `left` and `top` using `%` units.
You can do the same for the `width`.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
window.addEventListener("load", function() {
document.getElementById('map1').onclick = function(event) {
const rect = event.target.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
addMarker(x, y, rect.width, rect.height);
}
});
function resize() {
document.getElementById('map1').style.width = ((Math.random() * 50) + 50) + "%"
}
function addMarker(x, y, w, h) {
var i = new Image();
i.src = 'https://placehold.co/32x32/000000/FFF';
i.style.position = "absolute";
i.onload = function() {
var yOffset = y;
var xOffset = x;
console.log()
// Apply offsets for CSS margins etc.
yOffset -= i.height / 2;
xOffset -= i.width / 2;
// Set image insertion coordinates
// i.style.top = yOffset + 'px';
// i.style.left = xOffset + 'px';
i.style.top = yOffset / h * 100 + '%';
i.style.left = xOffset / w * 100 + '%';
// optionally:
// i.style.width = i.width / w * 100 + '%'
}
// Append the image to the DOM
document.getElementById('map1').appendChild(i);
}
<!-- language: lang-css -->
.responsive {
position: relative;
max-width: 1200px;
width: 100%;
height: auto;
border: 1px solid red;
}
.responsive #myImg {
width: 100%;
}
<!-- language: lang-html -->
<div class="container">
<div style="height: auto; padding: 3px 0 3px 0;">
<div class="card">
<div class="card_content">
<h1>Map PNG Testing <button onclick="resize()">toggle size</button></h1>
<div id="map1" class="responsive">
<img src="https://picsum.photos/800/400" id="myImg">
</div>
</div>
</div>
</div>
</div>
<!-- end snippet -->
|
I have developed a simple telegram bot using the telebot library in python. I want to deploy it somewhere so it's always running, preferably for free. I was thinking vercel, but can't get it to work, what is the easiest way to do this and the best place to deploy? Is there a template that I can use somewhere and then just replace it with my functions etc.?
I tried running it on vercel already and Heroku but it didn't quite work, I am open to using another library if need be, I just have my functions ready and want to make a telegram bot out of them, the current library works locally, but I want to deploy. |
Deploying telegram bot |
|python|deployment|bots|telegram|telegram-bot| |
null |
{"Voters":[{"Id":5641669,"DisplayName":"Johannes"},{"Id":2802040,"DisplayName":"Paulie_D"},{"Id":1940850,"DisplayName":"karel"}],"SiteSpecificCloseReasonIds":[13]} |
This error is unrelated to Turtle. It's raised by `mendeleev.element(element)`, although the error message is a bit confusing. A [minimal example](https://stackoverflow.com/help/minimal-reproducible-example) is:
```none
>>> import mendeleev
>>> mendeleev.element("si")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/g/.local/lib/python3.10/site-packages/mendeleev/mendeleev.py", line 64, in element
return _get_element(ids)
File "/home/g/.local/lib/python3.10/site-packages/mendeleev/mendeleev.py", line 81, in _get_element
return session.query(Element).filter(Element.symbol == str(ids)).one()
File "/home/g/.local/lib/python3.10/site-packages/sqlalchemy/orm/query.py", line 2797, in one
return self._iter().one() # type: ignore
File "/home/g/.local/lib/python3.10/site-packages/sqlalchemy/engine/result.py", line 1827, in one
return self._only_one_row(
File "/home/g/.local/lib/python3.10/site-packages/sqlalchemy/engine/result.py", line 760, in _only_one_row
raise exc.NoResultFound(
sqlalchemy.exc.NoResultFound: No row was found when one was required
```
The fix is to use the capitalized `"Si"` rather than the lowercase `"si"`:
```py
>>> mendeleev.element("Si").name
'Silicon'
```
There's a [PR open](https://github.com/lmmentel/mendeleev/pull/142) to improve the clarity of the error message. |
I have such violet color for options which I would like to choose:
[![enter image description here][1]][1]
in all tutorials which I reviewed options which I'm trying to use like `From Neuroscal .EEG file` are black. But Neuroscanio is installed as I see for eeglab:
[![enter image description here][2]][2]
so is it possible to fix such problem?
[1]: https://i.stack.imgur.com/6VXrl.png
[2]: https://i.stack.imgur.com/8OGJA.png |
Why options are not available in EEGLAB menu options? |
|matlab|eeglab| |
Working bilingual, Shortcut Ctrl+' used to work for me for years in both languages (English and Hebrew), but not in 2016. Is there a way to make Ctrl+, (the second language equivalent of Ctrl+') do the same copy-from-previous-record action? Thanks! |
Ctrl+' for copying from previous record in MS Access not working bilingual in Access 2016 |
Getting "422 Unprocessable Entity" error when positing stringified body from node.js to Python FastAPI |
|python|node.js|json|fastapi|stringify| |
I just start working with Ant Design and I encounter a problem with Table. Here is my code
```
<div className="main-table">
<Table
rowSelection={{
type: 'checkbox',
...rowSelection,
}}
columns={dataColumns}
dataSource={dataOrder}
bordered
pagination={{ pageSize: 50 }}
scroll={{ x: 'true', y: 240 }}
/>
</div>
```
My current layout has a sidebar on the left, and a table on the right. In ```dataSource```, I set width to every columns, have a fixed header and the last column has the attribute ``` fixed: right ```. The div with class 'main-table' has width: 100%. The result is that table displays on the whole page, not scrolling only in table. I suppose that is because there is no fixed width (when I set width to 1000px, it can scroll inside table). I want to keep width to 100%. How can I achieve this?
|