instruction stringlengths 0 30k ⌀ |
|---|
|object| |
You need:
su - username -c 'echo "$@"' -- bash "$@"
With [tag:php]:
su - www-data -s /bin/bash -c 'php /tmp/test.php <<< "$@"' -- bash "$@"
**/tmp/test.php**:
```
<?php
$f = file_get_contents("php://stdin", "r");
echo $f;
?>
```
---
The difference between `$@` and `$*`: Without quotes (don't do this!), there is no difference. With double quotes, `"$@"` expands to each positional parameter as its own argument: `"$1" "$2"` ..., while `"$*"` expands to the single argument `"$1c$2c..."`, where '`c`' is the first character of `IFS`. You almost always want `"$@"` (QUOTED!). The same goes for arrays: `"${array[@]}"`. |
I am trying to get a virtual machine to send a string/list to a second virtual machine and then have the second virtual machine return a string to the first virtual machine.
To do this, I have decided to go with a Python socket server and client script.
The virtual machines are both hosted via Oracle. Here is the code:
Server:
import socket
SERVER_IP = "localhost"
SERVER_PORT = 8000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((SERVER_IP, SERVER_PORT))
server_socket.listen(1)
print("Server listening on", SERVER_IP, "port", SERVER_PORT)
client_socket, client_address = server_socket.accept()
print("Connection from:", client_address)
data = client_socket.recv(1024)
print("Received data:", data.decode())
response = "Hello from the server!"
client_socket.send(response.encode())
client_socket.close()
server_socket.close()
Client:
import socket
SERVER_IP = "(Server Public IP Address)"
SERVER_PORT = 8000
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_IP, SERVER_PORT))
data = "Hello from the client!"
client_socket.send(data.encode())
response = client_socket.recv(1024)
print("Response from server:", response.decode())
client_socket.close()
I have opened up the port 8000 (tcp) with this tutorial:
https://www.youtube.com/watch?v=6Vgzvh2jqRQ
I have tried making the "localhost" with the actual public ip address
OSError: [Errno 99] Cannot assign requested address
I have made both machines ping each other successfully.
using ping (public ip)
Additionally, I tried to allow all protocols, but then when i run the code,
OSError: [Errno 113] No route to host
When running the code, the code does not show any indication of connection.
(with specifying src:8000 dst:8000 ip protcol" tcp)
I have no idea what to do
|
I am trying to do tokenization as part of my model, as it will reduce my CPU usage, and RAM, on the other hand, it will utilize my GPU more. But I am facing an issue saying `ValueError: as_list() is not defined on an unknown TensorShape.`
I have created a `Layer` called `TokenizationLayer` which takes care of the tokenization, and defines as:
```
class TokenizationLayer(Layer):
def __init__(self, max_length, **kwargs):
super(TokenizationLayer, self).__init__(**kwargs)
self.max_length = max_length
self.tokenizer = Tokenizer()
def build(self, input_shape):
super(TokenizationLayer, self).build(input_shape)
def tokenize_sequences(self, x):
# Tokenization function
return self.tokenizer.texts_to_sequences([x.numpy()])[0]
def call(self, inputs):
# Use tf.py_function to apply tokenization element-wise
sequences = tf.map_fn(lambda x: tf.py_function(self.tokenize_sequences, [x], tf.int32), inputs, dtype=tf.int32)
# Masking step
mask = tf.math.logical_not(tf.math.equal(sequences, 0))
return tf.where(mask, sequences, -1) # Using -1 as a mask value
def compute_output_shape(self, input_shape):
return (input_shape[0], self.max_length) # Use self.max_length instead of trying to access shape
```
But it keeps giving me an error saying `as_list() is not defined on an unknown TensorShape.`
Here is the complete code, if you need it:
```
import tensorflow as tf
from tensorflow.keras.layers import Layer, Input, Embedding, LSTM, Dense, Concatenate
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
class TokenizationLayer(Layer):
def __init__(self, max_length, **kwargs):
super(TokenizationLayer, self).__init__(**kwargs)
self.max_length = max_length
self.tokenizer = Tokenizer()
def build(self, input_shape):
super(TokenizationLayer, self).build(input_shape)
def tokenize_sequences(self, x):
# Tokenization function
return self.tokenizer.texts_to_sequences([x.numpy()])[0]
def call(self, inputs):
# Use tf.py_function to apply tokenization element-wise
sequences = tf.map_fn(lambda x: tf.py_function(self.tokenize_sequences, [x], tf.int32), inputs, dtype=tf.int32)
# Masking step
mask = tf.math.logical_not(tf.math.equal(sequences, 0))
return tf.where(mask, sequences, -1) # Using -1 as a mask value
def compute_output_shape(self, input_shape):
return (input_shape[0], self.max_length) # Use self.max_length instead of trying to access shape
# Build the model with the custom tokenization layer
def build_model(vocab_size, max_length):
input1 = Input(shape=(1,), dtype=tf.string)
input2 = Input(shape=(1,), dtype=tf.string)
# Tokenization layer
tokenization_layer = TokenizationLayer(max_length)
embedded_seq1 = tokenization_layer(input1)
embedded_seq2 = tokenization_layer(input2)
# Embedding layer for encoding strings
embedding_layer = Embedding(input_dim=vocab_size, output_dim=128, input_length=max_length)
# Encode first string
lstm_out1 = LSTM(64)(embedding_layer(embedded_seq1))
# Encode second string
lstm_out2 = LSTM(64)(embedding_layer(embedded_seq2))
# Concatenate outputs
concatenated = Concatenate()([lstm_out1, lstm_out2])
# Dense layer for final output
output = Dense(1, activation='relu')(concatenated)
# Build model
model = Model(inputs=[input1, input2], outputs=output)
return model
string1 = "hello world"
string2 = "foo bar baz"
max_length = max(len(string1.split()), len(string2.split()))
model = build_model(vocab_size=1000, max_length=max_length)
model.summary()
labels = tf.random.normal((1, 5))
model.compile(optimizer='adam', loss='mse')
model.fit([tf.constant([string1]), tf.constant([string2])], labels, epochs=10, batch_size=1, validation_split=0.2)
``` |
Getting `ValueError: as_list() is not defined on an unknown TensorShape.` when trying to tokenize as part of the model |
|python|numpy|tensorflow|keras|tokenize| |
At first, fetch all data, then write this code :
$total_quantity = array_sum(array_column($carts, "quantity"));
Here $carts are all cart data and the other one is the counting column, which you want to count. |
null |
It looks like you've been shifting things around since [last time](https://stackoverflow.com/a/78097819/85371). Some of the shifts have caused confusion.
E.g.:
using Section = std::map<Key, Value>;
struct IniSection {
std::string name;
Section pair;
};
There's a strong disconnect between the member name `pair` and its type `Section`.
Now instead of `std::vector<IniSection>` I would 100% use an associative container like I showed before:
using IniFile = std::multimap<Key, Section>;
But let's for the moment assume that you really really want to retain the input order just for sections (but not for keys, apparently). The logical change would be
using IniFile = std::vector<std::pair<Key, Section> >;
Introducing your own type `IniSection` and `IniFile` means you have to teach Qi how to propagate attributes to them. I can show you that, but first let's keep it simple:
```c++
namespace client {
using Key = std::string;
using Value = std::string;
using Entries = std::map<Key, Value>;
using Section = std::pair<Key, Entries>;
using IniFile = std::vector<Section>;
}; // namespace client
```
However, somehow your `value` and `key` rules have dropped their attributes. This quite simply means that they cannot expose their attribute at all:
qi::rule<Iterator> value;
qi::rule<Iterator> key;
Therefore no automatic propagation will occur anymore, because there's nothing to propagate. By definition all your data structures are incompatible with "no attributes". Restoring those first from my previous answer:
// lexemes
qi::rule<Iterator, Key()> key;
qi::rule<Iterator, Value()> value;
Now you include
#include <boost/fusion/include/adapt_struct.hpp>
That also means you *stopped* including
#include <boost/fusion/include/std_pair.hpp>
Let's also restore that from my previous answer:
#include <boost/fusion/adapted.hpp> // includes both
At this point [things compile again](https://coliru.stacked-crooked.com/a/103bd80958733f4b), but it's not parsing the entire section anymore. Looking more closely, that's because you dropped the skipper from the `IniSection` and `KVP` rules. (WHY?)
qi::rule<Iterator, IniSection()> section;
qi::rule<Iterator, KVP()> pair;
Restoring that from my previous answer, we get a full parse:
**[Live On Coliru](https://coliru.stacked-crooked.com/a/28bd0a3165c91511)**
```c++
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <map>
namespace client {
using Key = std::string;
using Value = std::string;
using Entries = std::map<Key, Value>;
using Section = std::pair<Key, Entries>;
using IniFile = std::vector<Section>;
}; // namespace client
namespace client {
namespace qi = boost::spirit::qi;
template <typename Iterator> struct ini_grammar : qi::grammar<Iterator, IniFile()> {
ini_grammar() : ini_grammar::base_type(start) {
skipper = qi::blank | '#' >> *(qi::char_ - qi::eol);
key = +qi::char_("a-zA-Z_0-9");
value = *(qi::char_ - qi::eol);
entry = key >> '=' >> value;
section = '[' >> key >> ']' >> +qi::eol >> *(entry >> +qi::eol);
file = *section;
start = qi::skip(copy(skipper))[file];
}
using Skipper = qi::rule<Iterator>;
using Entry = std::pair<Key, Value>;
Skipper skipper;
qi::rule<Iterator, IniFile()> start;
qi::rule<Iterator, IniFile(), Skipper> file;
qi::rule<Iterator, Section(), Skipper> section;
qi::rule<Iterator, Entry(), Skipper> entry;
qi::rule<Iterator, Key()> value;
qi::rule<Iterator, Value()> key;
};
} // namespace client
int main() {
for (std::string const input : {
R"([Section]
key1 = value1
key2 = value2
[Section10]
key3 = value3
[Section3] # let's see that order is preserved
key4 = value4
)",
}) {
std::cout << "-------------------------\n";
using It = std::string::const_iterator;
client::ini_grammar<It> grammar;
client::IniFile iniFile;
It iter = input.begin(), end = input.end();
bool r = parse(iter, end, grammar, iniFile);
if (r) {
std::cout << "Parsing succeeded\n";
for (auto const& [name, entries] : iniFile) {
std::cout << "[" << name << "]\n";
for (auto const& [k,v] : entries) {
std::cout << k << " = " << v << "\n";
}
}
} else {
std::cout << "Parsing failed\n";
}
if (iter!=end) {
std::cout << "Stopped at position: " << std::distance(input.begin(), iter) << std::endl;
std::cout << "\nRemaining input unparsed:\n" << std::string(iter, end);
}
}
}
```
Printing
-------------------------
Parsing succeeded
[Section]
key1 = value1
key2 = value2
[Section10]
key3 = value3
[Section3]
key4 = value4
## Side Notes
You no longer even checked the parse result (`r`) in main. Nor do you incorporate the [check for `eoi`](https://stackoverflow.com/questions/78097580/problem-parsing-ini-section-using-boost-spirit#comment137683813_78097819) into the parser. Adding those finishing touches:
**[Live On Coliru](https://coliru.stacked-crooked.com/a/5dce96b9c448f73b)**
```c++
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <map>
namespace client {
using Key = std::string;
using Value = std::string;
using Entries = std::map<Key, Value>;
using Section = std::pair<Key, Entries>;
using IniFile = std::vector<Section>;
}; // namespace client
namespace client {
namespace qi = boost::spirit::qi;
template <typename Iterator> struct ini_grammar : qi::grammar<Iterator, IniFile()> {
ini_grammar() : ini_grammar::base_type(start) {
skipper = qi::blank | '#' >> *(qi::char_ - qi::eol);
key = +qi::char_("a-zA-Z_0-9");
value = *(qi::char_ - qi::eol);
entry = key >> '=' >> value >> (+qi::eol | qi::eoi);
section = '[' >> key >> ']' >> (+qi::eol | qi::eoi) >> *entry;
file = *section;
start = qi::skip(copy(skipper))[ //
file >> qi::eoi //
];
}
private:
using Skipper = qi::rule<Iterator>;
using Entry = std::pair<Key, Value>;
Skipper skipper;
qi::rule<Iterator, IniFile()> start;
qi::rule<Iterator, IniFile(), Skipper> file;
qi::rule<Iterator, Section(), Skipper> section;
qi::rule<Iterator, Entry(), Skipper> entry;
qi::rule<Iterator, Key()> value;
qi::rule<Iterator, Value()> key;
};
} // namespace client
int main() {
using It = std::string::const_iterator;
static client::ini_grammar<It> const grammar;
for (std::string const input :
{
R"([Section]
key1 = value1
key2 = value2
[Section10]
key3 = value3
[Section3] # let's see that order is preserved
key4 = value4
)",
R"()",
R"(oops=bad)",
}) //
{
std::cout << "-------------------------\n";
client::IniFile iniFile;
if (parse(input.begin(), input.end(), grammar, iniFile)) {
std::cout << "Parsing succeeded\n";
for (auto const& [name, entries] : iniFile) {
std::cout << "[" << name << "]\n";
for (auto const& [k,v] : entries) {
std::cout << k << " = " << v << "\n";
}
}
} else {
std::cout << "Parsing failed\n";
}
}
}
```
Printing the expected output
-------------------------
Parsing succeeded
[Section]
key1 = value1
key2 = value2
[Section10]
key3 = value3
[Section3]
key4 = value4
-------------------------
Parsing succeeded
-------------------------
Parsing failed
## SUMMARY
You are doing good toying with the code to fit your needs as well as to "make it your own", i.e. understand it fully. However, along the way you have accrued a combination of many interfering changes that together made it impossible for yourself to see what went wrong. I have a suspicion, one thing led to another¹ and here you are.
The lesson there is: by all means go and tweak the code. A programmer cannot function if they fear to touch the code. However, help yourself with two basic principles:
1. have test cases
1. change only one thing at a time
1. check the test cases at *each* case.
This implies you can *never* have a change that fails to compile (you just undo that change) and will *immediately* spot when you break something. That doesn't necessarily mean you have to undo the change. Perhaps you needed to compensate for a change somewhere else in the code. Regardless, do not change anything unrelated until all tests pass again.
This is the Way Of The Enlightened Programmer.
----
¹ _and perhaps you started accepting some suggestions from Copilot?_ |
If you want to make sure specific props are not defined you can define them with `prop_name?: never`.
So for the example in the question it would become:
function dbQuery(): User[] {
return [];
}
function getAll(): GetAllUserData[] {
return dbQuery(); // Error: Type 'User[]' is not assignable to type 'GetAllUserData[]'
}
class User {
id: number = 0;
name: string = "";
}
class GetAllUserData {
id: number = 0;
name?: never;
}
[TS Playground link][1]
And if you're working with types instead of directly classes and would like to extend a type that uses `never` so you can allow that prop, you can use `Omit<>` to exclude that prop. That also allows you to 'overwrite' that prop with a concrete type:
type t1 = {
prop1: string;
prop2?: never;
}
type t2 = Omit<t1, 'prop2'> & {
prop2: string;
}
// No error
const obj1: t1 = {
prop1: 'foo',
}
// Error for extra prop
const obj2: t1 = {
prop1: 'foo',
prop2: 'bar' // Type 'string' is not assignable to type 'undefined'
}
// Error for missing prop
const obj3: t2 = { // Property 'prop1' is missing in type '{ prop2: string; }'
prop2: 'bar',
}
// No error
const obj4: t2 = {
prop1: 'foo',
prop2: 'bar',
}
[TS Playground link][2]
[1]: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAEwEYEUQFMBOBPACgEoAuRAVQGdcBtAXUQG8BYAKEQ8RyyhByXoBuNgF82bUJFgJEAcx4BBADZLiZAOKKVVXABEAhlH30mbTlx58kaTLkJFhrMazYQl%20ypQrUcp9pxhkMjAQAFtUXEQAXkQABkdzMH1QrDJKKBwYMFloxAAiPMdnV3dPRE0oZSUdHAMjP3NA4LCI3xj4s04klIB%20YKwAN1witiA
[2]: https://www.typescriptlang.org/play?#code/C4TwDgpgBMCMUF4oG8CwAoKUwCcD2YsAXFAM7A4CWAdgOYDcGWuBATAPwnUQBuEOjdAF8MGUJBitEUAPIBbSsAA8cADRQA5CzCsNAPigAyFE2z4dJclTqCR6DAHoHUAHJ4o-fDgwBjPNXIoPAAjACtiGHgkNEwzAgiNADM8PA1VDDtHZwBRHC8oZJwPAA8KAEM4sF9-QJDQ1hI4aRjmcwTk1PTY7QbNYLKcDSgnKAAVcGgNKxpaIcpSKGo8YCgy0lJKWmoy4IAbaGB3cUmAV2oAEwhEmghzjQzRdBHc-MKoBXWZyuqAlbqAZkaUmiw2cAAVzPxQJptLA5gsPhs6FAaDAJppkJVetMbFAhPduuZehp+oMupkns43B48nhvOg-L8gmEACxA5qmWEkJIpNKconc0l84RAA |
I'm wondering if anybody has used the react-i18next library with the latest React Router v6 and the `createBrowserRouter()`.
I'm experiencing the following warning in my web application:
[](https://i.stack.imgur.com/kLw9D.png)
In React Router `v6` the suggested router is `createBrowserRouter()` which needs to know all the routes ahead of time. My file structure has the routes in the `index.ts` of each page's directory and in that `index.ts` file I'm defining some meta data about the page.
The meta data is a `const` and includes the name of the page which is wrapped in `i18n.t()` which is causing warnings about using the function before the library has been initialized. I'm wondering if there are any best practices that should be followed in scenarios like this.
I'm hoping somebody has done this before or can maybe point me in the right direction?
The pseudo file structure/code looks like similar to this (I didn't define all the objects properly):
**main.tsx**
```
import routes from 'routes.ts'
const router = createBrowserRouter([
...router config and routes
])
ReactDOM.createRoot(document.getElementById('root'!).render(
<RouteProvider router=router/>
))
```
**routes.ts**
```
import routes1 from '.page1'
import routes2 from '.page2'
const routes = [
routes1,
routes2,
...
]
export default routes;
```
**page1/index.ts**
```
const metaData = {
title: i18n.t('Page Title')
...
}
const routes = [
{route with meta Data}
...
]
export default routes;
```
1. I've considered changing the `const metadata = [...]` to a function like `getPageData(i18n)`.
2. I've considered changing the routes so each page has a `getRoutes()` function that is executed after i18n has been initialized. And then I would call `getAllRoute()` in the `main.ts` where `createBrowserRouter()` is defined.
Edit: Here is a CodeSandbox [minimal reproducible example][1] as requested. If you inspect developer tools you will see the issue warning from above.
Edit: [I think I found a solution][2]
[1]: https://codesandbox.io/p/sandbox/i18next-react-router-3cgx5t?file=%2Fsrc%2FApp.tsx%3A10%2C13&layout=%257B%2522sidebarPanel%2522%253A%2522EXPLORER%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522cltop2l9f0006356itkrvq1i2%2522%252C%2522sizes%2522%253A%255B100%252C0%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522cltop2l9f0002356i1702ntn1%2522%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522cltop2l9f0003356i34myqyjx%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522cltop2l9f0005356in747ufrk%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B50%252C50%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522cltop2l9f0002356i1702ntn1%2522%253A%257B%2522id%2522%253A%2522cltop2l9f0002356i1702ntn1%2522%252C%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522cltopu8470002356ihhrw2pha%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522FILE%2522%252C%2522initialSelections%2522%253A%255B%257B%2522startLineNumber%2522%253A10%252C%2522startColumn%2522%253A13%252C%2522endLineNumber%2522%253A10%252C%2522endColumn%2522%253A13%257D%255D%252C%2522filepath%2522%253A%2522%252Fsrc%252FApp.tsx%2522%252C%2522state%2522%253A%2522IDLE%2522%257D%255D%252C%2522activeTabId%2522%253A%2522cltopu8470002356ihhrw2pha%2522%257D%252C%2522cltop2l9f0005356in747ufrk%2522%253A%257B%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522cltop2l9f0004356ijc5g1d4j%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522UNASSIGNED_PORT%2522%252C%2522port%2522%253A0%252C%2522path%2522%253A%2522%252F%2522%257D%255D%252C%2522id%2522%253A%2522cltop2l9f0005356in747ufrk%2522%252C%2522activeTabId%2522%253A%2522cltop2l9f0004356ijc5g1d4j%2522%257D%252C%2522cltop2l9f0003356i34myqyjx%2522%253A%257B%2522tabs%2522%253A%255B%255D%252C%2522id%2522%253A%2522cltop2l9f0003356i34myqyjx%2522%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Afalse%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A15%257D
[2]: https://codesandbox.io/p/sandbox/i18next-react-router-forked-lfqm6q?file=%2Fsrc%2Findex.tsx%3A15%2C45-16%2C12&layout=%257B%2522sidebarPanel%2522%253A%2522EXPLORER%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522cltoqb1qt0006356i82l75sxj%2522%252C%2522sizes%2522%253A%255B100%252C0%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522cltoqb1qt0002356i0xbn1w42%2522%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522cltoqb1qt0003356itg826egn%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522cltoqb1qt0005356i3y2ngoc3%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B52.02310477613656%252C47.97689522386344%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522cltoqb1qt0002356i0xbn1w42%2522%253A%257B%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522cltoqb1qt0001356iqr4uujpo%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522FILE%2522%252C%2522filepath%2522%253A%2522%252Fsrc%252Findex.tsx%2522%252C%2522state%2522%253A%2522IDLE%2522%252C%2522initialSelections%2522%253A%255B%257B%2522startLineNumber%2522%253A15%252C%2522startColumn%2522%253A45%252C%2522endLineNumber%2522%253A16%252C%2522endColumn%2522%253A12%257D%255D%257D%255D%252C%2522id%2522%253A%2522cltoqb1qt0002356i0xbn1w42%2522%252C%2522activeTabId%2522%253A%2522cltoqb1qt0001356iqr4uujpo%2522%257D%252C%2522cltoqb1qt0005356i3y2ngoc3%2522%253A%257B%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522cltoqb1qt0004356ipuhft98k%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522UNASSIGNED_PORT%2522%252C%2522port%2522%253A0%252C%2522path%2522%253A%2522%252F%2522%257D%255D%252C%2522id%2522%253A%2522cltoqb1qt0005356i3y2ngoc3%2522%252C%2522activeTabId%2522%253A%2522cltoqb1qt0004356ipuhft98k%2522%257D%252C%2522cltoqb1qt0003356itg826egn%2522%253A%257B%2522tabs%2522%253A%255B%255D%252C%2522id%2522%253A%2522cltoqb1qt0003356itg826egn%2522%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Afalse%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A15%257D
Edit: Here's an example route that's more descriptive
```
const routes: RouteObject[] = [{
path: "/example",
handle: {
// I'm not sure how to use the translate function properly below
text: t("Example Page"),
crumb: (data: object) => ({ ...data, text: t("Example Page") }),
},
element: <ExamplePage />,
...
}]
export default routes;
```
**TLDR:** I have strings in the `handle` key of my `RouteObjects[]` that need to use the react-i18next translate function but I'm not sure the correct way to wait for the react-i18n to finish initializing before using it. |
I am trying to make a new column which will take the first letter from the column and then filter the ones that have letter A
ChatGPT totally give me another way but I just want to understand what is wrong with my logic
'''Select Code,
FROM WIR
Where Code = 'A'
(Select Subject,
Zone_Location,
Left (Final_Status,1) As Code
from `poised-shift-415007.WIR.WIR_CEC` As WIR)''' |
Non Blocking Retry Support for KafkaStreams |
|spring-kafka|apache-kafka-streams| |
null |
Although it seems like Bash allows putting colons in function names, [this behaviour is not standardized by POSIX][2.9.5 Function Definition Command]:
> The function is named *fname*; the application shall ensure that it is a name (see XBD [*Name*][3.235 Name]) .... An implementation may allow other characters in a function name as an extension.
[3.235 Name] says it's:
> a word consisting solely of underscores, digits, and alphabetics from the [portable character set][6.1 Portable Character Set].
[2.9.5 Function Definition Command]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05
[3.235 Name]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235
[6.1 Portable Character Set]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap06.html#tag_06_01 |
null |
Here is a significant starting point for how to do this using [GNU awk](https://www.gnu.org/software/gawk/manual/gawk.html) for arrays of arrays, `gensub()`, `PROCINFO["sorted_in"]`, and `\S/\s`:
$ cat tst.sh
#!/usr/bin/env bash
awk '
function grade_to_points(grade, grade2pts,dfltPts) {
grade2pts["A"] = 4
grade2pts["A-"] = 3.7
grade2pts["B+"] = 3.3
grade2pts["B"] = 3
grade2pts["B-"] = 2.7
grade2pts["C+"] = 2.3
grade2pts["C"] = 2
grade2pts["D"] = 1
grade2pts["F"] = 0
dfltPts = -1 # for subjects with no grade
return ( grade in grade2pts ? grade2pts[grade] : dfltPts )
}
NR == FNR {
studId = $1
studName = gensub(/^\S+\s+/,"",1)
studId2Name[studId] = studName
next
}
FNR == 1 {
courseSubj = $2
courseYear = $3
courseSem = $4
next
}
{
studId = $1
grade = $2
grades[studId][courseSubj][courseYear][courseSem] = grade
}
END {
PROCINFO["sorted_in"] = "@ind_str_asc"
for ( id in grades ) {
totPoints = totSubjs = 0
print "Transcript for", id, studId2Name[id]
for ( subj in grades[id] ) {
totSubjs ++
for ( year in grades[id][subj] ) {
for ( sem in grades[id][subj][year] ) {
grade = grades[id][subj][year][sem]
totPoints += grade_to_points(grade)
print subj, year, "Sem", sem, grade
}
}
}
gpa = ( totSubjs ? totPoints / totSubjs : 0 )
printf "GPA for %d subjects %0.2f\n\n", totSubjs, gpa
}
}
' student.dat COMP101121S2.dat COMP101122S1.dat COMP241122S1.dat COMP243222S2.dat
<p>
$ ./tst.sh
Transcript for 1223 bob
COMP1011 2021 Sem 2 F
COMP1011 2022 Sem 1 B
COMP2411 2022 Sem 1 C+
COMP2432 2022 Sem 2
GPA for 3 subjects 1.43
Transcript for 1224 kevin
COMP1011 2022 Sem 1 B+
GPA for 1 subjects 3.30
Transcript for 1225 stuart
COMP1011 2022 Sem 1 B
GPA for 1 subjects 3.00
Transcript for 1234 john
COMP1011 2021 Sem 2 B
COMP2411 2022 Sem 1 B
GPA for 2 subjects 3.00
Transcript for 1235 mary
COMP1011 2021 Sem 2 B+
COMP2411 2022 Sem 1 B
COMP2432 2022 Sem 2
GPA for 3 subjects 1.77
Transcript for 1236 peter
COMP1011 2021 Sem 2 A
COMP2411 2022 Sem 1 A
COMP2432 2022 Sem 2
GPA for 3 subjects 2.33
Transcript for 1237 david
COMP2432 2022 Sem 2
GPA for 1 subjects -1.00
Transcript for 1238 alice
COMP1011 2022 Sem 1 C+
GPA for 1 subjects 2.30
It doesn't do what you want regarding ignoring failed grades if there's a retake or ignoring subjects with no grade (got to leave something for you to do!) but hopefully you'll find the above much easier to understand and modify to do whatever it is you want to do than your existing bash script. If you can't figure out how to do it yourself you can always ask a new question using an awk script as your code sample instead of your bash script. |
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"`
|
I'm trying to use drag and drop in Genexus and I can drag an element from my grid to an external variable. Now I need to do the opposite, drag an external variable and drop it in a specific grid (free style grid) cell.
I tried to set
```
Event Grid1.Drop(&SDTDrag)
&text = &SDTDrag.Turno
msg("drop on " + &index.ToString())
Endevent
```
where &text and &index are on the grid
When I drop the object the index is always 1 (the first row of the grid), regardless of where I dropped it and it's always the first &text variable to be set
Since it's a Free Style Grid I also tried to put a Table inside it and use its drop event, but in this case the event is not even launched, like there is not a drop event linked to it
```
Event TableInternal.Drop(&SDTDrag)
&text = &SDTDrag.Turno
msg("drop on " + &index.ToString())
Endevent
```
Is it possible to do what I want here? Drag an element and drop it into a specific cell of a free style grid? |
Drag and Drop in a specific row of a grid in Genexus |
|genexus| |
just to share my experienced on this issue on composer error # 1.
What I did was to get rid all composer inside the registry editor. It solved my problem. |
{"Voters":[{"Id":874188,"DisplayName":"tripleee"},{"Id":3832970,"DisplayName":"Wiktor Stribiżew"},{"Id":839601,"DisplayName":"gnat"}]} |
Well this would be painful as well since, if you don't have metro running each single change you make in the javascript code base, won't be automatically refresh to the device.
react-native bundle --platform ios --entry-file ./index.js --bundle-output ios/main.jsbundle --assets-dest ios
This command will make js bundle and if metro is not connected the iOS Simulator will take this js bundle as main one.
Again you will have to run this command even if you change a 'string' in your js code otherwise it won't reflect the change. |
You first create a new environment, then want to install Jupyter on top of it right away. What made you opt for not including Jupyter in your initial environment requirements, at the time of creation ? Doing so leverages the conda environment solver to figure your optimal configuration, as shown below.
The following proceeds without error: (your requirements plus Jupyter)
`conda create -n testenv pandas numpy matplotlib scikit-learn jupyter`
This proceeded without error and installed:
> conda list python # 3.10.13
> conda list jupyter # 1.0.0
etc..
So if you want to stick to Jupyter (as opposed to moving on to JupyterLab), indeed it looks like you should keep your Python at 3.10, but with this method, you can know it for yourself, instead of having to ask for advice.
Generally, attempting to install a (slightly old) Python module *after* the environment has been created (with up-to-date modules) may cause such problems. Related because same type of problem and solution: https://stackoverflow.com/q/77508384/12846804 |
You can execute linux commands within a php script - all you have to do is put the command line in backticks (`).
And also concentrate on `exec()`, this and `shell_exec()`. |
null |
I have a trouble. please help me.
My config
```java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
@Order(0)
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(registry -> registry
.requestMatchers("/mypage").hasRole("USER")
.requestMatchers("/messages").hasRole("MANAGER")
.requestMatchers("/config").hasRole("ADMIN")
.requestMatchers("/").permitAll()
.anyRequest().authenticated());
http.formLogin(Customizer.withDefaults());
http.logout(config -> config.logoutSuccessUrl("/"));
http.userDetailsService(userDetailsService);
return http.build();
}
@Order(1)
@Bean
SecurityFilterChain resource(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(registry -> registry
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.anyRequest().authenticated());
return http.build();
}
```
login.html
```html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:fragment="header">
<nav class="navbar navbar-dark sticky-top bg-dark ">
<div class="container">
<a class="text-light" href="#"><h4>Core Spring Security</h4></a>
<ul class="nav justify-content-end align-items-center">
<li sec:authorize="!isAnonymous()" class="nav-item">
<div class="text-light" th:text="${#authentication.name}">
The value of the "name" property of the authentication object should appear here.
</div>
</li>
<li sec:authorize="!isAuthenticated()" class="nav-item">
<a class="nav-link text-light" th:href="@{/login}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" href="/">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" th:href="@{/users}">Signup</a>
</li>
<li sec:authorize="isAuthenticated()" class="nav-item">
<a class="nav-link text-light" th:href="@{/logout}">Logout</a>
</li>
</ul>
</div>
</nav>
</div>
</html>
```
[This is an error page](https://i.stack.imgur.com/4aFJq.png)
I found that redirectUrl is css path but don't know why.
[This is a debugging screen](https://i.stack.imgur.com/w9b8f.png)
(AbstractAuthenticationFilter-> successHandler.onAuthenticaionSucess
and the successHandler instance is SavedRequestAwareAuthenticationSuccessHandler)
When combining the two settings, it works fine.
I heard that using `permitAll()` to static resource is alright
because the latest spring security doesn't access a `HttpSession`.
Is there a way that works well when using permitAll()
and separating the settings of static resources?
After logging in, I want to return to the page I was previously on. not css path. |
Thank you all for checking on this. I've found the answer and would like to share it with you for your benefit.
We have to make sure to give the correct name for the firewall to be turned on in the compute instance.
Make sure to use the target tags. It will help turn on the http and https traffic firewall rules.[enter image description here][1]
resource "google_compute_firewall" "default-allow-http" {
name = "default-allow-http"
network = "default"
allow {
protocol = "tcp"
ports = ["80"]
}
source_ranges = ["0.0.0.0/0"]
target_tags = ["http-server"]
}
resource "google_compute_firewall" "default-allow-https" {
name = "default-allow-https"
network = "default"
allow {
protocol = "tcp"
ports = ["443"]
}
source_ranges = ["0.0.0.0/0"]
target_tags = ["https-server"]
}
}
[1]: https://i.stack.imgur.com/u3EUq.png |
Spring Integration and Spring Batch transaction manager collision |
|spring-boot|spring-batch|spring-integration|spring-jdbc| |
null |
* When you iterate over `a`, `b` and `c` you get one element at a time in `aa`, `bb` and `cc`, so those are the variables you should use, but they are not arrays; they are scalars, so just use `"$aa"`, `"$bb"` and `"$cc"`.
* You need to remove the spaces around `=` in your assignments.
* Use `${a[@]}` etc. in the loops over the elements in the arrays.
Example (with `command` replaced with `echo`):
```bash
#!/bin/bash
a=(1 2 3 4)
b=('A' 'B' 'C')
c=('x' 'y')
for aa in "${a[@]}"; do
for bb in "${b[@]}"; do
for cc in "${c[@]}"; do
echo "$aa" "$bb" "$cc"
done
done
done
``` |
A relative recent re-occurrence of this issue was released as part of https://github.com/git/git/commit/7ee1af8cb8b97385fc4e603bc024d877def5adb4#r139625087
I've got a PR in! Hopefully it'll get through.
But if you look for the new version of `git-prompt.sh` on your machine, in that, look got `\001` and `\002`. It is missing the escaping of the `\`. So double them up to `\\001` and `\\002`. It looks like something evaluates `\001` into `0b1`/`0x01` and `\002` into `0b10`/`0x02`.
These are observable if you `echo $PS1 | hexdump -C`.
Not sure how relevant this is, but it was changed and others have commented it as being bad. I couldn't find a PR so I made one. |
|debian|puppeteer|chrome-for-testing| |
In regex, you have to escape a slash with a backslash (`/` -> `\/`)
So in your case:
```
\/log[^\/].*
▲ ▲
│ │
└──────┴─── Add backslashes here
```
[link to regex101.com](https://regex101.com/r/tru7sf/1) |
|selenium-webdriver|selenium-chromedriver|chrome-for-testing| |
I want to do endless scrolling so that after scrolling 20 more products and so on endlessly. I have a model and the api itself from there I take everything that is required. Everything is working out. But I need another 20 products to appear after scrolling to the end, like in aliexpress. How to do it?
```
@Composable
fun FeedProductsScreen(viewModel: ProductViewModel){
val products by viewModel.productsLiveData.observeAsState(emptyList())
LaunchedEffect(Unit) {
viewModel.fetchProducts()
}
LazyVerticalGrid(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 10.dp, vertical = 5.dp),
columns = GridCells.Fixed(2),
content = {
items(products) {product ->
ProductCard(product)
}
}
)
}
```
api code
```
interface MarketplaceApi {
@GET("products")
suspend fun getProducts(
@Query("skip") skip: Int,
@Query("limit") limit: Int
): ProductResponse
companion object {
fun create(): MarketplaceApi {
val retrofit = Retrofit.Builder()
.baseUrl("https://dummyjson.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(MarketplaceApi::class.java)
}
}
}
```
viewmodel code
```
class ProductViewModel : ViewModel() {
private val repository = ProductRepository()
val productsLiveData = MutableLiveData<List<Product>>()
private var currentPage = 0
private val pageSize = 20
fun fetchProducts() {
viewModelScope.launch {
try {
val response = repository.fetchProducts(currentPage, pageSize)
val products = response.products
productsLiveData.value = products
} catch (e: Exception) {
println("ERROR: ${e.message}")
}
}
}
```
I tried a lot of options but it didn't work out.I tried a lot of options but nothing came out. I tried through page numbering or through viewmodel management, but it still didn't work out.
Thank you! |
Running a Next.js application with PM2 requires some additional configuration, especially if you are using the npm start command.
1.Install PM2 globally if you haven't already: npm install -g pm2
2.Create an ecosystem file for PM2. You can manually create a pm2.config.js file or use the ecosystem.config.js
3. Replace /path/to/your/next/app with the actual path to your Next.js application.
4. Start your Next.js application with PM2:pm2 start ecosystem.config.js
Hope this helps you.
|
I need to send the video from my IP camera to Kinesis Video Stream, and use Sagemaker to host my ML model, which will then analyse the video from Kinesis Video Stream in real time. <br />
I followed this link: https://aws.amazon.com/blogs/machine-learning/analyze-live-video-at-scale-in-real-time-using-amazon-kinesis-video-streams-and-amazon-sagemaker/ <br />
**I am done with these things:**
1. Setup of IP camera and kinesis video stream to send video from IP camera to KVS
2. Setup cloud formation template for KIT (as mentioned in the link)
**I am stuck with this particular thing:**
How do i get the video frames from aws fargate in the sagemaker notebook as input (as shown in below image, step 3)? In the link it is mentioned that the KIT comes pre-bundled with a custom Lambda function that is written to process the prediction output of one of the Amazon SageMaker examples using **[Object Detection algorithm][1]**. I am not sure how this algorithm is taking input from KVS.
[![enter image description here][2]][2]
[1]: https://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/object_detection_pascalvoc_coco/object_detection_image_json_format.ipynb
[2]: https://i.stack.imgur.com/1voCE.gif
|
My program has a main while loop as the main logic, with an inner while loop for running the logic of the "command function". When inside the inner while loop, I want EOF (<kbd>Ctrl</kbd> + <kbd>D</kbd>) to exit from the inner while loop only and continue with the outer loop (to listen to more commands). However, its exiting from both the inner "command" loop and outer main while loop.
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String input, line;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
input = reader.readLine();
if (input == null)
break;
if (input.compareTo("echo") == 0) {
while (true) {
line = reader.readLine();
// Ctrl+D (EOF) will exit loop
if (line == null)
break;
else System.out.println("echo: " + line);
}
System.out.println("Stop echo-ing");
}
else System.out.println("Cmd not recognized");
// No EOF given, should not exit this loop
}
System.out.println("Exit main loop");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
```
To replicate problem:
1. Copy and paste code, and run it
2. Type `echo` to enter into inner while loop
3. Press <kbd>Ctrl</kbd> + <kbd>D</kbd> to provide EOF to standard input
The following is printed:
```shell
^D
Stop echo-ing
Exit main loop
```
"Exit main loop" is printed unexpectedly.
How can I exit only the inner while loop when <kbd>Ctrl</kbd> + <kbd>D</kbd> is pressed? |
Kindy install the required Hardware and Software requirements by this using this link [Software and Hardware ][1]. and follow the step by step instructions.
Once you have installed all the required software and hardware requirements please follow below steps.
> 1. System requirements:
Ubuntu 16.04 or higher (64-bit)
TensorFlow only officially support Ubuntu. However, the following instructions may also work for other Linux distros.
> 2. GPU setup :
Install the NVIDIA GPU driver if you have not. You can use the following command to verify it is installed.
nvidia-smi
> 3. Install TensorFlow :
TensorFlow requires a recent version of pip, so upgrade your pip installation to be sure you're running the latest version.
pip install --upgrade pip
Then, install TensorFlow with pip.
# For GPU users
pip install tensorflow[and-cuda]
# For CPU users
pip install tensorflow
> 4. Verify the installation:
Verify the GPU setup:
python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
If a list of GPU devices is returned, you've installed TensorFlow successfully.
Follow the above steps to install the tensorflow-gpu.
[1]: https://www.tensorflow.org/install/pip#hardware_requirements |
I'm not often working on Angular, so I don't really understand how it works.
I have a subscription like this :
```
this.subscriptions.add(
this.loadDataGrid.pipe(mergeMap((list: any) => this._ecSrvc.loadDataGrid(`api/getSomething?${this.sort ? `sort=${this.sort.field}:${this.sort.order}&` : ''}page=${this.page}&size=${this.size}`, list)))
.subscribe((data: any) => {
// does some stuff
}, (error) => {
// manage error
return this.rowDataError = error ? error : true;
})
);
```
And I have this function triggered by sorting columns on PrimeNG Table :
```
public loadData(event: LazyLoadEvent) {
this.loading = true;
if (this.size !== 0) {
this.page = event.first / this.size;
} else {
this.page = 0;
}
if (event.sortField) {
this.sort = {field: event.sortField, order: event.sortOrder === 1 ? 'desc' : 'asc'};
}
this.loadDataGrid.next(this.listFilter);
}
```
This thing works.
I want to test if backend error are managed by angular. So I have a column that can be sorted (response status 200), and one that cannot (error status 422)
If I get the 422, then I try to sort with the good one (that should return a 200), the api call isn't triggered at all. The subscription seems lost. How should I manager the error in my subscription ?
I tried some code found in other questions but didn't work |
Subscription seems lost when error on Angular 11 |
|angular|angularjs|typescript| |
null |
Which to use and when? And what are the advantages of one approach over the other?
Permutation brute force is the one in which at each recursion step, we can enter any of the array elements. If repeats are not allowed, we maintain a "visited" memo(as in DFS), if repeats are allowed, we don't need the "visited" memo
f(arr,target) -> for x in arr: f(arr,target-x)
Selection brute force is the one in which at each recursion step, we only enter a particular array element. If repeats are not allowed, we select the current element 0/1 times(0/1 knapsack). If repeats are allowed, we select the current element 0,1,2,... times(unbounded knapsack).
f(arr,i,n) -> f(arr,i+1,n)
I have seen that in the case of DP, if both options are available cleanly, it is better to use permutation brute force, because it creates a cleaner induction hypothesis because we dont have to involve index of supposedly "current element". Or else use the other.
But in case of backtracking, or if we need to GENERATE ALL SUBSETS, it is better to use selection brute force, because the know ordering helps eliminate the cases of repeated elements in our final answer.
I am confused about when to use what, and what are the advantages and disadvantages of one over the other.
What will you prefer and when? |
In a Java EE web application project, there is a DAO annotated as a CDI bean:
@RequestScoped
public class CustomerDAO {
@PersistentContext
private EntityManager em;
//some persistence operation afterwards
@Transactional
public void update() {
//implementation using the injected em
}
}
The injected `EntityManager` is not thread-safe according to JPA spec, but the **Question** is:
Is the injection of `EntityManager` into this per request `@RequestScoped` CDI bean thread-safe? and if it is not thread-safe, what potential concurrency issues there might be? |
Turn out that the issue I was having wasn't the code. It was an issue with the scene asset itself. I added a parent node to the scene asset and it worked just fine. |
Launching the AMI won't affect the original ec2.
AMI's are pretty expensive. You would likely be better off spinning up a basic ec2 and installing what you need in userdata.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
Here is a snippet from a CloudFormation template that will spin up an ec2 and run some commands.
cfn-init would be something to check out if you really want to get into it with deploying ec2.
```
jumpHostEC2:
Type: 'AWS::EC2::Instance'
Properties:
BlockDeviceMappings: # the secondary drive is listed in volumes to tag it so it will get backed up.
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 20
VolumeType: gp2
#IamInstanceProfile: <some profile>
ImageId: ami-00xxxxxxxxxxxxxxx
InstanceType: t2.micro
KeyName: dev-instances
SecurityGroupIds: # the two sg groups are for ssh and Qualys
- sg-xxxxxxxxx
- sg-xxxxxxxxx
SubnetId: subnet-xxxxxxxxx
Tags: # this controls apt-get patching
- Key: Name
Value: jumphost
UserData:
Fn::Base64:
#!/bin/bash
set -e
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -qq --no-install-recommends python-pip libssl-dev libffi-dev \
wget dpkg-dev debhelper build-essential
rm -rf /var/lib/apt/lists/*
apt-get update -y
apt-get install -y python-pip
``` |
I try to embed the `EditableGraph` function into a `PyQt5` application. I developed the following program for testing, based on solutions found online.
```python
from PyQt5 import QtWidgets, QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from netgraph import EditableGraph, InteractiveGraph
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.canvas = FigureCanvas(Figure())
self.canvas.ax = self.canvas.figure.add_subplot(111)
self.editgraph = EditableGraph([(0, 1), (1,2), (2,0)],
ax=self.canvas.ax)
# Enable key_press_event events:
self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
self.canvas.setFocus()
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
layout = QtWidgets.QVBoxLayout(widget)
layout.addWidget(self.canvas)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
w = MainWindow()
w.show()
app.exec_()
```
However I have the following error:
> self.fig.canvas.manager.key_press = key_press_handler AttributeError: 'NoneType' object has no attribute 'key_press'
More in detail, the error message is:
```none
Traceback (most recent call last):
File "C:... \testit.py", line 26, in <module>
w = MainWindow()
^^^^^^^^^^^^
File "C:... \testit.py", line 13, in __init__
self.graph = EditableGraph([(0, 1), (1,2), (2,0)], ax=self.canvas.ax)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C: ... \netgraph\_interactive_graph_classes.py", line 1971, in __init__
self.fig.canvas.manager.key_press = key_press_handler
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'key_press'
```
Moreover, when I exchange `EditableGraph` by `InteractiveGraph`, it works well.
I use the following dev version of `NetGraph`.
```sh
pip install https://github.com/paulbrodersen/netgraph/archive/dev.zip
```
I don't know where the problem originated from, and I couldn't find a solution on the Web. Can you please help me? This embedding is crucial for my application. Thank you. |
Permutation brute force vs Selection brute force algorithm. When to use what? |
|algorithm|depth-first-search|backtracking|brute-force| |
null |
When we launch application without docker container, we are able to record the components. But, when we launch inside docker container, record button is disabled.
When we launch standalone application inside docker container we are not able to record the component. |
Can we record components in qf-test if application is launched inside docker container? |
|qf-test| |
null |
I have a problem with my UIKit Swift App. When using a vertical StackView with a UIButton and a UILabel, the contentEdgeInsets gets ignored. This only happens when the UIButton is inside the Stackview with a UILabel. When I remove the UILabel or use the exact same button outside of the StackView it works perfectly fine. I created a [example project](https://github.com/SkashEU/weird-stackview-example) to showcase the problem.
[Screen of the example project using following snippet](https://i.stack.imgur.com/U0LFQ.png)
```
exampleButtonInStackView.titleLabel?.adjustsFontSizeToFitWidth = true
exampleButtonInStackView.layer.cornerRadius = 30
exampleButtonInStackView.backgroundColor = UIColor.white
exampleButton.titleLabel?.adjustsFontSizeToFitWidth = true
exampleButton.layer.cornerRadius = 30
exampleButton.backgroundColor = UIColor.white
let insets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
exampleButtonInStackView.contentEdgeInsets = insets
exampleButton.contentEdgeInsets = insets
``` |
UIButton.contentEdgeInsets gets ignored when UIButton is in a vertical StackView with a UILabel |
|ios|swift|uikit| |
null |
If you are using Cheerio library for Google Apps Script:
[Source code][1]
[Library page][2]
Installation by library ID:
`1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0`
A function to get current emojis [from unicode.org][3]:
```
function getEmojis() {
var t = new Date();
var url = 'https://unicode.org/emoji/charts/full-emoji-list.html';
var fetch = UrlFetchApp.fetch(url);
var contentText = fetch.getContentText();
//console.log(new Date() - t);
// Cherio
var $ = Cheerio.load(contentText);
var data = [];
$("table > tbody > tr").each((index, element) => {
var row = [];
$(element).find("td").each((index, child) => {
row.push($(child).text());
});
if (row.length > 0) {
data.push(row);
}
});
//console.log(data);
//console.log(new Date() - t);
// Result
return data;
}
```
↑ Sample code shows how to parse table and put it into `[[array]]`
May be used as a custom function:
[![enter image description here][4]][4]
**Bonus**
Parsing the site may be a time-consuming operation + you may reach the limit.
Here's a test file with a full version of the script:
https://docs.google.com/spreadsheets/d/1iO7YjYWyfseQu_YCfRbGDPg7NskOgMu_iO1iGjr7KxY/edit#gid=93365395
↑ it uses `CasheService` to reduce the number of calls.
[1]: https://script.google.com/home/projects/1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0/edit
[2]: https://github.com/tani/cheeriogs
[3]: https://unicode.org/emoji/charts/full-emoji-list.html
[4]: https://i.stack.imgur.com/qxc8L.png |
Infinity scroll products with dummyjson |
|kotlin|android-jetpack-compose|android-jetpack-compose-material3| |
null |
I use this, but I cannot confirm if it works with Jupyter notebooks or not.
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # or "1", "2", "3", ... |
|c#|selenium-webdriver|selenium-chromedriver|chrome-for-testing| |
I'm able to install the quil-mention but unable to import not sure why im getting the below error. Any suggestions appreciated!
Could not find a declaration file for module 'quill-mention'. '/Users/abcd/jsc-maps-front-end/react/node_modules/quill-mention/src/quill.mention.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/quill-mention` if it exists or add a new declaration (.d.ts) file containing `declare module 'quill-mention'; |
```
import pandas as pd
data = {'A': ['1, 1, 1', '1', '2', '3', '1'],
'B': ['1', '1,1,1,1', '2', '4', '1'],
'C': ['1, 1', '2', '3', '5', '1']}
df = pd.DataFrame(data)
def all_same(row, item=1):
cc = set()
for val in row:
try:
val = set(val.replace(" ", "").split(","))
except AttributeError: # cell with non-string value!
# decide if you want to ignore this, or reraise this
# for simplicity I just `pass`
pass
cc.update(val)
if item is not None:
return cc == {item}
return len(cc) == 1
df = df[~df.apply(all_same, axis=1)]
```
``` |
I was asked a question today to build a BST from set of coordinates, rather than a set of numbers. So the input would be unsorted coordinates
```[(1,2), (5,7), (0,5)]```
or in other form:
``` x = [1,5,0] y =[2,7,5]```
The heuristic to select a point to a tree is using an axis which has a largest range (median-cut algorithm). Can someone explain why this heuristic is best? We are trying to cut out as many points on each step, so we can have y-axis with a very small range but a lot of points with that range, and x-axis with a wide range, and I just cannot see why this is yielding the best result... If someone could explain this very simply I would be grateful. |
2 dimensions Binary Search Tree and median cut |
|algorithm|binary-tree|binary-search-tree| |
The input shown is malformed so `read_xml` will give an error. Since the question indicates it works there must have been a transcription error in moving the XML to the question. We have added a close div tag before the 4th opening div tag in the Note at the end.
Since the XML uses a namespace, first strip that using `xml_ns_strip` to avoid problems. Then form the appropriate xpath expression producing the needed nodes and convert those to dcf format (which is a name:value format where each field is on a separate line and a blank line separates records -- see `?read.dcf` for details) in variable `dcf`. Read that using `read.dcf`, convert the resulting character matrix to data frame and fix up the div entries.
library(dplyr)
library (xml2)
doc <- read_xml(Lines) # see Note at end for Lines
nodes <- doc %>%
xml_ns_strip() %>%
xml_find_all('//div | //head[@rend="time"] | //hi[@rend="italic"]')
dcf <- case_match(xml_name(nodes),
"div" ~ "\ndiv:",
"hi" ~ paste0("time:", xml_text(nodes)),
.default = paste0("content:", xml_text(nodes))
)
dcf %>%
textConnection() %>%
read.dcf() %>%
as.data.frame() %>%
mutate(div = row_number())
giving
div time content
1 1 TIME_1 CONTENT1
2 2 TIME_2 <NA>
3 3 TIME_3 CONTENT3
4 4 <NA> CONTENT4
|
null |
First remember that Lambda don't connect to Kinesis Video Stream. Then how do example get frame data of Kinesis Video Stream. It is AWS ECS Docker Image in CloudFormation.
```xml
DockerImageRepository:
Type: String
Default: >-
528560246458.dkr.ecr.us-east-1.amazonaws.com/kinesisvideosagemakerintegration_release:V1.0.3
Description: Docker image for Kinesis Video Stream & SageMaker Integration Driver.
```
It is XML file code to create CloudFormation. In this file, You can confirm to create Docker Image. Therefore you should to check code in Docker Image.
I can't open code in Docker Image. But i can find java code in Github.
https://github.com/aws/amazon-kinesis-video-streams-parser-library
https://github.com/aws/amazon-kinesis-video-streams-parser-library/tree/master/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
https://github.com/aws/amazon-kinesis-video-streams-parser-library/blob/master/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/FrameRendererVisitor.java
https://github.com/aws/amazon-kinesis-video-streams-parser-library/blob/master/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/OutputSegmentMerger.java
May be this code run in Docker Image. First this code read i-Frame at Kinesis Video Stream. Second compare with different at previous i-Frame. Third send to SageMaker endpoint and get Sagemaker inference. Last Send to Kinesis(Not Kinesis Video Stream) then Lambda receive Sagemaker inference.
I trying this example in develop product. You should follow my Github to communicate: https://github.com/WooSung-Jung |
wen i mov my muos outsid the boundry i drew in tkintre it gives eror
```
> Exception in Tkinter callback
Traceback (most recent call last):
File "c:\Users\My PC\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1962, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Windows\System32\awdkhjgeuyfsbiufhefse.py", line 4, in <lambda>
K=__import__('tkinter');m=K.Tk();R,C,z,p=50,50,10,0;l=[[0]*C for _ in range(R)];c=K.Canvas(m,w=C*z,he=R*z,bg='#0c0c0c');c.pack();[c.create_line(0,i*z,C*z,i*z,fill='#1a1a1a')for i in range(R)];[c.create_line(j*z,0,j*z,R*z,fill='#1a1a1a')for j in range(C)];c.bind("<B1-Motion>",lambda e:d(e.x//z,e.y//z));m.bind("<space>",t);m.mainloop()
^^^^^^^^^^^^^^^^
File "c:\Windows\System32\awdkhjgeuyfsbiufhefse.py", line 1, in d
def d(x,y):global l;l[y][x]=1;c.create_rectangle(x*z,y*z,(x+1)*z,(y+1)*z,fill='#fff',outline='')
~~~~^^^
IndexError: list assignment index out of range
```
the cod is:
```
def d(x,y):global l;l[y][x]=1;c.create_rectangle(x*z,y*z,(x+1)*z,(y+1)*z,fill='#fff',outline='')
def t(_=None):global p;p^=1;['',u()][p]
def u():global l,K;l=[[1 if(l[y][x]==1 and sum(l[y+dy][x+dx]for dx,dy in((dx,dy)for dx in(-1,0,1)for dy in(-1,0,1)if(dx,dy)!=(0,0))if 0<=x+dx<C and 0<=y+dy<R)in(2,3))or(l[y][x]==0 and sum(l[y+dy][x+dx]for dx,dy in((dx,dy)for dx in(-1,0,1)for dy in(-1,0,1)if(dx,dy)!=(0,0))if 0<=x+dx<C and 0<=y+dy<R)==3)else 0 for x in range(C)]for y in range(R)];K=__import__('tkinter');c.delete("all");[c.create_line(0,i*z,C*z,i*z,fill='#1a1a1a')for i in range(R+1)];[c.create_line(j*z,0,j*z,R*z,fill='#1a1a1a')for j in range(C+1)];[[c.create_rectangle(x*z,y*z,(x+1)*z,(y+1)*z,fill='white',outline='')for x in range(C)if l[y][x]]for y in range(R)];m.after(100,u) if p else None
K=__import__('tkinter');m=K.Tk();R,C,z,p=50,50,10,0;l=[[0]*C for _ in range(R)];c=K.Canvas(m,w=C*z,he=R*z,bg='#0c0c0c');c.pack();[c.create_line(0,i*z,C*z,i*z,fill='#1a1a1a')for i in range(R)];[c.create_line(j*z,0,j*z,R*z,fill='#1a1a1a')for j in range(C)];c.bind("<B1-Motion>",lambda e:d(e.x//z,e.y//z));m.bind("<space>",t);m.mainloop()
```
how fix?
i tried runing the code |
Writing A Subquery with Left and Where |
|sql|google-bigquery|subquery| |
TLS 1.3 Connection with Rust to MariaDB |
|rust|mariadb|tls1.3| |
I have a repo where files are organized by users:
```
-user1
--folder1
---file1
---file2
--folder2
-user2
--folder3
```
etc.
Now i want to make a fork of some work `user1` has done.
I forked the repo, added a `me` user, and a folder `mywork` which will contain, initially, a copy of `folder1`, so
```
-user1
--folder1
---file1
---file2
...
-me
--mywork
---copyoffile1
---copyoffile2
```
Once I'm done, if all goeas well, this fork will be merged into the main repo, with my work folder separate from `user1`'s, but, ideally, 'linked'. Users of the repository will need to be able to see the 2 versions maintaned by 2 users, in the same main branch.
Is there a way in git to 'fork' `folder1` into `mywork` so changes to `folder1` are preserved? |
I try to establish an connection between Rust and MariaDB over MYSQL_async. I get a connection to the database, but someting is wrong. Instead I get this error message:
```
Error: Io(Tls(TlsError(Os { code: -2146893018, kind: Uncategorized, message:"The format of the received message was unexpected or incorrect." })))
```
I think that I have an issue with TLS encryption but I do not find any example which explaines me why. I also tried it with sqlx and get nearly the same error message. I use a standard mariadb database with certificate autentification in two directions. When I use the certificates in MYSQL Workbench or in PHP, I have no issue with connection. What do I have to change on my connection that the format is correct? I do not see anything what I can change?
```
use mysql_async::{Pool, OptsBuilder, SslOpts, ClientIdentity};
use mysql_async::prelude::*;
use std::path::Path;
use mysql_async;
let ssl_opts = SslOpts::default()
.with_danger_accept_invalid_certs(true)
.with_client_identity(Some(
ClientIdentity::new(Path::new("./src/ssl/client-identity.p12"))
.with_password("password"),
));
let opts = OptsBuilder::default()
.ip_or_hostname("x.x.x.x")
.tcp_port(xxxx)
.user(Some("user"))
.pass(Some("password"))
.db_name(Some("db_x"))
.ssl_opts(ssl_opts);
let pool = Pool::new(opts);
let mut conn = pool.get_conn().await?;
let table_name = "table_name";
let query = format!("SELECT * FROM {}", table_name);
let result: Vec<mysql_async::Row> = conn.query(query).await?;
println!("Number of rows retrieved: {}", result.len());
``` |
While using @Alex's code, I encountered an issue when the culture info was set to "es" (Spanish). The decimal was printed with the format of "12,34", and the attribute wasn't working properly. I was able to fix this and make some other changes so that it works as closely to other components (such as using braces for parameters when using the ErrorMessage property"
```cs
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class PrecisionAndScaleAttribute : ValidationAttribute
{
private readonly int _precision;
private readonly int _scale;
public PrecisionAndScaleAttribute(int precision, int scale)
: base(() => "The field {0} only allows decimals with precision {1} and scale {2}.")
{
_precision = precision;
_scale = scale;
}
public override bool IsValid(object? value)
{
if (value is null)
return true;
if (value is not decimal decimalValue)
return false;
string? precisionValue = decimalValue.ToString(CultureInfo.InvariantCulture);
return precisionValue is null || Regex.IsMatch(precisionValue, $@"^(0|-?\d{{0,{_precision - _scale}}}(\.\d{{0,{_scale}}})?)$");
}
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage"/>
/// </summary>
/// <param name="name">The user-visible name to include in the formatted message.</param>
public override string FormatErrorMessage(string name)
=> string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _precision, _scale);
}
``` |
> Does the standard have anything like the below?
Not as a built-in language feature, so creating a class and adding a user-defined destructor to it like you've done is how it has to be done. There are many variations on that theme, like [`std::experimental::scope_exit`](https://en.cppreference.com/w/cpp/experimental/scope_exit), which is not in the standard library, but has been proposed to be included.
> Do I have any extremely obvious bugs with this?
It depends on what you're after. If this is to be used as some kind of "finally" at the end of scopes, then you may want to `delete` the ability to _copy_ your `DeferLambda`s. Otherwise, someone may end up with two of these things, doing the same operation when they go out of scope.
|
I have a stored procedure in MS SQL server which I am using for filtering, sorting and server-side pagination.
The filtering and sorting is working fine as expected but the sorting is giving me some trouble due to there being different datatypes sorted.
Below is the query
```
ALTER PROCEDURE [dbo].[GetAllData_filtered]
@PageNumber int,
@PageSize int,
@sortOrder nvarchar(max) = '1',
@sortField nvarchar(max),
@UserId nvarchar(max),
@FirstName nvarchar(max),
@SkillNames nvarchar(max)
AS BEGIN
Select *, COUNT(*) OVER() as 'TotalRecords' from
(SELECT
m.UserId as UserId ,
m.FirstName as FIRSTNAME,
(SELECT DISTINCT STUFF((SELECT ',' + s.skillname FROM MST_Skills s WHERE CONVERT(nvarchar, s.id) IN (SELECT val FROM dbo.f_split(m.SkillIds, ',')) FOR xml PATH ('')), 1, 1, '')) AS SkillNames,
CAST(0 AS BIT) AS IsAllocated
From MST_Users m ) as filteredTable
WHERE
UserId NOT IN(select UserId from Mentors)
AND (@FirstName IS NULL OR FIRSTNAME Like '%' + @FirstName + '%')
AND (@SkillNames IS NULL OR SkillNames Like '%' + @SkillNames + '%')
AND (@UserId IS NULL OR Cast(UserId as nvarchar) LIKE '%' + @UserId + '%')
ORDER BY
CASE WHEN @sortOrder = '1' THEN
CASE @sortField
**WHEN 'FirstName' then FIRSTNAME
WHEN 'SkillNames' then SkillNames
WHEN 'UserId ' then UserId
ELSE UserId **
END
END ASC,
CASE WHEN @sortOrder = '-1' THEN
CASE @sortField
**WHEN 'UserId ' then UserId
WHEN 'FirstName' then FirstName
WHEN 'SkillNames' then SkillNames
ELSE UserId **
END
END DESC
OFFSET (@PageNumber * @PageSize) ROWS
FETCH NEXT @PageSize ROWS ONLY;
END
```
Here the UserId column is a bigint column and the rest are nvarchars. Whenever the Stored Proc is executed and the @sortField is FirstName or SkillNames, it gives an error saying cannot convert from nvarchar to bigint.
What exactly am I doing wrong here.
Thanks
I tried casting it in same datatype(i.e nvarchar) but then the UserId gives data like 1,11,12,..,100,111,etc instead of 1,2,3,4 |
How to use different datatypes in a case statement |
|sql-server| |
null |
I have an application dash with a dash_table.DataTable that I can select to generate some graph. For info it look like that :
[![enter image description here][2]][2]
What I need to build the graph is the value in StrategyId of the selected rows. Currently my endpoint looks like that :
@app.callback(
Output('my_figure', 'figure'),
[Input('my_table', 'selected_rows'),
Input('monitoring_strategies_table', 'data')]
)
def my_callback(srows, mdata):
columns = mdata[srows[0]]['StrategyId']
# function continue here
As you can see, I pass as argument the whole data of the table, and the number of the selected rows, then I use that to access the StrategyId.
It works, but I find it pretty big just to get one value (I don't need to pass the whole data of the table, and it can be big, so don't know if it can have bad performance on long run).
So question is simple : is there a way to pass directly as input the value of the column StrategyId?
or at least just the data of the row selected, without passing the whole data of the table ?
Thanks
[1]: https://i.stack.imgur.com/5Lhe3.png
[2]: https://i.stack.imgur.com/OW3Pm.png |
You should you proper debug tools (like silk) if you're chasing performance gains.
From your queryset, i guess you have four models, EventSlot, EventBlock, EventVenue and Event. EventSlot has FKs to Event and EventBlock while EventBlock has a FK to EventVenue.
If thats the case, you might see a performance increase from the following.
````python
class EventVenueViewSet(viewsets.ReadOnlyModelViewSet):
qs = EventVenue.objects.all()
qs = qs.annotate(
num_slots=models.Count(
"eventblock__eventslot",
filter=Q(eventblock__eventslot__event=None)
)
)
qs = qs.filter(num_slots__gt=0)
slot_qs = EventSlot.objects.select_related("event")
block_qs = EventBlock.objects.prefetch_related(
Prefetch("eventslot_set", queryest=slot_qs)
)
qs = qs.prefetch_related(Prefetch("eventblock_set", queryset=block_qs))
````
This will remove one query and one prefetch mapping.
If you don't serialize `num_slots` and you only use it for filtering, you should consider using `.alias()` instead of `.annotate()` since it will remove it from the select |
I am new into Python GUI programming, I want to know if Qt Designer always change its geometry calculation for x and y values (or top and left values)? Like for example when I export python code to my VSCode, I soon realize that the x and y value for each different project and forms can be different depends on the size of the form/layout. Is there any reference to calculate so I can automatically re-arrange my GUI elements? Thank you
I expect that if I can combine each form/layout into single application I dont need to re-arrange my Python elements |
Is Qt Designer changes its reference for coordination value every time the form's/layout's size changes? |
|python|qt|pyqt| |
null |
I tried to make a full-screen dialog using Jetpack Compose using this code:
```
@Preview
@Composable
fun test() {
val showDialog = remember { mutableStateOf(value = false) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(color = Color.White)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(size = 100.dp)
.background(color = Color.Red)
.clickable(
onClick = { showDialog.value = true },
indication = null,
interactionSource = remember { MutableInteractionSource() }
)
) {
Text(text = "Dialog Button")
}
}
val properties = DialogProperties(
usePlatformDefaultWidth = false
)
if (showDialog.value) {
Dialog(
onDismissRequest = { /*TODO*/ },
properties = properties,
) {
Box(
modifier = Modifier.fillMaxSize().background(color = Color.Blue)
)
}
}
}
```
The running result of the above code:
Before clicking the "dialog" button:
[image][1]
After clicking the "dialog" button:
[image][2]
You can see in the images that the blue dialog cannot fill the entire screen, and there are gaps on the left and right sides of the dialog.
I have already set `usePlatformDefaultWidth` to `false`, but it didn't work.
[1]: https://i.stack.imgur.com/z59ey.png
[2]: https://i.stack.imgur.com/EfoIi.png |
Dash : Get column value in selected table |
|python|callback|data.table|plotly-dash| |
You need to add the app id to the specific config inside ios/config and android/config inside your app.json
Check this out: https://docs.expo.dev/versions/latest/config/app/#googlemobileadsappid
The link above is for iOS, which is similar to Android. They are in ios/config and android/config in your app.json - These settings will tell Expo to add the app id to the info.plist (ios) and manifest when running prebuild. You still need to keep the react-native-google-mobile-ads in your current config. So, there're 2 places in app.json need to be setup:
- googleMobileAdsAppId inside the platform config key.
- The config that outside the expo key
Note that you cannot add using the infoplist key inside iOS since expo will ignore it, you have to you the specific config in the document I provided |