instruction stringlengths 0 30k β |
|---|
null |
null |
null |
Making rendering placeholder on Laravel / Livewire site as written here: https://livewire.laravel.com/docs/lazy#rendering-placeholder-html
I try to use my library method :
public function placeholder()
{
return <<<'HTML'
<div>
' . LibraryFacade::getProcessingCode() . '
</div>
HTML;
}
But that does not not and I see my php code on the text.
Which way is correct?
"livewire/livewire": "^3.4.6",,
"laravel/framework": "^10.45.1",
"tailwindcss": "^3.4.1",
|
I think you want to initialize your Class_A instance on the heap with new. Then call the non-static member class a instance of Class_B instance:
#include <iostream>
class Class_A
{
public:
int number_;
// Here we define the constructor for "Class_A".
Class_A(int a)
{
number_ = a;
}
void printNumber()
{
std::cout << "The value in Class_A is " << number_ << std::endl;
}
};
class Class_B
{
public:
Class_A* class_A_instance;
// Here we define the constructor for "Class_B".
Class_B(int b)
{
class_A_instance = new Class_A(b);
}
};
int main()
{
Class_B class_B_instance(3);
class_B_instance.class_A_instance->printNumber();
return 0;
} |
Mutable borrow problem with inserting Vacant entry into HashMap |
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
```javascript
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));
``` |
null |
class ShutdownOnFirstTrue extends StructuredTaskScope<Optional<Boolean>> {
private volatile boolean succeeded;
@Override
protected void handleComplete(Subtask<? extends Optional<Boolean>> subtask) {
if (subtask.state() == State.SUCCESS) {
subtask.get().filter((b) -> b.booleanValue()).ifPresent( (b) -> {
succeeded = true;
shutdown();
});
}
}
public boolean isSucceeded() {
return succeeded;
}
}
and `isSucceeded` should be accessed after `join` completes
try (var scope = new ShutdownOnFirstTrue()) {
scope.fork...
scope.fork...
scope.fork...
scope.join();
boolean succeeded = scope.isSucceeded();
}
but instead of relying on the haphazard solution to equally haphazard (for example, you didn't specify a behavior on exceptions, thrown by subtasks) requirements, expressed in the question, I'd suggest to learn `handleComplete` overriding technique, it is recommended for definition of custom behavior, was introduced right in `StructuredTaskScope.ShutdownOnFailure` and `StructuredTaskScope.ShutdownOnSuccess` and @Holger gave another excellent example [in his answer](https://stackoverflow.com/a/78080818/2366397).
Some technical details:
- The class is not reentrant with next round of `fork`s after `join`. To achieve it, either have a (re)setter for `succeeded` field or override both `join`s like @Holger did, the second way is more elegant, but it is a bit more prone to errors as it might silently fail if next version will add third `join`; (but would like to have `joinImpl` protected in next version or have some kind of `joinCompleted` placeholder in the base class).
- `shutdown` is not guarded against concurrent invocations, as I believe that `implShutdown` already does this, so I found a guarding in `ShutdownOnSuccess.handleComplete` excessive.
- there is no any special action provisioned on an exception, thrown by a subtask. It will be just silently consumed. To handle an exception if it is expected please see if the result of `StructuredTaskScope.Subtask` in overridden `handleComplete` method is `Subtask.State.FAILED` and act accordingly. The good example of such handling is stock `ShutdownOnFailure.handleComplete`, `ShutdownOnFailure` is a final class, though, and cannot be reused for your purpose. Once again, due to the lack of clearly pronounced system requirements the `ShutdownOnFirstTrue` above is only a hint, not a fully working tool.
|
Spring's XML based bean configuration for Object Mapper's Case Insensitive property |
|spring|jboss|case-sensitive|objectmapper|spring-bean| |
null |
After I've tried to install shopify-cli using homebrew without success, my dev environment on macOS big sur seems to not work. I've tried in terminal to run the command `php -v` or `php localhost:8000 -t /my-site/` but I will see this error message
```
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicuio.70.dylib
Referenced from: /usr/local/opt/php@7.4/bin/php
Reason: image not found
```
I've tried to install php 8 using the command `brew install php` but this will produce this error
```
==> Fetching freetds
==> Downloading https://raw.githubusercontent.com/Homebrew/homebrew-core/cdae05f
Already downloaded: /Users/ziobru/Library/Caches/Homebrew/downloads/7b632fa6ee4cf65d34c6d977f0d52b2f41647860d8d12f976e61c1ac7a8e92c2--freetds.rb
==> Downloading https://www.freetds.org/files/stable/freetds-1.4.11.tar.bz2
dyld: Library not loaded: /usr/local/opt/openssl@3/lib/libssl.3.dylib
Referenced from: /usr/local/opt/libssh2/lib/libssh2.1.dylib
Reason: image not found
Error: php@8.2: Failed to download resource "freetds"
Download failed: https://www.freetds.org/files/stable/freetds-1.4.11.tar.bz2
```
Using the `which php` command will give me this result `/usr/local/opt/php@7.4/bin/php`, I'm a bit confused about this because it seems my php installation is gone.
How I can reinstall php on my macOS bigSur to be able to develop in php using the one installed on my machine? |
macOS BigSur - Unable to run bundled php version or brew php 8 |
|php|macos|homebrew|homebrew-cask| |
I'm attempting to hide the iOS app home indicator in React Native with no success. Research eventually led me to the react-native-home-indicator package.
[Step 3][1] of the ReadMe instructs one to configure changes in the **Appdelegate.m**. No such file appears to exist in my project. I cannot confirm, but such a file seems to be a vestige of programming in Xcode? Meanwhile, I created the project in React Native to avoid working in an iOS specific platform. Everything I've developed has been in VSCode up to this point.
Any insight would be appreciated. Avoiding step 3 of the configuration leads to errors in my application once I reference `<PrefersHomeIndicatorAutoHidden />` or `<HomeIndicator autoHidden />`.
(My project uses Expo, if that further muddies the water.)
[1]: https://www.npmjs.com/package/react-native-home-indicator?activeTab=readme |
Anyone have success configuring react-native-home-indicator? |
|react-native|expo|appdelegate| |
I'm using [Multipass][1] on an Ubuntu host to launch multiple local VMs, with the goal to create a docker swarm over multiple VMs. Everything with `multipass` itself and the installation of Docker (I've used the scripts at https://get.docker.com/) has gone well.
I've also been able to initialize the swarm by setting up `node1` as the manager through `docker swarm init --advertise-addr <VARIOUS_IPs>`, where `VARIOUS_IPs` has been any one of various I.Ps:
1. `127.0.0.1` (as per [this][2] SO post)
2. `172.17.0.1`, as per the output that I get when logging into `node1` through `multipass shell node` for the `docker0` interface:
```bash
jason@jason-ubuntu-desktop:~$ multipass shell node1
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.15.0-101-generic x86_64)
.
.
.
System load: 0.0 Processes: 97
Usage of /: 45.4% of 4.67GB Users logged in: 0
Memory usage: 31% IPv4 address for docker0: 172.17.0.1
Swap usage: 0% IPv4 address for ens3: 10.126.204.207
Expanded Security Maintenance for Applications is not enabled.
.
.
.
```
3. `10.126.204.207`, which is the I.P assigned to the interface `ens3` as you can see in the command above.
4. `192.168.2.6`, which is what `ifconfig -a` gives the interface `enp5s0` on the **HOST** machine:
```bash
jason@jason-ubuntu-desktop:~$ ifconfig -a
enp5s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.2.6 netmask 255.255.255.0 broadcast 192.168.2.255
inet6 2a02:85f:e0c9:8900:3523:25bb:2763:1923 prefixlen 64 scopeid 0x0<global>
inet6 2a02:85f:e0c9:8900:b0e8:1b53:b5c4:eddc prefixlen 64 scopeid 0x0<global>
inet6 fe80::4277:203e:fe56:63a8 prefixlen 64 scopeid 0x20<link>
ether 08:bf:b8:75:50:9b txqueuelen 1000 (Ethernet)
RX packets 3135402 bytes 4280258798 (4.2 GB)
RX errors 0 dropped 19 overruns 0 frame 0
TX packets 2289436 bytes 233651001 (233.6 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 10189 bytes 1551793 (1.5 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 10189 bytes 1551793 (1.5 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
mpqemubr0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.126.204.1 netmask 255.255.255.0 broadcast 10.126.204.255
inet6 fe80::5054:ff:fe50:214b prefixlen 64 scopeid 0x20<link>
ether 52:54:00:50:21:4b txqueuelen 1000 (Ethernet)
RX packets 616652 bytes 38339106 (38.3 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 815903 bytes 1211324469 (1.2 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
tap-7d21c24c2a2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::3cd8:e7ff:fe95:b7b7 prefixlen 64 scopeid 0x20<link>
ether 3e:d8:e7:95:b7:b7 txqueuelen 1000 (Ethernet)
RX packets 78108 bytes 5871486 (5.8 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 106416 bytes 158301533 (158.3 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
tap-9f0a4d14af6: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::6073:fcff:fe8d:fe22 prefixlen 64 scopeid 0x20<link>
ether 62:73:fc:8d:fe:22 txqueuelen 1000 (Ethernet)
RX packets 80889 bytes 6172614 (6.1 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 106378 bytes 158520504 (158.5 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
tap-f33ea83d210: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::f433:24ff:feb1:3f5f prefixlen 64 scopeid 0x20<link>
ether f6:33:24:b1:3f:5f txqueuelen 1000 (Ethernet)
RX packets 79189 bytes 5937738 (5.9 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 106441 bytes 158499276 (158.4 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
```
5. `192.168.2.255`, which is what `ifconfig -a` returns as `broadcast` for the `enp5s0` interface, as you can see above.
6. `10.126.204.1`, which is what `ifconfig -a` returns for the `mpqemubr0` interface, as you can see above.
7. The public I.P associated with my router (not pasting that one for security reasons).
No matter which I.P I use, I successfully start up a swarm, e.g, for `172.17.0.1`:
```
ubuntu@node1:~$ docker swarm init --advertise-addr 172.17.0.1
Swarm initialized: current node (1uih27t5jrmoe56hg6ko6zc7u) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --token <TOKEN>172.17.0.1:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
```
However, when I paste the generated `swarm join` command in either one of the other two nodes, after a wait of about 5 seconds, I get:
```
Error response from daemon: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing: dial tcp 172.17.0.1:2377: connect: connection refused"
```
I'm wondering what I.P I should be advertising in order to make the worker nodes join the swarm started from the manager node.
[1]: https://multipass.run/
[2]: https://stackoverflow.com/questions/69573675/getting-error-when-try-to-add-docker-swarm-manager-into-multipass-vm |
Docker on Multipass VMs: Connecting worker nodes to swarm results in rcp error |
|docker|docker-swarm|ifconfig|multipass| |
I am trying a render the App component in Jest for unit testing. I have installed the required libraries for the job but I keep getting an error message when I try to import the App.js file.
[Error message](https://i.stack.imgur.com/dDBhN.png)
The component I want to render is below along with the rest of the code.
# App.js
```javascript
import { useEffect,useState } from 'react';
import logo from './logo.svg';
import './App.css';
// import UserLogin from './components/login';
import ConnectedUsersData from './components/login';
import * as API from './data/_DATA';
import { handleGetUser } from './actions/login';
import {getUser} from './actions/login';
import {receiveQuestions} from './actions/questions';
import {handleInitialData} from './actions/shared';
import {connect} from'react-redux';
import { Route, Router,Routes } from "react-router-dom";
import ConnectedDashBoard from "./components/dashboard";
import ConnectedCreatePolls from "./components/createPolls";
import ConnectedLeaderBoard from "./components/leaderboard";
import ConnectedPolls from "./components/polls";
function App(props) {
// const [value, setNewValue] = useState(0);
useEffect(() => {
props.dispatch(handleInitialData(props.store))
}, []);
if(props.loading == true) {
return <div><h3>Loading.....</h3></div>
}
return (
// <div className="App">
// <ConnectedUsersData store={props.store}/>
// </div>
<Routes>
<Route path="/" element={<ConnectedUsersData/>}/>
<Route path="/dashboard" element={<ConnectedDashBoard/>}/>
<Route path="/add" element={<ConnectedCreatePolls/>}/>
<Route path="/leaderboard" element={<ConnectedLeaderBoard/>}/>
<Route path="/polls/:id" element={<ConnectedPolls/>}/>
</Routes>
);
}
// const ConnectedApp = connect((state)=> ({
// loading: state.loading
// }))(App);
const ConnectedApp = connect((state)=> ({
loading: state.loading
}))(App);
export default ConnectedApp;
```
# When I try to import ConnectApp, I get an error message.
# AppUI.test.js
```javascript
import '@testing-library/jest-dom';
import * as React from "react";
import '@testing-library/jest-dom/extend-expect';
import { render,screen } from "@testing-library/react";
import store from "../data/store";
// import ConnectedApp from '../App';
import ConnectedApp from '../App';
describe("Display UI", () => {
it("matches snapshot when we pass the store", async () => {
var component = render(
<Provider store={store}>
<BrowserRouter>
<ConnectedDashBoard/>
</BrowserRouter>
</Provider>
);
expect(component).toBeInTheDocument();
})
it("matches snapshot when we did not pass the store", async () => {
var component = render(
// <ConnectedApp/>
<Provider>
<BrowserRouter>
<ConnectedApp/>
</BrowserRouter>
</Provider>
);
expect(component).toBeInTheDocument();
});
})
```
# Package.json
```json
{
"name": "employeepoll",
"version": "0.1.0",
"private": true,
"dependencies": {
"@coreui/coreui": "^4.3.0",
"@coreui/react": "^4.11.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/user-event": "^13.5.0",
"babel-core": "^6.26.3",
"form-serialize": "^0.7.2",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^5.0.1",
"react-redux": "^9.1.0",
"react-redux-loading-bar": "^5.0.8",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"regenerator-runtime": "^0.14.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --no-cache",
"eject": "react-scripts eject"
},
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
},"plugins": ["@babel/plugin-transform-modules-commonjs"],
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/plugin-transform-modules-commonjs": "^7.24.1",
"@babel/preset-env": "^7.24.3",
"@babel/preset-react": "^7.24.1",
"@testing-library/react": "^14.2.2",
"babel-jest": "^29.7.0",
"jest": "^27.5.1",
"react-test-renderer": "^18.2.0"
}
}
```
# .babelrc
```json
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
```
`Is there anybody who knows how to properly configure jest so it can render a component? Can you help me please?`
|
null |
I am trying to get information of stock code from below website using excel vba
https://www.screener.in/company/KRISHANA/
I went through network tab and found out the code was in under peers node
https://www.screener.in/api/company/13611040/peers/
below is the code which I've written in excel vba, the html page has no information on the code
Note: I dont want to duplicate this thread, I tried searching everywhere, if its not possible in vba,
can we achieve this in python.
```
URLS = "https://www.screener.in/company/KRISHANA/"
Set xhr = New MSXML2.ServerXMLHTTP60
With xhr
.Open "GET", URLS, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
.send
If .readyState = 4 And .Status = 200 Then
Set Doc = New MSHTML.HTMLDocument
Doc.body.innerHTML = .responseText
End If
End With
DoEvents
``` |
Getting website metadata (Excel VBA/Python) |
|python|python-3.x|excel|vba| |
null |
I have a google sheet with values on it. Think it like this:
| header1 | col1 | header 3 | col2 |
| -------- | -------------- | --------- | --------
| First | | row | |
| Second | | row | |
I will have another data that will come and fill the 2nd and 4th column by respectively.
So what I want to use append_row with specific column name because after each process (my code) I want to immediately add it to my google sheet.
--------
WHAT I DO FOR NOW (I want to change this logic):
I have 2 columns like this. So what I have done before after my code completes (all data is ready now) I was adding those data with worksheet update like this (I am using gspread):
```python
headers = worksheet.row_values(1)
col1_index = headers.index('col1') + 1
col2_index = headers.index('col2') + 1
for item in result:
col1_list.append(item['col1'])
col2_list.append(item['col2'])
col1_transposed = [[item] for item in col1_list]
col2_transposed = [[item] for item in col2_list]
col1_range = '{}2:{}{}'.format(chr(65 + col1_index - 1), chr(65 + col1_index - 1),
len(col1_list) + 1)
col2_range = '{}2:{}{}'.format(chr(65 + col2_index - 1), chr(65 + col2_index - 1),
len(col2_list) + 1)
worksheet.update(col1_range, col1_transposed)
worksheet.update(col2_range, col2_transposed)
```
But now I want to say like I want to append my data row by row to specific columns. After each process I will have a data like this
{'col1': 'value1', 'col2': 'value2'}
and value1 will be on the col1 column and value2 will be on the col2 column in the first row.
|
I haven't actually implemented this yet. But moving my if elif statements outside of the function process_data should allow me to split it into a list of lists with the sub-lists being chunks and change the for loop in the multiprocessing pool definition to for chunk in chunks. Then all I should need to do is pass in the index of each chunk and rebuild them after.
I'll come back and update this thread with the code if it works ina bit. |
null |
The top rated answer does not work with the new Reflection implementation of [JEP416](https://openjdk.org/jeps/416) in e.g. Java 21 that uses MethodHandles and ignores the flags value on the Field abstraction object.
One solution is to use Unsafe, however with [this JEP](https://openjdk.org/jeps/8323072) Unsafe and the important `long objectFieldOffset(Field f)` and
`long staticFieldOffset(Field f)` methods are getting deprecated for removal so for example this will not work in the future:
```java
final Unsafe unsafe = //..get Unsafe (...and add subsequent --add-opens statements for this to work)
final Field ourField = Example.class.getDeclaredField("changeThis");
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");
```
I do not recommend this but it is possible in Java 21 with the new reflection implementation when making heavy use of the internal API if really needed.
# Java 21+ solution without `Unsafe`
See my answer [here](https://stackoverflow.com/a/77705202/23144795) on how to leverage the internal API to set a final field in Java 21 without Unsafe.
|
On Laravel 10 site using spatie/image I read file from storage path and making some modifications. I want to save it under other storage path, but I got error when try to save image under storage path
$this->destPath = '/_wwwroot/lar/NewsPublisher/storage/app/public/photos/RESULTS/RESULT.png';
// raise error: Unable to create a directory at /storage/app/public/photos.
I tried to write under public/storage subdirectory :
$this->destPath = '/_wwwroot/lar/NewsPublisher/public/storage/photos/RESULTS/RESULT.png';
// raise error: Unable to create a directory at /storage/app/public/photos.
When I try to debug imagePathRef object
dd($this->imagePathRef);
It shows :
Spatie\Image\Image^ {#1083
#manipulations: Spatie\Image\Manipulations^ {#1084
#manipulationSequence: Spatie\Image\ManipulationSequence^ {#1085
#groups: array:1 [
0 => array:3 [
"width" => "400"
"height" => "340"
"border" => "10,#ff0c75,overlay"
]
]
}
}
#imageDriver: "gd"
#temporaryDirectory: null
#optimizerChain: null
#pathToImage: "/storage/app/public/photos/KdRLx9YQ6gNsMtqg27fdXjvYqaPJnsSz15PXIaqs.jpg"
With valid pathToImage image I provided
I pass a valid directory path :
/_wwwroot/lar/NewsPublisher/public/storage/photos/RESULTS$ ls -la
total 4
drwxrwxrwx 1 root root 0 feb 28 10:45 .
drwxrwxrwx 1 root root 4096 feb 29 16:59 ..
So I excluded invalid path passed.
What is wrong ?
"spatie/image": "^2.2.7",
"laravel/framework": "^10.45.1",
|
I encountered a simalar issue a few days ago. My bot also fetches songs, but doesn't play any audio. I still haven't found an answer. Looks like a Lavalink or YouTube bug. |
{"Voters":[{"Id":16343464,"DisplayName":"mozway"},{"Id":1940850,"DisplayName":"karel"},{"Id":7201774,"DisplayName":"Rich"}],"SiteSpecificCloseReasonIds":[13]} |
On Laravel 10 site, in a app/Models/Points.php model I added lastModified attribute :
namespace App\Models;
use Config;
use DB;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Points extends Model
{
use Notifiable;
protected $primaryKey = 'id';
public $timestamps = false;
protected $table = 'points';
public function lastModified(): Attribute
{
$lastModifiedValue = ! empty($this->updated_at) ? $this->updated_at : $this->created_at;
return Attribute::make(get: fn($value) => $lastModifiedValue);
}
But I got error :
Undefined property: App\Models\Points::$created_at
I tried to use getAttribute method :
$lastModifiedValue = ! empty($this->getAttribute('updated_at')) ? $this->getAttribute('updated_at') : $this->getAttribute('created_at');
return Attribute::make(get: fn($value) => $lastModifiedValue);
But I got another error :
Xdebug has detected a possible infinite loop, and aborted your script with a stack depth of '512' frames
What is wrong and how that can be fixed ?
"laravel/framework": "^10.43.0"
|
I have this class called DrawLine and I have generated the adapter class
```
import 'dart:ui';
import 'package:hive/hive.dart';
part 'draw_line.g.dart';
@HiveType(typeId: 0)
class DrawnLine extends HiveObject{
@HiveField(0)
final List<Offset> path;
@HiveField(1)
final Color color;
@HiveField(2)
final double width;
@HiveField(3)
final bool isEraser;
DrawnLine(this.path, this.color, this.width, this.isEraser);
}
```
When I try to save list of `DrawLine` objects, there is an error which indicates hive does not recognize the type `Offset` in the object.
Which means that I have to in turn make an adapter for `Offset` too but I don't know how to go about it.
Any help will be much appreciated. |
Type Adapter for Offset in hive flutter |
|flutter|hive|adapter| |
null |
I attempted to compile Boost using clang and libc++. On x86, the LLVM target triple is x86_64-unknown-linux-gnu, It is the default installation locations for libc++'s header and library files. Clang will search for library files in this directories correctly based on the --target. However, when I tried to compile Boost using clang+libc++, the Boost build system forcibly passed --target=x86_64-pc-linux. This caused clang to fail to find the corresponding header and library files correctly.
use option to force boost build pass --target=x86_64-unknown-linux-gnu to clang |
build boost use libc++ on linux use wrong --target |
|boost|clang|llvm|libc++| |
null |
In general, the radius does not correspond to any value in meters. Depending on projection used and locations, distance in meters of 10 horizontal pixels could be very different from 10 vertical pixels. The world is spherical, not flat.
What MapboxGL offers is function [unproject](https://docs.mapbox.com/mapbox-gl-js/api/map/#map#unproject) - which converts a pixel locations to lng/lat pair. You can unproject a point in the center of the map, and then a point `radius` pixels right to it, compute distance between these coordinates (see Haversine formula), then choose a point `radius` pixels up from center to compute vertical distance. They might differ a lot (again, depending on projection and location on the globe). |
I want to make a discord bot in pyhton to start a minecraft server so a bat file but it cant find the user_jvm_args.txt file even when i say the code where it is. I am not good a coding I did most parts with Chatgpt if there are weird lines
Yes I imported the token.
here is the code:
```
import discord
from discord.ext import commands
import subprocess
import os
import asyncio
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
running_process = None
BOT_TOKEN = 'Token' # Replace 'YOUR_DISCORD_BOT_TOKEN' with your actual Discord bot token
@client.event
async def on_ready():
print("The bot is now ready for use!")
@client.command()
async def start(ctx):
global running_process
if running_process and running_process.poll() is None:
await ctx.send("A process is already running.")
return
batch_file_path = r"C:/Users/tomwi/Desktop/Dommmamjaydenantom/run.bat" # Update this path
user_jvm_args_path = r"C:/Users/tomwi/Desktop/Dommmamjaydenantom/user_jvm_args.txt" # Update this path
try:
await execute_batch_file(ctx, batch_file_path, user_jvm_args_path)
except Exception as e:
await ctx.send(f"Failed to start batch file: {e}")
async def execute_batch_file(ctx, batch_file_path, user_jvm_args_path):
with open(user_jvm_args_path, 'r') as f:
user_jvm_args = f.read().strip()
command = f'java @{user_jvm_args} -Xmx10G -Xms9G "{batch_file_path}"'
running_process = await asyncio.create_subprocess_shell(command)
await ctx.send("Batch file started.")
@client.command()
async def stop(ctx):
global running_process
if running_process and running_process.poll() is None:
try:
running_process.terminate()
await ctx.send("Batch file stopped.")
except Exception as e:
await ctx.send(f"Failed to stop batch file: {e}")
else:
await ctx.send("No batch file is currently running.")
client.run(BOT_TOKEN)
```
I tried many things like putting the file in the directory of the bot origanlly the file wasn't metionend in the code but then I implementet it and it did nothing
but like I said I don't know anything when it comes to programing |
The image here is just an example of what it is I'm trying to do. I have containers (left, main, right) and I want a visualized border, which I assume I will do via image of some sort. I honestly have no idea what they used here, nor how to create my own version of it with new artwork.
[](https://i.stack.imgur.com/28742.png)
I created a border image and now my website looks like a potato chunk slicer
But then after messing with the settings, it now looks like this:
[](https://i.stack.imgur.com/x1KVS.jpg)
At first I had utilized a picture of a border and just added 'border, like this here:
[](https://i.stack.imgur.com/SaiaM.jpg)
That looked like this when implemented on the site:
[![enter image description here][1]][1]
That made it look like this, which I guess isn't too terrible and more in line with my goal. I added this line to my index.html to get the above image:
`border-image: url("{{ url_for('static', filename='border.png')}}") 16 round;`
That wasn't what I wanted so I went into photoshop and created a border_top, _bottom, _left, _right and then tried to slice it and boy did it go wonky.
Image of border image: [](https://i.stack.imgur.com/10Uyc.png)
I only list one, but the others are just like it and are separated by side.
Then I tried this:
```
.container {
position: relative;
display: grid;
grid-template-columns: 1fr 3fr 1fr; /*Adjust the fr units as per your design */
gap: 10px;
height: 100vh; /* Use the full height of the viewport */
}
.container::before,
.container::after {
content: '';
position: absolute;
pointer-events: none;
}
.container::before { /* Top and bottom border */
top: 0; right: 0; bottom: 0; left: 0;
height: 100%;
border: solid transparent;
border-width: 16px 0; /* Top and bottom borders */
background-repeat: round;
background-image: url('border_top.png'), url('border_bottom.png');
background-position: top, bottom;
background-size: 100% 16px; /* Scale to the container width */
}
.container::after { /* Left and right border */
top: 0; right: 0; bottom: 0; left: 0;
width: 100%;
border: solid transparent;
border-width: 0 16px; /* Left and right borders */
background-repeat: round;
background-image: url('border_left.png'), url('border_right.png');
background-position: left, right;
background-size: 16px 100%; /* Scale to the container height */
```
and I ended up with the above picture of the potato chunk slicer. lol
Fair warning - I do NOT know what is standard for creating borders. Is there a way to take just a high-resolution texture and turn it into a border or do I have to create a border in the exact dimensions of each .container? Or? I have scoured the interwebs and see that using images as borders is problematic, but it was done in the above image so I'd like to try to get something similar in mine.
All help is appreciated. For the record, I have played around with all px sizes within. Some of them change the waffle pattern slightly but nothing that appears to fix the problem.
This is my index.html:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My RPG Game</title>
<link
rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}"
/>
<style>
.main-content {
position: relative;
border: 16px solid transparent;
/*border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;*/
}
.main-content::before {
content: "";
position: absolute;
top: -16px;
left: 0;
width: 100%;
height: 16px;
background: url("{{ url_for('static', filename='border_top.png') }}")
repeat-x;
}
/* Bottom border */
.main-content::after {
content: "";
position: absolute;
bottom: -16px;
left: 0;
width: 100%;
height: 16px;
background: url("{{ url_for('static', filename='border_bottom.png') }}")
repeat-x;
}
.sidebar-left {
border: 16px solid transparent;
border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;
}
.sidebar-right {
border: 16px solid transparent;
border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;
}
/* Left border */
.sidebar-left::before {
content: "";
position: absolute;
top: 0;
left: -16px;
width: 16px;
height: 100%;
background: url("{{ url_for('static', filename='border_left.png') }}")
repeat-y;
}
/* Right border */
.sidebar-right::after {
content: "";
position: absolute;
top: 0;
right: -16px;
width: 16px;
height: 100%;
background: url("{{ url_for('static', filename='border_right.png') }}")
repeat-y;
}
</style>
</head>
<body>
<div class="container">
<aside class="sidebar-left">
<!-- Character's location and stats go here -->
</aside>
<main class="main-content">
<!-- Main game content and chat area go here -->
<div class="chat">
<!-- Chat content goes here -->
</div>
<div class="inventory">
<!-- Inventory list goes here -->
</div>
<!-- Add additional sections as needed -->
</main>
<aside class="sidebar-right">
<!-- Additional information or ads could go here -->
</aside>
</div>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
```
This is my full style.css:
```
/* Reset margins and padding */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Container for the entire layout */
.container {
position: relative;
display: grid;
grid-template-columns: 1fr 3fr 1fr; /*Adjust the fr units as per your design */
gap: 10px;
height: 100vh; /* Use the full height of the viewport */
}
.container::before,
.container::after {
content: '';
position: absolute;
pointer-events: none;
}
.container::before { /* Top and bottom border */
top: 0; right: 0; bottom: 0; left: 0;
height: 100%;
border: solid transparent;
border-width: 16px 0; /* Top and bottom borders */
background-repeat: round;
background-image: url('border_top.png'), url('border_bottom.png');
background-position: top, bottom;
background-size: 100% 16px; /* Scale to the container width */
}
.container::after { /* Left and right border */
top: 0; right: 0; bottom: 0; left: 0;
width: 100%;
border: solid transparent;
border-width: 0 16px; /* Left and right borders */
background-repeat: round;
background-image: url('border_left.png'), url('border_right.png');
background-position: left, right;
background-size: 16px 100%; /* Scale to the container height */
}
.sidebar-left,
.sidebar-right {
background-color: #806c50; /* Example color */
/* Add more styling */
}
.main-content {
border-top: 16px solid transparent;
border-right: 16px solid transparent;
border-bottom: 16px solid transparent;
border-left: 16px solid transparent;
border-image-source: url('/static/border_top.png') 16 round,
url('/static/border_right.png') 16 round,
url('/static/border_bottom.png') 16 round,
url('/static/border_left.png') 16 round;
border-image-slice: 200;
border-image-repeat: repeat;
display: grid;
grid-template-rows: 1fr auto; /* Adjust the row sizes as needed
gap: 10px;*/
}
.chat {
background-color: #5c4838; /* Example color */
overflow-y: auto; /* If you want the chat to be scrollable */
/* Add more styling */
}
.inventory {
overflow-y: auto; /* Scrollable list of items */
/* Add more styling */
}
/* Responsive design */
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr; /* Stack sidebars and content on smaller screens */
}
.sidebar-left,
.sidebar-right {
display: none; /* Hide sidebars on smaller screens, or adjust as needed */
}
.main-content {
border-image: none; /* Remove the border image on smaller screens if needed */
grid-template-rows: auto; /* Adjust layout for mobile */
}
}
```
Edit #1:
Okay, so I have fixed the potato slicer view, but I'm basically where I was at from the start.
I commented out this line:
/*.container::before,
.container::after {
content: '';
position: absolute;
pointer-events: none;
}*/
That made it look like this:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/44aK6.png
[2]: https://i.stack.imgur.com/BZhFm.png |
{"Voters":[{"Id":5133585,"DisplayName":"Sweeper"},{"Id":1080064,"DisplayName":"tkausl"},{"Id":768644,"DisplayName":"rzwitserloot"}]} |
I am currently attempting to measure travel time distance using the HERE API. The process was successful for the first 100,000 points; however, I encountered an error when processing the next set of points. The error message appears as follows:
```
No routes found.
Error in if (!is.na(hroute$duration_base)) { : argument is of length zero
```
Do you have any ideas on how to solve this problem?
Thank you
I've attempted to use another variable, but I'm still encountering the same problem.
|
Error in if (!is.na(hroute$duration_base)) { : argument is of length zero |
|r|here-api|travel-time| |
null |
When openning a folder using remote ssh in Visual Studio code with Python extension of Microsoft, the "discovering python interpreters" goes on forever. On the remote (ubuntu), it can be observed that vscode-server is taking 100% of the CPU. Also, the Python extension functionality is not available. |
|visual-studio-code| |
I'm looking for an equivalent to x86/64's FTZ/DAZ instructions found in <immintrin.h>, but for M1/M2/M3. Also, is it safe to assume that "apple silicon" equals ARM?
[EDIT]: Since it seems people hate questions without some context info, here goes:
I am in the process of porting a realtime audio plugin (VST3/CLAP) from x64 Windows to MacOS on apple silicon hardware. At least on x64, it is important for realtime audio code, that denormal numbers (also known as subnormal numbers) are treated as zero by the hardware since these very-small-numbers are otherwise handled in software and that causes a real performance hit.
Now, as denormal numbers are part of the IEEE floating point standard, and they are explicitly mentioned over here https://developer.arm.com/documentation/ddi0403/d/Application-Level-Architecture/Application-Level-Programmers--Model/The-optional-Floating-point-extension/Floating-point-data-types-and-arithmetic?lang=en#BEICCFII, I believe there must be an equivalent to intel's _MM_SET_FLUSH_ZERO_MODE and _MM_SET_DENORMALS_ZERO_MODE macros. Of course, I might be mistaken, or maybe the hardware flushes to zero by default (it's not really clear to me from the ARM document), in which case, I'd like to know that, too. |
|c++|arm|apple-silicon|denormal-numbers| |
{"Voters":[{"Id":9952196,"DisplayName":"Shawn"},{"Id":4850040,"DisplayName":"Toby Speight"},{"Id":272109,"DisplayName":"David Makogon"}],"SiteSpecificCloseReasonIds":[18]} |
Solution found.
One of the changes in Laravel 11 included updating the environment variable for the default broadcast provider. The environment variable "BROADCAST_DRIVER" was changed to "BROADCAST_CONNECTION".
After updating that name everything worked as it did before. |
## Can we write source code in *binary file* when we are using *interpretation* or not?
Can we write source code in binary file when we are using interpretation or not?
Can we write source code in binary file when we are using interpretation or not?
Can we write source code in binary file when we are using interpretation or not?
Can we write source code in binary file when we are using interpretation or not? |
binary file and interpretation in java script? |
|binaryfiles|interpretation| |
null |
I have a MySQL table like this one:
|id|name|surname|score|
|---|---|---|---|
|1|john|smith|15|
|2|john|black|10|
|3|albert|black|5|
|4|john|smith|20|
There can be multiple rows with the same `name` and `surname` combination.
How can I extract data so that the scores are added when the `name` and `surname` are the same?
The outcome I'm looking for is:
|name|surname|added scores|
|---|---|---|---|
|john|smith|35|
|john|black|10|
|albert|black|5| |
null |
It's likely that Firefox is not looking for your `userChrome.css` on startup.
1. Open up a tab and navigate to `about:config` and click `Accept the Risk and Continue`.
2. In the `Search for Preference` box type `userprof`.
3. It should find the `toolkit.legacyUserProfileCustomizations.stylesheets` option. Just click the `toggle` button on the far right to change the setting to `true`.
4. Modify your `userChrome.css` to this:
````css
.tab-background[selected] {
background-color: #dd9933 !important;
background-image: none !important;
}
````
5. Restart your browser. |
A couple years ago I packed this nice solution in TForm-derived class, which you can use instead of Tform to enjoy hints in all your popup menus:
unit UnitMenu;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls,VCL.ExtCtrls, Vcl.AppEvnts;
// menuHint;
type
{β} TMenuItemHint = class(THintWindow)
{β} private
{β} activeMenuItem : TMenuItem;
{β} showTimer : TTimer;
{β} hideTimer : TTimer;
{β} procedure HideTime(Sender : TObject) ;
{β} procedure ShowTime(Sender : TObject) ;
{β} public
{β} constructor Create(AOwner : TComponent) ; override;
{β} destructor Destroy; override;
{β} procedure DoActivateHint(menuItem : TMenuItem) ;
{β} end;
TFormMenuHint = class(TForm)
ApplicationEventsMenu: TApplicationEvents;
procedure ApplicationEventsMenuHint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
//menuhint members
{β} miHint : TMenuItemHint;
{β} fOldWndProc: TFarProc;
procedure PopupListWndProc(var AMsg: TMessage);
public
{ Public declarations }
end;
var
Form8: TFormMenuHint;
implementation
{$R *.dfm}
{β} procedure TMenuItemHint.HideTime(Sender: TObject);
{β} begin
{β} //hide (destroy) hint window
{β} self.ReleaseHandle;
if assigned(hidetimer) then
begin
{β} hideTimer.OnTimer := nil;
freeandnil(hidetimer);
end;
{β} end;
{β} procedure TMenuItemHint.ShowTime(Sender: TObject);
{β}
{β} procedure Split(Delim: Char; Str: string; Lst: TStrings) ;
{β} begin
{β} Lst.Clear;
{β} Lst.StrictDelimiter := True;
{β} Lst.Delimiter := Delim;
{β} Lst.DelimitedText := Str;
{β} end;
{β}
{β} var
{β} r : TRect;
{β} wdth : integer;
{β} list : TStringList;
{β} s,str : string;
{β} j,h,w : integer;
{β}
{β} begin
{β} if activeMenuItem <> nil then
{β} begin
{β} str := activeMenuItem.Hint;
{β} str := StringReplace(str,#13#10,'|',[rfReplaceAll]);
{β} str := StringReplace(str,#13,'|',[rfReplaceAll]);
{β} str := StringReplace(str,#10,'|',[rfReplaceAll]);
{β} while AnsiPos('||',str) > 0 do
{β} begin
{β} str := StringReplace(str,'||','|',[]);
{β} end;
{β}
{β} list := TStringList.Create;
{β} split('|',str,list);
{β} s := '';
{β} h := Canvas.TextHeight(str) * (list.Count);
{β} w := 0;
{β} for j := 0 to list.Count -1 do
{β} begin
{β} if j > 0 then s := s + #13#10;
{β} s := s + list[j];
{β} wdth := Canvas.TextWidth(list[j]);
{β} if wdth > w then w := wdth;
{β} end;
{β} list.Free;
{β}
{β} //position and resize
{β} r.Left := Mouse.CursorPos.X;
{β} r.Top := Mouse.CursorPos.Y + 20;
{β} r.Right := r.Left + w + 8;
{β} r.Bottom := r.Top + h + 2;//6;
{β} ActivateHint(r,s);
{β} end;
{β}
{β} showTimer.OnTimer := nil;
hideTimer := TTimer.Create(self) ;
hideTimer.OnTimer := HideTime;
hidetimer.Interval:=50*length(s);
{β} end; (*ShowTime*)
{ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ}
{β} constructor TMenuItemHint.Create(AOwner: TComponent);
{β} begin
{β} inherited;
{β} showTimer := TTimer.Create(self) ;
{β} showTimer.Interval := Application.HintPause;
{β}
{β}// hideTimer := TTimer.Create(self) ;
{β}// hideTimer.Interval := Application.HintHidePause;
{β} end;
{ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ}
{β} destructor TMenuItemHint.Destroy;
{β} begin
{β} hidetimer.free;//hideTimer.OnTimer := nil;
{β} showTimer.free;//showTimer.OnTimer := nil;
{β} self.ReleaseHandle;
{β} inherited;
{β} end;
{ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ}
{β} procedure TMenuItemHint.DoActivateHint(menuItem: TMenuItem);
{β} begin
{β} //force remove of the "old" hint window
{β} hideTime(self) ;
{β}
{β} if (menuItem = nil) or (menuItem.Hint = '') then
{β} begin
{β} activeMenuItem := nil;
{β} Exit;
{β} end;
{β}
{β} activeMenuItem := menuItem;
{β}
{β} showTimer.OnTimer := ShowTime;
{β} //hideTimer.OnTimer := HideTime;
{β} end;
{ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ}
{β} procedure TFormMenuHint.ApplicationEventsMenuHint(Sender: TObject);
var
ms:Tpoint;
mitem,i:integer;
NewWndProc: TFarProc;
popupmenu:Tpopupmenu;
begin
getcursorpos(ms);
mitem:=-1;
for i:=0 to ComponentCount-1 do
if components[i] is Tpopupmenu then begin
popupmenu:=Tpopupmenu(components[i]);
mitem:=MenuItemFromPoint(0,Tpopupmenu(components[i]).Handle,ms);
if mitem>=0 then
break;
end;
if mitem<0 then
exit;
if not assigned(miHint) then begin
mihint:=Tmenuitemhint.create(self);
NewWndProc := MakeObjectInstance(PopupListWndProc);
fOldWndProc := TFarProc(SetWindowLong(VCL.Menus.PopupList.Window, GWL_WNDPROC,
nativeint(NewWndProc))); //11.3
end;
miHint.DoActivateHint(popupmenu.items[mItem]);
end;
procedure TFormMenuHint.FormDestroy(Sender: TObject);
{β} var
{β} NewWndProc: TFarProc;
{β} begin
if not assigned(mihint) then exit;
{β} NewWndProc := TFarProc(SetWindowLong(VCL.Menus.PopupList.Window, GWL_WNDPROC,
nativeint(fOldWndProc))); //11.3
{β} FreeObjectInstance(NewWndProc);
freeandnil(mihint);
{β} end;
procedure TFormMenuHint.PopupListWndProc(var AMsg: TMessage);
{β}
{β} function FindItemForCommand(APopupMenu: TPopupMenu; const AMenuMsg: TWMMenuSelect): TMenuItem;
{β} var
{β} SubMenu: HMENU;
{β} begin
{β} Assert(APopupMenu <> nil);
{β} // menuitem
{β} Result := APopupMenu.FindItem(AMenuMsg.IDItem, fkCommand);
{β} if Result = nil then begin
{β} // submenu
{β} SubMenu := GetSubMenu(AMenuMsg.Menu, AMenuMsg.IDItem);
{β} if SubMenu <> 0 then
{β} Result := APopupMenu.FindItem(SubMenu, fkHandle);
{β} end;
{β} end;
{β}
{β} var
{β} Msg: TWMMenuSelect;
{β} menuItem: TMenuItem;
{β} MenuIndex: integer;
{β}
{β} begin
{β} AMsg.Result := CallWindowProc(fOldWndProc, VCL.Menus.PopupList.Window, AMsg.Msg, AMsg.WParam, AMsg.LParam);
{β} if AMsg.Msg = WM_MENUSELECT then begin
{β} menuItem := nil;
{β} Msg := TWMMenuSelect(AMsg);
{β} if (Msg.MenuFlag <> $FFFF) or (Msg.IDItem <> 0) then begin
{β} for MenuIndex := 0 to PopupList.Count - 1 do begin
{β} menuItem := FindItemForCommand(PopupList.Items[MenuIndex], Msg);
{β} if menuItem <> nil then
{β} break;
{β} end;
{β} end;
{β} miHint.DoActivateHint(menuItem);
{β} end;
{β} end;
end.
Several weeks ago I had to migrate from Embarcadero Delphi 10.3 to Delphi 11.3 (my CE lysense has expired). Trying to slightly change my old project I rebuilt it and got an ugly error: access violation in the deeps of user32.dll. It costed me a pint of blood to find two casts:
integer(NewWndProc) in FormCreate and
integer(fOldWndProc) in FormDestroy
which worked as 64-bit in 10.3 and became 32-bit in 11.3. Use nativeint() instead
|
I am new to phoenix, and am trying to setup a project using Docker on WSL. I have the project running, and I can make changes just fine. The issue occurs when using one of the Phoenix generators, whenever I try to edit a generated file I have no permission to save it, since it was created from inside the container.
I have worked with Docker before, but mainly for PHP. I understand that I need to create a user that matches my host user. However, when I try this, I get errors that mix has no permission to read certain files, like from the _build directory for example. I am new and probably completely missing something. Here are my base Dockerfile docker-compose.yml and entrypoint.sh, without the user created:
Dockerfile:
```
FROM hexpm/elixir:1.16.2-erlang-26.2.2-alpine-3.19.1
RUN apk add --no-cache git
RUN mkdir /app
COPY . /app
WORKDIR /app
RUN mix local.hex --force
RUN mix deps.get && mix deps.compile
CMD /app/entrypoint.sh
```
docker-compose.yml:
```version: "3.2"
services:
phoenix:
build:
context: .
volumes:
- ./:/app
environment:
DB_USER: user
DB_PASSWORD: secret
DB_DATABASE: vrn
DB_PORT: 3306
DB_HOST: db
ports:
- 4000:4000
depends_on:
- db
db:
image: mysql:8.3
environment:
MYSQL_ROOT_PASSWORD: rootsecret
MYSQL_DATABASE: vrn
MYSQL_USER: user
MYSQL_PASSWORD: secret
restart: always
volumes:
- mysql:/var/lib/mysql
volumes:
mysql:
```
entrypoint.sh:
```mix deps.get
mix ecto.create
mix ecto.migrate
mix phx.server
```
I have tried creating a user and group to match my host user at the beginning of the Dockerfile, but I am sort of new to it and have probably completely messed that up. |
choises = {
"1": func1,
"2": func2("CategoryA"),
"3": func2("CategoryB"),
...
"7": func3,
...
}
Do you see the key difference in how the dictionary is using `func2` versus `func1` and `func3`?
The references to `func2` also have parentheses `()` after the function name, meaning the function is called _immediately_, and the returned value is stored in the dictionary.
But `func1` and `func3` do not have parentheses after, so the dictionary is storing the actual function objects, which are called _later_.
If you want `func2` to be called _later_, like `func1` and `func3`, then get rid of the parentheses in the dictionary definition.
EDIT:
If you want the dictionary to also contain arguments for some of the function calls, you can use `functools.partial()` to create a callable "bundle" with a function object and optionally some arguments:
from functools import partial
choises = {
"1": partial(func1),
"2": partial(func2, "CategoryA"),
"3": partial(func2, "CategoryB"),
...
"7": partial(func3),
...
}
Then you would just call the function object in the dict:
choises["2"]() |
{"Voters":[{"Id":10035985,"DisplayName":"Andrej Kesely"},{"Id":12131013,"DisplayName":"jared"},{"Id":15187728,"DisplayName":"bb1"}]} |
|r|docker|gdal|r-sf| |
null |
I am simulating CPU scheduling algorithms for a class. I have a struct called job that contains the basic info for each job, and I'm trying to order a priority queue of these jobs in order from smallest number of cycles needed to largest number of cycles needed. This is currently my custom comparator to do that:
```
class CompareJobTime {
public:
bool operator()(job job1, job job2) {
if (job1.cycles < job2.cycles) {
return false;
}
else
return true;
}
};
```
and this is how I'm using it in the priority queue declaration:
` priority_queue<job, vector<job>, CompareJobTime> jobTPQ;`
I've attached an image of the error it throws. Any help would be greatly appreciated, as I really don't have a clue where to go from here when it comes to debugging. Thanks!
I've tried changing up the definition in a couple ways, but I'm not sure what's wrong with it. I have also tried using decltype instead of a comparator class, but I couldn't get that to work since I was writing the comparator function as a member of the class this is all being written in. |
Using custom comparator to sort a Priority Queue in C++. Keep getting invalid operator error |
|c++|comparator|priority-queue| |
null |
{"Voters":[{"Id":7758804,"DisplayName":"Trenton McKinney"},{"Id":14732669,"DisplayName":"ray"},{"Id":530160,"DisplayName":"Nick ODell"}]} |
|docker|apache-kafka|docker-compose|docker-network| |
You can create a metric filter for your log group and then configure an alarm based on the metric filter -
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_alarm_log_group_metric_filter.html |
Discordbot(Python) who should start bat file(Minecraft server) can't find user_jvm_args.txt file |
|python|batch-file|discord| |
null |
I just spent a day with this, there is something you must be aware of when you try to fix the credential problem: aws does lot of magic where it gets your credentials from, you might be not using the ones you explicitely enter, but some from .env or user_home/.aws or from old settings when you opened your terminal.
try in a new console
aws s3 ls
aws configure list
and then in your visual studio code console, and you might get a surprise
|
My question is a bit complex, but I'll try to make it clear. I want to create a Bash function. Now, here's the interesting part - I want to do this by referencing what the user will type.
Since I don't know what that is, I'll optionally refer to it as $2, $3. How can I make it so that I can extract the commands that the user will type?
For example
```bash
function check() {
case $1 in
-c)
if [ -x $2 || -x ${@} ]
then
${@} $* # these ("$@ & $*) represent what goes into this function
fi
esac
}
```
Then I call the function - ` "check -c /usr/". `
Working with the func, for example:
```bash
if [ check -c | grep "/usr" != 0 ] # "check -c" is my func
then
cd /usr/
fi
```
Or: `check -c /usr/ && ls *`
If it succeeds, how do I continue writing what I want to do after "check -c /usr/"? Right after? Or in a new line?
It's a bit like making a programming language - how do I make it so that these commands I type into the functions run? In short - I would like to create such functions for programming myself. Or should such things be done in C? If so, can I get links to study it? The point of this is to make programming easier for myself.
I hope that was clear. If not, I can't explain it any better than that. Thanks in advance for your help!!!!
I just tested this, but not with much success. |
null |
In your Storage account, make sure the Blob Soft Delete option is Disabled. If it's enabled, follow the next step to learn how to disable it.
[![enter image description here][1]][1]
For details review this page
https://ganeshchandrasekaran.com/azure-databricks-configure-your-storage-container-to-load-and-write-data-to-azure-object-storage-3db8cd506a25
[1]: https://i.stack.imgur.com/Trq2C.png |
You need to add `group="Group Name"` to your call to `addLegend()`, which should then allow you to toggle the corresponding legends anytime you turn a layer on/off.
library(leaflet)
df1 <- data.frame(
Tickets = c(28, 4, 3),
long = c(-71.12088,-71.09524,-71.11935),
lat = c(42.37418, 42.36911, 42.38532)
)
df2 <- data.frame(
Tickets = c(33, 1, 21, 1),
long = c(-71.1213,-71.0915,-71.1226,-71.1016),
lat = c(42.37401, 42.37255, 42.37512, 42.36411)
)
base_map <- leaflet() %>%
addProviderTiles("CartoDB.Voyager") %>%
setView(-71.128184, 42.3769824, zoom = 14)
pal1 <- colorNumeric(palette = "RdBu",
domain = df1$Tickets)
pal2 <- colorNumeric(palette = "RdBu",
domain = df2$Tickets)
base_map |>
addCircles(
data = df1,
lng = df1$long,
lat = df1$lat,
color = pal1(df1$Tickets),
radius = 5,
group = "Group 1 Dots"
) %>%
addLegend(
"bottomright",
pal = pal1,
values = df1$Tickets,
title = "1 Dots",
group = "Group 1 Dots"
) %>%
addCircles(
data = df2,
lng = df2$long,
lat = df2$lat,
color = pal2(df2$Tickets),
radius = 5,
group = "Group 2 Dots"
) %>%
addLegend(
"bottomright",
pal = pal2,
values = df2$Tickets,
title = "2 Dots",
group = "Group 2 Dots"
) %>%
addLayersControl(
overlayGroups = c("Group 1 Dots", "Group 2 Dots"),
options = layersControlOptions(collapsed = FALSE)
) |
Phoenix in a docker dev environment - generated code can't be saved from VSCode |
|docker|docker-compose|dockerfile|elixir|phoenix-framework| |
null |
When writing a query with specific columns in select, I get only the first element that I specified in it. That is, such a code
```
query = select(self.model.name, self.model.price).join(CategoryRepository.model).join(
ImageRepository.model, is outer=True)
```
```
print((await self._session.scalars(query)).all())
```
Returns ```['Shoes', 'Dress', 'Pendant']``` - only the names, although the sql code generates the correct one. And when calling execute, everything works correctly
```
print((await self._session.execute(query)).all())
```
Returns ```[('Dress', 350.0199890136719), ('Shoes', 300.04998779296875), ('Pendant', 99.98999786376953)]``` |
The selection of specific columns in SQLAlchemy in scalars does not work |
|python|sqlalchemy|fastapi| |
null |
please enter this command with SSH;
docker-compose up -d
docker exec -it greenlight-v3 bundle exec rake admin:create['Your Name','email@example.com','!Example11Password']
|
{"OriginalQuestionIds":[66289122],"Voters":[{"Id":8690857,"DisplayName":"Drew Reese","BindingReason":{"GoldTagBadge":"javascript"}}]} |
I found the reason behind this issue. When I checked the **AWS console**. It was showing the cpu usage graph getting the peek value after each 3 hrs. then I checked my crons and found that there was a cron to upload the videos to youtube. Cron used to create multiple process for each video upload to avoid script timeout situation. Now in that script I have to fetch the video from my another server. The main reason was this. the streamname I was providing to the fetch the video from another server resulted in continues waiting state. Due to that the php-fpm also starts waiting for that script to exit. Hence unresolved state occurred every 3 hrs.
**What was the Reason?**
If PHP-FPM is not properly configured to handle PHP errors, such as syntax errors or fatal errors, it may not terminate the worker process after encountering such errors. As a result, PHP-FPM continues to create new processes for subsequent requests, leading to an accumulation of processes.
So If you guys are getting the same error as shown in above screenshot then there must be something wrong in your php script which is responsible for the php-fpm to wait endlessly.
if php-fpm process is started then it should stop, if does not then try to improve your code.
**Solution to the Problem**
1) Enable proper error handling and logging in PHP-FPM to identify and address any issues causing requests to fail. Make sure that PHP-FPM terminates worker processes after encountering fatal errors or other critical issues.
2) Try setting appropriate script timeout values (max_execution_time, max_input_time, etc.) in your PHP configuration to prevent requests from running excessively long.
I think you have got the main idea. Try to find if you notice something similar as in my case and get your server running smoothly. I also have summarized the entire situation in detail with possible reasons and with respective solutions on my blog. Check it out here. [Too many process created by PHP-FPM][1]
cheers :)
[1]: https://orgfoc.com/php-fpm-with-nginx-config-too-many-process/ |
public static string Mtd_GetDriveLetterWithLabel(string DriveLabel)
{
ManagementObjectSearcher DriveLabelQuery = new ManagementObjectSearcher(" SELECT * FROM Win32_Volume WHERE Label = '" + DriveLabel + "' ");
string DriveLetter = "";
foreach (ManagementObject DriveLabels in DriveLabelQuery.Get())
{
DriveLetter = DriveLabels["DriveLetter"].ToString();
}
return DriveLetter;
}
public static int Mtd_GetDiskNumberWithLetter(string DriveLetter)
{
ManagementObjectSearcher DriveLetterGeneralQuery = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
ManagementObjectCollection DriveLetterCollection = DriveLetterGeneralQuery.Get();
string Dependent = @"\\" + Environment.MachineName + "\\root\\cimv2:Win32_LogicalDisk.DeviceID=\"" + DriveLetter + "\"";
String DiskNumberTxt = "";
foreach (ManagementObject DiskNumbers in DriveLetterCollection)
{
if ((DiskNumbers["Dependent"].ToString()) == Dependent)
{
DiskNumberTxt = DiskNumbers["Antecedent"].ToString();
}
}
int From = DiskNumberTxt.IndexOf("Disk #") + "Disk #".Length;
int To = DiskNumberTxt.IndexOf(",");
String DiskNumberTrim = DiskNumberTxt.Substring(From, To - From);
int DiskNumber = Int32.Parse(DiskNumberTrim);
return DiskNumber;
}
public static string Mtd_GetSerialNumberWithDiskNumber(int DiskNumber)
{
ManagementObjectSearcher SerialNumberQuery = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
ManagementObjectCollection SerialNumberCollection = SerialNumberQuery.Get();
string Tag = @"\\.\PHYSICALDRIVE" + DiskNumber;
String SerialNumberTxt = "";
foreach (ManagementObject SerialNumbers in SerialNumberCollection)
{
if ((SerialNumbers["Tag"].ToString()) == Tag)
{
SerialNumberTxt = SerialNumbers["SerialNumber"].ToString();
}
}
return SerialNumberTxt;
}
string DriveLabel = "DATA";
string DriveLetter = Mtd_GetDriveLetterWithLabel(DriveLabel);
Console.WriteLine(DriveLetter);
int DiskNumber = Mtd_GetDiskNumberWithLetter(DriveLetter);
Console.WriteLine(DiskNumber);
string DiskSerialNumber = Mtd_GetSerialNumberWithDiskNumber(DiskNumber);
Console.WriteLine(DiskSerialNumber); |
We are trying to replace WebSphere Extremescape in our environment and planning to use redis. The only reason we are using WebSphere extremescale is to provide HTTP session persistence. I believe we can use jcache/redisson to have WebSphere Liberty use redis for session persistence. Has anyone done that - if yes, would you please share your configuration for redisson-jcache.yaml and server.xml configuration
Thanks,
Trying to setup the environment |
WebSphere Liberty integration with Redis for HTTP Session Persistence |
|redis|websphere-liberty|redisson|jcache| |
null |