instruction stringlengths 0 30k ⌀ |
|---|
|c#|asp.net-core|routes|asp.net-core-mvc| |
I am using PrivateGPT to chat with a PDF document. I ask a question and get an answer. If I am okay with the answer, and the same question is asked again, I want the previous answer instead of creating a new one. How can I handle this? Are there any options available?
settings-local.yaml
llm:
mode: llamacpp
max_new_tokens: 512
context_window: 3900
tokenizer: mistralai/Mistral-7B-Instruct-v0.2
llamacpp:
prompt_style: "mistral"
llm_hf_repo_id: TheBloke/Mistral-7B-Instruct-v0.2-GGUF
llm_hf_model_file: mistral-7b-instruct-v0.2.Q4_K_M.gguf
embedding:
mode: huggingface
huggingface:
embedding_hf_model_name: BAAI/bge-small-en-v1.5
vectorstore:
database: qdrant
qdrant:
path: local_data/private_gpt/qdrant
|
|amazon-web-services|terraform|terraform-provider-aws|aws-route53| |
Previous correct answer instead of creating a new one |
{"Voters":[{"Id":3874623,"DisplayName":"Mark","BindingReason":{"GoldTagBadge":"python"}}]} |
## Issue Description
Everytime i run my Streamlit Web APP terminal sends a Warning message always that i interact with the APP: "`label` got an empty value. This is discouraged for accessibility reasons and may be disallowed in the future by raising an exception. Please provide a non-empty label and hide it with label_visibility if needed". I checked the widgets and widgets arguments but maybe i am not watching something.
## Steps to Reproduce
1. Copy python code into a python file in your Visual Studio Code 'form.py'
2. Install python library: `streamlit==1.32.2`
* Example command to use: `pip install`
* Extra information: Use virtual environment`venv`
3. Run web app from file directory of main file `streamlit run ./form.py`
## Environment information
* Python version: `Python 3.12.2`
* SO: Windows
* Streamlit version: `streamlit==1.32.2`
* Code Editor: Visual Studio Code
## LOG
`'label' got an empty value. This is discouraged for accessibility reasons and may be disallowed in the future by raising an exception. Please provide a non-empty label and hide it with label_visibility if needed.`
# Code
```
import streamlit as st
import pandas as pd
import os
from datetime import datetime
with st.form('myform'):
st.subheader('Registration Form')
c1, c2, c3 = st.columns(3)
select_box = c1.selectbox('',('Mr','Mrs','Miss'))
first_name = c2.text_input('First Name', '')
last_name = c3.text_input('Last Name', '')
# Role
role = st.selectbox('Designation',('Software',
'Sr. Software','Technical Lead',
'Manager','Sr. Manager','Project Manager'))
# Date of Birth
dob = st.date_input('Date of Birth',
min_value=datetime(year=1900,month=1,day=1))
# Gender
gender = st.radio(
"Select Gender",
('Male','Female','Prefered Not to Say')
)
# age
age = st.slider('Age',min_value=1,max_value=100,step=1,value=20)
submitted = st.form_submit_button('Submit')
if submitted:
st.success('Form Subimitted Sucessfully')
details = {
'Name': f"{select_box} {first_name} {last_name}",
'Age': age,
'Gender':gender,
'Data of Birth': dob,
'Designation':role
}
st.json(details)
``` |
I want to get a pressed mouse or keyboard button from global object window or document when it's listening in setInterval.
```
setInterval(function () {
window.mouse.button. ...;
window.keyboard.button. ...;
// or maybe
document.mouse.button. ...;
document.keyboard.button. ...;
}, 1);
```
It would be kind of my own self-made event.
**How to detect a pressed button using setInterval and without any event in javascript?**
```
setInterval(function () {
window.mouse.button. ...;
window.keyboard.button. ...;
// or maybe
document.mouse.button. ...;
document.keyboard.button. ...;
}, 1);
```
|
How to detect a pressed button using setInterval and without any event in javascript? |
|button|events|setinterval|detect|pressed| |
null |
You can try in the following way.
> gte:2022-02-07T00:00:00.000Z
lte:2022-02-07T23:59:59:999Z
The reason for this is that:
> To expand a bit on the answer, the dates are stored as full date-time value. Think of it as ISODate("2022-02-07T00:00:00.000Z") is storing February 7th 2022 at midnight. Comparing ISODate("2022-02-07T00:00:00.000Z") and ISODate("2022-02-07T01:00:00.000Z") will not show them as equal since the full “datetime” is being compared.
This answer has been quoted from:
[Query date range of the same day][1]
Thank You
WeDoTheBest4You
[1]: https://www.mongodb.com/community/forums/t/query-date-range-of-the-same-day/146171/2 |
The solution was to change from this code
authorizeRequests.requestMatchers("/Ponyo").permitAll()
to this code
authorizeRequests.requestMatchers(new AntPathRequestMatcher("/Ponyo")).permitAll()
Works fine now
|
I'm new to FFMPEG.
To make it simple, I've created a program that applies a negative filter to small images in png format. For some of the images, everything is fine and the transparency is maintained... But for others, FFMPEG converted the transparency to either black or white pixels.
I'm just using the command:
`ffmpeg -y -i input.png -vf negate output.png`
I downloaded the latest binaries for windows from https://www.gyan.dev/ffmpeg/builds/ (2024/03/25) |
how to not remove transparency using negate option on png files ffmpeg |
|ffmpeg| |
null |
My drawables are on the folder drawable-xxhdpi and the background size is 1080 x 1920.
How the screens with this resolution, all is OK.
But when I test on a samsung A34 for example with the resolution 1080 X 2340, I have a black strip under my screen game and I don't know how to scale my background and the position of the other graphics elements to this specfic screen.
Thank you
Gigi
```
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
// Affichage du background
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.backgame), 0, 0, paint);
```
|
Android: How to scale a bitmap to fit the screen size using canvas? |
I'm trying to create a thumbnail sheet (a grid of thumbnails) using ImageMagick with filenames beneath each image. The filenames are long UUID style strings, and using the -title option they overflow into each other to create an unreadable mess. So I thought I'd truncate the names to only show the first n characters. My Bash script is below (running via Git Bash on Windows 11.) I'm not sure whether this is an error in my Bash code, or my use of ImageMagick.
```
magick montage -verbose -label "$(echo '%t' | cut -c -8)" -font Arial -pointsize 16 \
-background '#000000' -fill 'gray' \
-define jpeg:size=200x200 \
-geometry 200x200+2+2 -tile 8x0 \
-auto-orient \
$(ls -rt *.jpg) \
out.jpg
```
As far as I can tell the issue I have is with the `$(echo '%t'` ... part of the script in the first line; it doesn't seem to be piped into the cut command following it. If I use a literal string, eg. `echo 'Hello world!'`, each thumbnail is labeled with what I'd expect, 'Hello wo'. But if I instead use %t (which is ImageMagick's format variable for exposing the base filename of the image) I get the full untruncated filename as if the cut command isn't being applied.
When I use a naked format variable (I've tried %f, the full filename, and %t, the base filename), without echo'ing it into cut, I get the expected untruncated filename. As mentioned, if I echo a literal string (Hello world!) piped into cut, I get the expected truncated output. It is only when I combine the two to echo %f or %t into cut that the truncation fails and I get the full filename. I've also tried piping the echo into sed instead of cut, but yet again the second command is ignored and I get the full filename.
Any help gratefully received. |
ImageMagick / Bash : pipe ignored(?) when filename format variable used |
|bash|imagemagick| |
null |
Can someone please help me to get rid of this error?
> Error : [PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
PrivateRoute.js :
import React from "react"
import { Route, Navigate } from "react-router-dom"
import { useAuth } from "./AuthContex"
export default function PrivateRoute({ element: Element, ...rest }) {
const { currentUser } = useAuth()
return (
<Route
{...rest}
element={currentUser ? <Element {...rest} /> : <Navigate to="/login" />}
/>
)
}
App.js :
import Signup from "./components/signup"
import { Container } from "react-bootstrap"
import { AuthProvider, useAuth } from './components/AuthContex'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Dashboard from "./components/Dashboard"
import Login from "./components/Login"
import ForgotPassword from "./components/ForgotPassword"
import UpdateProfile from "./components/UpdateProfile"
function App() {
return (
<Container
className="d-flex align-items-center justify-content-center"
style={{ minHeight: "100vh" }}
>
<div className="w-100" style={{ maxWidth: "400px" }}>
<Router>
<AuthProvider>
<Routes>
<PrivateRoute path="/" element={<Dashboard />} />
<Route path="/update-profile" element={<UpdateProfile />} />
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
</Routes>
</AuthProvider>
</Router>
</div>
</Container>
)
}
function PrivateRoute({ element, ...rest }) {
const { currentUser } = useAuth();
// Redirect to login if not authenticated
if (!currentUser) {
return <Navigate to="/login" />;
}
// Render the element if authenticated
return <Route {...rest} element={element} />;
}
export default App`
I am trying to create a signup page using firebase authentication |
how to apply gaussian filter correctly |
|c++|canny-operator|stb-image| |
null |
resolve:you need to wrap the root component of the paths in which you have an <Outlet /> in <Provider /> (for me it was an <App/> component, then when you send Routes via module federation, you already have a redux context. |
I've created a minimal CMake project on Windows, which includes only a single C++ file. Despite setting `"C_Cpp.codeAnalysis.clangTidy.enabled": false` in my VSCode settings, I continue to encounter clang-tidy errors when building the project.
This issue seems to arise specifically when using the Ninja generator, which I prefer for its ability to generate compile_commands.json. Here's a brief overview of my setup:
- Platform: Windows
- Build system: CMake with Ninja generator
- VSCode setting to disable clang-tidy: "C_Cpp.codeAnalysis.clangTidy.enabled": false
I'm looking for a way to resolve these clang-tidy errors without switching away from the Ninja generator. Has anyone faced a similar issue, or does anyone know how to properly disable clang-tidy under these conditions? |
Compiling c++ code by VS Code is always blocked by clang-tidy error 'Error running 'clang-tidy' |
|visual-studio-code|cmake|clangd| |
I'm trying to create a script that will trigger key numbers from 1 to 3
I was trying:
KeyNum := 1
1:: {
global KeyNum
Send KeyNum
KeyNum := KeyNum + 1
if (KeyNum > 3) {
KeyNum := 1
}
}
but the output was `232323`, so I changed it to:
KeyNum := 1
~1:: {
global KeyNum
Send KeyNum
KeyNum := KeyNum + 1
if (KeyNum > 3) {
KeyNum := 1
}
}
but then I got `111213111213`
How can I prevent default action in the `~1::` version?
**or**
How can I call the default key action in the `1::` version?
I found [that question](https://stackoverflow.com/questions/77027232/how-to-skip-autohotkey-reaction-and-send-normal-key) but I don't know is it possible to implement it in my case. |
Dynamic default key action |
|autohotkey| |
Stood in front of the same problem, I solved it now for Tauri beta. This may help you:
my new imports:
````
import { save } from '@tauri-apps/plugin-dialog';
import { writeTextFile, writeFile } from '@tauri-apps/plugin-fs';
````
my func uses a blob from my api:
````
generateMonthlyConcerts(): void {
this.eventService.getMonthlyConcertPdf(this.starttimeOfMonth, this.endtimeOfMonth).pipe(take(1))
.subscribe(async blob => {
const readableStream = blob.stream();
const stream = readableStream.getReader();
let data: Uint8Array;
while (true) {
let { done, value } = await stream.read();
if (done) {
console.log('all blob processed.');
break;
}
data = value;
}
const path = await save({
defaultPath: 'Konzertprogramm_' + formatDate(this.starttimeOfMonth, 'MMMM_y', 'de-DE') + '.pdf',
filters: [
{
name: 'PDF Filter',
extensions: ['pdf']
},
],
});
await writeFile(path, data);
});
}
```` |
Upload Geotiff or Shapefile to Snowflake through streamlit |
|database|snowflake-cloud-data-platform|streamlit| |
null |
sudo apt-get install libcudnn8 |
MACHINE ?= "beaglebone" core-image-sato |
> I know this is very old question but this might help some new developers There are multiple ways to get this form working but here is a simple tweak
Here is the code
<form action="/" class="form" id="theForm">
<div id="placeOrder"
style="text-align: right; width: 100%; background-color: white;">
<button type="submit"
class='input_submit'
style="margin-right: 15px;"
onclick="placeOrder()">Place Order
</button>
</div>
</form>
<script>
function placeOrder(){
let form = document.getElementById('theForm');
let div = document.getElementById('placeOrder');
let span = document.createElement('span');
span.innerText = 'Processing...';
document.querySelector('button.input_submit').style.visibility = 'hidden';
div.appendChild(span);
}
</script> |
Can someone assist how to solve this issue (if possible to be solved)?
I am using **DevTools** for getting necessary token (in all automation tests). Tests are written in **Java (Selenium 4.16.1)**
In order to have them run on pipeline, must be in headless mode and in incognito mode, too.
But throws error: **java.awt.AWTException: headless environment**
Tried a lot of options in Chrome, but without any success. Chrome browser class looks like this:
```
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-extensions");
chromeOptions.addArguments("--enable-application-cache");
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--enable-automation");
chromeOptions.addArguments("--ignore-certificate-errors");
chromeOptions.addArguments("--remote-allow-origins=*");
chromeOptions.addArguments("--disable-dev-shm-usage");
chromeOptions.addArguments("--disable-gpu");
chromeOptions.addArguments("--remote-debugging-port=9222");
chromeOptions.addArguments("--disable-infobars");
String incognito = System.getProperty("incognito", "false");
if (incognito.equalsIgnoreCase("true")) {
chromeOptions.addArguments("--incognito");
}
String pathToDownl = System.getProperty("user.home") + "\\" + Constants.
$string("download.location");
HashMap<String, Object> chromePre = new HashMap<String, Object>();
chromePre.put("profile.default_content_settings.popups", 0);
chromePre.put("download.prompt_for_download", false);
chromePre.put("download.default_directory", pathToDownl);
chromePre.put("profile.content_settings.exceptions.automatic_downloads.*.setting", 1);
chromePre.put("safebrowsing.enabled", false);
chromeOptions.setExperimentalOption("prefs", chromePre);
//System.out.println(pathToDownl);
//chromeOptions.addArguments("--remote-debugging-port=9222");
if ($boolean("enableProxy")==true){
chromeOptions.setCapability("proxy", setProxy());
}
```
|
null |
Two things:
1. C# moved away from QuickSort to IntrospectiveSort, as also your link shows. You can see the comments and compatibility support at the [`Sort`](https://referencesource.microsoft.com/#mscorlib/system/array.cs,2300) source code.
2. The code you refer to is recrusive. Near the end of the loop is a recursive call:
```
private void IntroSort(int lo, int hi, int depthLimit)
{
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
// ...
InsertionSort(lo, hi);
return;
}
// ...
int p = PickPivotAndPartition(lo, hi);
IntroSort(p + 1, hi, depthLimit); // <--- recursive call
hi = p - 1;
}
}
```
The next iteration of the loop takes the *left* partition, and the recursive call takes the *right* partition. |
the only other code used in this from anywhere else is Player::getPosition(), which is just returning playerSprite.getPosition() and
Game::update which passes Player::getPosition() to this function
`sf::Vector2f enemyLocation{0.f, 0.f};`
starting value of enemyLocation for debugging
```
///<summary>
/// gets the amount enemy should move
/// called from Game.update()
///</summary>
/// <param name="t_playerPos"> player window position </param>
/// <returns> enemy move amount per frame (normalised) </returns>
sf::Vector2f Enemy::attemptMove(sf::Vector2f t_playerPos)
{
sf::Vector2f movement = { 0.f, 0.f }; // movement towards player each frame
sf::Vector2f direction = t_playerPos - enemyLocation; // delta playerPos and enemyPos
float angle = atan2f(direction.y, direction.x); // angle to player (rad)
angle = angle * 180.f / M_PI; // convert angle to degrees
float hyp = 1.f; // length of line to player (used for normalisation of vector)
// check if enemy is horizontally in line with player
if (direction.x == 0.f) {
if (direction.y > 0.f) { movement.y = hyp; } // move straight down
else { movement = -hyp; } // move straight up
}
// check if enemy is vertically in line with player
else if (direction.y == 0.f) {
if (direction.x > 0.f) { movement.x = hyp; } // move right
else { movement.x = -hyp; } // move left
}
// if enemy is not in line with player
else {
// ratio of sides y:x = opp:adj
movement.y = sinf(angle);
movement.x = cosf(angle);
// normalising the vector
hyp = sqrtf(abs(movement.x * movement.x) + abs(movement.y * movement.y));
hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse
movement.x = hyp * movement.x;
movement.y = hyp * movement.y; // sqrt(x^2 + y^2) should equal 1
move(movement);
}
return movement; // return to Game::update() (not currently assigned to anything there)
}
///<summary>
/// moves the enemy by the amount it should each frame
/// in final code will be called from Game.update()
/// for now only called from Enemy::attemptMove()
///</summary>
///<param name="t_movement"> amount to move each frame towards player </param>
void Enemy::move(sf::Vector2f t_movement)
{
enemyLocation += t_movement; // update enemy location
enemySprite.setPosition(enemyLocation); // set enemy position to updated location
}
```
my includes are
```
#include <SFML/Graphics.hpp>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
```
I expect the enemy to move in a straight line to the player, which does happen if the player is stationary
If the player moves diagonally away from the enemy, this also works, but if the player moves any other direction, the enemy spins in a circle (sometimes spiral) until the player stops moving or starts moving diagonally away from the enemy, or sometimes moves in a straight line in a completely wrong direction.
I have tried:
- assigning attemptMove() to a variable in Game::update and passing that to Enemy::move()
- including an alpha and beta angle and calculating the ratios of the angle by Sine rule
- including breakpoints to verify the angle is correct (it always seems to be)
- removing the checks for "in line" with player and always running the calculation
- changing if (movement.x/y == 0.f) to if (abs(movement.x/y) < 0.01f) and < epsilon
- changing where the functions are called from and what args are passed to them
- a few other changes, none of which seemed to have any promise
- rewriting large sections of the code outside of the block shown, which naturally had no effect
- cleaning up my code, (this is actually even cleaner than the one in my actual project, though I did run it to make sure it definitely didn't work before posting it)
nothing seems to have any effect, and a lot of things make the problem worse or more severe, I really don't know what else there is to do
EDIT: Below is working code
```
void Enemy::attemptMove(sf::Vector2f t_playerPos)
{
sf::Vector2f direction = t_playerPos - enemyLocation; // playerPos-enemyPos (direction to player)
float hyp;
// normalising the vector
hyp = sqrtf(abs(direction.x * direction.x) + abs(direction.y * direction.y));
hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse
direction.x = hyp * direction.x;
direction.y = hyp * direction.y; // sqrt(x^2 + y^2) should equal 1
move(direction);
}
void Enemy::move(sf::Vector2f t_movement)
{
enemyLocation += t_movement; // update enemy location
enemySprite.setPosition(enemyLocation); // set enemy position to updated location
}
``` |
|java|spring| |
Depending on the error in my back-end, I would like to display the corresponding error in my front-end, for example if an email address or a pseudo is already use in my DB (I work with nuxt-auth local provider)
At the moment, my custom message is displayed in my editor console like this: \[nuxt\] \[request error\] \[unhandled\] \[500\] E-mail adrress already use !
But in my console browser have an 500 (Internal Server Error) from POST http://localhost:3000/api/auth/register
Btw if I enter an address that is not yet known, my code works
```
//register.post.ts
export default defineEventHandler(async event => {
let e;
const response = await readBody(event);
console.log(response);
const userEmail = response.email;
const searchMailIntoDB = await client.query(`SELECT mail
from profil
where mail = '${userEmail}'`);
const isEmailExist = searchMailIntoDB.rows[0];
const userPseudo = response.pseudo;
const searchPseudoIntoDB = await client.query(`SELECT pseudo
from profil
where mail = '${userPseudo}'`);
const isPseudoExist = searchPseudoIntoDB.rows[0];
if (isEmailExist) {
throw new Error("E-mail address already in use!");
} else if (isPseudoExist) {
throw new Error("Pseudo already in use!");
} else {
console.log("Create new account..");
}
});
//connexion.vue
async function signUpWithCredentials() {
const credentials = {
email: signUpEmail.value,
password: signUpPassword.value,
firstName: firstName.value,
lastName: lastName.value,
gender: gender.value,
pseudo: pseudo.value
};
try {
await signUp(credentials, {callbackUrl: '/allPosts', redirect: true, external: true});
} catch (e) {
console.log(e);
}
}
``` |
Sends a personalised error message from the back-end to the front-end with Nuxt-auth |
|authentication|error-handling|nuxt.js|nuxt-auth| |
null |
Running Streamlit APP 1.32.2 Version - Can not delete warning message `label` got an empty value |
|python|streamlit| |
I used this code snippet inside one of my useEffect hooks. But it mutates the object and shows me the message to be appeared twice.
setConversations((prev) => {
const oldConversation = room in prev ? prev[room] : [];
const newConversation = [
...oldConversation,
{
sender: from,
message: msg,
time: new Date().toLocaleString(),
},
];
return { ...prev, [room]: newConversation };
});
What am I missing? Any suggestions would be much appreciated.
Edit:
The custom effect (where the message is received):
export const useSocketEventListener = (
socket,
peer,
setPeersOnConference,
setPeerIdsOnConference,
setAvailableUsers,
availableRooms,
setAvailableRooms,
setConferenceId,
setCallOthersTriggered,
setTransited,
calls,
setCalls,
setConversations
) => {
useEffect(() => {
socket?.on('receiveMessage', (msg, from, room) => {
// alert(`${msg} from ${from} room ${room}`);
// let temp = socket.id === room ? from : room;
setConversations((prev) => { // called twice (expected once to add the message to the state)
const oldConversation = room in prev ? prev[room] : [];
const newConversation = [
...oldConversation,
{
sender: from,
message: msg,
time: new Date().toLocaleString(),
},
];
console.log('calling once');
return { ...prev, [room]: newConversation };
});
console.log('i fire once');
});
socket?.on('joinRoomAlert', (socketId, room) => {
//
});
socket?.on('leaveRoomAlert', (socketId, room) => {
alert(`${socketId} left the room ${room}`);
});
socket?.on('receivePeersOnConference', (peersOnConference) => {
// setPeersOnConference(peersOnConference);
});
socket?.on('receiveData', (data) => {
setAvailableUsers(data.users);
setAvailableRooms(data.rooms);
});
socket?.on('peerEndCall', (peerId) => {
calls[peerId]?.close();
setCalls((prev) =>
Object.keys(prev)
.filter((key) => key !== peerId)
.reduce((obj, key) => ({ ...obj, [key]: prev[key] }), {})
);
setPeersOnConference((prev) => {
if (Object.keys(prev).length === 1) {
setCallOthersTriggered(false);
setTransited(false);
return {};
}
return Object.keys(prev)
.filter((key) => key !== peerId)
.reduce((obj, key) => ({ ...obj, [key]: prev[key] }), {});
});
});
socket?.on(
'receiveCallOthersTriggered',
(peerIds, conferenceId, caller) => {
console.log('peerIds: ', peerIds);
setConferenceId(socket.id === conferenceId ? caller : conferenceId);
setCallOthersTriggered(true);
setPeerIdsOnConference([...peerIds]);
}
);
socket?.on('leaveCallAlert', (leftPeerId) => {
//
});
socket?.emit('fetchData');
peer?.on('call', async (call) => {
try {
setTransited(true);
const selfStream = await getMedia();
console.log(peer.id, selfStream);
setPeersOnConference((prev) => ({ ...prev, [peer.id]: selfStream }));
call.answer(selfStream);
call.on('stream', (remoteStream) => {
console.log(call.peer, remoteStream);
setPeersOnConference((prev) => ({
...prev,
[call.peer]: remoteStream,
}));
});
call.on('close', () => {
selfStream.getTracks().forEach((track) => track.stop());
});
call.on('error', (e) => console.log('error in peer call'));
} catch (e) {
console.log('error while receiving call');
}
});
}, [socket, peer]);
};
The function to send message:
export const sendMessage = (socket, msg, to, setMessage, setConversations) => {
socket.emit('sendMessage', msg, to);
setMessage('');
setConversations((prev) => { // called once
const oldConversation = to in prev ? prev[to] : [];
const newConversation = [
...oldConversation,
{
sender: socket.id,
message: msg,
time: new Date().toLocaleString(),
},
];
return { ...prev, [to]: newConversation };
});
};
**Note:** Used the custom hook in the App.js file. |
I'm working on some code for a javascript implemenation of Conway's Game of Life Cellular Automata for a personal project, and I've reached the point of encoding the rules. I am applying the rules to each cell, then storing the new version in a copy of the grid. Then, when I'm finished calculating each cell's next state, I set the first grid's state to the second's one, empty the second grid, and start over. Here's the code I used for the rules:
```lang-js
//10x10 grid
let ecells = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];
let cells = empty_cells;
let new_cells = cells;
let paused = true;
function Cell(x, y) {
return cells[y][x];
}
function Nsum(i, j) {
if (i >= 1 && j >= 1) {
return Cell(i - 1, j) + Cell(i + 1, j) + Cell(i, j - 1) + Cell(i - 1, j - 1) + Cell(i + 1, j - 1) + Cell(i, j + 1) + Cell(i - 1, j + 1) + Cell(i + 1, j + 1);
}
}
//One can manually change the state of the cells in the "cells" grid,
//which works correctly. Then, one can run the CA by changing the "paused"
//value to false.
function simulation() {
for (i = 0; i < cells[0].length; i++) {
for (j = 0; j < cells.length; j++) {
if (Cell(i, j)) {
ctx.fillRect(20*i - 0.5, 20*j, 20, 20);
if (!paused) {
if (Nsum(i, j) == 2 || Nsum(i, j) == 3) new_cells[j][i] = 1;
else new_cells[j][i] = 0;
}
}
else {
ctx.clearRect(20*i - 0.5, 20*j, 20, 20);
if (!paused) {
if (Nsum(i, j) == 3) new_cells[j][i] = 1;
else new_cells[j][i] = 0;
}
}
}
}
if (!paused) cells = new_cells;
new_cells = empty_cells;
requestAnimationFrame(simulation);
}
simulation();
```
The rule logic is inside the nested for loop, Nsum is the function that calculates the neighborhood sum of the current cell. I say ncells[j][i] instead of ncells[i][j] because in a 2d array you address the row first.
I didn't try much, but I can't imagine a solution. Help! |
Had a similar issue while fetching available languages from a web API.
Adding UTF-8 encoding as header solved it for me:
.addHeader("Accept-Encoding", "UTF-8")
Maybe this helps someone. |
import random
def create_matrix(n, m, d):
# if d is greater than multiple of n and m, return error
if d > n*m : return f'd should be less than {n*m}'
else:
i = 0
# Create a n x m matrix with all value being zero
mtrx = [[0 for x in range(m)] for y in range(n)]
# Create a while loop with condtion i is less than d
while i < d:
# rest understandable with code
r = random.choice(range(n))
c = random.choice(range(m))
if mtrx[r][c] != 1:
mtrx[r][c] = 1
else:
i = i -1
i += 1
return mtrx
r = create_matrix(4,5, 10)
print(r) |
|android|canvas|resolution|image-resizing|multiscreen| |
null |
Updated it using async. it starts from the last div, but I think that's fine...
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Define an async function to handle scroll position reset
async function handleScrollPositionReset() {
const scrollables = document.querySelectorAll('.scrollable');
for (const scrollable of scrollables) {
resetScrollPosition(scrollable);
}
}
// Function to reset scroll position for a specific scrollable element
function resetScrollPosition(scrollable) {
// Replace 'targetItemId' with the ID of the item you want to scroll to
const targetItemId = 'current';
// Scroll to the target item within the scrollable element
const targetItem = scrollable.querySelector(`#${targetItemId}`);
if (targetItem) {
// Scroll to the calculated position within the scrollable element
targetItem.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
}
}
// Add scroll event listener to each scrollable element
document.addEventListener("DOMContentLoaded", async () => {
const scrollables = document.querySelectorAll('.scrollable');
scrollables.forEach(scrollable => {
scrollable.addEventListener('scroll', async () => {
clearTimeout(scrollable.timeout);
scrollable.timeout = setTimeout(async () => {
await handleScrollPositionReset();
}, 1000);
});
});
// Reset scroll position when the page is fully loaded
await handleScrollPositionReset();
});
// Reset scroll position when the page is fully loaded
window.onload = async function() {
await handleScrollPositionReset();
};
<!-- language: lang-css -->
.scrollable{
width: 300px;
height: 200px;
overflow-y: auto; /* Enable vertical scrolling */
border: 1px solid #ccc;
margin-bottom: 20px;
padding: 10px;
}
/* Styling for the scrollable div content */
.scrollable h2 {
margin-top: 0;
}
.scrollable p {
margin-bottom: 0;
}
body{
display:flex;
}
<!-- language: lang-html -->
<div id="scrollable1" class="scrollable">
<h2>Scrollable Div 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p style="color:red;" id="current">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<!-- Add more content as needed -->
</div>
<div id="scrollable2" class="scrollable">
<h2>Scrollable Div 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p style="color:red;" id="current">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<!-- Add more content as needed -->
</div>
<div id="scrollable3" class="scrollable">
<h2>Scrollable Div 3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p style="color:red;" id="current">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<!-- Add more content as needed -->
</div>
<div id="scrollable4" class="scrollable">
<h2>Scrollable Div 4</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p style="color:red;" id="current">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vestibulum, justo at euismod mollis, tortor metus suscipit felis, ut volutpat ipsum velit ac orci.</p>
<!-- Add more content as needed -->
</div>
<!-- end snippet -->
|
I have a collection of documents with a **timestamp** field named 'date'. I want to query a single document with the specific 'date': 2024/02/29 00:00:00 GMT05.30.
So in Flutter, I'm trying to get that doc by using the following query
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('mycolloection').where('date', isEqualTo: DateTime(2024,2,29,0,0,0,0,0),).snapshots(),),
but the above code does not retrieve any documents. So I played with isGreaterThan and isLesserThan for several hours and found out there is a hidden milliseconds value in the Firestore timestamp. So I have to give a milliseconds value as well. But this value is changing with different dates and it looks like a completely random number. Can anyone explain what is happening here... |
|flutter|firebase|dart|google-cloud-platform|google-cloud-firestore| |
null |
|angular|typescript| |
null |
{"OriginalQuestionIds":[23771117],"Voters":[{"Id":1116230,"DisplayName":"Nico Haase"},{"Id":1426539,"DisplayName":"yivi","BindingReason":{"GoldTagBadge":"php"}}]} |
I have a dataframe with the following schema :
col1 as col1,
col 2,
col 3,
.
.
col n
I have another dataframe with the following schema
col1 as diffName,
col n+1,
col n+2
.
.
.
how can i append values in col 1 of dataframe and the rest of the columns as null values?
**i have tried using union as well as merge but to no avail** |
Insert selective columns into pyspark dataframe |
|pyspark|apache-spark-sql| |
I have some histograms in a `.root` file which are called `"Name/NameEvent1Ch0"`, `"Name/NameEvent1Ch1"`... `"Name/NameEvent1Ch31"` ... `"Name/NameEvent2Ch0"`... `"Name/NameEvent{x}Ch32"`...
I want to create two lists, which match the characters after `Ch`, the last characters in the string. All the histograms of channels in `x_channels` should go into `analogues_x` and the others should go into `analogues_y`.
When there was only one moving part, that is when the strings were only named for the channel and not the event (`Name/NameCh{0-31}`) it was easy, I just did `analogues_x = [root_file.Get(f"Target/TargetCh{ch}") for ch in x_channels]`. Now that there's another variable I don't know how to do this in the most efficient way.
I'm extremely inexpert in regular expressions but it seems like this might be the way forward?
The following code:
```
x_channels = [8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0]
y_channels = [27,28,26,29,25,30,24,31,23,16,22,17,21,18,20,19]
analogues_x = [root_file.Get(re.compile(rf"Ch{ch}")) for ch in x_channels]
```
Gives me the error:
```
TypeError: bad argument type for built-in operation
``` |
Regular expression matching variable at end of string |
The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work.
There is no promise that an exception will be thrown, or that an error message will be displayed.
The specific language in the C++ Standard appears in Section 6.7.5.1 [basic.stc.general], where [item 4](https://eel.is/c++draft/basic.memobj#basic.stc.general-4) states, "Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior." |
i know you're able to do constant variables in lua now with <const>, but they seem to only work with local variables:
local myNumber <const> = 10 -- This works perfectly fine
myGlobalNumber <const> = 10 -- This causes an error
Is it possible to have constant global variables as well?
myGlobalNumber <const> = 10 |
global const variables in lua 5.4 |
|lua|fivem| |
null |
want to import HuggingFaceInferenceAPI.
from llama_index.llms import HugggingFaceInferenceAPI
llama_index.llms documentation doesnot have HugggingFaceInferenceAPI module. Anyone has update on this? |
ImportError: cannot import name 'HuggingFaceInferenceAPI' from 'llama_index.llms' (unknown location) |
|python|machine-learning|langchain|huggingface|llama-index| |
|c++|sfml|trigonometry| |
Issue while deploying JDK 17 and Spring 6 application in Tomcat 10.1.20 |
i know you're able to do constant variables in lua now with `<const>`, but they seem to only work with local variables:
`local myNumber <const> = 10 -- This works perfectly fine`
`myGlobalNumber <const> = 10 -- This causes an error`
Is it possible to have constant global variables as well?
`myGlobalNumber <const> = 10` |
I have a timer in my app that updates the current time on the UI and checks against a set time to trigger an event. However, my app crashes when the timer fires. The crash logs point to ViewController.TimeUp() and closure #1 in ViewController.updateTimer(). Here's a simplified version of the stack trace and related code:
>Crashed: com.apple.main-thread 0 EarAlarm 0x3677c AlarmViewController.TimeUp() + 4375193468 (<compiler-generated>:4375193468) 1 EarAlarm 0x297e8 closure #1 in AlarmViewController.updateCurrentTime() + 971 (AlarmViewController.swift:971) 2 EarAlarm 0x4dd98 thunk for @escaping @callee_guaranteed () -> () + 4375289240 (<compiler-generated>:4375289240) 3 libdispatch.dylib 0x26a8 <redacted> + 32 4 libdispatch.dylib 0x4300 <redacted> + 20 5 libdispatch.dylib 0x12998 <redacted> + 984 6 libdispatch.dylib 0x125b0 _dispatch_main_queue_callback_4CF + 44 7 CoreFoundation 0x36f9c <redacted> + 16 8 CoreFoundation 0x33ca8 <redacted> + 1996 9 CoreFoundation 0x333f8 CFRunLoopRunSpecific + 608 10 GraphicsServices 0x34f8 GSEventRunModal + 164 11 UIKitCore 0x22c8a0 <redacted> + 888 12 UIKitCore 0x22bedc UIApplicationMain + 340 13 EarAlarm 0x40bfc main + 22 (AppDelegate.swift:22) 14 ??? 0x1aec46dcc (シンボルが不足しています)`
Related code snippet:
```
import UIKit
import AVFoundation
import MediaPlayer
import AudioToolbox
import UserNotifications
import FirebaseCore
import GoogleMobileAds
import FirebaseAnalytics
class AlarmViewController: UIViewController, UNUserNotificationCenterDelegate {
let userDefaults = UserDefaults.standard
var appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
@IBOutlet weak var bannerView: GADBannerView!
@IBOutlet weak var bannerViewBig: GADBannerView!
var heightConstraint : NSLayoutConstraint?
var MPplayer: MPMusicPlayerController!
var MPplayerState: MPMusicPlaybackState!
var displayTimer: Timer?
var timer: Timer?
var snoozeTimer: Timer?
var vibrationTimer: Timer?
var SlowlyVolumeTimer: Timer?
var AudioPlayerSlowlyVolumeTimer: Timer?
var currentTime: String?
var df = DateFormatter()
var hourFormat = DateFormatter()
var minuteFormat = DateFormatter()
var nowHourStr : String?
var nowMinuteStr : String?
var nowHourInt : Int?
var nowMinuteInt : Int?
var setHour : Int?
var setMinute : Int?
var residueTime : Int?
var residueSeconds : Int?
let audioSession = AVAudioSession.sharedInstance()
var mpVolumeSlider = UISlider()
var SaveUserVolume : Float!
var MPplayerPlayingInt : Int!
var longPressTimer: Timer?
var slowlyInt : Int!
var slowlyFlo : Float!
var CurrentVolumeFlo : Float!
var SavedVolumeFlo : Float!
var CurrentSaveFlo : Float!
var SlowlyVolumeChangeFlo : Float!
var audioPlayeSlowlyVolumeChangeFlo : Float!
var audioPlayer:AVAudioPlayer!
var IntroductionPlayer:AVAudioPlayer!
var iPodSongTitle : String? = nil
var iPodUrl : NSURL? = nil
var SongTitle : String? = nil
var snoozeInt : Int!
var snoozeSetTimeSec : Int!
var snoozeTimeSec : Int!
var snoozeDisplaySec : Int!
var snoozeDisplayMin : Int!
var vibrationCount = 5
var introductionStopTimeSecInt : Int!
var nowIntroductionStopTimeSecInt : Int!
var notificationContent = UNMutableNotificationContent()
var alreadyTimeUp : Bool!
var AlarmTitleKey: String!
var iPodAlarmTitleKey: String!
var UseiPodKey: String!
var AlarmVolumeKey: String!
var iPodAlarmURLKey: String!
var slowlyKey: String!
var SnoozeKey: String!
var VibKey: String!
var IntroductionTitleKey: String!
var iPodIntroductionTitleKey: String!
var IntroductionUseiPodKey: String!
var IntroductionVolumeKey: String!
var IntroductionStopTimeKey: String!
var iPodIntroductionURLKey: String!
var iPodIntroductionAlbumArtDataKey: String!
@IBOutlet var NowTimeLabel: UILabel!
@IBOutlet var SetTimeLabel: UILabel!
@IBOutlet var niAlarmLabel: UILabel!
@IBOutlet var systemVolumeLabel: UILabel!
@IBOutlet var volumeParentView: UIView!
@IBOutlet var slider: UISlider!
@IBOutlet weak var UpMainVolumeBtn: UIButton!
@IBOutlet weak var DownMainVolumeBtn: UIButton!
@IBOutlet var SnoozeButton: UIButton!
@IBOutlet var HaikeiImageView: UIImageView!
@IBOutlet weak var nativeAdPlaceholder: UIView!
override func viewDidLoad() {
super.viewDidLoad()
setupVolumeSlider()
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
do {
try audioSession.setActive(true)
} catch {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {//1秒後に処理する
//ここに処理
do {
try self.audioSession.setActive(true)
} catch {
print("audioSession ラストエラー")
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
}
}
}
}
}
let KillNotificationCenter = NotificationCenter.default
KillNotificationCenter.addObserver(
self,
selector: #selector(SyuuryouKeikoku),
name:UIApplication.willTerminateNotification,
object: nil)
SnoozeButton.isHidden = true
SnoozeButton.isEnabled = false
niAlarmLabel.text = ""
setTimer()
let longPress5Up = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressUpMainVolume(gesture:)))
longPress5Up.minimumPressDuration = 0.3
UpMainVolumeBtn.addGestureRecognizer(longPress5Up)
let longPress1Up = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressDownMainVolume(gesture:)))
longPress1Up.minimumPressDuration = 0.3
DownMainVolumeBtn.addGestureRecognizer(longPress1Up)
nativeAdPlaceholder.alpha = 0
prepareIntroductionMuonAudioPlayer()
IntroductionPlayer.play()
admob()
admobBig()
}
func getFileURL(fileName: String) -> URL {
let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return docDir.appendingPathComponent(fileName)
}
func setTimer() {
setHour = appDelegate.SettingAlarmTimeHour
setMinute = appDelegate.SettingAlarmTimeMiunte
SetTimeLabel.text = "\(String(format: "%02d", setHour!)) : \(String(format: "%02d", setMinute!))"
self.userDefaults.set(appDelegate.AlarmNumber, forKey: "savedAlarmNumber")
self.userDefaults.set(setHour, forKey: "savedAlarmHourInsurance")
self.userDefaults.set(setMinute, forKey: "savedAlarmMinuteInsurance")
nowIntroductionStopTimeSecInt = 0
introductionStopTimeSecInt = userDefaults.integer(forKey: IntroductionStopTimeKey)
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
displayNowTime()
displayTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateNowTimeLabel), userInfo: nil, repeats: true)
AtoHowManyMinutesLater()
if residueTime! > 1434
{
} else
{
setTrigger()
}
}
@objc private func updateCurrentTime(){
df.locale = Locale(identifier: "en_US_POSIX")
hourFormat.locale = Locale(identifier: "en_US_POSIX")
minuteFormat.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "HH:mm:ss"
hourFormat.dateFormat = "HH"
minuteFormat.dateFormat = "mm"
df.timeZone = TimeZone.current
hourFormat.timeZone = TimeZone.current
minuteFormat.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
let timezoneDateH = hourFormat.string(from: Date())
let timezoneDateM = minuteFormat.string(from: Date())
currentTime = timezoneDate
nowHourStr = timezoneDateH
nowMinuteStr = timezoneDateM
nowHourInt = Int(nowHourStr!)
nowMinuteInt = Int(nowMinuteStr!)
NowTimeLabel.text = currentTime
AtoHowManyMinutesLater()
nowIntroductionStopTimeSecInt = nowIntroductionStopTimeSecInt + 1
if nowIntroductionStopTimeSecInt == introductionStopTimeSecInt {
IntroductionPlayer.volume = 0
}
if(nowHourInt == setHour && nowMinuteInt == setMinute){
if timer!.isValid {
timer?.invalidate()
}
if alreadyTimeUp == true {
} else {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.TimeUp()
}
}
}
}
func AtoHowManyMinutesLater(){
var residueTimeHour = 0
var residueTimeMinute = 0
let setAlarmMinute = setHour! * 60 + setMinute!
let nowTimeMinute = nowHourInt! * 60 + nowMinuteInt!
residueTime = setAlarmMinute - nowTimeMinute
if residueTime! > 0
{
if residueTime! < 60
{
residueTimeMinute = residueTime!
} else if residueTime! >= 60
{
residueTimeHour = residueTime! / 60
residueTimeMinute = residueTime! % 60
}
} else if residueTime! < 0
{
residueTime = setAlarmMinute + 1440 - nowTimeMinute
if residueTime! < 60
{
} else if residueTime! >= 60
{
residueTimeHour = residueTime! / 60
residueTimeMinute = residueTime! % 60
}
}
let hourSt = NSLocalizedString("時間", comment: "")
let minutesSt = NSLocalizedString("分", comment: "")
let goSt = NSLocalizedString("後", comment: "")
if residueTimeHour <= 0
{
if residueTimeMinute > 1
{
niAlarmLabel.text = "\(residueTimeMinute)\(minutesSt)\(goSt)"//分後
} else if residueTimeMinute <= 1
{
niAlarmLabel.text = NSLocalizedString("1分以内", comment: "")
}
}
else if residueTimeHour > 0
{
niAlarmLabel.text = "\(residueTimeHour)\(hourSt)\(residueTimeMinute)\(minutesSt)\(goSt)"//時間 分後
}
}
@objc private func updateNowTimeLabel(){
displayNowTime()
}
func displayNowTime() {
df.locale = Locale(identifier: "en_US_POSIX")
hourFormat.locale = Locale(identifier: "en_US_POSIX")
minuteFormat.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "HH:mm:ss"
hourFormat.dateFormat = "HH"
minuteFormat.dateFormat = "mm"
df.timeZone = TimeZone.current
hourFormat.timeZone = TimeZone.current
minuteFormat.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
let timezoneDateH = hourFormat.string(from: Date())
let timezoneDateM = minuteFormat.string(from: Date())
currentTime = timezoneDate
NowTimeLabel.text = currentTime
nowHourStr = timezoneDateH
nowMinuteStr = timezoneDateM
nowHourInt = Int(nowHourStr!)
nowMinuteInt = Int(nowMinuteStr!)
}
func TimeUp() {
if Thread.isMainThread {
print("MainThreadです TimeUp")
} else {
print("MainThreadではない TimeUp")
}
alreadyTimeUp = true
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
niAlarmLabel.text = ""
if IntroductionPlayer == nil {
} else {
if(IntroductionPlayer.isPlaying) {
IntroductionPlayer.stop()
}
}
prepareAudioPlayer()
SaveUserVolume = mpVolumeSlider.value
let useiPod = userDefaults.integer(forKey: UseiPodKey)
if useiPod == 2 {
} else {
MPplayer = MPMusicPlayerController.systemMusicPlayer
MPplayerState = MPplayer.playbackState
if MPplayerState == MPMusicPlaybackState.playing{
MPplayer.pause()
MPplayerPlayingInt = 1
}
if AVAudioSession.sharedInstance().isOtherAudioPlaying {
}
}
let AlarmVolumeFlo = userDefaults.float(forKey: AlarmVolumeKey)
slowlyInt = userDefaults.integer(forKey: slowlyKey)
audioPlayer.volume = 0
if slowlyInt == 0 {
audioPlayer.volume = 1
mpVolumeSlider.value = AlarmVolumeFlo
slider?.value = self.mpVolumeSlider.value
} else {
slowlyFlo = Float(slowlyInt)
audioPlayeSlowlyVolumeChangeFlo = 0
if AlarmVolumeFlo > SaveUserVolume{
CurrentVolumeFlo = SaveUserVolume
SavedVolumeFlo = AlarmVolumeFlo
CurrentSaveFlo = SavedVolumeFlo - CurrentVolumeFlo
SlowlyVolumeChangeFlo = CurrentVolumeFlo
SlowlyVolumeTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(SlowlyVolume), userInfo: nil, repeats: true)
} else {
mpVolumeSlider.value = AlarmVolumeFlo
slider?.value = self.mpVolumeSlider.value
}
AudioPlayerSlowlyVolumeTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(AudioPlayerSlowlyVolume), userInfo: nil, repeats: true)
}
audioPlayer.play()
let vibInt = userDefaults.integer(forKey: VibKey)
if vibInt == 0 {
vibrationTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(VibrationTimerAction), userInfo: nil, repeats: true)
}
push()
snoozeSwitch()
}
}
```
---------------------------
2024/3/31 update
I previously asked a question about my app crashing when a timer fires, pointing to ViewController.TimeUp() and a closure in ViewController.updateTimer(). I received some helpful suggestions, which I've implemented, but my app still crashes. Below are the changes I made based on the recommendations:
Original code:
```
// Inside setTimer, lines 841 to 846
// Retrieving the set alarm time
setHour = appDelegate.SettingAlarmTimeHour
setMinute = appDelegate.SettingAlarmTimeMiunte
SetTimeLabel.text = "\(String(format: "%02d", setHour!)) : \(String(format: "%02d", setMinute!))"
```
Updated code:
```
// Invalidate any existing timer before creating a new one
timer?.invalidate()
guard let setHour = appDelegate.SettingAlarmTimeHour,
let setMinute = appDelegate.SettingAlarmTimeMiunte else {
return
}
self.setHour = setHour
self.setMinute = setMinute
SetTimeLabel.text = "\(String(format: "%02d", setHour)) : \(String(format: "%02d", setMinute))"
```
Original Timer scheduling:
```
// Inside setTimer
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
```
Updated Timer scheduling:
```
// Using a closure-based timer to avoid strong reference cycles
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
self?.updateCurrentTime()
}
```
Despite these changes, the app continues to crash with similar crash logs pointing to the same methods as before. I made sure to invalidate any previous timers before setting a new one and used [weak self] in closures to prevent strong reference cycles. However, the issue persists.
Questions:
Are there any additional steps I should consider to properly manage the timer and avoid crashes?
Could there be another underlying issue with my implementation that I might be overlooking?
I appreciate any further insight or suggestions that could help resolve this crash issue. Thank you in advance for your help.
|
null |
i know you're able to do constant variables in lua now with `<const>`, but they seem to only work with local variables:
`local myNumber <const> = 10 -- This works perfectly fine`
`myGlobalNumber <const> = 10 -- This causes an error`
Is it possible to have constant global variables as well?
`myGlobalNumber <const> = 10` |
This example is not a good example, because `java.lang.NullPointerException` could be just anything - and therefore one can't even tell by such example, what the culprit or remedy to it would by. Usually one has to check for files not being checked in into version-control, if they're indeed present, which already catches most of the possible issues. For example, this would conditionally load a file - or log a proper warning:
```
File keystoreConfig = rootProject.file('keystore.properties');
if (keystoreConfig.exists()) {
def keystore = new Properties()
def is = new FileInputStream(keystoreConfig)
keystore.load(is)
// some values are being assigned in here.
is.close()
} else {
println "file missing: ${keystoreConfig}"
}
``` |
This happens because you are using ***Input.GetAxisRaw("Horizontal")***, In the Unity editor, Horizontal Axis is Defined as Both A,D And Left,Right Keys, There are a few solutions, Two of the easiest are as such:
1) Change GetAxisRaw, Use the specific Keys you want for each direction (This is kind of a lazy solution)
2) In the editor prefrences, change the axis keys to whichever you would like over at Edit > Project Settings > Input Manager > Axes > Horizontal / Vertial > Button + Alt Buttons
[1]: https://i.stack.imgur.com/rLgrk.png |
You need to center your [`rolling`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html) windows with `center=True`:
```
window = 12
hourly = df.resample(rule="h").median()
hourly["ma"] = hourly["TEC"].rolling(window=window, center=True).mean()
hourly["hour"] = hourly.index.hour
hourly["std_err"] = hourly["TEC"].rolling(window=window, center=True).std()
hourly["ub"] = hourly["ma"] + (1.67* hourly["std_err"])
hourly["lb"] = hourly["ma"] - (1.67* hourly["std_err"])
hourly["sig2"] = hourly["TEC"].rolling(window=window, center=True).var()
hourly["kur"] = hourly["TEC"].rolling(window=window, center=True).kurt()
hourly["pctChange"] = hourly.TEC.pct_change(12, fill_method="bfill")
hourly = hourly.dropna()
dTEC = hourly[(hourly["TEC"] > hourly["ub"])]
```
Output:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/aYJm3.png |
i have string ```"This auction will run from Friday 28 July - Monday 7 August. It will close from 7pm (GMT) on Monday 7 August 2023. Read here for information on how our auctions end."```
and im trying to get dates from this string
this is regex that i wrote and in regex checker site((\d{1,2} \w+(?: \d{4})?)) it matches for 28 july, 7 august and 7 august 2023, but in javascript it only matches for 7 august and 7 august 2023, whats wrong?
[enter image description here][1]
[1]: https://i.stack.imgur.com/2Kwzm.png |
How Can I make the height of the sidebar 100% in MUI |
I have a question.
What is the unit of the number which is shown when I type **swapon** with **-s** option. (in Ubuntu 16.04 LTS on oracle VM vertualbox, type : 64-bit)
Namely when I type
$ sudo swapon -s
| Filename | Type | Size | Used | Priority |
-
| /dev/sda5 | partition | 4192252 | 0 | -1 |
what is the unit of **4192252** ?
Note. 2^(20) = 4194304
Thanks in advance. |
i have string ```"This auction will run from Friday 28 July - Monday 7 August. It will close from 7pm (GMT) on Monday 7 August 2023. Read here for information on how our auctions end."```
and im trying to get dates from this string
this is regex that i wrote and in regex checker site((\d{1,2} \w+(?: \d{4})?)) it matches for 28 july, 7 august and 7 august 2023, but in javascript it only matches for 7 august and 7 august 2023, whats wrong?
[output][1]
[1]: https://i.stack.imgur.com/2Kwzm.png |
Alert! I am feeling so embarassed asking such an entry level question here!!!!
Hey guys, I have been working on a project that involves timeseries total electron content data. My goal is to apply statistical analysis and find anomalies in TEC due to earthquake.
I am following this research paper for sliding IQR method. But for some reason I am not getting results as shown in the paper with the given formulas. So I decided to use the rolling mean + 1.6 STD method.
The problem is when I use ax.fill_between(x1 = index, y1 = ub, y2=lb) method my confidence interval band is being plotted a step further than the data point. Please see the given figure for a better understanding.
Here's what I am currently doing:
```
df = DAEJ.copy()
window = 12
hourly = df.resample(rule="h").median()
hourly["ma"] = hourly["TEC"].rolling(window=window).mean()
hourly["hour"] = hourly.index.hour
hourly["std_err"] = hourly["TEC"].rolling(window=window).std()
hourly["ub"] = hourly["ma"] + (1.67* hourly["std_err"])
hourly["lb"] = hourly["ma"] - (1.67* hourly["std_err"])
hourly["sig2"] = hourly["TEC"].rolling(window=window).var()
hourly["kur"] = hourly["TEC"].rolling(window=window).kurt()
hourly["pctChange"] = hourly.TEC.pct_change(12, fill_method="bfill")
hourly = hourly.dropna()
dTEC = hourly[(hourly["TEC"] > hourly["ub"])]
fig, ax = plt.subplots(figsize=(12,4))
hourly["TEC"].plot(ax=ax, title="TEC Anomaly", label="Station: DAEJ")
ax.fill_between(x=hourly.index, y1=hourly["ub"], y2=hourly["lb"], color="red", label="Conf Interval", alpha=.4)
ax.legend()
```
And here's the result I got!

as seen in the given figure the data and the colored band aren't alinged properly, I know after calculating a rolling mean with a window of 12 hours will result in a 12 hour shifted value but even after dropping the first values I am still not getting an aligned figure. |
In the vue project, I have a `LoginView.vue` subpage in the `views` folder, in which I would like to link to an ASP.NET Core MVC project in which I use the ASP.NET Core Identity for the login/user registration form.
When sending a request from vue to ASP.NET Core MVC, I get an error http 400, I am 100% sure that my login details are correct.
I previously added exceptions such as CORS support to get rid of locks on the ASP.NET Core MVC side.
`LoginView.vue`:
```
<template>
<div>
<h2>Hello</h2>
<hr />
<div class="form-floating mb-3">
<input v-model="email" type="email" class="form-control" autocomplete="username" aria-required="true" />
<label for="email" class="form-label">Email</label>
</div>
<div class="form-floating">
<input v-model="password" type="password" class="form-control" autocomplete="current-password"
aria-required="true" />
<label for="password" class="form-label">Password</label>
</div>
<div class="form-check">
<input v-model="rememberMe" type="checkbox" class="form-check-input" id="rememberMe" />
<label class="form-check-label" for="rememberMe">Remember Me</label>
</div>
<button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>
</div>
</template>
<script>
import axios from 'axios';
const API_URL = "http://localhost:5211/";
export default {
data() {
return {
email: '',
password: '',
rememberMe: false
};
},
methods: {
login() {
const loginData = {
email: this.email,
password: this.password,
rememberMe: this.rememberMe
};
axios.post(API_URL + 'identity/Account/Login', loginData)
.then(response => {
console.log('Login response:', response.data);
console.log("Email:", this.email);
console.log("Password:", this.password);
})
.catch(error => {
console.error('Error during login:', error);
});
}
}
}
</script>
<style scoped></style>
```
ASP.NET Core MVC project - `Program.cs`:
```
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using AuthProject.Areas.Identity.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace AuthProject.Areas.Identity.Pages.Account
{
public class LoginModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (User.Identity.IsAuthenticated)
{
Response.Redirect("/");
}
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl ??= Url.Content("~/");
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
return Page();
}
}
}
```
When I enter login data (works in ASP.NET Core MVC) in the vue form after submitting the order using the Log in button, I get a response in the browser console
POST http://localhost:5211/identity/Account/Login
> 400 (Bad Request)
>
> @LoginView.vue:44
> _createElementVNode.onClick._cache.<computed>._cache.<computed>
> @LoginView.vue:18
`@LoginView.vue`:43 code:
```
axios.post(API_URL + 'identity/Account/Login', loginData)
```
`@LoginView.vue`:18 code:
```
<button @click="login" type="button" class="w-100 btn btn-lg btn-primary">Log in</button>
```
Second error:
 |
Problem sending HTTP post request from VUE to ASP.NET Core MVC project |
|axios|asp.net-core-mvc|vuejs3|asp.net-core-identity| |
resolve:you need to wrap the root component of the paths in which you have an `<Outlet />` in `<Provider />` (for me it was an `<App/>` component, then when you send Routes via module federation, you already have a redux context. |
https://github.com/SnailSword/npm-shovel
```
npx npm-shovel react
```
output:
```
react's dependencies:
||--react
| |--loose-envify@^1.1.0
| |--js-tokens@^3.0.0 || ^4.0.0
| |--object-assign@^4.1.1
| |--prop-types@^15.6.2
| |--loose-envify@^1.4.0
| |--js-tokens@^3.0.0 || ^4.0.0 *
| |--object-assign@^4.1.1 *
| |--react-is@^16.8.1
``` |
{"Voters":[{"Id":1431750,"DisplayName":"aneroid"},{"Id":14732669,"DisplayName":"ray"},{"Id":13376511,"DisplayName":"Michael M."}],"SiteSpecificCloseReasonIds":[18]} |
I started gVim lately in offline window pc.
Specification is below...
gVim - 9.1.0211 -64bit
python - windows embedded 3.11.8 (pandas 2.2.1) - 64bit
vimrc - filetype plugin indent on &_
set omnifunc=syntaxcomplete#Complete
After typing "import pandas as pd pd.", I pressed `<C-x><C-o>` then it shows "pattern not matched" So I tested in vim `:echo has("python3")` then it returns `1`, and `:python3 import pandas` then it says `ImportError: DLL load failed while importing aggregations`.
In terminal, pandas is normally imported (python3 >> import pandas as pd >> ...)
Import numpy and omnifunc works well, modules related to pandas doesn't work. I installed vc_redist.64x but not solved.
Has anyone this problem like this? I need some help, Thanks.
since my pc is local (no internet connection) and remote environment,
so I don't have any verbose. sorry.
1. Check c:\windows\system32 and found msvcp140.dll and concrt140.dll
2. Install jedi-vim and failed load module(pandas) but after quit the error message autocompleting works partially and the error occurs again and again
3. Try Neovim (installed pynvim) and omnifunc works |
Disclaimer: this is only a proof of concept - not a suggestion that this would be good or bad - I leave that to you to decide.
## Component Activation
Blazor has the ability to control component activation through an instance of the `IComponentActivator` interface.
The default one is called [`DefaultComponentActivator`][1] if you care to inspect it.
You can provide your own through DI like this:
```c#
builder.Services.AddSingleton<IComponentActivator,MyComponentActivator>();
```
`MyComponentActivator` is now used by the Renderer to create instances of Components as they are needed.
A quick copy paste of the `DefaultComponentActivator` and a bit of tweaking to use DI gives you something like this:
`MyComponentActivator`
```c#
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components;
public class MyComponentActivator(IServiceProvider serviceProvider) : IComponentActivator
{
public IComponent CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type componentType)
{
var resolvedType = serviceProvider.GetService(componentType);
if (resolvedType is IComponent component)
{
return component;
}
return DefaultCreateInstance(componentType);
}
/* Code below here is (c) Microsoft - taken from DefaultComponentActivator */
private static readonly ConcurrentDictionary<Type, ObjectFactory> _cachedComponentTypeInfo = new();
public static void ClearCache() => _cachedComponentTypeInfo.Clear();
/// <inheritdoc />
public IComponent DefaultCreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type componentType)
{
if (!typeof(IComponent).IsAssignableFrom(componentType))
{
throw new ArgumentException($"The type {componentType.FullName} does not implement {nameof(IComponent)}.", nameof(componentType));
}
var factory = GetObjectFactory(componentType);
return (IComponent)factory(serviceProvider, []);
}
private static ObjectFactory GetObjectFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type componentType)
{
// Unfortunately we can't use 'GetOrAdd' here because the DynamicallyAccessedMembers annotation doesn't flow through to the
// callback, so it becomes an IL2111 warning. The following is equivalent and thread-safe because it's a ConcurrentDictionary
// and it doesn't matter if we build a cache entry more than once.
if (!_cachedComponentTypeInfo.TryGetValue(componentType, out var factory))
{
factory = ActivatorUtilities.CreateFactory(componentType, Type.EmptyTypes);
_cachedComponentTypeInfo.TryAdd(componentType, factory);
}
return factory;
}
}
```
The `CreateInstance` method has been written to use DI to locate and activate component instances - with a fallback to the default component activation when DI doesn't resolve anything.
_reader task: can we instead inject the default IComponentActivator into MyComponentActivator so we don't need to copy the code???_
## Don't use Interfaces
When you write Blazor code, the compiler requires design time knowledge of components, and interfaces won't work.
You can't simply write
`<ITeacherInlineDisplay/>`
as it will not be recognised as a component.
## Extend a base component
Create a bare bones base component `TeacherInlineDisplay` (in a shared library as you would for the interface) which has the "interface" you want to use ( e.g. virtual parameters )
`TeacherInlineDisplay`
```c#
public class TeacherInlineDisplay : ComponentBase
{
[Parameter] public virtual int? TeacherID { get; set; }
}
```
And then inherit/extend that base class in your `Teacher` project/components.
e.g. `TeacherInlineLocal`
```c#
@* Inside the Teacher project *@
@inherits TeacherInlineDisplay
<div>
@Teacher.Name
@* Complex stuff in here: context menu, drag + drop etc. *@
</div>
@code {
[Parameter] public override int? TeacherId { get; set;}
}
```
## Wrapping it all up
You can now register component implementations in DI like this:
```c#
builder.Services.AddTransient<TeacherInlineDisplay, TeacherInlineLocal>();
```
And place the base component on the page like this:
```html
@* Inside the student project *@
@page "/student/view
<div>
My tearcher is <TeacherInlineDisplay TeacherId="@Student.TeacherId"/>
<br/>
</div>
```
And the component `TeacherInlineDisplay` will be resolved from DI.
[1]: https://github.com/dotnet/aspnetcore/blob/main/src/Components/Components/src/DefaultComponentActivator.cs |
I have to write a c code where for input 4 the output will be
444 4 444
433 3 334
432 2 234
433 3 334
444 4 444
if the input is 2
the
222
212
222
plz help me in that case , I have found the pattern but cant able to execute
plz give me a direction |