instruction stringlengths 0 30k ⌀ |
|---|
Outlook has limited CSS support, especially when it comes to layering elements on top/bottom of each other. Unless you can get real creative with using table elements to mimic what looks like elements on top of each other, the answer is no. It's not possible to pull this design off in Outlook instances as of today. |
I apologize for the excessive text, but I tried to explain how I think in detail.
Also, I know that term "sub-module" does not exist, since all modules are equal, but I am referring to a case where one module (go.mod file) is within some other module.
I am reading [documentation](https://go.dev/ref/mod) for golang modules and fully understand how it works in case of working through proxies, that is with GOPROXY protocol. However, I am confused by direct communication with VSCs (direct mode) when it comes to sub-modules.
Consider the following [alexedwards module](https://github.com/alexedwards/scs) and its [mysqlstore sub-module](https://github.com/alexedwards/scs/tree/master/mysqlstore).
Their module paths are:
1. alexedwards module -> `github.com/alexedwards/scs/v2` (`github.com/alexedwards/scs`)
2. mysqlstore sub-module -> `github.com/alexedwards/scs/mysqlstore`
First, documentation states the following:
> If the module path has a VCS qualifier (one of .bzr, .fossil, .git,
> .hg, .svn) at the end of a path component, the go command will use
> everything up to that path qualifier as the repository URL. For
> example, for the module example.com/foo.git/bar, the go command
> downloads the repository at example.com/foo.git using git, expecting
> to find the module in the bar subdirectory. The go command will guess the protocol to use based on the protocols supported by the version control tool.
However, since mysqlstore sub-module does not have VCS qualifier (its `github.com/alexedwards/scs/mysqlstore` and not `github.com/alexedwards/scs.git/mysqlstore`), we do not consider this.
Further, the documentation states the following:
> If the module path does not have a qualifier, the go command sends an
> HTTP GET request to a URL derived from the module path with a
> ?go-get=1 query string.
> The server must respond with an HTML document containing a <meta> tag
> in the document’s <head>.
So, I made a following [curl](https://reqbin.com/curl) request:
curl https://github.com/alexedwards/scs/mysqlstore?go-get=1
but got `404 (Not Found)`. Then, I was thinking maybe it works in the same way as in case of GOPROXY protocol and finding a module for package. Thus, I went a step back (took off `/mysqlstore`) and made the following request:
curl https://github.com/alexedwards/scs?go-get=1
and got the following meta tag:
<meta name="go-import" content="github.com/alexedwards/scs git https://github.com/alexedwards/scs.git">
So, according to this meta tag, it will now look at `https://github.com/alexedwards/scs.git` as repo-URL and `github.com/alexedwards/scs` as repository root path for the requested module `mysqlstore`.
Everything would be clear to me (at least I think) if there were no module (go.mod file) on a given path (`github.com/alexedwards/scs`), but there is. Will this way actually the wrong module being downloaded, that is, the `scs` module instead of the submodule `mysqlstore`? I mean, if `mysqlstore` is just a package, how can it even know that there is another module since we use `go get alexedwards/scs/mysqlstore` command for both package and module. In case of GOPROXY protocol it is solved by going backward (`.../scs/mysqlstore` -> `.../scs/` -> `...`), sending request for these paths and taking the module for longest path. However, in this case `https://github.com/alexedwards/scs/mysqlstore?go-get=1` did not gave a result.
I am missing something hard.
Does the module search process in direct mode really work as I described? Can anyone point me what I misunderstood and what the actual process is?
Any help is greatly appreciated. Thank you!! |
Error deploying Next.js app on Vercel: "RangeError: Maximum call stack size exceeded |
|next.js|vercel| |
|angular|rxjs| |
I'm using Next.js app version 14.
RTL is not applied to Shadcn components.
I'm also using next-intl to support multiple languages
Here's how my layout.tsx file looks like:
```
layout.tsx
import type { Metadata } from "next";
import "../globalsyour text.css";
import localFont from "next/font/local";
import { Provider } from "../../providers";
import { NextIntlClientProvider, useMessages } from "next-intl";
const iranSansFont = localFont({
src: "../../fonts/iranSans.woff2",
display: "swap",
variable: "--font-iranSans",
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
params: { locale },
}: Readonly<{
children: React.ReactElement;
params: { locale: string };
}>) {
const messages = useMessages();
return (
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"}>
<body
className={`${iranSansFont.className} bg-background text-foreground px-4 py-4 font-bold`}
>
<NextIntlClientProvider locale={locale} messages={messages}>
<Provider>{children}</Provider>
</NextIntlClientProvider>
</body>
</html>
);
}
```
Additionally, I've utilized @radix-ui/react-direction, but encountered the following error.
```
import type { Metadata } from "next";
import "../globals.css";
import localFont from "next/font/local";
import { Provider } from "../../providers";
import { NextIntlClientProvider, useMessages } from "next-intl";
import { DirectionProvider } from "@radix-ui/react-direction";
const iranSansFont = localFont({
src: "../../fonts/iranSans.woff2",
display: "swap",
variable: "--font-iranSans",
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
params: { locale },
}: Readonly<{
children: React.ReactElement;
params: { locale: string };
}>) {
const messages = useMessages();
return (
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"}>
<body
className={`${iranSansFont.className} bg-background text-foreground px-4 py-4 font-bold`}
>
<DirectionProvider dir={locale === "fa" ? "rtl" : "ltr"}>
<NextIntlClientProvider locale={locale} messages={messages}>
<Provider>{children}</Provider>
</NextIntlClientProvider>
</DirectionProvider>
</body>
</html>
);
}
```
Error:
⨯ node_modules\@radix-ui\react-direction\dist\index.mjs (4:82) @ undefined
⨯ TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function
at eval (webpack-internal:///(rsc)/./node_modules/@radix-ui/react-direction/dist/index.mjs:9:114)
at (rsc)/./node_modules/@radix-ui/react-direction/dist/index.mjs (C:\Users\ehsanKey\Documents\dev\portfolio-site\.next\server\vendor-chunks\@radix-ui.js:260:1)
at __webpack_require__ (C:\Users\ehsanKey\Documents\dev\portfolio-site\.next\server\webpack-runtime.js:33:42)
at eval (webpack-internal:///(rsc)/./src/app/[locale]/layout.tsx:14:83)
at (rsc)/./src/app/[locale]/layout.tsx (C:\Users\ehsanKey\Documents\dev\portfolio-site\.next\server\app\[locale]\page.js:374:1)
at Function.__webpack_require__ (C:\Users\ehsanKey\Documents\dev\portfolio-site\.next\server\webpack-runtime.js:33:42)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async collectGenerateParams (C:\Users\ehsanKey\Documents\dev\portfolio-site\node_modules\next\dist\build\utils.js:919:21)
at async Object.loadStaticPaths (C:\Users\ehsanKey\Documents\dev\portfolio-site\node_modules\next\dist\server\dev\static-paths-worker.js:46:13) {
type: 'TypeError',
page: ''
}
|
How to build an object from strings in rust? |
|oop|rust|type-conversion| |
null |
Try Removing @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@EmbeddedKafka( |
TYPO3 12.4, Powermail 12.2.1:
the following cObject in Mail to User or in Submit Page:
{f:cObject(typoscriptObjectPath:'lib.anrede',data:'{anrede}')}
throws the following error:
TYPO3\CMS\Fluid\ViewHelpers\CObjectViewHelper::getContentObjectRenderer(): Argument #1 ($request) must be of type Psr\Http\Message\ServerRequestInterface, null given, called in /var/www/html/site/vendor/typo3/cms-fluid/Classes/ViewHelpers/CObjectViewHelper.php on line 130
Any ideas?
Thanks! |
typoscriptObjectPath throws error in Powermail 12 |
|typo3| |
A return type changed from `const Bar& getBar()` to `const Bar getBar()`.
If i use:
`const auto& bar = getBar();`
and the return type changes. I have a reference on a temporary object.
If i use:
`const auto bar = getBar();`
i always make a copy of `Bar`.
What is The best practice for this problem?
``` lang-c++
class Bar {
public:
Bar() = default;
Bar(const Bar&) = default;
Bar(Bar&&) = delete;
Bar& operator=(const Bar&) = delete;
Bar& operator=(const Bar&&) = delete;
void setValue(int i);
int value() const;
private:
int m_i = 0;
};
class Foo {
public:
Foo(Bar& bar) : m_bar(bar) {}
Foo(const Foo&) = delete;
Foo(Foo&&) = delete;
Foo& operator=(const Foo&) = delete;
Foo& operator=(const Foo&&) = delete;
const Bar& giveMeBar();
private:
Bar& m_bar;
};
int main() {
auto bar = std::make_unique<Bar>();
auto foo = std::make_unique<Foo>(*bar.get());
const auto& barFromFoo = foo->giveMeBar();
bar->setValue(2);
std::cout << "original bar: " << bar->value() << std::endl;
std::cout << "bar from foo: " << barFromFoo.value() << std::endl;
}
``` |
//next.config.js
```javascript
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'export',
images: {
unoptimized: true
}
// Optional: Change links `/me` -> `/me/` and emit `/me.html` -> `/me/index.html`
// trailingSlash: true,
// Optional: Prevent automatic `/me` -> `/me/`, instead preserve `href`
// skipTrailingSlashRedirect: true,
// Optional: Change the output directory `out` -> `dist`
// distDir: 'dist',
}
module.exports = nextConfig
```
//package.json
```json
{
"name": "dummy",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/material": "^5.14.20",
"next": "14.0.4",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.0.4",
"typescript": "^5"
}
}
```
I tried by adding output: 'export' to next.config.js file, then "export: next export" to package.json file |
How to Apply RTL Support to Shadcn Components in Next.js? |
|next.js|next-i18next|radix-ui| |
I was using HTML, CSS, PHP and JavaScript to code a simple one page website in Visual Studio Code. I basically only added a background image and a header containing a logo and title when I left to do something else. When I came back, I recieved the following error:
> Error spawning PHP: Command failed with exit code 1: C:/Program
> Files/Ampps/php --version 'C:\Program Files\Ampps\php' is not
> recognized as an internal or external command, operable program or
> batch file.
This is weird considering nothing was changed on the computer during the 15 minutes between me working on the website and getting the error.
I already tried adding the PHP path to PHP Executable Path setting as follows:
```
{
"workbench.colorTheme": "Default High Contrast Light",
"php.executablePath": "C:/Program Files/Ampps/php74",
"php.executables": {},
"security.workspace.trust.untrustedFiles": "open"
}
```
I also added the path to the environment variables, I checked my firewall permissions, updated VS Code and made sure all my extentions are up to date while restarting my PC after each attempt at removing the error message, but so far nothing has worked. |
|php|html|visual-studio|executable| |
null |
I have 2 services(2 app runner endpoints) with 2 different api(1. test.com/svc1/home, 2. test.com/svc2/home). If I hit **test.com/svc1/home** it should get the data from service 1 and the URL should transfer into test.com/home and its the same for service 2. If I hit **test.com/svc2/home** it should get the data from service 2 and the URL should transfer into test.com/home. Is there any possibility to set this in AWS API gateway.
---------------------------- |
setting same API path for different service and transfering api path |
|api|aws-api-gateway|api-gateway| |
null |
Just as an academic challenge, here is a short-circuiting recursive approach that doesn't rely on a loop and explicitly checks for null-ness (versus falsey-ness). This won't be outperforming other scripts which use `foreach()` and no iterated function calls.
Code: ([Demo][1]) ([IIFE One-liner Demo][2])
$array = [
null,
null,
null,
1,
null
];
$fn = function($array) use (&$fn) {
return array_shift($array) ?? ($array ? $fn($array) : null);
};
var_export($fn($array));
Or with a more traditional style: ([Demo][3])
function getFirstNull($array) {
return array_shift($array) ?? ($array ? getFirstNull($array) : null);
}
var_export(getFirstNull($array));
The body of the function pulls the first element off of the array and return it if it is not null; otherwise, it will make a recursive call upon the remainder of the array (if there are any elements) else return `null` to prevent an infinite loop.
[1]: https://3v4l.org/UR3pP
[2]: https://3v4l.org/5Z1vN
[3]: https://3v4l.org/W511X |
Do note that the variables like `month` are tied to the UNIX time of the candle's open. For forex exchanges, Feb 5 candle opens on Feb 4, and Feb 6 candle opens on Feb 5, so the open on the Feb 5 daily candle returns `dayofmonth` of 4. As such, the expression you provided will be `true` for the end part of the Feb 5 candle and the beginning part of the Feb 6 candle. I can't guarantee that this is the source of your issue, but it might be.
To work around this, use `month(time_tradingday, "UTC+0")` and `dayofmonth(time_tradingday, "UTC+0")` -- the `time_tradingday` variable exists specifically to return the timestamp of the trading day the candle belongs to (00:00 UTC of said trading day, to be precise, which is why we additionally pass UTC+0 to the functions to make sure they parse the timestamp properly). Compare how these two approaches color bars on any forex symbol:
//@version=5
indicator("My script", overlay=true)
TimeToAvoid = month == 2 and dayofmonth == 5
TradingDayToAvoid = month(time_tradingday, "UTC+0") == 2 and dayofmonth(time_tradingday, "UTC+0") == 5
bgcolor(TimeToAvoid ? color.new(color.red, 80) : na)
bgcolor(TradingDayToAvoid ? color.new(color.green, 80) : na) |
I'm looking for a preg_replace that can replace " with ' when between font-family: and ;
I'm having an issue with my some dynamic html I'm using which requires me to replace the quotes with single quotes in my style attribute. Font and Font-family attributes can sometimes have quotes when they have spaces in the names but that is causing issues rendering the html. I haven't fully got a handle on how to use preg_replace so I'm hoping somebody can lend me a hand.
This is an example of the string: `<span style="font-weight:bold;font-family:"franklin gothic medium",arial,helvetica,sans-serif;font-size:29px"="">Made in the USA!</span>`
From how I though preg_replace worked I tried the following but it didn't work: `preg_replace("/font\-family\:[\"]+?\;/", "'", $string);` |
Replacing quotes with single quotes between two strings in php using preg_replace |
|php|preg-replace| |
null |
The justify-content:center is making the content to align to center and some of the left is cut off. You could remove it and try.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
width: 1000px;
margin: 0 auto;
display: flex;
flex-direction: row;
overflow-x:scroll
}
.container::before,
.container::after {
content: '';
width: 100%;
}
.box {
height: 100px;
border: 1px solid red;
min-width: 100px;
margin-right: 10px;
flex-grow: 1;
}
<!-- language: lang-html -->
<div class="container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<!-- end snippet -->
|
null |
The `justify-content: center` is making the content to align to center, and some of the left is cut off. You could remove it and try.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
width: 1000px;
margin: 0 auto;
display: flex;
flex-direction: row;
overflow-x:scroll
}
.container::before,
.container::after {
content: '';
width: 100%;
}
.box {
height: 100px;
border: 1px solid red;
min-width: 100px;
margin-right: 10px;
flex-grow: 1;
}
<!-- language: lang-html -->
<div class="container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
<!-- end snippet -->
|
It's just an operator precedence issue that you're facing.
In the expression **x&1 == 0**, `==` has the highest precedence; it will be executed before `&`. As a consequence, **x&1 == 0** will evaluate to **x & (1 == 0)** which evaluates to **x & 0** (always equal to 0).
You can find here the official C++ Operator Precedence [Table][1].
You can use parentheses to solve your issue: **(x & 1) == 0**
[1]: https://en.cppreference.com/w/cpp/language/operator_precedence |
I had a small question.
I was reading some code and found (code accepting filename and command line parameters)
**@ :: ARGS** = ($0,@ARGV);
but unable to understand 1st part of the expression, what exactly it is doing ?
is it behaves the same way as **@ARGS** = ($0,@ARGV);`
|
Perl :: special character use |
|perl| |
The problem is due to email enumeration protection which is active by default on Firebase accounts created after September 2023.
When this feature is active numerous auth functions no longer work. Specifically, concerning this question:
> You can no longer use the linkWithCredential client SDK method with an
> EmailAuthCredential on any platform. Use the REST API signUp instead,
> passing the user's ID token in the idToken field and the email,
> password fields to link.
source : https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection
and here is the link to the sign up api that should now be used:
https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts/signUp |
i am very new to JavaFX and no nothing about it. i have been watching youtube videos on how to use scenebuilder but somehow when im on this part i cant set the code and this message prompts.[this is the message that prompts](https://i.stack.imgur.com/VDeO2.png)
a fix for my problem that keeps on occurring
Login.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="820.0" prefWidth="1080.0" style="-fx-background-color: #1D242A;" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Login">
<children>
<Pane layoutX="315.0" layoutY="230.0" prefHeight="455.0" prefWidth="450.0" style="-fx-background-color: #2F353A;">
<children>
<Button fx:id="LoginBtn" layoutX="34.0" layoutY="397.0" mnemonicParsing="false" prefHeight="35.0" prefWidth="382.0" style="-fx-background-color: #158BF8;" text="Login" textFill="WHITE">
<font>
<Font name="System Bold" size="20.0" />
</font>
</Button>
<Label layoutX="129.0" layoutY="14.0" text="Welcome Back" textFill="WHITE">
<font>
<Font name="System Bold" size="28.0" />
</font>
</Label>
<Label layoutX="197.0" layoutY="54.0" text="Sign In" textFill="#aeaeae">
<font>
<Font name="System Bold" size="17.0" />
</font>
</Label>
<Label fx:id="Password" layoutX="55.0" layoutY="246.0" text="Password" textFill="#aeaeae">
<font>
<Font name="System Bold" size="17.0" />
</font>
</Label>
<PasswordField layoutX="55.0" layoutY="280.0" prefHeight="33.0" prefWidth="339.0" promptText="Enter your password" />
<TextField fx:id="tfUser" layoutX="55.0" layoutY="181.0" prefHeight="33.0" prefWidth="339.0" promptText="Enter you username" />
<Label fx:id="Username" layoutX="53.0" layoutY="144.0" text="Username" textFill="#aeaeae">
<font>
<Font name="System Bold" size="17.0" />
</font>
</Label>
</children>
</Pane>
<Label fx:id="label_Budo" layoutX="343.0" layoutY="139.0" text="BUDO Enterprise Inc." textFill="WHITE">
<font>
<Font name="System Bold" size="40.0" />
</font>
</Label>
</children>
</AnchorPane>
|
How to create a virtual-hosted-style presigned URL for an S3 bucket in a non US region? |
|amazon-web-services|amazon-s3|boto3|pre-signed-url| |
null |
Step 1: Create a file called header.js and paste following code:
`$(function(){
$("#header").html(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">........`);
});`
Step 2: Add <div id="header"></div> at proper place as you seem fit
Step 3: Add following code before ending of body tag:
<script src="assets/js/jquery-3.2.1.min.js"></script>
<script src="header.js"></script>
Do same steps for footer or sidebar. |
I made a library to convert from parquet to Postgres’ binary format: https://github.com/adriangb/pgpq.
It lets you use PyArrow to read the parquet data and your postgres driver of choice to write it out (e.g. psycopg).
Update: it's been pointed out to me that DuckDB can do this as well. Here's a benchmark where I show how to do it with both pgpq and DuckDB: [permalink](https://github.com/adriangb/pgpq/blob/4fe8600f23ead94de129bb57fbd1ba12b3f5b389/py/benches/copy.ipynb). Both perform about the same but DuckDB is of course much more widely used, better tested and more versatile. |
I am trying to generate a signature programmatically for the body of my SOAP Messages
Looking at the [spec](https://www.w3.org/TR/xmldsig-core2/#sec-KeyInfo) it should be possible to have
```
<KeyInfo>
<X509Data>
<X509Certificate/>
<X509IssuerSerial>
<X509IssuerName>
...
</X509IssuerName>
<X509SerialNumber>...</X509SerialNumber>
</X509IssuerSerial>
</X509Data>
</KeyInfo>
```
I am using WSS4J 3.0.3
```
KeyPair keyPair = generateKeys();
Certificate certificate = generateCertificate(new KeyPair(getPublicKey(), getPrivateKey()));
String alias = "alias";
KeyStore keyStore = saveKeyStore(temporaryFolder.newFile(KEY_STORE_FILENAME), PASSWORD, certificate, keyPair, alias);
try(InputStream inputStream = TestSOAPSignatureValidationServiceWSSJ.class.getResourceAsStream("UnsignedDocument.xml")){
SOAPMessage message = MessageFactory.newInstance().createMessage(null, inputStream);
SOAPBody soapBody = message.getSOAPBody();
Document document = soapBody.getOwnerDocument();
WSSecHeader secHeader = new WSSecHeader(document);
secHeader.setMustUnderstand(true);
Element securityHeaderElement = document.createElementNS("http://schemas.xmlsoap.org/soap/security/2000-12", "SOAP-SEC:Signature");
message.getSOAPHeader().appendChild(securityHeaderElement);
secHeader.setSecurityHeaderElement(securityHeaderElement);
secHeader.insertSecurityHeader();
WSSecSignature signature = new WSSecSignature(secHeader);
signature.setX509Certificate((X509Certificate) certificate);
Properties properties = new Properties();
properties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
Crypto crypto = CryptoFactory.getInstance(properties);
crypto.loadCertificate(new ByteArrayInputStream(certificate.getEncoded()));
((Merlin) crypto).setKeyStore(keyStore);
signature.setUserInfo(alias, PASSWORD);
WSDocInfo wsDocInfo = new WSDocInfo(document);
signature.setWsDocInfo(wsDocInfo);
signature.setAddInclusivePrefixes(false);
org.apache.xml.security.Init.init();
WSEncryptionPart wsEncryptionPart = new WSEncryptionPart(soapBody.getLocalName(), soapBody.getNamespaceURI(), "Content");
wsEncryptionPart.setElement(soapBody);
wsEncryptionPart.setId("Body");
signature.addReferencesToSign(List.of(wsEncryptionPart));
signature.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
Document signed = signature.build(crypto);
LOG.info(XMLUtils.prettyDocumentToString(signed));
}
}
```
but I am getting
```
<ds:KeyInfo Id="KI-c26f3a7c-ddf2-4889-9eef-55b541cb458f">
**<wsse:SecurityTokenReference** wsu:Id="STR-d5bbb99f-f861-4512-af56-f5e697c939ba" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<ds:X509Data>
<ds:X509IssuerSerial>
<ds:X509IssuerName>...</ds:X509IssuerName>
<ds:X509SerialNumber>..</ds:X509SerialNumber>
</ds:X509IssuerSerial>
</ds:X509Data>
**</wsse:SecurityTokenReference>**
</ds:KeyInfo>
```
Is it possible to instruct WSS4J to avoid the `SecurityTokenReference` tag and have the `X509Data` tag as a direct child of `KeyInfo`?
Thanks in advance!
|
null |
docker 19.0.3 ([release notes](https://docs.docker.com/engine/release-notes/19.03/)) added a `--gpus` argument to their `docker run` command
which we can provide through vagrant's `create_args` docker configuration option, [docs](https://developer.hashicorp.com/vagrant/docs/providers/docker/configuration):
> create_args (array of strings) - Additional arguments to pass to docker run when the container is started. This can be used to set parameters that are not exposed via the Vagrantfile.
so after adding this line, the GPUs will be exposed in the VM
```ruby
config.vm.provider "docker" do |d|
...
d.create_args = ["--gpus", "all"]
...
end
``` |
The thing is that I need to create a table and export it as a photo. There are some elements that I need them to be aligned to the right, but I want them to have some margin with respect to the end of the cell. What I did is to convert these numbers to a string, and then I added a blank space at the end (representing the margin)
[covert number to string](https://i.stack.imgur.com/x62LV.png)
After I add the margin, I put it in the excel file:
[Append](https://i.stack.imgur.com/2SLCU.png)
However, when I do this, and I export the file, I get the corner marked by the control Green Error Checking Markers of Excel, because it detects that the values are numbers, and thus, the exported image has the markers too:

My question is if there is any other way to leave a margin, or if there is a way to ignore these errors via openpyxl. Thanks |
I am trying to remove a item from a list. I have a table named InvItem and another table named InvItemLoc. When I add a item then the id of InvItem table is used as foreign key in InvItemLoc table. But when I delete a item the child table row is not deleted. Now I need to generate a list of InvItemLoc table by the InvItem id that is currently in InvItem table and with a specific organization. But when I am going to check that if it matches the InvItemLoc with InvItem table it is giving this error:
`No row with the given identifier exists: [inv.InvItem#9666]`
Here is my attempt below:
def items = InvItemLoc.findAllByAaOrgId(aaOrg)
List<InvItemLoc> found = new ArrayList<InvItemLoc>();
for(InvItemLoc item : items){
def invItem = InvItem.findById(item.invItemId.id)
if(!invItem){
found.add(item);
}
}
items.removeAll(found);
it is giving error at this line:
`def invItem = InvItem.findById(item.invItemId.id)`
Edit
---
My InvItemLoc domain looks like this:
class InvItemLoc {
static mapping = {
...
}
Long id
InvItem invItemId
...
static constraints = {
...
}
}
InvItem domain look likes this:
class InvItem {
static mapping = {
...
}
Long id
...
static constraints = {
...
}
String toString() {
...
}
} |
Sam's answer worked. Also, I had to add a **+0** at the end to get 0 when the values are not present.
Bug Count 2 =
CALCULATE(
COUNT('test_execution_summary'[ExecutionDefect]) + 0,
'defect_report'[Issue Type] = "Bug"
) |
Since you're not using Hilt for dependency injection, you need to provide an instance of FoodDao to your MainViewModel manually.
you can modify your code to provide the FoodDao dependency to MainViewModel:
@Composable
fun MainActivityScreen(viewModel: MainViewModel = viewModel()) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val foodDao = remember { AppDatabase.getInstance(context).foodDao()}
val viewModel = remember { MainViewModel(foodDao)}
val foods = viewModel.foods
LaunchedEffect(key1 = context) {
viewModel.getAllFoods()
}
}
In this modification, we create an instance of FoodDao using the AppDatabase (assuming AppDatabase is your Room database class) and pass it to the MainViewModel constructor. This way, the MainViewModel has access to the required dependencies.
|
I'm assuming you ARE getting an error message. You check the logs and you get a message, "Sign-in button successfully located.", then a message, "Failed to locate the sign-in button.", and THEN the actual exception message printed to the logs. I'm assuming the error message is an element not interactable exception.
There are a number of issues that should be addressed to make this work and work better,
1. You don't get any error when you try to click because you are catching all exceptions
catch (Exception e)
A better practice is to only catch exceptions you are expecting and only if you plan on handling them. Eating all exceptions and printing a generic message is not very helpful when you go to debug... which you are experiencing right now. I would remove the `try-catch` and let the script fail when it throws. Continuing the script after an exception will likely cause it to fail later and then you'll have a harder time figuring out why it failed.
1. Your locator, `By.tagName("button")`, is way to generic. That's going to grab *every* BUTTON on the page, which depending on the page could be a LOT of BUTTONs. The HTML of the BUTTON you posted has an ID... you should always use that, `By.id("signin-button")`. It's likely you are grabbing *a* BUTTON but the wrong button and it's not visible or otherwise causing a failure and that's why you get the success message and then the failure message.
1. This message, "Sign-in button successfully located." is not really true. It just prints when the wait doesn't time out... it doesn't mean that it's found the correct element, which I'm assuming is what is happening here.
My suggestion is to reduce the code to the below,
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
url = 'https://staging3.rolustech.com:44353/index.php/site/login'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.ID,"LoginForm_username"))).send_keys("username")
wait.until(EC.visibility_of_element_located((By.ID,"LoginForm_password"))).send_keys("password")
sign_in = wait.until(EC.element_to_be_clickable((By.ID,"signin-button")))
sign_in.click()
time.sleep(1)
sign_in.click()
If the code throws an exception, it will fail and get printed to the logs and you'll have the full exception message that you can review. Don't print success messages, they don't add any value. If your code gets past that line, you know it succeeded. Don't make yourself or others wade through hundreds of lines of success messages just to find the error message. It just prolongs the investigation time unnecessarily.
----
Other misc suggestions...
1. You define `wait3` at the top of the code but you aren't actually using it. Three lines below you use `wait` instead.
1. Three seconds is really short. I would do a minimum of 10s, depending on the scenario. If the element is immediately available, the code will not wait so it doesn't slow the code down. The only time it really slows down is if the element will never be available and you've specified a long wait time, e.g. 60s. Then it's going to wait the full 60s before it times out. You'll need to tailor the time to the scenario but my suggestion is for most scenarios, 10s is the right amount of time to wait. |
As the title suggests, I want to record the screen with the iPad's own record button. Currently, I can record in silent mode. I received information saying "it does capture sound, you just need to enable it." However, I can't find where to enable it.[![de][1]][1]
[1]: https://i.stack.imgur.com/C5KDh.png |
Record screen with sound in İpad Pro(11-inch) simulator |
|ios|xcode|simulator| |
Since you have explicitly mentioned decrease clause, Dafny will use that decrease clause. You assumption that it will compare `x + y` with tuple `x`, `y` is wrong. It would have chosen tuple `x`, `y` as if you haven't provided decrease clause. In either case it will compare decrease clause of invoking function/lemma with called function/lemma. Hence it will compare `x+y` with `x+y` (recursion call values) or `x, y` with `x, y` (recursion call values) in this case.
Now take case when it is called with `x = 3` and `y = 2`. Here `x + y` is 5 and when you call recursively in last else if branch it will be `x = 2` and `y = 3` but `x + y` is 5 still. It is not decreasing hence Dafny is complaining. |
unreachable network error when establishing a bluetooth connection between raspberrypi and laptop |
|python|c++|raspberry-pi|bluetooth|network-programming| |
I have a project and when i try to run the main or the test directories i have no problems with the gradle build.
But now when i try to run a an android test i get this error:
Directory 'C:\Users\...' does not contain a Gradle build.
i wrote a Compose Test that looks like this:
`@RunWith(AndroidJUnit4::class)
class NavigationTest {
@get :Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
fun startApp_showRegistrationScreen() {
composeTestRule.setContent {
MyTheme {
MyApp()
}
}
val registerString = composeTestRule.activity.getString(R.string.register_for_first_time)
composeTestRule.onNodeWithText(registerString).assertIsDisplayed()
}
}`
the error:
Directory 'C:\Users\alici\MyProject\Myproject' does not contain a Gradle build.
* Try:
> Run gradle init to create a new Gradle build in this directory.
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
I am confused. WHat do i need to do?
Here the project structure:
[![Project strucure][1]][1]
[1]: https://i.stack.imgur.com/kX0oe.png |
The app I work on currently uses Java 8. We're migrating to 17 and as part of that I need to convert some code which currently references SoyTofu to use SoySauce ([Google Closure Templates][1]). Here's the relevant parts of the class I'm working in. My goal is to have the lightest possible touch on this code, but I'm getting stymied at every turn. Note that I'm also a new Java developer, so take my lack of knowledge with a grain of salt.
```
import com.google.template.soy.SoyFileSet;
import com.google.template.soy.tofu.SoyTofu;
public class Foobar {
...
private SoyTofu soyTemplates;
...
@Override
protected void startUp() throws Exception {
...
String templatesProperty = "templates/mail.soy templates/mail-admin.soy";
try {
String[] templates = templatesProperty.split("\\s+");
if (templates.length > 0) {
SoyFileSet.Builder builder = SoyFileSet.builder();
for (String t : templates) {
URL url = get.Url(t);
builder.add(url);
}
soyTemplates = builder.build().compileToTofu();
}
}
...
}
public Message compose(MailItem item) {
...
Map<String, Object> ijData = new HashMap<String, Object>();
ijData.put("supported", true);
ijData.put("brand", "Accounts");
String renderSubject = soyTemplates.newRenderer(item.subject).setData(item.data).setIjData(ijData).render();
message.setSubject(renderSubject);
String renderBody = soyTemplates.newRenderer(item.body).setData(item.data).setIjData(ijData).render();
message.setContent(renderBody, MediaType.TEXT_HTML);
...
}
}
```
And a snippet of one of the .soy files
```
/**
* Account request submitted subject
*/
{template accountRequestSubmittedSubject}
{@param username : string}
{$ij.brand} account request: {$username}
{/template}
```
The GitHub repository for GCT has a [migration doc][2], but it's different enough that I'm not able to get it working. It seems to indicate that I __can__ compile the templates in real time, but doesn't suggest that it's a good idea; for speed purposes. I'm willing to take that hit though since there are only two templates.
Several parts of this code are showing deprecation warnings, which I can deal with after I get the migration working. The primary issue is that the injected data method doesn't appear to be working correctly.
When I run a unit test which references this code I get an exception
```none
Caused by: com.google.template.soy.error.SoyCompilationException: errors during Soy compilation
file:/target/test-classes/templates/mail-admin.soy:8: error: Unknown variable.
8: {$ij.brand} account request: {$requestorUsername}
~~~
```
I've tried creating a separate SoySauce builder, I've tried converting the SoyTofu builder to SoySauce, but I keep hitting walls. Anyone have thoughts?
[1]: https://github.com/google/closure-templates/tree/master
[2]: https://github.com/google/closure-templates/blob/master/documentation/dev/soysauce-migration.md |
Create an Azure AD application and grant User.Read API permission:

Generate the auth-code by using below endpoint and sign-in with the user account:
```json
https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://replyUrlNotSet
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
```

**You can make use of below code to get the singed in user details:**
```csharp
using Microsoft.Graph;
using Azure.Identity;
class Program
{
static async Task Main(string[] args)
{
var scopes = new[] { "User.Read" };
var tenantId = "TenantID";
var clientId = "ClientID";
var clientSecret = "ClientSecret";
var authorizationCode = "authcodefromabove";
var options = new AuthorizationCodeCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};
var authCodeCredential = new AuthorizationCodeCredential(
tenantId, clientId, clientSecret, authorizationCode, options);
var graphClient = new GraphServiceClient(authCodeCredential, scopes);
try
{
// Fetch user details using GET request to Microsoft Graph API
var result = await graphClient.Me.GetAsync();
// Output user details
Console.WriteLine($"User ID: {result.Id}");
Console.WriteLine($"Display Name: {result.DisplayName}");
Console.WriteLine($"Email: {result.Mail}");
Console.WriteLine($"Job Title: {result.JobTitle}");
// Add more properties as needed
}
catch (Exception ex)
{
Console.WriteLine($"Error fetching user details: {ex.Message}");
}
}
}
```

***Modify the code and use the below to get the details you require:***
```csharp
try
{
var result = await graphClient.Me
.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string[] { "displayName", "id", "officeLocation", "givenName", "businessPhones", "jobTitle", "mobilePhone", "preferredLanguage", "surname", "userPrincipalName", "mail" };
});
// Output user details
Console.WriteLine($"User ID: {result.Id}");
Console.WriteLine($"Display Name: {result.DisplayName}");
Console.WriteLine($"Email: {result.Mail}");
Console.WriteLine($"Job Title: {result.JobTitle}");
Console.WriteLine($"Business Phones: {string.Join(",", result.BusinessPhones)}");
Console.WriteLine($"Given Name: {result.GivenName}");
Console.WriteLine($"Mobile Phone: {result.MobilePhone}");
Console.WriteLine($"Office Location: {result.OfficeLocation}");
Console.WriteLine($"Preferred Language: {result.PreferredLanguage}");
Console.WriteLine($"Surname: {result.Surname}");
Console.WriteLine($"User Principal Name: {result.UserPrincipalName}");
// Add more properties as needed
}
catch (Exception ex)
{
Console.WriteLine($"Error fetching user details: {ex.Message}");
}
}
}
```
And get response like below:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/bK7Ju.png
**UPDATED: To make use of Interactive browser credential flow make use of below code:**
```csharp
using Microsoft.Graph;
using Azure.Identity;
class Program
{
static async Task Main(string[] args)
{
var scopes = new[] { "User.Read" };
var tenantId = "TenantID";
var clientId = "ClientID";
var options = new InteractiveBrowserCredentialOptions
{
TenantId = tenantId,
ClientId = clientId,
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
// MUST be http://localhost or http://localhost:PORT
// See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
RedirectUri = new Uri("http://localhost"),
};
// https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
var interactiveCredential = new InteractiveBrowserCredential(options);
var graphClient = new GraphServiceClient(interactiveCredential, scopes);
try
{
// Fetch user details using GET request to Microsoft Graph API
var result = await graphClient.Me.GetAsync();
// Output user details
Console.WriteLine($"User ID: {result.Id}");
Console.WriteLine($"Display Name: {result.DisplayName}");
Console.WriteLine($"Email: {result.Mail}");
Console.WriteLine($"Job Title: {result.JobTitle}");
// Add more properties as needed
}
catch (Exception ex)
{
Console.WriteLine($"Error fetching user details: {ex.Message}");
}
}
}
``` |
null |
null |
I would like to check if it is possible for CKAN to connect to SSL/TLS solr and redis?
I have created CA and certificate (signed by CA) using openssl, then I imported the certificates into the certificate manager in linux, here is what I did to import to the certificate manager.
In **Dockerfile** of solr,
COPY solrCA.crt /usr/local/share/ca-certificates/solrCA.crt
RUN cat /usr/local/share/ca-certificates/solrCA.crt >> /etc/ssl/certs/ca-certificates.crt
RUN update-ca-certificates
then in the solr's environment variable, I have indicated these env variables, (I have mounted all certificates into /var/solr/ssl)
SOLR_SSL_KEY_STORE=/var/solr/ssl/solrCA.pfx`=
SOLR_SSL_KEY_STORE=
SOLR_SSL_KEY_STORE_TYPE=PKCS12
SOLR_SSL_TRUST_STORE=/var/solr/ssl/solr.p12
SOLR_SSL_TRUST_STORE_PASSWORD=
SOLR_SSL_TRUST_STORE_TYPE=PKCS12
SOLR_SSL_NEED_cLIENT_AUTH=true
SOLR_SSL_WANT_cLIENT_AUTH=true
SOLR_SSL_CHECK_PEER_NAME=true
After configured the above, my ckan program hit with the below error
`[ckan.lib.search.common] Failed to connect to server at https://solr:8983/solr/ckan/select/?q=........: HTTPSConnectionPool(host='solr'. port=8983): Max retries exceed with url: /solr/ckan/select/?q-..... (Caused by SSLError(SSLCertVerificationError[1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:997)')))`
|
Is CKAN able to connect to self-signed certificate of solr and redis? |
|ssl|solr|ckan| |
**HTML**
<h1 class="font-black uppercase text-6xl md:text-8xl text-center py-8 px-4">
<div [ngStyle]="true ? { color: 'red' } : { color: 'yellow' }">home page</div>
</h1>
**ts**
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-home-page',
standalone: true,
imports: [CommonModule],
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent {
}
please check this stack blitz link
[https://stackblitz.com/edit/github-tvhx5n-p1zh8q?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.ts][1]
[1]: https://stackblitz.com/edit/github-tvhx5n-p1zh8q?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.ts |
This is easy to decode manually:
* 30: data type
* 0f: 15 bytes of data follows
* 31: data type
* 0d: 13 bytes of data follows
* 30: data type
* 0b: 11 bytes of data follows
* 06: data type
* 03: 3 bytes of data follows
* 550403: data
* 13: data type
* 04: 4 bytes of data follows
* 46616b65: data: `"Fake"`
Here is an ad hoc parser:
```Perl
$_ = pack('H*', '300f310d300b0603550403130446616B65';
s@^\x30.\x31.\x30.\x06(.)@@s or die;
length >= ord($1) or die;
substr($_, 0, ord($1)) = "";
s@^\x13.@@s or die;
print "$_\n"; #: Fake
```
There are more robust options such as using a DER parser library. |
Мне необходимо вывести таблицу (целиком) из файла Excel в модель Anylogic.
Во время моделирования в файл xlsx будут записываться значения некоторых переменных (таблица изначально непустая). После будут проводиться еще некоторые действия и снова запись в файл xlsx. Нужно чтобы во время всего моделирования на экране было напечатано содержимое таблицы xlsx в реальном времени.
Пытался сделать с помощью табличной функции, но не получается, больше идей нет как ещё можно отобразить таблицу Excel :(
На картинке привёл пример, как я себе представляю таблицу в модели[enter image description here](https://i.stack.imgur.com/mOUeC.png) |
How to display an Excel table in an AnyLogic model? |
|excel|model|anylogic| |
null |
I'm trying to write this code and I'm only partially done. Not sure how to finish it. Tried many times only to get errors. See attachments for partial code.
[code 1][1]
[code 2][2]
program CrazyGame;
#include( "stdlib.hhf" );
static
number1: int32;
number2: int32;
number3: int32;
setCounter: int32 := 0;
gameWon: boolean := false;
eightDetected: boolean := false;
begin CrazyGame;
gameLoop:
// Reset for each game set
mov( false, gameWon );
mov( false, eightDetected );
mov( 0, setCounter );
// Get the first number from the user
stdout.put( "Gimme a number: " );
stdin.get( number1 );
mov( number1, eax ); // Move number1 into eax for arithmetic operations
mov( 10, ebx ); // Move 10 into ebx for division
xor( edx, edx ); // Clear edx before division since div uses edx:eax
div( ebx ); // Divide eax by ebx, the remainder will be in edx
cmp( edx, 8 ); // Compare the remainder (last digit of number1) with 8
je FoundEight1; // If it's 8, jump to FoundEight1 label
// If not, proceed to get the second number
jmp GetNumber2;
FoundEight1:
mov( true, eightDetected ); // Set eightDetected to true
// Here we should proceed to the end of the game loop to check if the game is won or not
jmp EndOfGameCheck;
// The code for GetNumber2, FoundEight2, GetNumber3, and FoundEight3 should follow a similar pattern
// ... continue with the next steps ...
EndOfGameCheck:
// Here, we will write the logic to determine if the game has been won or lost
// ... continue with the end game logic ...
GetNumber2:
stdout.put( "Gimme a number: " );
stdin.get( number2 );
mov( number2, eax ); // Move number2 into eax for arithmetic operations
xor( edx, edx ); // Clear edx before division
div( ebx );
cmp( edx, 8 ); // Compare the remainder (last digit of number2) with 8
je FoundEight2; // If it's 8, jump to FoundEight2 label
// If not, proceed to get the third number
jmp GetNumber3;
FoundEight2:
mov( true, eightDetected ); // Set eightDetected to true
jmp EndOfGameCheck; // Proceed to the end of the game loop to check if the game is won
GetNumber3:
stdout.put( "Gimme a number: " );
stdin.get( number3 );
mov( number3, eax ); // Move number3 into eax for arithmetic operations
xor( edx, edx ); // Clear edx before division
div( ebx ); // Divide eax by ebx, the remainder will be in edx
cmp( edx, 8 ); // Compare the remainder (last digit of number3) with 8
je FoundEight3; // If it's 8, jump to FoundEight3 label
FoundEight3:
mov( true, eightDetected ); // Set eightDetected to true
jmp EndOfGameCheck; // Proceed to the end of the game loop to check if the game is won
End CrazyGame;
this is the program and what the output should be. only hla basic instructions. use jmp and cmp for loops
PROGRAM 6: Crazy 8s Game
Write a program that reads a set of three different numbers. Then by subtracting off tens, determine if any of the values ends in an eight. Continue looping as long as one of the numbers in the set ends in eight. Three sets with a value ending in eight wins the game!
Shown below are sample program dialogues to help you build your program.
Gimme a number: 20
Gimme a number: 12
Gimme a number: 44
Sorry Charlie! You lose the game!
Gimme a number: 58
Gimme a number: 23
Gimme a number: 70
One of them ends in eight!
Gimme a number: 1
Gimme a number: 12
Gimma a number: 28
One of them ends in eight!
Gimme a number: 7
Gimme a number: 8
Gimme a number: 22
One of them ends in eight!
You Win The Game!
Gimme a number: 51
Gimme a number: 51
Gimme a number: 51
Sorry Charlie! You lose The Game!
[1]: https://i.stack.imgur.com/C1TKj.png
[2]: https://i.stack.imgur.com/krK40.png |
I have a form that includes multiple fields, but I encounter an issue when displaying selected input fields and radio buttons such as 'Country' and 'Status of Availability' in a Tablesome table. When I select 'Afghanistan', it appears correctly in Forminator submissions. However, when attempting to display all the data in table format using the Tablesome plugin, the country field displays 'one' or 'two' instead of 'Afghanistan'. Similarly, when selecting 'yes' from the radio button on the 'Status of Availability' field, it displays 'one' instead of 'yes'. The rest of the fields display correctly.
Forminator Form:
[![enter image description here][1]][1]
after submitted tablesome table. where i need the selected value but it displays one or two:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/uNgmX.png
[2]: https://i.stack.imgur.com/Udhvm.png |
My apprise container running on 8000 port. When I try to send an Http Request Im facing below error message
An unhandled exception has occurred while executing the request.
System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (localhost:8000)
I tried to send an http request to apprise, it gives "No connection could be made because the target machine actively refused it. (localhost:8000)" error message |
Apprise: No connection could be made because the target machine actively refused it. (localhost:8000) |
|c#|containers|connection| |
null |
Is there a way to play a notification sound as fast as a button click? I feel like there is a delay of a few hundred milliseconds!
Im using this
```
public void btn_Click(object sender, eventargs e)
{
playExclamation();
}
public void playExclamation()
{ SystemSounds.Exclamation.Play();
}
```
|
You can directly include the html without `include` function like this. This is a working live snippet:
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
</head>
<body>
<div class="container">
<h2><span id="count">0</span></h2>
<button id="decBtn" class="button" onclick="onDec()">-</button>
<button id="incBtn" class="button" onclick="onInc()">+</button>
</div>
<script>
let count = 0;
const counter = document.getElementById("count");
function onDec() {
count = count-1;
counter.textContent = count;
}
function onInc() {
count = count+1;
counter.textContent = count;
}
</script>
</body>
</html>
<!-- end snippet --> |
I am building an CNN model using Tensorflow 2.0 but not using transfer learning. How to predict with new images? I want to load it from my directory and need predictions (classification problem).
My code is given below:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,MaxPool2D,Dropout,Flatten
from tensorflow.keras.callbacks import EarlyStopping
model = Sequential()
model.add(Conv2D(filters = 16,kernel_size = (3,3), input_shape = image_shape, activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))
model.add(Conv2D(filters = 32,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))
model.add(Conv2D(filters = 64,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))
model.add(Flatten())
model.add(Dense(128,activation = 'relu'))
#model.add(Dropout(0.5))
model.add(Dense(1,activation = 'sigmoid'))
model.compile(loss = 'binary_crossentropy',optimizer = 'adam',
metrics = ['accuracy'])
early_stop = EarlyStopping(monitor = 'val_loss',patience = 2)
batch_size = 16
train_image_gen = image_gen.flow_from_directory(train_path,
target_size = image_shape[:2],
color_mode = 'rgb',
batch_size = batch_size,
class_mode = 'binary')
test_image_gen = image_gen.flow_from_directory(test_path,
target_size = image_shape[:2],
color_mode = 'rgb',
batch_size = batch_size,
class_mode = 'binary',
shuffle = False)
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy')>0.97):
print("\nReached 97% accuracy so cancelling training!")
self.model.stop_training = True
callbacks = myCallback()
results = model.fit_generator(train_image_gen,epochs = 85,
validation_data = test_image_gen,
callbacks = [callbacks])
# Let's now save our model to a file
model.save('cell_image_classifier.h5')
# Load the model
model = tf.keras.models.load_model('cell_image_classifier.h5')
model.evaluate_generator(test_image_gen)
#Prediction on image
pred = model.predict_generator(test_image_gen)
predictions = pred > .5
print(classification_report(test_image_gen.classes,predictions))
confusion_matrix(test_image_gen.classes,predictions)
Now externally I want to load the image and get prediction. |
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/O5C27.png
In the provided picture, you have imported LoginComponent, but the component itself is not included in the declarations array. Therefore, it will not be able to utilize imports like LoginRoutingModule or MaterialModule. Is LoginComponent declared in a different module? |
{"OriginalQuestionIds":[36659600],"Voters":[{"Id":5754656,"DisplayName":"Artyer","BindingReason":{"GoldTagBadge":"c++"}}]} |
The snippet below shows a struct (`ckmsgq`) with a function pointer as a member (`func`). Then there is a function (`create_ckmsgq`) that is assigning a value to the function pointer. However the function isn't using the usual syntax for a function pointer parameter. It's just accepting what looks like a normal pointer to a variable, and it has the const keyword (`const void *func`).
```
struct ckmsgq {
...
void (*func)(ckpool_t *, void *);
...
};
ckmsgq_t *create_ckmsgq(ckpool_t *ckp, const char *name, const void *func)
{
...
ckmsgq->func = func;
...
}
static void *ckmsg_queue(void *arg) {
...
ckmsgq->func(ckp, msg->data);
...
}
```
I think I know the answer to what will be my first question, but I would like to hear someone explain it to me (I can't find an explanation anywhere). Why is the syntax of the 2nd function parameter for `create_ckmsgq` not `const void (*func)(ckpool_t *, void *)`?
My guess is that we are only assigning the value and not actually calling the function from this context. However, how would I have known to do that if I where writing this code?
Other question is what is the effect of the `const` keyword on that 2nd parameter for `create_ckmsgq` if it's just a pointer to a function? |
Assign value of function pointer in struct member via a const paramater |
|c|pointers| |
This is how you can do it without FAISS and only langchain tooling, and you can have multiple retriever configurations:
from langchain.chains import RetrievalQA
from langchain.retrievers.merger_retriever import MergerRetriever
from langchain.chat_models import ChatOpenAI
def init_llm(
temperature,
key="",
):
return ChatOpenAI(
model_name='gpt-3.5-turbo-16k',
openai_api_key=key,
temperature=temperature,
model_kwargs={'deployment_id': 'gpt-35-turbo-16k'})
def query_document(
vector_store,
query: str,
question_language: str,
search_type="similarity",
k=5,
temperature=0.0,
chain_type="stuff",
token="",
):
retrievers = [
vector.as_retriever(
search_type=search_type,
search_kwargs={"k": k},
)
for vector in vector_store
]
merged_retrievers = MergerRetriever(retrievers=retrievers)
qa = RetrievalQA.from_chain_type(
llm=init_llm(temperature, token),
chain_type=chain_type,
retriever=merged_retrievers,
chain_type_kwargs={"prompt": custom_prompt(question_language)},
return_source_documents=True
)
return qa({"query": query})
This way, merging the vectors as retrievers, I could merge the vectors in the Dict into one, and even though I use one retriever in the example, the idea is you can merge multiple vector retrievers with their own configuration. |
If I have an array:
[null, 'a', 'b', 'c']
I want to get the first non-null value from the array, in this case "a". How could I go about doing that nice and easily? |
Get first non-null value from a flat array |
The problem you have, I think, is not that there are changes at higher levels of the url, but that the pages you are looking at are constantly changing (for example adding timestamps, and very much more).
The way to resolve this is to look at which lines in a webpage have changed since you last looked. In this way you can take a note of which lines change regularly, and ignore them when looking for a significant change.
The code below looks at a webpage every second, and using difflib prints out a list of the numbers of the lines which have changed since the last look.
import difflib
from urllib.request import urlopen, Request
import time
link = "https://website/"
url = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
r_new = urlopen(url).read().decode('utf-8')
# print(r_new)
while True:
time.sleep(1)
r_old = r_new
url = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
r_new = urlopen(url).read().decode('utf-8')
diff = difflib.context_diff(r_new.splitlines(keepends=True),
r_old.splitlines(keepends=True), n=0)
differences = []
for line in diff:
if (line.startswith('*** ') or line.startswith('--- ')) and len(line) > 5:
differences.append(line.strip(' -*\n'))
if not differences:
differences = "No change"
print(differences)
Here is a sample output:
['470', '470', '575', '575']
['470', '470', '575', '575']
['470', '470', '575', '575']
So in this case lines 470 and 575 change with every reading. If this was the page you were interested in, then all you would need to do is to look for a change in this list.
By the way, don't forget to check your site's robots.txt file to check its policy on web bots.
|
> will it affect my original instance, the one that is currently running?
No.
> I just need to make sure that I will not affect in any way, the original instance, to avoid damages or anything that might affect the operation of the original instance.
Indeed, you have to ensure, to have separate accounting for the separate instances, as otherwise, credits go out faster because you use more resources und then credits are being spend faster and this will affect all running instances. Separate that part first.
Apart from that, in general no. However, keep in mind, that there are no backups or guarantees and you're operating in a running, complex system. The next instance you launch might just be that instance that brings complete AWS down due to some unforeseen configuration bug. Very unlikely, but as the systems are interconnected through and dependent on AWS, you might hit the Jackpot and bring a large share of the US Internet Market down just by chance. |
|powershell|powershell-core|secret-manager| |
I need to get from my Pytorch AutoEncoder the importance it gives to each input variable. I am working with a tabular data set, no images.
My AutoEncoder is as follows:
class AE(torch.nn.Module):
def __init__(self, input_size, hidden_layer, latent_layer):
super().__init__()
self.encoder = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_layer),
torch.nn.ReLU(),
torch.nn.Linear(hidden_layer, latent_layer)
)
self.decoder = torch.nn.Sequential(
torch.nn.Linear(latent_layer, hidden_layer),
torch.nn.ReLU(),
torch.nn.Linear(hidden_layer, input_size)
)
def forward(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
To save unnecessary information, I simply call the following function to get my model:
average_loss, model, train_losses, test_losses = fullAE(batch_size=128, input_size=genes_tensor.shape[1],
learning_rate=0.0001, weight_decay=0,
epochs=50, verbose=False, dataset=genes_tensor, betas_value=(0.9, 0.999), train_dataset=genes_tensor_train, test_dataset=genes_tensor_test)
Where "model" is a trained instance of the previous AutoEncoder:
model = AE(input_size=input_size, hidden_layer=int(input_size * 0.75), latent_layer=int(input_size * 0.5)).to(device)
Well now I need to get the importance given by that model to each input variable in my original "genes_tensor" dataset, but I don't know how. I have researched how to do it and found a way to do it with shap software:
e = shap.DeepExplainer(model, genes_tensor)
shap_values = e.shap_values(
genes_tensor
)
shap.summary_plot(shap_values,genes_tensor,feature_names=features)
The problem with this implementation is the following: 1) I don't know if what I am actually doing is correct. 2) It takes forever to finish, since the dataset contains 950 samples, I have tried to do it with only 1 sample and it takes long enough. The result using a single sample is as follows:
I have seen that there are other options to obtain the importance of the input variables like Captum, but Captum only allows to know the importance in Neural Networks with a single output neuron, in my case there are many.
The options for AEs or VAEs that I have seen on github do not work for me since they use concrete cases, and especially images always, for example:
https://github.com/peterparity/PDE-VAE-pytorch
https://github.com/FengNiMa/VAE-TracIn-pytorch
Is my shap implementation correct?
Edit:
I have run the shap code with only 4 samples and get the following result:
[shap with 4 samples][1]
[1]: https://i.stack.imgur.com/wzcDJ.png
I don't understand why it's not the typical shap summary_plot plot that appears everywhere.
I have been looking at the shap documentation, and it is because my model is multi-output by having more than one neuron at the output. |
|php|arrays|null| |
null |
|sql|sql-server|t-sql|sql-server-2012| |
{"OriginalQuestionIds":[69802194],"Voters":[{"Id":5470544,"DisplayName":"JSON Derulo"},{"Id":8017690,"DisplayName":"Yong Shun"},{"Id":5468463,"DisplayName":"Vega","BindingReason":{"GoldTagBadge":"angular"}}]} |
If `chkconfig` is still available (it seems on ESXi v8), you can type this command :
```shell
$ chkconfig --list | grep -w on | sort
DCUI on
ESXShell on
apiForwarder on
cdp on
clusterAgent on
dcbd on
dellism on
drivervm-init on
envoy on
esxTokenCPS on
........................on
``` |
I have spend a reasonable part of my career writing engineering simulation software but as these pieces of code have only been used internally I have never written an interface and have no experience of GUIs at all. I am now thinking of making my software more user friendly and would like to make a drag and drop interface where components a can be dragged from a menu of some sort, probably something like a tree and dropped onto a palette and linked up into a system. An example of a commercial interface might be modelica, simcape or GT suite for example. I'd be grateful for any advice about what the easiest language to use would be, or any recommendations for books or tutorials to get me started please?
I haven't coded anything yet as I'm not sure where to start but I am going to write some simple dragging and dropping of images in VB.NET as that is the language I am most familiar with. |
That regularly/predictably formatted string is a "**AWS authorization header**" or a "**AWS Signature Version 4 header**".
You can use `sscanf()`: ([Demo][1])
$str = "AWS-HMAC-SHA256 Credential=eyJhbGciOiJIUzI1NiIsIngtc3MiOjEy/20160911/cn/user-service/request,SignedHeaders=host;x-aws-date, Signature=d9ee2d43f2067e4b8857f15fa8fff27820051d95a4ec31e93be866f201e0797a";
var_export(
sscanf(
$str,
'AWS-HMAC-SHA256 Credential=%[^,],SignedHeaders=%[^,], Signature=%[^,]'
)
);
There is an alternative syntax whereby you provide the reference variables to populate with the matched values. ([Demo][2])
sscanf(
$str,
'AWS-HMAC-SHA256 Credential=%[^,],SignedHeaders=%[^,], Signature=%[^,]',
$credentials,
$headers,
$signature
);
var_dump($credentials, $headers, $signature);
---
To create an associative array using the exact key and value pairs from the almost-ini-formatted text, use `parse_ini_string()` after tweaking the format into separate lines. This will be more forgiving of optional spaces around separators or differently ordered components. ([Demo][3])
var_export(
parse_ini_string(
preg_replace('/[, ]+/', "\n", $str)
)
);
Output:
array (
'Credential' => 'eyJhbGciOiJIUzI1NiIsIngtc3MiOjEy/20160911/cn/user-service/request',
'SignedHeaders' => 'host',
'Signature' => 'd9ee2d43f2067e4b8857f15fa8fff27820051d95a4ec31e93be866f201e0797a',
)
---
Using `preg_match_all()` is a little too cumbersome with named capture groups; and `preg_split()` will be a relative chore to ensure key-value relationships.
[1]: https://3v4l.org/1aaUr
[2]: https://3v4l.org/Vv7UQ
[3]: https://3v4l.org/kT4eQ |