instruction stringlengths 0 30k ⌀ |
|---|
With sprint boot 3.1.5 in two microservices, one using FeignClient to request to the other microservice , I have this properties configuration in both microservices:
management:
tracing:
propagation:
produce: b3
consume: b3
brave:
span-joining-supported: true
logging:
pattern:
level: "%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-},%X{parentId:-}]"
I have next library in both poms:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
<version>1.1.6</version>
</dependency>
I have this FeignConfiguration lets called in microservice A to get the context propagated to the microservice B:
@Configuration
public class FeignConfiguration {
@Bean
public Capability capability(final MeterRegistry registry) {
return new MicrometerCapability(registry);
}
}
I have this in order to log PARENT_ID in both microservices and is working fine:
@Configuration
public class BraveTracerConfig {
@Bean
CorrelationScopeCustomizer parentIdCorrelationScopeCustomizer() {
return builder -> builder.add(SingleCorrelationField.create(BaggageFields.PARENT_ID));
}
}
When microservice A calls microservice B, traceId is propagated but I dont see in microservice B in the logs the spanId or parentId logged in the feignClient from the microservice A, they are different except for traceId. According to the brave configuration I used, it is supposed I can get it according to this [https://github.com/spring-projects/spring-boot/pull/35165][1], right?
Thanks!
[1]: https://github.com/spring-projects/spring-boot/pull/35165 |
I discovered recently mlflow Databricks so I'm very very new to this
Can someone explain for me clearly the steps to track my runs into the databricks API.
Here is the steps I followed :
1/ install Databricks CLI
2/ I sewed up authentication between Databricks CLI and my Databricks workspaces according to instructions here [text](https://docs.databricks.com/en/dev-tools/cli/authentication.html#token-auth)
I checked the file cat ~/.databrickscfg and everything is fine
3/
I'm using Pycharm and I'm writing a python script including mlflow and I want to track the runs on my Databricks workspace
Here is a part of my code :
```
mlflow.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
disable=False,
exclusive=False,
disable_for_unsupported_versions=True,
silent=False
)
#mlflow.login()
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment("mlflowAUS")
with mlflow.start_run() as run:
bestModel.fit(X_train, y_train)
y_pred = bestModel.predict(X_test)
runId = run.info.run_id
mlflow.set_tag('mlflow.runName', datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
mlflow.log_param("model_name", str(bestModel)[: str(bestModel).index("(")])
```
and if I add to my code :
```
mlflow.login()
```
I got another time the same error but before the error I got : (I hided my the link with xxxx )
```
2024/03/30 01:40:44 INFO mlflow.utils.credentials: Successfully connected to MLflow hosted tracking server! Host: https://dbc-xxxxxx-xxxx.cloud.databricks.com.
```
What I don't understand if it says that I'm successfully connected after adding mlflow.login() why I still got the same error and I can't track my runs ?
Please help me and I thank you in advance for the support
this code return error :
```
Traceback (most recent call last):
File "/Users/kevin/PycharmProjects/Projects2024/nov23_continu_mlops_meteo/src/models/bestModel.py", line 184, in <module>
mlflow.set_experiment("mlflowAUS")
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/tracking/fluent.py", line 142, in set_experiment
experiment = client.get_experiment_by_name(experiment_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/tracking/client.py", line 539, in get_experiment_by_name
return self._tracking_client.get_experiment_by_name(name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/tracking/_tracking_service/client.py", line 236, in get_experiment_by_name
return self.store.get_experiment_by_name(name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/store/tracking/rest_store.py", line 323, in get_experiment_by_name
response_proto = self._call_endpoint(GetExperimentByName, req_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/store/tracking/rest_store.py", line 60, in _call_endpoint
return call_endpoint(self.get_host_creds(), endpoint, method, json_body, response_proto)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/utils/rest_utils.py", line 220, in call_endpoint
response = verify_rest_response(response, endpoint)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kevin/opt/anaconda3/envs/env_2023/lib/python3.11/site-packages/mlflow/utils/rest_utils.py", line 170, in verify_rest_response
raise MlflowException(f"{base_msg}. Response body: '{response.text}'")
mlflow.exceptions.MlflowException: API request to endpoint was successful but the response body was not in a valid JSON format. Response body: '<!doctype html>
``` |
"""hello.
this code is runing,
versions:
Python==3.11.1
opencv-contrib-python==4.9.0.80
opencv-python==4.9.0.80
in this case we have "DICT_7X7_100" but you can change to "DICT_5X5_100", you must to change en 3 lines of this program"""
import numpy as np
import cv2
import sys
import time
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DICT_4X4_250": cv2.aruco.DICT_4X4_250,
"DICT_4X4_1000": cv2.aruco.DICT_4X4_1000,
"DICT_5X5_50": cv2.aruco.DICT_5X5_50,
"DICT_5X5_100": cv2.aruco.DICT_5X5_100,
"DICT_5X5_250": cv2.aruco.DICT_5X5_250,
"DICT_5X5_1000": cv2.aruco.DICT_5X5_1000,
"DICT_6X6_50": cv2.aruco.DICT_6X6_50,
"DICT_6X6_100": cv2.aruco.DICT_6X6_100,
"DICT_6X6_250": cv2.aruco.DICT_6X6_250,
"DICT_6X6_1000": cv2.aruco.DICT_6X6_1000,
"DICT_7X7_50": cv2.aruco.DICT_7X7_50,
"DICT_7X7_100": cv2.aruco.DICT_7X7_100,
"DICT_7X7_250": cv2.aruco.DICT_7X7_250,
"DICT_7X7_1000": cv2.aruco.DICT_7X7_1000,
"DICT_ARUCO_ORIGINAL": cv2.aruco.DICT_ARUCO_ORIGINAL,
"DICT_APRILTAG_16h5": cv2.aruco.DICT_APRILTAG_16h5,
"DICT_APRILTAG_25h9": cv2.aruco.DICT_APRILTAG_25h9,
"DICT_APRILTAG_36h10": cv2.aruco.DICT_APRILTAG_36h10,
"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}
def aruco_display(corners, ids, rejected, image):
if len(corners) > 0:
ids = ids.flatten()
for (markerCorner, markerID) in zip(corners, ids):
corners = markerCorner.reshape((4, 2))
(topLeft, topRight, bottomRight, bottomLeft) = corners
topRight = (int(topRight[0]), int(topRight[1]))
bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
topLeft = (int(topLeft[0]), int(topLeft[1]))
cv2.line(image, topLeft, topRight, (0, 255, 0), 2)
cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)
cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)
cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)
cX = int((topLeft[0] + bottomRight[0]) / 2.0)
cY = int((topLeft[1] + bottomRight[1]) / 2.0)
cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)
cv2.putText(image, str(markerID),(topLeft[0], topLeft[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
print("[Inference] ArUco marker ID: {}".format(markerID))
return image
def pose_estimation(frame, aruco_dict_type, matrix_coefficients, distortion_coefficients):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_7X7_100) # cv2.aruco.DICT_4X4_250 seleccion del modelo Aruco
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(dictionary, parameters)
corners, ids, rejected_img_points = detector.detectMarkers(gray)
if len(corners) > 0:
for i in range(0, len(ids)):
rvec, tvec, markerPoints = cv2.aruco.estimatePoseSingleMarkers(corners[i], 0.02, matrix_coefficients, distortion_coefficients)
cv2.aruco.drawDetectedMarkers(frame, corners)
cv2.drawFrameAxes(frame, matrix_coefficients, distortion_coefficients, rvec, tvec, 0.01)
return frame
aruco_type = "DICT_7X7_100"
arucoDict = cv2.aruco.DICT_7X7_100
arucoParams = cv2.aruco.DetectorParameters()
intrinsic_camera = np.array(((933.15867, 0, 657.59),(0,933.1586, 400.36993),(0,0,1)))
distortion = np.array((-0.43948,0.18514,0,0))
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while cap.isOpened():
ret, img = cap.read()
output = pose_estimation(img, ARUCO_DICT[aruco_type], intrinsic_camera, distortion)
cv2.imshow('Estimated Pose', output)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
If you used the **Free plan** of Vercel this caused the issue. Because it provides only **Edge runtime** but **JWT cannot run on Edge runtime**. You need to use an alternative for authorization (e.g.: [jose](https://www.npmjs.com/package/jose)) which is supported by Edge runtime.
In this discussion of official Vercel GitHub repo you can find an example implementation of jose: [https://github.com/vercel/next.js/issues/43115#issuecomment-1321785193](https://github.com/vercel/next.js/issues/43115#issuecomment-1321785193) |
I've verified I am recording an audio file correctly. I would now like to send it to open ai for speech to text. Here is my nextjs code pages/api/speechToText.js file:
import { OpenAI } from "openai";
const openai = new OpenAI(process.env.OPENAI_API_KEY);
export const config = {
api: {
bodyParser: false,
},
};
export default async function handler(req, res) {
const formidable = require("formidable");
const form = new formidable.IncomingForm();
form.parse(req, async (err, fields, files) => {
try {
const transcription = await openai.audio.transcriptions.create({
file: files.audio[0],
model: "whisper-1",
});
res.status(200).json({ transcription: transcription.text });
} catch (error) {
console.error("Error transcribing audio:", error);
res.status(500).json({ error: "Error processing your request" });
}
});
}
What am I doing wrong? |
I have a scenario when I need to operate on large array inside some inner function (a service) but result of this operation is to be consumed (serialized to JSON and returned over HTTP) by parent function:
```
public IActionResult ParentFunction()
{
var returnedArray = InnerFunction(1000);
return Ok(returnedArray.Take(1000));
}
public int[] InnerFunction(int count)
{
var rentedArray = _defaultArrayPool.Rent(count);
// make operation on rentedArray
return rentedArray;
}
```
In the above code obviously array is not returned to `_defaultArrayPool` thus it is never reused.
I considered several options, but I am willing to know what's the best implementation?
#### Option 1 - Return by parent function
*I don't like this option because Rent and Return are called in different parts of the code.*
```
public IActionResult ParentFunction()
{
int[] returnedArray = null;
try
{
returnedArray = InnerFunction(1000);
return Ok(returnedArray.Take(1000));
}
finally
{
if (returnedArray != null)
{
_defaultArrayPool.Return(returnedArray);
}
}
}
public int[] InnerFunction(int count)
{
var rentedArray = _defaultArrayPool.Rent(count);
// make operation on rentedArray
return rentedArray;
}
```
#### Option 2 - Rent and Return by parent function, and pass as reference
*It is better, but won't work if ParentFunction does not know the length/count upfront.*
```
public IActionResult ParentFunction()
{
var rentedArray = _defaultArrayPool.Rent(1000); // will not work if 'Count' is unknown here, and is to be determined by InnerFunction
try
{
InnerFunction(rentedArray, 1000);
return Ok(rentedArray.Take(1000));
}
finally
{
if (rentedArray != null)
{
_defaultArrayPool.Return(rentedArray);
}
}
}
public void InnerFunction(int[] arr, int count)
{
// make operation on arr
}
```
#### Option 3 - Rent and Return by different functions
*It will work when inner function is determining needed count/length*
```
public IActionResult ParentFunction()
{
int[] rentedArray = null;
try
{
var count = InnerFunction(out rentedArray);
return Ok(rentedArray.Take(count));
}
finally
{
if (rentedArray != null)
{
_defaultArrayPool.Return(rentedArray);
}
}
}
public int InnerFunction(out int[] arr)
{
int count = 1000; // determin lenght of the array
arr = _defaultArrayPool.Rent(count);
// make operation on arr
return count;
}
```
Are there any other better options? |
How to return array to ArrayPool when it was rented by inner function? |
|c#|arrays|.net| |
The following test has the purpose of ensure that any visitor is assigned a role
```
test "role for non logged in user" do
get root_path
puts ('role ' + @role.to_s)
assert @role == 'end consumer'
end
```
the role can change based on a join table where a shop is known via the host and the process is invoked in the application controller with
`before_action :set_clean_host_site` this method in turn calls a method in a concern to set the role
```
def set_clean_host_site
rurl = request.host
if request.subdomains.empty?
rurl = 'www.' + rurl
end
clean_host = rurl.chomp("/")
@site = Site.where('host = ?', clean_host.to_s).first
if @site
session[:active_shop_id] = @site.shop_id
@shop = Shop.find(@site.shop_id)
set_role
else
@shop = Shop.find(1)
puts @shop.inspect
session[:active_shop_id] = @shop.id
set_role
puts @role
end
end
def set_role
if current_user
cu_rsu = Roleshopuser.where('user_id = ? AND shop_id = ?', current_user.id, @shop.id ).first
if cu_rsu
@role = cu_rsu.role.name
end
else
@role = 'consumer'
end
puts @role
end
```
a `shops.yml` fixture contains:
```
id_one:
id: 1
name: MyString
nation: one
slug: MyString
```
Thus two observations are derived.
1) the fixture with its id (1) for a shop is not found. but that should not impede the method to complete..
2) the `set_role` should be fired; the method is a fallback to ensure a role is attributed. The "puts" yield [blank for shop]:
```
consumer
consumer
role
```
and thus the test visibly does not have access to the instance variable.
What is going on / wrong with this approach?
|
{"Voters":[{"Id":3730754,"DisplayName":"LoicTheAztec"},{"Id":11987538,"DisplayName":"7uc1f3r"},{"Id":839601,"DisplayName":"gnat"}]} |
I have a numpy array and corresponding row and column indices:
```
matrix = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,])
col_idx = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
```
I would like to unravel the matrix by the groups specified by row_idx and col_idx. In the case of this example, the row_idx are all zero, so the elements would unravel by columns:
```
result = np.array([0, 3, 6, 1, 4, 7, 2, 5, 8])
```
I have tried aggregate() from the numpy_groupies package, but it is both slow and returns an array combining np.arrays and ints (which makes further manipulation difficult and slow). Need something that will generalise to where the matrix has areas that are grouped by rows and other areas by columns based on the row_idx and col_idx. |
|python|numpy|array-broadcasting| |
I am having an issue. It just published my first project and now I am realising if you add an "/" to the end of the URL it does load in a very different way I cant even explain. When you add a "Trailingslash" some of the Buttons of the Website are not clickable and if I do this with ng serve the font is changing, I cant click buttons and I get a white border to the side. You can try it yourself on https://22ndspartans.de the issue is only on the discord page at https://22ndspartans.de/discord and the issues appear with https://22ndspartans./discord/.
I tried it on my localhost, I tried to do it with other browsers and other devices. I found this issue when I set up my google search indexing. When I clicked my Discord page directly from the search results it doesn't load any backgroundimage. At the begining the issue was on the other pages aswell. I am abolutely confused.
Sorry for the english I gave my best to explain it.
[you can see the white border and font here with Trailingslash][1] ---->
[How it should be (without trailingslash)][2]
Edit: I found out in the published version the Anchor to the homepage is not working when you have a trailingslash on any other page. The rest seems to be working. I am hosting with cloudflare. Maybe this has something to do with google search aswell. Idk
2nd Edit: Okay I found out that the main problem is the Trailingslash so how do I tell my application to redirect to no trailingslash if a trailingslash is called? Or how do I get my website to load correctly with Trailingslash
Updated code:
[HTML of DiscordComponent][3]---->[TS of DiscordComponent][4]---->[New appo.routes.ts][5]
[1]: https://i.stack.imgur.com/C9NOF.jpg
[2]: https://i.stack.imgur.com/58Pmk.jpg
[3]: https://i.stack.imgur.com/jJgZp.jpg
[4]: https://i.stack.imgur.com/jXYub.jpg
[5]: https://i.stack.imgur.com/wW4S9.jpg |
{"Voters":[{"Id":205233,"DisplayName":"Filburt"},{"Id":238704,"DisplayName":"President James K. Polk"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]} |
{"OriginalQuestionIds":[35236895],"Voters":[{"Id":530160,"DisplayName":"Nick ODell"},{"Id":12131013,"DisplayName":"jared"},{"Id":9214357,"DisplayName":"Zephyr"}]} |
{"Voters":[{"Id":349130,"DisplayName":"Dr. Snoopy"},{"Id":2602877,"DisplayName":"Christoph Rackwitz"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]} |
|c#|asp.net-mvc|entity-framework-core|asp.net-identity| |
null |
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField]
private float _enemySpeed = 1f;
private float _kamikazeSpeed = 6f;
private Player _player;
// handle to animator component
private Animator _animate;
private AudioSource _explosionSX;
private float _fireRate = 1.0f;
private float _canFire = -1f;
private float _enemyFrequency = 1.0f;
private float _enemyAmplitude = 5.0f;
private float _enemycycleSpeed = 1.0f;
private float _enemyAggressive = 3.0f;
[SerializeField]
float _rayCastRad = 8.5f;
[SerializeField]
float _rayDistance = 8.0f;
private Vector3 _enemyPos;
private Vector3 _enemyAxis;
[SerializeField]
private GameObject _enemyLaser;
[SerializeField]
private GameObject _shieldVisualizer;
private bool _isenemyshieldActive = false;
private int _randomshieldedEnemies;
[SerializeField]
private SpriteRenderer _shieldRenderer;
private int _shieldStrengh = 1;
private bool _isLaserDetected;
// Start is called before the first frame update
void Start()
{
_player = GameObject.Find("Player").GetComponent<Player>();
_explosionSX = GetComponent<AudioSource>();
_enemyPos = transform.position;
_enemyAxis = transform.right;
_randomshieldedEnemies = Random.Range(0, 7);
_enemyAggressive = Random.Range(0, 5);
//null check player
if (_player == null)
{
Debug.LogError("The Player is NULL.");
}
//assign the component
_animate = GetComponent<Animator>();
if (_animate == null)
{
Debug.LogError("The aninator is NULL");
}
_randomshieldedEnemies = Random.Range(0, 5);
if(_randomshieldedEnemies == 3)
{
ActiveShield();
}
}
// Update is called once per frame
void Update()
{
//move down at 4 meters per second
//if bottom of screen
//respawn at to with a new random x position
CalculateMovement();
if (Time.time > _canFire)
{
_fireRate = Random.Range(1f, 3f);
_canFire = Time.time + _fireRate;
GameObject enemyFire = Instantiate(_enemyLaser, transform.position, Quaternion.identity);
Laser[] lasers = enemyFire.GetComponentsInChildren<Laser>();
}
}
void CalculateMovement()
{
transform.Translate(Vector3.down * _enemySpeed * Time.deltaTime);
_enemySpeed = Random.Range(3f, 5f);
if (transform.position.y < -5f)
{
float randomX = Random.Range(-15f, 15f);
transform.position = new Vector3(randomX, 15, 0);
}
if (transform.position.x < 1)
{
_enemyPos += Vector3.down * Time.deltaTime * _enemycycleSpeed;
float randomX = Random.Range(-15f, 15f);
transform.position = _enemyPos + _enemyAxis * Mathf.Sin(Time.time * _enemyFrequency) * _enemyAmplitude;
_enemycycleSpeed = Random.Range(1f, 5.0f);
}
if(_player != null)
{
if (Vector3.Distance(transform.position, _player.transform.position)< _enemyAggressive)
{
KamikazePlayer();
}
}
}
public void ActiveShield()
{
_isenemyshieldActive = true;
_shieldVisualizer.SetActive(true);
}
private void KamikazePlayer()
{
if (transform.position.x < _player.transform.position.x)
{
transform.Translate(Vector3.right * _kamikazeSpeed * Time.deltaTime);
}
else if (transform.position.x > _player.transform.position.x)
{
transform.Translate(Vector3.left * _kamikazeSpeed * Time.deltaTime);
}
else if (transform.position.y > _player.transform.position.y)
{
transform.Translate(Vector3.down * _kamikazeSpeed * Time.deltaTime);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
// if other is Player
//Destroy Us
//damage the player
if (other.gameObject.CompareTag("Player"))
{
//damage player
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
player.Damage();
}
_animate.SetTrigger("OnEnemyDeath");
_enemySpeed = 0;
_explosionSX.Play();
Destroy(this.gameObject, 2.8f);
}
//if other is laser
//laser
//destroy us
if (other.gameObject.CompareTag ("Laser"))
{
if (_player != null)
{
_player.AddScore(10);
}
Destroy(other.gameObject);
_shieldStrengh--;
_shieldVisualizer.SetActive(false);
return;
}
}
public void EnemyDeath()
{
if (_shieldStrengh == 0)
{
return;
}
}
}
```
This is what I have at the moment my shield does work as intended but, after the shield is destroyed the laser has no effect on the enemy ship. But when I add this
```
_animate.SetTrigger("OnEnemyDeath");
```
```
Destroy(this.gameObject, 2.8f);
```
to destroy the ship after the shield is down it will destroy both shield and ship instead what am I doing wrong because I had this working and it just stop so I rewrote it after some more research and still no luck.
I was expecting my laser to destroy the shield and enemy separately not at the same time. |
I am trying to create an authentication system using EJS and PG database, but I am having trouble getting the routing and rendering to work.
In my `index.html` I have an anchor element that points to `signup.html`, which works. In `signup.html` I have a login form, but then when I try to submit it, I get an HTTP 405 error.
How do I properly set up the routing between `index.html`, `signup.html`, and `app.js` (where the authentication logic happens)?
`index.html`
```
<a href="signup.html" class="auth-link">Sign Up</a>
```
`signup.html`
```
<form action="/users/register" method="POST">
```
`app.js`
``` js
app.get("/users/register", checkAuthenticated, (req, res) => {
res.render("register.ejs");
});
```
THANKS! |
How to render a ejs view after sending POST form data to the server? |
null |
{"Voters":[{"Id":6868543,"DisplayName":"j6t"},{"Id":10871073,"DisplayName":"Adrian Mole","BindingReason":{"GoldTagBadge":"c++"}}]} |
Support for mounting volume subpaths is only available in Docker 26.0.0 (release March 20, 2024) and later (the pull request merged [in janurary](https://github.com/moby/moby/pull/45687)). This adds the `subpath` option to volume mounts.
Using `docker run`, we can mount the `pgdata` subdirectory of the `vol-web` volume on `/data` like this:
```
docker run -it --rm \
--mount type=volume,source=vol-web,target=/data,volume-subpath=pgdata \
alpine sh
```
Support for this feature in `docker compose` was only merged [a few days ago](https://github.com/docker/compose/commit/3950460703bc0054a9bbcf2b29e64308a25cc983) and is only available in the `compose` plugin version 2.26.0 and later; this doesn't appear to be available in a release of Docker at this time.
Prior to the above versions it was not possible to mount a volume subpath.
---
Unrelated to your question but important: when you create a volume like this:
```
docker volume create --driver local \
--opt type=nfs \
--opt o=addr=10.0.0.2,rw \
--opt device=:/var/web \
vol-web
```
And then use a volume entry like this in your compose file:
```
volumes:
vol-web:
```
They are **not** referring to the same volume. Volume, network, and container names in your compose file get prefixed by your compose project name (typically the name of the directory that contains the compose file, but can also be set explicitly). If you want your compose file to reference an existing external volume, you would need to set it as `external`:
```
volumes:
vol-web:
external: true
``` |
There's a following table, called `fields`:
[![enter image description here][1]][1]
And there's a dedicated table to store its values, called `values`
[![enter image description here][2]][2]
I want to run a query to produce the following output:
Finished | Faculity | Characteristic | Photo
---------------------------------------------
1 | Math | Good |
0 | Biology | Not Good |
Not easy as it seems. From this [simlar question][3], I have tried running the following query:
SELECT flds.id,
(case when flds.name = 'Finished' THEN vals.value END) AS Finished,
(case when flds.name = 'Faculty' THEN vals.value END) AS Faculty,
(case when flds.name = 'Characteristic' THEN vals.value END) AS Characteristic,
(case when flds.name = 'Photo' THEN vals.value END) AS Photo
FROM `values` vals
LEFT JOIN `fields` flds
ON vals.field_id = flds.id
GROUP BY
flds.id,
vals.value;
Which gives me an unexpected result:
[![enter image description here][4]][4]
Is there any way to resolve it?
[1]: https://i.stack.imgur.com/ahT5u.png
[2]: https://i.stack.imgur.com/TAW4z.png
[3]: https://stackoverflow.com/questions/12004603/mysql-pivot-row-into-dynamic-number-of-columns
[4]: https://i.stack.imgur.com/9WV5v.png |
How to have fixed options using Option.Applicative in haskell? |
|parsing|haskell|optparse-applicative| |
i am here to ask about the problem about this function that calculates the sum at a given depth in a tree, it is working in all cases but the last level, the compiler is giving me this :
`[Done] exited with code=3221225477 in 0.309 seconds`
and this is my code and everything you need(there is more other functions and stuff but i think this is enough):
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef int element;
typedef struct node{
element e;
struct node * left;
struct node * right;
}node;
typedef node * tree;
int isEmpty(tree a){
return a==NULL;
}
element root(tree a){
return a->e;
}
tree left(tree a){
return a->left;
}
tree right(tree a){
return a->right;
}
int max(int x,int y){
return x>y?x:y;
}
int sumAtBis(tree a, int n, int i){
if(i==n){
if(isEmpty(a))
return 0;
else
return root(a);
}
return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1);
}
int sumAt(tree a, int n){
return sumAtBis(a,n,0);
}
int testSumAtBis(tree a, int n, int i){
return sumAt(a,n)==0?1:0;
}
int testSumAt(tree a, int n){
return testSumAtBis(a,n,0)==0?1:0;
}
int main(){
node g={-1,NULL,NULL};
node f={1,NULL,NULL};
node e={0,&f,&g};
node d={0,NULL,NULL};
node c={1,&d,&e};
node b={-1,NULL,NULL};
node a={1,&c,&b};
tree v;
v=&a;
sumAt(v,3);
return 0;
}```
i tried printing the value of i at each level when but it also gives an error so i can't know, also i tried to ask Copilot and Gemini but they didn't help |
What is the problem in my "sumAtBis" code? |
|c|data-structures|binary-tree| |
null |
Getting error while typing public ExtentReports ext
using NUnit.Framework;
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
namespace TestProject1.BaseClass
{
[TestFixture]
public class BaseTest
{
public IWebDriver driver;
public ExtentReports ext; //shows error here
}
}
also tried :
using AventStack.ExtentReports; |
C# Error: 'ExtentReports' is a namespace but is used like a type |
|c#|selenium-webdriver|extentreports| |
null |
I have checked almost all previous question related to my query but did not find my solution.
I'm facing issue with Full keyboard access accessibility when integrate it with scrollview. Inside scrollview textfield and secure textfield are accessible with "tab" key but other component like buttons are not accessible using "tab" key.
but when I remove scrollview all elements are accessible with "tab" key.
Even in system installed iOS Apps they don't support scrollview with tab button, I have
analysed apple documentation regarding this but did not find specific to this.
https://fileport.io/WymhhSPWyZH5 : this video is with scrollview addedd and not able to access all buttons with tab key.
https://fileport.io/DkbeCussK7LP : this video shows without scrollview and all buttons can we accessed with tab key
Does anyone have idea regarding this kind of behaviour? |
pagination, next page with scrapy |
|python|html|scrapy|request|screen-scraping| |
null |
I am having this error when I am installing yfinance. Any solution on that?
kevin@KevindeMacBook-Air test % pip install yfinance --upgrade --no-cache-dir
Collecting yfinance
Downloading yfinance-0.2.37-py2.py3-none-any.whl.metadata (11 kB)
Requirement already satisfied: pandas>=1.3.0 in ./venv/lib/python3.9/site-packages (from yfinance) (1.5.3)Requirement already satisfied: numpy>=1.16.5 in ./venv/lib/python3.9/site-packages (from yfinance) (1.24.2)Requirement already satisfied: requests>=2.31 in ./venv/lib/python3.9/site-packages (from yfinance) (2.31.0)Collecting multitasking>=0.0.7 (from yfinance)Downloading multitasking-0.0.11-py3-none-any.whl.metadata (5.5 kB)Collecting lxml>=4.9.1 (from yfinance)Downloading lxml-5.1.1-cp39-cp39-macosx_10_9_x86_64.whl.metadata (3.5 kB)Collecting appdirs>=1.4.4 (from yfinance)Downloading appdirs-1.4.4-py2.py3-none-any.whl.metadata (9.0 kB)Requirement already satisfied: pytz>=2022.5 in ./venv/lib/python3.9/site-packages (from yfinance) (2022.7.1)Collecting frozendict>=2.3.4 (from yfinance)Downloading frozendict-2.4.0-cp39-cp39-macosx_10_9_x86_64.whl.metadata (23 kB)Collecting peewee>=3.16.2 (from yfinance)Downloading peewee-3.17.1.tar.gz (3.0 MB)3.0/3.0 MB 25.5 MB/s eta 0:00:00Installing build dependencies ... doneGetting requirements to build wheel ... errorerror: subprocess-exited-with-error
Getting requirements to build wheel did not run successfully.exit code: 1[32 lines of output]Traceback (most recent call last):File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>main()File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in mainjson_out['return_val'] = hook(**hook_input['kwargs'])File "/Users/kevin/PycharmProjects/test/venv/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheelreturn hook(config_settings)File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheelreturn self._get_build_requires(config_settings, requirements=['wheel'])File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 295, in _get_build_requiresself.run_setup()File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 487, in run_setupsuper().run_setup(setup_script=setup_script)File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 311, in run_setupexec(code, locals())File "<string>", line 109, in <module>File "<string>", line 86, in _have_sqlite_extension_supportFile "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 600, in compileself._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py", line 185, in _compileself.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 1041, in spawnspawn(cmd, dry_run=self.dry_run, **kwargs)File "/private/var/folders/6f/dx1v1ksd39732901t1pjp3dw0000gn/T/pip-build-env-yb2xybts/overlay/lib/python3.9/site-packages/setuptools/_distutils/spawn.py", line 57, in spawnproc = subprocess.Popen(cmd, env=env)File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 947, in initself._execute_child(args, executable, preexec_fn, close_fds,File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1739, in _execute_childenv_list.append(k + b'=' + os.fsencode(v))File "/usr/local/Cellar/python@3.9/3.9.1_8/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 810, in fsencodefilename = fspath(filename) # Does type-checking of filename.TypeError: expected str, bytes or os.PathLike object, not int[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.error: subprocess-exited-with-error
Getting requirements to build wheel did not run successfully.exit code: 1See above for output.
yfinance version - UNABLE TO INSTALL ANY yfinance version
python version: Python 3.9.1
on Mac
I can install other libraries, but not yfinance. |
[Python]Subprocess error during installing yfinance |
|python-3.x|yfinance| |
null |
I want to use java/kotlin in flutter with dart programming language. Java/kotlin has many functionalities which dart is lacking. But flutter is good in UI UX. So I want to use flutter with dart, but java/kotlin also for back-end programming. How can I do that? |
Can we use java/kotlin code in flutter with dart code? |
Try this:
// ...
app.Run(async context =>
{
await context.Response.WriteAsync("I'm upgrading!\nTRY AGAIN LATER");
});
app.Run(); |
I'm unable to ping/or perform curl to any website from an instance which has only ipv6 address assigned whereas I'm able to ping/access internet if I create a windows instance with same settings (Ubuntu or Amazon Linux instances are not working), some of the details are as follows
ip -6 addr:

Route Table:

Security Groups:

Ping command response (Stuck with no output): https://i.stack.imgur.com/gYY0j.png |
please delete flutter_mint package from the pubspec.yaml |
I saw this piece of code in MDN while I was learning some syntax about Class in JavaScript today, which really confused me. [Here is it][1]:
```javascript
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
```
If I create an instance of Rectangle without passing into any arguments, the default value of height 0 doesn't work on the instance.
```javascript
const rec = new Rectangle();
// { height: undefined, width: undefined }
```
My question is "Is this piece of code is a bad practice?". If a class filed has been assigned inside the constructor, we shouldn't give a defalut valut to the class outside the constructor because it will always not work.
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#field_declarations:~:text=class%20Rectangle%20%7B%0A%20%20height%20%3D%200%3B%0A%20%20width%3B%0A%20%20constructor(height%2C%20width)%20%7B%0A%20%20%20%20this.height%20%3D%20height%3B%0A%20%20%20%20this.width%20%3D%20width%3B%0A%20%20%7D%0A%7D |
How do defalut values of Class fields work in JavaScript |
|javascript| |
I have the same problem due to my stupid mistake! I figured out that the problem came from the wrong database URL in application.yml
before: "**localhost:3306//**" then I changed it to "mysqldb" and then compose(but did not delete the previous docker image) => I think you should delete it and compose a new one |
rails minitest not picking up fixture properly, instance variable not percolating |
|ruby-on-rails|minitest| |
Ended up using a DTO, as suggested in the comments.
This appears to be required, at least until a new, relevant version of the Nuget is realeased. |
So I am basically very new to Assembly in general. I was trying to write this simple code where I need to sort numbers in an ascending order from source data and rewrite it into destination data.
and whenever I run it, it shows: executables selected for download on to the following processors doesn't exist...
here is the code, maybe something wrong with it:
```
.global main
main:
ldr r0, =src_data // load the input data into r0
ldr r1, =dst_data // load the output data into r1
mov r2, #32 // word is 32
first_loop:
ldr r3, =Input_data // load the input data into r3
ldr r4, [r3], #4 // load the 1st elem of input data into r4
mov r5, r0 // move to the second loop
second_loop:
ldr r6, [r1] // load the value of output data into r6
cmp r4, r6 // compare the current element eith the value in output data
ble skip_swap // if the current element is less than or equal, continue
// swap the elements:
str r6, [r1]
str r4, [r1, #4]
skip_swap:
// move to the next elem in output data
add r1, r1, #4
// decrement by one remaining elements (r2 was 32)
subs r2, r2, #1
// check if we have reached the end of input_data
cmp r3, r0
// if not, continue to the second loop
bne second_loop
// if the first loop counter is not zero, continue to the first loop
subs r2, r2, #1
bne first_loop
// exit
mov r7, #0x1
svc 0 // software interrupt
.data
.align 4
src_data: .word 2, 0, -7, -1, 3, 8, -4, 10
.word -9, -16, 15, 13, 1, 4, -3, 14
.word -8, -10, -15, 6, -13, -5, 9, 12
.word -11, -14, -6, 11, 5, 7, -2, -12
// should list the sorted integers of all 32 input data
// like if saying: .space 32
dst_data: .word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
```
well, basically registers were all blank in Vitis IDE, even though I think it is supposed to be working.. |
I have a spring boot application where I get request text and files as form-data
If I send text data in code format, I get this error
```
JSON parse error: Unexpected character ('b' (code 98)): was expecting comma to separate Object entries
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:406) ~[spring-web-6.0.10.jar:6.0.10]
```
The request value is like this
```
{
"content": " #backgroundImage {
border: none;
height: 100%;
pointer-events: none;
position: fixed;
top: 0;
visibility: hidden;
width: 100%;
}
[show-background-image] #backgroundImage {
visibility: visible;
}
</style>
</head>
<body>
<iframe id="backgroundImage" src=""></iframe>
<ntp-app></ntp-app>
<script type="module" src="new_tab_page.js"></script>
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="stylesheet" href="chrome://theme/colors.css?sets=ui,chrome">
<link rel="stylesheet" href="shared_vars.css">
</body>
</html>",
"title": "test1"
}
```
At first I got
```
JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
```
But this one is fixed after using
```
jackson:
parser:
allow-unquoted-control-chars: true
```
in application.yml
But I don't know how to deal with this Unexpected character error
Is client-side responsible to parse JSON type
or
server-side should parse the JSON type data? |
{"Voters":[{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":522444,"DisplayName":"Hovercraft Full Of Eels"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
You can solve this by wrapping the command in a shell command:
xterm -e sh -c php 1.php |
{"Voters":[{"Id":3581217,"DisplayName":"Bart"},{"Id":681865,"DisplayName":"talonmies"},{"Id":16217248,"DisplayName":"CPlus"}]} |
If you're encountering errors while pushing to a remote Git repository, it might not necessarily be your internet connection; it could be related to the buffer size.
### Solutions:
1. **Increase the buffer size**: You can adjust the buffer size to prevent this error. Run the following command in your terminal:
```bash
git config http.postBuffer 524288000
```
2. **Push smaller batches of changes**: If you're attempting to push a large number of changes at once, it could overwhelm the remote repository. Consider pushing smaller batches of changes instead.
3. **Contact GitHub support**: If none of the above solutions work, it might be beneficial to reach out to GitHub support for further assistance.
These steps should help address the issue you're experiencing with pushing to the remote repository.
The answer originally comes from this [discussion][1]
[1]: https://github.com/orgs/community/discussions/49789#discussioncomment-5276609 |
Im creating my own version of a `MarkDown` render. My goal is to read a string or file line by line then return the `MD` rendered as `HTML`. The problem im facing is my return and line by line functionaility is not-returning what I want and I dont know why. Ive tried debugging but everything seemed fine. Ive also tried chaning my for loop but still no luck.
```js
//function used to render MD for the user
function render(md){
let code = ""; //For functions return
let mdLines = md.split('\n');
for(let i = 0; i < mdLines.length; i++){
//Statements to see what kind of MD header a line is.
//I only have these statments as I just started this and am still figuring how I want to approach.
if(mdLines[i].slice(0, 1) == "#"){
code += code.concat("<h1>" + mdLines[i].replace("#", "") + "</h1>")
}
if(mdLines[i].slice(0, 2) == "##"){
code += code.concat("<h2>" + mdLines[i].replace("##", "") + "</h2>")
}
if(mdLines[i].slice(0, 3) == "###"){
code += code.concat("<h3>" + mdLines[i].replace("###", "") + "</h3>")
}
if(mdLines[i].slice(0, 4) == "####"){
code += code.concat("<h4>" + mdLines[i].replace("#", "") + "</h4>")
}
if(mdLines[i].slice(0, 5) == "#####"){
code += code.concat("<h5>" + mdLines[i].replace("#", "") + "</h5>")
}
if(mdLines[i].slice(0, 6) == "######"){
code += code.concat("<h6>" + mdLines[i].replace("######", "") + "</h6>")
}
};
return code;
}
//editor
//This is what the users .js file would be.
//I have it set up like this for testing.
let text1 = "## he#llo \n there \n # yooo"
let text2 = "# he#llo \n there \n ## yooo"
console.log(render(text1));
console.log(render(text2));
```
text1 returns `<h1># he#llo </h1><h1># he#llo </h1><h2> he#llo </h2>`
text2 reutrns `<h1> he#llo </h1>`
text1 should return `<h2>he#llo</h2> there <h1> yooo </h1>`
text2 should return `<h1> he#llo </h1> there <h2> yooo </h2>`
If someone could help me get the proper returns and some potentially reusable code for this issue it would be greatly appreciated.
Ive also looked up the issue with some select terms but it seems no one has documented my very specific issue.
Also for those saying it's a beginner issue just use Elseif, I did that. It dont work. Soooooo..... womp womp.
|
How do I send an audio file to OpenAi? |
|javascript|node.js|next.js|openai-api| |
this would be a solution in Python. It reads the file from input.txt and counts the occurrances between the character "——". Then it writes the number of lines found per block to output.txt. I hope this meets your needs.
'''
parses the file input.txt in the same path
as this python file
and counts the occurrences of a keyword2 (kw2)
in blocks around kw1
'''
import pathlib
import re
kw1 = "——"
kw2 = "^[\d]+ nuit"
def write_to_output(res_kw):
fout = open("output.txt", 'a')
for cnt in res_kw:
fout.write(str(cnt) + "\n")
fout.close()
path = pathlib.Path(__file__).parent.resolve()
print(path)
finput = open("input.txt", mode="r", encoding="utf-8")
lines = finput.readlines()
block = []
for i in range(len(lines)):
if re.search(kw1, lines[i]):
block.append(i)
nuit = [0]*(len(block)-1)
i = 1
while i < len(block):
start = block[i - 1]
end = block[i]
for line in lines[start : end]:
if re.search(kw2, line):
nuit[i-1] += 1
else:
pass
start = end
i += 1
write_to_output(nuit)
The output of the code would be the number of lines with "x nuit" without "total ...":
5
3
6
|
I understand from the code that there might be an issue with the `refreshControl` and the `onRefresh` method. Please check carefully; you are only updating setRefreshing to true and false, which doesn't seem to make sense. |
I have route '/Book'. And i am displaying recently played list when user clicks on any recently played book. BookDetail component opens up which has book details on the same page and same route i.e '/Book'
I have provided back button on top left corner. Desired behavior is when a user clicks on this back button this component should snap back. It should appear only when user clicks on any book.
Here is what i tried to useState and on clicking to change state, but its not working as desired. I am using react-router-dom v 6.16
Here is the code
```
import { Grid, Paper, Typography, IconButton } from '@mui/material';
import { ArrowBack, Language } from '@mui/icons-material';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../app/store/configureStore';
import NotFound from '../../app/errors/NotFound';
import ReactPlayer from 'react-player';
import LoadingComponent from '../../app/layout/LoadingComponent';
import { productSelectors } from './bookSlice';
import { fetchMediumAsync, mediumSelector } from '../medium/mediumSlice';
import useProducts from '../../app/hooks/useProducts';
import { useEffect, useState } from 'react';
interface Props {
bk_ID: string;
}
export default function BookDetail({ bk_ID }: Props) {
const { productsLoaded } = useProducts();
const dispatch = useAppDispatch();
const product = useAppSelector(state => productSelectors.selectById(state, bk_ID!));
const[snap, setSnap] = useState(false);
if (!productsLoaded) return <LoadingComponent message='Loading books...' />;
if (!product) {
return <NotFound />;
}
const { bk_Name = ''} = product;
const trimmedTitle = product.bk_Title.length > 22 ? product.bk_Title.substring(0, 22) + '...' : product.bk_Title;
const trimmedSummary = product.bk_Summary.length > 800 ? product.bk_Summary.substring(0, 800) + '...' : product.bk_Summary;
const shouldFetchAudio = product.media[0].md_ID !== null;
const medium = useAppSelector(state => mediumSelector.selectById(state, product?.media[0].md_ID || ''));
useEffect(() => {
if (shouldFetchAudio && product.media[0].md_ID && !medium) {
dispatch(fetchMediumAsync(product.media[0].md_ID));
}
}, [dispatch, product.media[0].md_ID, medium, shouldFetchAudio]);
const handleBackClick = () => {
setSnap(true)
};
return (
<Paper sx={{ padding: 2, width: '100%', position: 'sticky', top: '20px', alignSelf: 'flex-start' }}>
{/* Top Bar */}
<Grid container justifyContent="space-between" alignItems="center" mb={2}>
{/* Back Button */}
<IconButton component={Link} to='/Book' onClick={() => handleBackClick}>
<ArrowBack />
</IconButton>
{/* Language Icon */}
<IconButton>
<Language />
</IconButton>
</Grid>
{/* Book Title */}
<Typography variant="h5" sx={{ fontWeight: 'bold', position: 'absolute', top:80, right: 20}}>{trimmedTitle}</Typography>
{/* Book Image */}
<img src={product.media[0]?.downloadURL} alt={bk_Name} style={{ width: '30%', height: '10%', maxWidth: 200, marginTop: 1, marginBottom: 1 }} />
{/* Book Author */}
<Typography variant="subtitle1" sx={{ position: 'absolute', top:120, right: 20}}>{product.authors[0]?.at_Name_Ar}</Typography>
{/* Book Description */}
<Typography variant="body1" sx={{ marginTop: 1, fontSize: 'small' }}>{trimmedSummary}</Typography>
{/* Audio Player */}
<Paper variant="outlined" sx={{ padding: 2, marginTop: 1 }}>
{/* React Player */}
{shouldFetchAudio ? (
<ReactPlayer
url={medium?.downloadURL}
controls={true}
playing={true}
width="100%"
height="50px"
/>
) : (
<div>
Book Audio: <p>NA</p>
</div>
)}
</Paper>
</Paper>
);
}
``` |
Snap Back component on clicking back button |
|reactjs| |
null |
|python|matplotlib|openai-gym| |
I am trying to understand the internal workings of RowSet.
How does it set the properties data and create a connection?
```
RowSetFactory factory = RowSetProvider.newFactory();
JdbcRowSet jdbcRowSet = factory.createJdbcRowSet();
jdbcRowSet.setUrl(".................."); jdbcRowSet.setUsername("............."); jdbcRowSet.setPassword(".............."); jdbcRowSet.setCommand("...............");
jdbcRowSet.execute();
``` |
null |
Creating a module for this purpose is inevitable and not a strenuous task at all. All u need is a `package.json` with an `exports` field to limit which submodules can be loaded from within the package. From the [official Node.js docs](https://nodejs.org/api/packages.html#exports):
> The "exports" field allows defining the entry points of a package when imported by name loaded via a node_modules lookup. It is an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules
⚠️ Note that all paths defined in the `"exports"` must be relative file URLs starting with `./` except for the default one `.` as mentioned in the official doc.
So in your case, the `package.json` inside your `facade` folder would be:
```json
{
"name": "@facade",
"private": true,
"version": "0.0.0",
"exports": {
"./B.tsx": "./B.tsx"
}
}
```
Now the external code outside of the `facade` folder (a.k.a the `@facade` package) can only `import {B} from "@facade/B.tsx";`. Both `@facade/A.tsx` and `"@facade/C.tsx"` are inaccessible to the external code. |
Use row values from another table to select them as columns and establish relations between them (pivot table) |
|mysql| |
|bash|sed|rename|space| |
I followed the recommendations from the best answer and also used a YouTube video that helped me set up the connection between Google Cloud Storage and Snowflake. (www.youtube.com/watch?v=4SBNUNMotRY) The most important point is creating the integration:
CREATE OR REPLACE STORAGE INTEGRATION gcs_int
TYPE = EXTERNAL_STAGE
STORAGE_PROVIDER = 'GCS'
ENABLED = TRUE
STORAGE_ALLOWED_LOCATIONS = ('gcs://bucket');
GRANT USAGE ON INTEGRATION gcs_int TO ROLE test;
After establishing the connection, you need to create a table into which the data will be loaded, and then simply copy it:
COPY INTO raw_chikago_taxi_trips (column_names)
FROM 'gcs://bucket'
STORAGE_INTEGRATION = gcs_int
FILE_FORMAT = (type = 'CSV' skip_header = 1
FIELD_OPTIONALLY_ENCLOSED_BY = '"'
TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS UTC');
This is how I implemented the recommendations and configured the connection between GCS and Snowflake.
|
```
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import load_img, img_to_array
#load model using tensorflow
model = tf.keras.models.load_model('./models/Object_Detection.h5')
print('model loaded successfully')
path = './test_images/N11.jpg'
image = load_img(path) #PIL object
image = np.array(image,dtype=np.uint8) #8 bit array (0,255)
image1 = load_img(path,target_size=(224,224))
image_arr_224 = img_to_array(image1)/255.0 #convert into array and get the normalized output
#print size of original image
h,w,d = image.shape
print('height:',h)
print('width:',w)
plt.imshow(image)
plt.show()
```
That is the code am using on windows 10 with an 8gb ram and 1tb storage. Am running that code in jupyter notebook via a tensorflow virtual environment created via anaconda cmd. But whenever i try to run the plt.imshow() and plt.show() function to display the image, the kernel dies out and restarts automatically. Have tried to tried all the solutions with almost similar problem but still it didn't work. |
The kernel appears to have died. It will restart automatically. whenever i try to run the plt.imshow() and plt.show() function in jupyter notebook |
|tensorflow|matplotlib|jupyter-notebook|tf.keras|imshow| |
null |
I wrote some code in Pycharm last year, to loop through VAT numbers entered into the Gov website, so make sure they were still valid. It still works fine on the original laptop, but not on my other laptop, even thought the code is exactly the same (the only adjustment was for the location of the spreadsheet). I have given my code down below. When I try to run it on my other laptop, it comes up with the following error.
Traceback (most recent call last):
File "C:\Users\neils\Documents\Pycharm Projects\VATChecker\VATChecker.py", line 30, in <module>
VAT = web.find_element_by_xpath('//*[@id="target"]')
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
Process finished with exit code 1
One thing I also notice, is that the import sys and import datetime are both greyed out. I guess that's because it crashed before these imports were used?
Are you able to advise me what the problem is please? Many thanks in advance.
```
import datetime
import sys
from selenium import webdriver
from openpyxl import workbook, load_workbook
from datetime import date
web = webdriver.Chrome()
wb = load_workbook('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx', data_only=True, read_only=False)
ws = wb.active
x=2
y=1
current_datetime = datetime.datetime.now()
current_datetime.strftime('%x %X')
invalid = ""
while ws.cell(x,1).value !=None:
ws.cell(x,9).value = ""
web.get("https://www.tax.service.gov.uk/check-vat-number/enter-vat-details")
web.implicitly_wait(10)
VatNumber = ws.cell(x,4).value
VAT = web.find_element_by_xpath('//*[@id="target"]')
VAT.send_keys(VatNumber)
VAT.submit()
web.implicitly_wait(4)
registered = web.find_element_by_xpath('/html/body/div[2]')
if (registered.text.find("Invalid")) > 0:
ws.cell(x,9).value = "Invalid VAT number"
invalid = invalid + str(y) + " " + ws.cell(x,1).value + " " + ws.cell(x,2).value + ", "
y=y+1
else:
ws.cell(x,9).value = "Valid VAT number"
ws.cell(x,6).value = current_datetime
x=x+1
if invalid == "":
print("All VAT records are correct")
else:
print("Invalid VAT records are " + invalid)
wb.save('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx')
``` |
Accessibility : Full keyboard access with scroll view in swiftui |
|ios|swiftui|accessibility|swiftui-scrollview|accessibility-api| |
I have a ksqldbcluster with 2 nodes. Sometimes i might receive an alert from grafana(which i monitor the cluster) that some queries are in error state. When i check the show queries i see that a number of queries have 1 PERSISTENT running and 1 ERROR. I restart first the second ksqdb docker instance. Sometimes is fixed sometimes is not. If is not i restart the first ksqldb docker instance and then is fixed. Any ideas?
version: '3'
services:
ksqldb-server:
container_name: ksqldb-server
hostname: ksqldb.cablenet-as.net
network_mode: host
image: confluentinc/ksqldb-server:latest
environment:
KSQL_HOST_NAME: ksqldb.cablenet-as.net
KSQL_BOOTSTRAP_SERVERS: xxxxxx:9093
KSQL_SECURITY_PROTOCOL: SSL
KSQL_LISTENERS: http://xxxxxx:8088,https://xxxxxx:8443
KSQL_KSQL_SCHEMA_REGISTRY_URL: http://xxxxxxxx-as.net:8081,http://xxxxxx:8082
KSQL_SSL_CLIENT_KEY_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_KEY_STORE_PASSWORD: xxxxxx
KSQL_SSL_CLIENT_TRUST_STORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_CLIENT_TRUST_STORE_PASSWORD: xxxxxxx
KSQL_SERVER_ID: id1
KSQL_STREAMS_NUM_STANDBY_REPLICAS: 1 # Corrected property name
KSQL_LOG4J_ROOT_LOGLEVEL: "ERROR"
KSQL_QUERY_PULL_ENABLE_STANDBY_READS: true
KSQL_HEARTBEAT_ENABLE: true
KSQL_QUERY_PULL_THREAD_POOL_SIZE: "30"
KSQL_LAG_REPORTING_ENABLE: true
KSQL_INTERNAL_LISTENER: http://xxxxxxx:8080
KSQL_SSL_TRUSTSTORE_LOCATION: /etc/kafka/secrets/ksqldb.truststore.jks
KSQL_SSL_TRUSTSTORE_PASSWORD: xxxxxx
KSQL_SSL_KEYSTORE_LOCATION: /etc/kafka/secrets/ksqldb.keystore.jks
KSQL_SSL_KEYSTORE_PASSWORD: xxxxxxx
KSQL_JMX_OPTS: -Dcom.sun.management.jmxremote -javaagent:/etc/kafka/secrets/jmx_prometheus_javaagent-0.17.2.jar=4000:/etc/kafka/secrets/ksql.yaml
ports:
- 8088:8088
- 4000:4000
- 8443:8443
volumes:
- /ksqldata/data:/var/lib/ksqldb-server/data
- /ksqldata/newssl/:/etc/kafka/secrets/
ksqldb-cli:
image: confluentinc/ksqldb-cli:latest
container_name: ksqldb-cli
entrypoint: /bin/sh
tty: true # Corrected indentation
telegraf:
image: telegraf
restart: always
volumes:
- ./telegraf.conf:/etc/telegraf/telegraf.conf:ro
- /var/run/docker.sock:/var/run/docker.sock
~
When restarting ksqldb instance the issue is resolved. Maybe i am missing something in my parameters or how to fix the error? |
KSQLDB Cluster persistent error on a number of queries sometimes |
|ksqldb| |
null |
You'd have to edit file `gradle/libs.versions.toml` and add in TOML format:
[versions]
androidx_compose_bom = '2024.03.00'
androidx_compose_uitest = '1.6.4'
androidx_media3 = '1.3.0'
# ...
[libraries]
androidx_compose_bom = { module = "androidx.compose:compose-bom", version.ref = "androidx_compose_bom" }
androidx_compose_uitest = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx_compose_uitest" }
androidx_media3_exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "androidx_media3" }
androidx_media3_exoplayer_dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "androidx_media3" }
androidx_media3_exoplayer_ui = { module = "androidx.media3:media3-exoplayer-ui", version.ref = "androidx_media3" }
# ...
And one can even bundle these (optional):
[bundles]
androidx_exoplayer = ["androidx_media3_exoplayer", "androidx_media3_exoplayer_dash", "androidx_media3_exoplayer_ui"]
Which means, you can't just copy & paste, but have to convert to TOML.<br/>
Be aware that for BOM dependencies, this only works for the BOM itself.<br/>
When there's no version number, one can use: `//noinspection UseTomlInstead`.
The names of the definitions of the default empty activity app are kind of ambiguous, since they're not explicit enough. There `androidx` should better be called `androidx_compose`, where applicable... because eg. `libs.androidx.ui` does not provide any understandable meaning (low readability), compared to `libs.androidx.compose.ui`. Proper and consistent labeling is important there.
---
Once added there, one can use them in `build.gradle` or `build.gradle.kts`:
implementation(libs.androidx.media3.exoplayer)
implementation(libs.androidx.media3.exoplayer.ui)
Or by the bundle:
implementation(libs.androidx.exoplayer)
Further reading:
- [Sharing dependency versions between projects](https://docs.gradle.org/current/userguide/platforms.html)
- [Migrate your build to version catalogs](https://developer.android.com/build/migrate-to-catalogs) |
I have a website for url//link shortening, that uses Google Spreadsheets and Google App Scripts,
I have been trying to find a way to redirect the users when they type my link, but app scripts either tries to load the redirection URL in an iframe which gets rejected by most sites these days or I have to open up a new tab using `window.open(url, _blank);` which acts as a pop up that has to require permission from the user to open up the first time.
Now i'm aware that I can create an html button which will then redirect them, but thats a really slow and tedious process for a url shortener.
So if anybody is aware on how I can redirect the user automatically instead of making a click button or opening a new tab with popup please do share.
Here is the link to my website that shortens links and then redirects:
https://surl.jayeshrocks.com/
Heres the `doGet` function for the Code.gs script
```
function doGet(e) {
var slug = e.queryString;
if (slug == '') {
var title = 'Dashboard | ' + serviceName;
return HtmlService.createHtmlOutputFromFile('Dashboard').setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).setTitle(title);
} else {
var notFound = false;
var redirectsData = getRedirects();
for (var i = 0; i < redirectsData.length; i++) {
if (slug == redirectsData[i].slug) {
var redirectURL = redirectsData[i].longURL;
var html = "<body>Redirected! You can now close this tab.</body><script>window.open('" + redirectURL + "','_blank');</script>";
return HtmlService.createHtmlOutput(html).setTitle('Redirected!');
break;
} else {
notFound = true;
}
}
if (notFound) {
var html = "<body>No redirections found! Redirected to Link Loom. You can now close this tab.</body><script>alert('No redirects found!');window.open('" + customDomain + "','_blank');</script>";
return HtmlService.createHtmlOutput(html).setTitle('Error 404');
}
}
}
```
If you would like to check out my full script, here is the link:
https://script.google.com/d/1lAwOw4Os0bZI5Ze1orJd-Crjg_MkKt0WUavO87VCME07C6QdgN7kxxQQ/edit?usp=sharing |
I know it's a bit late, but I got it working by overwriting the default values. In my case, I needed to store my data in a global state, so it was a bit easy to implement this without a lib. But in order for this to work, you cannot reset your state.
Also, I believe that **kwaku hubert** and **Hao Zonggang** did basically the same thing, by using `LocalStorage` or the `usePersistForm` lib, which seems to work ^-^
```
const { selectedProduct, setSelectedProduct } = useProductsContext();
const {
control,
handleSubmit,
getValues,
setValue,
formState: { errors },
} = useForm({
resolver: yupResolver<IAnnouncementRegistrationSchema>(
announcementRegistrationSchema
),
defaultValues: selectedProduct || DEFAULT_VALUES,
});
``` |
Easy way would be [`Date.prototype.getDay()`][1]:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const dayNumber = new Date().getDay();
console.log(dayNumber);
<!-- end snippet -->
If by all means you want to use something to "look it up", this would be one approach to get the weekday as a number:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const day = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
weekday: 'long',
});
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const dayNumber = weekdays.indexOf(day.format(Date.now()));
console.log(dayNumber);
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay |
{"Voters":[{"Id":20292589,"DisplayName":"Yaroslavm"},{"Id":2386774,"DisplayName":"JeffC"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
I have a list of cities and distances between them:
NewYork- Los Angeles 2 441 minutes
NewYork- Los Angeles 1500 minutes
NewYork- Dallas 100 minutes
Los Angeles Washington 2456
Los Angeles Dallas 2435
the task is to find the shortes path to start from NYC and end in NYC and visit every city only once.
I have a list, not a graph. I have so much data (200 records) so i cant make a graph out of them and solve it like Traveling Salesman Problem. How to find shortes path? |
How to find shortes path and visit them once |
|python| |
{"Voters":[{"Id":3874623,"DisplayName":"Mark"},{"Id":5014455,"DisplayName":"juanpa.arrivillaga"},{"Id":839601,"DisplayName":"gnat"}]} |
{"Voters":[{"Id":13302,"DisplayName":"marc_s"},{"Id":1197518,"DisplayName":"Steve"},{"Id":839601,"DisplayName":"gnat"}]} |
{"Voters":[{"Id":14732669,"DisplayName":"ray"},{"Id":5577765,"DisplayName":"Rabbid76"},{"Id":839601,"DisplayName":"gnat"}]} |