instruction stringlengths 0 30k ⌀ |
|---|
Sorry, you can't ignore syntax errors (assuming you want to allow any template constructs at all). The parser can't do that. `TemplateExceptionHandler`-s only handle runtime errors, that is, errors during template execution (which is later than parsing).
Also, if you could ignore syntax errors, that's certainly confusing for the user. Because, then things that are wrong just silently output nothing, and the user may not notice that the output is broken. When they do notice it, they still don't know why it didn't print anything, as they won't get any error details. |
I've written this BASH script:
```
find ./build/html -name '*.html' \( -exec echo ../emojize_pngorsvg.py \"{}\" \> \"{}.emojized\" \&\& rm \"{}\" \&\& mv \"{}.emojized\" \"{}\" >> ../emojize_commands.sh \; \)
cat ../emojize_commands.sh
chmod +x ../emojize_commands.sh
../emojize_commands.sh
```
It loops over all of the HTML files it finds in the `./build/html` dir and it creates a single file called `emojize_commands.sh` which looks something like this:
```
../emojize_pngorsvg.py "./build/html/Home/Technical/Guides/Windows/Force-activate-a-Windows-evaluation/index.html" > "./build/html/Home/Technical/Guides/Windows/Force-activate-a-Windows-evaluation/index.html.emojized" && rm "./build/html/Home/Technical/Guides/Windows/Force-activate-a-Windows-evaluation/index.html" && mv "./build/html/Home/Technical/Guides/Windows/Force-activate-a-Windows-evaluation/index.html.emojized" "./build/html/Home/Technical/Guides/Windows/Force-activate-a-Windows-evaluation/index.html"
../emojize_pngorsvg.py "./build/html/Home/Technical/Guides/Windows/Various-Windows-Tips/index.html" > "./build/html/Home/Technical/Guides/Windows/Various-Windows-Tips/index.html.emojized" && rm "./build/html/Home/Technical/Guides/Windows/Various-Windows-Tips/index.html" && mv "./build/html/Home/Technical/Guides/Windows/Various-Windows-Tips/index.html.emojized" "./build/html/Home/Technical/Guides/Windows/Various-Windows-Tips/index.html"
../emojize_pngorsvg.py "./build/html/Home/Technical/Guides/Windows/Configure-RDP-to-connect-with-stored-credentials/index.html" > "./build/html/Home/Technical/Guides/Windows/Configure-RDP-to-connect-with-stored-credentials/index.html.emojized" && rm "./build/html/Home/Technical/Guides/Windows/Configure-RDP-to-connect-with-stored-credentials/index.html" && mv "./build/html/Home/Technical/Guides/Windows/Configure-RDP-to-connect-with-stored-credentials/index.html.emojized" "./build/html/Home/Technical/Guides/Windows/Configure-RDP-to-connect-with-stored-credentials/index.html"
# Much more lines here
```
Then it executes `emojize_commands.sh` - which works perfectly as expected!
I'm trying to remove the need for it to use a temporary file to do all of this. I'd rather it just execute the commands directly instead of needing to `echo` them to a file first.
I've tried removing `echo` and `>> ../emojize_commands.sh` (plus all of the other lines of code) so I am left with just this:
```
find ./build/html -name '*.html' \( -exec ../emojize_pngorsvg.py \"{}\" \> \"{}.emojized\" \&\& rm \"{}\" \&\& mv \"{}.emojized\" \"{}\" \; \)
```
But when I run it I get a bunch of "file not found" errors!
How can I get `find` to work how I want please? |
|angular|google-cloud-platform| |
I have already have a CNN algorithm and saved it in .h5 format but when I use this for prediction with the help of camera I am not able to predict , its just camera opens but there is no predictions and other content
Here is my code , I am actually learning ML so could you please solve this problem ?
Here is my code , I am actually learning ML so could you please solve this problem ?
I am expecting to predict the image class when I show a image to laptop camera
```
import numpy as np
import cv2
from keras.models import load_model
# Load the model
model = load_model('C:/Users/Win/Downloads/traffic_classifier.h5')
# Parameters
frameWidth = 640 # CAMERA RESOLUTION
frameHeight = 480
brightness = 180
threshold = 0.5 # PROBABILITY THRESHOLD
font = cv2.FONT_HERSHEY_SIMPLEX
# SETUP THE VIDEO CAMERA
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10, brightness)
def preprocessing(img):
# Convert image to RGB format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Resize image to 30x30
img = cv2.resize(img, (30, 30))
# Normalize pixel values
img = img / 255.0
# Add batch dimension
img = np.expand_dims(img, axis=0)
return img
def getClassName(classNo):
classes = {
0: 'Speed Limit 20 km/h',
1: 'Speed Limit 30 km/h',
2: 'Speed Limit 50 km/h',
3: 'Speed Limit 60 km/h',
4: 'Speed Limit 70 km/h',
5: 'Speed Limit 80 km/h',
6: 'End of Speed Limit 80 km/h',
7: 'Speed Limit 100 km/h',
8: 'Speed Limit 120 km/h',
9: 'No passing',
10: 'No passing for vehicles over 3.5 metric tons',
11: 'Right-of-way at the next intersection',
12: 'Priority road',
13: 'Yield',
14: 'Stop',
15: 'No vehicles',
16: 'Vehicles over 3.5 metric tons prohibited',
17: 'No entry',
18: 'General caution',
19: 'Dangerous curve to the left',
20: 'Dangerous curve to the right',
21: 'Double curve',
22: 'Bumpy road',
23: 'Slippery road',
24: 'Road narrows on the right',
25: 'Road work',
26: 'Traffic signals',
27: 'Pedestrians',
28: 'Children crossing',
29: 'Bicycles crossing',
30: 'Beware of ice/snow',
31: 'Wild animals crossing',
32: 'End of all speed and passing limits',
33: 'Turn right ahead',
34: 'Turn left ahead',
35: 'Ahead only',
36: 'Go straight or right',
37: 'Go straight or left',
38: 'Keep right',
39: 'Keep left',
40: 'Roundabout mandatory',
41: 'End of no passing',
42: 'End of no passing by vehicles over 3.5 metric tons'
}
return classes[classNo]
while True:
success, imgOriginal = cap.read()
# Preprocess the image
img = preprocessing(imgOriginal)
# Predictions
predictions = model.predict(img)
classIndex = np.argmax(predictions, axis=1)
probabilityValue = np.amax(predictions)
# Display results if probability is above threshold
if probabilityValue > threshold:
class_name = getClassName(classIndex)
cv2.putText(imgOriginal, "CLASS: " + class_name, (20, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(imgOriginal, "PROBABILITY: " + str(round(probabilityValue * 100, 2)) + "%", (20, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow("Result", imgOriginal)
else:
cv2.imshow("Processed Image", imgOriginal)
if cv2.waitKey(1) & 0xFF == ord('q'): # Check for 'q' key press to exit
break
cap.release()
cv2.destroyAllWindows()
```
|
My frontend is a React app that I compiled using `npm run build`. Once the build folder is copied to the django project, I go in my Django virtualenv and run `python3 manage.py collectstatic` and `python3 manage.py runserver`
When I run the server, I can read two errors in the console:
Loading module from “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js” was blocked because of a disallowed MIME type (“text/html”).
The resource from “http://127.0.0.1:8000/assets/index-6ReKyqhx.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
and one warning:
Loading failed for the module with source “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js”.
(Django) settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
package.json
...
"scripts": {
"dev": "vite",
"build": "rm -rf ../backend/build && tsc && vite build && cp -r build ../backend/build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
...
I am confuse because there is no static folder in the build folder. Django gives me this warning:
WARNINGS:
?: (staticfiles.W004) The directory '/home/user/project/backend/build/static' in the STATICFILES_DIRS setting does not exist.
The build folder looks like this:
build/
----assets/
--------index-<randomString>.css
--------index-<anotherString>.js
----index.html
----vite.svg
Note: I run everything locally |
im studying into a bootcamp and one of past challenge was create a Pokedex with pokeapi. i over the challenge and now im going to fix some thinks.
I have a strange problem when im into details of the single pokemon. When into interpolation i put the varius propriety i dont get problm, into screen stamp it but console log give me and error.
```
detail.component.ts:79 ERROR TypeError: Cannot read properties of undefined (reading 'type')
at DetailComponent_Template (detail.component.ts:26:12)
at executeTemplate (core.mjs:11223:9)
at refreshView (core.mjs:12746:13)
at detectChangesInView$1 (core.mjs:12970:9)
at detectChangesInViewIfAttached (core.mjs:12933:5)
at detectChangesInComponent (core.mjs:12922:5)
at detectChangesInChildComponents (core.mjs:12983:9)
at refreshView (core.mjs:12796:13)
at detectChangesInView$1 (core.mjs:12970:9)
at detectChangesInViewIfAttached (core.mjs:12933:5)
```
```Details Component
@Component({
selector: 'app-detail',
standalone: true,
imports: [DetailComponent],
template: `
<div>
<h2>{{ this.pokemonDetails.name.toUpperCase() }}</h2>
<img
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{
pokemonId
}}.png"
alt="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{
pokemonId
}}.png"
height="100"
/>
<div>
<p>Pokemon type:</p>
<p>{{ this.pokemonDetails.types[0].type.name }}</p>
<p>{{ this.pokemonDetails.types[1].type.name }}</p>
</div>
<div>
<p>
Description:
{{ this.speciesDetail.flavor_text_entries[0].flavor_text }}
</p>
</div>
<div>
<p>BASE STAT:</p>
<ul>
<li>
<p>HP:{{ this.pokemonDetails.stats[0].base_stat }}</p>
</li>
<li>
<p>ATK:{{ this.pokemonDetails.stats[1].base_stat }}</p>
</li>
<li>
<p>DEF:{{ this.pokemonDetails.stats[2].base_stat }}</p>
</li>
<li>
<p>S. ATK:{{ this.pokemonDetails.stats[3].base_stat }}</p>
</li>
<li>
<p>S. DEF:{{ this.pokemonDetails.stats[4].base_stat }}</p>
</li>
<li>
<p>SPEED:{{ this.pokemonDetails.stats[5].base_stat }}</p>
</li>
</ul>
</div>
</div>
`,
styles: ``,
})
export default class DetailComponent implements OnInit {
pokemonId!: number;
pokemonDetails!: Pokemon;
speciesDetail!: Species;
public service = inject(StateService);
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.route.params.subscribe((params) => {
this.pokemonId = params['id'];
this.service.getPokemonById(this.pokemonId).subscribe((pokemon) => {
this.pokemonDetails = pokemon;
console.log(this.pokemonDetails);
});
this.service
.getPokemonSpeciesDetailsById(this.pokemonId)
.subscribe((pokemon) => {
this.speciesDetail = pokemon;
console.log(this.speciesDetail);
});
});
}
}
```
```this is the service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, forkJoin } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { Pokemon, PokemonResults } from '../../model/pokemon';
@Injectable({
providedIn: 'root',
})
export class StateService {
private pokemonListSubject: BehaviorSubject<Pokemon[]> = new BehaviorSubject<
Pokemon[]
>([]);
public pokemonList$: Observable<Pokemon[]> =
this.pokemonListSubject.asObservable();
constructor(private http: HttpClient) {}
fetchPokemonList(offset: number = 0, limit: number = 20): Observable<void> {
const url = `https://pokeapi.co/api/v2/pokemon/?offset=${offset}&limit=${limit}`;
return this.http.get<PokemonResults>(url).pipe(
map((data: PokemonResults) => data.results),
mergeMap((pokemonResults) =>
this.fetchDetailedPokemonData(pokemonResults)
),
map((detailedPokemonList) => {
this.pokemonListSubject.next(detailedPokemonList);
})
);
}
private fetchDetailedPokemonData(
pokemonList: { name: string; url: string }[]
): Observable<Pokemon[]> {
return forkJoin(
pokemonList.map((pokemon) => this.http.get<Pokemon>(pokemon.url))
);
}
getPokemonById(id: number): Observable<Pokemon> {
const url = `https://pokeapi.co/api/v2/pokemon/${id}`;
return this.http.get<Pokemon>(url);
}
getPokemonSpeciesDetailsById(id: number): Observable<any> {
const url = `https://pokeapi.co/api/v2/pokemon-species/${id}`;
return this.http.get<any>(url);
}
}
```
[enter image description here](https://i.stack.imgur.com/o3YQe.png)
i hope someone can help me becouse some pokemon display and some no! im going crazy to found the problem!
<h2>{{ this.pokemonDetails.name?.toUpperCase() }}</h2>
i try somethinks like this but orange alert appears.
im newbie into the world of programmation |
Pokedex on angular 17 |
|angular|typescript|angular17| |
null |
|javascript|firebase-realtime-database|react-native-firebase| |
null |
For SpringBoot version 3 and above just add this dependency in pom.xml to run swagger
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
But if you want to use SpringFox dependencies first you need to downgrade SpringBoot to below version 3
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Then add SpringFox dependencies in pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
Make SwaggerConfig class
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // Specify the package containing your controllers
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API Documentation")
.description("Documentation for your API")
.version("1.0")
.build();
}
}
Lastly add ANT_PATH_MATCHER in application.properties file
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
Swagger-ui will run in http://localhost:8080/swagger-ui/index.html
|
|ms-access|keyboard-shortcuts| |
null |
As of now you can't use multiple inputs through RouterChain in Python, but it's possible in NodeJs. I tried there output parsers and created mine also but in python it doesn't work the way it worked in NodeJs.
You can do one thing, you can replace the strings and pass single input to the router chain, it will work for you. cheers :)
May be in future langchain will provide a solution for that as it's drastically changing. |
I just set up Docker for the first time and had the same question, that's how I came across your thread. I realized that in my case -- and this might not apply to you -- the images in question were generated by external sources, so the created dates are presumably based on their original creation date or a later modification date by the source, not the date they're created on my computer. One was a welcome-to-docker image generated by Docker, and the other was a Vikunja image. The date for any container that I create myself is generating correctly. |
You can try this:
```
conda update conda
conda update conda-build
conda install -n base conda-libmamba-solver
conda config --set solver libmamba
```
My answer is based on the issue raised [in Conda's issue tracker](https://github.com/conda/conda/issues/11919). |
data(murders)
murders_2 <- murders %>%
mutate(rate = total / population * 100000) %>%
mutate(idx = case_when(rate < median(rate) ~ "low",
TRUE ~ "high")) %>%
select(state, region, rate, idx) %>%
group_by(idx)
group_by(idx) is not applicable.
What's the problem?
I hope the results are sorted according to idx |
I typed all the codes well, but only the group_by function doesn't work |
|r|group-by|rstudio| |
null |
Popovers created with the Popover API are in a separate “layer”, so they can’t be easily positioned relative to other elements in your document.
[Read more][1]
[1]: https://hidde.blog/positioning-anchored-popovers/ |
It looks like you are looking for a function wrapper, which takes the arguments as you really want them, and which has the function `F` as a local function inside of it, and calls it:
```
def zeta(S, n): # wrapper around F
def F(d, n):
if d == 0:
return 1
return sum(F(d-1, k)/(k**S[-d]) for k in range(1, n+1))
return F(len(S), n) # Call F and return what it returns
# Example call
result = zeta((10, 2, 1, 1, 1), 20)
print(result)
```
|
I have an assignment to complete using RTC-Tools. Failure to install it via pip.
I need RTC-Tools for a homework assignment. Tried to follow this tutorial to get it: https://rtc-tools.readthedocs.io/en/stable/getting-started.html
As it needed pip for installation, I installed pip: https://www.geeksforgeeks.org/how-to-install-pip-on-windows/
Then, I followed the RTC-Tools installation steps.
In the command prompt, I wrote "pip install rtc-tools"
It started downloading, but at the end I got an error message. I don't know how to fix it.
I also tried to git clone ("git clone https://gitlab.com/deltares/rtc-tools.git"). That gave the same error message.
I am using Python 3.9.
Here is the error message in the console (pictures provided, too): ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\admin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\rtctools_channel_flow\\modelica\\Deltares\\ChannelFlow\\SimpleRouting\\Branches\\Internal\\KLagNonlinearityParameterDenominator.mo'
[the error shown in the command prompt] (https://i.stack.imgur.com/ecSkw.png)
|
Trained ML model with the camera module is not giving predictions |
|python|machine-learning|computer-vision|camera| |
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):
[CubeMX][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/z3BUu.png |
Problem is that you have your **search** `ImageButton` defined inside `MainFragment` layout but you are trying to search it within activity contentView, so in this case `findViewById` returns null and code crashes on `NullPointerException`.
You should move the definition of search ImageButton and the assignment of `OnClickListener` into `MainFragment` code.
Also, when using `viewBindings` you don't have to assign view manually by `findViewById`, you can use it's reference from generated `viewBindings`. |
I'm running selenium and when a ask to open Chrome it open and after 1 sec closes
From my understanding that happens becasue chromedrive is not updated to my google version 123.0.6312.87 (oficial) (arm64) form MacOs Sonoma. How can I fix it? |
Selenium ChromeDriver |
|selenium-chromedriver| |
null |
I have installed Debian 12 on Google Cloud Compute Engine, and I used Mokutil to install a certificate, but I couldn't.
mokutil --import certification.cer
After rebooting, the Mokutil key management screen appears, but I cannot enter the key.
Does anyone know how to solve this problem? |
|google-cloud-platform|debian|google-compute-engine| |
null |
I have installed Debian 12 on Google Cloud Compute Engine, and I used Mokutil to install a certificate, but I couldn't.
```
mokutil --import certification.cer
```
After rebooting, the Mokutil key management screen appears, but I cannot enter the key.
Does anyone know how to solve this problem? |
If I have a vector A = [0, 0, 1, 1, 2, 3] and B = [11, 23, 45, 1, 4, 7] and C = [0, 2, 3] how can I fill vector D such that it has all elements from B that are the corresponding indices where the value of A matches the value in C at the same index meaning D = [11, 23, 4, 7]?
I am using Thrust and I have a solution to do that using a device_vector of device_vectors which works when I set my DEVICE TARGET to CPP but when I set my DEVICE TARGET to CUDA it does not work, specifically the initialization of device vector of device vectors did not work. I think it is because I am initializing them with a value and they're all pointing to the same base element, but I am not sure about that, this is where the error I get when I compile the program with CUDA (It worked with CPP)
```
int max_particles_in_a_cell = 5;
//unique_cell_ids is a vector of size 50.
thrust::device_vector<int> vector_of_particles_in_cell(max_particles_in_a_cell, -1);
thrust::device_vector<thrust::device_vector<int>> vector_of_vector_of_particles_in_cell(unique_cell_ids.size(), vector_of_particles_in_cell);
```
|
How can I do a successful map when the number of elements to be mapped is not consistent in Thrust C++ |
|java|json|parsing|jsonparser| |
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 reference to double-check 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 for troubleshooting this. |
null |
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? The protocols which is given to us is below.
[[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()
```
|
I have a couple of queries (2-4) which are independent and results of which I need to concatenate once all are finished.
Since I don't know about how postgresql works under the hood, I am wondering:
1. Do queries run in parallel automatically?
2. Can I force them to run in parallel if they dont do it automatically?
3. Should I do it?
I would like to avoid running them in serial fashion if parallelization is possible.
Pseudo code of my scenario:
```
(
SELECT func(col1, col2, col3)
FROM table1
JOIN...
WHERE...
)
||
(
SELECT func(col1, col2, col3)
FROM table2
JOIN...
WHERE...
)
||
(
SELECT func(col1, col2, col3)
FROM table3
JOIN...
WHERE...
)
```
|
Concatenate result from several queries - parallelization |
|postgresql| |
The top rated answer does not work with the new Reflectation implementation in e.g. Java 21 that uses MethodHandles and ignores the flags value on the Field abstraction object.
One solution is to use Unsafe, however with [this JEP](https://openjdk.org/jeps/8323072) Unsafe and the important `long objectFieldOffset(Field f)` and
`long staticFieldOffset(Field f)` methods are getting deprecated for removal so for example this will not work in the future:
```java
final final Unsafe unsafe = //..get Unsafe (...and add subsequent --add-opens statements for this to work)
final Field ourField = Example.class.getDeclaredField("changeThis");
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");
```
I do not recommend this but it is possible in Java 21 with the new reflection implementation when making heavy use of the internal API if really needed.
# Java 21+ solution without `Unsafe`
See my answer [here](https://stackoverflow.com/a/77705202/23144795) on how to leverage the internal API to set a final field in Java 21 without Unsafe.
|
With more pondering on the question, I have chosen to approach the question differently thanks to [Elliott][A].
The OP starts out this way and I quote:
> Imagine two smart pointer templates, `smart_ptr` and `smart_ptr_with_abort`
Forgive me for *my approach* but instead let’s imagine two `class`es that can take an arbitrary type upon construction.<sup>[1]</sup>
The constraint is that one `class A` must only take a type that has a method `Abort()` while another `class B` will only take a type that does not have the method `Abort()`. If `class A` is specialized with a type that doesn’t have the member function `Abort()`, the program fails to compile. And if `class B` takes a type that has the member function `Abort()`, the program also fails to compile.
> Using `concept`s I can make `smart_ptr_with_abort`<sup>[2]</sup> fail to compile if it's being used with an object that doesn't have an `Abort()` method.
Without your code I will write one approach here for posterity.
<pre><code>template<class T>
concept Abortable = requires(T t) { {t.Abort()}; };
template<Abortable T>
class A {/* implementation */}</code></pre>
> Is there a way to achieve the reverse situation, where `smart_ptr<object>`<sup>[3]</sup> would fail to compile but `smart_ptr_with_abort<object>` would succeed?
That is by using *”A Logical Negation expression”*. We can simply negate the other `concept` to produce a new `concept`.
<pre><code>template<class T>
concept NotAbortable = !Abortable<T>;
template<NotAbortable T>
class B {/* implementation */}</code></pre>
<hr />
More on *Logical negation expression*:
> <sup>5</sup> [*Note:* A logical negation expression (7.6.2.1) is an atomic constraint; the negation operator is not treated as a logical operation on constraints. As a result, distinct negation constraint-expressions that are equivalent under 13.7.6.1 do not subsume one another under 13.5.4. Furthermore, if substitution to determine whether an atomic constraint is satisfied (13.5.1.2) encounters a substitution failure, the constraint is not satisfied, regardless of the presence of a negation operator. [*Example:*
> <pre><code>template <class T> concept sad = false;
>
> template <class T> int f1(T) requires (!sad<T>);
>
> template <class T> int f1(T) requires (!sad<T>) && true;
> int i1 = f1(42); // ambiguous, !sad<T> atomic constraint expressions (13.5.1.2) are not formed from the same expression
>
> template <class T> concept not_sad = !sad<T>;
>
> template <class T> int f2(T) requires not_sad<T>;
>
> template <class T> int f2(T) requires not_sad<T> && true;
> int i2 = f2(42); // OK, !sad<T> atomic constraint expressions both come from not_sad
>
> template <class T> int f3(T) requires (!sad<typename T::type>);
> int i3 = f3(42); // error: associated constraints not satisfied due to substitution failure
>
> template <class T> concept sad_nested_type = sad<typename T::type>;
>
> template <class T> int f4(T) requires (!sad_nested_type<T>);
> int i4 = f4(42); // OK, substitution failure contained within sad_nested_type</code></pre>
>
> Here,
>
> <code>requires (!sad<typename T::type>)</code> requires that
> there is a nested type that is not sad, whereas
>
> <code>requires (!sad_nested_type<T>)</code> requires that there is no sad nested type. *— end example* ] *— end note* ]
>
> —-ISO/IEC JTC1 SC22 WG21 N4860 13.5.1.1
<hr/>
<sub>[1] This approach shields us from having our design criticized. I admit I did that in my first answer and any critic would do the same I believe.</sub>
<sub>[2] That will be `class A` in our illustration.</sub>
<sub>[3] That will be `class B` in our illustration.</sub>
[A]: https://stackoverflow.com/users/8658157/elliott
|
How can Spring Boot's `PoolingHttpClientConnectionManager` be binded to Micrometer while maintaining as much of Spring Boot's auto-configuration as possible?
Spring Boot auto-configures `PoolingHttpClientConnectionManager` as part of `RestTemplate` (and `RestClient`) when `httpclient5` is on the class path.
As seen here:
https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactories.java#L215
```
private static HttpClient createHttpClient(Duration readTimeout, SslBundle sslBundle) {
// [ truncated extra code ]
PoolingHttpClientConnectionManager connectionManager = connectionManagerBuilder.useSystemProperties()
.build();
return HttpClientBuilder.create().useSystemProperties().setConnectionManager(connectionManager).build();
}
```
I have not been able to get a hold of this `PoolingHttpClientConnectionManager` to apply Micrometer's binder:
```
new PoolingHttpClientConnectionManagerMetricsBinder(connectionManager, "myPool").bindTo(registry);
``` |
How to bind Spring Boot's PoolingHttpClientConnectionManager to Micrometer's PoolingHttpClientConnectionManagerMetricsBinder |
|java|spring|spring-boot|micrometer| |
as I see it you have 3 options:
1. call `plt.show()` at the very end
2. use `plt.show(block=False)`
3. switch to interactive-mode (by calling `plt.ion()` at the very beginning of the script) to avoid blocking the terminal in general
For interactive-mode, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.isinteractive.html#matplotlib.pyplot.isinteractive
|
Actually the issue was something to do with the classes I was using. So because I used the same class for the original row (the empty hidden one) and for the cloned rows that I filled with data, it was coming up in the search and not staying hidden. Also, in the #searchInp, I was just using tr to identify what to filter. When I changed it to use the class name it all worked fine.
|
You have missed an argument in what you wrote. There is no method overloaded for requestLocationUpdates with just four arguments.
There is, however, this [one][1]:
public void requestLocationUpdates (String provider,
long minTimeMs,
float minDistanceM,
Executor executor,
LocationListener listener)
which I think is the one you were trying to invoke. Notice there is an extra argument of Executor type.
There is an explanation about the Executor in the documentation:
> Executor: the executor handling listener callbacks This value cannot
> be null. Callback and listener events are dispatched through this
> Executor, providing an easy way to control which thread is used. To
> dispatch events through the main thread of your application, you can
> use Context.getMainExecutor(). Otherwise, provide an Executor that
> dispatches to an appropriate thread.
So in your case, you would need to add it to your call:
try {
locationManager = (LocationManager) requireActivity().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
3000,
3,
Context.getMainExecutor().
locationListener);
}
catch (Exception e){
e.printStackTrace();
}
[1]: https://developer.android.com/reference/android/location/LocationManager#requestLocationUpdates(java.lang.String,%20long,%20float,%20java.util.concurrent.Executor,%20android.location.LocationListener) |
The code below uses a **background callback** (dash) to retrieve a value.
[![enter image description here][1]][1]
Every 3 seconds, `update_event(event, shared_value)` sets an `event` and define a `value`. In parallel, `listening_process(set_progress)` waits for the `event`.
This seems to work nicely and the waiting time is low (say a few seconds). When the waiting time is below 1 second (say 500ms), `listening_process(set_progress)` is missing values.
Is there a way for the **background callback** to refresh faster ?
It looks like the server updates with a delay of a few hundred of ms, independently of the rate at which I set the `event`.
```
import time
from uuid import uuid4
import diskcache
import dash_bootstrap_components as dbc
from dash import Dash, html, DiskcacheManager, Input, Output
from multiprocessing import Event, Value, Process
from datetime import datetime
import random
# Background callbacks require a cache manager + a unique identifier
launch_uid = uuid4()
cache = diskcache.Cache("./cache")
background_callback_manager = DiskcacheManager(
cache, cache_by=[lambda: launch_uid], expire=60,
)
# Creating an event
event = Event()
# Creating a shared value
shared_value = Value('i', 0) # 'i' denotes an integer type
# Updating the event
# This will run in a different process using multiprocessing
def update_event(event, shared_value):
while True:
event.set()
with shared_value.get_lock(): # ensure safe access to shared value
shared_value.value = random.randint(1, 100) # generate a random integer between 1 and 100
print("Updating event...", datetime.now().time(), "Shared value:", shared_value.value)
time.sleep(3)
app = Dash(__name__, background_callback_manager=background_callback_manager)
app.layout = html.Div([
html.Button('Run Process', id='run-button'),
dbc.Row(children=[
dbc.Col(
children=[
# Component sets up the string with % progress
html.P(None, id="progress-component")
]
),
]
),
html.Div(id='output')
])
# Listening for the event and generating a random process
def listening_process(set_progress):
while True:
event.wait()
event.clear()
print("Receiving event...", datetime.now().time())
with shared_value.get_lock(): # ensure safe access to shared value
value = shared_value.value # read the shared value
set_progress(value)
@app.callback(
[
Output('run-button', 'style', {'display': 'none'}),
Output("progress-component", "children"),
],
Input('run-button', 'n_clicks'),
prevent_initial_call=True,
background=True,
running=[
(Output("run-button", "disabled"), True, False)],
progress=[
Output("progress-component", "children"),
],
)
def run_process(set_progress, n_clicks):
if n_clicks is None:
return False, None
elif n_clicks > 0:
p = Process(target=update_event, args=(event,shared_value))
p.start()
listening_process(set_progress)
return True, None
if __name__ == '__main__':
app.run(debug=True, port=8050)
```
EDIT : found a solution using `interval`.
```
@app.callback(
[
Output('run-button', 'style', {'display': 'none'}),
Output("progress-component", "children"),
],
Input('run-button', 'n_clicks'),
prevent_initial_call=True,
interval= 100, #### **THIS IS NEW**
background=True,
running=[
(Output("run-button", "disabled"), True, False)],
progress=[
Output("progress-component", "children"),
],
)
```
But then, what is the advantage of this approach over a `dcc.interval` ? In both case, there is polling. The only advantage I can see is that the consumer receives the updated value at the *exact* same time it is produced.
[1]: https://i.stack.imgur.com/jqJ5v.gif |
It is a bit difficult to give you an exact solution because it strongly depends on your specific context like for instance:
* how these test files are produced,
* do they change frequently,
* where these files are stored (cloud or other systems),
* are the tests executed on CI or locally,
* are the tests executed on an emulator or real device
... and so on.
That said, you can evaluate the following solutions:
* provide these files through a rest API letting the tests access that endpoint to retrieve the files. This of course has the drawback of increasing the overall time taken to execute the tests (since the tests need to download the files)
* or, build a custom emulator instance (or docker instance) where you pre-propulate the image with the test files and located them in a folder openly accessible without special permission (like for instance `/sdcard/Documents` or `/data/local/tmp` or in the app's private area) |
I have been trying do multi-level mixed effects model on the microbiome data I am working, but I keep getting the error below. What is frustrating is that, I don't encounter this error on my Windows OS which I use in the office, indicating that the problem may not be with the code. I am using a Mac OS.
```
Error in t(do.call(sparseMatrix, do.call(rbind, lapply(seq_along(blist), :
invalid 'lazy' to 'R_sparse_transpose'
```
|
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
{"Voters":[{"Id":2554330,"DisplayName":"user2554330"},{"Id":22180364,"DisplayName":"Jan"},{"Id":1940850,"DisplayName":"karel"}]} |
{"Voters":[{"Id":2554330,"DisplayName":"user2554330"},{"Id":22180364,"DisplayName":"Jan"},{"Id":1940850,"DisplayName":"karel"}],"SiteSpecificCloseReasonIds":[]} |
I would like to ask if the tunctl command can be installed on starem9? I have been reading information related to namespace recently and want to learn more.
I searched for information, but couldn't find it. I used yum -y install tunctl, but it didn't work. |
Stream9,tunctl,yum -y install tunctl |
|linux| |
null |
I had exactly the same requirement i.e. using some of the tkinter.filedialog functions from console apps or scripts rather than a GUI. All my searches for how to achieve it turned up answers involving the creation of a temporary tkinter root window and destroying it after using the dialog box. For years I used such a solution, but was always annoyed at the lag that it created (sometimes, randomly, quite long).
I recently discovered that you just have to invoke the dialog box function - no pesky root window required!
```
from tkinter import filedialog
def getPath(): # now barely worth writing as a function!
path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=(("Text Documents", "*.txt"),))
return path
print(getPath())
```
This has been working for me with filedialog.askopenfilename, filedialog.askdirectory etc, and without the annoying lag. If only I had seen an answer like this earlier!
Please comment if it does not work on your system/version though. |
To get the website source code via scraping:
String targetPage = site;
if(targetPage.contains("https://"))
{
} else {
targetPage = "https://".concat(targetPage);
}
System.out.println();
//System.out.print(targetPage);
System.out.println();
URL wiki = new URI(targetPage).toURL();
URLConnection yc = wiki.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
String line = "";
while ((inputLine = in.readLine()) != null)
line += inputLine;
in.close();
From there, you can use the substring method to find everything in between </title>:
line.substring("</title>","</title>")
You can do the same String manipulation by reading the .html file too |
For this kind of task (multi-dimensional array), you will see a huge benefit in using `numpy`. Not only is it more efficient (when large amount of data), but also everything is more natural.
With `numpy` you can get what you want in 1 line of code (`y = ...`):
```
import numpy as np
x = np.array([
[0, 5, -3, 5, 0, 0],
[-3, 0, 1, 0, 5, 0],
[1, 0, 5, 0, -5, 0],
[-3, 0, 3, 0, 0, 5]
])
y = np.sum(x, axis=0) / np.sum(x != 0, axis=0)
print(y) # [-1.66666667 5. 1.5 5. 0. 5. ]
```
Here you do a sum "vertically" (`axis=0`), and you divide this *vector* by the vertical sum of 0 and 1 values (1 if `!= 0` and 0 if `== 0`), i.e. you are dividing by the count of non-zero elements in each column. |
I have an error with php function chmod https://www.php.net/manual/en/function.chmod.php Any solutions?
I'm running Linux Debian 13.05 with root access.
Php Warning: chmod(): No such file or directory in file: index.php on line: 8
Php Warning: fopen(./access.log): Failed to open stream: Permission denied in file: index.php on line: 9
$root_path = './'; define('LOG_FILE', $root_path . 'access.log');
function add_log_entry($access = '')
{
if (LOG_FILE)
{
chmod(LOG_FILE, 0755);
$fopen = fopen(LOG_FILE, 'ab');
}
} |
After this:
>create directoy importDir as C:/dump
you should have also ran
grant read, write on directory importdir to import
Otherwise, `import` user won't be able to access any file in that directory. If it (`import` user) won't *write* anything there, then `read` privilege is enough.
(BTW, I wouldn't name user `import`; although allowed, it causes confusion as it looks as the `import` database utility.)
As of (the last) error you got: should've probably been
impdp import/123@PDB1 directory=importDir ...
----
just PDB1, not XEPDB1 |
You can try this :
```lang-py
fig.update_layout(legend_itemsizing="constant")
```
> [`itemsizing`][1] - Determines if the legend items symbols scale with their corresponding "trace" attributes or remain "constant" independent of the symbol size on the graph.
In general, we set `itemsizing="constant"` if the marker size is a variable and `itemsizing="trace"` if the marker size is fixed, but in your situation when the marker size is fixed to a small value which is too small for the legend, the "constant" sizing probably remains the best option.
However, this constant is hardcoded somewhere and we can't override it, so the resulting size in the legend might not suffice. The only other way ("trace") sadly requires to increase the marker size on the traces.
[1]: https://plotly.com/python/reference/layout/#layout-legend-itemsizing |
Error while creating docker image from env.yml file which has a python package that i created locally |
|docker|dockerfile|miniconda| |
null |
There are a couple of ways to accomplish what you're asking here. One involves parsing `procfs` which doesn't require "root" privileges and the other is using the [_Taskstats_](https://www.kernel.org/doc/Documentation/accounting/taskstats.txt) (a _Netlink_ interface) which does.
If you can get root privileges using _Generic Netlink_ sockets would be _by far_ the most optimal with regards to overhead.
I have a working solution using the first solution that parses `procfs`:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
class ShMemMonitorProcess(object):
def __init__(self, ppid):
self.ppid = ppid
# Create a Sub-Class for Thread module
self.memory = {'kB':1024, 'mB':1024*1024, 'gB':1024*1024*1024}
self.scrape_procfs
def calculate_memory(self, vmrss):
memory, size = vmrss.split()
return int(memory) * self.memory[size]
@property
def scrape_procfs(self):
rss = 0
child_ps = dict()
start = time.time()
while (time.time() - start) < 100:
for pid in filter(lambda p: p.isdigit(), os.listdir('/proc')):
try:
# open /proc/PID/status but catch as some can be ephemeral
with open('/proc/{}/status'.format(pid)) as fh:
ppid = [i for i in fh.readlines() if i.startswith('PPid')]
if not ppid:
continue
ppid = ppid[0].split('\t')[1].strip('\n')
if ppid == self.ppid:
with open('/proc/{}/status'.format(pid)) as fh:
vmrss = fh.readlines()
vmrss = [i for i in vmrss if i.startswith('VmRSS')]
if not vmrss:
continue
vmrss = vmrss[0].split('\t')[1].strip('\n')
ps_rss = self.calculate_memory(vmrss)
if not child_ps.get(pid):
with open('/proc/{}/comm'.format(pid)) as fh:
comm = fh.readlines()
print('Found Child Process {}!'.format(pid))
print(comm)
print('Adding Process to Hash...')
child_ps[pid] = ps_rss
rss += ps_rss
time.sleep(1)
else:
# re-calculate process memory
print('Process was already found running...')
print('Re-calculating memory usage...')
previous_rss_used = child_ps[pid]
if previous_rss_used > ps_rss:
memory_adj = previous_rss_used - ps_rss
rss -= memory_adj
elif previous_rss_used <= ps_rss:
memory_adj = ps_rss - previous_rss_used
rss += memory_adj
child_ps[pid] = ps_rss
print('Bytes....{}'.format(rss))
except FileNotFoundError:
continue
if __name__ == '__main__':
# Pass the Process ID through STDIN on calling
pid = sys.argv[1]
shmem = ShMemMonitorProcess(pid)
Then just calling this with the PID of what process is the "Parent" to what group you are looking to find RSS totals for.
python ./Find_RSS.py 1234
Found Child Process 12541!
22:54:40 [12/222]
['Privileged Cont\n']
Adding Process to Hash...
Bytes....202661888
Found Child Process 12606!
['WebExtensions\n']
Adding Process to Hash...
Bytes....667672576
Found Child Process 12666!
['Utility Process\n']
Adding Process to Hash...
Bytes....709660672
Found Child Process 14803!
['RDD Process\n'] |
{"Voters":[{"Id":920069,"DisplayName":"Retired Ninja"},{"Id":207421,"DisplayName":"user207421"},{"Id":12002570,"DisplayName":"user12002570"}],"SiteSpecificCloseReasonIds":[13]} |
I am developing a custom DatePicker using the moment.js library in React. However, I have noticed that the value of my TextField is not updated when I select a new hour and minute in the DatePicker.
```
import clsx from "clsx";
import moment from "moment";
import React, { useCallback, useMemo } from "react";
import { WiTime3 } from "react-icons/wi";
import { Popover, PopoverContent, PopoverTrigger, Timer } from "../../atoms";
import { TextField } from "../../forms";
import { timeFormat } from "../../util/time-helpers";
export interface TimePickerFieldProps {
id: string;
name: string;
label?: string;
className?: string;
value?: moment.Moment;
onChange: (time: moment.Moment) => void;
onBlur?: () => void;
error?: string;
disabled?: boolean;
align?: "start" | "center" | "end";
}
export const TimePickerField = React.forwardRef<
HTMLInputElement,
TimePickerFieldProps
>(
(
{
id,
name,
onChange,
align,
className,
disabled,
error,
label,
onBlur,
value,
},
ref
) => {
const formattedValue = useMemo(
() => (value ? timeFormat(value) : ""),
[value]
);
const handleSelectTime = useCallback(
(time?: moment.Moment) => {
if (time) {
onChange(time);
}
},
[onChange]
);
const handleOpenChange = useCallback(
(open: boolean) => {
if (!open) {
onBlur?.();
}
},
[onBlur]
);
return (
<Popover onOpenChange={handleOpenChange}>
<PopoverTrigger className="block w-full">
<TextField
id={id}
name={name}
label={label}
autoComplete="off"
error={error}
disabled={disabled}
ref={ref}
readOnly
suffix={<WiTime3 className="text-primary" />}
className={clsx("pointer-events-none", className)}
value={formattedValue}
/>
</PopoverTrigger>
<PopoverContent align={align}>
<Timer selected={value} onSelect={handleSelectTime} />
</PopoverContent>
</Popover>
);
}
);
```
```
import moment from "moment";
import { useState } from "react";
import { HourBar } from "./HourBar/HourBar";
import { MinuteBar } from "./MinuteBar/MinuteBar";
export interface TimerProps {
selected?: moment.Moment | undefined;
onSelect?: (time: moment.Moment) => void;
}
export const Timer: React.FC<TimerProps> = ({ onSelect, selected }) => {
const [selectedTime, setSelectedTime] = useState<moment.Moment>(moment());
const handleTimeChange = (field: "hour" | "minute", value: number) => {
setSelectedTime((prevTime) => prevTime.clone().set(field, value));
};
return (
<div>
<div className="flex flex-row h-[7.75rem] w-[6.5rem] bg-other-transparent-darkest rounded p-2 gap-2">
<HourBar
selectedHour={selectedTime.hour()}
onHourChange={handleTimeChange}
/>
<MinuteBar
selectedMinute={selectedTime.minute()}
onMinuteChange={handleTimeChange}
/>
</div>
</div>
);
};
```
```
import { Caption } from "../../../typography";
export interface HourBarProps {
selectedHour: number;
onHourChange: (field: "hour" | "minute", value: number) => void;
}
export const HourBar: React.FC<HourBarProps> = ({
selectedHour,
onHourChange,
}) => {
const hours = Array.from({ length: 24 }, (_, i) => i);
return (
<div className="flex flex-col overflow-y-auto scrollbar-hide w-full items-center gap-1">
{hours.map((hour, index) => (
<Caption
key={index}
className={`flex justify-center rounded py-[0.125rem] size-full text-sm cursor-pointer
${hour === selectedHour && "bg-primary text-font-primary"}`}
onClick={() => onHourChange("hour", hour)}
>
{hour}
</Caption>
))}
</div>
);
};
```
```
import { Caption } from "../../../typography";
export interface HourBarProps {
selectedMinute: number;
onMinuteChange: (field: "hour" | "minute", value: number) => void;
}
export const MinuteBar: React.FC<HourBarProps> = ({
selectedMinute,
onMinuteChange,
}) => {
const minutes = Array.from({ length: 60 }, (_, i) => i);
const filteredMinutes = minutes.filter((minute) => minute % 15 === 0);
return (
<div className="flex flex-col overflow-y-auto scrollbar-hide w-full items-center gap-1">
{filteredMinutes.map((minute, index) => (
<Caption
key={index}
className={`flex justify-center rounded py-[0.125rem] size-full text-sm cursor-pointer
${minute === selectedMinute && "bg-primary text-font-primary"}`}
onClick={() => onMinuteChange("minute", minute)}
>
{minute}
</Caption>
))}
</div>
);
};
```
**Consultation:
**
What could be causing the TextField value to not update correctly when selecting a new hour and minute in the DatePicker? Are there any additional steps I need to take to ensure the value is updated correctly in the UI?
Any suggestions or help would be greatly appreciated! Thank you very much in advance.
When I select a new hour and minutes the value of the TextField is not updating |
DateTimePicker not working, textField not updating with selected hours and minutes |
|javascript|reactjs|next.js|timer|momentjs| |
null |
I'm writing a landing page to handle redirects from AWS Marketplace, show a signup form, and if the user signs up associate a marketplace customer ID as a custom attribute in Cognito.
My app uses the amplify `<Authenticator>` component to render a sign-up/login form, but it doesn't have an obvious prop where I can either set additional user fields for Cognito or hook into a signup/login event or provide clientContext data to be passed into Cognito's post-confirmation lambda hook.
How do I set additional data on the user? |
You can use the `delete_after` parameter which specifies after how much seconds the message will be deleted after sending.
```py
await ctx.send("Loading...", delete_after=3) #deleting after 3 seconds
``` |
It is confusing how opencv works in python. I understand that `cv2.imread()` assumes that the image is in BGR. However, when i convert the image from BGR to RGB using `cv2.cvtColor(image, cv2.COLOR_BGR2RGB)`, and the try to save the image and then read it using `PIL`, the colors are inverted.
**Context:** I am building a ROS pipeline where I have to use opencv ROS bridge to get images as rostopics and then transform the images using PIL.
Please refer to the following code and output image:
```import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image as im
image1 = cv2.imread('/home/ali/Pictures/rgb.png' )
image2 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
cv2.imwrite('/home/ali/Pictures/test_img_bgr_cv.png', image2)
image3 = im.open('/home/ali/Pictures/test_img_bgr_cv.png')
plt.figure(figsize=(10, 10))
plt.subplot(1, 3, 1), plt.imshow(image1)
plt.title('Image 1'), plt.xticks(\[\]), plt.yticks(\[\])
plt.subplot(1, 3, 2), plt.imshow(image2)
plt.title('Image 2'), plt.xticks(\[\]), plt.yticks(\[\])
plt.subplot(1,3,3), plt.imshow(image3)
plt.title('Image 3'), plt.xticks(\[\]), plt.yticks(\[\])
plt.show()
```
[output image](https://i.stack.imgur.com/6xX8k.png) |
Python cv2 imwrite() - RGB or BGR |
|python-3.x|opencv|python-imaging-library|ros|robotics| |
null |
I'm pretty new to Blazor myself, but this was one of the first questions that occurred to me and I think I have a better solution.
The `IServiceProvider` automagically knows how to provide the [`IHostApplicationLifetime`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.ihostapplicationlifetime). This exposes a `CancellationToken` representing graceful server shutdown. Inject the application lifetime into your component base and use [`CreateLinkedTokenSource`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.createlinkedtokensource) to create a CTS that you can cancel when the component is disposed:
```C#
public abstract class AsyncComponentBase : ComponentBase, IDisposable
{
[Inject]
private IHostApplicationLifetime? Lifetime { get; set; }
private CancellationTokenSource? _cts;
protected CancellationToken Cancel => _cts?.Token ?? CancellationToken.None;
protected override void OnInitialized()
{
_cts = Lifetime != null ? CancellationTokenSource.CreateLinkedTokenSource(Lifetime.ApplicationStopping) : new();
}
public void Dispose()
{
GC.SuppressFinalize(this);
if(_cts != null)
{
_cts.Cancel();
_cts.Dispose();
_cts = null;
}
}
}
``` |
|c++|cuda|thrust| |
null |
I'm trying to run two PSQL scripts inside a docker container, the idea is that I want to use docker healthcheck feature to wait for the database to be ready to run the scripts, the first on creates a custom DB and the second is run on that custom DB
**What could be causing that the first script is run (database is created) but no the second ?**
Here is the pg-server.Dockerfile
```
# Use official PostgreSQL image
FROM postgres:latest
# Copy the initialization scripts into the container
COPY ./00_init-database.sql /docker-entrypoint-initdb.d/
COPY ./01_create-tables.sql /docker-entrypoint-initdb.d/
```
The docker-compose file has this
```
services:
postgres:
build:
context: ./database
dockerfile: pg-server.Dockerfile
ports:
- "5432:5432"
volumes:
- ./database/pg_data:/docker-entrypoint-initdb.d/
environment:
POSTGRES_DB: cloud_parking_db
POSTGRES_USER: someUser
POSTGRES_PASSWORD: somePassword
INIT_DB: "true"
healthcheck:
test:
[
"CMD",
"pg_isready",
"-q",
"-d",
"cloud_parking_db",
"-U",
"someUser"
]
interval: 10s
timeout: 5s
retries: 5
networks:
- cp_network
```
When I docker-compose build and up, the database is getting created but the tables are not created
Here is the log for postgress container
```
2024-03-31 15:49:14 The files belonging to this database system will be owned by user "postgres".
2024-03-31 15:49:14 This user must also own the server process.
2024-03-31 15:49:14
2024-03-31 15:49:14 The database cluster will be initialized with locale "en_US.utf8".
2024-03-31 15:49:14 The default database encoding has accordingly been set to "UTF8".
2024-03-31 15:49:14 The default text search configuration will be set to "english".
2024-03-31 15:49:14
2024-03-31 15:49:14 Data page checksums are disabled.
2024-03-31 15:49:14
2024-03-31 15:49:14 fixing permissions on existing directory /var/lib/postgresql/data ... ok
2024-03-31 15:49:14 creating subdirectories ... ok
2024-03-31 15:49:14 selecting dynamic shared memory implementation ... posix
2024-03-31 15:49:14 selecting default max_connections ... 100
2024-03-31 15:49:14 selecting default shared_buffers ... 128MB
2024-03-31 15:49:14 selecting default time zone ... Etc/UTC
2024-03-31 15:49:14 creating configuration files ... ok
2024-03-31 15:49:14 running bootstrap script ... ok
2024-03-31 15:49:14 performing post-bootstrap initialization ... ok
2024-03-31 15:49:15 syncing data to disk ... ok
2024-03-31 15:49:15
2024-03-31 15:49:15
2024-03-31 15:49:15 Success. You can now start the database server using:
2024-03-31 15:49:15
2024-03-31 15:49:15 pg_ctl -D /var/lib/postgresql/data -l logfile start
2024-03-31 15:49:15
2024-03-31 15:49:15 waiting for server to start....2024-03-31 20:49:15.075 UTC [48] LOG: starting PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
2024-03-31 15:49:15 2024-03-31 20:49:15.078 UTC [48] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2024-03-31 15:49:15 2024-03-31 20:49:15.087 UTC [51] LOG: database system was shut down at 2024-03-31 20:49:14 UTC
2024-03-31 15:49:15 2024-03-31 20:49:15.094 UTC [48] LOG: database system is ready to accept connections
2024-03-31 15:49:15 done
2024-03-31 15:49:15 server started
2024-03-31 15:49:15 CREATE DATABASE
2024-03-31 15:49:15
2024-03-31 15:49:15
2024-03-31 15:49:15 /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
2024-03-31 15:49:15
2024-03-31 15:49:15 waiting for server to shut down...2024-03-31 20:49:15.300 UTC [48] LOG: received fast shutdown request
2024-03-31 15:49:15 .2024-03-31 20:49:15.302 UTC [48] LOG: aborting any active transactions
2024-03-31 15:49:15 2024-03-31 20:49:15.304 UTC [48] LOG: background worker "logical replication launcher" (PID 54) exited with exit code 1
2024-03-31 15:49:15 2024-03-31 20:49:15.304 UTC [49] LOG: shutting down
2024-03-31 15:49:15 2024-03-31 20:49:15.307 UTC [49] LOG: checkpoint starting: shutdown immediate
2024-03-31 15:49:15 2024-03-31 20:49:15.399 UTC [49] LOG: checkpoint complete: wrote 923 buffers (5.6%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0.020 s, sync=0.064 s, total=0.095 s; sync files=301, longest=0.004 s, average=0.001 s; distance=4257 kB, estimate=4257 kB; lsn=0/1913078, redo lsn=0/1913078
2024-03-31 15:49:15 2024-03-31 20:49:15.405 UTC [48] LOG: database system is shut down
2024-03-31 15:49:15 done
2024-03-31 15:49:15 server stopped
2024-03-31 15:49:15
2024-03-31 15:49:15 PostgreSQL init process complete; ready for start up.
2024-03-31 15:49:15
2024-03-31 15:49:15 initdb: warning: enabling "trust" authentication for local connections
2024-03-31 15:49:15 initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.
2024-03-31 15:49:15 2024-03-31 20:49:15.537 UTC [1] LOG: starting PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
2024-03-31 15:49:15 2024-03-31 20:49:15.538 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
2024-03-31 15:49:15 2024-03-31 20:49:15.538 UTC [1] LOG: listening on IPv6 address "::", port 5432
2024-03-31 15:49:15 2024-03-31 20:49:15.543 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2024-03-31 15:49:15 2024-03-31 20:49:15.550 UTC [64] LOG: database system was shut down at 2024-03-31 20:49:15 UTC
2024-03-31 15:49:15 2024-03-31 20:49:15.560 UTC [1] LOG: database system is ready to accept connections
2024-03-31 15:54:15 2024-03-31 20:54:15.550 UTC [62] LOG: checkpoint starting: time
2024-03-31 15:54:19 2024-03-31 20:54:19.911 UTC [62] LOG: checkpoint complete: wrote 46 buffers (0.3%); 0 WAL file(s) added, 0 removed, 0 recycled; write=4.324 s, sync=0.018 s, total=4.361 s; sync files=13, longest=0.008 s, average=0.002 s; distance=261 kB, estimate=261 kB; lsn=0/19544E8, redo lsn=0/19544B0
```
The database script `00_init-database.sql`
``` psql
DO $$
BEGIN
IF current_setting('INIT_DB') = 'true' THEN
-- Drop the database if it already exists
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = 'cloud_parking_db') THEN
DROP DATABASE cloud_parking_db;
END IF;
CREATE DATABASE cloud_parking_db;
END IF;
END $$;
```
and `01_create-tables.sql` has this
``` psql
DO $$
BEGIN
IF current_setting('INIT_DB') = 'true' THEN
BEGIN;
-- Create the ParkingUser table
CREATE TABLE ParkingUser (
UserId SERIAL PRIMARY KEY,
Username VARCHAR(50) NOT NULL,
Email VARCHAR(100) NOT NULL,
Password VARCHAR(255) NOT NULL,
Role VARCHAR(20) NOT NULL
);
-- Create the Country table
CREATE TABLE Country (
CountryId SERIAL PRIMARY KEY,
Name VARCHAR(100) NOT NULL
);
-- more tables
COMMIT ;
END IF;
END $$;
``` |
Only the first SQL script gets executed inside Docker Postgres container |
|postgresql|docker|docker-compose| |
You can use [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to make a counter lookup table based on the `id` key, then use [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to remove any items that appeared only once in the lookup table. Time complexity is O(n).
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const lookup = values.reduce((a, e) => {
a[e.id] = ++a[e.id] || 0;
return a;
}, {});
console.log(values.filter(e => lookup[e.id]));
<!-- end snippet -->
You can simplify this if your browser supports `Object.groupBy`:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const lookup = Object.groupBy(values, e => e.id);
console.log(values.filter(e => lookup[e.id].length > 1));
<!-- end snippet --> |
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):
[CubeMX][1][CubeMX][2][schematic][3][schematic][4][schematic][5]
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/z3BUu.png
[2]: https://i.stack.imgur.com/U2BsI.png
[3]: https://i.stack.imgur.com/W0FWx.png
[4]: https://i.stack.imgur.com/ALsCK.png
[5]: https://i.stack.imgur.com/KuwsE.png |
I have this program:
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
for (i=0; i < argc;i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
I am wondering about the argument `char *argv[]`. My first thought was that this was an **array of character pointers**? But then it should compile if we write: `(char *argv)[]`? But then I get the error meassage
testargs.c:3:20: error: expected declaration specifiers or '...' before '(' token
3 | int main(int argc, (char *argv)[]) {
However it will compile and run correctly if I have `char *(argv[])`. But what is this actually in terms of pointers and arrays? Is it a character pointer to an array, or what is it? |
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):
[CubeMX][1] [CubeMX][2] [schematic][3] [schematic][4]
[schematic][5]
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/z3BUu.png
[2]: https://i.stack.imgur.com/U2BsI.png
[3]: https://i.stack.imgur.com/W0FWx.png
[4]: https://i.stack.imgur.com/ALsCK.png
[5]: https://i.stack.imgur.com/KuwsE.png |
I am trying to build this **Dockerfile** for **Go Application** and then deploy this to **GKE** but I'm seen this error upon pod creation. Upon describing this pod, I observed the same error.:
> Error: failed to create containerd task: failed to create shim task:
> OCI runtime create failed: runc create failed: unable to start
> container process: exec: "./bin": stat ./bin: no such file or
> directory: unknown
This image successfully run locally using this command.
```docker run -it --rm bytecode01/domainalert:v2```
#Dockerfile
FROM golang:alpine as builder
WORKDIR /data
COPY go.mod go.mod
RUN go mod download
# Copy the go source
COPY . .
# Build
RUN go build -a -o bin main.go
FROM alpine:latest
WORKDIR /data
COPY --from=builder /data/bin .
RUN chmod +x bin
CMD ["./bin"]
GKE *PVC successfully mounted*
```
#pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: de
labels:
name: de
spec:
containers:
- name: de-pod
image: bytecode01/domainalert:v2
imagePullPolicy: Always
volumeMounts:
- mountPath: /data
name: app-volume
volumes:
- name: app-volume
persistentVolumeClaim:
claimName: pvc-dynamic
```
```
#pvc-dynamic.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-dynamic
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Mi
storageClassName: standard
```
**Help to get my issue solved.** |
```
self.MapView.isMyLocationEnabled = true
```
gives the following error - how do i fix it ?
import GoogleMaps
class ViewController: UIViewController,CLLocationManagerDelegate {
//Outlets
@IBOutlet var MapView: GMSMapView!
//Variables
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
initializeTheLocationManager()
self.MapView.isMyLocationEnabled = true
}
func initializeTheLocationManager() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var location = locationManager.location?.coordinate
cameraMoveToLocation(toLocation: location)
}
func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) {
if toLocation != nil {
MapView.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15)
}
}
}
(https://i.stack.imgur.com/XdqUF.png)
(https://i.stack.imgur.com/4y2FI.png)
This is what the story board looks like. I am new to swift and want to see my current location on google maps via swift. What should i do differently |
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value - MapView.isMyLocationEnabled |
|swift| |
null |