instruction stringlengths 0 30k ⌀ |
|---|
I hope you are all doing well. I’m currently working on this video: https://youtu.be/HYnZAX7g0lc It’s about the voice chat function with EOS. I’ve installed the EOS voice chat plugin and have also followed the three previous videos from the tutorial series. Right at this point (Link directly to this timestamp: https://youtu.be/HYnZAX7g0lc?t=292), he added the dependency for the EOS Voice-Plugin. Then, a bit later at this point (Link: https://youtu.be/HYnZAX7g0lc?t=308), when he does the include, I can’t find the include. Does it work for you? Can anyone help me?
I would be grateful for any assistance. |
EOS Voice Chat Missing include |
|c++|unreal-engine5| |
I am trying to compute Lah numbers with Maple, but without using the Lah numbers recurrence relation, but the relation with Stirling numbers of both kind:
$L(n, k) = \sum_{j=0}^{n} s(n, j) S(j, k)$, where
$s(n, k) = s(n-1, k-1) + (n-1) s(n-1, k)$ and
$S(n, k) = S(n-1, k-1) + k S(n-1, k)$.
I have tried the following code:
s := proc(n, k) option remember;
`if`(n = k, 1, `if`(k < 0 or n < k, 0, s(n - 1, k - 1) + (n - 1)*s(n - 1, k)));
end proc;
S := proc(n, k) option remember;
`if`(n = k, 1, `if`(k < 0 or n < k, 0, S(n - 1, k - 1) + k*S(n - 1, k))); end proc;
sum(s(n, j)*S*(j, k), j = 0 .. n);
end do;
and it always reports an error:
```Error, unable to parse ```
It looks like that the code is wrong, but I do not know how to fix it.
When I click on the error, it sends me to this website:
https://www.maplesoft.com/support/help/errors/view.aspx?path=Error,%20unable%20to%20parse
Any suggestions for fixing the code?
Thanks a lot.
I have tried to fix the code but I do not know how to fix it. |
create remote cache if does not exist during write and ignore remote cache if connection cannot be made |
|spring|caching|infinispan| |
I have an SVG file with text elements.
The file is [here](https://commons.wikimedia.org/wiki/File:Powers_of_rotation,_shear,_and_their_compositions.svg) on Wikimedia Commons.
The text I use as an example is: (s∘r)<sup>2</sup>
```xml
<g style="text-anchor: middle; letter-spacing: -1;" font-size="25px" font-family="sans-serif">
<text x="500">
(s∘r)
<tspan baseline-shift="super" font-size="18px">2</tspan>
</text>
</g>
```
Rendered in Image Viewer on Ubuntu it looks like it should. Also when I open it with Inkscape.<br>
In Firefox it looks almost the same, except that `baseline-shift` does not work.<br>
But rendered on Wikimedia Commons it is shifted to the right.<br>
I see no reason for that. (It does not happen to the shorter text elements above.)
[![enter image description here][1]][1]
Does the Commons renderer do something wrong?<br>Or is my code somehow vague enough to allow this?
The `width` and `height` of my SVG is 10 times bigger than the actual size.<br>Could that be the reason?
[1]: https://i.stack.imgur.com/dpigO.jpg |
You need to ensure that the coordinates obtained are within the range of the grid before updating the list l.
You can modify your `d` function to handle out-of-range coordinates like:
def d(x, y):
global l
# Check if the coordinates are within the grid range
if 0 <= x < C and 0 <= y < R:
l[y][x] = 1
c.create_rectangle(x * z, y * z, (x + 1) * z, (y + 1) * z, fill='#fff', outline='') |
```
final String uid = FirebaseAuth.instance.currentUser!.uid;
Padding(
padding: const EdgeInsets.all(20),
child: StreamBuilder(
stream: FirebaseFirestore.instance.collection('Users').doc(uid).snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data?["name"]);
} else {
return CircularProgressIndicator();
}
},
),
),
```
I want to display the name data saved in Firebase on the screen, but even though I type it according to the documentation, CircularProgressIndicator keeps returning. Where am I doing wrong?
|
I use supertest and mocha and all works but I got one problem. If I use the expect function and it fails my test says still its passing but this is false it should show an error and not passed. What I am doing wrong ?
```
Create Tenant Account
Login to a user who is Admin
POST /api/auth/sign_in 200 745.330 ms - 3341
AssertionError: expected { isAdmin: true, …(4) } to have own property 'isAdm21221in'
at file:///C:/Users/rambo/Desktop/psm-solution/backend/test/createTenant.test.js:34:28
at processTicksAndRejections (node:internal/process/task_queues:95:5) {
actual: {
isAdmin: true,
isTenantAdmin: true,
provider: 'email',
providers: [ 'email' ],
tenantId: 'f997ca0e-9bed-4550-a115-1175ff1406e7'
},
expected: undefined,
showDiff: false
}
✔ should login to a user and recieve a 200 http status code (970ms)
1 passing (994ms)
```
You see AssertionError and the expected fails but then you see at the bottom 1 passing so it succeed. it should fail here is my code
```
import supertest from 'supertest';
import { app, supabase } from '../src/server.ts';
import { expect } from 'chai';
describe('Create Tenant Account', () => {
describe('Login to a user who is Admin', () => {
it('should login to a user and recieve a 200 http status code', done => {
supertest(app)
.post('/api/auth/sign_in')
.send({email: 'testmest@evt2.de', password: '123456'})
.then(res => {
expect(appmeta).to.haveOwnProperty('isAdm21221in');
expect(res.statusCode).to.equal(200);
done();
})
.catch(e => {
console.log(e);
done();
});
});
});
});
``` |
I have an array state variable `flashingBoxLoaderItems` that will collect the "receipts" from individual async fetches happening in the component, to let me know when all the fetches are complete. There's also a boolean variable `flashingBoxLoaderComplete` that is set on an `Effect` monitoring any changes on `flashingBoxLoaderItems` to hide the loader when everything's done.
const [flashingBoxLoaderItems, setFlashingBoxLoaderItems] = useState<string[]>([]);
const [flashingBoxLoaderComplete, setFlashingBoxLoaderComplete] = useState(false);
Example of fetches. Note that the state variable is correctly updated for the Effect using the spread ... syntax, so the effect does pick it up.
const fetch1 = async() => {
try {
const response = await get<any>("/url1/");
//...
} catch {
//...
} finally {
setFlashingBoxLoaderItems([...flashingBoxLoaderItems, 'fetch1']);
}
}
// ETC. - Same for fetch2(), fetch(3), etc.
Effect to check all the receipts and set the final `complete` variable:
useEffect(() => {
let fetchesExpected = ['fetch1','fetch2','fetch3','fetch4','fetch5'];
let result = fetchesExpected.every(i => flashingBoxLoaderItems.includes(i));
setFlashingBoxLoaderComplete(result);
}, [flashingBoxLoaderItems]);
But this doesn't work correctly. The debugger shows that my `flashingBoxLoaderItems` doesn't grow incrementally as expected. Sometimes it has 1 or 2 strings instead of the expected 4 or 5 on the 4th or 5th fetch. My suspicion is the fetches all happen at different times and the array isn't being synchronously maintained. So the `complete` variable at the end never gets set to TRUE after the 5th fetch as it should.
The code that does work is if I simply `flashingBoxLoaderItems.push('fetchN')` after each fetch. But in that case, since there's no state variable change, so there's no re-render. I never get the chance to re-render and hide/show the loader. |
I am new to B2B Commerce LWR site. I have been trying to find the authenticated user details using expressions but I keep getting undefined as value
Can anyone please guide me ?
B2B Commerce Undefined issue:
[![image of error][1]][1]
I tired {!User.userId} but no luck !
[1]: https://i.stack.imgur.com/C9Jl4.png |
null |
I am new to B2B Commerce LWR site. I have been trying to find the authenticated user details using expressions but I keep getting undefined as value
Can anyone please guide me?
B2B Commerce Undefined issue:
[![image of error][1]][1]
I tried `{!User.userId}` but no luck!
[1]: https://i.stack.imgur.com/C9Jl4.png |
I think the cleanest solution is to use `hidden` on a parent `div`, and use jsPDF to print the `div` inside.
<div hidden>
<div id="divToPdf">Some content here</div>
</div> |
I use this simple code and it works well(if you want to release the button from being pressed ,set timer).I hope this will help you..
> xaml code
``` xml
<Button Name="male" Height="318" Width="352" Click="male_Click" Margin="236,120,1332,642">
<Button.Background>
<ImageBrush ImageSource="pack://application:,,,/Imagesrc/logotype/USER_MALE.png" ></ImageBrush>
</Button.Background>
</Button>
```
> pressed code
``` c#
public void male_Click(object sender, RoutedEventArgs e)
{
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Source = new BitmapImage(new Uri(@"pack://application:,,,/maindocket;component/Imagesrc/logotype/USER_MALE_SELECTED.png"));
male.Content = img;
}
``` |
# Use a button with an event listener
Your problem can be reduced to this example:
A simple HTML document with a script (I've used a module).
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module" src="script.js"></script>
</head>
<body>
</body>
</html>
```
The script defines two functions and calls one.
```js
function ZoomTo(extent) {
alert(extent);
}
function FeatureType() {
document.body.innerHTML += "<a href='javascript:ZoomTo(extent);'>Zoom to Marker</a>";
}
FeatureType()
```
The above code reproduces your error exactly.
We can fix it by using a more sophisticated approach to HTML generation and event handling.
Here we create a button and call the `ZoomTo` function in an event handler.
```js
function FeatureType() {
const button = document.createElement('button');
button.textContent = 'Zoom to marker';
document.body.append(button);
button.addEventListener('click', ev => {
ZoomTo('test');
});
}
```
|
Is there a way to make this request with UrlFetchApp in app script?
curl -X GET http://test.com/api/demo -H 'Content-Type: application/json' -d '{"data": ["words"]}'
I attempted it with this code:
const response = UrlFetchApp.fetch(API_URL, {
method: "GET",
headers: { "Content-Type": "application/json" },
payload: JSON.stringify(payload)
});
*The payload and the endpoint are the exact same as the curl request which I tested*
However I got this error "Failed to deserialize the JSON body into the target type: missing field `name` at line 1 column 88". |
Sending a body in a GET request with UrlFetchApp? |
|google-apps-script|curl|urlfetch| |
null |
VB.Net Project using visual Studio
Microsoft Visual Studio Community 2022 (64-bit) - Current
HTMLAgility Pack
When I try to load a web page via the HtmlWeb Load method, I receive this error: "Cannot access a disposed object"
I put following code in the form load event. It doesn't get any simpler than this:
Dim Web As HtmlWeb = New HtmlWeb()
Dim Document = Web.Load("https://scrapeme.live/shop/")
When the Web.Load event executes, I get the error.
Any advice would be greatly appreciated.
I simplified the code as much as possible and placed it in the form load event. |
Why does hovering over a DateTimeOffset display the Hour value only? |
My problem is pretty similar to the following [post][1]
In my database i have multiple columns containing values like M0, M6, M12... and so on. And i have columns having those names M0, M6, M12...
I would like to replace the first columns containing the M0... with the value corresponding in the column
As an understanding example i have :
```
df <- data.frame(time=c("M0","M12","M0","M0","M12"),
M0=c(1,2,4,5,1),
M12=c(8,5,9,2,1))
df
time M0 M12
1 M0 1 8
2 M12 2 5
3 M0 4 9
4 M0 5 2
5 M12 1 1
```
As mentioned i found a post with interesting answers, and one in particular with the use of `cur_data()`
```
df2 <- df %>%
rowwise %>%
mutate(newd = cur_data()[[cur_data()$time]]) %>%
ungroup
df2
# A tibble: 5 × 4
time M0 M12 newd
<chr> <dbl> <dbl> <dbl>
1 M0 1 8 1
2 M12 2 5 5
3 M0 4 9 4
4 M0 5 2 5
5 M12 1 1 1
```
It works, but takes a really long time and also apparently the `cur_data` is deprecated in favor of `pick()` which i don't get how to replace to make it work
Any advice on this would be much appreciated !
[1]: https://stackoverflow.com/questions/70313383/adding-column-name-into-a-new-column-if-it-equals-row-value |
Multiple async fetches writing to an array state variable cause inconsistent state |
I am trying to add the code below to an existing application that uses GStreamer 1.22.1.
It compiles but gives a link error:
>/home/src/webrtc/gst/gst.c:99: undefined reference to `gst_rtp_buffer_map'
The code seems to be in [gst-plugins-base][1], which Is enabled.
What am I missing?
This is the build command:
```
meson \
-Dbuildtype=release \
-Drs=disabled \
-Dtests=disabled \
-Dexamples=disabled \
-Drtsp_server=disabled \
-Dges=disabled \
-Dgst-examples=disabled \
-Ddoc=disabled \
-Dgtk_doc=disabled \
-Dpython=disabled \
-Dqt5=disabled \
-Dgst-plugins-bad:openh264=disabled \
-Dugly=${x264_flag} \
-Dgpl=${x264_flag} \
-Dlibav=enabled \
-Dbase=enabled \
-Dgood=enabled \
-Dbad=enabled \
-Dgst-plugins-good:rtp=enabled \
-Dgst-plugins-base:ogg=disabled \
-Dgst-plugins-base:vorbis=disabled \
-Dgst-plugins-good:jpeg=disabled \
-Dgst-plugins-good:lame=disabled \
-Dgst-plugins-bad:rtp=enabled \
-Dgst-plugins-bad:webrtc=enabled \
-Dgst-plugins-bad:va=enabled \
-Dgst-plugins-bad:dvb=disabled \
-Ddevtools=disabled \
--prefix=/opt/local/build/gst/ builddir && ninja -C builddir && ninja -C builddir install && ldconfig
```
And this is the new code:
```
#include <gst/rtp/gstrtpbuffer.h>
...
if (gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)) {
rtptime = gst_rtp_buffer_get_timestamp (&rtp);
seqnum = gst_rtp_buffer_get_seq (&rtp);
gst_rtp_buffer_unmap (&rtp);
}
```
[1]: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/blob/main/subprojects/gst-plugins-base/gst-libs/gst/rtp/gstrtpbuffer.c?ref_type=heads |
I have a MySQL data base, and **mysqld** is running.
In a php file i have:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions
$g_dbconn = 0;
$g_hostname = "localhost";
$g_dbname = "test_db";
$g_user = "test_user";
$g_pw = "test_pw";
try {
$g_dbconn = mysqli_connect($g_hostname, $g_user, $g_pw, $g_dbname);
println("Success!");
} catch (mysqli_sql_exception $e) {
die('Could not connect using: '. $g_hostname.' ' . $g_dbname.' '. $g_user.' '. $g_pw . ': Exception: ' . $e->getMessage().'<br/>');
}
?>
When i run this code in the browser, the exception gets thrown and i get
Could not connect using: localhost test_db test_user test_pw: Exception: No such file or directory
i.e. the exception has been thrown, but there is no further explanation.
I get the same message if i call this php file from the console:
php test_mysql.php
The connection parameters are in order - using them i can log in to **mysql** on the console without any problems.
What could cause this problem?
How can i find out what file or directory does not exist? |
mysqli_connect throws exception "No such file or directory" |
|php|mysql|mysqli| |
Web application is loaded only in the form address `ip:8080`.
I've a web application that is configured as `Wildfly` server and `Nginx` reverse proxy, I am trying to load this application in the browser without success because the application load only with ip address information.
This is my first time that I use `Wildfly` server and `Nginx` then I don't have experience, but I've reading high. My application is a `Maven` project in `Java`, all in the project is working fine.
Below is my configurations.
My `standalone.xml`:
```
<subsystem xmlns="urn:jboss:domain:deployment-scanner:2.0">
161 <deployment-scanner name="itcmedbr.war" path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" auto-deploy-exploded="true" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>
162 </subsystem>
```
My `nginx` conf:
```
1 server {
2 listen 80;
3 listen [::]:80;
4 server_name itcmedbr.com www.itcmedbr.com;
5
6 # Load configuration files for the default server block.
7
8 location / {
9 root /opt/wildfly/standalone/data/content/39/c296b5d6d608465514ecce78b062f85b5f9001/content;
10 proxy_set_header X-Forwarded-For $remote_addr;
11 proxy_set_header Host $server_name:$server_port;
12 proxy_set_header Origin http://myipaddress;
13 proxy_set_header Upgrade $http_upgrade;
14
15 proxy_pass http://127.0.0.1:8080;
16 }
17
18 error_page 404 /404.html;
19 location = /40x.html {
20 }
21
22 error_page 500 502 503 504 /50x.html;
23 location = /50x.html {
24 }
25 }
```
In my mind I understanding that when is made a deploy a file is created so I looked in the `wildfly` folders and found this file that I specified in the root parameter of my `nginx.conf`, but the problem still the same, i.e `domain.com` and load the page.
What I must to do to solve this problem?
Thanks and best regards.
1 - deploy the war file
```
ls /opt/wildfly/standalone/deployments/
itcmedbr.war itcmedbr.war.deployed README.txt
```
2 - configuration of `nginx`:
```
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# Settings for a `TLS` enabled server.
#
# server {
# listen 443 ssl http2 default_server;
# listen [::]:443 ssl http2 default_server;
# server_name _;
# root /usr/share/nginx/html;
#
# ssl_certificate "/etc/pki/nginx/server.crt";
# ssl_certificate_key "/etc/pki/nginx/private/server.key";
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 10m;
# ssl_ciphers PROFILE=SYSTEM;
# ssl_prefer_server_ciphers on;
#
# # Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
#
# location / {
# }
#
# error_page 404 /404.html;
# location = /40x.html {
# }
#
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }
}
```
2.1 - configuration of `itcmedbr.com.conf` in `/etc/nginx/conf.d`:
```
server {
listen 80;
listen [::]:80;
server_name itcmedbr.com www.itcmedbr.com;
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
# Redirect all port 80 (HTTP) requests to port 443 (HTTPS).
return 301 https://itcmedbr.com$request_uri;
# Load configuration files for the default server block.
location / {
proxy_set_header Origin http://ipaddress;
proxy_pass http://127.0.0.1:8080;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
```
3 - status `nginx`:
```
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2024-03-03 18:36:43 -03; 41s ago
```
4 - status `wildfly.service`:
```
Loaded: loaded (/etc/systemd/system/wildfly.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2024-03-03 18:25:40 -03; 41s ago
```
5 - `firewall` ports:
```
firewall-cmd --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0
sources:
services: http https ssh
ports: 8080/tcp 9990/tcp 3306/tcp 80/tcp 443/tcp
protocols:
forward: no
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
ss -tunelp | grep 80
tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=159107,fd=6),("nginx",pid=159105,fd=6)) ino:2538418 sk:4b <->
tcp LISTEN 0 2048 xxx.xxx.xx.xxx:8080 0.0.0.0:* users:(("java",pid=158828,fd=494)) uid:990 ino:2536856 sk:4c <->
tcp LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=159107,fd=7),("nginx",pid=159105,fd=7)) ino:2538419 sk:4f v6only:1 <->
ss -tunelp | grep 443
tcp LISTEN 0 511 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=159107,fd=8),("nginx",pid=159105,fd=8)) ino:2538420 sk:4d <->
tcp LISTEN 0 2048 xxx.xxx.xx.xxx:8443 0.0.0.0:* users:(("java",pid=158828,fd=495)) uid:990 ino:2536857 sk:4e <->
tcp LISTEN 0 511 [::]:443 [::]:* users:(("nginx",pid=159107,fd=9),("nginx",pid=159105,fd=9)) ino:2538421 sk:50 v6only:1 <->
```
Now when I typing `itcmedbr.com` I receiving " This site can't be reached The connection was reset." and if I typing in the browser `ip:8080` the "`Welcome to Wildfly`" page is loaded.
Trying to solve the problem I did the following steps:
1 - uninstall and remove `Nginx`
2 - install `nginx` with `certbot`
```
yum install nginx certbot python3-certbot-nginx
```
3 - create my `server conf`
```
vi /etc/nginx/conf.d/itcmedbr.conf
server {
server_name itcmedbr.com;
}
```
4 - configure `certbot`
```
certbot --nginx
define email
define domain
```
5 - `reload`, `restart`, `nginx` and `wildfly`
6 - when test `nginx` result is:
```
nginx -t
nginx: [warn] conflicting server name "itcmedbr.com" on 0.0.0.0:80, ignored <==(I don't know why this occur and how to solve this)
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
```
7 - result of `nginx.conf`
```
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# Settings for a TLS enabled server.
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name _;
root /usr/share/nginx/html;
ssl_certificate "/etc/ssl/certs/nginx-selfsigned.crt";
ssl_certificate_key "/etc/ssl/private/nginx-selfsigned.key";
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers PROFILE=SYSTEM;
ssl_prefer_server_ciphers on;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
server {
server_name itcmedbr.com; # managed by Certbot
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/itcmedbr.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/itcmedbr.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = itcmedbr.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name itcmedbr.com;
return 404; # managed by Certbot
}}
```
How we can see `nginx.conf` was updated by `certbot` and is managed by `certbot` too.
After all of this now I've a new problem that when I typing my `ipaddress:9990` in the browser to open `wildfly` console I receive the same message "This site can't be reached." |
I would suggest recreating the local variable as a map:
```hcl
locals {
storage_accounts = {
sa_we = "0c975d82-85a2-4b3a-bb23-9be5c681b66f"
sa_gl = "9ee248b1-26f6-4d72-a3ac-7b77cf6c17f2"
}
}
```
Then, using the [`for_each`][1] meta-argument you could use the resource block only once:
```hcl
resource "azurerm_role_assignment" "storage_account_access" {
for_each = local.storage_accounts
scope = azurerm_storage_account.jd-messenger.id
role_definition_name = "Storage Blob Data Reader for ${each.key}"
principal_id = each.value
}
```
[1]: https://developer.hashicorp.com/terraform/language/meta-arguments/for_each |
I was able to successfully render the simplest `hello` shiny app successfully, it worked fine and fast!
```
# Copy "Hello World" from `{shiny}`
system.file("examples", "01_hello", package="shiny") |>
fs::dir_copy("myapp", overwrite = TRUE)
# Turn it into a Shinylive app
shinylive::export("myapp", "site")
# Run it
httpuv::runStaticServer("site/")
```
But I can't finish my own app, I know that `shinylive` is still experimental, but I don't know what the problem is, promptly after I search the whole repo.
Here is the [repo](https://github.com/toxintoxin/shiomix)
It fails with the following js console output:
```
load-shinylive-sw.js:37 Service Worker registered
shinylive.js:21554 Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtools
:7446/favicon.ico:1
Failed to load resource: the server responded with a status of 404 (Not Found)
shinylive.js:31930 WebR is using `PostMessage` communication channel, nested R REPLs are not available.
Xs @ shinylive.js:31930
shinylive.js:34938 preload error:wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.
_error @ shinylive.js:34938
shinylive.js:34938 preload error:falling back to ArrayBuffer instantiation
_error @ shinylive.js:34938
shinylive.js:34937 preload echo:
shinylive.js:34937 preload echo:R version 4.3.0 (2023-04-21) -- "Already Tomorrow"
shinylive.js:34937 preload echo:Copyright (C) 2023 The R Foundation for Statistical Computing
shinylive.js:34937 preload echo:Platform: wasm32-unknown-emscripten (32-bit)
shinylive.js:34937 preload echo:
shinylive.js:34937 preload echo:R is free software and comes with ABSOLUTELY NO WARRANTY.
shinylive.js:34937 preload echo:You are welcome to redistribute it under certain conditions.
shinylive.js:34937 preload echo:Type 'license()' or 'licence()' for distribution details.
shinylive.js:34937 preload echo:
shinylive.js:34937 preload echo:R is a collaborative project with many contributors.
shinylive.js:34937 preload echo:Type 'contributors()' for more information and
shinylive.js:34937 preload echo:'citation()' on how to cite R or R packages in publications.
shinylive.js:34937 preload echo:
shinylive.js:34937 preload echo:Type 'demo()' for some demos, 'help()' for on-line help, or
shinylive.js:34937 preload echo:'help.start()' for an HTML browser interface to help.
shinylive.js:34937 preload echo:Type 'q()' to quit R.
shinylive.js:34937 preload echo:
shinylive.js:34938 preload error:Downloading webR package: Rcpp
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: R6
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: fastmap
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: rlang
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: later
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: magrittr
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: promises
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: httpuv
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: mime
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: jsonlite
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: xtable
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: base64enc
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: digest
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: ellipsis
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: htmltools
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: fontawesome
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: sourcetools
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: crayon
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: withr
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: commonmark
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: glue
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: cachem
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: jquerylib
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: cli
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: lifecycle
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: memoise
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: fs
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: rappdirs
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: sass
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: bslib
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: codetools
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: renv
_error @ shinylive.js:34938
shinylive.js:34938 preload error:Downloading webR package: shiny
_error @ shinylive.js:34938
shinylive.js:34794 Robj construction for this JS object is not yet supported
runApp2 @ shinylive.js:34794
```
Could this be related to the version of R and the system, my version of R is 4.3.2 and the OS is win11.
Any advice would be appreciated!!! |
Try the latest version (4.x) for JDK 17 support : https://eclipse.dev/eclipselink/releases/4.0.php |
Has anyone found or created a good SQL provider that implements `IFeatureDefinitionProvider` for the .NET Feature Management?
I've seen some stuff about implementing your own, but I was hoping that by now there would be one available. So far I have been unable to find one. |
.NET Feature Management IFeatureDefinitionProvider SQL provider |
I need to migrate approximately 200,000 customers to Shopify, including their passwords. However, it appears that Magento does not provide this option by default, likely due to security reasons. I have attempted to use the code below, but it is returning an empty string for the password.
use Magento\Framework\App\Bootstrap;
require DIR.'/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Customer Repository
//$singlecustomer = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface')->getById('206991');
$customerCollection = $objectManager - >create('\Magento\Customer\Model\ResourceModel\Customer\Collection');
try {
// Output CSV header
$csvHeader = ['ID', 'First Name', 'Last Name', 'Email', 'Hash', 'Password'];
$outputFile = fopen('customers.csv', 'w');
fputcsv($outputFile, $csvHeader);
// Loop through customers and write to CSV
$i = 1;
$encrypt = $objectManager->create('\Magento\Framework\Encryption\Encryptor');
foreach ($customerCollection as $customer) {
if ($i == 10) {
break;
}
$customerId = $customer->getId();
$customerFirstName = $customer->getFirstname();
$customerLastName = $customer->getLastname();
$customerEmail = $customer->getEmail();
$pass = false;
$hash = $customer->getPasswordHash() ?? '';
$password = '';
if (!empty($hash)) {
$password = $encrypt->decrypt($hash);
}
fputcsv($outputFile, [$customerId, $customerFirstName, $customerLastName, $customerEmail, $hash, $password]);
$i++;
}
fclose($outputFile);
echo "Customer data exported successfully.\n";
} catch (Exception $e) {
echo "Error: ".$e->getMessage()."\n";
}
The code above generates empty passwords because I need plaintext passwords to import them into Shopify. I understand that this may not be possible due to security reasons, but I'm hoping someone more knowledgeable can provide a solution.
|
Issues retrieving Terraform output from remote state in Artifactory terraform-backend repository |
|terraform|artifactory| |
null |
Given an linear system Ax=b, x = [x1; x2], where A,b are given and x1 is also given. A is symmetric. I want to compute the gradient of x1 in terms of A,b, i.e. dx1/dA, dx1/db. It seems that torch.autograd.backward() can only compute the gradient by solving the whole linear system. But I want to make it more efficient by not solving x1 again since it is already given. Is it feasible? If so, how to implement it using pytorch?
For now, I only know how to get the gradient by solving the whole system:
```
#[A1 A2; A3 A4] * [x1; x2] = [b1; b2]
m1 = 10
n1 = 10
m3 = 5
n3 = n1
m2 = m1
n2 = m1 + m3 - n1
m4 = m3
n4 = n2
A = torch.rand((m1+m3,n1+n2))
A1 = A[:m1,:n1]
A2 = A[:m1,n1:]
A3 = A[m1:,:n1]
A4 = A[m1:,n1:]
x1 = torch.ones((n1,1)).clone().detach().requires_grad_(True)
x2_gt = torch.rand((n2,1))
b1 = (A1 @ x1 + A2 @ x2_gt).detach().requires_grad_(True)
b2 = (A3 @ x1 + A4 @ x2_gt).detach().requires_grad_(True)
b = torch.vstack((b1,b2))
x = torch.linalg.solve(A,b)
x.backward(torch.ones(m1+m3,1))
``` |
{"OriginalQuestionIds":[59054548],"Voters":[{"Id":328193,"DisplayName":"David","BindingReason":{"GoldTagBadge":"html"}}]} |
I'm encountering difficulties with my Terraform configuration, utilizing Artifactory's terraform-backend repository as the backend for storing tfstates.
Configuration Overview:
Terraform Backend: **remote: Artifactory | repository type: terraform-backend**
Terraform Version: **1.0.2**
I would greatly appreciate any insights or guidance on how to effectively retrieve Terraform state or output from Artifactory in this specific scenario.
Thank you in advance!
I have explored two potential solutions to retrieve Terraform output from the state:
**1st Solution:** Attempting to obtain the output directly from the remote state.
**Problem:** I haven't found a corresponding Terraform command to achieve this.
**2nd Solution:** Downloading the tfstate from the Artifactory terraform-backend repository locally and executing the command: `terraform output -state=terraform.tfstate output-1`.
**Problem:** Downloading the file state.latest.json directly from the terraform-backend Artifactory results in a file containing state versions, rather than the expected tfstate content containing outputs. |
Insert an additional element in the JSON output |
Try using the following formula:
[![enter image description here][1]][1]
----------
=LET(
_LastRow, COUNTA(L:L),
_FRng, B3:INDEX(B:M,_LastRow,),
_CriteriaRange1, L3:INDEX(L:L,_LastRow),
_CriteriaRange2, M3:INDEX(M:M,_LastRow),
_Output, FILTER(_FRng,(_CriteriaRange1="Dan")*(_CriteriaRange2="Negotiating")),
INDEX(_Output,SEQUENCE(ROWS(_Output)),{1,11,12}))
----------
[1]: https://i.stack.imgur.com/huBIx.png |
I have been converting an existing application into a set OSGI modules along with their innumerable dependencies.
After tracking them all down, creating new bundles out existing jars with `bnd`, I finally have everything loaded into Felix. All of the bundles are activating.
I then created a simple activator that called my MainClass.main static method to see if it would fire up.
Amazingly, it seems to work.
But I'm getting this when my activator is fired.
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
After it prints that, later I get this:
INFO: Registered provider org.slf4j.simple.SimpleServiceProvider of service org.slf4j.spi.SLF4JServiceProvider in bundle slf4j.simple
That means SLF4J is starting, and I know I had to jump through some hoops in install the OSGI plumbing to support SLF4J (Aries service provider support). But, it's starting after my activator is called, and SLF4J doesn't seem to "know" that Simple is installed.
Now, my code is not using any of the OSGI service frameworks logic. At this stage, I'm just using OSGI as an elaborate class loader. My code is just using SLF4J like a normal application, rather than the OSGI Logger system.
I tried adding a ServiceTracker to not start mine up until SLF4J appears as a service, but getting the same result. Likely this is because its one thing to wait for formal OSGI service, but that's quite different from having internal classpaths all configured up. That happens right away, and it's clearly not finding the SLF4J provider. I even changed one of the modules to require the SLF4J provider as an Import-Package, but to no affect.
Edit:
Here is a sample java module, including the Activator and the Service
willh@iMac-2 LogTestOsgi % cat src/main/java/pkg/logtestosgi/Activator.java
package pkg.logtestosgi;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
Logger l = LoggerFactory.getLogger(this.getClass());
public void start(BundleContext context) throws Exception {
context.registerService(MyService.class.getName(), new MyServiceImpl(), null);
System.out.println("Activating myservice");
l.info("activating log info");
}
public void stop(BundleContext context) throws Exception {
System.out.println("deactivating myservice");
l.info("deactivating log info");
}
}
The service interface:
willh@iMac-2 LogTestOsgi % cat src/main/java/pkg/logtestosgi/MyService.java
package pkg.logtestosgi;
public interface MyService {
public void go();
}
And the service:
willh@iMac-2 LogTestOsgi % cat src/main/java/pkg/logtestosgi/MyServiceImpl.java
package pkg.logtestosgi;
public class MyServiceImpl implements MyService {
public void go() {
System.out.println("My Service says hello");
}
}
This is the POM file. Note that it copies all of the required modules into the target/lib directory.
willh@iMac-2 LogTestOsgi % cat pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pkg</groupId>
<artifactId>LogTestOsgi</artifactId>
<version>1.2.3</version>
<packaging>bundle</packaging>
<name>LogTestOsgi OSGi Bundle</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.7</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.aries.spifly</groupId>
<artifactId>org.apache.aries.spifly.dynamic.bundle</artifactId>
<version>1.3.6</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.aries</groupId>
<artifactId>org.apache.aries.util</artifactId>
<version>1.1.3</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-analysis</artifactId>
<version>9.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
<version>9.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-tree</artifactId>
<version>9.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.3.7</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-Activator>pkg.logtestosgi.Activator</Bundle-Activator>
<Export-Package/>
</instructions>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<excludeGroupIds>org.osgi</excludeGroupIds>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
From the project root, here's a simple shell script to move everything into place. It assumes that the Felix installation archive is in my Downloads directory.
willh@iMac-2 LogTestOsgi % cat go.sh
set -x
rm -rf felix-framework-7.0.5
unzip ~/Downloads/org.apache.felix.main.distribution-7.0.5.zip
cp target/lib/* felix-framework-7.0.5/bundle
cp target/LogTestOsgi-1.2.3.jar felix-framework-7.0.5/bundle
It copies all of the modules into the Felix's bundle directory so that they will auto install and start when Felix starts.
Here's the test:
willh@iMac-2 LogTestOsgi % cd felix-framework-7.0.5
willh@iMac-2 felix-framework-7.0.5 % java -jar bin/felix.jar
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.
Activating myservice
Jan 31, 2024 11:41:39 AM org.apache.aries.spifly.BaseActivator log
INFO: Registered provider org.slf4j.simple.SimpleServiceProvider of service org.slf4j.spi.SLF4JServiceProvider in bundle slf4j.simple
____________________________
Welcome to Apache Felix Gogo
g! lb
START LEVEL 1
ID|State |Level|Name
0|Active | 0|System Bundle (7.0.5)|7.0.5
1|Active | 1|LogTestOsgi OSGi Bundle (1.2.3)|1.2.3
2|Active | 1|org.objectweb.asm (9.5.0)|9.5.0
3|Active | 1|org.objectweb.asm.tree.analysis (9.5.0)|9.5.0
4|Active | 1|org.objectweb.asm.commons (9.5.0)|9.5.0
5|Active | 1|org.objectweb.asm.tree (9.5.0)|9.5.0
6|Active | 1|org.objectweb.asm.util (9.5.0)|9.5.0
7|Active | 1|jansi (1.18.0)|1.18.0
8|Active | 1|JLine Bundle (3.13.2)|3.13.2
9|Active | 1|Apache Aries SPI Fly Dynamic Weaving Bundle (1.3.6)|1.3.6
10|Active | 1|Apache Aries Util (1.1.3)|1.1.3
11|Active | 1|Apache Felix Bundle Repository (2.0.10)|2.0.10
12|Active | 1|Apache Felix Gogo Command (1.1.2)|1.1.2
13|Active | 1|Apache Felix Gogo JLine Shell (1.1.8)|1.1.8
14|Active | 1|Apache Felix Gogo Runtime (1.1.4)|1.1.4
15|Active | 1|slf4j-api (2.0.7)|2.0.7
16|Active | 1|slf4j-simple (2.0.7)|2.0.7
All bundles are active and there are no dependency warnings.
The activator is trying to use the SLFJ logger, but this triggers the
`No SLF4J providers were found.` warning. But, SLF4J and SLF4J simple are included in the collection of bundles.
This is not about how to use SLF4J as part of the OSGI Logging Service, this is about getting a legacy module that uses SLF4J internally to have it properly discover a provider (in this case SLF4J-simple).
SLF4J, as I understand it, relies on the Java ServiceLoader framework, which is why the Aries and ASM modules are included (as, to my understanding, these provide the necessary glue for OSGI to work in the ServiceLoader world).
But clearly something is missing.
|
I am trying to get the FB ads through the Graph API using the code below,
$fb = new \Facebook\Facebook([
'app_id' => 'app_id',
'app_secret' => 'app_secret',
'default_graph_version' => 'v19.0',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken instance.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
$params = array(
"access_token" => "accesstokenhere",
"ad_reached_countries" => "US",
"search_terms" => "bags"
);
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/ads_archive',
'accesstokenhere',
array (
'ad_reached_countries' => 'US',
'search_terms' => 'bags',
), );
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
dd($me);
but it gave me `The parameter ad_reached_countries is required`. I tried concatenating the `$params` variable at the end of the GET call but still it gives the same error message. When I also placed `ad_reached_countries` after the `ads_archive`, it gave me `Invalid parameter` error. How would I properly place the `ad_reached_countries` and/or other paramters when searching for ads. Any help is greatly appreciated. Thanks. |
Decrypting Magento 2 customer passwords using email for migration to Shopify |
I have a parent component that retrieves a todo item from a pinia store, based on the current vue router params `/todo/123`, and passes it into a child component as a prop.
The app works properly when navigating to the component using router-links. Except when I refresh the page while I am in a TodoViewComponent page `(localhost:5173/todo/123)`. When I refresh the page, the props are `undefined` initially, hence throwing me an error.
```
Proxy(Object) {todo: undefined}
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')
Proxy(Object) {todo: Proxy(Object)}
```
What would be the solution so that the `SingleTodoComponent` receives the todo prop "instantaneously" upon page reload?
TodoViewComponent (parent):
```javascript
<script setup>
import { useRoute } from 'vue-router'
import { computed } from 'vue';
import SingleTodoComponent from '@/components/SingleTodoComponent.vue';
import { useTodos } from '@/stores/todosStore';
const route = useRoute()
const todosStore = useTodos()
const todo = computed(() => todosStore.todos.find(t => {
return t.id === parseInt(route.params.todoId)
}))
</script>
<template>
<SingleTodoComponent :todo="todo"></SingleTodoComponent>
</template>
```
SingleTodoComponent:
```javascript
<script setup>
const props = defineProps(['todo'])
console.log(props)
const formState = reactive({
id: props.todo.id,
content: props.todo.content_en,
bookmarked: props.todo.bookmarked,
completed: props.todo.completed,
date_deadline: props.todo.date_deadline
})
</script>
``` |
Vue prop is undefined for a moment when page is reloaded |
|vue.js|pinia| |
If you applied above solution and not working, then enable traditional
traditional: true,
Sample Below
url: 'GetOrgs/CourseCatalog',
method: "POST",
traditional: true,
data: {'checkedOrgIds': orgIds},
|
According to the [spec](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension), the `immutable` extension to the `Cache-Control` header:
> Clients SHOULD NOT issue a conditional request during the response’s freshness lifetime (e.g., upon a reload) unless explicitly overridden by the user (e.g., a force reload).
>
> The immutable extension only applies during the freshness lifetime of the stored response. Stale responses SHOULD be revalidated as they normally would be in the absence of the immutable extension.
The freshness of a response is determined by its **age**, which in HTTP is the time elapsed since the response was generated. You can read more about [how a cache calculates the age](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#fresh_and_stale_based_on_age) on MDN, but it is essentially the difference between when the object was stored by the cache and it's `max-age` (or the value of an `Expires` header), which in your case is one year, so any cache following the spec, should not attempt a conditional request to validate the stored object.
I have confirmed on my Ubuntu laptop using Chrome and Firefox that Firefox will not issue a conditional validation request upon caching the response, but Chrome will. If you inspect the [**Browser compatibility**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#browser_compatibility) table on MDN for the `Cache-Control` header, you will see that **Chrome does not support the `immutable` extension, but Firefox does**.
In short, according to the spec, clients _should not_ issue a conditional request to validate a cached object that included the `immutable` extension to a response's `Cache-Control` header while the object is still fresh.
Chrome is not honoring the `immutable` extension, and therefore issuing a conditional request in the form of an `If-None-Match` request header due to the `Etag` on the returned resource. |
supertest mocha Why I get success test passing although expected fails? |
|node.js|mocha.js|chai|supertest| |
I have class `Membership` that represents a many to many relationship and has only 2 routes, DELETE that represents user joining community, and POST that represents the opposite.
Membership entity class:
```php
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use App\Repository\MembershipRepository;
use Doctrine\DBAL\Types\Types;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Link;
use App\State\Persisters\MembershipPersistStateProcessor;
use App\State\Removers\MembershipRemoveStateProcessor;
use App\State\Providers\CommunityStateProvider;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MembershipRepository::class)]
#[ApiResource(
description: "A representation of a single user being a member of 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 member of this subreddit.")]
class Membership
```
As user data is taken out of access token and Community data is passed thought URI variable I have no need for json body.
And...
```php
$response = $client->request('POST', 'api/subreddits/'.$community->getId().'/join', [
'headers' => [
'Content-Type' => 'application/ld+json',
'Authorization' => 'Bearer ' . $token,
],
'json' => [],
]);
```
..look absolutely terrible.
Base on the pull requests I found within API Platform repository([pull][1]) empty requests for POST and PUT should be possible with content-type set to '', yet all configurations I tried only let to more errors. Is there a way to do it?
[1]: https://github.com/api-platform/core/pull/1786 |
Sending empty POST request in Api Platform Symfony Application |
null |
I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view:
```python
def get_product(request, slug):
try:
product = Product.objects.get(slug=slug)
if request.GET.get('size'):
size = request.GET.get('size')
print(size)
return render(request, "core/product_detail.html")
except Exception as e:
print(e)
```
And here's the JavaScript function:
```javascript
function get_correct_price(size) {
console.log(size);
window.location.href = window.location.pathname + `?size=${size}`;
}
```
In my HTML template, I'm calling the JavaScript function with the size parameter:
```html
<button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button>
```
However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console.
Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you! |
Issue Passing Size Parameter from JavaScript to Django Backend |
|javascript|python|html|django|django-views| |
null |
You have only declared the SnackBar and not called the function to show it, for that, do this:
ScaffoldMessenger.of(context).showSnackBar(snackBar); //snackBar is your declared one |
{"Voters":[{"Id":16540390,"DisplayName":"jabaa"},{"Id":1871033,"DisplayName":"CherryDT"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":8017690,"DisplayName":"Yong Shun"},{"Id":272109,"DisplayName":"David Makogon"}]} |
I am building a conferencing application making use of the Livekit SDK for Flutter & Dart. But I am unable to figure out how to setup the *`EGRESS`* functionality of Livekit in Dart.
```
EgressServiceClient client = EgressServiceClient.create(
"http://example.com",
"apiKey",
"secret");
LivekitEgress.EncodedFileOutput output = LivekitEgress.EncodedFileOutput.newBuilder()
.setFileType(LivekitEgress.EncodedFileType.MP4)
.setFilepath("test-recording.mp4")
.setS3(LivekitEgress.S3Upload.newBuilder()
.setAccessKey("access-key")
.setSecret("secret")
.setBucket("bucket")
.setEndpoint("https://my.s3.endpoint")
.build())
.build();
Call<LivekitEgress.EgressInfo> call = client.startRoomCompositeEgress(
"roomName",
output
);
try {
LivekitEgress.EgressInfo egressInfo = call.execute().body();
// handle engress info
} catch (IOException e) {
// handle error
}
```
This is what is mentioned in the documentation of the Livekit.
But I am unable to find any function for the *`EGRESS`* setup like that in dart. I have already added livekit_client in my pubspec.yaml. |
I am attempting to use Microsoft.AspNetCore.TestHost to test routes via TestServer. I believe the WebHost setup I have should be sufficient, however, whenever I run my test, I receive an error message,
```
Test method ID_Test.Controllers.Test_CloudPrintController_RouteTests.AppController_ShouldRouteCorrectly threw exception:
System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (localhost:80) ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.
```
From my understanding, this is either related to firewall issues or incorrect appsettings, but if my appsettings work for all my other non-TestServer tests, and this uses the same Program.cs / Startup.cs, then I feel as if it should work for this as well.
Here is my test Class and the Mock Services I made.
```
public class MockAuthenticationService
{
public async Task SignInAsync(IServiceProvider serviceProvider)
{
// Mock implementation of signing in
// Contents removed for brevity
}
}
public class MockAuthenticationSchemeProvider : IAuthenticationSchemeProvider
{
// Contents removed for brevity
}
public class MockAuthenticationHandler : IAuthenticationHandler
{
// Contents removed for brevity
}
public class MockAuthenticationHandlerProvider : IAuthenticationHandlerProvider
{
// Contents removed for brevity
}
public class MockClaimsTransformation : IClaimsTransformation
{
// Contents removed for brevity
}
public class MockOptionsAuthentication : IOptions<AuthenticationOptions>
{
// Contents removed for brevity
}
[TestClass]
public class Test_CloudPrintController_RouteTests : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
// Register mock implementations
services.AddSingleton<IAuthenticationSchemeProvider, MockAuthenticationSchemeProvider>();
services.AddSingleton<IAuthenticationHandlerProvider, MockAuthenticationHandlerProvider>();
services.AddSingleton<IClaimsTransformation, MockClaimsTransformation>();
services.AddSingleton<IOptions<AuthenticationOptions>, MockOptionsAuthentication>();
services.AddSingleton<MockAuthenticationService>();
// Register AuthenticationService with correct dependencies
services.AddSingleton(sp =>
{
var mockAuthService = sp.GetRequiredService<MockAuthenticationService>();
var mockSchemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
var mockHandlers = sp.GetRequiredService<IAuthenticationHandlerProvider>();
var mockTransform = sp.GetRequiredService<IClaimsTransformation>();
var mockOptions = sp.GetRequiredService<IOptions<AuthenticationOptions>>();
return new AuthenticationService(mockSchemeProvider, mockHandlers, mockTransform, mockOptions);
});
// Add JWT authentication for testing purposes
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false; // In test environment, set to false for simplicity
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false, // Set to false for testing
ValidateAudience = false, // Set to false for testing
ValidateLifetime = false, // Set to false for testing
ValidateIssuerSigningKey = false, // Set to false for testing
// Modify other parameters as needed for testing purposes
};
});
});
}
[TestMethod]
[DoNotParallelize]
public async Task AppController_ShouldRouteCorrectly()
{
// Arrange
HttpClient _client = CreateClient();
var cookieContainer = new CookieContainer();
cookieContainer.Add(_client.BaseAddress, new Cookie("Cookie", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEwMDE5IiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoiaW1leWVyc0B0aGluaXguY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6ImltZXllcnNAdGhpbml4LmNvbSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2dpdmVubmFtZSI6IklzYWFjIE1leWVycyIsImlzbG9ja2Vkb3V0IjoiRmFsc2UiLCJpc2FwcHJvdmVkIjoiVHJ1ZSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6WyIqIiwibWVtYmVyIiwiZGV2ZWxvcGVyIiwic3VwcG9ydCJdLCJuYmYiOjE3MTE0ODg1NDAsImV4cCI6MTcxNDA4MDU0MCwiaXNzIjoiaHR0cDovL2lzdGF0dXMuY29tIiwiYXVkIjoiaHR0cDovL2lzdGF0dXMuY29tIn0.MalKNawXYB0fdfe1644Ut_4rjb1W2QaBw236WVJrHTM"));
var handler = new HttpClientHandler { CookieContainer = cookieContainer };
_client = new HttpClient(handler) { BaseAddress = _client.BaseAddress };
// Simulate authentication by adding mock authentication token/header
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEwMDE5IiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoiaW1leWVyc0B0aGluaXguY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6ImltZXllcnNAdGhpbml4LmNvbSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2dpdmVubmFtZSI6IklzYWFjIE1leWVycyIsImlzbG9ja2Vkb3V0IjoiRmFsc2UiLCJpc2FwcHJvdmVkIjoiVHJ1ZSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6WyIqIiwibWVtYmVyIiwiZGV2ZWxvcGVyIiwic3VwcG9ydCJdLCJuYmYiOjE3MTE0ODg1NDAsImV4cCI6MTcxNDA4MDU0MCwiaXNzIjoiaHR0cDovL2lzdGF0dXMuY29tIiwiYXVkIjoiaHR0cDovL2lzdGF0dXMuY29tIn0.MalKNawXYB0fdfe1644Ut_4rjb1W2QaBw236WVJrHTM");
// Act
var devResponse = await _client.GetAsync("/developer"); // 100 is the test printer node
var response = await _client.GetAsync("/api/subscription-bundles"); // 100 is the test printer node
// Assert
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); // This 404's, presumably cannot reach this endpoint through the test code
}
}
```
Thanks in advance for your help! |
No connection could be made because the target machine actively refused it. (localhost:80) when attempting to test routes with TestServer |
|c#|routes|.net-6.0|mstest|asp.net-core-testhost| |
I have spring boot BE running on port 8080 on my server with nginx and ssl cert.
I have forwarded ports on my router 80 and 443 to the server.
Also i have ddns in no-ip.
This all works correctly.
Now i started developing mobile app with React Native and Expo. When I try to call some endpoint on my BE it works correctly when I open it in web browser. After I try to open it in physical device, only network error is printed.
For example Im trying to show this image: https://prieskumnici-is.ddns.net/api/img/bg/default/day.jpg
or call this endpoint: https://prieskumnici-is.ddns.net/api/api/background
when i load the image in emulator locally it also works (http://192.168.1.35:8080/...)
the endpoints are correct as im using them in my angular webpage
So I assume the problem is in nginx or Spring boot configuration
Also there are no logs in nginx nor Interceptor in BE gets any request
There are som codes:
nginx config
```
http {
client_max_body_size 500M;
server {
listen 443 ssl;
server_name prieskumnici-is.ddns.net localhost;
ssl_certificate C:/nginx/ssl/prieskumnici-is.crt; # Path to your SSL certificate
ssl_certificate_key C:/nginx/ssl/prieskumnici-is.key; # Path to your SSL private key
large_client_header_buffers 4 8096k;
location /api/ {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
root "C:\Users\Singi\Desktop\prieskumnici\prieskumnici-ui\dist\prieskumnici-ui";
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
types {
text/html html htm shtml;
text/css css scss;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js mjs;
application/atom+xml atom;
application/rss+xml rss;
}
}
}
```
RN
```
return <ImageBackground source={{uri: "https://prieskumnici-is.ddns.net/api/img/bg/default/day.jpg"}} resizeMode="cover" style={{height: '100%'}}>
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Home</Text>
</View>
</ImageBackground>
```
I dont know what is relevant from Spring Boot for this issue
To summarize: API and nginx wont recieve request from Physical device with React Native app over internet
I tried to load any other API on the device and it works correctly, also tried to load image from other page and works fine: https://www.prieskumnici.sk/assets/img/banner_zbor.png
**UPDATE** I have configured the nginx to also proxy port 80 to the BE and it works, now i can show image like this:
http://prieskumnici-is.ddns.net/api/img/bg/default/day.jpg
but https doesnt work |
class ItemGetter extends EventEmitter {
constructor () {
super();
this.on('item', item => this.handleItem(item));
}
handleItem (item) {
console.log('Receiving Data: ' + item);
}
getAllItems () {
for (let i = 0; i < 15; i++) {
this
.getItem(i)
.then(item => this.emit('item', item))
.catch(console.error);
}
console.log('=== Loop ended ===')
}
async getItem (item = '') {
console.log('Getting data:', item);
return new Promise((resolve, reject) => {
exec('echo', [item], (error, stdout, stderr) => {
if (error) {
throw error;
}
resolve(item);
});
});
}
}
(new ItemGetter()).getAllItems()
You logic, for first, run loop with calling all GetItem, then output '=== Loop ended ===', and only after that run all promices resolution, so, if you want get result of each getItem execution independently of eachother, just don't abuse asynchronous logic, frequently right solution much simpliest, than it seems ;)
Note: in this solution, you will get the same output, because loop with getItem calling, runnung faster, then promises with exec, but in this case, each item will be handled exactly after appropriate promise will be resolved, except of awaiting of all promises resolution. But in case, when you whant to make method getAllItems, asyncronous too, and await, when all results will be handled, but still remaining each promise running independently, you should implement you own logic, eg, using counter of started getItem methods, which increments in a loop and decrements on each promise resolution, so, this can be not so trivial. From other side, when you starts getItems in a loop sincronuosly, its have a sence to leave using promise.all, and then handle all results also sincronously. |
|php|rest|symfony|http-post|api-platform.com| |
You can store tokens securely in `HttpOnly` cookies.
https://medium.com/@sadnub/simple-and-secure-api-authentication-for-spas-e46bcea592ad
If you worry about long-living Refresh Token. You can skip storing it and not use it at all. Just keep Access Token in memory (JavaScript variable) and do silent sign-in when Access Token expires.
> Don't use `Implicit` flow because it's [obsolete][1].
The most secure way of authentication for SPA is [Authorization Code with PKCE][2].
In general, it's better to use existing libraries based on [oidc-client][3] than building something on your own.
[1]: https://developer.okta.com/blog/2019/05/01/is-the-oauth-implicit-flow-dead
[2]: https://developer.okta.com/blog/2019/08/22/okta-authjs-pkce
[3]: https://github.com/IdentityModel/oidc-client-js/ |
Is there support for non blocking retry functionality for KafkaStreams in Spring Kafka? I see details mentioned in [this link][1] related to setting it up for Kafka Listener.
In case non blocking retry works with Kafka Stream, kindly guide with documentation or example.
[1]: https://%20https://docs.spring.io/spring-kafka/reference/retrytopic/retry-topic-combine-blocking.html |
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<body>
<p id="Num"></p>
<p id="musicTitle"></p>
<button onclick="next()">pipi</button>
<audio controls>
<source id="songSrc" type="audio/mp3">
</audio>
<script>
Num = 1
const maxNum = 2
document.getElementById("Num").innerHTML = Num
song = [{
title: "evil forest",
src: "https://files.catbox.moe/c5zrzm.mp3"
},
{
title: "forest",
src: "https://files.catbox.moe/c5zrzm.mp3"
},
]
let music = document.getElementById("music");
music.src = song[Num - 1].src;
document.getElementById("musicTitle").innerHTML = song[Num - 1].title;
function next() {
if (maxNum > Num) {
Num++
} else {
let Num = 1
}
let music = document.getElementById("music")
music.src = song[songNum - 1].src
document.getElementById("musicTitle").innerHTML = song[Num - 1].title;
document.getElementById("Num").innerHTML = Num
}
</script>
</body>
</html>
<!-- end snippet -->
1) I wanted Num to change as you click the button, but it either doesn't change the variable or doesn't reflect the change in document.getElementById.
2) song title isn't showing even though I made song title variable and made document.getElementById statement. |
VerifyUser.refreshToken = refreshToken;
VerifyUser.save();
res.cookie('access_token',accessToken,{maxAge:1000*60*60*24,secure:true,sameSite:'none'})
res.cookie('jwt',refreshToken ,{httpOnly:true,maxAge:1000*60*60*24,secure:true,sameSite:'none'})
i'm expecting like another way to send cookie like after a time browser will automatic delete those or you know a clean way to send cookie |
LiveKit Flutter/Dart EGRESS support |
|flutter|dart|livekit| |
null |
Try replacing localhost with 127.0.0.1
"proxy": "http://127.0.0.1:2371", |
### To rename your current branch to a new branch name:
git branch -m <new_name>
This will set the new name for the current branch you are working with.
### To rename another branch:
git branch -m <old_name> <new_name>
Here you have to provide the old branch name and the new branch name.
|
The microcontroller throws an error when I'm trying to modify its flash.
[![The error message][1]][1]
The memory looks to be unlocked, here is screenshot of option bytes
[![Option bytes][2]][2]
[![Option bytes][3]][3]
The microcontroller is soldered into a custom board, with power and reset circuit as on the image below.
[![enter image description here][4]][4]
What I've tried:
- Initially, the microcontroller was trying to execute instructions from "outside of program code", 0x1fffxxxx range. It happened randomly, the device managed to startup, call HAL_Init, configure clock. I did some switching back and forth with nBOOT0 and nBOOT1 option bytes, and the device started working fine. I did not understand what was the issue and switched them again to try and reproduce the issue. After that the microcontroller refused to write into flash any more...
- I seem to be able to write into WRP1A_STRT and WRP1B_STRT, though it doesn't seem to unlock the flash. WRP2A_STRT and WRP2B_STRT will switch back to 0x00 if I try to modify them. I suspect it's because the device does not have second bank of memory, so it shouldn't affect the flash protection.
- I watched SWDCLK, SWDIO and power pins with an oscilloscope, they look completely healthy.
Interestingly, CubeProgrammer and ST-Link read different data out of the device. Not sure why, and if it's connected to the issue. The data doesn't change over time though.
[![enter image description here][5]][5]
Please suggest what may be the issue or what else I could check.
[1]: https://i.stack.imgur.com/EE3DS.png
[2]: https://i.stack.imgur.com/GgqMA.png
[3]: https://i.stack.imgur.com/XyVbY.png
[4]: https://i.stack.imgur.com/MwxXZ.png
[5]: https://i.stack.imgur.com/iLpVz.png |
STM32G030 refuses write to flash |
|stm32|microcontroller|cortex-m| |
|c#|.net-core|azure-cosmosdb| |
Exception has occurred.
FlutterError (setState() or markNeedsBuild() called during build.
This _ModalScope<dynamic> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
_ModalScope<dynamic>-[LabeledGlobalKey<_ModalScopeState<dynamic>>#96ae3]
The widget which was currently being built when the offending call was made was:
HaveAccountOrNot)
The code is:
```
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false ,
key: scaffold,
backgroundColor: Color(0xfff8f8f8),
body: SafeArea(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TopTitle(
subsTitle: "Welcome To FoodZone",
title: "Login"),
Center(
child: Container(
height: 200,
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MyTextFormField(title: "Email", controller: email,),
SizedBox(
height: 10,
),
MyPasswordTextFormField(
title: "Password",
controller: password,
),
MyButton(
name: "Login",
onPressed: () {
vaildation();
},
),
HaveAccountOrNot(
onTap: () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (ctx) => SignUp(),
)
);
},
title: "I don't have an Account", subsTitle: "SignUp"
),
],
),
),
),
],
),
)),
);
}
```
|
is there any other way i can send more secure cookie rather than this |
|node.js|mongoose|node-modules| |
null |
I have this code but I don't actually get the email text.
Have I got to decode the email text?
import sys
import imaplib
import getpass
import email
import email.header
from email.header import decode_header
import base64
def read(username, password, sender_of_interest):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.mail.com", 993)
imap.login(username, password)
imap.select('INBOX')
# Use search(), not status()
# Print all unread messages from a certain sender of interest
if sender_of_interest:
status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
else:
status, response = imap.uid('search', None, 'UNSEEN')
if status == 'OK':
unread_msg_nums = response[0].split()
else:
unread_msg_nums = []
data_list = []
for e_id in unread_msg_nums:
data_dict = {}
e_id = e_id.decode('utf-8')
_, response = imap.uid('fetch', e_id, '(RFC822)')
html = response[0][1].decode('utf-8')
email_message = email.message_from_string(html)
data_dict['mail_to'] = email_message['To']
data_dict['mail_subject'] = email_message['Subject']
data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
#data_dict['body'] = email_message.get_payload()[0].get_payload()
data_dict['body'] = email_message.get_payload()
data_list.append(data_dict)
print(data_list)
# Mark them as seen
#for e_id in unread_msg_nums:
#imap.store(e_id, '+FLAGS', '\Seen')
imap.logout()
return data_dict
So I do this:
print('Getting the email text bodiies ... ')
emailData = read(usermail, pw, sender_of_interest)
print('Got the data!')
for key in emailData.keys():
print(key, emailData[key])
The output is:
> mail_to me@mail.com
> mail_subject Get json file
> mail_from ('Pedro Rodriguez', 'pedro@gmail.com')
> body [<email.message.Message object at 0x7f7d9f928df0>, <email.message.Message object at 0x7f7d9f928f70>]
How to actually get the email text?
Tried the suggestion, but it seems it fails as it is multipart, with an attached text file:
def read(username, password, sender_of_interest):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.qq.com", 993)
imap.login(username, password)
imap.select('INBOX')
# Use search(), not status()
# Print all unread messages from a certain sender of interest
if sender_of_interest:
status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
else:
status, response = imap.uid('search', None, 'UNSEEN')
if status == 'OK':
unread_msg_nums = response[0].split()
else:
unread_msg_nums = []
data_list = []
for e_id in unread_msg_nums:
data_dict = {}
e_id = e_id.decode('utf-8')
_, response = imap.uid('fetch', e_id, '(RFC822)')
email_message = email.message_from_bytes(response[0][1], policy=default)
#html = response[0][1].decode('utf-8')
#email_message = email.message_from_string(html)
data_dict['mail_to'] = email_message['To']
data_dict['mail_subject'] = email_message['Subject']
data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
#data_dict['body'] = email_message.get_payload()[0].get_payload()
#data_dict['body'] = email_message.get_payload()[0]
data_dict['body'] = email_message.get_body('html', 'text').get_payload(decode=True)
data_list.append(data_dict)
print(data_list)
# Mark them as seen
#for e_id in unread_msg_nums:
#imap.store(e_id, '+FLAGS', '\Seen')
imap.logout()
return data_dict
Get this error:
> emailData = read(usermail, pw, sender_of_interest) Traceback (most
> recent call last): File "/usr/lib/python3.10/idlelib/run.py", line
> 578, in runcode
> exec(code, self.locals) File "<pyshell#126>", line 1, in <module> File "<pyshell#125>", line 29, in read TypeError:
> MIMEPart.get_body() takes from 1 to 2 positional arguments but 3 were
> given |
There are two problems
In the next() function you are redeclaring Num with let. This creates a new local variable instead of updating the global one. Instead, you should remove the let keyword inside the else block to update the global variable.
```
if (maxNum > Num) {
Num++;
} else {
Num = 1; //this way you update the global num and you don't create a new one
}
```
Second, You're using songNum instead of Num when accessing the song array. I I think it should be Num
``` music.src = song[songNum-1].src ```
should be
``` music.src = song[Num-1].src ```
Hope it helps
|
<head>
<script src="https://js.stripe.com/v3/"></script>
<script src="checkout.js" defer></script>
</head>
<body>
<!-- Display a payment form -->
<form id="payment-form">
<div id="payment-element">
<!--Stripe.js injects the Payment Element-->
</div>
<input type="number" value="50" id="amount1" name="amount1">
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<div id="payment-message" class="hidden"></div>
</form>
checkout.js:
const stripe = Stripe("test_key_here");
const items = [{ id: "55" }];
// Here's the js function
// Fetches a payment intent and captures the client secret
async function initialize() {
const { clientSecret } = await fetch("create.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items }),
}).then((r) => r.json());
elements = stripe.elements({ clientSecret });
const paymentElementOptions = {
layout: "tabs",
};
create.php:
require_once 'autoload.php';
require_once 'secrets.php';
$stripe = new \Stripe\StripeClient($stripeSecretKey);
function calculateOrderAmount($TrueAmount): int {
$TrueAmount = 50;
// If I try to change the amount to a variable $_POST['amount1'] it will error: JSON.parse unexpected character at line 1
return $TrueAmount;
}
// Create a PaymentIntent with amount and currency
$paymentIntent = $stripe->paymentIntents->create([
'amount' => calculateOrderAmount($jsonObj->items),
'currency' => 'usd',
'metadata' => ['order_id' => '1234'],
// In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
'automatic_payment_methods' => [
'enabled' => true,
],
]);
If I set a default amount, it works just fine (50 for example). I'm just a newbie that's looking to capture the value from the input on checkout.html (id = amount1, name=amount1). Whatever value that input is set to is the amount that I would like to charge. Please note, at this point, I'm not worried about sending over any other data, I'd just like to start with this. Thank you much! |
How do I set a dynamic amount for Stripe's PaymentIntent? |
Creating a column by finding its corresponding value in a colname |
|r|dplyr| |
I have a big dataset of several thounds of persons. Each person has several treatment periods indicated by a separate row, where I have id, startdate, enddate and dose for each period. If 2 subsequent treatment periods are separated by more than 7 days, then they are separated by a third row indicating also startdate and enddate of the break and dose=0. However, if the break between 2 periods is less than 7 days, there is no such row.
Problem: What I want to do, is: for every person where there are 2 or more periods after each other with less than 7 days between, to merge them together to 1 continuous period. It is important that the peirods have same id AND same dose, as adjasent periods with different doses should not be merged togther altough the break between them is less than 7 days.
Here you see an example of my dataset:
```
library(data.table)
d=data.frame(id=c(1,1,1,1,1,1,1,2,2,2,2,2,2),
inn=as.Date(c("2017-09-11", "2017-12-21", "2018-03-19", "2018-06-27", "2019-01-15", "2019-04-29", "2019-11-20",
"2019-02-06","2019-04-07","2019-05-14","2019-07-13","2019-07-23","2019-09-25")),
out=as.Date(c("2017-12-21","2018-03-19", "2018-06-27", "2019-01-15", "2019-04-25", "2019-11-15", "2021-07-10",
"2019-04-07","2019-05-14","2019-07-13","2019-07-23","2019-09-21","2021-05-14")),
dose=c("20","0","20","0", "20", "20","20","2.5","0","2.5","0","2.5","2.5"))
setDT(d)
```
The result I wish is:
```
e=data.frame(id=c(1,1,1,1,1,2,2,2,2,2),
inn=as.Date(c("2017-09-11", "2017-12-21", "2018-03-19", "2018-06-27", "2019-01-15",
"2019-02-06","2019-04-07","2019-05-14","2019-07-13","2019-07-23")),
out=as.Date(c("2017-12-21","2018-03-19", "2018-06-27", "2019-01-15","2021-07-10",
"2019-04-07","2019-05-14","2019-07-13","2019-07-23","2021-05-14")),
dose=c("20","0","20","0", "20","2.5","0","2.5","0","2.5"))
```
I have tried to use "ifelse", but it gives error if there are more than 2 adjasent periods that should be merge together. I guess I need to create a kind of a "loop", but I cant figure it out..
I would appreciate any help.. |
Creating a loop to adjust dates/periods? |
|loops| |
null |
The most semantic way to make a background image accessible is to use both a background image and a regular `img` tag as well.
1. Place the `img` within the element with the background image.
2. Visually hide the `img` so that sighted users just see the background image behind it, but users with assistive technologies are still presented the `img`.
Note: just setting the image to `display: none;` will hide also it from assistive technologies, which isn't the goal. A different approach is needed.
If you're using Bootstrap, it has a handy built-in class for doing just this: `.sr-only`. If you're not, you can add the styles for that class to your own stylesheet:
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
Applying this technique to the example above looks like this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
article {
position: relative;
width: 320px;
margin: 5rem auto;
}
figure {
width: 100%;
height: 180px;
/* not accessible */
background-image: url('http://www.fillmurray.com/300/300');
background-size: cover;
background-position: center;
}
<!-- language: lang-html -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<article class="panel panel-default">
<header class="panel-heading">
<h4 class="panel-title">Title of Article</h4>
</header>
<div class="panel-body">
<figure class="article-image">
<!-- include the img tag but visually hide it with .sr-only -->
<img class="sr-only" alt="Bill Murray" src="http://www.fillmurray.com/300/300" />
</figure>
</div>
<footer class="panel-footer">
<a class="btn btn-default" href="#">Read</a>
</footer>
</article>
<!-- end snippet -->
**Edit:** The [object-fit property](https://css-tricks.com/almanac/properties/o/object-fit/) eliminates the need for the background image, but at the time of writing this property is not fully supported in IE or Edge.
|
The simple fix: the TXT file had an misspelling in the name, so I fixed it and it worked fine after that. |