instruction stringlengths 0 30k ⌀ |
|---|
Unable to deploy to GAE from Github Actions |
|node.js|google-cloud-platform|google-app-engine|github-actions| |
[Bun.js][1] has a [useful native API to read periodical user input][2]:
```js
const prompt = "Type something: ";
process.stdout.write(prompt);
for await (const line of console) {
console.log(`You typed: ${line}`);
process.stdout.write(prompt);
}
```
Is there a way to read user inputs, outside a loop?
***
I found this solution:
```js
const stdinIterator = process.stdin.iterator()
console.write('What is your name?\n> ')
const userName = (await stdinIterator.next()).value.toString().trimEnd()
console.log('Hello,', userName)
console.write(`What would you like, ${userName}?\n> `)
const answer = (await stdinIterator.next()).value.toString().trimEnd()
console.log('Do something with answer:', answer)
```
It works. But then the process is not terminated automatically (I need to press <kbd>Ctrl</kbd>+<kbd>C</kbd> manually).
[1]: https://bun.sh/
[2]: https://bun.sh/guides/process/stdin |
Combining multiple Find and Replace functions into one |
|google-apps-script| |
I am working on a virtualised data grid for my application.
I use transform: translateY for the table offset on scroll to make table virtualised.
I developed all the functionality in React 17 project, but when migrated to React 18 I found that the data grid behaviour changed for the worse - the data grid started to bounce on scroll.
I prepared the minimal representing code extract, which shows my problem.
To assure that the code is the same for React 17 and React 18, I change only the import of ReactDOM from 'react-dom/client' to 'react-dom' (which is of course incorrect, since the latter is deprecated) in my index.tsx file.
React 18:
![React 18][1]
React 17:
[React 17][2]
This is the code:
index.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Virtuailsed table</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
```
index.js
```
// import ReactDOM from "react-dom";
import ReactDOM from "react-dom/client";
import { useState } from "react";
import "./styles.css";
let vendors = [];
for (let i = 0; i < 1000; i++ ){
vendors.push({
id: i,
edrpou: i,
fullName: i,
address: i
})
}
const scrollDefaults = {
scrollTop: 0,
firstNode: 0,
lastNode: 70,
};
function App() {
const [scroll, setScroll] = useState(scrollDefaults);
const rowHeight = 20;
const tableHeight = rowHeight * vendors.length + 40;
const handleScroll = (event) => {
const scrollTop = event.currentTarget.scrollTop;
const firstNode = Math.floor(scrollTop / rowHeight);
setScroll({
scrollTop: scrollTop,
firstNode: firstNode,
lastNode: firstNode + 70,
});
};
const vendorKeys = Object.keys(vendors[0]);
return (
<div
style={{ height: "1500px", overflow: "auto" }}
onScroll={handleScroll}
>
<div className="table-fixed-head" style={{ height: `${tableHeight}px` }}>
<table style={{transform: `translateY(${scroll.scrollTop}px)`}}>
<thead style={{ position: "relative" }}>
<tr>
{vendorKeys.map((key) => <td>{key}</td>)}
</tr>
</thead>
<tbody >
{vendors.slice(scroll.firstNode, scroll.lastNode).map((item) => (
<tr style={{ height: rowHeight }} key={item.id}>
{vendorKeys.map((key) => <td><div className="data">{item[key]}</div></td>)}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
// const rootElement = document.getElementById("root");
// ReactDOM.render(<App />, rootElement);
const root = ReactDOM.createRoot(
document.getElementById('root')
);
root.render(
<App />
);
```
styles.css
```
* {
padding: 0;
margin: 0
}
.table-fixed-head thead th{
background-color: white;
}
.row {
line-height: 20px;
background: #dafff5;
max-width: 200px;
margin: 0 auto;
box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.5);
}
.data{
width: 150px;
white-space: nowrap;
overflow: hidden;
margin-right: 20px;
}
```
I have spent 1.5 day trying to find the reason why the table bounces on scroll in React 18 without result.
BTW, overscroll-behaviour: none doesn`t work.
[1]: https://i.stack.imgur.com/AHoNg.gif
[2]: https://i.stack.imgur.com/L2QEa.gif |
Why is this String suddenly null in my chat_gpt_sdk run? |
|flutter|dart|chatgpt-api| |
null |
I'm trying to create a picker to select a ShoppingCategory from a menu. However, when displaying the menu, none of the images show up besides the selected image. The user can still click on the empty cells, but no images are displayed.
Here's the view code:
```
@State private var category: ShoppingCategory? = nil
var body: some View {
Picker("Category", selection: $category) {
Image(systemName: "slash.circle")
.tag(ShoppingCategory?(nil))
ForEach(ShoppingCategory.allCases, id: \.self) { category in
category.systemImage
.resizable()
.frame(width: 32)
.tag(ShoppingCategory?(category))
}
}
.pickerStyle(.menu)
}
```
And here's the ShoppingCategory enum:
```
enum ShoppingCategory: Int, CaseIterable, Codable {
case groceries
case pet
case restauraunt
case furniture
case clothes
case makeup
case household
case toys
case tech
case games
var systemImageName: String {
switch self {
case .groceries: "carrot"
case .pet: "pawprint"
case .restauraunt: "fork.knife"
case .furniture: "chair.lounge"
case .clothes: "hanger"
case .makeup: "sparkles"
case .household: "house"
case .toys: "teddybear"
case .tech: "desktopcomputer"
case .games: "gamecontroller"
}
}
var systemImage: Image {
Image(systemName: systemImageName)
}
}
```
[Here's what it displays when clicking on the menu:](https://i.stack.imgur.com/E5t1M.png)
I tried putting the options in a regular Menu view, but the same thing happened:
```
Menu {
Button {
self.category = nil
} label: {
Image(systemName: "slash.circle")
.resizable()
.frame(width: 32)
}
ForEach(ShoppingCategory.allCases, id: \.self) { category in
Button {
self.category = category
} label: {
category.systemImage
.resizable()
.frame(width: 32)
}
}
} label: {
if let category {
category.systemImage
} else {
Image(systemName: "slash.circle")
}
}
```
[Here's the result:](https://i.stack.imgur.com/u6Jcp.png)
|
Why aren't images appearing inside of SwiftUI's Picker? |
|swift|swiftui|picker| |
null |
- See this [answer][1] for the correct way to pass positional arguments to the seaborn plotting API.
- Dataframes passed to seaborn should be tidy (long-form), not a wide-form, which can be implemented with `pandas.DataFrame.melt`, as shown in the answers to this [question][2].
- Seaborn’s preferred approach is to work with data in a 'long-form' or 'tidy' format. This means that each variable is a column and each observation is a row. This format is more flexible because it makes it easier to subset the data and create complex visualizations.
- General use cases:
- Line plot: continuous data, such as a value against dates
- Bar chart: categorical data, such as a value against a category
- Scatter plot: bivariate plots showing the relationship between two variables measured on a single sample of subjects
- **Tested in `python v3.12.0`, `pandas v2.2.1`, `matplotlib v3.8.1`, `seaborn v0.13.2`.**
```python
import yfinance as yf
import seaborn as sns
import matplotlib.pyplot as plt
# download the data
end_of_year_2018 = yf.download(['ABBN.SW', 'ADEN.SW', 'CFR.SW', 'SGSN.SW', 'HOLN.SW', 'NESN.SW', 'NOVN.SW', 'ROG.SW', 'SREN.SW', 'SCMN.SW', 'UHR.SW', 'UBSG.SW', 'ZURN.SW'], start='2018-12-28', end='2023-12-29')['Adj Close']
# convert the data to a long form
end_of_year_2018_long = end_of_year_2018.melt(ignore_index=False).reset_index()
# plot
plt.figure(figsize=(10, 8))
ax = sns.scatterplot(data=end_of_year_2018_long, x='Date', y='value', hue='Ticker', marker='.')
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
```
[![enter image description here][3]][3]
- Optionally, use `sns.relplot`, which removes the need to separately set the figure size and legend position.
```python
g = sns.relplot(data=end_of_year_2018_long, x='Date', y='value', hue='Ticker', marker='.', height=7)
```
[![enter image description here][4]][4]
___
## Notes
- If many dates are being compare, a line chart, not a scatter plot, should be used.
```python
g = sns.relplot(kind='line', data=end_of_year_2018_long, x='Date', y='value', hue='Ticker', aspect=3)
```
[![enter image description here][5]][5]
- To compare the values for a single date, as suggested by the use of `start='2018-12-28', end='2018-12-29'`, then a bar chart, not a scatter plot, should be used.
```python
end_of_year_2018 = yf.download(['ABBN.SW', 'ADEN.SW', 'CFR.SW', 'SGSN.SW', 'HOLN.SW', 'NESN.SW', 'NOVN.SW', 'ROG.SW', 'SREN.SW', 'SCMN.SW', 'UHR.SW', 'UBSG.SW', 'ZURN.SW'], start='2018-12-28', end='2018-12-29')['Adj Close']
end_of_year_2018_long = end_of_year_2018.melt(ignore_index=False).reset_index()
g = sns.catplot(kind='bar', data=end_of_year_2018_long, x='Ticker', y='value', aspect=3)
_ = g.fig.suptitle('Adjusted Close for 2018-12-28')
```
[![enter image description here][6]][6]
---
### `end_of_year_2018.head()`
```lang-none
Ticker ABBN.SW ADEN.SW CFR.SW HOLN.SW NESN.SW NOVN.SW ROG.SW SCMN.SW SGSN.SW SREN.SW UBSG.SW UHR.SW ZURN.SW
Date
2018-12-28 15.066603 34.481403 58.147148 32.570705 70.373329 55.331772 208.348633 381.062653 74.905602 64.147781 10.002420 254.402374 222.631409
2019-01-03 14.885272 32.702148 56.541176 31.991671 71.643211 55.305443 213.356201 389.256622 75.007278 64.133545 10.010596 245.528900 222.555435
2019-01-04 15.260020 34.211132 58.664013 33.704643 72.577995 55.845329 214.854187 389.500031 76.939247 65.130074 10.317168 254.047409 225.745667
2019-01-07 15.151222 34.714130 59.033199 33.350792 71.537399 54.712891 212.200623 389.743408 77.007027 64.930763 10.337606 254.047409 223.846725
2019-01-08 15.360760 35.795193 60.048466 33.817234 71.872498 55.753159 216.138184 386.336060 77.515434 65.001945 10.398920 260.081360 226.505249
```
### `end_of_year_2018_long.head()`
```lang-none
Date Ticker value
0 2018-12-28 ABBN.SW 15.066603
1 2019-01-03 ABBN.SW 14.885272
2 2019-01-04 ABBN.SW 15.260020
3 2019-01-07 ABBN.SW 15.151222
4 2019-01-08 ABBN.SW 15.360760
```
### `end_of_year_2018`
- With `start='2018-12-28', end='2018-12-29'`, which is only one day of data.
```lang-none
Ticker ABBN.SW ADEN.SW CFR.SW HOLN.SW NESN.SW NOVN.SW ROG.SW SCMN.SW SGSN.SW SREN.SW UBSG.SW UHR.SW ZURN.SW
Date
2018-12-28 15.066599 34.4814 58.147148 32.570705 70.373329 55.331787 200.049286 381.062653 74.905609 64.147789 10.002419 254.402344 222.631409
```
---
- As noted by [@JohanC][7], `markers=['.']*len(end_of_year_2018.columns)` can work.
- `markers=False` results in [a bug][8].
```python
ax = sns.scatterplot(data=end_of_year_2018, markers=['.']*len(end_of_year_2018.columns))
```
[1]: https://stackoverflow.com/a/64133229/7758804
[2]: https://stackoverflow.com/q/36537945/7758804
[3]: https://i.stack.imgur.com/Xgh83.png
[4]: https://i.stack.imgur.com/1Vzge.png
[5]: https://i.stack.imgur.com/Nrw7d.png
[6]: https://i.stack.imgur.com/OgBDj.png
[7]: https://stackoverflow.com/users/12046409/johanc
[8]: https://github.com/mwaskom/seaborn/issues/3652 |
I've the following string containing HMTL. What would be sample code in JavaScript to remove leading and trailing white spaces that would appear in the rendering of this string? In other words: how can I obtain a string that would not show any leading or training white spaces in the HTML rendering but otherwise be identical?
```html
<p> </p>
<div> </div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p> </p>
<div> </div>
```
In this scenario, the following criteria was used to decide whether something is a whitespace or not. This is a customized definition of whitespaces according to what I was needing at the time I posted this question.
1. a string that wasn't displaying a non-blank printable character and also was not showing any noticeable/desirable effect according to our requirements, was being treated as a whitespace
2. a string that is considered whitespace by the JavaScript's trim method was also a whitespace
If a whitespace is within an element tag that also contains non-blank display character(s) within the html element tag then the whitespace is not trimmed even though it may be a leading or trailing whitespace.(whitespaces within a an element are put there by the developer for a reason and we should not be trimming in such cases).
So, `<br />` shows no non-blank printable character, and therefore its a whitespace in this scenario. (But in another system of custom whitespaces, this same `<br />` tag may not be a whitespace since it produces a noticeable/desirable effect of a new line.)
Also, `<div> </div>` or `<p> </p>` are both considered whitespace since they produce no non-blank printable characters nor produce any noticeable/desirable effect according to requirements. |
I want the `addNumbers` function to always return a number, adding `b` or `c` to `a`. Argument `a` is always required, `b` and `c` are required, but [mutually exclusive][1], meaning only `b` or `c` should be passed, but not both at the same time.
I tried:
```ts
function addNumbers1({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)):
// here typescript complains "Function lacks ending return statement and return type does not include 'undefined'.(2366)"
number {
if (b) {
return a + b;
}
if (c) {
return a + c;
}
}
```
Because of the `Function lacks ending return statement and return type does not include 'undefined'.(2366)` error, I tried to check that `a` or `b` are always defined to never allow the case of not having a return type like so:
```ts
function addNumbers2({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)): number | string {
// added this line to guard against b or c being undefined.
if (b === undefined && c === undefined) return "error";
// at this point b or c should definitely be defined, so one of the following conditions would always return a number.
// however typescript still complains: Function lacks ending return statement and return type does not include 'undefined'.(2366)
if (b) {
return a + b;
}
if (c) {
return a + c;
}
}
```
Now I try something else:
```ts
function addNumbers3({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)): number | string {
// make sure again that either b or c is defined
if (b === undefined && c === undefined) return "error";
if (b) {
return a + b;
} else {
// but now I get "'c' is possibly 'undefined'.(18048)"
// how can that be with the check above?
return a + c;
}
}
```
What is the best approach to handle this problem? I want to keep the function's arguments as they are.
[Playground][2]
[1]: https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist/60617060#60617060
[2]: https://www.typescriptlang.org/play?#code/PTAEEMBtIgTWByBXAtgIwKYCcDOoBmSAdgMYAuAlgPZF4AW4AbhhFgOaoZFkSgC8oIqkxYIRWKw4ouPNKAAeVUSQh4h6bKAAUc8ONArwPMnRY5w00JUtEqPKJCoB3DLACUAOlA4MLOmTIABxwALhAcMnASAGsqZix8RycPEioUYHBgADYABiyARgB2PJzgACYygA4AFgBWHIAoBpBQAElQJz17eGQNXCsqCEhOgE88LAwyJCwiXnURABo4WAoiNlAAIjQN0CVNkh2yQY3wDY8mwlJKGmXekRx8rQBvBtAIBdfQNA+3kg+AXxCoCeECB800-1AADJtJ8AD7Ar5g4TYADcBgA-GCMPFQP94YiSMi+ui0FjBDiIQ03G4gc0wKYJlYRoEMDgSFgKIEeKkUIFIOBVngNgAxYjkaizAUxPBcFZrUATKYzbyRMgYaTcMQSJXTWZkFksWBUNmCOygVYkSBIWAsADkxFt+FWrjtHi0ZQAzFksm4Ng1waIXp8KPhtGg3MDPm9dSrwKAANRfVGffEhsNaEiRl5vGOTPW8JMkFNvfFplpUaLgEZWUxEJaQSZ4MhYGs4NKTOirNgeXsNS4Sm7gHoo3BlZ6fcA-L7Tv4NQGI8DEkR46Gwt4IkFoZdozHY3H4jeEndYUnkoiU0T4mkn0AIiKchXBt4tYe2iQmCh4SAugagDjgFgEjgGwgq0LIuzKF8GDdqAjoYM6F6wOcbyhuG-B8AI8GIa40IwiomFYeICEuu4ir5iqGzYFgSgbCmnyvsYXZ4IEVCrBBewqDgdBUEgkASE6qwUOqkA1pgoCCUhSztrsF67GGJgsPgVDQM4sGpOIwmSngTi8fxQyjOMFGzPGgYoaALQ8S4uIGqy7KctyqoUNABhpPyYGhKAYpXJKoDStEsqaQqsazBERgajI2rkcq+qGhJJpqOalrWraoAOsROGwG6Hrer6TSoRmEZRrm0UFvGSZoCWeL5RaGZZsVuYhYWBhVWWTQtI2ZDNq2HTCXQYigBgkA+L25wDtcJkjn0OCehObxTp83yfHOC4gkugijquMJaASW4nuiJDnpe1VHiCRIbSSXxHQe1K0hdK45rV4bZtGpVxomyapoNw0sI9L5gLYTgWjw5hjGlJB2haLFUDgOAUGgolpdhpHZfklQ5NUlRuK9TXlS1qbzhc4oTbco44NUc3vIts4AkCa23pC227Ui927od+5UqdBj7VdHNXrdt73i2sHPhZYCVtWtZcEsKDgNEZjTCwIFgbWRiDX1mhyJxUMSSRSHpuhhFwRlpF4QYGFEZJriRk1VFYDRWB0TVaE6C9JW4x9lVfUNPgNf9TkucJ3jVngdoQzrrGw-DiPpVbWXumjGNY69lnOAYeiq7ILBOH1UsGKYMQQGgcQYBiOPGc1xYE+WYAAOoMDwX555gEQQIEgQ0VE-VHKADDiI2tZNx3VAIxqGJAA |
SQL Server: Joining Multiple Columns to the Same DIM Table |
|sql-server| |
I'm working on writing some tests for a function that takes some user supplied data and returns a JSON string based on a template. Up until now, I have simply been doing assertions that compare the entire output string against an 'expected' json document. It works, but the tests are brittle. Any change to the output requires updating the expected document, even if the change is unrelated to what is being tested.
What I should be doing is making assertions against specific sections of the json output, but I am struggling to find a library that does what I want. JsonPath can get the job done, but the syntax is unwieldy. I know where the particular data I want to test is, but trying to craft the exact JsonPath query string to retrieve it is a time consuming slog.
What I'm hoping to find is a library that allows me to add a 'tag' comment to a json element that I can use in my tests to get the exact data I need. Something like:
{
"elementType": "formInputHidden",
"name": "message_id",
"value": "274"
},
{
"elementType": "formInputHidden",
"name": "message_status",
"value": "PENDING_MODERATOR_APPROVAL"
}
Then in my test I could do a lookup like:
Object result = jsonFind.get(jsonOutput, "name", "message_id");
//result="274"
Does anything like this exist? |
I have an HTML table with the following structure:
```
<table>
<thead>..</thead>
<tbody>
<tr>
<td>some</td>
<td>content</td>
<td>etc</td>
</tr>
<tr class="certain">
<td><div class="that-one"></div>some</td>
<td>content</td>
<td>etc</td>
</tr>
several other rows...
<tbody>
</table>
```
And I am trying to figure out what to do with the `<div class="that-one">` (or any other element, if needed) inside the table so it can be painted outside the table.
I have tried the negative left property, ```transform: translateX(-20px)```, and ```overflow: visible```.
I know that there is something different with rendering HTML tables. I cannot change the structure of the table just can add whatever element inside.
Finding: both negative left property and ```transform: translateX(-20px)``` work in Firefox but don't work in Chrome (behaves like ```overflow: hidden```).
Have some Javascript workaround on my mind, but would rather stay without it.
Also, I don't want it as CSS pseudoelement, because there will be some click event binded. |
I need to extract info from a professional experience section like the following and store the result in a dataframe.
https://www.linkedin.com/in/maxlvsq/details/experience/
[enter image description here][1]
I have been reading about how to do it, including this stack overflow thread: https://stackoverflow.com/questions/75539164/get-the-experience-section-of-a-linkedin-profile-with-selenium-and-python, which proposes this solution:
jobs = driver.find_elements(By.CSS_SELECTOR, 'section:has(#experience)>div>ul>li')
for job in jobs:
exp['job'] += [job.find_element(By.CSS_SELECTOR, 'span[class="mr1 t-bold"] span').text]
exp['company'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal"] span').text]
exp['date'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"] span').text]
try:
exp['location'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"]:nth-child(4) span').text]
except NoSuchElementException:
exp['location'] += ['*missing value*']
try:
exp['description'] += [job.find_element(By.CSS_SELECTOR, 'ul li ul span[aria-hidden=true]').text]
except NoSuchElementException:
exp['description'] += ['*missing value*']
This solution however does not work for me, because the elements do not exist anymore under those names. Here is what I tried. I can get out the description and timeframes (but I face the issue that the lists have different length). For the position, company name, and location I have not been able to find the class or id names.
# description
descriptions = driver.find_elements(By.CLASS_NAME, 'pvs-list__outer-container')
# timeframes
timeframes = driver.find_elements(By.CLASS_NAME, 'pvs-entity__caption-wrapper')
Is there anyone who knows how to fix that?
Thanks :)
|
Image: https://i.stack.imgur.com/3dIm0.png
I have a method called Background Blur, but it completely blurs the background of the window, and even if the window is transparent, the corners of the window look bad. How can I ensure that this is applied only to the background of the border?
Blur.cs:
```
namespace TestApp
{
internal enum AccentState
{
ACCENT_DISABLED = 1,
ACCENT_ENABLE_GRADIENT = 0,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
[StructLayout(LayoutKind.Sequential)]
internal struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
internal enum WindowCompositionAttribute
{
// ...
WCA_ACCENT_POLICY = 19
// ...
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class Blurx
{
[DllImport("user32.dll")]
internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
internal void EnableBlur(dynamic Element)
{
IntPtr hwnd;
PresentationSource source = PresentationSource.FromVisual(Element);
hwnd = source != null ? ((HwndSource)source).Handle : IntPtr.Zero;
AccentPolicy accent = new AccentPolicy
{
AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND
};
int accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
WindowCompositionAttributeData data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
SetWindowCompositionAttribute(hwnd, ref data);
Marshal.FreeHGlobal(accentPtr);
}
public void Show(dynamic Element)
{
EnableBlur(Element);
}
}
}
```
MainWindow.Xaml.cs:
```
namespace TestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Blurx Blur;
public MainWindow()
{
InitializeComponent();
Blur = new Blurx();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Blur.Show(Main);
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
}
}
```
MainWindow.Xaml:
```
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestApp"
mc:Ignorable="d"
WindowStyle="None"
Background="Transparent"
AllowsTransparency="True"
Title="MainWindow" Loaded="Window_Loaded" MouseLeftButtonDown="Window_MouseLeftButtonDown" Height="500" Width="500">
<Border CornerRadius="50" x:Name="Main" Background="#7FDE7AFF">
</Border>
</Window>
```
[1]: https://i.stack.imgur.com/QSSft.png |
Depending on what exactly you mean by "the text", you probably want the [`get_body` method.](https://docs.python.org/3/library/email.message.html#email.message.EmailMessage.get_body) But you are thoroughly mangling the email before you get to that point. What you receive from the server isn't "HTML" and converting it to a string to then call `message_from_string` on it is roundabout and error-prone. What you get are bytes; use the `message_from_bytes` method directly. (This avoids all kinds of problems when the bytes are not UTF-8; the `message_from_string` method only really made sense back in Python 2, which didn't have explicit `bytes`.)
```
from email.policy import default
...
_, response = imap.uid(
'fetch', e_id, '(RFC822)')
email_message = email.message_from_bytes(
response[0][1], policy=default)
body = email_message.get_body(
('html', 'text')).get_content()
```
The use of a `policy` selects the (no longer very) new `EmailMessage`; you need Python 3.3+ for this to be available. The older legacy `email.Message` class did not have this method, but should be avoided in new code for many other reasons as well.
This could fail for multipart messages with nontrivial nested structures; the `get_body` method without arguments can return a `multipart/alternative` message part and then you have to take it from there. You haven't specified what your messages are expected to look like so I won't delve further into that.
More fundamentally, you probably need a more nuanced picture of how modern email messages are structured. See https://stackoverflow.com/questions/48562935/what-are-the-parts-in-a-multipart-email |
Thats my first post on stackoverflow so i hope i'm doing this properly, if not let me know.
i have a problem with the code, but i cant see were. The CS50 check gives me un output error:
**
*":( encrypts "This is CS50" as "Cbah ah KH50" using yukfrnlbavmwzteogxhcipjsqd as key.
Cause:
output not valid ASCII text"***
```
Thats the code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./substitution\n");
return 1;
}
string key = argv[1];
if (strlen(key) != 26)
{
printf("The key must contain 26 characters\n");
return 1;
}
for(int i = 0; i < strlen(key); i++)
{
if (!isalpha(key[i]))
{
printf("Usage: ./substitution\n");
return 1;
}
}
for (int i = 0; i < strlen(key); i++)
{
for(int j = i + 1; j < strlen(key); j++)
{
if (toupper(key[i]) == toupper(key[j]))
{
printf("Usage: substitution key\n");
return 1;
}
}
}
string plaintext = get_string("Plaintext: ");
printf("ciphertext: ");
for(int i = 0; i < strlen(plaintext); i++)
{
if(isupper(plaintext[i]))
{
int letter = plaintext[i] - 'A';
printf("%c", key[letter]);
}
else if(islower(plaintext[i]))
{
int letter = plaintext[i] - 'a';
printf("%c", tolower(key[letter]));
}
else if (plaintext[i] == ' ') // Handle spaces
{
printf(" ");
}
else
{
printf("%c",plaintext[i]);
}
}
printf("\n");
return 0;
}
``` |
I figured it out. The issue was the script was running before the loading js was. I couldn't change the order of the code in the theme, so I added a delay when the code is run on click.
// Update reveal with all .post-list-card items
function updateReveal() {
setTimeout(function() {
const updatedSections = document.querySelectorAll(".post-list-card");
reveal = Array.from(updatedSections); // Update the reveal array
reveal.forEach((newSection) => {
sectionObserver.observe(newSection); // Observe new items
});
},800);
}
|
I solved the problem.
This configuration is for window, but I think it will have been working on Linux too.
You need to configure 3 files.
--------------------
1-httpd.conf
2-httpd-vhost.conf
3-httpd-ssl.conf
General rules
do not use 0.0.0.0:80
do not use 0.0.0.0:443
or
[::]:80
[::]:443
Keep all original like *:80 *:443
-----------
1-httpd.conf
--------
(keep original)
Listen *:80 or Listen 80
Never define any <VirtualHost *:80 > in httpd.conf, we will define it at httpd-vhost.conf
Never define any <VirtualHost *:443 > in httpd.conf, we will define it at httpd-ssl.conf
Never define any ssl certificate in httpd.conf
otherwise the system is confused make you wait 5s periodically..
Define Directory tag of each vhost like this:
Example:
DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">
Options Indexes FollowSymLinks Includes
AllowOverride All
Require all granted
</Directory>
<Directory "C:/xampp/htdocs2">
Options Indexes FollowSymLinks Includes
AllowOverride All
Require all granted
</Directory>
---------------------
2- httpd-vhost.conf
---
Never define any ssl certifiacte in httpd-vhost.conf
Never Never define any <VirtualHost *:443 > in vhost file, we will define it at httpd-ssl.conf
otherwise you have to wait 5sn periodically.
Define <VirtualHost> only for 80 port and dont use 0.0.0.0:80 in tags etc, keep original like below
Example:
<VirtualHost *:80 >
ServerName domain1.com
DocumentRoot "C:/xampp/htdocs/htdocs"
ErrorLog "logs/error-hh2.log"
</VirtualHost>
<VirtualHost *:80 >
ServerName domain2.com
DocumentRoot "C:/xampp/htdocs/htdocs2"
ErrorLog "logs/error-hh2.log"
</VirtualHost>
---------------------
3- httpd-ssl.conf
---
Apache is starting to listen 443 port in this file, so after listen 443 or at the bottom add following naturally.
(keep original)
Listen 443
#edit existing
<VirtualHost *:443 >
ServerName domain1.com
DocumentRoot "C:/xampp/htdocs/htdocs"
ErrorLog "logs/error-hh.log"
SSLEngine On
SSLCertificateFile conf/ssl_hh/server.crt
SSLCertificateKeyFile conf/ssl_hh/server.key
SSLCertificateChainFile conf/ssl_hh/server-ca.key
#keep FilesMatch or BrowserMatch parameter as original if not needed
</VirtualHost>
#add for second domain
<VirtualHost *:443 >
ServerName domain2.com
DocumentRoot "C:/xampp/htdocs/htdocs2"
ErrorLog "logs/error-hh2.log"
SSLEngine On
SSLCertificateFile conf/ssl_hh/server2.crt
SSLCertificateKeyFile conf/ssl_hh/server2.key
SSLCertificateChainFile conf/ssl_hh/server2-ca.key
</VirtualHost>
That is all.
Edit :
---
!!! Do not forget to add SSLCertificateChainFile CA file.
--- |
#include <stdio.h>
#include <math.h>
#define MAX_BITS 32
int counter = 0, dec_eqv = 0;
int runcounter = 1;
int binToDec(char *bit)
{
printf("dec_eqv is %d\n", dec_eqv);
if (counter == 0 && runcounter)
{
dec_eqv = 0;
int i = 0;
while (*(bit + i++))
;
counter = (i - 1) - 1;
runcounter = 0;
printf("counter is %d\n", counter);
}
if (*bit != 0)
{
printf("*bit not zero\n");
if (*bit == '1')
{
dec_eqv += (int)pow(2, counter--);
}
else
{
counter--;
}
binToDec(bit + 1);
}
else
{
printf("here *bit is 0\n");
runcounter = 1;
printf ("here dec_eqv is %d\n", dec_eqv);
return dec_eqv;
printf ("Skipping return\n");
}
return -1;
}
int main()
{
char bin[MAX_BITS];
printf("Enter binary number (%d-bit max): ", MAX_BITS);
scanf("%[^\n]s", bin);
int result = binToDec(bin);
printf("Decimal equivalent of 0b%s is %d.", bin, result);
return 0;
}
I've added the ```printf()``` statements in ```binToDec()``` for debugging, and it seems that the compiler is ignoring the ```return dec_eqv;``` statement in the final ```else``` block and directly executing the ```return -1;``` at the end. What could be possibly wrong? I am using Clang/LLVM compiler in Ubuntu 23.10 AMD64. |
```
void _rotateScreen() {
final currentOrientation = MediaQuery.of(context).orientation;
if (currentOrientation == Orientation.portrait) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
]);
} else {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
}
setState(() {});
}
```
when i click the button screen is rotating down but if screen is down its not come again portrait up |
Flutter rotate the screen |
|android|flutter|rotation|screen| |
null |
I am trying to make an animation where n points are equally distributed around a circle and an animation displays the permutations of those points by swapping their positions simultaeneously .
My issue is that when the animation ends either one of the points disappears from the scene or two distinct points get sent to the same position , here's the code :
```
from manim import*
import numpy as np
from itertools import*
import random
class CircleWithPoints(Scene):
def construct(self):
n = 6 # Number of points
radius = 2
colors = [RED, GREEN, GOLD, BLUE, PINK, PURPLE]
# Create circle
circle = Circle(radius=radius, color=WHITE)
self.play(Create(circle))
# Create points and assign colors
points = []
for i in range(n):
angle = i * 2 * np.pi / n
x = radius * np.cos(angle)
y = radius * np.sin(angle)
point = Dot(point=[x, y, 0], color=colors[i])
points.append(point)
self.play(Write((point)),run_animation=.25)
all_permutations = list(permutations(range(n)))
random_permutation =list(random.choice(all_permutations))
# Permutation animation
new_points=[]
animated_new_points=[]
animated_points=[]
for i in range(n):
next_index = random_permutation[i-1]
next_point = points[next_index-1]
if next_point is not points[i]:
animated_new_points.append(next_point)
animated_points.append(points[i])
self.wait(1)
self.play(*[Swap(animated_points[i],animated_new_points[i]) for i in range(len(animated_points))])
self.wait(1)
```
I tried making a copy of the list of points to only take into account the points that are not fixed by the permutation however it doesn't seem like it worked
|
Indeed, KeyboardAvoidingView is not always easy to handle. Here are a few ideas:
1. Try to use KeyboardAvoidingView without absolute positioning. If needed, wrap such view in another that uses `position: absolute`, but leave this one with relative positioning.
2. Try replacing `behaviour={"position"}` with `padding` or `height` [(Docs)][1], and see what works best for your scenario. I usually use `padding` for Android and `position` for iOS.
3. Check if `KeyboardAvoidingView` has been imported from the correct module.
4. Edit your question to include the `styles.container` styling so we can see weather it has any impact on the implementation
[1]: https://reactnative.dev/docs/keyboardavoidingview#behavior |
I want the `addNumbers` function to always return a number, adding `b` or `c` to `a`. Argument `a` is always required, `b` and `c` are required, but [mutually exclusive][1], meaning they are not to be passed at the same time.
I tried:
```ts
function addNumbers1({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)):
// here typescript complains "Function lacks ending return statement and return type does not include 'undefined'.(2366)"
number {
if (b) {
return a + b;
}
if (c) {
return a + c;
}
}
```
Because of the `Function lacks ending return statement and return type does not include 'undefined'.(2366)` error, I tried to check that `a` or `b` are always defined to never allow the case of not having a return type like so:
```ts
function addNumbers2({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)): number | string {
// added this line to guard against b or c being undefined.
if (b === undefined && c === undefined) return "error";
// at this point b or c should definitely be defined, so one of the following conditions would always return a number.
// however typescript still complains: Function lacks ending return statement and return type does not include 'undefined'.(2366)
if (b) {
return a + b;
}
if (c) {
return a + c;
}
}
```
Now I try something else:
```ts
function addNumbers3({
a,
b,
c,
}: { a: number } & (
| { b: number; c?: never }
| { c: number; b?: never }
)): number | string {
// make sure again that either b or c is defined
if (b === undefined && c === undefined) return "error";
if (b) {
return a + b;
} else {
// but now I get "'c' is possibly 'undefined'.(18048)"
// how can that be with the check above?
return a + c;
}
}
```
What is the best approach to handle this problem? I want to keep the function's arguments as they are.
[Playground][2]
[1]: https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist/60617060#60617060
[2]: https://www.typescriptlang.org/play?#code/PTAEEMBtIgTWByBXAtgIwKYCcDOoBmSAdgMYAuAlgPZF4AW4AbhhFgOaoZFkSgC8oIqkxYIRWKw4ouPNKAAeVUSQh4h6bKAAUc8ONArwPMnRY5w00JUtEqPKJCoB3DLACUAOlA4MLOmTIABxwALhAcMnASAGsqZix8RycPEioUYHBgADYABiyARgB2PJzgACYygA4AFgBWHIAoBpBQAElQJz17eGQNXCsqCEhOgE88LAwyJCwiXnURABo4WAoiNlAAIjQN0CVNkh2yQY3wDY8mwlJKGmXekRx8rQBvBtAIBdfQNA+3kg+AXxCoCeECB800-1AADJtJ8AD7Ar5g4TYADcBgA-GCMPFQP94YiSMi+ui0FjBDiIQ03G4gc0wKYJlYRoEMDgSFgKIEeKkUIFIOBVngNgAxYjkaizAUxPBcFZrUATKYzbyRMgYaTcMQSJXTWZkFksWBUNmCOygVYkSBIWAsADkxFt+FWrjtHi0ZQAzFksm4Ng1waIXp8KPhtGg3MDPm9dSrwKAANRfVGffEhsNaEiRl5vGOTPW8JMkFNvfFplpUaLgEZWUxEJaQSZ4MhYGs4NKTOirNgeXsNS4Sm7gHoo3BlZ6fcA-L7Tv4NQGI8DEkR46Gwt4IkFoZdozHY3H4jeEndYUnkoiU0T4mkn0AIiKchXBt4tYe2iQmCh4SAugagDjgFgEjgGwgq0LIuzKF8GDdqAjoYM6F6wOcbyhuG-B8AI8GIa40IwiomFYeICEuu4ir5iqGzYFgSgbCmnyvsYXZ4IEVCrBBewqDgdBUEgkASE6qwUOqkA1pgoCCUhSztrsF67GGJgsPgVDQM4sGpOIwmSngTi8fxQyjOMFGzPGgYoaALQ8S4uIGqy7KctyqoUNABhpPyYGhKAYpXJKoDStEsqaQqsazBERgajI2rkcq+qGhJJpqOalrWraoAOsROGwG6Hrer6TSoRmEZRrm0UFvGSZoCWeL5RaGZZsVuYhYWBhVWWTQtI2ZDNq2HTCXQYigBgkA+L25wDtcJkjn0OCehObxTp83yfHOC4gkugijquMJaASW4nuiJDnpe1VHiCRIbSSXxHQe1K0hdK45rV4bZtGpVxomyapoNw0sI9L5gLYTgWjw5hjGlJB2haLFUDgOAUGgolpdhpHZfklQ5NUlRuK9TXlS1qbzhc4oTbco44NUc3vIts4AkCa23pC227Ui927od+5UqdBj7VdHNXrdt73i2sHPhZYCVtWtZcEsKDgNEZjTCwIFgbWRiDX1mhyJxUMSSRSHpuhhFwRlpF4QYGFEZJriRk1VFYDRWB0TVaE6C9JW4x9lVfUNPgNf9TkucJ3jVngdoQzrrGw-DiPpVbWXumjGNY69lnOAYeiq7ILBOH1UsGKYMQQGgcQYBiOPGc1xYE+WYAAOoMDwX555gEQQIEgQ0VE-VHKADDiI2tZNx3VAIxqGJAA |
Swap method results in disappearing points in Manim scene |
|animation|permutation|swap|manim| |
null |
I wrote the code using the pyautogui library. I tried to compile the file using modules such as pyinstaller, nuitka, auto-py-to-exe, but when opening the resulting file it gives the error "No module named pyautogui". How can I import this library into an exe file so that everything works and there are no errors?
I want to get an exe file that won't cause an error when opened. How can I do that? |
Error "No module named autopygui" after opening the compiled exe file |
|python|python-3.x|pyinstaller|auto-py-to-exe|nuitka| |
null |
Question:
Given an integer array S of length N(N=100,000),there are M(M≥2) workers concurrently accessing and updating S.Each worker repeats the following operation 10,000 times:
Generate random numbers i and j, 0≤i, j<100,000. Update S such that S(j)=S(i)+S(i+1)+S(i+2). If i+1 or i+2 is out of bounds, then use (i+1)%N or (i+2)%N.
Hint: (a) Please consider concurrent protection,i.e.. reading S(i),S(i+1),S(i+2) and updating S(j) are atomic operations. *Refer to the two-phase locking algorithm. (b) Pay attention to the lock granularity. Each worker only reads 3 elements at a time and writes 1 element. There are a total of 100,000 elements. The probability that concurrent workers access the same element is very low. Using fine-grainted locks can reduce conflicts and improve concurrency. (c) Pay attention to the difference between read locks and write locks. (d) j may fall in the [i, i+2] range. (e) Addtional thinking: Will deadlock occur? How to avoid?
Regarding to this question, I tried using segmented locking technique. This method divides the shared array into multiple segments, each segment is protected by a mutex, and each thread only needs to lock the segment it accesses. Is this idea feasible or are there any better suggestions? |
The problem of "fine-grained locks and two-phase locking algorithm" |
|c++|multithreading|locking| |
null |
I'm making a YouTube downloader. A bug has come up with playlists and I want it to check if the inputed link is a playlist. This is done by checking for the presence of `list`. So, I copied my normal `if` statement and ran it, but it didn't like this:
```shell
if "%link:list=%" == "%link%" goto Playlist
```
I think the three special characters affecting it that are used in Youtube Playlist links are `?` and `&` and `=`
ChatGPT kept trying to use either of the first two examples below. The first one I can't use as I rely on `%ERRORLEVEL`, and log the errors. The second one gave the same error codes as my original attempt.
First version:
```shell
echo %link%| findstr /C:"list=" >nul 2>&1
if %ERRORLEVEL% equ 0 goto Playlist
```
Second version:
```shell
if not x%test_link:list=%==x%link% goto Playlist
```
This third version made me give up on ChatGPT, so now I'm here!
```shell
REM Check if 'list=' is part of the string
for /F "tokens=1,2 delims=&" %%A in ("%test_link%") do (
if "%%B" neq "" (
if "%%A" neq "%%Alist=" (
set "playlist=1"
)
)
)
``` |
Hovering doesn't want to work by any way.
Code Below: -
```
self.setStyleSheet("""
QMenuBar {
background-color: white;
color: black;
border: 3px solid silver;
font-weight: bold;
font-size: 23px;
}
QMenuBar::item {
background-color: white;
border: 2px solid silver;
}
QMenuBar::item::selected {
background-color: grey;
}
QLabel:hover { #I tried both QLabel and QWidgetAction
background-color: grey;
}
""")
```
And here the QWidgetAction and QLabel below: -
```
self.Menu = QMenuBar(self)
self.Menu.resize(self.width(), 40)
self.Menu.move(0, 0)
self.File = self.Menu.addMenu('File')
self.FileNew = QWidgetAction(self.File)
self.New = QLabel("New")
self.New.setMouseTracking(True)
self.New.setAlignment(QtCore.Qt.AlignCenter)
self.New.setStyleSheet("border: 2px solid silver; background-color: white; color: black; padding: 4 4 4 4px")
self.FileNew.setDefaultWidget(self.New)
```
I searched in many threads and docs abt :hover method and tried it but it didn't work for me. And when I hover with my mouse on the QWidgetAction it stills frozen.
Thanks for your time. |
|python|pyqt5|qlabel|qwidgetaction| |
Joining Multiple Columns to the Same DIM Table |
|sql|sql-server| |
I have an HTML table with the following structure:
```
<table>
<thead>..</thead>
<tbody>
<tr>
<td>some</td>
<td>content</td>
<td>etc</td>
</tr>
<tr class="certain">
<td><div class="that-one"></div>some</td>
<td>content</td>
<td>etc</td>
</tr>
several other rows...
<tbody>
</table>
```
And I am trying to figure out what to do with the `<div class="that-one">` (or any other element, if needed) inside the table so it can be painted outside the table.
I have tried the negative left property, ```transform: translateX(-20px)```, and ```overflow: visible```.
I know that there is something different with rendering HTML tables. I cannot change the structure of the table just can add whatever element inside.
Finding: both negative left property and ```transform: translateX(-20px)``` work in Firefox and Safari but don't work in Chrome (behaves like ```overflow: hidden```).
Have some Javascript workaround on my mind, but would rather stay without it.
Also, I don't want it as CSS pseudoelement, because there will be some click event binded. |
Basically, this is a Bash/shell question. Let's talk about this variable:
```
'JAVA_TOOL_OPTIONS' : '-Djavax.net.ssl.trustStore=${TRUSTSTORE} -Djavax.net.ssl.trustStorePassword=${TRUSTSTORE_PASSWORD}'
```
First, you need to understand who expands (replaces) the strings of the form `$FOO` at which point in time. In your case, it's certainly not Gradle (although you could have Gradle do that easily if, for example, you know `TRUSTSTORE` is static and won't dynamically change at container runtime). Most of the time, it's a shell program that replaces such strings.
Then, it's like you are asking the shell to replace a string inside a string that is replacing yet another string. That is, you want it to replace strings recursively such that, for example, `FOO="foo $FOO"` may expand to an infinite sequence of `foo`'s.
But Bash doesn't recursively expand variables: https://unix.stackexchange.com/questions/194028/variable-not-expanding-inside-another-variable-bash
For example,
```
$ ( INNER='inner' OUTER='$INNER' ; echo $OUTER )
$INNER
```
OTOH, the following script expands `$INNER` first and then assign the expanded value (the string literal of `inner`) to `OUTER`.
```
$ ( INNER='inner' OUTER="$INNER" ; echo $OUTER )
inner
```
---
Lastly, I am not sure if this will help, but just in case: https://stackoverflow.com/q/59357410/1701388
|
I figured out what was going on here. On macOS you need to load some specific extensions that are not loaded by default because macOS doesn't have native support for Vulkan.
Turns out that the environment variables *do not matter at all*.
It was all about loading the proper extensions. This is the code with the extensions added:
use anyhow::Result;
use ash::{self, vk};
fn main() -> Result<()> {
let mut extension_names = Vec::new();
extension_names.push(vk::KhrPortabilityEnumerationFn::name().as_ptr());
extension_names.push(vk::KhrGetPhysicalDeviceProperties2Fn::name().as_ptr());
let entry = unsafe { ash::Entry::load() }?;
let application_info = vk::ApplicationInfo::builder().api_version(vk::API_VERSION_1_3);
let create_flags = vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR;
let create_info = vk::InstanceCreateInfo::builder()
.application_info(&application_info)
.enabled_extension_names(&extension_names)
.flags(create_flags);
let instance = unsafe { entry.create_instance(&create_info, None) }?;
Ok(())
}
Now it can find the driver and runs without issues. |
I think I found the solution.
This is the new configuration inside `editorTheme`:
```javascript
editorTheme: {
projects: {
// To enable the Projects feature set this value to true
enabled: false
},
palette: {
catalogues: [ // Alternative palette manager catalogues
'https://catalogue.nodered.org/catalogue.json',
'https://dev.azure.com/myorg/myOtherCatalogue.json'
]
},
}
```
Now my question becomes. How do I expose my npm feed as 'https://dev.azure.com/myorg/myOtherCatalogue.json'
At the moment, I have to manually create that JSON, but I would like that to be somewhat "automatic".
How can I do that? |
So i'm trying to replicate a very fast C library which basically preallocates X amount of bytes to accomodate 99% of the use cases.
Data comes in, if size needed is less than X then it uses a stack pre-allocated buffer. If it doesnt the C library uses malloc.
I'm trying to do the same with rust but i think i'm using the wrong approach.
static mut TMP:[u64; 32] = [1u64; 32];
pub struct MaybePreallocated<'a> {
pub x: &'a [u64]
}
impl MaybePreallocated<'_> {
pub fn new(howmany: usize) -> Self {
if (howmany > 32) {
MaybePreallocated {
/// ????
}
} else {
MaybePreallocated {
x: &TMP
}
}
}
}
fn main() {
println!("Hello, world!");
}
Besides the "????" i really need to mutate the underlying data as part of the computation and i can, for now, be sure that only one instance of MaybePreallocated will exist.
The static mut is a bit scary tbh and would also love to have the dynamically allocated vec/slice to be freed when nobody owns any MaybePreallocated.
Is this possible in Rust?
If yes, how? |
Single-instanced struct with maybe preallocated databuffer |
|rust| |
Somewhen I wanted to create a case insensitive autoloader, so I used the Example here:
https://www.php-fig.org/psr/psr-4/examples/
... and modified it a bit.
I added a method to create pattern for `glob()`. It creates a pattern where every single char exists in uppercase and lowercase, as long it differs in case it is the same then there is no extra pattern needed so dots and slashes doesn't have uppercase or lowercase versions. path/file.php will look like [pP][aA][tT][hH]/[fF][iI][lL][eE].[pP][hH][pP].
It is not perfect, because in some cases in utf8 there are more than just one alternative char, so in case lowercase and uppercase differs from the given char, it also adds this to the pattern of possible chars, but just this one and not all alternatives.
/**
* Convert path and filename to a case insensitive pattern for glob().
*
* @param string $path
* @return string
*/
private function createCaseInsensitivePattern(string $path) {
$chars = mb_str_split($path);
$pattern = '';
foreach ($chars as $char) {
$lower = mb_strtolower($char);
$upper = mb_strtoupper($char);
if ($char == $lower && $char == $upper) {
$pattern .= $char;
} else {
$pattern .= '['.$lower.$upper.($char != $lower && $char != $upper?$char:'').']';
}
$pattern .= $char == '/' || $char == '\\' ? $char:('');
}
return $pattern;
}
And then I extended the `requireFile()` method with an else case.
So in case the file is not found in the correct case, then it simply calls the `createCaseInsensitivePattern()` method and does a `glob()` with the result. In case nothing fits, then it just returns false.
/**
* If a file exists, require it from the file system.
*
* @param string $file The file to require.
* @return bool True if the file exists, false if not.
*/
protected function requireFile(string $file)
{
if (file_exists($file)) {
require $file;
return true;
} else {
$filePattern = $this->createCaseInsensitivePattern($file);
$possibleFiles = glob($filePattern);
foreach ($possibleFiles as $currentFile) {
if (file_exists($currentFile)) {
require $currentFile;
return true;
}
}
}
return false;
}
In case you just want to do the file_exists, just remove the two "lines that start with `require`. |
|windows|if-statement|batch-file|special-characters|variable-expansion| |
I was developing a simple application to learn redis caching. Until I add redis as a caching mechanism on spring boot project the API's works fine. **REST** project you can say. Using Postman for calling different API. After adding redis I saw that `@CacheEvict` which is used for deleting data works fine. But when I call request like **GetMapping**, **PutMapping** which annotated with `@Cacheable`, `@CachePut` doesn't work. I don't understand what is the problem where `@CacheEvict` working perfectly `@Cacheable`, `@CachePut` doesn't.
Here is the **error** given by postman when I'm calling API's using following url:
**PUT:** `http://localhost:8080/bank/2/deposit`
**GET:** `http://localhost:8080/bank/holderName/Aysha`
{
"dateTime": "2024-03-30T16:49:17.7557062",
"message": "Cannot serialize",
"error": "uri=/bank/2/deposit",
"path": "Bad Request"
}
Let me explain in more detail how I configured redis:
**POM:**
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
**application.properties:**
spring.cache.type=redis
spring.cache.redis.time-to-live=60000
spring.cache.redis.host=localhost
spring.cache.redis.port=6379
**Account (Entity):**
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String holderName;
private double balance;
}
**Here I enabled caching:**
@SpringBootApplication
@EnableCaching
public class SimpleBankingApplication {
@Bean
public ModelMapper mapper(){
return new ModelMapper();
}
public static void main(String[] args) {
SpringApplication.run(SimpleBankingApplication.class, args);
}
}
**Controller class:**
@Controller
@RequestMapping("bank")
@AllArgsConstructor
@CacheConfig(cacheNames = "account")
public class AccountController {
private AccountService service;
@PostMapping("createAccount")
public ResponseEntity<AccountDTO> createAccount(@RequestBody @Valid AccountDTO dto){
return new ResponseEntity<>(service.addAccount(dto), HttpStatus.CREATED);
}
@GetMapping("holderName/{name}")
@Cacheable(value = "account", key = "#name")
public ResponseEntity<AccountDTO> getAccountByName(@PathVariable String name){
return new ResponseEntity<>(service.getAccount(name),HttpStatus.ACCEPTED);
}
@PutMapping("{id}/deposit")
@CachePut(cacheNames = "account", key = "#id")
public ResponseEntity<AccountDTO> deposit(@PathVariable Long id, @RequestBody Map<String, Double> request){
Double value = request.get("balance");
return new ResponseEntity<>(service.deposit(id,value), HttpStatus.ACCEPTED);
}
@PutMapping("{id}/withdraw")
public ResponseEntity<AccountDTO> withdraw(@PathVariable Long id, @RequestBody Map<String, Double> request){
Double value = request.get("withdraw_balance");
return new ResponseEntity<>(service.withdraw(id,value), HttpStatus.ACCEPTED);
}
@GetMapping("allAccounts")
public ResponseEntity<List<AccountDTO>> getAllAccount(){
return new ResponseEntity<>(service.getAllAccounts(),HttpStatus.ACCEPTED);
}
@DeleteMapping("deleteAccount/{id}")
@CacheEvict(cacheNames = "account", key = "#id", beforeInvocation = true)
public ResponseEntity<String> deleteAccount(@PathVariable Long id){
service.delete(id);
return new ResponseEntity<>("Account has been deleted!!!", HttpStatus.ACCEPTED);
}
}
**Project link:** [view the project][1]
[1]: https://github.com/SakibvHossain/Simple-Banking-Application |
Cannot serialize (Spring Boot) |
|java|spring-boot|caching|redis|postman| |
This is some kind of bug in SwiftData since you are not doing anything wrong.
The issue is that your `CarMakeView` has a property `make` of type `CarMake` but you are not updating that property directly but via the relationship and this means that the view doesn't see anything dependent being updated and has no reason to update itself.
This is the bug then because `make` is actually updated when a new car model is added but somehow this change to the relationship property isn't observed properly.
There are some workarounds for this:
The one I use if the relationship properties are optional is to append the new `CarModel` object to the `make` property instead because then we update the `make` property directly
private func addItem(name: String) {
let newItem = CarModel(name: name)
make.models.append(newItem)
}
For your case we need to make the relationship property optional in `CarModel` though for this to work
```
@Model
final class CarModel {
var name: String
var make: CarMake?
init(name: String, make: CarMake? = nil) {
self.name = name
self.make = make
}
}
```
Another solution is make the view update for some other reason, in your example I simply made use of an existing property
@State var count: Int = 1
and added it to the `body` in a `Text` which will cause the view to redraw
var body: some View {
VStack {
Text("\(count)")
List {
ForEach(make.models) { item in
//...
|
I want to be able to generate a (pseudo)random binary sequence (for example, a sequence of Rs and Ls like RLLRRLR) which is counterbalanced such that the same item does not occur more than twice in a row in the sequence and if I, for example, have a sequence of 20, I get 10 of each. Is there a function in R that can do something like this?
I tried to write a function like this myself. Here is the attempt:
```
RL_seq <- function(n_L = 10, n_R = 10, max_consec = 2, initial_seq = NULL) {
while(n_L > 0 | n_R > 0){
side <- sample(c("R", "L"), 1)
if (side == "R" & n_R > 0 & length(grep("R", tail(initial_seq, max_consec))) != max_consec) {
initial_seq <- append(initial_seq, side)
n_R <- n_R - 1
} else if (side == "L" & n_L > 0 & length(grep("L", tail(initial_seq, max_consec))) != max_consec) {
initial_seq <- append(initial_seq, side)
n_L <- n_L - 1
}
}
print(initial_seq)
}
# The function does not stop with the following seed
set.seed(1)
RL_seq()
```
However, it's up to chance whether the code gets stuck or not. I was also hoping that I could change the rules for the sequence (for example, allowing for 3 consecutive Rs), but the code tends to breaks if I touch the arguments. At this point I would be happy if I could run it with the default arguments and not have it get stuck.
I have searched around but I cannot find an answer. |
Generating a pseudorandom binary sequence where the same number does not occur more than twice in a row |
I'm trying to write tests to see if a form is posting data properly. Specifically I'm trying to test that form data (name and phone_number) are being sent to a contact info form for takeout. I keep running into an error that I think is due to the fact I'm using FormField and I'm not sure what the correct data to send is.
I'm using python unittest for a Flask application I'm writing that is supposed to be a mock Order Management System.
Here's the test:
test_routes.py
``` python
import os
import models
from flask import get_flashed_messages, session
from unittest import TestCase
# Before importing app, set environmental variable to use a test db for tests
os.environ['DATABASE_URL'] = 'postgresql:///omakase-test'
# Now import app
from app import app
app.config['WTF_CSRF_ENABLED'] = False
# Make Flask errors be real errors, not HTML pages with error info
app.config['TESTING'] = True
app.config['DEBUG_TB_HOSTS'] = ['dont-show-debug-toolbar']
def test_post_takeout_contact_form(self):
with self.client:
resp = self.client.post('/takeout/contact-form', follow_redirects=True,
data={
'name': 'test customer',
'phone_number': '123-456-7890'
})
html = resp.get_data(as_text=True)
testUser = models.User.query.filter_by(name="test").first()
self.assertEqual(resp.status_code, 200)
self.assertIn("We're pleased to take your order", html)
```
I'm specifically trying to test and see if a flash message pops up, but I keep getting the error message:
```
======================================================================
FAIL: test_post_takeout_contact_form (tests.test_routes.OrderTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/projects/capstone-project-one/tests/test_routes.py", line 272, in test_post_takeout_contact_form
self.assertIn("We're pleased to take your order", html)
AssertionError: "We're pleased to take your order" not found in '<!DOCTYPE html>\n<html
lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-
width, initial-scale=1.0">\n <title></title>\n <link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootswatch@5.3.2/dist/united/bootstrap.min.css">\n <link
rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
integrity="sha512-
DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="
crossorigin="anonymous" referrerpolicy="no-referrer" />\n</head>\n<body class="bg-light">\n\n<nav
class="navbar navbar-expand-lg bg-danger" data-bs-theme="dark">\n <div class="container-fluid">\n
<a class="navbar-brand" href="/">Omakase OMS</a>\n <button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-
expanded="false" aria-label="Toggle navigation">\n <span class="navbar-toggler-icon"></span>\n
</button>\n <div class="collapse navbar-collapse" id="navbarColor01">\n <ul class="navbar-
nav me-auto">\n <li class="nav-item">\n <a class="nav-link" href="/">Home\n
<span class="visually-hidden">(current)</span>\n </a>\n </li>\n <li
class="nav-item">\n <a class="nav-link" href="/dine-in/select-table">Dining In</a>\n
</li>\n <li class="nav-item">\n <a class="nav-link" href="/takeout">Takeout</a>\n
</li>\n <li class="nav-item">\n <a class="nav-link" href="/delivery">Delivery</a>\n
</li>\n <li class="nav-item dropdown">\n <a class="nav-link dropdown-toggle"
href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">\n
Employees\n </a>\n <ul class="dropdown-menu" aria-labelledby="navbarDropdown">\n
<li><a class="dropdown-item" href="/employee-dashboard">Employee Dashboard</a></li>\n
<li><a class="dropdown-item" href="/kitchen-dashboard">Kitchen Dashboard</a></li>\n
<li><a class="dropdown-item" href="/add-menu-item">Add Menu Item</a></li>\n <li><hr
class="dropdown-divider"></li>\n <li><a class="dropdown-item" href="/employees/list">
Employee List</a></li>\n <li><a class="dropdown-item" href="/employees/add-employee">Add
Employee</a></li>\n </ul>\n </li>\n </ul>\n <ul class="navbar-nav me-1"
id="user-profile">\n \n <li class="nav-item float-end me-2">\n <a class="nav-
link" href="/login">Login</a>\n </li>\n \n \n </ul>\n \n </div>\n
</div>\n</nav>\n\n\n \n\n\n<div class="container-fluid g-0 p-0" style="min-height:75vh;">\n\n\n\n
\n <div class="container p-3 bg-secondary mb-5 rounded">\n <h1>Please Fill Out The
Information Below</h1>\n \n \n<div class="container p-3 bg-light">\n<h3
class="display-3">Takeout</h3>\n\n <form id="takeout-form" method="POST">\n <!--add
type=hidden form fields -->\n\n \n\n \n \n\n <label
for="contact_info">Contact Info</label>\n <div class="container bg-white rounded py-2">\n
\n <label for="contact_info-name">Name</label>\n <input class="form-control
my-3" id="contact_info-name" name="contact_info-name" required type="text" value="">\n
\n <label for="contact_info-phone_number">Phone Number</label>\n <input
class="form-control my-3" id="contact_info-phone_number" name="contact_info-phone_number"
type="text" value="">\n \n </div>\n \n \n\n <p>\n \n
<small class="form-text text-danger">\n name\n </small>\n \n
</p>\n\n \n\n <button class="btn btn-success btn-lg" type="submit">Submit</button>\n
</form>\n</div>\n\n </div>\n\n\n</div>\n\n<footer>\n<div class="container-fluid text-center bg-
secondary d-flex justify-content-center" style="height:100px;">\n \n <div class="row">\n\n
<div class="col align-self-center">\n Vegetarian image by <a href="https://www.freepik.com/free-
vector/flat-world-vegetarian-day-labels-
collection_30590488.htm#query=vegetarian&position=13&from_view=search&track=sph&uuid=592ca90d-bf6b-
4116-9533-47be0d368220">Freepik</a>\n </div>\n\n </div>\n\n</div>\n</footer>\n \n<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script> \n\n\n</body>\n</html>'
----------------------------------------------------------------------
Ran 5 tests in 0.227s
FAILED (failures=1)
```
Checking the code in the html page, I noticed that the form is not accepting the data, and so it's just redirecting to the form again.
After examining the form data using flask toolbar, I noticed that the form data being sent is form.contact_info.data, which is an object of name and phone_number. So I thought sending:
``` python
data={
"contact_info": {
"name": "test",
"phone_number": "123-456-7890"
}
}
```
in testing would work, but I keep getting the same error as above. I'm not really sure what else to try.
I'm out of ideas of what to do next because I can't figure out why the form data isn't being sent in the test file. I'd really appreciate some advice or direction to what I could look up to get a better understanding of what I'm doing wrong.
I'll include the relevant code sections from the form.py and routes below.
app.py
``` python
@app.route('/<state>/contact-form', methods=['GET', 'POST'])
def contact_form(state):
if state=='takeout':
form = TakeoutForm()
if form.validate_on_submit():
name = form.contact_info.data['name']
phone_number = form.contact_info.data['phone_number']
customer = User(name=name, phone_number=phone_number, temp=True,
groups=[Group.query.filter_by(name='customer').first()])
new_order = Order(type='Takeout')
db.session.add_all([customer, new_order])
db.session.commit()
session['current_order_id'] = new_order.id
session['temp_customer_id'] = customer.id
flash(f"We're pleased to take your order, {name}!", 'success')
return redirect(url_for('order_page'))
if state=='delivery':
form = DeliveryForm()
if form.validate_on_submit():
name = form.contact_info.data['name']
phone_number = form.contact_info.data['phone_number']
proto_add = [i.strip() for i in form.address.data.values()]
address = ", ".join(proto_add)
customer = User(name=name, phone_number=phone_number, address=address, temp=True,
groups=[Group.query.filter_by(name='customer').first()])
new_order = Order(type='Takeout')
db.session.add_all([customer, new_order])
db.session.commit()
session['current_order_id'] = new_order.id
session['temp_customer_id'] = customer.id
flash(f"We're pleased to take your order, {name}!", 'success')
return redirect(url_for('order_page'))
return render_template('contact-form.html', form=form, state=state)
```
forms.py
``` python
class ContactInfo(Form):
"""Subform for adding customer contact info"""
name = StringField("Name", validators=[DataRequired()])
phone_number = StringField("Phone Number")
class TakeoutForm(FlaskForm):
contact_info = FormField(ContactInfo)
``` |
How can I test a post request to a wtform that uses FormField in flask? |
|unit-testing|flask|wtforms| |
null |
I'm running a set of tests on the database using `.directory(TEST_DIRECTORY)` as instructed [in the docs](https://docs.objectbox.io/android/android-local-unit-tests). There's a `setUp()` and a `tearDown()` for `@Before` and `@After`, respectively.
I test the following cases:
1. queries on the database return empty lists for all three **suspend** functions declared in the interface
1. for each **suspend** function, I test the outcome
What is strange is the following:
1. the empty lists queries succeed
1. out of the three functions that suppose to return an entity populated object, two of them fail and one of them succeeds
This makes me wonder: is there a possibility that the `setUp()` and `tearDown()` don't work as expected?
The error I get is the following:
```
java.lang.IllegalArgumentException: ID is higher or equal to internal ID sequence: 1 (vs. 1). Use ID 0 (zero) to insert new entities.
```
for both of the failing test cases (to reiterate: one of them is succeeding so the population of entities in the database works as expected for this [always] one test case but fails [always] for the other two test cases).
In an **object** I declare a list of Entity instantiations with the id set to `0L` (the default) of the form:
```kotlin
object MyEntitiesMockDataSource {
...
val entityList = listOf(
MyEntity(
parameterOne = "someValueOne",
parameterTwo = someValueOne,
parameterThree = someValueOne
),
MyEntity(
parameterOne = "someValueTwo",
parameterTwo = someValueTwo,
parameterThree = someValueTwo
),
MyEntity(
parameterOne = "someValueThree",
parameterTwo = someValueThree,
parameterThree = someValueThree
),
...
}
```
in total of 10 `MyEntity` objects.
The tests are in the form of:
```kotlin
@Test
fun testGetLatest10EntitiesByOwner_populatedBox_emitsExpectedEntitiesByOwner() = runTest {
val owner = "email@example.com"
val entities = MyEntityMockDataSource.entityList
/** Insert test entities into the database */
boxStore.boxFor<MyEntity>().put(entities)
repository.getLatest10EntitiesByOwner(owner).test {
val emission = awaitItem()
awaitComplete()
/** reversed() because the query does orderDesc() */
assertEquals(entities.reversed(), emission)
}
}
```
Could it be possible that ObjectBox somehow doesn't delete the database and it then fails after first successful execution of the first (non empty) test case and then hits the second and the third but there're already entities instantiated and thus the ID generation now fails?
How could this be even when the id is set to `0L`? Or is it because of the **suspend** functions? Should I just use regular functions? Will ObjectBox run them asynchronously in **Dispatcher.IO** thread?
I **do not** want to set `@Id(assignable = true)` - I'm sure there's a way to make the tests work without setting `assignable` to `true`. |
Coroutine tests break automatically assigned id for ObjectBox Entity in Kotlin Jetpack Compose |
In Rust, I have created a struct Foo. I now want to initialise that from a string using a macro, for example:
```rust
create_struct!("Foo");
```
I am struggling to do this - any help would be hugely appreciated! Thanks.
src/main.rs:
<!-- language: rust -->
pub struct Foo {
}
// Macro to initialize an instance of the struct with the given name
macro_rules! create_struct {($struct_name:literal) => {$struct_name {}}};
fn main() {let my_struct = create_struct!("Foo");}
Output on compilation:
```lang-none
error: macro expansion ignores token `{` and any following
--> src/main.rs:8:26
|
8 | $struct_name {}
| ^
...
14 | let my_struct = create_struct!("Foo");
| --------------------- caused by the macro expansion here
|
= note: the usage of `create_struct!` is likely invalid in expression context
```
|
Now I am writing Fortran on Notepad++, and every time I want to execute my program (namely, test), I would open cmd, change the path to current dictionary, type ``gfortran test.f90 -o test``, finally type ``test.exe`` again. I wonder if there is a simpler way for execution, so that I can run Fortran with the click of a mouse.
I have tried running this line in Notepad++
```
gfortran "$(FULL_CURRENT_PATH)" -o "$(FULL_CURRENT_PATH).exe"
```
It will generate test.f90.exe file and I have to open cmd to execute it every time, which still takes some effort. |
I need to generate a distance matrix with the geographic (Euclidian) distances between 48 points sampled in a regular grid with exactly 120 centimeters between neighbouring points both vertically and horizontally:
[![Sampling matrix][1]][1]
Thus, the distance between sample 1K (cell A1) and both 1NP(cell A2) and 2WN(cell B1) is 120 cm, and 240 cm for 1K-1WNP and 1K-3W, and so on. Diagonally, the distances can be calculated using simple Pythagoras, so that the distance from 1K (A1) to 2WP (B2) is Squareroot(120^2 + 120^2)=169,7, and that from 1K(A1) to 2P(B3) is Squareroot(240^2 + 120^2)= 268,33, and so on.
This will make for a total matrix for distances between all points of 48x48. Here are the first two columns and 16 rows of how the matrix should look:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/BgjNb.png
[2]: https://i.stack.imgur.com/npq98.png
How does one do that in R? I have tried to define a set of data and use the dist() function, but that clearly does not work. |
How to generate a regular matrix of 48 samples with distances between them in Euclidian values in R? |
|r|distance-matrix| |
I updated Flutter to 3.19. Then when I try to run the iphone15 simulator I get the following error. what should I do?
Error: The pod "Firebase/Firestore" required by the plugin "cloud_firestore" requires a higher minimum iOS deployment version than the plugin's reported minimum version.
To build, remove the plugin "cloud_firestore", or contact the plugin's developers for assistance.
Error running pod install
Error launching application on iPhone 15. |
In my Api Platform Symfony Application, I have a class called `Membership`, which represents a many-to-many relationship between Users and Communities. It contains only two routes: DELETE, for user leaving a community, and POST, for joining.
`Membership` entity class:
```php
#[ORM\Entity(repositoryClass: MembershipRepository::class)]
#[ApiResource(
description: "A representation of a single user being a member of a given subreddit.",
operations: [
new Post(
uriTemplate: '/subreddits/{subreddit_id}/join.{_format}',
uriVariables: [
'subreddit_id' => new Link(
fromClass: Community::class,
fromProperty: 'members',
),
],
security: "is_authenticated()",
securityMessage: "Only logged-in users can join a subreddit.",
denormalizationContext: ['groups' => ['membership:create']],
// openapiContext: ['requestBody' => false],
// openapiContext: ['requestBody' => ['content' => ['application/ld+json' => ['schema' => ['type' => 'object']]]]],
input: Community::class,
provider: CommunityStateProvider::class,
processor: MembershipPersistStateProcessor::class,
),
new Delete(
uriTemplate: '/subreddits/{subreddit_id}/leave.{_format}',
uriVariables: [
'subreddit_id' => new Link(
fromClass: Community::class,
fromProperty: 'members'
),
],
security: "is_authenticated()",
securityMessage: "Only logged-in users can leave a subreddit.",
input: Community::class,
provider: CommunityStateProvider::class,
processor: MembershipRemoveStateProcessor::class,
),
],
)]
#[UniqueEntity(fields: ['subreddit', 'member'], message: "You are already a member of this subreddit.")]
class Membership
```
Since user data is extracted from the access token and community data is passed through URI variable, there is no need for a JSON body.
And...
```php
$response = $client->request('POST', 'api/subreddits/'.$community->getId().'/join', [
'headers' => [
'Content-Type' => 'application/ld+json',
'Authorization' => 'Bearer ' . $token,
],
'json' => [],
]);
```
...looks absolutely terrible.
Based on the pull requests I found within the API Platform repository ([pull][1]), allowing empty requests for POST and PUT should be possible by setting the content-type to '', yet all configurations I tried only led to more errors. Is there a way to achieve this?
[1]: https://github.com/api-platform/core/pull/1786 |
How can I connect to a local SSAS (OLAP) server from Python? |
I'm facing intermitents issues like
> This MySqlConnection is already in use.
and
> Connection must be Open; current state is Connecting
They are hard to reproduce but in logs I can see a lot of them.
I'm using the library `Pomelo.EntityFrameworkCore.MySql` and running queries with dapper `QueryAsync`.
connectionstring:
Server=****;DataBase=*****;Uid=***;Pwd=****;default command timeout=0;SslMode=none;max pool size=1000;Connect Timeout=300;convert zero datetime=True;ConnectionIdleTimeout=5;Pooling=true;MinimumPoolSize=25
Code example:
var query = $@"
SELECT
at.*, dpt.*, c.*, cnt.*, mEnc.*, atUsr.*, usr.*
FROM Atendimento AS at
INNER JOIN Departamento AS dpt ON at.DepartamentoId = dpt.Id
INNER JOIN Canal AS c ON at.CanalId = c.Id
LEFT JOIN Contato AS cnt ON at.ContatoId = cnt.Id
LEFT JOIN MotivoEncerramento as mEnc ON at.MotivoEncerramentoId = mEnc.id
LEFT JOIN (
AtendimentoUsuario AS atUsr
INNER JOIN Users AS usr ON atUsr.UserId = usr.Id
) ON at.Id = atUsr.AtendimentoId
WHERE at.IdRef = '{idRef}'
ORDER BY dpt.Id, c.Id, atUsr.Id, usr.Id;";
var atendimentos = await Dapper.SqlMapper.QueryAsync<Atendimento, Departamento, Canal, Contato, MotivoEncerramento, AtendimentoUsuario, Usuario, Atendimento>(
_dbContext.Database.GetDbConnection(),
query,
(atendimento, departamento, canal, contato, motivoEncerramento, atUsuario, usuario) =>
{
atendimento.Departamento = departamento;
atendimento.Contato = contato;
atendimento.MotivoEncerramento = motivoEncerramento;
atendimento.Canal = canal;
atendimento.AtendimentoUsuarios = new List<AtendimentoUsuario>();
if (atUsuario is not null)
{
atUsuario.Usuario = usuario;
atendimento.AtendimentoUsuarios.Add(atUsuario);
}
return atendimento;
});
var result = atendimentos.GroupBy(a => a.Id).Select(g =>
{
var groupedAtendimento = g.First();
if (g.Any(c => c.AtendimentoUsuarios.Count > 0))
{
groupedAtendimento.AtendimentoUsuarios = g.Select(a => a.AtendimentoUsuarios.SingleOrDefault()).ToList();
}
return groupedAtendimento;
});
atendimento = result.First();
This `_dbContext.Database.GetDbConnection()` method:
//
// Summary:
// Gets the underlying ADO.NET System.Data.Common.DbConnection for this Microsoft.EntityFrameworkCore.DbContext.
// This connection should not be disposed if it was created by Entity Framework.
// Connections are created by Entity Framework when a connection string rather than
// a DbConnection object is passed to the 'UseMyProvider' method for the database
// provider in use. Conversely, the application is responsible for disposing a DbConnection
// passed to Entity Framework in 'UseMyProvider'.
//
// Parameters:
// databaseFacade:
// The Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade for the context.
//
// Returns:
// The System.Data.Common.DbConnection
//
// Remarks:
// See Connections and connection strings for more information.
public static DbConnection GetDbConnection(this DatabaseFacade databaseFacade)
{
return GetFacadeDependencies(databaseFacade).RelationalConnection.DbConnection;
}
I see some people saying to use `ToList()` after the `Select` method but they weren't using dapper. |
I have a group of items that I'm running an animation on. After clicking on a button, more items are added with the same class. These items are being added in groups of 4.
At first intersection observer ignores the new items, but if I click the button again, they work.
The funny thing is, my code works as intended in my example here, BUT not on the page I'm working on which uses the same basic structure, and that exact JS for that part (link removed).
Any ideas on what the issue on that page could be?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const options = {
threshold: 0.6
};
const sectionObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('enter');
observer.unobserve(entry.target);
}
});
}, options);
// Convert NodeList to an array
let reveal = Array.from(document.querySelectorAll('.post-list-card'));
// Initial observation for existing items
reveal.forEach(section => {
sectionObserver.observe(section);
});
// Update reveal with all .post-list-card items
function updateReveal() {
const updatedSections = document.querySelectorAll('.post-list-card');
reveal = Array.from(updatedSections); // Update the reveal array
reveal.forEach(newSection => {
sectionObserver.observe(newSection); // Observe new items
});
}
const loadMore = document.querySelector('.post-list .fusion-load-more-button');
loadMore.addEventListener('click', updateReveal);
/* this is not part of the code. added just for demonstration purposes */
function addNewCards() {
const contentDiv = document.querySelector('.content');
for (let i = 0; i < 4; i++) {
const newCard = document.createElement('div');
newCard.classList.add('post-list-card');
newCard.textContent = 'New Card'; // You can customize the content here
contentDiv.appendChild(newCard);
}
}
<!-- language: lang-css -->
.post-list-card{
width: 100%;
height: 50px;
margin: 50px 0;
padding: 50px;
background: blue;
color: yellow;
}
.post-list-card.enter{
background: red;
color: #fff;
}
<!-- language: lang-html -->
<div class="post-list">
<div class="content">
<div class="post-list-card">Card</div>
<div class="post-list-card">Card</div>
<div class="post-list-card">Card</div>
<div class="post-list-card">Card</div>
</div>
<button class="fusion-load-more-button" onclick="addNewCards()">Load More</button>
</div>
<!-- end snippet -->
EDIT: Found a solution. Added it as an answer.
|
Fluent bit v3.0.0 is configured on Ubuntu 22.04.3 LTS and on Windows server 2016 standart. The configs (fluent-bit.conf, parser.conf) on these linux and windows machines are absolutely the same. however I ran into a problem. The modify filter works correctly only on a Windows machine and does not work on Linux.
Fluent bit has been configured, which parses into two tables in clickhouse. The first table name is 'access', the second table name is 'flussonic'. The name of the column is 'server_ip' in the tables is the same.
Configured a modify filter that should add a constant value to the 'server_ip' columns in each of the two clickhouse tables.
fluent-bit.conf:
```
[FILTER]
name modify
match access
add server_ip 192.168.1.2
[FILTER]
name modify
match flussonic
add server_ip 192.168.1.2
```
In this case, the addition occurs only in 'flussonic', and a constant value is not written to 'access'.
I tried this setting:
```
[FILTER]
name modify
match *
add server_ip 192.168.1.2
```
In this case, the addition also occurs only in 'flussonic'.
I tried changing the name of the 'server_ip' column to 'ip_server'. No result.
There are no errors in the fluent bit logs that could help us understand the problem. I would be grateful if you tell me what to do and where I am wrong. Because setting it up for the first time. Any ideas? |
|kotlin|objectbox| |
I have a large CSV file without a header row, and the header is available to me as a vector. I want to use a subset of the columns of the file without loading the entire file. The subset of columns required are provided as a separate list.
*Edit: in this case, the column names provided in the header list are important. This MRE only has 4 column names, but the solution should work for a large dataset with pre-specified column names. The catch is that the column names are only provided externally, not as a header in the CSV file.*
```
1,2,3,4
5,6,7,8
9,10,11,12
```
```R
header <- c("A", "B", "C", "D")
subset <- c("D", "B")
```
So far I have been reading the data in the following manner, which gets me the result I want, but loads the entire file first.
```R
# Setup
library(readr)
write.table(
structure(list(V1 = c(1L, 5L, 9L), V2 = c(2L, 6L, 10L), V3 = c(3L, 7L, 11L), V4 = c(4L, 8L, 12L)), class = "data.frame", row.names = c(NA, -3L)),
file="sample-data.csv",
row.names=FALSE,
col.names=FALSE,
sep=","
)
header <- c("A", "B", "C", "D")
subset <- c("D", "B")
# Current approach
df1 <- read_csv(
"sample-data.csv",
col_names = header
)[subset]
df1
```
```
# A tibble: 3 × 2
D B
<dbl> <dbl>
1 4 2
2 8 6
3 12 10
```
How can I get the same result without loading the entire file first?
Related questions
- [Only read selected columns](https://stackoverflow.com/q/5788117/21891079) includes the header in the first row.
- [Ways to read only select columns from a file into R? (A happy medium between `read.table` and `scan`?) [duplicate]](https://stackoverflow.com/q/2193742/21891079) does not specify column names outside the file and the answers do not apply to this situation.
- [how to skip reading certain columns in readr [duplicate]](https://stackoverflow.com/q/31150351/21891079) is different because it seems to be about skipping an unknown first column and reading a known second and third column across multiple files. Data types are not necessarily known in advance in this question.
- [Is there a way to omit the first column when reading a csv [duplicate]](https://stackoverflow.com/q/14527466/21891079): column is skipped based on position, not position in an externally provided list of column names. |
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/3uUjE.png
In this image, which is from figma. There is keypad on screen, which, when entered shows up in that square box. How do I make it? |
How to make such functioning screen like this in flutter? |
|flutter| |
I have Magento CE 2.4.6 running on a ubuntu server with Elasticsearch 8.11.4.
For a mandatory module I absolutely need, I need to downgrade to ES 7.9.3
I read everywhere it was not possible to downgrade ES.
Is there a way to uninstall ES 8.4.11 and install ES 7.9.3 wihtout damaging the system?
If yes, how?
(I don't want to make any mistakes)
Thank you for your help! |
Magento 2.4 : how to change server Elasticsearch version? |
|elasticsearch|magento2| |
Getting RedisConnectionFailureException intermittently |
I have an esp32 and i wish to use it to drive a HC-SR04 sonar module. I use interrupts to get information from sensors,then I use a queue to pass the data to a freertos task to output it. At first, it work and output the correct data, but after few second, it report an error and reboot.
Here is the error:
Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC : 0x40084c90 PS : 0x00050631 A0 : 0x800d31c4 A1 : 0x3ffbf53c
A2 : 0x00000040 A3 : 0x00018040 A4 : 0x000637ff A5 : 0x3ffbf50c
A6 : 0x00000008 A7 : 0x00000000 A8 : 0x00000001 A9 : 0x4008bf6e
A10 : 0x00060b23 A11 : 0x3ffc4a14 A12 : 0x3ff44000 A13 : 0xffffff00
A14 : 0x00000000 A15 : 0x00000020 SAR : 0x0000001d EXCCAUSE: 0x0000001c
EXCVADDR: 0x800d31d0 LBEG : 0x400899a4 LEND : 0x400899ba LCOUNT : 0xffffffff
Backtrace: 0x40084c8d:0x3ffbf53c |<-CORRUPTED
Then I found that if I delete the code that were used to push the data to the queue, it will work normally. So I guass that is the problem,but I don't Know how to fix it.
Here is main:
```
radar radar0(25,35);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.setDebugOutput(true);
radar0.start();
}
```
Here is how radar class define:
```
class radar
{
private:
uint8_t txPin,rxPin;
Ticker loopTrigger; //ticker that use to trigger loop
Ticker singalEnder; //ticker that use to generate a 1ms pulse
QueueHandle_t dstQueue; //queue that use to pass dst to coroutine
float previousDst;
bool enable;
unsigned long echoStartTime; //The time the echo start received
void loop();
void echoStartHandler(); //callback when the echo start
void echoEndHandler(); //callback when the echo end
void queueListener();
public:
radar(uint8_t txPin,uint8_t rxPin);
void start();
};
radar::radar(uint8_t txPin,uint8_t rxPin){
this->txPin=txPin;
this->rxPin=rxPin;
this->enable=true;
this->dstQueue = xQueueCreate(4,sizeof(float));
}
void radar::start(){
//set pin mode
pinMode(this->txPin,OUTPUT);
pinMode(this->rxPin,INPUT);
//low down the txPin
digitalWrite(this->txPin,LOW);
//Create a coroutine for listening to the dstQueue
auto fn = [](void *arg){static_cast<radar*>(arg)->queueListener();};
xTaskCreate(fn,"dstListener",1024,this,0,NULL);
//enable the radar
this->enable=true;
this->loop();
}
void radar::queueListener(){
float dst;
while (this->enable)
{
if (xQueueReceive(this->dstQueue,&dst,0)==pdFALSE){
//sleep 10ms if the queue is empty
vTaskDelay(10/portTICK_PERIOD_MS);
continue;
}
if (abs(dst-this->previousDst)>5){
Serial.println(dst);
this->previousDst=dst;
}
}
vTaskDelete(NULL);
}
void radar::echoStartHandler(){
this->echoStartTime = micros();
//Set rxPin pull-down interrupt
attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoEndHandler();},this,FALLING);
}
void radar::echoEndHandler(){
detachInterrupt(this->rxPin);
unsigned long echoEndTime = micros();
float pluseTime;
if (echoEndTime > this->echoStartTime){ //If the variable does not overflow
pluseTime = echoEndTime - this->echoStartTime;
}else{
pluseTime = echoEndTime + (LONG_MAX - this->echoStartTime);
}
float dst = pluseTime * 0.0173;
//push the dst to queue
BaseType_t xHigherPriorityTaskWoken;
xQueueSendFromISR(this->dstQueue,&dst,&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken==pdTRUE){
portYIELD_FROM_ISR();
}
}
void radar::loop(){
if (!this->enable){
return;
}
//Set loop() to be triggered after 100ms
this->loopTrigger.once_ms<radar*>(100,[](radar* r){r->loop();},this);
//Generate a 1ms pulse at txPin
digitalWrite(this->txPin,HIGH);
this->singalEnder.once_ms<uint8_t>(1,[](uint8_t pin){digitalWrite(pin,LOW);},this->txPin);
//Set rxPin pull-up callback
attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoStartHandler();},this,RISING);
}
```
Thank for your help!
ps: Please forgive my poor English.I'm not a native speaker. |
it's my test code
```
public class Test {
public static SoftReference<byte[]> cache = new SoftReference<>(new byte[0]);
public static List<byte[]> list = new ArrayList<>();
public static void main(String[] args) {
try {
func();
} catch (OutOfMemoryError e) {
sniff();
e.printStackTrace();
}
}
public static void func() {
byte[] bytes = new byte[1024 * 1024];
cache = new SoftReference<>(bytes);
for(;;) {
byte[] tmp = new byte[1024 * 1024];
list.add(tmp);
}
}
public static void sniff() {
byte[] bytes = cache.get();
if (bytes == null) {
System.out.println("recycling data.");
} else {
System.out.println("object still live");
}
}
}
```
The program output is as follows
> object still live
java.lang.OutOfMemoryError: Java heap space
I don't understand? why?
This is a sentence I found in the official documentation of Oracle:
> All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.
Even more strangely, if I put `byte[] bytes = new byte[1024 * 1024]; cache = new SoftReference<>(bytes);` into the for loop; like this
```
public class Test {
public static SoftReference<byte[]> cache = new SoftReference<>(new byte[0]);
public static List<byte[]> list = new ArrayList<>();
public static void main(String[] args) {
try {
func();
} catch (OutOfMemoryError e) {
sniff();
e.printStackTrace();
}
}
public static void func() {
for(;;) {
byte[] tmp = new byte[1024 * 1024];
list.add(tmp);
byte[] bytes = new byte[1024 * 1024];
cache = new SoftReference<>(bytes);
}
}
public static void sniff() {
byte[] bytes = cache.get();
if (bytes == null) {
System.out.println("recycling data.");
} else {
System.out.println("object still live");
}
}
}
```
the program output is as follows:
> recycling data.
java.lang.OutOfMemoryError: Java heap space
I have two question:
1. The first writing method,Why did the garbage collector not collect SoftReferences
2. Why do these two writing methods produce such a difference
I analyzed the dump file and the first way of writing really doesn't collect it |
Java SoftReference: Soft references were not collected before the occurrence of OOM |
|java|garbage-collection|soft-references| |
null |
I have recently started working on a Spring Boot project and chose MongoDB as my database. I have the following Document structure.
Following is the User document structure.
```
@Data
@Builder(setterPrefix = "with")
@Document(collection = "users")
@JsonIgnoreProperties(value = {"password", "createdAt", "updatedAt"}, allowSetters = true)
public class User {
@Id
@Indexed
private String id;
@Indexed(unique = true, direction = IndexDirection.DESCENDING)
private String username;
private String name;
private String password;
@CreatedDate
private Date createdAt;
@LastModifiedDate
private Date updatedAt;
}
```
I have the following structure for Borrow document.
```
@Document(collection = "borrows")
@Data
@SuperBuilder(setterPrefix = "with")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@AllArgsConstructor
@NoArgsConstructor
public abstract class Borrow {
@Id
@EqualsAndHashCode.Include
private String id;
@DocumentReference
private User borrower;
@DocumentReference
private User borowee;
private Date expectedReturnDate;
private Date actualReturnDate;
private String place;
private String occasion;
private BorrowStatus status;
public abstract String getType();
}
```
and two sub classes for Borrow as follows.
BorrowMoney
```
@Document(collection = "borrows")
@Data
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@SuperBuilder(setterPrefix = "with")
@BsonDiscriminator(key = "type", value = "Money")
public class BorrowMoney extends Borrow{
private Double amount;
@Override
public String getType() {
return "Money";
}
}
```
```
@Document(collection = "borrows")
@Data
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@SuperBuilder(setterPrefix = "with")
@BsonDiscriminator(key = "type", value = "Money")
public class BorrowMoney extends Borrow{
private Double amount;
@Override
public String getType() {
return "Money";
}
}
```
Reminder Document Structure
```
@Data
@Builder
@Document(collection = "reminders")
public class Reminder {
@Id
private String id;
@DocumentReference
private Borrow borrow;
private String message;
private String header;
@Indexed
private String borrower;
@Indexed
private String borowee;
private boolean read;
@CreatedDate
private Date createdAt;
@LastModifiedDate
private Date updatedAt;
}
```
I am trying to fetch all the reminders of the currently logged in user by using the id of the user.
I followed the official `spring-data-mongo` [documentation](https://docs.spring.io/spring-data/mongodb/reference/repositories/query-methods-details.html#repositories.query-methods.query-property-expressions) for understanding the property expression query.
I wrote the following method in the ReminderRepository.
```
@Repository
public interface ReminderRepository extends MongoRepository<Reminder, String> {
List<Reminder> findByBorrowBorrowerId(String id);
}
```
However, executing this always returns 0 results although the records are already present.
`2024-03-30 17:05:26.998 DEBUG 27280 [nio-3080-exec-4,6607f8fe755cc27c4afe5cfe81fb8f8b,75158ed32fd3ebcc] o.s.d.m.c.MongoTemplate : find using query: { "borrow" : { "$oid" : "6605a6ea9796e7405763c9ac"}} fields: Document{{}} for class: class com.kitaab.hisaab.ledger.entity.Reminder in collection: reminders`
I am seeing that the above query is getting generated by `spring-data-mongo` and the id `6605a6ea9796e7405763c9ac` here is actually of the user not of the borrow.
As per the [documentation](https://docs.spring.io/spring-data/mongodb/reference/repositories/query-methods-details.html#repositories.query-methods.query-property-expressions) it should have taken the property path borrow.borrower.id.
Also tried with `@Query("{ 'borrow.borrower.id' : ?0 }}")` annotation. However, no breakthrough.
Help me resolve this issue.
Repository [link](https://github.com/nvseshaiah2013/hisaab_kitaab_api_spring).
|
Spring Data Mongo Property Expression Query not returning any results |
|mongodb|spring-boot|spring-data-jpa|mongodb-query|spring-data-mongodb| |
null |