Itunes tuneup int code

House sitting: Care for homes and pets in exchange for free world travel accommodation

2015.06.15 08:38 vanessaanderson62 House sitting: Care for homes and pets in exchange for free world travel accommodation

/housesittingforum is a community for house sitters, home owners, nomads and travelers who want to share their experiences, advice and resources. If you're a short or long term traveler, global nomad or are just new to the concept of house sitting, then we'd love to hear from you. All questions will be answered.
[link]


2024.05.14 14:47 ZealousidealBoat4724 Programming AI voice assistant for school project

im coming here to ask for help, ive been searching around for some time now and im coming to a dead spot, ive tried many youtube videos for help but they are all so different ( due to being years ago ) ive also tried asking chatgpt and copilot. no help. Im doing my major project for design and tech in school and need help im very new to programming on python, so if anyone could help that would be great. Ive got a program which already works and you can talk to it and it will talk back. but i want to add functions to it such as: it being able to google search for me, open apps on my computer. this is my code:
import os
from os import PathLike
from time import time
import asyncio
from typing import Union
from dotenv import load_dotenv
import openai
from deepgram import Deepgram
import pygame
from pygame import mixer
import elevenlabs
from record import speech_to_text
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
DEEPGRAM_API_KEY = os.getenv("DEEPGRAM_API_KEY")
elevenlabs.set_api_key(os.getenv("ELEVENLABS_API_KEY"))
gpt_client = openai.Client(api_key=OPENAI_API_KEY)
deepgram = Deepgram(DEEPGRAM_API_KEY)

mixer is a pygame module for playing audio

mixer.init()
context = "You are Cypher, Bear's human assistant. You are witty and full of personality. Your answers should be limited to 1-4 short sentences."
conversation = {"Conversation": []}
RECORDING_PATH = "audio/recording.wav"
def request_gpt(prompt: str) -> str:
"""
Send a prompt to the GPT-3 API and return the response.
Args:
Returns:
The response from the API.
"""
response = gpt_client.chat.completions.create(
messages=[
{
"role": "user",
"content": f"{prompt}",
}
],
model="gpt-3.5-turbo",
)
return response.choices[0].message.content
async def transcribe(
file_name: Union[Union[str, bytes, PathLike[str], PathLike[bytes]], int]
):
"""
Transcribe audio using Deepgram API.
Args:
Returns:
The response from the API.
"""
with open(file_name, "rb") as audio:
source = {"buffer": audio, "mimetype": "audio/wav"}
response = await deepgram.transcription.prerecorded(source)
return response["results"]["channels"][0]["alternatives"][0]["words"]
def log(log: str):
"""
Print and write to status.txt
"""
print(log)
with open("status.txt", "w") as f:
f.write(log)
if __name__ == "__main__":
while True:

Record audio

log("Listening...")
speech_to_text()
log("Done listening")

Transcribe audio

current_time = time()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
words = loop.run_until_complete(transcribe(RECORDING_PATH))
string_words = " ".join(
word_dict.get("word") for word_dict in words if "word" in word_dict
)
with open("conv.txt", "a") as f:
f.write(f"{string_words}\n")
transcription_time = time() - current_time
log(f"Finished transcribing in {transcription_time:.2f} seconds.")

Get response from GPT-3

current_time = time()
context += f"\nAlex: {string_words}\nJarvis: "
response = request_gpt(context)
context += response
gpt_time = time() - current_time
log(f"Finished generating response in {gpt_time:.2f} seconds.")

Convert response to audio

current_time = time()
audio = elevenlabs.generate(
text=response, voice="Adam", model="eleven_monolingual_v1"
)
elevenlabs.save(audio, "audio/response.wav")
audio_time = time() - current_time
log(f"Finished generating audio in {audio_time:.2f} seconds.")

Play response

log("Speaking...")
sound = mixer.Sound("audio/response.wav")

Add response as a new line to conv.txt

with open("conv.txt", "a") as f:
f.write(f"{response}\n")
sound.play()
pygame.time.wait(int(sound.get_length() * 1000))
print(f"\n --- USER: {string_words}\n --- JARVIS: {response}\n")
if anyone can help please do!!!!!!!!!
submitted by ZealousidealBoat4724 to pythonhelp [link] [comments]


2024.05.14 14:05 Benjifors Need Help on Arduino R4 Project!

Hello!
I'm currently working on a project with an uno R4 and It's not working. It's currently connected to 2 motors and I'm trying to make the code work so that i can control it through a dashboard and Arduino IOT. The code is suppose to make the motors go forward or backwards with a controllable speed through sliders with a value between 0 and 255 (each motor has a slider) and a switch to control a boolean which determines if it goes forward or backwards.
Can you PLEASE tell me what's wrong with the code?
/*
Sketch generated by the Arduino IoT Cloud Thing "Untitled"
https://create.arduino.cc/cloud/things/b7ca2cfc-cbdf-4571-a46a-96bf47f95d4e
Arduino IoT Cloud Variables description
The following variables are automatically generated and updated when changes are made to the Thing
int motor_left;
int motor_right;
bool motor_direction;
Variables which are marked as READ/WRITE in the Cloud Thing will also have functions
which are called when their values are changed from the Dashboard.
These functions are generated with the Thing and added at the end of this sketch.
*/

include "thingProperties.h"

void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
ArduinoCloud.update();
// Your code here
}
/*
Since MotorLeft is READ_WRITE variable, onMotorLeftChange() is
executed every time a new value is received from IoT Cloud.
*/
void onMotorLeftChange() {
// Add your code here to act upon MotorLeft change
analogWrite(6, motor_left);
/*digitalWrite(6, motor_left);*/
}
/*
Since MotorRight is READ_WRITE variable, onMotorRightChange() is
executed every time a new value is received from IoT Cloud.
*/
void onMotorRightChange() {
// Add your code here to act upon MotorRight change
analogWrite(9, motor_right);
/*digitalWrite(9, motor_right);*/
}
/*
Since MotorDirection is READ_WRITE variable, onMotorDirectionChange() is
executed every time a new value is received from IoT Cloud.
*/
void onMotorDirectionChange() {
// Add your code here to act upon MotorDirection change
if (motor_direction == true)
analogWrite(7, HIGH);
analogWrite(8, LOW);
if (motor_direction == false)
analogWrite(7, LOW);
analogWrite(8, HIGH);
/*if(motor_direction == true)
digitalWrite(7,HIGH);
digitalWrite(8,LOW);
if(motor_direction == false)
digitalWrite(7,LOW);
digitalWrite(8,HIGH);*/
}
submitted by Benjifors to arduino [link] [comments]


2024.05.14 14:00 Kajle_kajla How to arrange printed symbols in a custom amount of blank space

Not sure if i expressed my desire appropriately, but i want my matrices values to print out in the same number of placeholding blank spaces, if this makes any sense...
'''

include

define MAX 100

int main() { int a[MAX][MAX],b,i,j,m,n;
printf("Vrsta m: "); scanf("%d",&m); printf("Kolona n: "); scanf("%d",&n); printf("Unesi elemente matrice: /n"); for(i=0;i }
'''
This is my code, and the output looks like this....
'''
Vrsta m: 2 Kolona n: 2 Unesi elemente matrice: /nelement[0][0]: 12345 element[0][1]: 12345 element[1][0]: 123456 element[1][1]: 123456 12345 12345 123456 123456
[Program finished]
'''
I want my numbers i am printing out, to have custom number of space that they go into...For example i want both the 12345 and 123456 numbers to have 10 blank spaces they can go into, if that makes any sense.
submitted by Kajle_kajla to C_Programming [link] [comments]


2024.05.14 13:21 vacillatingfox Do my dependencies go the wrong way in OOP composition?

Hi! First time posting here after being a reader for a while. Sadly ChatGPT and Copilot were not very helpful, so I'd appreciate any insights. Since I'm by no means an expert in Python, OOP, or design patterns, and this feels like a general conceptual issue rather than specific to my task, I thought I'd ask in a beginner's forum first.
I have written a Python package and am pretty happy with it. It works well and as intended, and I think it's really not bad considering my level of experience.
However, even though it all works, I'm not too happy about the structure of the code, as it goes against what my instinct says would be the right way to do things.
The package is very much written with OOP, and specifically tries to make use of composition as it makes absolute sense for the task. Given the requirements of the project, however, it was a challenge to make it work without circular imports, and in the result it feels to me like the dependencies go the wrong way.
A fairly minimal code example is below. The methods are silly examples that aren't the real ones, they just demonstrate what I need the classes to do.
Essentially, I have a main class `C` that should be composed of `C.a` and `C.b`, where `a` is a numeric type and `b` is an instance of `B`. Each instance of `B` that is created gets registered in an instance of `Container`.
"""c.py""" from container import container # Can't import `B` as that would be circular import and gives problems class C: """An object possessing a number and a B.""" # `b` must be an instance of `B` but can't give as type hint def __init__(self, a: int float, b): self.a = a self.b = b # `b` will always be an instance of `B` def __repr__(self): return (f"C({self.a}, {self.b})") def __str__(self): return f"{self.a}*{self.b}" def __mul__(self, other): # Can't import `B` so have to check if `other` is a `B` by duck-typing # Could implement behaviour of `C * B` in `B.__rmul__()` but doesn't # really solve the overarching problem if hasattr(other, "name") and hasattr(other, "as_C"): return C(self.a, self.b * other) else: return NotImplemented def __rmul__(self, other): if isinstance(other, (int, float)): new_a = other * self.a return C(new_a, self.b) def question(self): # Return a new `C` where its `b` has an added question mark # Since `self.b.question()` returns a `C` not a new `B`, # can't just do `C(self.a, self.b.question())` return self.a * self.b.question() def from_string(self, string): """Parse a string into an `a` and a `b` and return a new `C`.""" split_string = string.split() a = float(split_string[0]) possible_matches = container.find(split_string[1]) b = possible_matches[0] return C(a, b)c.py ################################## """b.py""" from c import C from container import container # Feels like both of the above should depend on `B`, not the other way round class B: """One of the key constituent elements of a `C`.""" def __init__(self, name: str): self.name = name container.add(name[:3], self) def __repr__(self): return (f"B('{self.name}')") def __str__(self): return def __mul__(self, other): if isinstance(other, B): new_name = self.name + "x" + other.name return B(new_name) def __rmul__(self, other): if isinstance(other, (int, float)): # This is key behaviour that is absolutely required because # it is the main API for the user to create a `C` return C(other, self) else: return NotImplemented def as_C(self): """Return an instance of C that has itself.""" # Indirectly creates an instance of `C` via `self.__rmul__()` # Could equally just use `C(1, self)` but this way has advantages return 1 * self def question(self): """Add a question mark to the name, then return an instance of C.""" new_B = B(self.name + "?") return 1 * new_B ################################## """container.py""" # Can't import `B` as that would be circular import and gives problems class Container: def add(self, code: str, b): """Add a `B` to the Container under the provided three-letter code.""" # Again `b` must be an instance of `B` but can't give as type hint # Make sure all codes are unique while hasattr(self, code): code = code[:-1] + chr(ord(code[-1]) + 1) # Naturally this results in a horrible namespace but it is just to # demonstrate the point, the real implementation is more sophisticated setattr(self, code, b) def find(self, search: str): """Return list of all `B`s whose name contains the search string, in alphabetical order of their codes.""" # Uses a much more complicated method to sort but key point is that the methods # of `Container` are also dependent on the implementation of `B` matched_codes = [code for code, b in self.__dict__.items() if search in b.name] sorted_matches = sorted(matched_codes) matches = [getattr(self, code) for code in sorted_matches] return matches container = Container() 
I would have thought that for a composition approach, `c.py` should be importing `B`, partly for type hinting but mainly because `C` has methods that rely on `C.b` being a `B`.
Due to the further constraints described below, however, `b.py` is importing `C`! Am I right in feeling this is unorthodox and "wrong"?
Naturally, the duck-typing means that anything that implements the same methods as `B` could be passed to `C()`. But that just doesn't feel right.
And even though I got rid of a true circular import, `B` and `C` are still very much coupled and depend on each other. I already had a couple of bugs with endless loops due to each class referencing the other.
Or am I overthinking and actually this is all normal and ok?
submitted by vacillatingfox to learnpython [link] [comments]


2024.05.14 13:03 myuser01 A JS function to verify Irish PPSNs?

This is driving me batty, guys. I need some help. I have a non-working function to verify Irish PPSNs. It's a simple checksum used by many site-owners online to pre-check official submissions to State bodies from their users so users don't submit fake PPSNs.
This one isn't working for me. Part of the problem is I only have one PPSN to test it with. Mine has a single character at the end, others have two characters.
A little help would be great?
function isValidIrishPPSNumber(ppsNumber) {
// Remove all spaces from the input
ppsNumber = ppsNumber.replace(/\s/g, '');
// Check if PPS number is in the correct format
var ppsRegex = /^[0-9]{7}[A-Za-z]{1,2}$/;
if (!ppsRegex.test(ppsNumber)) {
return false;
}
// Extract the numeric part and the check character(s)
var numericPart = ppsNumber.substring(0, 7);
var checkCharacter = ppsNumber.substring(7);
// Calculate the check character(s) based on the numeric part
var total = 0;
for (var i = 0; i < numericPart.length; i++) {
total += parseInt(numericPart.charAt(i)) * (8 - i);
}
// If there are two check characters, validate both
if (checkCharacter.length === 2) {
var secondTotal = total;
for (var j = 0; j < numericPart.length; j++) {
secondTotal += parseInt(numericPart.charAt(j)) * (9 - j);
}
var firstCheckCharacter = String.fromCharCode(64 + (total % 23) + 1); // Convert to ASCII
var secondCheckCharacter = String.fromCharCode(64 + (secondTotal % 23) + 1); // Convert to ASCII
return checkCharacter.charAt(0).toUpperCase() === firstCheckCharacter && checkCharacter.charAt(1).toUpperCase() === secondCheckCharacter;
}
// Calculate the check character based on the numeric part
var checkChar = String.fromCharCode(64 + (total % 23) + 1); // Convert to ASCII
// Check if the calculated check character matches the input check character
return checkChar === checkCharacter.toUpperCase();
}
// Example usage:
var ppsInput = document.getElementById('pps-number').value;
var isValid = isValidIrishPPSNumber(ppsInput);
console.log(isValid); // Output true or false based on the validation result
submitted by myuser01 to DevelEire [link] [comments]


2024.05.14 12:29 BasePlate_Admin modern_colorthief - Modified Median Cut Quantization algorithm in rust + python

What my project does :

It gets the dominant colocolor palette from given image.

Target Audience:

Anyone

Usage

modern_colorthief exposes two functions get_color and get_palette
Here is how to use get_color:
```python from modern_colorthief import get_color

Path to any image

path = ...
print(get_color(path)) # returns tuple[int,int,int] ```
Here is how to use get_palette:
```python from modern_colorthief import get_color

Path to any image

path = ...
print(get_palette(path)) # returns list[tuple[int,int,int]] ```

Goals:

Benchmarks:

Written in deatils
Gist:
```python Python Took: 0.09976800000004005 CPP Took: 0.008461299999908078 RUST Took: 0.008549499994842336
Python Took: 0.0960583999985829 CPP Took: 0.008564600000681821 RUST Took: 0.007692700004554354 ```

Differences

With fast-colorthief

With color-thief-py

If you like this project please star this repository
submitted by BasePlate_Admin to Python [link] [comments]


2024.05.14 12:26 Ibishek No clock enables for URAM pipeline registers?

Hi,
I'm trying to infer a URAM cascade memory from my code, which should be simple dual port, have clock enable (needs to support backpressure) and have output register pipeline to reduce the critical path. I've taken the Xilinx code templates for simple dual port URAM (which do not have a clock enable) and added the clock enable but synthesis reports that no pipeline registers can be absorbed. If I remove the clock enable, the pipeline registers are absorbed without an issue.
At first I thought that maybe the clock enables are not a supported feature but Xilinx documentation mentions ports OREG_CE_B/A as ' output pipeline register CLK enable' so that gave me some hope.
Anyways, I was not able to find any resources describing how to write the code so that the desired URAM is inferred, does anyone know how to do this? Code for my URAM is as follows:
//Port declarations etc.
(\ ram_style = "ultra" *)* logic [DATA_IN_WDT-1:0] mem[ (1< logic [DATA_IN_WDT-1:0] memreg; logic [DATA_IN_WDT-1:0] mem_pipe_stage[PIPE_OUT_CNT-1:0]; logic en_pipe_reg[PIPE_OUT_CNT:0]; always_ff @(posedge clk) begin : uram_mem_proc //write first if(rd_en & clk_en) begin if(wr_en) mem[wr_addr] <= data_in; memreg <= mem[rd_addr]; end end //pipelined enable signal always_ff @ (posedge clk) begin : en_pipe_reg_proc if(clk_en) begin en_pipe_reg[0] <= rd_en & clk_en; for (int i = 0; i < PIPE_OUT_CNT; i++) en_pipe_reg[i+1] <= en_pipe_reg[i]; end end //initial RAM output register always_ff @ (posedge clk) begin: init_mem_pipe_stage_proc if (en_pipe_reg[0]) mem_pipe_stage [0] <= memreg; end //RAM output pipeline always_ff @ (posedge clk) begin : mem_pipe_stage_proc for (int i = 0; i < PIPE_OUT_CNT-1; i++) if (en_pipe_reg[i+1]) mem_pipe_stage[i+1] <= mem_pipe_stage[i]; end //final output register always_ff @ (posedge clk) begin : fin_mem_pipe_stage_proc if(!rst_n) begin data_out <= '0; end if(clk_en) begin if(en_pipe_reg[PIPE_OUT_CNT]) data_out <= mem_pipe_stage[PIPE_OUT_CNT-1]; end end
So basically the clock enable is on the enable register pipeline and on the final register output. I've also tried adding it to the data register pipeline but it did not work either.
I guess directly inserting the URAM primitive is also an option but I'd like to make this inference template work.
Thanks!
submitted by Ibishek to FPGA [link] [comments]


2024.05.14 12:08 HairrryStyles Spoiler!!! Path with Maximum Gold - Why i am getting a TLE??

class Solution { public: int backtrack(int i,int j,vector>& grid){ int m=grid.size(); int n=grid[0].size(); if(i<0 i>=m j<0 j>=n grid[i][j]==0){ return 0; } int curr=grid[i][j]; grid[i][j]=0; int localGold=0; vector> dir{{-1,0},{1,0},{0,-1},{0,1}}; for(auto x: dir){ int newI=i+x[0]; int newJ=j+x[1]; localGold=max(localGold,backtrack(newI,newJ,grid)); } grid[i][j]=curr; return localGold+curr; } int getMaximumGold(vector>& grid) { int m=grid.size(); int n=grid[0].size(); int maxGold=0; for(int i=0;i The code seems to be working fine?
submitted by HairrryStyles to leetcode [link] [comments]


2024.05.14 10:42 Ok_Share_6448 Stuck on HelloWorld.cpp

Need help with HelloWorld.
I keep getting different errors that have to do with the .json file. I changed every instance of "hello" to "howdy", but that's the only personalization I made, which I doubt caused the error. I'm very new to this so any help would be greatly appreciated.
Code for HowdyWorld.cpp :
#include  int main(){ printf ("Howdy world"); return 0; } 
Pop-up error:
launch: program '' does not exist.
Debug console after running:
-------------------------------------------------------------------
You may only use the C/C++ Extension for Visual Studio Code
with Visual Studio Code, Visual Studio or Visual Studio for Mac
software to help you develop and test your applications.
-------------------------------------------------------------------
My launch.json file:
{ "version": "0.2.0", "configurations": [ { "name": "(Windows) Launch", "type": "cppvsdbg", "request": "launch", "program": "HowdyWorld.exe", "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "console": "externalTerminal" } ] } 
My tasks.json file:
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: cl.exe build active file", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/nologo", "/Fe${fileDirname}\\${fileBasenameNoExtension}.exe", "${file}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$msCompile" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } 
My c_cpp_properties.json file:
{ "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/VC/Tools/MSVC/14.39.33519/bin/Hostx64/x64/cl.exe" } ], "version": 4 } 
submitted by Ok_Share_6448 to learnprogramming [link] [comments]


2024.05.14 10:39 RollingPandaKid Question about variable scope in Readability.

Hello, I just finished Readability for pset2 and it works fine, but I have one question.
I have 3 functions to count the number of letters, words and sentences. To count these first I need to know the length of the string and Im using int i strlen(text)
The problem is Im doing the same thing 3 times, calling strlen inside every function because I need to know the length of the string to calculate the number of letters, words and sentences.
I tried to put strlen at the beggining of the code to have access of the , but it doesnt work because I get the string after that, in the main function with get_string.
Is there a better or cleaner way to do this?
submitted by RollingPandaKid to cs50 [link] [comments]


2024.05.14 10:04 Insurgent25 Leetcode 557

So i had this question in a round to inplace reverse each word in a string, interviewer told me to use only one loop, cannot use any functions like swap, reverse, etc. Cannot use extra space.
What would be approach to this?
The best solution i found was:
string reverseWords(string str) {
int start = 0; for (int i = 0; i <= str.size(); i++){ if (str[i] == ' ' i == str.size()) { // Pointer to the last character // of the current word int end = i - 1; // Reverse the current word while (start < end) { swap(str[start], str[end]); start++; end--; } // Pointer to the first character // of the next word start = i + 1; } } return str; 
}
But it still uses 2 loops, this has a time complexity of O(n) i didn't understand that part either because if the loop is inside a loop doesnt the time complexity become O(n2)? help is appreciated.
He was pretty confident a solution exists.
Sorry for the non formatted code on mobile rn
submitted by Insurgent25 to leetcode [link] [comments]


2024.05.14 08:14 NienNine Looking for an Interactive CLI Library

Hi all,
As the title says I am looking for an Interactive CLI Library. I have looked at at bullet and prompt-toolkit however they both appear to be missing the prompt style I am looking for. I am looking for a prompt that looks like this:
Select Choice 1) Do something 1 2) Do something 2 3) Do something 3 Enter selection: 
Specifically I am looking for a library which will allow the user to select an option using both the arrow keys and by using a numeric key press, though if I had to choose one over the other I would choose the numeric way. I have looked at bullet and prompt-toolkit and while they have the option to create the menus that respond to arrow input I have yet to find an example of a combo, or numeric key press one. I guess I could use their basic take any prompt, but then I would have to write all the input validation code and loops along with having to deal with formatting the choices. I have already written my own hacked together CLI for the app but I have reason to re-write it and was hoping to do it in a much cleaner manner using a library.
Edit: to be clear I am looking for a library which will allow me to do this, but also clear the terminal buffer after each attempt so it does not clutter the terminal:
def create_list_prompt(options): # Create text string for prompt prompt_string = "Choose a selection between ({}-{}):\n".format(1, len(options)) selection_dict = {} for index, option in enumerate(options): prompt_string += "{}) {}.\n".format(index + 1, option) selection_dict[index + 1] = option valid = False emergency_exit = ['e', 'x'] result = None while not valid: result = input(prompt_string) # Strip whitespace, turn to lowercase for easier checking result = result.strip().lower() if result.isnumeric(): # only allow numeric result = int(result) if len(options) >= result >= 1: # Verify input value is within allowable range valid = True elif result in emergency_exit: # User wants to abort, return none return None # If all else fails inform user of error and try again if not valid: print("\nInvalid selection, to exit out of this prompt type 'x'") return result, selection_dict[int(result)] 
Thanks in advance!
submitted by NienNine to learnpython [link] [comments]


2024.05.14 06:43 HungryBar3834 Hey guys if im taking large amount data from a server and it makes the app so slow so what is the best way to take that data

import 'dart:convert'; import 'package:fluttematerial.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_map_marker_clusteflutter_map_marker_cluster.dart'; import 'package:latlong2/latlong.dart'; import 'dart:ui' as ui; import 'dart:typed_data'; import 'package:http/http.dart' as http;
void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MapScreen(), ); } } class MapScreen extends StatefulWidget { const MapScreen({super.key}); @override _MapScreenState createState() => _MapScreenState(); } class _MapScreenState extends State { List shops = []; late Map markerIcons; bool isLoading = false; String error = ''; @override void initState() { super.initState(); markerIcons = {}; fetchShops(); } Future fetchShops() async { setState(() { isLoading = true; error = ''; }); const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NTQsImlhdCI6MTcxMzIzMjQwOCwiZXhwIjoxNzI2MTkyNDA4fQ.hdJsGEMYRAAEs5y6RERuT2TNJTBUITkWy-7FarMc_C4"; // Replace with your actual token try { final response = await http.get( Uri.parse('https://api.carcare.mn/v1/shop'), headers: {'Authorization': 'Bearer $token'}, ); if (response.statusCode == 200) { final jsonData = json.decode(response.body)['data']; if (jsonData != null) { setState(() { shops = jsonData.map((data) => Shop.fromJson(data)).toList(); }); await loadMarkerIcons(); } else { setState(() { shops = []; }); } } else { setState(() { error = 'Failed to load shops (${response.statusCode})'; }); } } catch (e) { setState(() { error = 'Error fetching data: $e'; }); } finally { setState(() { isLoading = false; }); } } Future getMarkerIcon(String imageUrl) async { try { final response = await http.get(Uri.parse(imageUrl)); if (response.statusCode == 200) { return response.bodyBytes; } else { print('Failed to load image: ${response.statusCode}'); return null; } } catch (e) { print('Error loading image: $e'); return null; } } Future loadMarkerIcons() async { for (var shop in shops) { Uint8List? markerIcon = await getMarkerIcon(shop.thumbnail); if (markerIcon != null) { markerIcons[shop.id] = markerIcon; } else { markerIcons[shop.id] = await MarkerGenerator.defaultMarkerBytes(); } } setState(() {}); } @override Widget build(BuildContext context) { List markers = shops.map((shop) { return Marker( width: 80, height: 80, point: LatLng(shop.location.latitude, shop.location.longitude), child: Container( child: markerIcons[shop.id] != null && markerIcons[shop.id]!.isNotEmpty ? Image.memory(markerIcons[shop.id]!) : Icon(Icons.location_on, color: Colors.red), ), ); }).toList(); return Scaffold( appBar: AppBar( title: const Text('Map with Markers'), ), body: isLoading ? Center(child: CircularProgressIndicator()) : FlutterMap( options: MapOptions( initialCenter: LatLng(47.9187, 106.917), initialZoom: 10, ), children: [ TileLayer( urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', userAgentPackageName: 'com.example.app', ), MarkerClusterLayerWidget(options: MarkerClusterLayerOptions( markers: markers, builder: (context, markers) { return Container( width: 80, height: 80, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.blue, ), child: Center( child: Text( markers.length.toString(), style: TextStyle(color: Colors.white), ), ), ); }, ), ) ], ), ); } } class Shop { final int id; final String name; final String description; final String phone; final String type; final List additional; final String thumbnail; final List bannerImages; final List branches; final List schedules; final Location location; final List services; Shop({ required this.id, required this.name, required this.description, required this.phone, required this.type, required this.additional, required this.thumbnail, required this.bannerImages, required this.branches, required this.schedules, required this.location, required this.services, }); factory Shop.fromJson(Map? json) { return Shop( id: json?['id'] ?? 0, name: json?['name'] ?? '', description: json?['description'] ?? '', phone: json?['phone'] ?? '', type: json?['type'] ?? '', additional: List.from(json?['additional'] ?? []), thumbnail: json?['thumbnail'] ?? '', bannerImages: (json?['bannerImages'] as List?) ?.map((bannerImage) => BannerImage.fromJson(bannerImage)) .toList() ?? [], branches: List.from(json?['branches'] ?? []), schedules: List.from(json?['schedules'] ?? []), location: Location.fromJson(json?['location'] ?? {}), services: List.from(json?['services'] ?? []), ); } } class BannerImage { final int id; final String name; final String path; final String fileMimeType; final int fileSize; final int fileWidth; final int fileHeight; BannerImage({ required this.id, required this.name, required this.path, required this.fileMimeType, required this.fileSize, required this.fileWidth, required this.fileHeight, }); factory BannerImage.fromJson(Map json) { return BannerImage( id: json['id'] ?? 0, name: json['name'] ?? '', path: json['path'] ?? '', fileMimeType: json['fileMimeType'] ?? '', fileSize: json['fileSize'] ?? 0, fileWidth: json['fileWidth'] ?? 0, fileHeight: json['fileHeight'] ?? 0, ); } } class Location { final int id; final double longitude; final double latitude; final String address; final dynamic city; final dynamic country; final dynamic province; final dynamic subProvince; final dynamic street; Location({ required this.id, required this.longitude, required this.latitude, required this.address, this.city, this.country, this.province, this.subProvince, this.street, }); factory Location.fromJson(Map json) { return Location( id: json['id'] ?? 0, longitude: json['longitude'] ?? 0.0, latitude: json['latitude'] ?? 0.0, address: json['address'] ?? '', city: json['city'], country: json['country'], province: json['province'], subProvince: json['subProvince'], street: json['street'], ); } } class MarkerGenerator { static Future defaultMarkerBytes() async { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder, Rect.fromPoints(Offset(0, 0), Offset(100, 100))); final paint = Paint()..color = Colors.red; canvas.drawCircle(Offset(50, 50), 50, paint); final picture = recorder.endRecording(); final img = await picture.toImage(100, 100); final byteData = await img.toByteData(format: ui.ImageByteFormat.png); return byteData!.buffer.asUint8List(); } } 
submitted by HungryBar3834 to flutterhelp [link] [comments]


2024.05.14 05:41 Autumn_Rabbit (Offer) Planes Fire and Rescue, Dunkirk, Jurassic Park Original Trilogy (Request) I, Tonya, Rush, Rocky Movies

To my knowledge most all but the iTunes codes should be unspilt. I've done my best to describe where I can.
4K Codes
Split 4K (redeemed through iTunes)
******HD Codes - MA/F@H/iTunes/GP ******
Star Wars - The Force Awakens (Full Code)
Star Wars - The Last Jedi (Full Code)
Planes - Fire and Rescue (Full Code)
Guardians of the Galaxy Vol 2
21 Jump St
Dunkirk
Perks of Being a Wallflower
Jurassic Park
Lockout
Fast Five
Mr Peabody and Sherman
Fate of the Furious Theatrical
HD Codes - iTunes Only (May be split - unsure)
Fifty Shades Darker (Unrated)
Jurassic World
Jurassic Park 1 - 3 - All seperate codes (would prefer to trade as a set, but we'll see)
Paranormal Activity - The Ghost Dimension
Whiplash
Possibly Barry Season 1 (iTunes only) will send first to have checked

~~~~~I'm Looking For...~~~~~~
A Bug's Life
The Blacklist Season 3 , 5 - 8 (Will trade multiple for)
Christmas Classics
Ford V Ferrari
It (1990)
I, Tonya
Lovely Bones
Kingdom of Heaven
No Time To Die
Rocky Knockout Collection (Will trade multiple for)
Rush
The Artist
Tolkien
And of course I'll look at lists but preference will likely go to the above list. As a note, please don't offer GP/FN as I don't use them. I will use iTunes but I prefer MA/F@H.
submitted by Autumn_Rabbit to uvtrade [link] [comments]


2024.05.14 05:39 GrapefruitCorrect187 How do you use this algorithm to sort the randomly generated numbers??

This is the algorithm my teacher wanted me to use/apply to the program:
* Selection sort algorithm
For PassNumber = 0 to ListSize - 2 ‘loop from beginning to last but one element (1st nested loop)
‘ find the smallest element in the unsorted range
SmallestPos = PassNumber ‘ initialise the smallest found so far as the element at the beginning of this range
For position = PassNumber + 1 to ListSize - 1 (2nd nested loop)
SmallestPos = Position
Next Position
‘ if element at PassNumber isn’t the smallest, move it there and swap
If PassNumber <> SmallestPos then (1st Selection)
‘ Swap
Temp = List(SmallestPos)
List(SmallestPos) = List(PassNumber)
List(PassNumber) = Temp
End If
‘ At this point, list from 0 to passnumber is sorted
Next PassNumber
And this is the programming code I did:
* The scenario is to generate random numbers from 1 to 100 and then sort them in ascending order.
Public Class Form1
'Declare the variables
Public MAXSIZE As Integer = 19
Public ItemCount As Integer = 0
Public arrnumbers(MAXSIZE) As Integer
Public bigpos As Integer
Public smallpos As Integer
'generate random numbers from 1 to 100
Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
Dim loops As Integer
Randomize()
lstDisplay.Items.Clear()
For loops = 0 To MAXSIZE - 1
arrnumbers(loops) = Int(100 * Rnd() + 1)
lstDisplay.Items.Add(arrnumbers(loops))
ItemCount = ItemCount + 1
Next
End Sub
' Select biggest number
Private Sub btnBig_Click(sender As Object, e As EventArgs) Handles btnBig.Click
Dim biggest As Integer = arrnumbers(0)
Dim bigpos As Integer
For i As Integer = 0 To ItemCount - 1
If arrnumbers(i) > biggest Then
biggest = arrnumbers(i)
bigpos = i
End If
Next
MsgBox("The biggest number is " & biggest.ToString)
End Sub
' Select smallest number
Private Sub btnSmall_Click(sender As Object, e As EventArgs) Handles btnSmall.Click
Dim smallest As Integer = arrnumbers(0)
Dim smallpos As Integer
For i As Integer = 0 To ItemCount - 1
If arrnumbers(i) < smallest Then
smallest = arrnumbers(i)
smallpos = i
End If
Next
MsgBox("The smallest number is " & smallest.ToString)
End Sub
'Sort the randomized numbers << THIS ONE
Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click
' Sort the array
Array.Sort(arrnumbers, 0, ItemCount)
' Clear the list box
lstDisplay.Items.Clear()
' Add sorted numbers to the list box
For loops = 0 To ItemCount - 1
lstDisplay.Items.Add(arrnumbers(loops))
Next
End Sub
The sort Button
https://preview.redd.it/6f4ioe2pbb0d1.png?width=427&format=png&auto=webp&s=7435aa7d05eeda54330b97900f7e9a4494a7d45c
This leads to the question that I have put in the title... the code that I wrote still sorts the numbers correctly, but that's probably not the one that my teacher wants me to use.
Maybe I'm not understanding the purpose of sorting..?
submitted by GrapefruitCorrect187 to visualbasic [link] [comments]


2024.05.14 05:34 RobotDragon0 PIC24: Trouble with converting between TMR value and seconds

https://imgur.com/a/Rx27Qga
I am having difficulty using the HC-SR04 ultrasonic sensor. This is the datasheet I have been referring to: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
As directed by the data sheet, I have been sending 10uS pulses to the trigger pin in order to get a response on the echo pin that can be used to determine the distance between an object and the sensor.
Additionally, according to the datasheet as well as the below Arduino code from Git, in order to determine the number of centimeters between an object and the sensor, you take the duration of the pulse on the echo pin and divide by 58: https://github.com/JRodrigoTech/Ultrasonic-HC-SR04/blob/masteUltrasonic/Ultrasonic.cpp
Now, here is the issue I am having. I do not know how to convert the values in TMRx to real time values (seconds). My method is using the input capture peripheral and configuring it to use Timer 3, and I record values whenever there is a change on the echo pin.
As the code shows, the formula I use to get the real time is time = (finalTime - currTime)*(Prescalar)/(frequency) where PRvalue = 65535, frequency = 16MHz, and Prescalar = 256. However, the real time value I always end up with is 0. From the screenshot in the imgur image, it seems like the result is always 0 because currTime and finalTime are always close to each other, and I cannot represent very small numbers because of the limited number of bits used to represent values.
What is the issue here? As the Imgur link shows, my sensor is sending back signals after I set a 10uS pulse on trigger, and when putting a breakpoint in my input capture ISR, the program correctly stops inside of it. That means this isnt a hardware issue but instead an issue with how I am calculating time.
Here is the minimally working example of my code:
#include "xc.h" #include  bool stopMotion = 0; volatile unsigned long int currTime = 0; volatile unsigned long int finalTime = 0; volatile unsigned long int overflowtmr = 0; volatile unsigned long int distanceThreshold = 1; void setup(){ CLKDIVbits.RCDIV = 0; TRISBbits.TRISB4 = 1; //input for echo TRISBbits.TRISB5 = 0; //output for trig LATBbits.LATB5 = 0; //IC1 setup IC1CONbits.ICTMR = 0; //timer 3 IC1CONbits.ICM = 1; //PPS for IC1 __builtin_write_OSCCONL(OSCCON & 0xbf);// unlock PPS RPINR7bits.IC1R = 4; // RP4 (pin 11) __builtin_write_OSCCONL(OSCCON 0x40); // lock PPS T3CON = 0; TMR3 = 0; T3CONbits.TCKPS = 3; _T3IF = 0; PR3 = 65535; T3CONbits.TON = 1; IFS0bits.T3IF = 0; IEC0bits.T3IE = 1; IPC2bits.T3IP = 5; IFS0bits.IC1IF = 0; IEC0bits.IC1IE = 1; IPC0bits.IC1IP = 5; } void __attribute__((interrupt, auto_psv)) _IC1Interrupt(){ IFS0bits.IC1IF = 0; if(PORTBbits.RB4 == 1){ currTime = TMR3 + 65536*overflowtmr; } else{ finalTime = TMR3 + 65536*overflowtmr; overflowtmr = 0; TMR3 = 0; finalTime = (finalTime - currTime)*(256)/(16000000); volatile unsigned long int distance = finalTime/58; if(distance <= distanceThreshold) stopMotion = 1; else stopMotion = 0; } } void __attribute__((interrupt, auto_psv)) _T3Interrupt(){ IFS0bits.T3IF = 0; overflowtmr++; } void delay_ms(unsigned int ms){ while(ms-- > 0){ asm("repeat #15999"); asm("nop"); } } void delay_10us(void){ int i = 10; while(i-- > 0){ asm("repeat #3"); asm("nop"); } } void sendTrig(){ LATBbits.LATB5 = 1; delay_10us(); LATBbits.LATB5 = 0; } int main(void) { setup(); while(1){ sendTrig(); delay_ms(2000); } } 
Edit: Updated code:
#include "xc.h" #include  bool stopMotion = 0; volatile double finalTime = 0; volatile unsigned long int overflowtmr = 0; volatile unsigned long int distanceThreshold = 1; void setup(){ CLKDIVbits.RCDIV = 0; TRISBbits.TRISB4 = 1; //input for echo TRISBbits.TRISB5 = 0; //output for trig LATBbits.LATB5 = 0; //IC1 setup IC1CONbits.ICTMR = 0; //timer 3 IC1CONbits.ICM = 1; //PPS for IC1 __builtin_write_OSCCONL(OSCCON & 0xbf);// unlock PPS RPINR7bits.IC1R = 4; // RP4 (pin 11) __builtin_write_OSCCONL(OSCCON 0x40); // lock PPS T3CON = 0; TMR3 = 0; T3CONbits.TCKPS = 3; _T3IF = 0; PR3 = 65535; T3CONbits.TON = 1; IFS0bits.T3IF = 0; IEC0bits.T3IE = 1; IPC2bits.T3IP = 3; IFS0bits.IC1IF = 0; IEC0bits.IC1IE = 1; IPC0bits.IC1IP = 3; //TIMER1 setup T1CON = 0; TMR1 = 0; T1CONbits.TCKPS = 0; _T1IF = 0; PR1 = 160; //for a delay of 10uS T1CONbits.TON = 0; IFS0bits.T1IF = 0; IEC0bits.T1IE = 1; IPC0bits.T1IP = 5; //higher priority than the input capture interrupt } void __attribute__((interrupt, auto_psv)) _IC1Interrupt(){ IFS0bits.IC1IF = 0; if(PORTBbits.RB4 == 1){ TMR3 = 0; } else{ finalTime = (double)(TMR3) + 65536*overflowtmr; overflowtmr = 0; TMR3 = 0; finalTime = (finalTime)*(256)/(16000000); double distance = finalTime/58; if(distance <= distanceThreshold) stopMotion = 1; else stopMotion = 0; } } void __attribute__((interrupt, auto_psv)) _T3Interrupt(){ IFS0bits.T3IF = 0; overflowtmr++; } void __attribute__((interrupt, auto_psv)) _T1Interrupt(){ _T1IF = 0; LATBbits.LATB5 = 0; } void sendTrig(){ LATBbits.LATB5 = 1; T1CONbits.TON = 1; } int main(void) { setup(); while(1){ sendTrig(); } } 
Edit: Updated code for calculating distance by using time in units of a 10th of a nanosecond:
#include "xc.h" #include  
bool stopMotion = 0;
volatile uint32_t finalTime = 0;
volatile int overflowtmr = 0;
int distanceThreshold = 1;
void setup(){
CLKDIVbits.RCDIV = 0;
TRISBbits.TRISB4 = 1; //input for echo
TRISBbits.TRISB5 = 0; //output for trig
LATBbits.LATB5 = 0;
//IC1 setup
IC1CONbits.ICTMR = 0; //timer 3
IC1CONbits.ICM = 1;
//PPS for IC1
__builtin_write_OSCCONL(OSCCON & 0xbf);// unlock PPS
RPINR7bits.IC1R = 4; // RP4 (pin 11)
__builtin_write_OSCCONL(OSCCON 0x40); // lock PPS
T3CON = 0;
TMR3 = 0;
T3CONbits.TCKPS = 0;
_T3IF = 0; //a prescaler of 1 for TMR3
PR3 = 65535;
T3CONbits.TON = 1;
IFS0bits.T3IF = 0;
IEC0bits.T3IE = 1;
IPC2bits.T3IP = 3;
IFS0bits.IC1IF = 0;
IEC0bits.IC1IE = 1;
IPC0bits.IC1IP = 3;
//TIMER1 setup
T1CON = 0;
TMR1 = 0;
T1CONbits.TCKPS = 0;
_T1IF = 0;
PR1 = 160; //for a delay of 10uS
T1CONbits.TON = 0;
IFS0bits.T1IF = 0;
IEC0bits.T1IE = 1;
IPC0bits.T1IP = 5; //higher priority than the input capture interrupt
}
void __attribute__((interrupt, auto_psv)) _IC1Interrupt(){
IFS0bits.IC1IF = 0;
if(PORTBbits.RB4 == 1){
//reset both TMR3 and overflowtmr
TMR3 = 0;
overflowtmr = 0;
}
else{
finalTime = (TMR3)*625 + overflowtmr*625*65536;
overflowtmr = 0;
TMR3 = 0;
uint16_t distance = finalTime/((58)*(10000/10));
if(distance <= distanceThreshold)
stopMotion = 1;
else
stopMotion = 0;
}
}
void __attribute__((interrupt, auto_psv)) _T3Interrupt(){
IFS0bits.T3IF = 0;
overflowtmr++;
}
void __attribute__((interrupt, auto_psv)) _T1Interrupt(){
_T1IF = 0;
LATBbits.LATB5 = 0;
}
void sendTrig(){
LATBbits.LATB5 = 1;
T1CONbits.TON = 1;
}
void delay_ms(unsigned int ms){
while(ms-- > 0){
asm("repeat #15999");
asm("nop");
}
}
int main(void) {
setup();
while(1){
sendTrig();
delay_ms(2000); //delay for 2 seconds before sending another trig signal.
}
}
submitted by RobotDragon0 to embedded [link] [comments]


2024.05.14 05:11 mmaynee [c++] Using RAND to initialize an array.

So i'm currently learning coding out of a book and was looking for some additional feedback on some specific code. My book is from 2007; and I dont really have anyone for questions right now.
The issue appears when using rand() is tandum with arrays. My current program rolls n number of dice, then prints the ammount of times each dice was rolled. When I run my code sometimes it works perfectly, other times I get massive errors. I added a few test points with cout<< and I've tracked that the die roll is coming back as a valid number 1-6, but when i try to update Array[validnumber - 1] my storage values in the array will print completely wacky (some times showing a billion rolls collected, when it only was asked and only printed 4.)
Biggest question mark is how this code can work flawless one run, and then horrible the next? I assume its some interaction with the rand() but I did my best trying to control its outputs. Not sure whats happening here; thanks for any advice.
#include  #include  #include  #define DVALUE 6 //how many sides of dice do you want using namespace std; int rng(); int main(){ srand(time(NULL)); //seed rand with current time int testAmmount; int dtally[DVALUE]; // # == faces on die; cout << "How many test rolls?: "; cin >> testAmmount; for(int i = 1; i <= testAmmount; i++){ int k = rng() - 1; dtally[k]++; //originally: dtally[rng() - 1]++ //added int k, trying to lock varible value cout << k + 1 << "'s in dtally block: " << dtally[k] << endl; } for(int i = 0; i < DVALUE; i++){ cout << i + 1 << "'s Rolled: " << dtally[i] << endl; } } /*I added the if statement and recursion to this function to try and make sure it only returns ints 1 to DVALUE, again I added int k to try and lock value in varible.*/ int rng(){ int k = (rand() % DVALUE) + 1; if(k >= 0 && k <= DVALUE){ cout << "I rolled: " << k << endl; return k; } return rng(); } 
Here are two runs of the same code back to back:
How many test rolls?: 7 I rolled: 6 6's in dtally block: 1 I rolled: 3 3's in dtally block: 590430763 I rolled: 5 5's in dtally block: 11 I rolled: 1 1's in dtally block: 591490841 I rolled: 6 6's in dtally block: 2 I rolled: 5 5's in dtally block: 12 I rolled: 6 6's in dtally block: 3 1's Rolled: 591490841 2's Rolled: 32514 3's Rolled: 590430763 4's Rolled: 32514 5's Rolled: 12 6's Rolled: 3 dub@penguin:~/cppwofear$ ./rngeval How many test rolls?: 7 I rolled: 6 6's in dtally block: 1 I rolled: 1 1's in dtally block: 1 I rolled: 5 5's in dtally block: 1 I rolled: 1 1's in dtally block: 2 I rolled: 1 1's in dtally block: 3 I rolled: 4 4's in dtally block: 1 I rolled: 3 3's in dtally block: 1 1's Rolled: 3 2's Rolled: 0 3's Rolled: 1 4's Rolled: 1 5's Rolled: 1 6's Rolled: 1 
submitted by mmaynee to learnprogramming [link] [comments]


2024.05.14 05:10 gamerguy45465 K&R 8.5 Example Help

Hi, so I am currently on Chapter 8 and section 5 on K&R. I just had a question regarding the following code:
1 #define NULL 0
2 #define EOF (-1)
3 #define BUFSIZ 1024
4 #define OPEN_MAX 20 /* max #files open at once */
5 typedef struct _iobuf {
6 int cnt; /* characters left */
7 char *ptr; /* next character position */
8 char *base; /* location of buffer */
9 int flag; /* mode of file access */
10 int fd; /* file descriptor */
11 } FILE;
12 extern FILE _iob[OPEN_MAX];
13 #define stdin (&_iob[0])
14 #define stdout (&_iob[1])
15 #define stderr (&_iob[2])
16 enum _flags {
17 _READ = 01, /* file open for reading */
18 _WRITE = 02, /* file open for writing */
19 _UNBUF = 04, /* file is unbuffered */
20 _EOF = 010, /* EOF has occurred on this file */
21 _ERR = 020 /* error occurred on this file */
22 };
23 int _fillbuf(FILE *);
24 int _flushbuf(int, FILE *);
25 #define feof(p) ((p)->flag & _EOF) != 0)
26 #define ferror(p) ((p)->flag & _ERR) != 0)
27 #define fileno(p) ((p)->fd)
28 #define getc(p) (--(p)->cnt >= 0 \
29 ? (unsigned char) *(p)->ptr++ : _fillbuf(p))
30 #define putc(x,p) (--(p)->cnt >= 0 \
31 ? *(p)->ptr++ = (x) : _flushbuf((x),p))
32 #define getchar() getc(stdin)
33 #define putcher(x) putc((x), stdout)
Okay, on line 9, we declare the flag variable for _iobuf, but then don't assign it to anything the entire code. Then on lines 25 and 26 we and it with two of the flags that we defined in our enum.
The thing is, wouldn't that turn the EOF flag off? Because flag is not set to anything, so wouldn't that mean that it doesn't have a value associated to it, and thus would just be zero? That's what I thought would happen anyway.
submitted by gamerguy45465 to cprogramming [link] [comments]


2024.05.14 04:01 Saso23 [Next14] Dynamic Routes not working

I've always used NextJS as a main frontend framework, but I want to learn to use it for backend as well, given how powerful it is. To do so I am coding a simple to do app to integrate with Prisma and postgresql.
// Import the PrismaClient constructor from the Prisma client package. import { PrismaClient } from '@prisma/client'; // Create an instance of PrismaClient. const prisma = new PrismaClient(); export async function GET( { params }: { params?: { slug?: string } } ) { if (!params !params.slug) { return new Response(JSON.stringify({ error: "No ID provided" }), { status: 400, headers: { 'Content-Type': 'application/json' }, }); } const id = parseInt(params.slug, 10) if (isNaN(id)) { return new Response(JSON.stringify({ error: "Invalid ID" }), { status: 400, headers: { 'Content-Type': 'application/json' }, }); } try { const todos = await prisma.todo.findUnique({ where: {id}, }) return new Response(JSON.stringify(todos), { status: 200, headers: { 'Content-Type': 'application/json', }, }) } catch(error) { return new Response(JSON.stringify({error}), { status: 500, headers: { 'Content-Type': 'application/json', }, }) } } 
I have `api/todos/route.ts` with a GET and a POST request function that work properly. Then when I create a GET in `api/todos/todo/[slug]/route.ts` as can be seen in the code above, and I call it with GET http://localhost:3000/api/todos/todo/1 then it always returns the 400 error.
According to the docs I should be doing it correctly, does anyone see what is wrong here? Not even ChatGPT4 is helping
submitted by Saso23 to nextjs [link] [comments]


2024.05.14 03:52 dipsy01 [Zephyr/SPI] Trying to understand why the sensor data is being shown this way

[ZephySPI] Trying to understand why the sensor data is being shown this way
I have a MAX31855 thermocouple sensor that transmits its data via SPI, most significant bit first. So according to this, the first bit it transmits when CS is driven low is the sign bit for the temperature data.
https://preview.redd.it/w3rbirqcra0d1.png?width=1031&format=png&auto=webp&s=4d043a947e7dbd30eaf6d4bf1aea76d811733ff3
But when I look at my buffer the data is going into, for byte 0 I'm getting 00000001. This is the correct order to translate into decimal, meaning the furthest most left 0 is the most significant bit, and the 1 was the least significant bit (for this portion, obviously theres more data I'm not showing).
I was expecting byte 0 of my rx buffer to be 10000000, and have to reverse it. Wouldn't the first bit received by the sensor go into bit 0 of the first byte?
Maybe zephyr is doing something to the rx buffer I'm not aware of? Here is my code:
LOG_MODULE_REGISTER(main, LOG_LEVEL_DBG); #define SPI1_NODE DT_NODELABEL(spi1) //#define SPI_NSS_PIN DT_PROP_BY_IDX(DT_NODELABEL(spi1), pinctrl_0, 0) #define SPI_BUS_FREQ 1000000 int main(void) { uint8_t rx_data[4] = {0}; static const struct spi_config spi_cfg = { .frequency = SPI_BUS_FREQ, //.operation = (SPI_OP_MODE_MASTER SPI_WORD_SET(8) SPI_TRANSFER_MSB), .operation = (SPI_OP_MODE_MASTER SPI_WORD_SET(8)), .cs = NULL, }; struct spi_buf spi_rx_buff; spi_rx_buff.buf = rx_data; spi_rx_buff.len = 4; struct spi_buf_set spi_rxbuffer_set = { .buffers = &spi_rx_buff, .count = 1, }; static const struct device *spi1_dev = DEVICE_DT_GET(SPI1_NODE); if (!spi1_dev) { LOG_INF("Error: Could not find SPI device"); return 1; } while (1) { if (spi_read(spi1_dev, &spi_cfg, &spi_rxbuffer_set) != 0) { LOG_INF("ERROR: SPI receive failed"); return 1; } //LOG_INF("Data: %x %x %x %x", rx_data[3], rx_data[2], rx_data[1], rx_data[0]); LOG_INF("Data2: %x %x %x %x", rx_data[0], rx_data[1], rx_data[2], rx_data[3]); k_sleep(K_SECONDS(1)); } return 0; } 
submitted by dipsy01 to embedded [link] [comments]


2024.05.14 02:28 Sheo996 I freaking LOVE holy magic! Anyone else a big Golden Order fan?

Idc what anybody says about how viable holy damage is in this game, I am a die-hard golden order fan. First playthrough was a golden order fundamentalist with crucible armor and cipher pata > coded sword > golden order greatsword as I obtained them, and got the Perfect Order ending. NG+ I try to make a cleanrot knight larp build (at least their ashes of war did holy damage), but like around altus plateau I just HAD to go back to holy and made a pure holy GO caster healer. I literally cannot escape the golden order, they have me by their clutches. It's like the Skyrim stealth archer for me. All the bright golden lights just look so fucking cool. The golden order greatsword is PEAK design. Idc if 80% of the game has 20%+ resistance to holy, I'll use it on every boss except the 80%+ resistance ones (where sadly for my own sanity I am forced to use blasphemous blade). It just looks fucking COOL! I hate that GO spells have an asinine int requirement, but whatever, it's still worth it for the holy larp. I like my golden discs and elden stars! Besides, everything having 20-40% holy resistance isn't that bad if you stack a bunch of holy damage stuff. I use the gold mask, 2 GO seals (since the boost stacks), sacred scorpion charm and flock's canvas talisman. Does decent damage even against 40% resist. Is there anyone else who feels similar? I've only ever seen one other GO bro in my playthroughs. Any other ideas for another holy-themed build for my 3rd run?
submitted by Sheo996 to Eldenring [link] [comments]


2024.05.14 01:38 quietyoucantbe Do games (or other programs) have a "main running loop" and then a "game loop" inside?

I'm working on a basic 2D side scroller with C++/SDL2. So far I have a working framework (game class, renderer class, entity class, etc) and I want to implement levels. My idea:
while (m_Run)
Events();
//Render start menu/instructions
if (user presses enter)
if (level == 1) function that implements entities for level 1
if (level == 2) " " " etc
while (m_GameLoop)
Events();
Update();
Render();
When level 1 is done, increment an int or something, hop out of the game loop, destroy level 1, implement level 2, etc, etc
I'm pretty sure I could make all this work, but I guess I'm wondering how it's usually done? When I don't know something, I'll try and figure out a solution before I look it up. Sometimes I'll start with the code I want to end up with and work backwards from there. Sorry the indentations didn't work.
Thank you!
submitted by quietyoucantbe to learnprogramming [link] [comments]


http://swiebodzin.info