instruction stringlengths 0 30k β |
|---|
null |
Coding a two-dimensional, dynamically allocated array of `int` is a non-trivial task. If you use a _double pointer_, there are significant memory allocation details. In particular, you need to check every allocation attempt, and, if any one fails, back out of the ones that didn't fail, without leaking memory. And, finally, to take a term from the C++ lexicon, you need to provide some equivalent of the _Rule of Three_ functions used by a C++ _RAII_ class.
A two-dimensional array of `int` with `n_rows` and `n_cols` should probably be allocated with a single call to `malloc`:
```lang-c
int* data = malloc(n_rows * n_cols * sizeof int);
```
With this approach, you have to write indexing functions that accept both `row` and `col` subscripts.
The program in the OP, however, takes the _double pointer_ route, and allocates an _array of pointers to int_. The elements in such an array are `int*`. Thus, the array is an _array of pointers to rows_, where each row is an _array of `int`_. The argument to the `sizeof` operator, therefore, must be `int*`.
```lang-c
int** data = malloc(n_rows * sizeof (int*)); // step 1.
```
Afterwards, you run a loop to allocate the columns of each row. Conceptually, each row is an array of `int`, with `malloc` returning a pointer to the first element of each row.
```lang-c
for (size_t r = 0; r < n_rows; ++r)
data[r] = malloc(n_cols * sizeof int); // step 2.
```
The program in the OP errs in step 1.
```lang-c
// from the OP:
ret = (int **)malloc(sizeof(int) * len); // should be sizeof(int*)
```
Taking guidance from the [answer by @Eric Postpischil](https://stackoverflow.com/a/78248309/22193627), this can be coded as:
```lang-c
int** ret = malloc(len * sizeof *ret);
```
The program below, however, uses (the equivalent of):
```lang-c
int** ret = malloc(len * sizeof(int*));
```
#### Fixing memory leaks
The program in the OP is careful to check each call to `malloc`, and abort the allocation process if any one of them fails. After a failure, however, it does not call `free` to release the allocations that were successful. Potentially, therefore, it leaks memory. It should keep track of the row where a failure occurs, and call `free` on the preceding rows. It should also call `free` on the original array of pointers.
There is enough detail to warrant refactoring the code to create a separate header with functions to manage a two-dimensional array. This separates the business of array management from the application itself.
Header `tbx.int_array2D.h`, defined below, provides the following functions.
- _Struct_ β `struct int_array2D_t` holds a `data` pointer, along with variables for `n_rows` and `n_cols`.
- _Make_ β Function `make_int_array2D` handles allocations, and returns a `struct int_array2D_t` object.
- _Free_ β Function `free_int_array2D` handles deallocations.
- _Clone_ β Function `clone_int_array2D` returns a _deep copy_ of a `struct int_array2D_t` object. It can be used in initialization expressions, but, in general, should not be used for assignments.
- _Swap_ β Function `swap_int_array2D` swaps two `int_array2D_t` objects.
- _Copy assign_ β Function `copy_assign_int_array2D` replaces an existing `int_array2D_t` object with a _deep copy_ of another. It performs allocation and deallocation, as needed.
- _Move assign_ β Function `move_assign_int_array2D` deallocates an existing `int_array2D_t` object, and replaces it with a _shallow copy_ of another. After assignment, it zeros-out the source.
- _Equals_ β Function `equals_int_array2D` performs a _deep comparison_ of two `int_array2D_t` objects, returning `1` when they are equal, and `0`, otherwise.
```lang-c
#pragma once
// tbx.int_array2D.h
#include <stddef.h>
struct int_array2D_t
{
int** data;
size_t n_rows;
size_t n_cols;
};
void free_int_array2D(
struct int_array2D_t* a);
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols);
struct int_array2D_t clone_int_array2D(
const struct int_array2D_t* a);
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b);
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b);
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b);
// end file: tbx.int_array2D.h
```
#### A trivial application
With these functions, code for the application becomes almost trivial.
I am not sure why the OP wrote his own version of `strlen`, but I went with it, changing only the type of its return value.
```lang-c
// main.c
#include <stddef.h>
#include <stdio.h>
#include "tbx.int_array2D.h"
size_t ft_strlen(char* str)
{
size_t count = 0;
while (*str++)
count++;
return (count);
}
struct int_array2D_t parray(char* str)
{
size_t len = ft_strlen(str);
struct int_array2D_t ret = make_int_array2D(len, 2);
for (size_t r = ret.n_rows; r--;) {
ret.data[r][0] = str[r] - '0';
ret.data[r][1] = (int)(len - 1 - r);
}
return ret;
}
int main()
{
char* str = "1255555555555555";
struct int_array2D_t ret = parray(str);
for (size_t r = 0; r < ret.n_rows; ++r) {
printf("%d %d \n", ret.data[r][0], ret.data[r][1]);
}
free_int_array2D(&ret);
}
// end file: main.c
```
#### Source code for `tbx.int_array2D.c`
Function `free_int_array2D` has been designed so that it can be used for the normal deallocation of an array, such as happens in function `main`, and also so that it can be called from function `make_int_array2D`, when an allocation fails.
Either way, it sets the `data` pointer to `NULL`, and both `n_rows` and `n_cols` to zero. Applications that use header `tbx.int_array2D.h` can check the `data` pointer of objects returned by functions `make_int_array2D`, `clone_int_array2D`, and `copy_assign_int_array2D`. If it is `NULL`, then the allocation failed.
```lang-c
// tbx.int_array2D.c
#include <stddef.h>
#include <stdlib.h>
#include "tbx.int_array2D.h"
//======================================================================
// free_int_array2D
//======================================================================
void free_int_array2D(struct int_array2D_t* a)
{
for (size_t r = a->n_rows; r--;)
free(a->data[r]);
free(a->data);
a->data = NULL;
a->n_rows = 0;
a->n_cols = 0;
}
//======================================================================
// make_int_array2D
//======================================================================
struct int_array2D_t make_int_array2D(
const size_t n_rows,
const size_t n_cols)
{
struct int_array2D_t a = {
malloc(n_rows * sizeof(int*)),
n_rows,
n_cols
};
if (!n_rows || !n_cols)
{
// If size is zero, the behavior of malloc is implementation-
// defined. For example, a null pointer may be returned.
// Alternatively, a non-null pointer may be returned; but such
// a pointer should not be dereferenced, and should be passed
// to free to avoid memory leaks. β CppReference
// https://en.cppreference.com/w/c/memory/malloc
free(a.data);
a.data = NULL;
a.n_rows = 0;
a.n_cols = 0;
}
else if (a.data == NULL) {
a.n_rows = 0;
a.n_cols = 0;
}
else {
for (size_t r = 0; r < n_rows; ++r) {
a.data[r] = malloc(n_cols * sizeof(int));
if (a.data[r] == NULL) {
a.n_rows = r;
free_int_array2D(&a);
break;
}
}
}
return a;
}
//======================================================================
// clone_int_array2D
//======================================================================
struct int_array2D_t clone_int_array2D(const struct int_array2D_t* a)
{
struct int_array2D_t clone = make_int_array2D(a->n_rows, a->n_cols);
for (size_t r = clone.n_rows; r--;) {
for (size_t c = clone.n_cols; c--;) {
clone.data[r][c] = a->data[r][c];
}
}
return clone;
}
//======================================================================
// swap_int_array2D
//======================================================================
void swap_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
struct int_array2D_t t = *a;
*a = *b;
*b = t;
}
//======================================================================
// copy_assign_int_array2D
//======================================================================
void copy_assign_int_array2D(
struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->data != b->data) {
if (a->n_rows != b->n_rows || a->n_cols != b->n_cols) {
free_int_array2D(a);
*a = make_int_array2D(b->n_rows, b->n_cols);
}
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
a->data[r][c] = b->data[r][c];
}
}
}
}
//======================================================================
// move_assign_int_array2D
//======================================================================
void move_assign_int_array2D(
struct int_array2D_t* a,
struct int_array2D_t* b)
{
if (a->data != b->data) {
free_int_array2D(a);
*a = *b;
b->data = NULL;
b->n_rows = 0;
b->n_cols = 0;
}
}
//======================================================================
// equals_int_array2D
//======================================================================
int equals_int_array2D(
const struct int_array2D_t* a,
const struct int_array2D_t* b)
{
if (a->n_rows != b->n_rows ||
a->n_cols != b->n_cols) {
return 0;
}
for (size_t r = a->n_rows; r--;) {
for (size_t c = a->n_cols; c--;) {
if (a->data[r][c] != b->data[r][c]) {
return 0;
}
}
}
return 1;
}
// end file: tbx.int_array2D.c
```
|
I have a custom layout that lays views from left to right and if horizontal space runs out then it lays the next views below. If I put a basic text element that says "hello" inside this custom layout then the view occupies all the horizontal space. How can I adjust my setup so the custom layout only occupies the needed horizontal space?
```swift
struct ContentView: View {
var body: some View {
CustomLayout {
Text("Hello")
}
.background(.blue)
}
}
struct CustomLayout: Layout {
var alignment: Alignment = .leading
var spacing: CGFloat = 0
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let maxWidth = proposal.width ?? 0
var height: CGFloat = 0
let rows = generateRows(maxWidth, proposal, subviews)
for (index, row) in rows.enumerated() {
if index == (rows.count - 1) {
height += row.maxHeight(proposal)
} else {
height += row.maxHeight(proposal) + spacing
}
}
return .init(width: maxWidth, height: height)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
var origin = bounds.origin
let maxWidth = bounds.width
let rows = generateRows(maxWidth, proposal, subviews)
for row in rows {
let leading: CGFloat = bounds.maxX - maxWidth
let trailing = bounds.maxX - (row.reduce(CGFloat.zero) { partialResult, view in
let width = view.sizeThatFits(proposal).width
if view == row.last {
return partialResult + width
}
return partialResult + width + spacing
})
let center = (trailing + leading) / 2
origin.x = (alignment == .leading ? leading : alignment == .trailing ? trailing : center)
for view in row {
let viewSize = view.sizeThatFits(proposal)
view.place(at: origin, proposal: proposal)
origin.x += (viewSize.width + spacing)
}
origin.y += (row.maxHeight(proposal) + spacing)
}
}
func generateRows(_ maxWidth: CGFloat, _ proposal: ProposedViewSize, _ subviews: Subviews) -> [[LayoutSubviews.Element]] {
var row: [LayoutSubviews.Element] = []
var rows: [[LayoutSubviews.Element]] = []
var origin = CGRect.zero.origin
for view in subviews {
let viewSize = view.sizeThatFits(proposal)
if (origin.x + viewSize.width + spacing) > maxWidth {
rows.append(row)
row.removeAll()
origin.x = 0
row.append(view)
origin.x += (viewSize.width + spacing)
} else {
row.append(view)
origin.x += (viewSize.width + spacing)
}
}
if !row.isEmpty {
rows.append(row)
row.removeAll()
}
return rows
}
}
extension [LayoutSubviews.Element] {
func maxHeight(_ proposal: ProposedViewSize) -> CGFloat {
return self.compactMap { view in
return view.sizeThatFits(proposal).height
}.max() ?? 0
}
}
``` |
You can remove the port binding for the frontend service in the docker-compose file. Since your Nginx server can access the frontend service by name, use the frontend container's default port (port 80) in your Nginx configuration instead:
proxy_pass http://frontend/;
I'm unsure how you're currently serving your frontend through port 80 within that container. However, if you only have a frontend application, you can build it into static files and serve them directly from the default Nginx location. This eliminates the need for additional Docker images apart from Nginx. |
Your application binds to the loopback interface (127.0.0.1). That means it'll only accept connections from there. In a container, it'll only accept connections from inside the container.
You need to bind to 0.0.0.0 for it to accept connections from outside the container.
The key log message to look for is `Development Server (http://127.0.0.1:36001) started`. That needs to change to 0.0.0.0. |
I'm using Cognito with a SPA and leveraging the Hosted UI to handle all the user interface/authentication logic (i.e. the SPA is only redirecting to Cognito and handling callbacks from Cognito). Sign ups are disabled and users are pre-created using [AdminCreateUser][1] so that the new user is in the `FORCE_CHANGE_PASSWORD` state.
Unfortunately, many users do not sign in before their temporary password expires. Once this happens the user cannot sign in and also cannot reset their password. This is obviously not a great user experience and the two ways I've seen to unblock the user both require an administrator to first be notified of the issue and then to manually intervene (either using `AdminCreateUser` with the RESEND `MessageAction` or via the console to delete and create the user again). This just doesn't scale with hundreds or thousands of users in this state.
Is there an alternate method or workaround to automatically reset the user's password expiration? Ideally this would be in response to a user attempting to sign in with an expired password (perhaps using a Lambda Trigger?) and not an out of band process to RESEND credentials for all users with expired passwords but I'm open to other creative ideas.
[1]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html |
Automating Password Reset/Expiry in Cognito Hosted UI for Users with Expired Temporary Passwords |
|amazon-web-services|amazon-cognito| |
Here is what you could do if you only intend to focus on a limited number of locales, and keep a sensible default.
```php
$formatter = match ($lang) {
'en' => new \IntlDateFormatter($lang, pattern: 'EEEE, MMMM d'),
'sv' => new \IntlDateFormatter($lang, pattern: 'MMMM d, EEEE'),
default => new \IntlDateFormatter($lang, \IntlDateFormatter::FULL, \IntlDateFormatter::NONE),
};
$date = $formatter->format($datetime);
```
|
Using the IExpress utility present on Windows, I created a self-extracting EXE (self-extracting Win32 CAB), which will be used to open Python files. During building, I checked the "extract files and run an installation command" option and typed "`cmd /c myfile.bat`" to install the program. Concerning the source BAT file, instead, it contains only one line (`START "" "C:\Program Files\Spyder\Python\pythonw.exe" "C:\Program Files\Spyder\Spyder.launch.pyw" %1`, to be specific), which is used to open Python scripts (.py) via the Spyder IDE.
Now, if I double-click on the new resulting EXE, it extracts and launches the correct application, as expected. However, if I right-click on a generic PY file, select "Open with", and choose the EXE as a program to open the file, everything stops and I get a "Command line option syntax error. Type command /? for help" message.
It occurs to me that a possible solution is to modify the installation command on IExpress (`cmd /c myfile.bat`), or to appropriately modify the batch file. However, given my very little knowledge on the subject, I don't know how to do it.
How can I solve this problem without having to use external programs, going directly through the EXE? |
Working on a CMS/rich text editor, and for now just recreating the layout Wix is using.
Looks like this at the moment: [Base Layout](https://i.stack.imgur.com/2DcbL.png) and with the sidebar expanded like this: [Expanded Sidebar](https://i.stack.imgur.com/vbeAc.png)
[Flexbox Model](https://i.stack.imgur.com/9ZDdQ.png)
Using flex over absolute on the sidebar, as I want the editor to shrink whenever the sidebar gets expanded.
Blue is the container, red and green are the children. Red is position: sticky, so is the toolbar within the green container.
Things work, the sticky toolbar inside the green editor container stays where it is supposed to, but the sidebar in red scrolls down with the editor text:
[On Scroll](https://i.stack.imgur.com/BDsAl.png)
[Desired Outcome](https://i.stack.imgur.com/SZz3U.png)
Ideally, I'd like to have the scrollbar only within the editor view, and any scrolling to only affect it (in yellow).
I tried giving the red sidebar a max-height of (100vh - header), which kind of works, but is easily broken, e.g whenever a horizontal scrollbar appears and disappears.
Also tried the old overflow: hidden on body, and overflow: auto on the editor, but couldn't get scrolling to work again unless I remove overflow: hidden from body. |
CSS scrolling only on part of website - Flexbox, sidebar |
|css|flexbox|wix|scrollbar|overflow| |
null |
A windowed function is processed at the same time the SELECT is.
More specifically, this is the order of operations:
- List item
- FROM and JOINS
- WHERE
- GROUP BY
- HAVING
- SELECT
notice how SELECT is processed last.
Therefore your queries are not the same. Your first query is filtering before the windowed function. The second query is filtering after.
|
`from llama_index.core.node_parser import SimpleNodeParser` ? |
Going through the issues on [vscode-python](https://github.com/microsoft/vscode-python) repository, it is being mentioned in multiple issues that git bash is not officially supported. For example [here](https://github.com/microsoft/vscode-python/issues/23008#issuecomment-1972618316):
> Note Gitbash isn't supported by Python extension, so use Select default profile to switch to cmd or powershell if need be.
Possibly it is a bug and it will be better to use cmd or powershell, since you can run into issues in the future as well.
Some related issues which mention the same
* https://github.com/Microsoft/vscode-python/issues/3035
* https://github.com/microsoft/vscode-python/issues/23008
* https://github.com/microsoft/vscode-python/issues/22957 |
The problem is even if the *condition* is *false* and the *capture* didn't return any frame (like at the end of the video), your code still tries to track this nonexistent frame before the *while* condition will do its job:
```python
while condition:
condition, frame = capture.read()
results = model.track(frame, persist=True)
```
So here I would propose to use the usage example from Ultralytics documentation: https://docs.ultralytics.com/modes/track/#persisting-tracks-loop. This code will end the process in both cases: when the video ends or when "q" is pressed, and will not try to process the frames after the end of the video.
```python
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Open the video file
video_path = "./Vine_Golvo.mp4"
cap = cv2.VideoCapture(video_path)
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True)
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Display the annotated frame
cv2.imshow("Paul", annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
``` |
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal, then the page/js freezes. Why does it freeze?
```
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div_1">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
<p id="open_modal">open the modal</p>
<script>
document.addEventListener("DOMContentLoaded", () => {
let test = document.querySelector("#div_1")
for (let i = 0; i < test.children.length; i++) {
test.children[i].addEventListener("click", () => {
console.log(test.children[i].innerHTML)
});
};
});
document.querySelector("#open_modal").addEventListener("click", () => {
if (!document.querySelector("#modal")) {
document.body.innerHTML += `
<div id="modal" style="display: block; position: fixed; padding-top: 200px; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(0,0,0,0.4)">
<div id="modal_content">
<span id="modal_close">×</span>
<p style="color: green;">Some text in the Modal..</p>
</div>
</div>
`;
document.querySelector("#modal_close").addEventListener("click", () => {
document.querySelector("#modal").style.display = "none";
});
} else {
document.querySelector("#modal").style.display = "block";
};
});
</script>
</body>
</html>
``` |
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++23 Standard](https://timsong-cpp.github.io/cppwp/n4950/) appears in Section 6.7.5.1 [basic.stc.general], where [item 4](https://timsong-cpp.github.io/cppwp/n4950/basic.stc.general#4) states, "Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior." |
> How should I code to test for an integer value of 0 or 1
The right answer is to use **OR-Patterns**, described in [PEP 622][1]:
> Multiple alternative patterns can be combined into one using |. This
> means the whole pattern matches if at least one alternative matches.
> **Alternatives are tried from left to right and have a short-circuit
> property, subsequent patterns are not tried if one matched**.
<!-- language-all: python -->
x = 1
match x:
case int(0 | 1):
print('case of x = int(0) or x = int(1)')
case _:
print('x != 1 or 0')
> Output: 'case of x = int(0) or x = int(1)'
**Type insensitive** would be like this:
x = 1.0
match x:
case 0 | 1:
print('case of x = 0 or x = 1')
case _:
print('x != 1 or 0')
> Output: 'case of x = 0 or x = 1'
----------
In case you want to check for **each case separately**, you would do:
x = 1.0
match x:
case int(0):
print('x = 0')
case int(1):
print('x = 1')
case _:
print('x != 1 or 0')
> Output: `x != 1 or 0`
x = 1.0
match x:
case 0:
print('x = 0')
case 1:
print('x = 1')
case _:
print('x != 1 or 0')
> Output: `x = 1`
[1]: https://peps.python.org/pep-0622/#combining-multiple-patterns-or-patterns |
I want to update or insert 100,0000 records into a database in a single batch process using some effective design pattern.
Example: I have 1 million records in my table date range from 1/1/2020 to 1/1/2024 and if user updates any transaction in the middle, e.g. 1/1/2022, then based on that particular date I need to update the remaining records that come after 1/1/2022.
I am using Java and Hibernate.
Need to understand more about how design patterns work with bulk data and which design pattern I should learn for the above scenario? |
Design patterns - How Design patterns work with bulk data |
|java|hibernate|design-patterns| |
null |
{"Voters":[{"Id":354577,"DisplayName":"Chris"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
Figured it out. Had a dumb if statement manually checking the first index of the argv array for the file path. This wouldn't work if switching from `node index.js <command>` to `scaffold <command>` because the first index no longer points to what the if statement is looking for, thereby never allowing runCLI() to run. Shame on me.
The culprit:
```js
if (process.argv[1] === fileURLToPath(import.meta.url)) {
runCLI();
}
``` |
{"Voters":[{"Id":2395282,"DisplayName":"vimuth"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
{"Voters":[{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
{"Voters":[{"Id":9952196,"DisplayName":"Shawn"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}],"SiteSpecificCloseReasonIds":[18]} |
1. Return a pointer to the `Node` of interest instead of updating the out parameter `head_dest`. The stack will implicitly hold `cur_list_dest`.
1. The original implementation changes the original list. To create a new list you need to return a pointer to *copy* of the smallest node or NULL. To emphasize that I made the argument constant with `const Node *head`.
1. Finally, you can optimize the implementation of `pairWiseMinimumInNewList_Rec()` by observing that we return NULL in the base case. Otherwise we clone either first or 2nd node, and the recursive case is either 2 nodes ahead or we are done:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int val;
struct Node *pt_next;
} Node;
Node *linked_list_new(int val, Node *pt_next) {
Node *n = malloc(sizeof *n);
if(!n) {
printf("malloc failed\n");
exit(1);
}
n->val = val;
n->pt_next = pt_next;
return n;
}
Node *linked_list_create(size_t n, int *vals) {
Node *head = NULL;
Node **cur = &head;
for(size_t i=0; i < n; i++) {
*cur = linked_list_new(vals[i], NULL);
if(!head) head = *cur;
cur = &(*cur)->pt_next;
}
return head;
}
void linked_list_print(Node *head) {
for(; head; head=head->pt_next)
printf("%d->", head->val);
printf("NULL\n");
}
void linked_list_free(Node *head) {
while(head) {
Node *tmp = head->pt_next;
free(head);
head=tmp;
}
}
Node *pairWiseMinimumInNewList_Rec(const Node* head) {
if(!head)
return NULL;
return linked_list_new(
(head->pt_next && head->val < head->pt_next->val) ||
(!head->pt_next) ?
head->val :
head->pt_next->val,
pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL)
);
}
int main() {
Node *head=linked_list_create(7, (int []) {2,1,3,4,5,6,7});
Node* head_dest=pairWiseMinimumInNewList_Rec(head);
linked_list_free(head);
linked_list_print(head_dest);
linked_list_free(head_dest);
}
```
Example run that exercises the main two code paths:
```
1->3->5->7->NULL
``` |
Custom layout occupies all horizontal space |
Try modifying your li style like this:
``` css
OL { margin-left: 0; padding-left: 0; }
```
And add this:
``` css
li p { padding-left: 10px; }
``` |
null |
I do not understand how the following operations `2s β 1` and `1 - 2s` are performed in the following expressions:
```vhdl
R <= (s & '0') - 1;
L <= 1-(s & '0');
```
Considering the fact that `R` and `L` are of type `signed(1 downto 0)` and `s` of type `std_logic`. I have extracted them from a `vhdl` code snippet in my professor's notes.
__What I understand (or at least consider to understand β premises of my reasoning)__
1. The concatenation with the `0` literal achieves the product by `2` (That is what shifting to the left does).
2. The concatenation also achieves a `std_logic_vector` of 2 bits (not so sure about that, I inferred this from a comment in the following [StackOverflow question]( https://stackoverflow.com/questions/18689477/how-to-add-std-logic-using-numeric-std)
3. "`std_logic_vector` is great for implementing data buses, itβs useless for performing arithmetic operations" - source: [vhdlwhiz](https://vhdlwhiz.com/signed-unsigned/#:~:text=Finally%2C%20signed%20and%20unsigned%20can,can%20only%20have%20number%20values).
__What baffles me:__
1. What type does the compiler interpret the `1` literal is?
- An integer? If so, can an `integer` be used without casting in an arithmetic expression with a `std_logic_vector`? This option doesn't seem very plausible to me...
- Assuming the fact that the `(s & '0')` is indeed interpreted as a `std_logic_vector` (second premise) it also comes to my mind the possibility that the compiler, based on the type of the other operand in the expression (i.e., `(s & '0')`), inferred `1` to be of type `std_logic_vector` as well. However, even though both `(s & '0')` and `1` were interpreted as `std_logic_vector` they should not be behaving correctly according to my third premise.
- A thought that comes to my mind in order tu justify the possibility of both operands being of type `std_logic_vector` is that both `(s & '0')` and `1` are implicitly casted to `signed` by the compiler because it acknowledges the fact the signal in which the result is stored is of type `signed`. This, doesn't seem to make sense to me (suppose `s` is equal to `1`):
`R <= (s & '0') - 1;`
Both operands are converted to `std_logic_vectors(1 downto 0)`
`R <= "10" - "01"`
Now, if the contents of the std_logic_vectors were interpreted as `signed` the result of the subtraction would be
`R <= (-2) - (1) = -3`
As you can tell I am really confused. I believe we've only scratched the surface when it comes to discussing data types in class and I am encountering a lot of problems when solving problems because choosing the wrong data types
I sincerely apologize for the questions not being as clear as I would, but they are only a reflection of my understanding on the subject. I appreciate your patience.
|
Is there any difference between using map and using function if everything is known at compile time. (I'm new to Kotlin/Java and i couldn't find answer to this) Maximal number of items will never be higher than 200 and for the most of the time it would be below 10
Example:
```kt
val mappings = mapOf(
"PL" to "Poland",
"EN" to "England",
"DE" to "Germany",
"US" to "United States of America",
)
fun mappingsFunc(code: String): String {
return when (code) {
"PL" -> "Poland"
"EN" -> "England"
"DE" -> "Germany"
"US" -> "United States of America"
else -> "Unknown" // previous checks guarantee never returning this
}
}
fun main() {
println(mappings["PL"])
println(mappingsFunc("US"))
}
```
Playground: https://pl.kotl.in/xo24ulKbo
Both of them works, both syntax's are fine for me but i dunno which one is recommended. |
[my question is what's the meaning of new_image[new_image] in this image img in index what does it mean can you help me with this and specify what img in index returns my image in this is gray scale thank all of you answering my question](https://i.stack.imgur.com/umMGp.png)
|
what is it? my question is what's the meaning of img[img] |
|python|indexing| |
null |
I dont see any problem working with the above xml, you will have to query into object and create a table / collection for each.
Or
Create a type field for each and store them in the same table/collection
{ "type": "person", "name": "John", "age": 30 }
{ "type": "car", "name": "BMW", "price": 50000 }
{ "type": "book", "name": "Harry Potter", "author": "Rowling" }
|
Working on a CMS/rich text editor, and for now just recreating the layout Wix is using.
Looks like this at the moment: [Base Layout](https://i.stack.imgur.com/2DcbL.png) and with the sidebar expanded like this: [Expanded Sidebar](https://i.stack.imgur.com/vbeAc.png)
[Flexbox Model](https://i.stack.imgur.com/9ZDdQ.png)
Using flex over absolute on the sidebar, as I want the editor to shrink whenever the sidebar gets expanded.
Blue is the container, red and green are the children. Red is position: sticky, so is the toolbar within the green container.
Things work, the sticky toolbar inside the green editor container stays where it is supposed to, but the sidebar in red scrolls down with the editor text:
[On Scroll](https://i.stack.imgur.com/BDsAl.png)
Makes sense, in the flex model, as when green grows, so does red.
[Desired Outcome](https://i.stack.imgur.com/SZz3U.png)
Ideally, I'd like to have the scrollbar only within the editor view, and any scrolling to only affect it (in yellow).
I tried giving the red sidebar a max-height of (100vh - header), which kind of works, but is easily broken, e.g whenever a horizontal scrollbar appears and disappears.
Also tried the old overflow: hidden on body, and overflow: auto on the editor, but couldn't get scrolling to work again unless I remove overflow: hidden from body. |
The issue you're experiencing might be due to the margin-left property in your .col img CSS rule. When the screen size is reduced, the margin-left: 7vw; causes the image to extend beyond the viewport width.
To fix this, you can adjust the margin-left property inside the media query to reduce the margin when the screen size is smaller: |
{"Voters":[{"Id":476,"DisplayName":"deceze"}]} |
I don't know how, but everything was fixed after a reboot :) |
You'd have to edit file `gradle/libs.versions.toml` and add in TOML format:
[versions]
androidx_media3 = '1.3.0'
androidx_compose_bom = '2024.03.00'
androidx_compose_uitest = '1.6.4'
# ...
[libraries]
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" }
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" }
# ...
And one can even bundle these (optional):
[bundles]
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`... because eg. `libs.androidx.ui` does not provide any understandable meaning (readability), compared to `libs.androidx.compose.ui`. Proper labeling is important there.
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) |
Spring Data JPA doesn't support aggregate functions in queries using method names (see the table of supported keywords [here][1]).
The suggested approach is to use `@Query` as mentioned in your question. Why do you consider it dirty? It isn't IMHO.
[1]: https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html#jpa.query-methods.query-creation |
### For the new Firebase update
Try this code for the latest Firebase update.
Open the console, paste this code and hit enter!!!
```js
setInterval(() => {
document.getElementsByClassName('edit-account-button mat-mdc-menu-trigger mat-mdc-icon-button mat-mdc-button-base')[0].click()
Array.from(document.getElementsByClassName('mat-mdc-focus-indicator mat-mdc-menu-item ng-star-inserted')).at(-1).click();
document.getElementsByClassName('confirm-button mat-mdc-raised-button mat-mdc-button-base mat-warn')[0].click()
}, 1000)
``` |
null |
### For the new Firebase update
Try this code for the latest Firebase update. Open the console, paste this code and hit enter.
```js
setInterval(() => {
document.getElementsByClassName('edit-account-button mat-mdc-menu-trigger mat-mdc-icon-button mat-mdc-button-base')[0].click()
Array.from(document.getElementsByClassName('mat-mdc-focus-indicator mat-mdc-menu-item ng-star-inserted')).at(-1).click();
document.getElementsByClassName('confirm-button mat-mdc-raised-button mat-mdc-button-base mat-warn')[0].click()
}, 1000)
``` |
I just needed to add ```mkdir -p /var/run/kea``` to the ```kea-dhcp4-server``` script under ```init.d```.
(I had already tried this but forgot to set execute permission on ```kea-dhcp4-server``` in my .bbappend). |
{"Voters":[{"Id":349130,"DisplayName":"Dr. Snoopy"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":2836621,"DisplayName":"Mark Setchell"}],"SiteSpecificCloseReasonIds":[18]} |
I do not understand how the following operations `2s β 1` and `1 - 2s` are performed in the following expressions:
```vhdl
R <= (s & '0') - 1;
L <= 1-(s & '0');
```
Considering the fact that `R` and `L` are of type `signed(1 downto 0)` and `s` of type `std_logic`. I have extracted them from a `vhdl` code snippet in my professor's notes.
__What I understand (or at least consider to understand β premises of my reasoning)__
1. The concatenation with the `0` literal achieves the product by `2` (That is what shifting to the left does).
2. The concatenation also achieves a `std_logic_vector` of 2 bits (not so sure about that, I inferred this from a comment in the following [StackOverflow question]( https://stackoverflow.com/questions/18689477/how-to-add-std-logic-using-numeric-std)
3. "`std_logic_vector` is great for implementing data buses, itβs useless for performing arithmetic operations" - source: [vhdlwhiz](https://vhdlwhiz.com/signed-unsigned/#:~:text=Finally%2C%20signed%20and%20unsigned%20can,can%20only%20have%20number%20values).
__What baffles me:__
1. What type does the compiler interpret the `1` literal is?
- An integer? If so, can an `integer` be used without casting in an arithmetic expression with a `std_logic_vector`? This option doesn't seem very plausible to me...
- Assuming the fact that the `(s & '0')` is indeed interpreted as a `std_logic_vector` (second premise) it also comes to my mind the possibility that the compiler, based on the type of the other operand in the expression (i.e., `(s & '0')`), inferred `1` to be of type `std_logic_vector` as well. However, even though both `(s & '0')` and `1` were interpreted as `std_logic_vector` they should not be behaving correctly according to my third premise.
- A thought that comes to my mind in order tu justify the possibility of both operands being of type `std_logic_vector` is that both `(s & '0')` and `1` are implicitly casted to `signed` by the compiler because it acknowledges the fact the signal in which the result is stored is of type `signed`. This, doesn't seem to make sense to me (suppose `s` is equal to `1`):
`R <= (s & '0') - 1;`
Both operands are converted to `std_logic_vectors(1 downto 0)`
`R <= "10" - "01"`
Now, if the contents of the std_logic_vectors were interpreted as `signed` the result of the subtraction would be
`R <= (-2) - (1) = -3`
As you can tell I am really confused. I believe we've only scratched the surface when it comes to discussing data types in class and I am encountering a lot of problems when solving problems because choosing the wrong data types.
I apologize for any lack of clarity in my questions; they reflect my current understanding of the subject. Thank you for your patience.
|
I was working with importing classes (please see my code below) and I ran into the following mistake:
Below is the code of the file `admin_instance.py` and I see the squiggly line under admin in `admin_instance.py`
```
import admin
my_admin = admin.Admin('john', 'doe', 30, 'USA')
my_admin.describe_user()
my_admin.admin_privileges.show_privileges()
```
and this one is the code of `admin.py`
```
class User:
def __init__(self, first_name, last_name, age, location):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.location = location
def describe_user(self):
print(f"The full name of the user is {self.first_name.title()} {self.last_name.title()}."
f" He is {self.age} years old and he is from {self.location}.")
def greet_user(self):
print(f"Hello, {self.first_name.title()} {self.last_name.title()}!")
class Privileges:
def __init__(self, privileges = ['can add post', 'can delete post', 'can ban user']):
self.privileges = privileges
def show_privileges(self):
print("Administrator's set of privileges are: ", sep = "", end = " ")
for x in self.privileges:
print(x, end = " ")
class Admin(User):
def __init__(self, first_name, last_name, age, location):
super().__init__(first_name, last_name, age, location)
self.admin_privileges = Privileges()
```
The code is running in VS Code, but it says that `Import 'admin' could not be resolved Pylance (reportMissingImports) [Ln 1, Col 8]`.
Both of my files are in the same directory, so I'm not sure what the mistake is here. Please help me fix that issue! Please see the screenshot below.
[](https://i.stack.imgur.com/EDIcQ.png)
|
Mistake in importing the class |
|python|import|importerror| |
null |
In my extension I add files and create filters for them in `project.vcxproj.filters` file (it's for C++ project). Now I'm doing something like this:
```
ProjectItems items;
items.AddFromFile(path);
// Mofify <project>.vcxproj.filters
project.DTE.ExecuteCommand("File.SaveAll");
project.DTE.ExecuteCommand("Project.UnloadProject");
project.DTE.ExecuteCommand("Project.ReloadProject");
```
Is it possible just to update filters strcuture without reloading an entire project? |
Is it possible to refresh filters instead of reloading project |
|c#|visual-studio-extensions|vsix| |
Encountering
`Warning: Trying to access array offset on value of type null in /www/wwwroot/kopsis/config.php on line 95
Warning: Trying to access array offset on value of type null in /www/wwwroot/kopsis/config.php on line 96
Warning: Trying to access array offset on value of type null in /www/wwwroot/kopsis/config.php on line 97
Warning: Trying to access array offset on value of type null in /www/wwwroot/kopsis/config.php on line 98
Fatal error: Uncaught mysqli_sql_exception: Table 'kopsis.akun' doesn't exist in /www/wwwroot/kopsis/config.php:115 Stack trace: #0 /www/wwwroot/kopsis/config.php(115): mysqli->prepare() #1 /www/wwwroot/kopsis/index.php(2): include('...') #2 {main} thrown in /www/wwwroot/kopsis/config.php on line 115`
This error occurs when running my code on a VPS with AAPanel. It works fine on cPanel hosting with PHP 7.4. How can I resolve this issue on the VPS with AAPanel and php 7.4 also?"
I've already switched to PHP 7.3, 8.1, and still encountering the same issue, even triggering new errors
This is Config.PHP code
<!-- begin snippet: js hide: false console: true babel: false -->
oh sorry, this is my config.php code:
<!-- language: php -->
<?php
// Menonaktifkan tampilan pesan kesalahan
error_reporting(E_ALL);
// Atur zona waktu ke "Asia/Jakarta" (Waktu Indonesia Barat)
date_default_timezone_set('Asia/Jakarta');
// Tampilkan tanggal dan waktu dalam format yang diinginkan
$currentDateTime = date('d M Y H:i:s');
// Memulai sesi
session_start();
// Mendefinisikan path fisik ke file connection.php
$path_to_connection = $_SERVER['DOCUMENT_ROOT'].
"/connection.php";
// Melakukan include file menggunakan path fisik
include $path_to_connection;
// CEK LOGIN USER
if (isset($_COOKIE['login'])) {
$key_login = $_COOKIE['login'];
$ciphering = "AES-128-CTR";
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
$decryption_iv = '1234567891011121';
$decryption_key = "ecommerce";
$decryption = openssl_decrypt($key_login, $ciphering, $decryption_key, $options, $decryption_iv);
$iduser_key_login = explode("hcCTZvFLD7XIchiaMqEka0TLzGgdpsXB", $decryption);
$id_user_login = $iduser_key_login[0];
$select_profile = $server - > prepare("SELECT * FROM `akun` WHERE `id`=?");
$select_profile - > bind_param("i", $id_user_login);
$select_profile - > execute();
$result = $select_profile - > get_result();
$profile = $result - > fetch_assoc();
// Jika profil tidak ditemukan, redirect ke halaman logout
if (!$profile) {
header('Location: '.$url.
'/system/logout.php');
exit(); // Pastikan untuk menghentikan eksekusi setelah melakukan redirect
}
// Simpan informasi pemilik toko yang sedang login
$iduser = $profile['id'];
// COUNT CART
$count_cart_header = $server - > query("SELECT * FROM `keranjang` WHERE `id_user`='$iduser' ");
$cek_cart_header = mysqli_num_rows($count_cart_header);
// COUNT NOTIFICATION
$count_notif_header = $server - > query("SELECT * FROM `notification` WHERE `id_user`='$iduser' AND `status_notif`='' ");
$cek_notif_header = mysqli_num_rows($count_notif_header);
// COUNT FAVORIT
$count_favorit_header = $server - > query("SELECT * FROM `favorit` WHERE `user_id`='$iduser' ");
$cek_favorit_header = mysqli_num_rows($count_favorit_header);
// COUNT CHAT
$count_chat_header = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='$iduser' AND `status`='' ");
$cek_chat_header = mysqli_num_rows($count_chat_header);
// COUNT PESANAN
$count_pesanan_header = $server - > query("SELECT * FROM `invoice` WHERE `id_user`='$iduser' AND `tipe_progress`='' ");
$cek_pesanan_header = mysqli_num_rows($count_pesanan_header);
}
// NOTIFIKASI JUMLAH PESAN BARU
$count_unread_chat = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='1' AND `status`=''");
$cek_unread_chat = mysqli_num_rows($count_unread_chat);
// NOTIFIKASI JUMLAH PERMINTAAN PENARIKAN
$count_pending_rows = $server - > query("SELECT COUNT(*) as total FROM `riwayat_penarikan` WHERE `status`=0");
$row = $count_pending_rows - > fetch_assoc();
$total_pending_rows = $row['total'];
// ADMIN MAIL
$setting_email_query = $server - > query("SELECT * FROM `setting_email` WHERE `id`='1'");
$data_setting_email = mysqli_fetch_assoc($setting_email_query);
$setfrom_smtp = $data_setting_email ? $data_setting_email['setfrom_smtp'] : null;
// HEADER SETTING
$setting_header = $server - > query("SELECT * FROM `setting_header` WHERE `id_hs`='1'");
$data_setting_header = mysqli_fetch_assoc($setting_header);
$logo = $data_setting_header['logo'];
$favicon = $data_setting_header['favicon'];
$title_name = $data_setting_header['title_name'];
$slogan = $data_setting_header['slogan'];
$meta_description = $data_setting_header['meta_description'];
$meta_keyword = $data_setting_header['meta_keyword'];
$google_verification = $data_setting_header['google_verification'];
$bing_verification = $data_setting_header['bing_verification'];
$ahrefs_verification = $data_setting_header['ahrefs_verification'];
$yandex_verification = $data_setting_header['yandex_verification'];
$norton_verification = $data_setting_header['norton_verification'];
// API KEY SETTING
$setting_apikey = $server - > query("SELECT * FROM `setting_apikey` WHERE `id_apikey`='1'");
$data_setting_apikey = mysqli_fetch_assoc($setting_apikey);
$google_client_id = $data_setting_apikey['google_client_id'];
$google_client_secret = $data_setting_apikey['google_client_secret'];
$midtrans_client_key = $data_setting_apikey['midtrans_client_key'];
$midtrans_server_key = $data_setting_apikey['midtrans_server_key'];
$rajaongkir_key = $data_setting_apikey['rajaongkir_key'];
$tinypng_key = $data_setting_apikey['tinypng_key'];
// LOKASI TOKO
$lokasi_toko = $server - > query("SELECT * FROM `setting_lokasi` WHERE `id`='1'");
$data_lokasi_toko = mysqli_fetch_assoc($lokasi_toko);
$provinsi_toko = $data_lokasi_toko['provinsi'];
$provinsi_id_toko = $data_lokasi_toko['provinsi_id'];
$kota_toko = $data_lokasi_toko['kota'];
$kota_id_toko = $data_lokasi_toko['kota_id'];
// TIPE PEMBAYARAN
$tipe_pembayaran = $server - > query("SELECT * FROM `setting_pembayaran` WHERE `status`='active'");
$data_tipe_pembayaran = mysqli_fetch_array($tipe_pembayaran);
$nama_tipe_pembayaran = $data_tipe_pembayaran['tipe'];
$jumlahPesanan = array(
'Belum Bayar' => 0,
'Dikemas' => 0,
'Dikirim' => 0,
'Selesai' => 0,
'Dibatalkan' => 0,
);
// Loop melalui tiap tipe progress dan hitung jumlah pesanan
foreach($jumlahPesanan as $tipeProgress => & $jumlah) {
// Gunakan prepared statement untuk keamanan
$query = $server - > prepare("SELECT COUNT(*) AS jumlah
FROM invoice INNER JOIN iklan ON invoice.id_iklan = iklan.id INNER JOIN akun ON iklan.user_id = akun.id WHERE(iklan.user_id = ? OR akun.id = ? ) AND invoice.tipe_progress = ? ");
$query - > bind_param("iis", $iduser, $iduser, $tipeProgress); $query - > execute(); $result = $query - > get_result();
// Hitung jumlah pesanan
$row = $result - > fetch_assoc(); $jumlah = $row['jumlah'];
// Tutup prepared statement
$query - > close();
}
// Fungsi untuk mendapatkan jumlah tipe progress dari database
function getJumlahTipeProgress($server) {
$jumlahTipeProgress = array();
$query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`");
$query - > execute();
$result = $query - > get_result();
while ($row = $result - > fetch_assoc()) {
$tipeProgress = $row['tipe_progress'];
$jumlah = $row['jumlah'];
$jumlahTipeProgress[$tipeProgress] = $jumlah;
}
$query - > close();
return $jumlahTipeProgress;
}
// Dapatkan jumlah tipe progress
$jumlahTipeProgress = getJumlahTipeProgress($server);
// Array untuk menyimpan jumlah pesanan berdasarkan tipe progress
$jumlahPesananTerbaru = array(
'Belum Bayar' => 0,
'Dikemas' => 0,
'Dikirim' => 0,
'Selesai' => 0,
'Dibatalkan' => 0,
);
// Loop melalui tiap tipe progress dan hitung jumlah pesanan
foreach($jumlahPesananTerbaru as $tipeProgressTerbaruKey => & $jumlahPesananTerbaruValue) {
// Gunakan prepared statement untuk keamanan
$queryPesanan = $server - > prepare("SELECT COUNT(*) AS jumlah FROM `invoice` WHERE `id_user` = ? AND `tipe_progress` = ?");
$queryPesanan - > bind_param("is", $iduser, $tipeProgressTerbaruKey);
$queryPesanan - > execute();
// Dapatkan hasil query
$resultPesanan = $queryPesanan - > get_result();
// Hitung jumlah pesanan
$rowPesanan = $resultPesanan - > fetch_assoc();
$jumlahPesananTerbaruValue = $rowPesanan['jumlah'];
// Tutup prepared statement
$queryPesanan - > close();
}
// Fungsi untuk mendapatkan jumlah tipe progress dari database
function getJumlahTipeProgressTerbaru($server) {
$jumlahTipeProgressTerbaru = array();
$query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`");
$query - > execute();
$result = $query - > get_result();
while ($row = $result - > fetch_assoc()) {
$tipeProgressTerbaru = $row['tipe_progress'];
$jumlah = $row['jumlah'];
$jumlahTipeProgressTerbaru[$tipeProgressTerbaru] = $jumlah;
}
$query - > close();
return $jumlahTipeProgressTerbaru;
}
// Dapatkan jumlah tipe progress
$jumlahTipeProgressTerbaru = getJumlahTipeProgressTerbaru($server);
<!-- end snippet -->
|
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal, then the page/js freezes. Why does it freeze?
```
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div_1">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
<p id="open_modal">open the modal</p>
<script>
document.addEventListener("DOMContentLoaded", () => {
let test = document.querySelector("#div_1")
for (let i = 0; i < test.children.length; i++) {
test.children[i].addEventListener("click", () => {
console.log(test.children[i].innerHTML)
});
};
});
document.querySelector("#open_modal").addEventListener("click", () => {
if (!document.querySelector("#modal")) {
document.body.innerHTML += `
<div id="modal" style="display: block; position: fixed; padding-top: 200px; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(0,0,0,0.4)">
<div id="modal_content">
<span id="modal_close">×</span>
<p style="color: green;">Some text in the Modal..</p>
</div>
</div>
`;
document.querySelector("#modal_close").addEventListener("click", () => {
document.querySelector("#modal").style.display = "none";
});
} else {
document.querySelector("#modal").style.display = "block";
};
});
</script>
</body>
</html>
``` |
Windows "Open with" a file with self-extracting CAB Win32 |
|windows|cab|open-with|self-extracting|iexpress| |
null |
As far as I know, tflite models require metadata in order to run. Regarding the "*cannot initialize type StatusCode*" error, I recently resolved the same situation with *tflite_support* imports simply by downgrading the TensorFlow version in Google Colab like:
!pip uninstall tensorflow
!pip install tensorflow=="2.13.0"
I hope it helps
|
[enter image description here][1]I'm relatively new to using neo4j. I've connected to a database with the py2neo library and populated the database with the faker library to create nodes for Person and Address each with attributes attached to them. I'm interested in creating indexes and testing the performance of different indexes. Before I get to that point, I created some indexes and used the command
```
`graph.run("SHOW INDEXES;")`
```
I was expecting 2 indexes to show but 3 indexes returned. The final one was a Look up type and had some null properties. That attached image shows the output, Why is this index showing up? Thanks.
I was expecting only 2 to return, so I'm thinking maybe this is some lack of understanding on my part? I've started reading through the Neo4j documentation on indexes but I'm still unsure. Any help would be appreciated. Thanks!
[1]: https://i.stack.imgur.com/6Hw4J.png |
You could try something like this:
print("Welcome to Nim!")
name = input("Enter name: ")
replay = 'y'
while replay == 'y':
and then at the end of the game:
```
winner = current_player print("Winner is", winner)
replay = str(input("One more round (y/n)?"))
``` |
Single core embedded system
Priority based scheduling
Thread 2(T2) - High priority
Thread 1(T1) - Low priority
**Requirement:**
1. Data flow from T2 to T1 through shared circular buffer. Data flow
possible in one direction i.e. T2 to T1.
2. Between threads planning to use circular buffer as shared memory to
post received packets from T2 to T1.
3. T2 will enqueue and T1 will dequeue the packets from circular buffer.
4. And planning to add enqueue index and dequeue index pointer for circular buffer as volatile(consider it won't solve critical section problem).
5. T2 will update the Enqueue index pointer in circular buffer and T2
will update the Dequeue index pointer in circular buffer.
6. T1 thread will check Enqueue and dequeue index are equal before
start to dequeue the packet from circular buffer.
**Query:**
- while T1 thread(low priority) trying to read the enqueue index, let's say in
that instance task switched to high priority thread T2 and it will update the enqueue index variable?
- In this case again task switched to T1, whether variable 'enqueue index' read will give old value or INVALID value?
- My understanding is, for my requirement T2->T1 direction only
possible so here critical section issue will not come in preemptive
scheduling
Please give your views
|
Shared variable read from low priority thread in preemptive scheduling |
|c|multithreading|embedded|critical-section|preemptive| |
****just add 'title' to display tooltip message**
<i class="fas fa-question-circle help-icon" data-bs-toggle="tooltip" data-bs-placement="top" container="body" aria-label=".." title="....."></i>
**or
else put tooltip properties inside anchor tag**
<a href="#" tooltip properties><i.....></i></a>** |
{"Voters":[{"Id":12265927,"DisplayName":"Puteri"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
{"Voters":[{"Id":6243352,"DisplayName":"ggorlen"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}],"SiteSpecificCloseReasonIds":[13]} |
{"Voters":[{"Id":29157,"DisplayName":"Adam Liss"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
{"Voters":[{"Id":14732669,"DisplayName":"ray"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
{"Voters":[{"Id":2372064,"DisplayName":"MrFlick"},{"Id":22180364,"DisplayName":"Jan"},{"Id":1974224,"DisplayName":"Cristik"}]} |
Several things are needed to help break the binding loop:
1. Check a break flag as smr has suggested
2. Allow events, use Qt.callLater() means idle time is granted so events can fire
3. Define events that reset and set the break flag
We can borrow the userbreak pattern and implement here with mouse tapped, keypress and even visibility changing as things that will raise a userbreak.
```qml
import QtQuick
import QtQuick.Controls
Page {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
property int anum: 0
property int bnum: 1
property bool userbreak: false
onAnumChanged: {
if (userbreak) return;
Qt.callLater( () => { bnum++ } );
}
onBnumChanged: {
if (userbreak) return;
Qt.callLater( () => { anum++ } );
//Is there some way to stop loop call ?
//in widget we can unconnect some signal and slot
//but how to disconnect in qml
}
Button{
text: "begain %1 %2".arg(anum).arg(bnum)
onClicked: {
userbreak = false;
Qt.callLater( () => { anum++ } );
}
}
TapHandler {
onTapped: userbreak = true;
}
Keys.onPressed: {
userbreak = true;
}
onVisibleChanged: {
userbreak = true;
}
}
```
You can [Try it Online!](https://stephenquan.github.io/qmlonline/?zcode=AAADjXicrVNNS8NAEL3nVwwFIUGoVkQkomJ7qejBguh504zJ4nYm3Z1Yi/S/u5toTfzCg3MImX375s3X6kXFVmAms1rPHyPdc4cTJrFsXHSjCoSXCLytdC5lCkeH+41boi5KSeHwuPWftNOZwRTE1ticiJbgL92tjQdTNIbhnq3JB0nU4JXlCq2sQZOAonqRwv5XIGuAUR/ImA3UDm1mUT2m8KCMwzYq04VnTEpFBebpW+7B9APEW0oCFqW2dLKFZzKcK2OulaCNIU7g9AxeGvXdXdhA0t7cvIuM/1FEfRIJtrd36UBKtAiOFwgrtQZhcMIVGPafEAfOO/c1hREVKLBCjxLUNGcinEsbwemClPFiOTjD0mFmtUDJqxA/1+6d5OMtF6Zb9bgWYfooVvDZL8Agw0L5yzsj2DkYDJUt4lBQ0vyF/iVbAtPE+PXqtyzYtmVw2s7ypAf/vW2bbr63qpr6cg3ajhyTP65CCl3RsLS9CV/h2g2Zbiw618/3VxrTXfsOvtmNn4ib6BUnCgO4) |
I am using `react-bootstrap` `Table`
filteredData function should return `searchTerm` matches record from the data.
I am getting empty data on search now.
How to loop through Object and return true If any of the searchTerm match?
```javascript
import { Table, Pagination, Form } from 'react-bootstrap';
```
```javascript
const dummyData = [
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-18'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-17'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-16'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-15'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-14'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-13'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-12'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-11'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-19'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-22'), edit:'edite',delete:'delete'},
{ consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-24'), edit:'edite',delete:'delete'},
// Add more dummy data as needed
];
const [data, setData] = useState(dummyData);
```
```javascript
const filteredData = useMemo(() => {
return data.filter(row =>
Object.entries(row).every(([key, value]) => {
if (key === 'createdDate') {
// Check if createdDate is null or matches the search date
return !searchDate || value.toISOString().split('T')[0] === searchDate;
}
return value.toString().toLowerCase().includes(searchTerm.toLowerCase());
})
);
}, [data, searchTerm, searchDate]);
```
```javascript
<input
type="text"
placeholder="Search..."
value={searchTerm}
className='rounded border border-1 border-solid border-dark'
onChange={(e) => setSearchTerm(e.target.value)}
/>
``` |
I try to go from Spring-Boot 2.7 to 3.1 - its regarding Security.
What I have under old version 2.
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
@Override
protected void configure (HttpSecurity http) throws Exception
{
http.cors ().and ()
.csrf ().disable ()
.authorizeRequests ()
.antMatchers ("/web/test").permitAll ()
.antMatchers ("/web/**").hasAnyRole ("USER")
.anyRequest ().authenticated ()
.and ()
.addFilter (new SecurityAuthenticationFilter (authenticationManager ()))
.addFilter (new SecurityAuthorizationFilter (authenticationManager ()))
.sessionManagement ()
.sessionCreationPolicy (SessionCreationPolicy.STATELESS);
}
What I already have for version 3.
@Bean
public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception
{
http
.cors (Customizer.withDefaults ())
.csrf (AbstractHttpConfigurer::disable)
.authorizeHttpRequests ((requests) -> requests
.requestMatchers ("/web/test").permitAll ()
.requestMatchers ("/web/**").hasRole ("USER")
.anyRequest ().authenticated ()
)
//.addFilter (new SecurityAuthenticationFilter (authenticationManager ()))
.sessionManagement (httpSecuritySessionManagementConfigurer ->
httpSecuritySessionManagementConfigurer.sessionCreationPolicy (SessionCreationPolicy.STATELESS))
;
return http.build();
But here I struggle with authenticationManager () of former WebSecurtyConfigurationAdapter - for my 2 custom filters.
Where can get this and can I use my filters as they are in Spring3??
They are
public class SecurityAuthenticationFilter extends UsernamePasswordAuthenticationFilter
and
public class SecurityAuthorizationFilter extends BasicAuthenticationFilter
Thanks! |
Spring 3 - Security: How to rebuild authManager () usage? |
|java|spring-boot|spring-security| |
In Delphi 7 I have a report written in QuickReport.
The report is called by the function from another form
`
var RepResult : integer
RepResult := ShowReport(param1,param2...);
`
The function inside report looks like
` var QuickRep1 : TQuickReport;
ReportResult : integer;
function ShowReport(param1,param2...) : integer
begin
...
QuickRep1.PreviewModal;
Result := ReportResult;
end;`
The calculation of variable ReportResult is complicated, based on many queries inside QuickReport and calculated in events of DetailBands, ChildBands ,LoopBands and so on .
The report and the calculations works fine , but now the customer wants to see result of this calculations in another place without viewing the report.
So the question is : Is it possible to get only the result of the function without previewing or printing the report ?
I tried QuickRep1.PreviewModeless and quickrep1.print to non-existed printer. Nothing works |
Delphi - How to get result of function from QuickReport without viewing a report? |
|delphi-7|quickreports| |
null |
{"Voters":[{"Id":147356,"DisplayName":"larsks"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":5320906,"DisplayName":"snakecharmerb"}]} |
There is no such thing as a "normal shell". You have "interactive shells" and "non-interactive shells", which differ, among other things, by what `*rc` file they source at startup and by *whether aliases are expanded or not*. And there are other types, even.
By default Vim uses a *non-interactive shell* for `:!` and `$ man bash` as the following to say about aliases in non-interactive shells:
> Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).
Now, you *could* try to play with `shopt` or try to convince Vim to use an interactive shell with `:help 'shellcmdflag'` but these don't sound like solutions to me.
The only proper solution, IMO, is to turn your aliases into actual shell scripts, somewhere in your `$PATH`, where they will be accessible to all kinds of shells.
--- EDIT ---
FWIW, I don't like the suggestion made in `:help :!` becauseβ¦
- As illustrated in the other answer, it creates other problems which in turn requires solutions and so on.
- The "shell" in which `:!` commands are executed is a very dumb one that is not made at all for interactive stuff (no colors, etc.).
- I much prefer to suspend Vim and end up in a proper shell than to execute lots of commands in the bastardized `:!`.
And there's even `:help :terminal` nowadays if that's your thing.
- I find it a lot cleaner, portable, and scalable to create proper shell scripts in general.
That said, I still have a bunch of aliases, like everyone, but none of them is of any use in a `:!` context so there is no point a) adding `-i` to `shellcmdflag` or b) turning them into scripts:
```
alias fgrep='LC_ALL=C fgrep -nsH --color=auto'
alias flush='sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder'
alias g='git'
alias grep='LC_ALL=C grep -nsH --color=auto'
alias la='ls -alhGF --color=auto'
alias ld='ls -dlhGF --color=auto *'
alias ll='ls -lhGF --color=auto'
alias majports='sudo port selfupdate && port outdated && sudo port upgrade outdated && sudo port uninstall inactive && sudo port uninstall rleaves && sudo port clean all'
alias mgc='magento-cloud'
alias python='python2.7'
alias tigb='tig blame'
alias tigd='tig show'
alias tigg='tig grep'
alias tigl='tig log'
alias tigs='tig status'
alias up='cd ..'
alias vim='mvim -v'
alias webshare='python2.7 -c "import SimpleHTTPServer;SimpleHTTPServer.test()"'
```
`:!` is just not a good enough environment for running interactive commands. |
You could use [`top_k`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.top_k.html) and slice the last row:
```
import polars as pl
np.random.seed(0)
df = pl.DataFrame({'col': np.random.choice(5, size=5, replace=False)})
out = df.top_k(2, by='col')[-1]
```
You could also [`filter`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.filter.html) with [`rank`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.Expr.rank.html), but this will perform a full sort, so it could be algorithmically less efficient:
```
out = df.filter(pl.col('col').rank(descending=True)==2)
```
Output:
```
shape: (1, 1)
βββββββ
β col β
β --- β
β i64 β
βββββββ‘
β 3 β
βββββββ
```
Input:
```
shape: (5, 1)
βββββββ
β col β
β --- β
β i64 β
βββββββ‘
β 2 β
β 0 β
β 1 β
β 3 β
β 4 β
βββββββ
```
##### timings:
1M rows
```
# top_k
39.3 ms Β± 7.23 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
# filter+rank
54.6 ms Β± 8.58 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
```
10M rows:
```
# top_k
427 ms Β± 84.8 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
# filter+rank
639 ms Β± 102 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
```
100M rows
```
# top_k
4.04 s Β± 411 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
# filter+rank
6.12 s Β± 244 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
``` |
PYTHON & OPENPYXL: Drag copy paste formula down below from previous cell |
|python|automation|openpyxl| |
null |
{"Voters":[{"Id":2921691,"DisplayName":"Markus Safar"},{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[13]} |
|python|python-typing|metaclass|type-alias| |
I've started working with Svelte and I stumbled upon some unexpected behavior. This is the snippet of my app source
```typescript
let currentPage = 1;
$: if (currentPage || $selectedOption) {
fetchPage(currentPage, $selectedOption);
}
async function fetchPage(page: number, option: string) {
//...
}
onMount(() => {
fetchPage(currentPage, $selectedOption);
});
```
When I load the page for the first time `fetchPage()` function is called twice. However, if I'll make this change `let currentPage = 0;` it is properly called only once. The problem is that I need to have `currentPage` value initially set to 1.
I've tried also this change:
```typescript
let currentChange = 0;
// ... rest the same
onMount(() => {
fetchPage(currentPage, $selectedOption);
currentPage = 1;
});
```
But this didn't help as well. Similarly any bool flags set in `onMount()` and then checked in if statement didn't help.
Any suggestion what else can I do? |
In order to solve your problem, you first need insight into what is occurring.
So to do that, you should enable SSH debugging:
git config --global core.sshCommand "ssh -vvv"
Then run your `git clone` again. This time, it will show you a lot more information. You can create a new StackOverflow question with those details.
When you are finished debugging, run this command to turn off SSH debugging:
git config --global core.sshCommand ""
----
All of that said, you probably just don't have SSH keys installed properly: https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account |
How can I get all available devices for CuPy? I'm looking to write a version of this for CuPy:
```
if is_torch(xp):
devices = ['cpu']
import torch # type: ignore[import]
num_cuda = torch.cuda.device_count()
for i in range(0, num_cuda):
devices += [f'cuda:{i}']
if torch.backends.mps.is_available():
devices += ['mps']
return devices
``` |
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[18]} |
i'm trying to play a short sound clip when a usr click on a javafx canvas, i have followed the attach audio documentation provided by gluon yet no sound is being played when i install the app on android phone the following is my implementation based on gluon documentation
```
graphicContext.getCanvas().setOnMousePressed(e -> {
playSound();
});
private void playSound(){
soundTask = new Task<Void>(){
@Override
protected Void call(){
Services.get(AudioService.class)
.ifPresent(audioService -> audioService
.loadSound(getClass().getResource("/com/mycompany/sample/gameClick.wav"))
.ifPresent(audio -> audio.play()));
return null;
}
};
Thread soundThread = new Thread(soundTask);
soundThread.setDaemon(true);
soundThread.start();
}
```
my attach list look like this in my pom.xml
```
<dependency>
<groupId>com.gluonhq.attach</groupId>
<artifactId>audio</artifactId>
<version>${attach.version}</version>
</dependency>
<dependency>
<groupId>com.gluonhq.attach</groupId>
<artifactId>audio</artifactId>
<version>${attach.version}</version>
<classifier>android</classifier>
<scope>runtime</scope>
</dependency>
<plugin>
<groupId>com.gluonhq</groupId>
<artifactId>gluonfx-maven-plugin</artifactId>
<version>${gluonfx.plugin.version}</version>
<configuration>
<target>${gluonfx.target}</target>
<attachList>
<list>display</list>
<list>lifecycle</list>
<list>statusbar</list>
<list>storage</list>
<list>util</list>
<list>audio</list>
</attachList>
<mainClass>${mainClassName}</mainClass>
<resourcesList><item>.*/gameClick.wav$</item></resourcesList>
</configuration>
</plugin>
```
when i run
> mvn -Pandroid gluonfx:install gluonfx:nativerun
i get the following.
nativerun logs:
```
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 0, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): Util :: Load className com/gluonhq/helloandroid/Util
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] V/GluonAttach( 382): Util <init>
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): DETACH_DALVIK, tid = 608, existed = 1, env at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): Dalvik Util init was called
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] I/GluonAttach( 382): JNI_OnLoad_audio called
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): [Audio Service] Initializing native Audio from OnLoad
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): Util :: Load className com/gluonhq/helloandroid/DalvikAudioService
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): DETACH_DALVIK, tid = 608, existed = 1, env at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] I/GluonAttach( 382): JNI_OnLoad_storage called
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): [Storage Service] Initializing native Storage from OnLoad
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GluonAttach( 382): Util :: Load className com/gluonhq/helloandroid/DalvikStorageService
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): DETACH_DALVIK, tid = 608, existed = 1, env at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 608, existed? 1, dalvikEnv at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): DETACH_DALVIK, tid = 608, existed = 1, env at 0xb40000714bcf3590
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): ATTACH_DALVIK, tid = 610, existed? 0, dalvikEnv at 0xb40000714bcf3d70
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalGluon( 382): DETACH_DALVIK, tid = 610, existed = 0, env at 0xb40000714bcf3d70
[Sun Mar 31 13:46:24 EAT 2024][INFO] [SUB] D/GraalCompiled( 382): don't add points, primary = -1
``` |
Using Malvin Lok's answer as a lead, I located `io.netty.handler.codec.http.HttpHeaders` and put a breakpoint for each `set*(..)` and `add*(..)` method. Here's what I found
Default headers are added one by one in different places of Netty code. It's hard-coded, there are no injected strategies or configs. There's apparently nothing you can do about it
1. `Accept-Encoding`
```java
// reactor.netty.http.client.HttpClient
public final HttpClient compress(boolean compressionEnabled) {
if (compressionEnabled) {
if (!configuration().acceptGzip) {
HttpClient dup = duplicate();
HttpHeaders headers = configuration().headers.copy();
headers.add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
dup.configuration().headers = headers;
dup.configuration().acceptGzip = true;
return dup;
}
}
```
2, 3, 4. `User-Agent`, `Host`, `Accept`
```java
// reactor.netty.http.client.HttpClientConnect.HttpClientHandler
Publisher<Void> requestWithBody(HttpClientOperations ch) {
try {
ch.resourceUrl = this.resourceUrl;
ch.responseTimeout = responseTimeout;
UriEndpoint uri = toURI;
HttpHeaders headers = ch.getNettyRequest()
.setUri(uri.getPathAndQuery())
.setMethod(method)
.setProtocolVersion(HttpVersion.HTTP_1_1)
.headers();
ch.path = HttpOperations.resolvePath(ch.uri());
if (!defaultHeaders.isEmpty()) {
headers.set(defaultHeaders);
}
if (!headers.contains(HttpHeaderNames.USER_AGENT)) {
headers.set(HttpHeaderNames.USER_AGENT, USER_AGENT);
}
SocketAddress remoteAddress = uri.getRemoteAddress();
if (!headers.contains(HttpHeaderNames.HOST)) {
headers.set(HttpHeaderNames.HOST, resolveHostHeaderValue(remoteAddress));
}
if (!headers.contains(HttpHeaderNames.ACCEPT)) {
headers.set(HttpHeaderNames.ACCEPT, ALL);
}
```
If you specify your own `Host` header
```java
// like so
Mono<Map<String, Object>> responseMono = WebClient.builder()
.baseUrl("https://httpbin.org")
.build()
.get()
.uri("/headers")
.header(HttpHeaders.HOST, "fake-host")
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
```
Netty will be unaware of it (*that `if`* will still evaluate to `true`), but the server will *still* get your "fake" host because at some point, your custom headers and Netty's default headers are merged by Spring. Custom headers overwrite those of Netty's
In the code below, Spring creates a `Flux` of "commit actions" which Netty will subscribe to (indirectly, through multiple wrapper layers). By doing so, it will trigger execution of all commit action `Runnables`, including the one that merges headers (see `applyHeaders()`)
```java
// org.springframework.http.client.reactive.AbstractClientHttpRequest
/**
* Apply {@link #beforeCommit(Supplier) beforeCommit} actions, apply the
* request headers/cookies, and write the request body.
* @param writeAction the action to write the request body (may be {@code null})
* @return a completion publisher
*/
protected Mono<Void> doCommit(@Nullable Supplier<? extends Publisher<Void>> writeAction) {
if (!this.state.compareAndSet(State.NEW, State.COMMITTING)) {
return Mono.empty();
}
this.commitActions.add(() ->
Mono.fromRunnable(() -> {
applyHeaders();
applyCookies();
this.state.set(State.COMMITTED);
}));
if (writeAction != null) {
this.commitActions.add(writeAction);
}
List<Publisher<Void>> actions = new ArrayList<>(this.commitActions.size());
for (Supplier<? extends Publisher<Void>> commitAction : this.commitActions) {
actions.add(commitAction.get());
}
return Flux.concat(actions).then();
}
```
```java
// org.springframework.http.client.reactive.ReactorClientHttpRequest
@Override
protected void applyHeaders() {
getHeaders().forEach((key, value) -> this.request.requestHeaders().set(key, value));
}
``` |