instruction stringlengths 0 30k ⌀ |
|---|
No matter what I do on the pages nothing is shown. Even if I write "hello" on my index.html page it will not show it. The server only shows what I pulled from github a week ago. Nothing, no change. I added the sentry logging tool, it takes zero notice, I copied pasted the logging snippet used and it completely ignores it. I write an extra word on the menu bar at the top, nothing is shown.
I tried this to remove the cache, no effect
sudo apt-get autoclean
sudo apt-get autoremove
on the menu bar, I added an "x" here and it is not shown! This is insane! About usx
<a href="#" class="nav-item nav-link">{% blocktrans %}About usxc {% endblocktrans %}</a>
I am using gunicorn, nginx and supervisor for django. I have reloaded gninx but it makes no difference. I just can't believe that a simple "hello" hard written on my index.html page won't show. |
{"Voters":[{"Id":529282,"DisplayName":"Martheen"},{"Id":3306020,"DisplayName":"Magnas"},{"Id":256196,"DisplayName":"Bohemian"}]} |
{"Voters":[{"Id":529282,"DisplayName":"Martheen"},{"Id":3306020,"DisplayName":"Magnas"},{"Id":256196,"DisplayName":"Bohemian"}],"SiteSpecificCloseReasonIds":[]} |
I'm trying to move non sensitive data from Azure Government Cloud to Public cloud. I read through links and understood AAD auth works for cross tenant access. I couldn't find anything on the cross cloud access. Is it possible for an application running in Government cloud to access public cloud resource using AAD? |
Azure Cross Cloud Auth using AAD |
|azure-active-directory|azure-authentication|azure-identity|azure-gov|azure-entra-id| |
|python|python-3.x|list|numpy| |
The accepted [answer][1] saved me a ton of time
I tested out with Swift 5 + Xcode 15, here's how how you write it in Swift
```swift
class BorderlessWindow: NSWindow {
override var canBecomeKey: Bool {
return true
}
override var canBecomeMain: Bool {
return true
}
}
```
Also, I find that `canBecomeMain` is not necessary. `canBecomeKey` alone is enough to solve the problem.
[1]: https://stackoverflow.com/a/11638926/2142577 |
{"Voters":[{"Id":62576,"DisplayName":"Ken White"},{"Id":9517769,"DisplayName":"Amira Bedhiafi"},{"Id":6463558,"DisplayName":"Lin Du"}]} |
{"Voters":[{"Id":62576,"DisplayName":"Ken White"},{"Id":857132,"DisplayName":"John3136"},{"Id":6463558,"DisplayName":"Lin Du"}]} |
{"Voters":[{"Id":8565438,"DisplayName":"zabop"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":6463558,"DisplayName":"Lin Du"}]} |
Be sure to select/click **Read all** in the *STM32CubeProgrammer*. By default, it reads (downloads) only the first 0x400 bytes from the µC, which is indicated in the *Size* box in the GUI. |
You should use @keydown with @change, and wrap the api call function with setTimeout - for debounce. And trigger your api call for every event you want together! |
{"Voters":[{"Id":584183,"DisplayName":"jmcilhinney"},{"Id":982149,"DisplayName":"Fildor"},{"Id":5394572,"DisplayName":"madreflection"}],"SiteSpecificCloseReasonIds":[16]} |
The issue lies in the form action. Since you're updating a student record, the form action should point to the update method in your StudentController, not the edit method. The correct action for the form should be students.update route instead of students.edit. |
I guess it's `struct lock_t` in lock0priv.h file. |
The issue lies in the form action. Since you're updating a student record, the form action should point to the update method in your StudentController, not the edit method. The correct action for the form should be **students.update** route instead of students.edit. |
It’s not possible to take text and translate it into a convenient format |
Thank you for the help in advance.
I am using Spring boot webflux 3 with Spring doc Open API 2.4
Here is my response entity records
```
public record UserResponse(
Integer id,
String name,
ScoreResponse scoreSummary
){
}
```
```
public record ScoreResponse(
Integer avgScore,
List<Score> score
){
public record Score(
Integer scoreId,
Integer score
){
}
}
```
Here is the handler class
```
@Component
@RequiredArgsConstructor
public class UserHandler {
private final UserService userService;
private final UserMapper userMapper;
private final ClientAuthorizer clientAuthorizer;
@Bean
@RouterOperations({
@RouterOperation(
path = "/user/{userId}",
produces = {MediaType.APPLICATION_JSON_VALUE},
method = RequestMethod.GET,
beanClass = UserHandler.class,
beanMethod = "getById",
operation = @Operation(
description = "GET user by id", operationId = "getById", tags = "users",
responses = @ApiResponse(
responseCode = "200",
description = "Successful GET operation",
content = @Content(
schema = @Schema(
implementation = UserResponse.class
)
)
),
parameters = {
@Parameter(in = ParameterIn.PATH,name = "userId")
}
)
)
})
public @NonNull RouterFunction<ServerResponse> userIdRoutes() {
return RouterFunctions.nest(RequestPredicates.path("/user/{userId}"),
RouterFunctions.route()
.GET("", this::getById)
.build());
}
@NonNull
Mono<ServerResponse> getById(@NonNull ServerRequest request) {
String userId = request.pathVariable("userId");
return authorize(request.method(), request.requestPath())
.then(userService.getUserWithScore(userId))
.map(userMapper::toResponseWithScores)
.flatMap(result -> ServerResponse.ok().body(Mono.just(result), UserResponse.class))
.switchIfEmpty(Mono.error(new ResourceNotFoundException("userId:%s does not exist".formatted(userId))))
.doOnEach(serverResponseSignal -> LoggingHelper.addHttpStatusToContext(serverResponseSignal, HttpStatus.OK))
.contextWrite(context -> LoggingHelper.addUserServiceContextValues(context, "/user", userId, null));
}
private Mono<AuthenticatedPrincipal> authorize(HttpMethod httpMethod, RequestPath requestPath) {
return ReactiveSecurityContextHolder.getSecurityContext().flatMap(authenticationDetail -> {
// Retrieve AuthorizationDetail from the context
boolean isAuthorized = clientAuthorizer.authorizeByPath(authenticationDetail.permissions(), httpMethod, requestPath);
if (isAuthorized) {
return Mono.just(authenticationDetail);
} else {
return Mono.error(new ResourceAccessNotPermittedException());
}
});
}
}
```
The expected example in Swagger UI is
```
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
{
"scoreId": 1073741824,
"score": 1073741824
}
]
}
}
```
But actual example is
```
{
"id": 1073741824,
"name": "string",
"scoreSummary": {
"avgScore": 1073741824,
"score": [
"string"
]
}
}
```
Additionally I can see an error in the UI
```
Errors
Resolver error at responses.200.content.application/json.schema.$ref
Could not resolve reference: JSON Pointer evaluation failed while evaluating token "score" against an ObjectElement
```
Please help me to find what I am missing.
After days of research I found this and it worked and I got expected result. But I need ro understand is there any better approach or is this fine.
Added below bean definition in my handler class.
```
@Bean
public OpenApiCustomizer schemaCustomizer() {
ResolvedSchema resolvedSchema = ModelConverters.getInstance()
.resolveAsResolvedSchema(new AnnotatedType(Score.class));
return openApi -> openApi
.schema(resolvedSchema.schema.getName(), resolvedSchema.schema);
}
``` |
You can attempt to do it and see if it works out successfully.
<ClaimsProvider>
<Domain>commonaad</Domain>
<DisplayName>Common AAD</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="AADCommon-OpenIdConnect">
<Metadata>
<!-- ... -->
<Item Key="scope">openid profile email</Item>
</Metadata>
<OutputClaims>
<!-- ...other output -->
<!-- Add OutputClaim -->
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="preferred_username" />
</OutputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
|
For me all i had to do was to pod install because i switched to a different git branch that had different pods configuration |
Here is the producer code:
```js
import * as amqp from "amqplib";
export default class Producer {
channel;
async createChannel() {
const connection = await amqp.connect("amqp://localhost");
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
console.log("called");
await this.createChannel();
}
const exchangeName = "loggerEx";
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(`The new ${routingKey} log is sent to exchange ${exchangeName}`);
}
}
```
Here is how I am using `Producer` class:
```js
import Producer from "./producer.js";
const producer = new Producer();
producer.publishMessage("info", "somemessage");
producer.publishMessage("info", "somemessage");
```
In RabbitMQ management UI, I see two connections:
[![enter image description here][1]][1]
In `Producer` class I am checking for the existence of the channel.
```js
if (!this.channel) {
console.log("called");
await this.createChannel();
}
```
then why connection is being created multiple times.
[1]: https://i.stack.imgur.com/GqYYh.png |
RabbitMQ creating multiple connections |
|node.js|rabbitmq|amqp|node-amqplib| |
|excel|excel-formula|wps| |
|javascript|css|frontend|backend| |
While on the transaction in parallel situation, prisma throw error like that message
so i wanna know why it error occured, and how to resolove it,
ERROR MESSAGE
```
[Nest] 43187 - 2024. 03. 17. 오후 4:14:56 ERROR [ExceptionsHandler] Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
PrismaClientKnownRequestError: Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
at xt.transaction (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:111:12322)
at Proxy._transactionWithCallback (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:127:9568)
at AccountService.recharge (/src/src/account/charge.service.ts:34:5)
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-execution-context.js:46:28
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-proxy.js:9:17
```
TEST CODE
```
const willChargeAmount = Array.from({ length: 20 }, () =>
randomIntByRange(1000, 5000),
);
console.log(willChargeAmount);
console.log('-------------------------------------------------');
const responses = await Promise.all(
willChargeAmount.map((amount) =>
request(app.getHttpServer())
.post(`/users/${foundUser?.user_id}/recharge`)
.set('Authorization', `Bearer ${jwt}`)
.send({ amount }),
),
);
console.log('-------------------------------------------------');
```
charge.service.ts
```
public async recharge(rechargeRequest: chrageDatas) {
await this.accountRepository.recharge(rechargeRequest);
}
```
accountRepository.ts
```
public async recharge(
rechargeRequest: chrageDatas,
) {
return this.prismaService.prisma.$transaction(async (tx) => {
const amounts = await tx.accounts.findMany({
where: {
AND: [
{ user_id: rechargeRequest.user.userId }
],
},
});
const points = amounts.filter(
(amount) => amount.type === PERMANENT,
);
if (points.length >= 1) {
return tx.accounts.update({
where: {
account_id: points[0].account_id,
},
data: {
amount: rechargeRequest.amount,
},
});
}
return tx.accounts.create({
data: {
users: {
connect: {
user_id: rechargeRequest.user.userId,
},
},
type: PERMANENT,
amount: rechargeRequest.amount,
},
});
});
}
```
i'm expection nothing error occured, and finish transcation successfully |
I'm connecting to Postgres Database using psycopg2 connector and using cursor property, i'm fetching the records along with their column names. Here is the code snippet of the same:
rds_conn = psycopg2.connect(
host=config.RDS_HOST_NAME,
database=config.RDS_DB_NAME,
user=config.RDS_DB_USER,
password=config.RDS_DB_PASSWORD,
port=config.RDS_PORT)
cur = rds_conn.cursor()
cur.execute(sql_query)
names = [x[0] for x in cur.description]
rows = cur.fetchall()
cur.close()
I'm initialising a Pandas dataframe with column names from the `cursor.description` property:
df = pd.DataFrame(rows, columns=names)
Instead of Pandas dataframe, if i would like to initialise a Polars dataframe with column names from the cursor.description property, how would i do it? I don't want to convert Pandas to Polars dataframe.
I tried using `polars.Dataframe.with_Columns` property but it didn't work.
Can someone please help me on this?
|
How to initialise a polars dataframe with column names from database cursor description? |
|python|pandas|dataframe|python-polars|rust-polars| |
### UPDATE
Use [`::marker` pseudo-element][1]. See [@RobertKegel answer below][2].
***
### Legacy answer
<sub>*Based on [@dzimney answer][3] and similar to [@Crisman answer][4] (but different)*</sub>
That answer is good but has **indention issue** (bullets appear **inside of `li` scope**). Probably you don't want this. See simple example list below (this is a default HTML list):
- *Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.*
- *Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.*
But if you use the mentioned answer the list will be like below (ignoring the size of the bullets):
• <del>*Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.*</del>
• <del>*Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.*</del>
***
**So I recommend this approach that resolves the issue:**
<!-- language: lang-css -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
li {
list-style-type: none;
position: relative; /* It's needed for setting position to absolute in the next rule. */
}
li::before {
content: '■';
position: absolute;
left: -0.8em; /* Adjust this value so that it appears where you want. */
font-size: 1.1em; /* Adjust this value so that it appears what size you want. */
}
<!-- language: lang-html -->
<ul>
<li>Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.</li>
<li>Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.</li>
</ul>
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Web/CSS/::marker
[2]: https://stackoverflow.com/a/70928342/5318303
[3]: https://stackoverflow.com/a/34570803/5318303
[4]: https://stackoverflow.com/a/38164530/5318303 |
|python|pytorch|macos-ventura|amd-gpu| |
I want to open a URL via Chrome to fill in data and hit a submit button, using Excel VBA.
I wrote the command to open the URL.
How do I key in the data and submit the form?
My Code starts as
```vba
Sub OpenHyperlinkInChrome()
Dim chromeFileLocation As String
Dim hyperlink As String
hyperlink = "<URL OVER HERE>"
chromeFileLocation = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromeFileLocation & "-url " & hyperlink)
driver.FindElementByName("trackingId").Value = "123"
driver.FindElementByID("epm-submit-button-announce").Click
End Sub
```
I get a syntax error on `driver.FindElementByName`.
My field HTML code:
<!-- language: lang-html -->
<input type="text" placeholder="Example: BLUE_SHOES_08. This information is for your tracking purposes." name="trackingId" class="a-input-text a-span12">
The button HTML code reads as
<!-- language: lang-html -->
<span id="epm-submit-button-announce" class="a-button-text a-text-center" aria-hidden="true">
Submit
</span>
How can I fill the form and submitting? |
Fill data and click on button on Chrome browser after opening URL |
null |
I want to open a URL via Chrome to fill in data and hit a submit button, using Excel VBA.
I wrote the command to open the URL.
How do I key in the data and submit the form?
My code:
```vba
Sub OpenHyperlinkInChrome()
Dim chromeFileLocation As String
Dim hyperlink As String
hyperlink = "<URL OVER HERE>"
chromeFileLocation = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromeFileLocation & "-url " & hyperlink)
driver.FindElementByName("trackingId").Value = "123"
driver.FindElementByID("epm-submit-button-announce").Click
End Sub
```
I get a syntax error on `driver.FindElementByName`.
My field HTML code:
<!-- language: lang-html -->
<input type="text" placeholder="Example: BLUE_SHOES_08. This information is for your tracking purposes." name="trackingId" class="a-input-text a-span12">
The button HTML code reads as
<!-- language: lang-html -->
<span id="epm-submit-button-announce" class="a-button-text a-text-center" aria-hidden="true">
Submit
</span>
How can I fill the form and submit? |
You'd need to type-erase the deferred async operations. Or write out the entire composed operation so the internal type discrepancies don't leak out to `co_composed`.
Both aren't without overhead, so perhaps you might flip the visitation inside out so the composed operation is never variant to begin with:
template <typename Connection, typename CompletionToken> auto non_awaitable_func_impl(Connection& con, CompletionToken&& token) {
return asio::async_initiate<CompletionToken, Sig>(
asio::experimental::co_composed<Sig>([](auto state, Connection& con) -> void {
auto [ec] = co_await con.send(as_tuple(asio::deferred));
co_yield state.complete(ec);
}),
token, con);
}
template <typename CompletionToken> auto non_awaitable_func(connection& con, CompletionToken&& token) {
std::visit(
[&token](auto& con) { return non_awaitable_func_impl(con, std::forward<CompletionToken>(token)); },
con);
}
This works. You can combine the two if you don't mind readability:
template <typename CompletionToken> auto non_awaitable_func(connection& con, CompletionToken&& token) {
return std::visit(
[&token](auto& con) {
return asio::async_initiate<CompletionToken, Sig>(
asio::experimental::co_composed<Sig>([&con](auto state) -> void {
auto [ec] = co_await con.send(as_tuple(asio::deferred));
co_yield state.complete(ec);
}),
token);
},
con);
}
See it **[Live On Coliru](https://coliru.stacked-crooked.com/a/12346f9a8a2cc25f)** (or [Godbolt](https://godbolt.org/z/Tx5vvcM63))
```c++
#include <chrono>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/experimental/co_composed.hpp>
using namespace std::chrono_literals;
namespace asio = boost::asio;
using error_code = boost::system::error_code;
using Sig = void(error_code);
struct tcp {
template <asio::completion_token_for<Sig> Token> auto send(Token&& token) {
// pseudo implementation
auto tim = std::make_unique<asio::steady_timer>(exe_, 1s);
return tim->async_wait(consign(std::forward<Token>(token), std::move(tim)));
}
asio::any_io_executor exe_;
};
struct tls {
template <asio::completion_token_for<Sig> Token> auto send(Token&& token) {
return dispatch( // pseudo implementation
append(std::forward<Token>(token), make_error_code(boost::system::errc::bad_message)));
}
asio::any_io_executor exe_;
};
using connection = std::variant<tcp, tls>;
template <asio::completion_token_for<Sig> Token> auto non_awaitable_func(connection& con, Token&& token) {
return std::visit(
[&token](auto& con) {
return asio::async_initiate<Token, Sig>(
asio::experimental::co_composed<Sig>([&con](auto state) -> void {
auto [ec] = co_await con.send(as_tuple(asio::deferred));
co_return state.complete(ec);
}),
token);
},
con);
}
int main() {
asio::io_context ioc;
connection
con1 = tls{ioc.get_executor()},
con2 = tcp{ioc.get_executor()};
non_awaitable_func(con1, [&](error_code ec) { std::cout << "cb1:" << ec.message() << std::endl; });
non_awaitable_func(con2, [&](error_code ec) { std::cout << "cb2:" << ec.message() << std::endl; });
ioc.run();
}
```
Note that it is important to let ADL find the correct `make_error_code` overload.
Prints:
cb1:Bad message
cb2:Success
## UPDATE: Promise!
I had a brainwave. Another experimental type, `asio::experimental::promise<>` which, like `std::promise`, apparently does some type erasure internally, yet, unlike `std::future` also can be `await`-transformed in Asio coroutines.
And indeed it works:
template <asio::completion_token_for<Sig> Token> //
auto async_send(connection& con, Token&& token) {
return asio::async_initiate<Token, Sig>(
boost::asio::experimental::co_composed<Sig>([&con](auto /*state*/) -> void {
auto [ec] = co_await std::visit(
[](auto& c) { return c.send(asio::as_tuple(asio::experimental::use_promise)); }, con);
co_return {ec};
}),
token);
}
Here's a way more complete test program:
**[Live On Coliru](https://coliru.stacked-crooked.com/a/7d0be2c3d4ba00d1)** or [Godbolt](https://godbolt.org/z/ofo189Kxz)
```c++
#include <boost/asio.hpp>
#include <boost/asio/experimental/co_composed.hpp>
#include <boost/asio/experimental/promise.hpp>
#include <boost/asio/experimental/use_coro.hpp>
#include <boost/asio/experimental/use_promise.hpp>
#include <boost/core/demangle.hpp>
#include <chrono>
#include <iostream>
#include <syncstream>
using namespace std::chrono_literals;
namespace asio = boost::asio;
using error_code = boost::system::error_code;
using Sig = void(error_code);
static inline auto out() { return std::osyncstream(std::clog); }
struct tcp {
template <asio::completion_token_for<Sig> Token> //
auto send(Token&& token) {
// pseudo implementation
auto tim = std::make_unique<asio::steady_timer>(exe_, 1s);
return tim->async_wait(consign(std::forward<Token>(token), std::move(tim)));
}
asio::any_io_executor exe_;
};
struct tls {
template <asio::completion_token_for<Sig> Token> //
auto send(Token&& token) {
return dispatch( // pseudo implementation
append(std::forward<Token>(token), make_error_code(boost::system::errc::bad_message)));
}
asio::any_io_executor exe_;
};
using connection = std::variant<tcp, tls>;
template <asio::completion_token_for<Sig> Token> //
auto async_send(connection& con, Token&& token) {
return asio::async_initiate<Token, Sig>(
boost::asio::experimental::co_composed<Sig>([&con](auto /*state*/) -> void {
auto [ec] = co_await std::visit(
[](auto& c) { return c.send(asio::as_tuple(asio::experimental::use_promise)); }, con);
co_return {ec};
}),
token);
}
template <class V> // HT: https://stackoverflow.com/a/53697591/85371
std::type_info const& var_type(V const& v) {
return std::visit([](auto&& x) -> decltype(auto) { return typeid(x); }, v);
}
int main() {
asio::thread_pool ioc(1);
connection
con1 = tls{ioc.get_executor()},
con2 = tcp{ioc.get_executor()};
{ // callback
async_send(con1, [&](error_code ec) { out() << "cb1:" << ec.message() << std::endl; });
async_send(con2, [&](error_code ec) { out() << "cb2:" << ec.message() << std::endl; });
}
{ // use_future
auto f1 = async_send(con1, as_tuple(asio::use_future));
auto f2 = async_send(con2, as_tuple(asio::use_future));
out() << "f1: " << std::get<0>(f1.get()).message() << std::endl;
out() << "f2: " << std::get<0>(f2.get()).message() << std::endl;
try {
async_send(con1, asio::use_future).get();
} catch (boost::system::system_error const& se) {
out() << "alternatively: " << se.code().message() << std::endl;
}
}
{ // use_awaitable
for (connection& con : {std::ref(con1), std::ref(con2)}) {
auto name = "coro-" + boost::core::demangle(var_type(con).name());
co_spawn(
ioc,
[&con, name]() -> asio::awaitable<void> {
auto [ec_defer] = co_await async_send(con, as_tuple(asio::deferred));
auto [ec_aw] = co_await async_send(con, as_tuple(asio::use_awaitable));
out() << name << ": " << ec_defer.message() << "/" << ec_aw.message() << std::endl;
co_await async_send(con, asio::deferred); // will throw
},
[name](std::exception_ptr e) {
try {
if (e)
std::rethrow_exception(e);
} catch (boost::system::system_error const& se) {
out() << name << " threw " << se.code().message() << std::endl;
}
});
}
}
ioc.join();
}
```
Printing e.g.
cb1:Bad message
f1: Bad message
cb2:Success
f2: Success
alternatively: Bad message
coro-tls: Bad message/Bad message
coro-tls threw Bad message
coro-tcp: Success/Success |
The difference in *character columns* when using the default `na.strings=` argument in `read.csv` and `na=` argument in `read_csv` is in empty fields. Try the code below where the second field on the last row is empty.
The reason for the difference is that by default `na.strings="NA"` in `read.csv` so empty fields result in zero length strings whereas in `read_csv` the default is `na=c("", "NA")` so empty fields result in an `NA` (not a NULL).
cat("A,B,C\na,b,c\nd,,e\n", file = "test.csv")
readr::read_csv("test.csv")
## ... snip ...
# A tibble: 2 × 3
A B C
<chr> <chr> <chr>
1 a b c
2 d <NA> e
read.csv("test.csv")
## A B C
## 1 a b c
## 2 d e
|
You could try this approach using a helper `struct FontModel` to
hold the font results and make it easier to use in the `ForEach` loop.
struct ContentView: View {
var body: some View {
AddFontStyleItems(DrawModel(curFont: "Helvetica"))
}
}
// for testing
struct DrawModel {
var curFont: String
}
struct FontModel: Identifiable { // <--- here
let id = UUID()
var fontType: String
var fontName: String
var fontWeight: Int
var fontTrait: Int
init(_ arr: [Any]) {
if arr.count < 5 {
self.fontType = arr[0] as? String ?? ""
self.fontName = arr[1] as? String ?? ""
self.fontWeight = arr[2] as? Int ?? 0
self.fontTrait = arr[3] as? Int ?? 0
} else {
self.fontType = ""
self.fontName = ""
self.fontWeight = 0
self.fontTrait = 0
}
}
}
struct AddFontStyleItems: View {
var dm: DrawModel
@State private var fontStyles: [FontModel] = [] // <--- here
init(_ dm: DrawModel) { self.dm = dm }
var body: some View {
ForEach(fontStyles) { curStyle in // <--- here
Button(curStyle.fontName) {
print("---> Style: \(curStyle)")
}
}
.onAppear {
fontStyles = getFontStyles(for: dm.curFont) // <--- here
}
}
func getFontStyles(for fontFamily: String) -> [FontModel] {
var results: [FontModel] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
results.append(FontModel(member))
}
}
return results
}
}
EDIT-1:
if just want an array of Strings
struct AddFontStyleItems: View {
var dm: DrawModel
@State private var fontStyles: [String] = [] // <--- here
init(_ dm: DrawModel) { self.dm = dm }
var body: some View {
ForEach(fontStyles, id: \.self) { curStyle in // <--- here
Button(curStyle) {
print("---> Style: \(curStyle)")
}
}
.onAppear {
fontStyles = getFontStyles(for: dm.curFont) // <--- here
}
.onChange(of: dm.curFont) { // <--- here
fontStyles = getFontStyles(for: dm.curFont)
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
Or simply:
struct AddFontStyleItems: View {
var dm: DrawModel
var body: some View {
VStack {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
print("---> dm: \(dm) Style: \(curStyle)")
}
}
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
EDIT-2:
Here is my full test code that shows, changing the `curFont` of the `drawModel` in the parent view,
changes the `AddFontStyleItems` view displaying the Font Styles. Tested on MacOS 14.4.
struct ContentView: View {
@State private var drawModel = DrawModel(curFont: "Helvetica") // <--- here
var body: some View {
VStack {
Button("Change curFont") {
drawModel.curFont = "Times" // <--- here
}.padding(20)
Divider()
Text(drawModel.curFont).foregroundStyle(.red)
Divider()
AddFontStyleItems(dm: drawModel)
Spacer()
}
}
}
struct AddFontStyleItems: View {
var dm: DrawModel
var body: some View {
VStack {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
print("---> dm: \(dm) Style: \(curStyle)")
}
}
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
struct DrawModel: Identifiable {
let id = UUID()
var curFont: String
}
EDIT-3:
try this approach to `select` the `font` and the `style` for your `DrawModel`.
Example code:
struct ContentView: View {
@State private var drawModel = DrawModel(curFont: "", curStyle: "") // <--- here
var body: some View {
VStack {
Text(drawModel.curFont).foregroundStyle(.red)
Text(drawModel.curStyle).foregroundStyle(.blue)
Divider()
AddFontItems(dm: $drawModel) // <--- here $
Spacer()
}
}
}
struct AddFontItems: View {
@Binding var dm: DrawModel // <--- here
var uniqueFontFamilies = NSFontManager.shared.availableFontFamilies //.unique()
var body: some View {
HStack {
ScrollView {
ForEach(uniqueFontFamilies, id: \.self) { curFont in
Button(curFont) {
dm.curFont = curFont
print("---> curFont: \(curFont)")
}
}
}
Spacer()
ScrollView {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
dm.curStyle = curStyle
print("Set Style:\t \(curStyle)")
}
}
}
}
}
func getFontStyles(for font: String) -> [String] {
var justStyles: [String] = []
if let fontInfo = NSFontManager.shared.availableMembers(ofFontFamily: font ) {
for curFontInfo in fontInfo {
if curFontInfo.count > 1 {
justStyles.append(curFontInfo[1] as? String ?? "")
}
}
}
return justStyles
}
}
struct DrawModel: Identifiable {
let id = UUID()
var curFont: String
var curStyle: String
}
|
I asked to this question to:
I found the solution at [github][1].
[1]: https://github.com/aquasecurity/trivy/discussions/6305 |
|php|mysql|database| |
null |
The [handle class](https://www.mathworks.com/help/matlab/handle-classes.html) and its copy-by-reference behavior is the natural way to implement linkage in Matlab.
It is, however, possible to implement a linked list in Matlab without OOP. And an abstract list which does *not* splice an existing array in the middle to insert a new element -- as complained in [this comment](https://stackoverflow.com/questions/1413860/matlab-linked-list#comment23877880_1422443).
(Although I do have to use a Matlab data type somehow, and adding new element to an existing Matlab array requires memory allocation somewhere.)
The reason of this availability is that we can model linkage in ways other than pointer/reference. The reason is *not* [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) with [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html).
I will nevertheless use closure to encapsulate a few *persistent* variables. At the end, I will include an example to show that closure alone confers no linkage. And so [this answer](https://stackoverflow.com/a/1421186/3181104) as written is incorrect.
At the end of the day, linked list in Matlab is only an academic exercise. Matlab, aside from aforementioned handler class and classes inheriting from it (called subclasses in Matlab), is purely copy-by-value. Matlab will optimize and automate how copying works under the hood. It will avoid deep copy whenever it can. That is probably the better take-away for OP's question.
The absence of reference in its core functionality is also why linked list is not obvious to make in Matlab.
-------------
##### Example Matlab linked list:
```lang-matlab
function headNode = makeLinkedList(value)
% value is the value of the initial node
% for simplicity, we will require initial node; and won't implement insert before head node
% for the purpose of this example, we accommodate only double as value
% we will also limit max list size to 2^31-1 as opposed to the usual 2^48 in Matlab vectors
m_id2ind=containers.Map('KeyType','int32','ValueType','int32'); % pre R2022b, faster to split than to array value
m_idNext=containers.Map('KeyType','int32','ValueType','int32');
%if exist('value','var') && ~isempty(value)
m_data=value; % stores value for all nodes
m_id2ind(1)=1;
m_idNext(1)=0; % 0 denotes no next node
m_id=1; % id of head node
m_endId=1;
%else
% m_data=double.empty;
% % not implemented
%end
headNode = struct('value',value,...
'next',@next,...
'head',struct.empty,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',m_id);
function nextNode=next(node)
if m_idNext(node.id)==0
warning('There is no next node.')
nextNode=struct.empty;
else
nextNode=makeNode(m_idNext(node.id));
end
end
function node=makeNode(id)
if isKey(m_id2ind,id)
node=struct('value',id2val(id),...
'next',@next,...
'head',headNode,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',id);
else
warning('No such node!')
node=struct.empty;
end
end
function temp=id2val(id)
temp=m_data(m_id2ind(id));
end
function addEnd(value)
addAfter(value,m_endId);
end
function addAfter(value,id)
m_data(end+1)=value;
temp=numel(m_data);% new id will be new list length
if (id==m_endId)
m_idNext(temp)=0;
else
m_idNext(temp)=temp+1;
end
m_id2ind(temp)=temp;
m_idNext(id)=temp;
m_endId=temp;
end
function deleteAt(id)
end
end
```
With the above .m file, the following runs:
```lang-matlab
>> clear all % remember to clear all before making new lists
>> headNode = makeLinkedList(1);
>> node2=headNode.next(headNode);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> headNode.push_back(2);
>> headNode.push_back(3);
>> node2=headNode.next(headNode);
>> node3=node2.next(node2);
>> node3=node3.next(node3);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> node0=node2.head;
>> node2=node0.next(node0);
>> node2.value
ans =
2
>> node3=node2.next(node2);
>> node3.value
ans =
3
```
`.next()` in the above can take any valid node `struct` -- not limited to itself. Similarly, `.push_back()` etc can be done from any node. But what relative node to get next node from needs to be passed in because a non-OOP [`struct`](https://www.mathworks.com/help/matlab/ref/struct.html) in Matlab cannot reference itself implicitly and automatically. It does not have a `this` pointer or `self` reference.
In the above example, nodes are given unique IDs, a dictionary is used to map ID to data (index) and to map ID to next ID. (With pre-R2022 `containers.Map()`, it's more efficient to have 2 dictionaries even though we have the same key and same value type across the two.) So when inserting new node, we simply need to update the relevant next ID. (Double) array was chosen to store the node values (which are doubles) and that is the data type Matlab is designed to work with and be efficient at. As long as no new allocation is required to append an element, insertion is constant time. Matlab automates the management of memory allocation. Since we are not doing array operations on the underlying array, Matlab is unlikely to take extra step to make copies of new contiguous arrays every time there is a resize. [Cell array](https://www.mathworks.com/help/matlab/ref/cell.html) may incur less re-allocation but with some trade-offs.
Since [dictionary](https://www.mathworks.com/help/matlab/ref/dictionary.html) is used, I am not sure if this solution qualifies as purely [functional](https://en.wikipedia.org/wiki/Functional_programming).
------------
##### re: closure vs linkage
In short, closure does not confer linkage. Matlab's nested functions have access to variables in parent functions directly -- as long as they are not shadowed by local variables of the same names. But there is no variable passing. And thus there is no pass-by-reference. And thus we can't model linkage with this non-existent referencing.
I did take advantage of closure above to make a few variables persistent and shared, since scope (called [workspace](https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html) in Matlab) being referred to means all variables in the scope will persist. That said, Matlab also has a [persistent](https://www.mathworks.com/help/matlab/ref/persistent.html) specifier. Closure is not the only way.
To showcase this distinction, the example below will not work because every time there is passing of `previousNode`, `nextNode`, they are passed-by-value. There is no way to access the original `struct` across function boundaries. And thus, even with nested function and closure, there is no linkage!
```lang-matlab
function newNode = SOtest01(value,previousNode,nextNode)
if ~exist('previousNode','var') || isempty(previousNode)
i_prev=m_prev();
else
i_prev=previousNode;
end
if ~exist('nextNode','var') || isempty(nextNode)
i_next=m_next();
else
i_next=nextNode;
end
newNode=struct('value',m_value(),...
'prev',i_prev,...
'next',i_next);
function out=m_value
out=value;
end
function out=m_prev
out=previousNode;
end
function out=m_next
out=nextNode;
end
end
``` |
I have written a code, when the image button is clicked in Activity1, the webview must be opened in Activity2 with the respective link address which have been provided as a string. When I ran the below code It showed no error in the console, but when I clicked the image button the app was closing. it failed to get to activity 2. Can somebody help me to overcome this issue?
Mainactivity.java
package com.example.gptapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private ImageButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openLinkInBrowser(View view) {
button=findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendData();
}
});
}
public void sendData(){
String url = "https://youtube.com";
Intent intent = new Intent(MainActivity.this,Activitylink.class);
intent.putExtra(Activitylink.website,url);
startActivity(intent);
}
}
Activity 2
package com.example.gptapp;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.appcompat.app.AppCompatActivity;
public class Activitylink extends AppCompatActivity {
private BroadcastReceiver MyReceiver = null;
public static String website;
private String websiteURL;// sets web url
public WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitylink);
Intent intent = getIntent();
websiteURL = intent.getStringExtra(website);
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
}
}
Activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageButton
android:id="@+id/imageButton"
android:layout_width="222dp"
android:layout_height="307dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/finalpic"
android:onClick="openLinkInBrowser"/>
</androidx.constraintlayout.widget.ConstraintLayout> |
Not sure another ways but I have to have a login step.
##### Main function
fun MacrobenchmarkScope.startBenchmark() {
pressHome()
startActivityAndWait()
loginByPhone()
// After login, do another steps
}
##### Login function
fun MacrobenchmarkScope.loginByPhone() {
waitAndClickElement("phoneLoginButton")
setTextFieldValue("phoneNumberTextField", "1222223333")
// Send OPT Next button
waitAndClickElement("sendOTPButton")
setTextFieldValue("smsVerifyTextField", "123456")
// SMS verify Next button
waitAndClickElement("verifyOTPButton")
}
##### Some helpers
fun MacrobenchmarkScope.waitAndClickElement(res: String) {
val btnSelector = By.res(res)
device.wait(Until.hasObject(btnSelector), 5000)
val buttonObject = device.findObject(btnSelector)
if (buttonObject == null) {
Log.e("waitAndClickElement", "error at res=$res")
}
buttonObject.click()
}
fun MacrobenchmarkScope.setTextFieldValue(res: String, value: String) {
val textFieldSelector = By.res(res)
device.wait(Until.hasObject(textFieldSelector), 5_500)
val textFieldObject = device.findObject(textFieldSelector)
if (textFieldObject == null) {
Log.e("setTextFieldValue", "error at res=$res")
}
textFieldObject.text = value
}
Hope this help someone! |
You can follow the procedure below to get the required format:
Here is a sample JSON, which is the JSON format of a data frame:
{"id":2,"name":"Alice","properties":{"age":"25","gender":"Female"}}
{"id":1,"name":"John","properties":{"age":"30","gender":"Male"}}
Read the JSON and flatten its structure in your Spark Data Frame, use the `select` function along with the `alias` function to rename the properties as required. Use the following code:
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, struct
json_df = spark.read.json("<jsonPath>/data.json")
flattened_df = json_df.select(
col("id"),
col("name"),
col("properties.age").alias("age"),
col("properties.gender").alias("gender")
)
To see the flattened JSON, use the code below:
json_string = flattened_df.toJSON().collect()
# Print JSON string
for row in json_string:
print(row)
**Output:**
{"id":2,"name":"Alice","age":"25","gender":"Female"}
{"id":1,"name":"John","age":"30","gender":"Male"}
Write the DataFrame into JSON format using the following code:
flattened_df.write.option("header", "false").mode("overwrite").json("<jsonPath>/data.json") |
null |
I am a bit confused and I am not very familliar with CSS/JS.
I try to dynamically add an "input" field to my form in order to add an author of a document.
Adding the field technically works as it takes a text and upload it in the database.
Yet the added "input" field with jQuery does not take the CSS properties of the webpage. The field 1 should look like the field 0.
[![CSS Issue][1]][1]
I checked in the web dev tool and indeed the css elements are different for the two input fields.
[![<inpu> comparison][2]][2]
Although the classes are identical to the two input fields, the applied css is different.
So that's why i am confused. There must be something else managing the css of the input field so I guess the parent with pseudo-element maybe. Moreover I read [here][3] that JS cannot work with pseudo-element or that we have to use other ways.
Sorry If I ask a stupid question but is my issue really with pseudo-elements ? And if yes, is it possible to update the styling with the newly added element or is my issue completely different than I think ?
[1]: https://i.stack.imgur.com/X1mnT.png
[2]: https://i.stack.imgur.com/JtiRx.png
[3]: https://stackoverflow.com/questions/17788990/access-the-css-after-selector-with-jquery |
This is my code ,
It basically ususe an esp8266, max30100 and an oled display .
The max30100 is used to detect the spo2 and hear beat of the person and shows the output in the oled display and also has an inbuilt local webserver in which the output will be shown.
This was working properly before a month but now the esp connects to the wifi and disconnect again and again. What could be the issue here ?
```
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#define REPORTING_PERIOD_MS 1000
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
float BPM, SpO2;
uint32_t tsLastReport = 0;
PulseOximeter pox;
const char *ssid = "Testing";
const char *password = "zxcvbnm";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;)
;
}
// Initialize MAX30100 sensor
Serial.print("Initializing Pulse Oximeter..");
if (!pox.begin()) {
Serial.println("FAILED");
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("FAILED");
display.display();
for (;;)
;
} else {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("SUCCESS");
display.display();
Serial.println("SUCCESS");
}
// Web Server Routes
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
// Generate HTML response
pox.update();
float bpm = pox.getHeartRate();
float spo2 = pox.getSpO2();
// Check if readings are valid
bool validReading = isValidReading(bpm, spo2);
String html = "<!DOCTYPE html>
**HTML CODE GOES HERE**
if (validReading) {
html += "<div class='data BPM'><i class='fas fa-heartbeat icon'></i><div class='reading' id='BPM'>" + String(bpm) + "<span class='superscript'>BPM</span></div></div><div class='data SpO2'><i class='fas fa-lungs icon'></i><div class='reading' id='SpO2'>" + String(spo2) + "<span class='superscript'>%</span></div></div>";
} else {
html += "<div class='data invalid'><p>Invalid readings. Wear your band properly.</p></div>";
}
html += "</body></html>";
request->send(200, "text/html", html);
});
server.on("/data", HTTP_GET, [](AsyncWebServerRequest *request) {
// Retrieve latest sensor data
pox.update();
float bpm = pox.getHeartRate();
float spo2 = pox.getSpO2();
// Create a JSON response
String json = "{\"bpm\":" + String(bpm) + ",\"spo2\":" + String(spo2) + "}";
request->send(200, "application/json", json);
});
server.begin();
}
void loop() {
// Update sensor data
pox.update();
BPM = pox.getHeartRate();
SpO2 = pox.getSpO2();
if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
// Update display
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
if (isValidReading(BPM, SpO2)) {
display.setCursor(0, 16);
display.println("BPM: " + String(BPM) + " BPM");
display.setCursor(0, 30);
display.println("SpO2: " + String(SpO2) + "%");
} else {
display.setCursor(0, 16);
display.println("Invalid readings. Wear your band properly");
}
display.display();
tsLastReport = millis();
}
}
bool isValidReading(float bpm, float spo2) {
return (bpm > 50 && spo2 > 90 && bpm < 150 && spo2 <= 100);
}
```
**
I've tried a lot of changes to the program and the connection in the Arduino ide too but still i cant sort out the issue.
Can someone sort the issue or suggest me any changes in the program.** |
Wifi disconnects and connects again and again while using esp8266, max30100 and oled display |
|arduino|esp8266|arduino-ide|arduino-esp8266| |
null |
i want to develop a AutoCAD plugin with c#.And I creat a custom class by objectarx,after compilation produce a .dbx and .lib file ,but c# use .dll file, i don't know how to use this custom class with .
Begin,i tried to use hybrid programming, but immediately I realised that is was illogical,and also i couldn't find a similar example like this. |
for (int i = 0; i < chickens; ++i)
{
Console.Write("Eggs:");
egg_ = Convert.ToInt32(Console.ReadLine());
}
// I want the code to prompt the user with the writeline statement equal to the number of chickens i.e. chickens = 4, Console.Write("Eggs:") 4 times.
//Ive tried while loop and if statements but couldn't figure it out. |
Having issues iterating a statement, C# |
|c#| |
I posted the question below, but none of the answers I was pointed to worked, though they look like they should.
I activated (again) the virtualenv. It still tells me that pip can't be found by apt when doing an 'apt install' command. But here is where I am now, and very confused.
I pointed my directory to "/home/.../q7root/bin/pip" and did an "ls". It shows a sub-directory with pip in it (or, I think, a link to it - I'm not the best at Unix). When I type "which pip" I get the path to this point ('q7root/pip'). bit if I just type "pip" at the CLI I get I get this error:

I have looked at my PATH, and this q7root/bin is the first place to look on the path. And, despite trying mightily with all the references people gave me, pip3 never gets installed.
But even pip is challenged. "which pip" points to this copy in the virtual environment site, but typing "pip" as a command tells me 'No module named pip.'
So pip seems to need more stuff installed (?), or there is some mess. Any advice?
**Original Question:**
*At the suggestion of others working on what was a functional Django project, I upgraded to a more recent version of Ubuntu (18).
However, when I first try to run it it blows up at line 3 of the initial script module when asked to import django as a package.
I tried `pip -r requirements.txt`, but the system said pip was an unknown package. I dropped down and used apt to load pip onto my machine (`sudo apt-get pip`), then tried using pip itself (`pip update pip`) which failed.:

I also tried `pip install django`, and got this:

I would have thought an OS upgrade would not require re-installing all currently installed packages (seems like a no-brainer to do the work of installing everything that had been installed). But right now I am terribly stuck...obviously, having 'pip' let's you (at least) have a basic CLI tool.
Any advice? |
Opening webview when the image button is clicked |
|java|xml|android-studio| |
null |
|php|laravel|validation| |
null |
Trying to attach a function to the method `attachPropertyChange` on the [sap.ui.model.odata.v4.ODataModel][1]
onAfterRendering: function () {
var oModel = this.getView().getModel(); //based on sap.ui.model.odata.v4.ODataModel
oModel.attachPropertyChange(() => console.log("hello"));
}
in the console it appears:
[![enter image description here][2]][2]
Has the event `PropertyChange` been deprecated on `sap.ui.model.odata.v4.ODataModel`?
The model is defined in `manifest.json` file and it has the version 4.0
"dataSources": {
"mainService": {
"uri": "/sap/opu/odata4/sap/ui_sensitivefielditem/srvd/sap/ui_sensitivefielditem/0001/",
"type": "OData",
"settings": {
"annotations": [
"annotation"
],
"localUri": "localService/metadata.xml",
"odataVersion": "4.0"
}
},
"annotation": {
"type": "ODataAnnotation",
"uri": "annotations/annotation.xml",
"settings": {
"localUri": "annotations/annotation.xml"
}
}
}
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "com.swisslife.vimsensitivefielditem.i18n.i18n"
}
},
"": {
"dataSource": "mainService",
"preload": true,
"settings": {
"synchronizationMode": "None",
"operationMode": "Server",
"autoExpandSelect": true,
"earlyRequests": true
}
},
[1]: https://sapui5.hana.ondemand.com/sdk/#/api/sap.ui.model.odata.v4.ODataModel%23methods/Summary
[2]: https://i.stack.imgur.com/vEGQG.png |
I have a project to monitorize some parameters with ESP32 (Arduino IDE sketch) and I save result into a gsheets. Every new day gerenate new sheet to save dates. After new sheet creation, I want to insert into sheet a line chart with 3 series using requests addChart. With one serie is ok, but is more explicit evolution of 3 parameters so when I define 3 series in json I receive next error.
"error": {
"code": 400,
"message": "Invalid requests[0].addChart: If specifying more than one sourceRange within a domain or series, each sourceRange across the domain & series must be in order and contiguous.",
"status": "INVALID_ARGUMENT"
Succint what I try:
domain sources: A1:A1000 (time of event) on axis x
series1 sources: B1:B1000 (values of parameter A)
series2 sources: C1:C1000 (values of parameter B)
series2 sources: D1:D1000 (values of parameter C)
Using [https://developers.google.com/sheets/api/samples/charts](https://developers.google.com/sheets/api/samples/charts) this is result.
```
`
{
"requests": [
{
"addChart": {
"chart": {
"spec": {
"basicChart": {
"chartType": "LINE",
"domains": {
"domain": {
"sourceRange": {
"sources": [
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
}
]
}
}
},
"series": {
"series": {
"sourceRange": {
"sources": [
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 5,
"endColumnIndex": 6,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 6,
"endColumnIndex": 7,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 7,
"endColumnIndex": 8,
"sheetId": 1439439696
}
]
}
}
}
}
},
"position": {
"overlayPosition": {
"anchorCell": {
"sheetId": 1439439696,
"rowIndex": 2,
"columnIndex": 2
}
}
}
}
}
}
}`
```
What I'm wrong?
What I expected:
[enter image description here][1]
[1]: https://i.stack.imgur.com/j4m8Q.jpg |
CSS not applied to an "input" field added by jQuery within a Symfony 6 form |
|javascript|jquery|forms|symfony6| |
My application is not running on a virtual device after I press the Run button, I get the message [Execution finished](https://i.stack.imgur.com/EIdAo.jpg). The Project is correctly [building](https://i.stack.imgur.com/k9fqx.jpg) and I don't get any error message in logcat.
I've deleted all the virtual devices and created a new one wich is working well because I can load it in the device manager. I've also checked the [Run configurations](https://i.stack.imgur.com/AoW8h.jpg) tab and it seems to be ok.
This is my Android [tree structure](https://i.stack.imgur.com/mAAbc.jpg)
Here my Manifest and gradle files
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.DeviworksApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:screenOrientation="sensorLandscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.2.2' apply false
id ("com.google.devtools.ksp") version "1.9.0-1.0.12" apply false
}
plugins {
id 'com.android.application'
id 'com.google.devtools.ksp'
}
android {
namespace 'com.deviworksapp'
compileSdk 34
defaultConfig {
applicationId "com.deviworksapp"
minSdk 21
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dataBinding{
enabled=true
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
def room_version = "2.6.1"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
// To use Kotlin annotation processing tool (kapt)
ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
// optional - Test helpers
testImplementation("androidx.room:room-testing:$room_version")
// optional - Paging 3 Integration
implementation("androidx.room:room-paging:$room_version")
}
```
|
With Apache Jena, you can:
- List the URIs of all imported ontologies `model.listImportedOntologyURIs()`
- List all the classes of an imported ontology `model.getImportedModel(uri).listClasses()`
You can then write a method to check if an `OntClass` comes from an imported `OntModel`:
public boolean isFromImportedOntology(OntClass ontClass, OntModel ontModel) {
for (String uri : ontModel.listImportedOntologyURIs()) {
Set<OntClass> importedClasses = ontModel.getImportedModel(uri).listClasses().toSet();
if (importedClasses.contains(ontClass)) {
return true;
}
}
return false;
}
Note: Thanks to UninformedUser for base ideas. |
The method written by the friend above is also correct, but I wrote a nice function for you. You can trigger this function (button click, onFieldSubmitted and onEditingComplete in the textformfield, or click anywhere on the page) or close the keyboard when it is clicked. functional
void removeFocus(final BuildContext context) {
final FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
If you have a problem with dir, you can get rid of this error if you scroll the Filter page design. For example, if you wrap the Filter Page with the SingleChildScrollView class, this problem will disappear. |
I have an issue with node fs.unlink
I have a function that writes files to disk storage extracts data from the these files then deletes the files
```js
const parseShpFile = async ({
cpgFile,
dbfFile,
prjFile,
qmdFile,
shpFile,
shxFile,
}) => {
// saving binary files to local machine
const dbfPath = await saveBinaryToLocalMachine(dbfFile);
const shpPath = await saveBinaryToLocalMachine(shpFile);
//reading files from local machine using shapefile
const shpParsedData = await shapefile
.open(shpPath, dbfPath)
.then((src) => src.read())
.then(async (data) => {
await deleteFilesFromLocal([shpPath, dbfPath]);
return data;
})
.catch((e) => {
console.log("Error", e);
});
return shpParsedData;
};
```
the delete function is
```js
const deleteFilesFromLocal = async (filePaths) => {
for (const filePath of filePaths) {
try {
await fsP.unlink(path.resolve(filePath), console.log);
} catch (e) {
console.log("error in deleting file", filePath);
}
}
return;
};
```
the write function is
```js
const saveBinaryToLocalMachine = async (binaryFile) => {
const name = binaryFile.name.split("/")[2];
const binary = await binaryFile.async("nodebuffer");
const writePath = path.resolve(`./db/tmp/${name}`);
try {
await fsP.writeFile(writePath, binary);
console.log("file saved");
return writePath;
} catch (e) {
console.log(e);
}
};
```
The issue is when I run this code the files are not removed from the desk until the server restarts or shutdowns.
Before server restart or shutdown
[![enter image description here][1]][1]
After the server restarted.
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/2shE3.png
[2]: https://i.stack.imgur.com/GRxkJ.png |
## Authenticate is not a use-case
First of all, `authenticate` is not really a use-case. You already know it, but many readers of this answer do not and I feel compelled to clarify:
- From the use-case analysis point of view, it's not a goal for the user. No user would buy a system just to authenticate. It's just a constraint necessary for certain behaviours to complete.
- From the strict UML point of view, a use-case
> specifies a set of behaviors performed by that subject, which yields an **observable result** that is **of value** for Actors or other stakeholders
But performing authentication may not necessarily be observable (for example if the authentication is performed via single sign on capability behind the scene) and the user may not value the result of the authentication, but only the value of the other use cases for which authentication is a constraint.
* There is no order defined for use-cases. Use cases are not meant to describe workflow, whereas both of your diagrams expect an order. (By the way, I assume that in the second diagram, `User` should also be associated with `authenticate`)
Last but not least, more and more, authentication is no longer performed in the system but by an external system that is identity provider, and in this case it may even be behind the scene without the user knowing - one proof more that it's not a set of behavior performed in interaction with the user ;-) .
## What diagram alternative is more suitable
I strongly disagree with your professor: the first alternative is not the recommended one, because it's a functional decomposition of your use-cases. While this is not forbidden in UML, it is seen as bad practice by leading authors such as [Bittner & Spence][1].
The second one is more elegant in this regard, as your actor specialisation (which is fully legit) allows to see what an authenticated user can do and what a non-authenticated user can do. The only flaw is the `authenticate` use-case. But if you'd remove it, it would still be correct and express your design intention. How the authentication is managed, is then a technical or a user-interface detail.
Some side-remarks:
- if you'd insist on keeping `authenticate`, then add at least an association with `User`
- you do not need the redundant association between `navigate products` and `Authenticated user`, because this association is inherited from `User` (all what a user can do, the authenticated user can do as well)
- you should remove the arrows from the associations between actors and use-cases. This old notation is no longer valid (even if you'll find many examples of it on the internet and in books, refers to the UML 2.5.1 specifications in case of doubt).
## A better way?
Use your second, diagram, but remove the `authenticate` use-case which is not one.
The authentication should either be a constraint, or some action to be performed (perhaps conditionally, e.g. if user is already authenticated). This action would be a part of the activity diagram that describes the details behind a use-case.
[1]: https://books.google.com/books/about/Use_Case_Modeling.html?id=zvxfXvEcQjUC&redir_esc=y |
null |
{"Voters":[{"Id":21588212,"DisplayName":"DileeprajnarayanThumula"}],"DeleteType":1} |
{"Voters":[{"Id":23528,"DisplayName":"Daniel A. White"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":6463558,"DisplayName":"Lin Du"}]} |
Ensure that the Material icon stylesheet is included in the index.html, if not you need to add it manually.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
I am getting the below java exception for API which i am triggering from eclipse,
JAVA Version : 1.8
IDE : Eclipse
Exception :"javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"
Pre Condition : It is a 3rd party tool which we use and To login this URL we need to login ZScaler and then basic auth will call.
Tried Below thing,
1) Install jdk 1.8 and configured java home path to jdk 1.8
2) Eclipse-Project Run Configuration : Java Build Path set to jdk 1.8
3) Added root cert to cacerts using keystore ["C:\Program Files\Java\jre8\lib\security\cacerts"]
4) re stared my system and ran again
To import Cert used below command
"keytool -importcert -file location_of_cert -alias cd12 -keystore "C:\Program Files\Java\jre8\lib\security\cacerts"
---------------------------------------------------------------------------
Just for Ref, I am trying below code in rest assured, but getting above exception,
RestAssured.proxy("ipaddress", portno);
//RestAssured.useRelaxedHTTPSValidation("TLSv1.2");
RestAssured
.given()
.auth().basic("username", "Pwd")
.contentType(ContentType.JSON)
//.baseUri("https://apiURL")
.when()
.get()
.then()
.assertThat()
//.body(null, null, null)
.statusCode(200);
|
I would like to mutate a column in a dataframe, based off a column in another dataframe (similar to the XLOOKUP() function in Excel) in R.
So I have this dataframe (df):
```
orientatie jaar token
1 gay 1991 эхо
2 gay 1991 татарстане
3 gay 1991 донесшийся
4 gay 1991 менска
5 gay 1991 ответной
...
100000 gay 2020 клич
100001 gay 2020 гей
100002 gay 2020 славяне
100003 gay 2020 вызвал
100004 gay 2020 многонациональной
100005 gay 2020 республике
100006 gay 2020 ответного
```
And this dataframe (df2)
```
token lemma
1 ответному ответный
2 ответного ответный
3 ответным ответный
4 ответном ответный
5 ответной ответный
...
3000000 1-му 1-й
3000001 1-ого 1-й
3000002 1-ое 1-й
3000003 1-ой 1-й
3000004 1-ом 1-й
3000005 1-ому 1-й
```
How can I mutate the data in token column in df into the data from column lemma in df2 based off their token column counterpart?
This is the result that I expect:
```
orientatie jaar lemma
5 gay 1991 ответный
...
100006 gay 2020 ответный
```
I have tried to use the join function:
```
df_gelemmatiseerd <- df %>%
inner_join(df2, by = "token", relationship = "many-to-many")
```
But it retrieved me funky result.
Your help is appreciated, thank you! |
I have been working on a classifier for a few days on Azure Auto ML and when I tried disabling some variables that I do not need, I encountered the below error.
I have never encountered this type of error before. Even after creating a new dataset with just the variables I am interested in, the error persists. I need help to resolve this issue. Thank you
The only SQL code that you will on my Data sets on Auto ML is SELECT * FROM my_table and it works since I can see the data on Azure ML studio. Plus I only started to have this error yesterday and I do not know why.
Encountered error while fetching data.
```Error:
Error Code: ScriptExecution.Database.Unexpected
Native Error: Dataflow visit error: ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 }))))))
VisitError(ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 })))))))
=> Failed with execution error: An error occur when executing database query.
ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 }))))))
Error Message: Database execution failed with "SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))". "Ok(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 })))"| session_id=af8ac40c-2ffe-410f-8ecb-70e45405ef78
```
Thank you
I just swicthed off some of the variables that my model does not need. So I would just create a new version of that data set with less variables that I could use for a new version of the model, which is something I have been constantly doing for the last couple of weeks.
I created a new dataset containing just the variables I need but I get the same error. Now I seem to be getting the same error always, no matter what I do. |
null |
In my case I needed the checkbox to get the checked state only via an Input property and not via a mouse click. In an Angular app this did the trick:
<input [checked]="someCondition" (click)="$event.preventDefault()"> |
|php|wordpress|woocommerce| |
null |
Counterintuitive approach to above problem. Mine was a three step build.
1. Package front end code
2. Then create symlinks from the compiled frontend code to my backend code
3. Backend code is a maven packaging plugin which packaged all the code from itself and the symlinks to a jar (final product)
The symlink code was working fine for mac and linux properly and not for windows. So i used the resource tag which points directly to the code package by frontend dropping the symlink tag. |
There are several ways to [Check out multiple repositories in your pipeline - Azure Pipelines | Microsoft Learn](https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/multi-repo-checkout?view=azure-devops) and we don't need to add headers. Here is a sample for your reference.
Please note that, if you would use `git clone` command in a script to checkout a **non-self** repo (`RepoC` in my sample) in a YAML pipeline, please don't forget to disable `Protect access to repositories in YAML pipelines`.
[![enter image description here][1]][1]
```
pool:
vmImage: windows-latest
resources:
repositories:
- repository: A
name: RepoA
type: git
steps:
- checkout: self # TestRepo
- checkout: A
path: RepoA
displayName: Checkout RepoA
- checkout: git://$(TheProjectName)/RepoB
path: RepoB
displayName: Checkout RepoB
- powershell: |
Write-Host "Agent.BuildDirectory - $(Agent.BuildDirectory)"
git clone https://$(AzureDevOpsOrgName):$(System.AccessToken)@dev.azure.com/$(AzureDevOpsOrgName)/$(TheProjectName)/_git/RepoC
tree /F /A
displayName: Checkout RepoC
workingDirectory: $(Agent.BuildDirectory)
```
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/Vh8lt.png
[2]: https://i.stack.imgur.com/dPnuc.png |
i am getting io.UnsupportedOperation: fileno error in
@app.route('/view_pdf/<unique_id>', methods=['POST', 'GET'])
def view_pdf(unique_id):
unique_id = request.form['unique_id']
award_data = request.form.get('award_data')
# Map the selected data type to the corresponding table name
table_mapping = {
'10th_data': '10th_students',
'12th_data': '12th_students',
'tr_data': 'teacher',
'pr_data': 'principal',
'scl_data': 'school'
}
if award_data in table_mapping:
table_name = table_mapping[award_data]
# Fetch all data from the corresponding table
cur = db.engine.connect()
query = f"SELECT * FROM `{table_name}` WHERE id LIKE %s"
result = cur.execute(query, (unique_id,))
user_data = result.fetchall()
cur.close()
if user_data:
# Generate image
image_buffer = generate_filled_image(user_data)
# Generate PDF
pdf_buffer = generate_pdf_buffer(image_buffer)
# Serve PDF for viewing in browser
response = make_response(send_file(pdf_buffer, mimetype='application/pdf'))
response.headers['Content-Disposition'] = 'inline; filename={unique_id}.pdf'
return response
else:
return "User not found for the provided ID."
def generate_filled_image(user_data):
# Load the existing JPG image template
existing_image_path = 'certificate_template.jpg'
existing_image = Image.open(existing_image_path)
# Use the provided code for text insertion
font_type = ImageFont.truetype('static/Arima-Bold.ttf', 130)
draw = ImageDraw.Draw(existing_image)
draw.text(xy=(800, 1200), text=f"{user_data[0][1]}",
fill=(255, 69, 0), font=font_type)
# Save the new image to a BytesIO buffer
image_buffer = BytesIO()
existing_image.save(image_buffer, format='JPEG')
image_buffer.seek(0)
return image_buffer
def generate_pdf_buffer(image_buffer):
# Create a temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(image_buffer.read())
try:
# Open the temporary file with PIL Image
image_data = Image.open(temp_file.name)
# Create a BytesIO buffer to save the PDF
pdf_buffer = BytesIO()
# Create a PDF canvas
pdf_canvas = canvas.Canvas(pdf_buffer, pagesize=letter)
# Draw the image onto the PDF canvas
pdf_canvas.drawInlineImage(image_data, 0, 0)
# Save the PDF canvas to the BytesIO buffer
pdf_canvas.save()
# Move the buffer cursor to the beginning
pdf_buffer.seek(0)
return pdf_buffer
finally:
# Close and delete the temporary file
temp_file.close()
os.unlink(temp_file.name)
i was expecting to print something on a jpg and download in pdf |
Mutating a column XLOOKUP function in R? |
|r|dataframe|mutate|lemmatization|xlookup| |
null |
I want to capture the full page screenshot from figma design and validate that screen shot with actual static site. I need to do that using Playwright visual validation.
I am trying to capture the full page SS of the figma design using below code:
test('figma design',async({page})=>
{
await page.goto("https:xyz");
await expect(page).toHaveScreenshot("FigmaDesignScreenshotFull.png",{fullPage: true});
});
Its runs correctly but its not capturing the full page screenshot its just capturing the page displayed in Figma Url.
Actions taken:-
1- Tried increasing the port size while capturing the screen.
2- Tried scrolling down with mouse and capture
above approach did not worked.
Note:- The Figma design is for responsive site. |
{"Voters":[{"Id":213269,"DisplayName":"Jonas"},{"Id":10008173,"DisplayName":"David Maze"},{"Id":6463558,"DisplayName":"Lin Du"}],"SiteSpecificCloseReasonIds":[18]} |
{"Voters":[{"Id":9599344,"DisplayName":"uber.s1"}]} |
```
[2024-03-29 11:11:32,491] ERROR - AccessTokenGenerator Error occurred when generating a new Access token. Server responded with 400
[2024-03-29 11:11:32,646] ERROR - APIUtil Error occurred while executing SubscriberKeyMgtClient.
feign.FeignException$Unauthorized: [401 Unauthorized] during [POST] to [http://0.0.0.0:8080/realms/master/clients-registrations/openid-connect] [DCRClient#createApplication(ClientInfo)]: [{"error":"invalid_token","error_description":"Failed decode token"}]
at feign.FeignException.clientErrorStatus(FeignException.java:215) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.FeignException.errorStatus(FeignException.java:194) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.FeignException.errorStatus(FeignException.java:185) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:92) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.AsyncResponseHandler.handleResponse(AsyncResponseHandler.java:98) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:141) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:91) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:100) ~[io.github.openfeign.feign-core_11.9.1.jar:?]
at jdk.proxy35.$Proxy467.createApplication(Unknown Source) ~[?:?]
at org.wso2.keycloak.client.KeycloakClient.createApplication(KeycloakClient.java:134) ~[keycloak.key.manager_2.1.0.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication_aroundBody8(AbstractApplicationRegistrationWorkflowExecutor.java:153) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:1) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication_aroundBody6(AbstractApplicationRegistrationWorkflowExecutor.java:120) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:1) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete_aroundBody2(ApplicationRegistrationSimpleWorkflowExecutor.java:77) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete(ApplicationRegistrationSimpleWorkflowExecutor.java:1) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute_aroundBody0(ApplicationRegistrationSimpleWorkflowExecutor.java:54) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute(ApplicationRegistrationSimpleWorkflowExecutor.java:1) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration_aroundBody106(APIConsumerImpl.java:2313) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration(APIConsumerImpl.java:1) ~[org.wso2.carbon.apimgt.impl_9.28.116.76.jar:?]
at org.wso2.carbon.apimgt.rest.api.store.v1.impl.ApplicationsApiServiceImpl.applicationsApplicationIdGenerateKeysPost(ApplicationsApiServiceImpl.java:788) ~[?:?]
```
I'm getting above error when configuring keyclock as a Key Manager in WSO2 APIM. I have doubled check the URLS in keymanager also and gone through this blog [text](https://medium.com/@nelconcr/troubleshooting-keycloak-as-the-keymanager-in-wso2-api-manager-4-2-0-56bcf209e016) also. But not solved. I'm using WSO2 APIM 4.2.0. |
Configuring Keyclock 22.0.4 as a key manager in WSO2 APIM |
|keycloak|wso2-api-manager| |
null |
I am making a realtime game application using socket io, react and nodejs.
I have deployed backend server and also frontend site. When I am running the frontend site on local host using the deplyed backend server it is running fine, but the problem occurs when I am running it on deployed frontend site.
I have deplyed frontend site using render.
here is the link to my frontend website - https://gamefront.onrender.com/
here is the link to my backend server - https://gameback-6z3w.onrender.com/
here is link to my frontend repository - https://github.com/Arjit31/gameFront/tree/master
here is link to my backend repository - https://github.com/Arjit31/gameBack
Here is a piece of my frontend code -
```
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import io from "socket.io-client";
import "./home.css"; //imports css file into project not just the component
//for importing into components use import styles from "./home.css"
const socket = io();
export default function Home() {
const [key, setKey] = useState("");
const [inputKey, setInputKey] = useState("");
const navigate = useNavigate();
useEffect(() => {
socket.on("keyGenerated", (generatedKey) => {
setKey(generatedKey);
});
socket.on("userConnected", (param) => {
// setConnectedUserId(otherUserId);
redirect(param);
});
return () => {
socket.off("keyGenerated");
socket.off("userConnected");
};
}, []);
const generateKey = (e) => {
e.preventDefault();
socket.emit("generateKey");
};
const connectByKey = (e) => {
e.preventDefault();
socket.emit("connectByKey", inputKey);
// navigate("/game");
// redirect();
};
const redirect = (param) => {
const key = param[0];
let gameURL = "/game?";
gameURL += `key=${key}&user=${param[1]}`;
// console.log(param);
// console.log(param);
// if({key})
// {
// gameURL += `key=${key}`;
// }
// else{
// gameURL += `key=${inputKey}`;
// }
navigate(gameURL);
}
return (
<div className="homeScreen">
{key ? (
<div className="keyGen">{key}</div>
) : (
<div>
<form className="gameForm">
<input
className="gameKey"
placeholder="Game Key"
value={inputKey}
onChange={(e) => setInputKey(e.target.value)}
></input>
<div className="buttonGroup">
<button className="btn join" onClick={connectByKey}>
Join
</button>
<button className="btn create" onClick={generateKey}>
Create
</button>
</div>
</form>
</div>
)}
</div>
);
}
```
Here is my problem screenshot -
[](https://i.stack.imgur.com/I5JFr.png)
[enter image description here](https://i.stack.imgur.com/2yOFc.png)
I think the problem may be lies in the deployment part. |
io.UnsupportedOperation: fileno |
|python|flask| |
null |
I am fetching data within a `MovieItem` component. When I just display one `MovieItem` this works correctly. However when I move this card into a `List` the data isn't fetched correctly and nothing is displayed.
My code looks something like this
MovieModel
```
class MovieModel: ObservableObject {
var movie: Movie
fetchMovie(movieId) {
...request stuff from core data...
self.movie = movie
}
}
```
ListView
```
struct ListView: View {
@ObservedObject var movies: [Movie(name: "Titanic", id: 1)]
var body: some View {
List {
ForEach(movies) { movie in
MovieItem(movie: movie)
}
}
}
}
```
MovieItem
```
struct MovieItem: View {
@ObservedObject var movieModel: MovieModel
var movie: Movie
var body: some View {
Text(movie.name)
}
.onAppear {
movieModel.fetchMovie(movie)
}
}
```
Is it obvious to anyone what's wrong and the approach to take to get this to work? |