instruction stringlengths 0 30k ⌀ |
|---|
Sharing RSO2 Topic communication between containers operating on two Windows host machines A and B, each equipped with Docker |
I'm coding a program to find perfect numbers. I have found some interesting properties and worked on my code to generate perfect numbers. This is my idea:
```static List<int> TesterPerfectNumber(int upperbound)
{
List<int> nums = new List<int>();
for (int i = 2; i < upperbound; i++)
{
if (IsPrime(i))
{
int mersenneNumber = (int)Math.Pow(2, i) - 1;
if (IsPrime(mersenneNumber))
{
int perfectNumber = (int)Math.Pow(2, i - 1) * mersenneNumber;
nums.Add(perfectNumber);
}
}
}
return nums;
}
static bool IsPrime(int number)
{
if (number <= 1)
return false;
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0)
return false;
}
return true;
}
```
[](https://i.stack.imgur.com/WWL4d.png)
The output is correct for the first 4 perfect numbers, however I don't know why it failed on the 5th and outputted negative numbers (with `foreach (int j in TesterPerfectNumber(20)){Console.WriteLine(j);}`):
I suspect the bug is in my algorithm, but the alternative form of finding perfect numbers is (2^(p-1))*(2^p - 1) with p and 2^p-1 being primes. Also, I have already found another way to find perfect numbers but consumes more storage and time, basically looping and finding factors of all positive numbers and adding up until it reaches the upperbound limit.
Can you help me debug the code or come up with another reasonable solution to my code? Or are there any limits to the `List<T>` or `int` that I haven't taken into consideration? Please help me and thanks. |
I suggest using the toString() method, then use the split() or subString() method; get the number string before 'tickers'. |
Why does getting a datastore work when using `val` but not when using `fun`?
```
val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
fun Context.test(name: String){
// Property delegate must have a 'getValue(Nothing?, KProperty*>)' method. None of the following functions are suitable.
val dataStore: DataStore<Preferences> by preferencesDataStore(name = name)
}
```
When clicking on the suggestion, the following code is generated:
```
private operator fun <T, V> ReadOnlyProperty<T, V>.getValue(v: V?, property: KProperty<V?>): V {
}
```
However, the `operator` has the following error: `'operator' modifier is inapplicable on this function: second parameter must be of type KProperty<*> or its supertype`.
----------
Originally, I thought the context was passed through `this`, but it turns out that there is no `this` when using `val`.
```
val Context.example = this.getString(R.string.example) // Extension property cannot be initialized because it has no backing field
// correct way
val Context.example: String
get() = this.getString(R.string.example)
```
|
Preferences datastore with dynamic name: Property delegate must have a 'getValue(Nothing?, KProperty*>) method |
|android|android-jetpack-datastore| |
I would like to access my `log::Log` impl instance in order to access a particular field, but once I receive the reference I am not able to downcast it to my struct.
I tried to convert the logger reference into `core::any::Any` and then downcasting it into my original struct, but I always obtain `None`.
```rust
use core::any::Any;
pub trait AToAny: 'static {
fn as_any(&self) -> &dyn Any;
}
impl<T: 'static> AToAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
struct MyLogger {}
impl log::Log for MyLogger {
fn enabled(&self, _: &log::Metadata<'_>) -> bool { todo!() }
fn log(&self, _: &log::Record<'_>) { todo!() }
fn flush(&self) { todo!() }
}
pub fn main() {
let logger_impl = MyLogger {};
log::set_boxed_logger(Box::new(logger_impl)).unwrap();
let logger = log::logger();
let logger_any = logger.as_any();
let logger_impl = logger_any.downcast_ref::<MyLogger>()
.expect("downcast failed");
}
```
I also tried without passing from log initialization functions, but I obtain the same result:
```rust
use core::any::Any; // 0.10.1
pub trait AToAny: 'static {
fn as_any(&self) -> &dyn Any;
}
impl<T: 'static> AToAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
struct MyLogger {}
impl log::Log for MyLogger {
fn enabled(&self, _: &log::Metadata<'_>) -> bool { todo!() }
fn log(&self, _: &log::Record<'_>) { todo!() }
fn flush(&self) { todo!() }
}
pub fn main() {
let logger_impl = MyLogger {};
let logger_boxed: Box<MyLogger> = Box::new(logger_impl);
let logger: &'static mut dyn log::Log = Box::leak(logger_boxed);
let logger_any = logger.as_any();
let logger_impl = logger_any.downcast_ref::<MyLogger>()
.expect("downcast failed");
}
```
Here is the [code on the playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=use+core%3A%3Aany%3A%3AAny%3B+%2F%2F+0.10.1%0A%0Apub+trait+AToAny%3A+%27static+%7B%0A++++fn+as_any%28%26self%29+-%3E+%26dyn+Any%3B%0A%7D%0A%0Aimpl%3CT%3A+%27static%3E+AToAny+for+T+%7B%0A++++fn+as_any%28%26self%29+-%3E+%26dyn+Any+%7B%0A++++++++self%0A++++%7D%0A%7D%0A%0Astruct+MyLogger+%7B%7D%0A%0Aimpl+log%3A%3ALog+for+MyLogger+%7B%0A++++fn+enabled%28%26self%2C+_%3A+%26log%3A%3AMetadata%3C%27_%3E%29+-%3E+bool+%7B+todo%21%28%29+%7D%0A++++fn+log%28%26self%2C+_%3A+%26log%3A%3ARecord%3C%27_%3E%29+%7B+todo%21%28%29+%7D%0A++++fn+flush%28%26self%29+%7B+todo%21%28%29+%7D%0A%7D%0A%0Apub+fn+main%28%29+%7B%0A++++let+logger_impl+%3D+MyLogger+%7B%7D%3B%0A++++log%3A%3Aset_boxed_logger%28Box%3A%3Anew%28logger_impl%29%29.unwrap%28%29%3B%0A++++let+logger+%3D+log%3A%3Alogger%28%29%3B%0A++++%0A++++%2F%2F+let+logger_impl+%3D+MyLogger+%7B%7D%3B%0A++++%2F%2F+let+logger_boxed%3A+Box%3CMyLogger%3E+%3D+Box%3A%3Anew%28logger_impl%29%3B%0A++++%2F%2F+let+logger%3A+%26%27static+mut+dyn+log%3A%3ALog+%3D+Box%3A%3Aleak%28logger_boxed%29%3B%0A++++%0A++++let+logger_any+%3D+logger.as_any%28%29%3B%0A++++let+logger_impl+%3D+logger_any.downcast_ref%3A%3A%3CMyLogger%3E%28%29%0A++++++++.expect%28%22downcast+failed%22%29%3B%0A%7D).
I saw that the `type_id` of the `logger` variable is different from the `type_id` of the `logger_impl` so I believe that this is what is preventing me from doing the downcast, but I cannot understant how I am supposed to fix this. |
null |
I want to change the class 'fa-meh-blank' to 'fa-smile-wink' but it doesn't work.
When I flip the two classes, however, it works. I don't understand what's wrong, what would anyone have an idea?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const icone = document.querySelector("i");
console.log(icone);
//Je soumets
icone.addEventListener('click', function() {
console.log('icône cliqué');
icone.classList.toggle('happy');
icone.classList.toggle('fa-smile-wink');
});
<!-- language: lang-html -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<div class="container">
<div class="bloc-central">
<h1>Projet Abonnez-vous</h1>
<div class="bloc-btn">
<i class="far fa-meh-blank"></i>
<button class="btn">Abonnez-vous</button>
</div>
</div>
</div>
<!-- end snippet -->
|
Icons of Font Awesome don't change |
raceback (most recent call last):
File "C:\Users\Tariq\Downloads\Blank-main\Blank\env\Scripts\process.py", line 9, in <module>
import pyaes
ModuleNotFoundError: No module named 'pyaes'
288 INFO: PyInstaller: 6.5.0, contrib hooks: 2024.3
288 INFO: Python: 3.12.2
307 INFO: Platform: Windows-10-10.0.19045-SP0
Script file 'loader-o.py' does not exist.
Can anyone help me, i dont know anythink about python
I installed pyaes already but nothing changes |
Python 3.12.2 Tool |
|python|windows|pyinstaller| |
null |
When I try to divide `1/60` or `1/(60*60)` it gives 0. Even in debugger window. I am a bit confused what it could be, because `2/3` or `2.5/6` give results.
My code:
int main()
{
double k1 = 1/60;
cout << k1 << endl;
double k2 = 1/(60*60);
cout << k2 << endl;
return 0;
} |
Dividing 1 by any number gives 0 |
If you read the Firebase documentation, you'll see there are two [message types](https://firebase.google.com/docs/cloud-messaging/concept-options):
> * Notification messages, sometimes thought of as "display messages." These are handled by the FCM SDK automatically.
> * Data messages, which are handled by the client app.
So notification messages are handled by the system, which only displays them when the app is **not** active. If the user is using the app, it doesn't display the notification but *does* deliver it to your code.
The easiest way to ensure the message is always displayed consistently, is to let your code handle its display. So send a **data** message, and write the code to [handle foreground and background messages](https://firebase.google.com/docs/cloud-messaging/flutter/receive#message_handling) and display a local notification. |
null |
|docker|ros2| |
null |
null |
null |
null |
null |
null |
I am working on a RN app, but I can't seem to get rid of what appears to be a default header at the very top.
At first I thought that this might have to do with react-navigation or something, but even if I render only some text:
```typescript
const App = () => {
return (
<View style={{ backgroundColor: '#e0e0e0', height: '100%' }}>
<Text>WHY IS THERE A HEADER ABOVE ME?</Text>
</View>
);
};
export default App;
```
I still get this header on top:
[![enter image description here][1]][1]
I have also tried to hide the `StatusBar`:
```typescript
const App = () => {
return (
<>
<StatusBar hidden />
<View style={{ backgroundColor: '#e0e0e0', height: '100%' }}>
<Text>WHY IS THERE A HEADER ABOVE ME?</Text>
</View>
</>
);
};
```
Something got removed apparently, as the header is now black, but as you can see, there is still a gap between the view and the top of the screen.
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/i4t4v.png
[2]: https://i.stack.imgur.com/U98pm.png |
Unable to remove (default?) header |
|react-native|expo| |
|python|documentation|psd|color-profile| |
|android|android-intent|whatsapp| |
null |
[Example](https://i.stack.imgur.com/ujcMb.jpg)
Мне нужно выбрать иерархическую систему управления базой данных для моего проекта, какую иерархическую систему управления базой данных вы бы посоветовали использовать мне? Заранее благодарю. Спасибо
haven't tried anything yet. |
This toy code:
```cpp
union a {
int b;
int c;
};
template<int a::* p> void b() {}
template<> void b< &a::b >() {}
template<> void b< &a::c >() {}
```
Builds fine in clang and gcc, but in MSVC gives:
> error C2766: explicit specialization; 'void b<pointer-to-member(0x0)>(void)' has already been defined
Compiler-explorer link: https://godbolt.org/z/TfoMjv8ch
As can be seen in CE, in gcc/clang the specialization names mangling encodes the union-member names:
```
_Z1bIXadL_ZN1a1bEEEEvv
^
_Z1bIXadL_ZN1a1cEEEEvv
^
```
but in MSVC the mangling encodes just the member offset within the union (0), and therefore the specializations are considered duplicate:
```
??$b@$0A@@@YAXXZ
^
```
Is this an MSVC bug or undefined/unspecified behavior? Any pointers (hehe) to relevant standard clauses? |
I'm using a [CDN](https://unpkg.com/vue) to run some vue code in my `index.html`. I'm just learning from a tutorial and this is my first time I use vue.
This is `index.html`.
```html
<!DOCTYPE html>
<html>
<head>
<title>THE TITLE</title>
</head>
<body>
<div id="app">
{{ greeting }}
<input v-model="greeting"/> <hr />
</div>
<div v-if="isVisible" class="box"></div>
<script src='https://unpkg.com/vue'></script>
<script src="vue.js"></script>
</body>
</html>
```
And this is `vue.js`
```js
let app = Vue.createApp({
data: function() {
return {
greeting: "Hello vue3!",
isVisible: false
}
}
});
app.mount("#app");
```
I am sure that vue cdn is working because v-model is working properly, but somehow v-if is not.
Also i asked chatGPT and it said I'm not importing CDN properly and edited my `vue.js` file completely. |
I think you can use static parameters and shadow attributes `_select="{$xpathId}"`.
```
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:param name="providerId" />
<xsl:param name="xpathId" static="yes" select="'/format1/some_id'"/>
<xsl:param name="xpathUrl" static="yes" select="'/format1/theUri'"/>
<xsl:template match="/">
<myXml>
<provider>
<xsl:value-of select="$providerId" />
</provider>
<id>
<xsl:value-of _select="{$xpathId}"/>
</id>
<url>
<xsl:value-of _select="{$xpathUrl}"/>
</url>
</myXml>
</xsl:template>
</xsl:stylesheet>
```
and use an additional map for `fn:transform`
```
'static-params': map {
QName('', 'xpathId'): $xpathId,
QName('', 'xpathUrl'): $xpathUrl
},
```
Of course given the two different XML formats you could also just consider a stylesheet like
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" expand-text="yes">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:param name="providerId" />
<xsl:mode on-no-match="shallow-skip"/>
<xsl:template match="/*">
<myXml>
<provider>{$providerId}</provider>
<xsl:apply-templates/>
</myXml>
</xsl:template>
<xsl:template match="/format1/some_id | /format2/also_the_id">
<id>{.}</id>
</xsl:template>
<xsl:template match="/format1/the_uri | /format2/url_field">
<url>{.}</url>
</xsl:template>
</xsl:stylesheet>
Just added that as a note to show that, as long as you deal with known vocabularies of XML elements, it should suffice to provide the adequate match patterns.
|
`call` is necessary for .bat or .cmd files, else the control will not return to the caller.
For exe files it isn't required.
`Start` isn't the same as `call`, it creates a new cmd.exe instance, so it can run a *called* batch file asynchronosly.
`call` has some unexpected behavior for the arguments, the parser run two times and all carets are doubled.
As one result, it's not possible to escape special characters like `&|<>` with carets when using `call`
Example (Simplified without calling another batch file)
@echo off
echo #1 Show a caret ^^ and a percent %% sign
echo #2 "Show a caret ^ and a percent %% sign"
call echo #3 Show a caret ^^ and a percent %%%% sign
call echo #4 "Show 2 carets ^ and a percent %%%% sign"
call echo #5 "Show 4 carets ^^ and a percent %%%% sign"
|
|python|python-3.x|oop|metaclass| |
**NEW**
In the meantime I think I found a better solution
df.between_time('7:00', '10:45')
Full code:
import pandas as pd
idx = pd.date_range("2024-01-01 06:00", periods=3600*6+5, freq="S")
df = pd.DataFrame([i for i in range(len(idx))], index=idx)
print(df.between_time('7:00', '11:00'))
returns:
2024-01-01 07:00:00 3600
2024-01-01 07:00:01 3601
2024-01-01 07:00:02 3602
2024-01-01 07:00:03 3603
2024-01-01 07:00:04 3604
... ...
2024-01-01 10:59:56 17996
2024-01-01 10:59:57 17997
2024-01-01 10:59:58 17998
2024-01-01 10:59:59 17999
2024-01-01 11:00:00 18000
**OLD**
You could create a mask that additionally asks for the 11:00:00 exclusively. So to find all times between 7am and 11 am you could use:
mask = ((df.index.hour >= 7) & (df.index.hour <= 10)) | ((df.index.hour == 11) & (df.index.minute == 0) & (df.index.second == 0))
df1 = df[mask]
which gives me:
time
2024-01-01 07:00:00 07:00:00
2024-01-01 07:00:01 07:00:01
2024-01-01 07:00:02 07:00:02
time
2024-01-01 10:59:58 10:59:58
2024-01-01 10:59:59 10:59:59
2024-01-01 11:00:00 11:00:00
|
I'm try decode a barcode created by myself, but i cant.
Created barcode reading another barcode scanner app.
I try bitmatrix and bitmap to convert BinaryBitmap but always returning null result
Yes, sometimes can return null if not decode but **how can i strong my encode code for pure decode?**
Error is
`java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:558)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: com.google.zxing.NotFoundException`
Encoder
```
class BarcodeWriter: Writer {
override fun encode(
contents: String?,
format: BarcodeFormat?,
width: Int,
height: Int
): BitMatrix {
return MultiFormatWriter().encode(contents, format, width, height)
}
override fun encode(
contents: String?,
format: BarcodeFormat?,
width: Int,
height: Int,
hints: MutableMap<EncodeHintType, *>?
): BitMatrix {
return MultiFormatWriter().encode(contents, format, width, height, hints)
}
}
```
Decoder
```
class BarcodeReader : Reader {
override fun decode(image: BinaryBitmap?): Result {
return MultiFormatReader().decode(image)
}
override fun decode(image: BinaryBitmap?, hints: MutableMap<DecodeHintType, *>?): Result {
return MultiFormatReader().decode(image, hints)
}
override fun reset() {
//
}
}
```
Conveters
```
fun bitMatrixToBmp(bitMatrix: BitMatrix, xColor: Int?, yColor: Int?): Bitmap {
val height: Int = bitMatrix.height
val width: Int = bitMatrix.width
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
for (x in 0 until width) {
for (y in 0 until height) {
bmp.setPixel(x, y, if (bitMatrix.get(x, y)) xColor?:Color.BLACK else yColor?:Color.WHITE)
}
}
return bmp
}
fun bmpToBinaryBitmap(bitmap: Bitmap) : BinaryBitmap {
val intArray = IntArray(bitmap.width * bitmap.height)
val source = RGBLuminanceSource(bitmap.width, bitmap.height, intArray)
return BinaryBitmap(HybridBinarizer(source))
}
fun bitMatrixToBinary(bitMatrix: BitMatrix): BinaryBitmap {
val intArray = IntArray(bitMatrix.width * bitMatrix.height)
val source = RGBLuminanceSource(bitMatrix.width, bitMatrix.height, intArray)
return BinaryBitmap(HybridBinarizer(source))
}
```
Barcode encode code;
```
val hints = hashMapOf(
EncodeHintType.CHARACTER_SET to "utf-8"
)
BarcodeWriter().encode(
contents = "URL:${urlFormModel.url}",
format = BarcodeFormat.QR_CODE,
width = 100,
height = 100,
hints = hints
)
```
Barcode decode code;
```
val decodeHints = hashMapOf(
DecodeHintType.CHARACTER_SET to "utf-8",
//DecodeHintType.PURE_BARCODE to true,
//DecodeHintType.TRY_HARDER to true
)
val result = BarcodeReader().decode(testBarcode.bitMatrix!!.toBinaryMap(), decodeHints)
```
|
Zxing decode com.google.zxing.NotFoundException |
|android|kotlin|zxing| |
null |
I have a npc class which has a method called `chase` that is referenced inside the `update` function. when `chase` is called it says its not a function or it's not defined. I have another method being referenced in the same way that works.
chase()
{
this.Phaser.Physics.moveToObject(NPC_spr, player_spr, 100);
this.anims.play('NPC',true);
}
chase method in npcClass.js
bullet_ary = bulletGroup.getChildren();
for (let bullet_spr of bullet_ary)
{
bullet_spr.updateMe();
}
NPC_ary = npcGroup.getChildren();
for (let npc_spr of NPC_ary)
{
npc_spr.chase();
}
`chase` is called at `npc_spr.chase();` which is in the update function, this creates an error while above the `bullet_spr.updateMe()` works. `updateMe` is also a method.
what I expected to happen was for the method to be called like the one above for the bullets. I have tried many different ways of rewriting it but everything results in the not defined or not a function error.
Error in console - Uncaught TypeError: npc_spr.chase is not a function |
|python|dataset|huggingface-datasets|vision-transformer| |
For the exact code format, errors are logged and sent back to the client(Postman) in `development` mode. But not sent back to the client in `production` mode. This is the code for the global error handler
module.exports = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (process.env.NODE_ENV === 'development') {
sendErrorDev(err, res);
}
if (process.env.NODE_ENV === 'production') {
// let error = { ...err };
// if (error.name === 'CastError') error = handleCastErrorDB(error);
sendErrorDev(err, res);
}
};
**SendErorDev()**
const sendErrorDev = (err, res) => {
res.status(err.statusCode).json({
status: err.status,
// error: err,
message: err.message,
// stack: err.stack,
});
This is all from Jonas Node JS course which I am currently doing |
While trying to install ruffle through Homebrew, I get across the error of: undefined reference to \`SSL_get0_group_name'.
Here is the output of the process:
```
brew install --HEAD ruffle-rs/ruffle/ruffle
==> Fetching ruffle-rs/ruffle/ruffle
==> Cloning https://github.com/ruffle-rs/ruffle.git
Updating /home/benjamen/.cache/Homebrew/ruffle--git
==> Checking out branch master
Already on 'master'
Your branch is up to date with 'origin/master'.
HEAD is now at 6e1e26e0e chore: Update translations from Crowdin
==> Installing ruffle from ruffle-rs/ruffle
==> cargo build --package=ruffle_desktop
Last 15 lines from /home/benjamen/.cache/Homebrew/Logs/ruffle/01.cargo:
Compiling dirs v5.0.1
Compiling os_info v3.7.0
Compiling sys-locale v0.3.1
error: linking with `cc` failed: exit status: 1
|
= note: LC_ALL="C" PATH="/home/linuxbrew/.linuxbrew/Cellar/rust/1.75.0/lib/rustlib/x86_64-unknown-linux-
= note: /home/linuxbrew/.linuxbrew/opt/binutils/bin/ld: /tmp/ruffle-20240109-31311-r1xadv/target/debug/deps/libcurl_sys-7febe95ed6fa6e9f.rlib(openssl.o): in function `ossl_connect_step2':
/home/benjamen/.cache/Homebrew/cargo_cache/registry/src/index.crates.io-6f17d22bba15001f/curl-sys-0.4.70+curl-8.5.0/curl/lib/vtls/openssl.c:3994:(.text.ossl_connect_step2+0x638): undefined reference to `SSL_get0_group_name'
collect2: error: ld returned 1 exit status
= note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
= note: use the `-l` flag to specify native libraries to link
= note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)
error: could not compile `ruffle_desktop` (bin "ruffle_desktop") due to previous error
If reporting this issue please do so at (not Homebrew/brew or Homebrew/homebrew-core):
https://github.com/ruffle-rs/homebrew-ruffle/issues
ruffle's formula was built from an unstable upstream --HEAD.
This build failure is expected behaviour.
Do not create issues about this on Homebrew's GitHub repositories.
Any opened issues will be immediately closed without response.
Do not ask for help from Homebrew or its maintainers on social media.
You may ask for help in Homebrew's discussions but are unlikely to receive a response.
Try to figure out the problem yourself and submit a fix as a pull request.
We will review it but may or may not accept it.
```
I tried linking the `openssl` library through the `makefile` in that location:
`/home/benjamen/.cache/Homebrew/cargo_cache/registry/src/index.crates.io-6f17d22bba15001f/curl-sys-0.4.70+curl-8.5.0/curl/lib`
But I had no success there. I have installed openssl through Homebrew as well.
What am I missing here?
I thought I'd get the ruffle install through Homebrew, but it didn't let me. |
I can't recall when this was changed, but the current method to get a `Context` object during Instrumented testing is to import
```java
import android.support.test.InstrumentationRegistry;
```
and call
```java
InstrumentationRegistry.getContext();
```
Hope this helps! |
null |
I'm normally very comfortable performing joins in my work/on online practice sets but sort of blanked when I got this question.
Here's the data: [enter image description here](https://i.stack.imgur.com/iUmN0.png)
I was asked to perform a Select * statement on the two tables, and write down the result for all 5 kinds of joins.
So basically:
select * from table_a a left join table_b b on a.column_a = b.column_b
For this I answered: 1 1 0 0 1 1 1 1 0 0 null
Can somebody tell me if the answer is wrong/right?
Also, can you please list down the output for all 5 types of joins (left, right, inner outer, cross) for this? With a good explanation
Any help would be appreciated!
Listed out my answer in the block above. |
Had a really embarrassing interview today. The question was SQL based and was about the 5 types of JOINS |
|sql|mysql|sql-server|postgresql|sqlite| |
null |
Hey all I am trying to figure out how to go about updating a part of my json. So far I have not found anywhere that shows me how to do this.
For an example, this is what I am needing to update:
{
"lastUpdated": "",
"firetvs": [
{
"name": "lr",
"ip": "",
"mac": "",
"token": ""
},
{
"name": "mbr",
"ip": "",
"mac": "",
"token": ""
},...ETC....
So I am needing to update the data under the
"name": "mbr"
"mac": ""
part which I would need to update the mac address to something like:
"name": "mbr"
"mac": "C1:41:Q4:E8:S1:98:V1"
I have found code that allows me to update a **standard value** like my **lastUpdated** but not for something that's part of an array:
String jsonObject = "{" +
"\"lastUpdated\": \"\"," +
"\"firetvs\": [" +
"{" +
"\"name\": \"lr\"," +
"\"ip\": \"\"," +
"\"mac\": \"\"," +
"\"token\": \"\"" +
"}," +
"{" +
"\"name\": \"mbr\"," +
"\"ip\": \"\"," +
"\"mac\": \"\"," +
"\"token\": \"\"" +
"}" +
"]" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = null;
try {
objectNode = objectMapper.readValue(jsonObject, ObjectNode.class);
objectNode.put("lastUpdated", "02-08-2024");
Log.d("test", objectNode.toPrettyString());
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
I did find this:
objectNode.with("firetvs").put("mac", "C1:41:Q4:E8:S1:98:V1");
But that wont work since its just going to find the first instance of "mac" and update that value instead of updating the 2nd instance of it. And I also get an error of:
>Property 'firetvs' has value that is not of type ObjectNode (but com.fasterxml.jackson.databind.node.ArrayNode)
So, how would I accomplish this? |
Try it, maybe this is what you wanted? Saves the selected ranges into two separate PDF files, maybe I misunderstood you. Part of the code was found on this forum and adapted to your needs. Good luck.
Option Explicit
Sub Export()
Dim shArr As Variant
Dim wb As Workbook
Dim strPath As String
Dim myFile As Variant
Dim rng As Range
On Error GoTo errHandler
Set wb = ThisWorkbook
Set shArr = Sheets(Array("Administratief", "Spuiwater TID"))
strPath = ThisWorkbook.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
For Each shArr In ThisWorkbook.Worksheets
If shArr.Name = "Administratief" Then
' The user chooses the range himself
Set rng = Application.InputBox("Please, Select a Range: ", "Prompt to select a range for the print area on the selected worksheet", Type:=8).Areas(1)
shArr.PageSetup.PrintArea = rng.Address
' ' Uncomment the following line if you want to print a fixed range
' ' Fixed range without request
' shArr.PageSetup.PrintArea = shArr.Range("A1:F22").Address
ElseIf shArr.Name = "Spuiwater TID" Then
' The user chooses the range himself
Set rng = Application.InputBox("Select a Range inside the target sheet: ", "Prompt to select a range for the print area on the selected worksheet", Type:=8).Areas(1)
shArr.PageSetup.PrintArea = rng.Address
' ' Uncomment the following line if you want to print a fixed range
' ' Fixed range without request
' shArr.PageSetup.PrintArea = shArr.Range("B4:F17").Address
Else
End If
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPath, _
FileFilter:="PDF (*.pdf), *.pdf", _
Title:="Select folder and filename to save")
shArr.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Set rng = Nothing
Next shArr
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not export file", vbCritical, "Export"
Resume exitHandler
Set shArr = Nothing
Set wb = Nothing
End Sub |
The [handle class](https://www.mathworks.com/help/matlab/handle-classes.html) and its copy-by-reference behavior is the natural way to implement linkage in Matlab.
It is, however, possible to implement a linked list in Matlab without OOP. And an abstract list which does *not* splice an existing array in the middle to insert a new element -- as complained in [this comment](https://stackoverflow.com/questions/1413860/matlab-linked-list#comment23877880_1422443).
(Although I do have to use a Matlab data type somehow, and adding new element to an existing Matlab array requires memory allocation somewhere.)
The reason of this availability is that we can model linkage in ways other than pointer/reference. The reason is *not* [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) with [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html).
I will nevertheless use closure to encapsulate a few *persistent* variables. At the end, I will include an example to show that closure alone confers no linkage. And so [this answer](https://stackoverflow.com/a/1421186/3181104) as written is incorrect.
At the end of the day, linked list in Matlab is only an academic exercise. Matlab, aside from aforementioned handler class and classes inheriting from it (called subclasses in Matlab), is purely copy-by-value. Matlab will optimize and automate how copying works under the hood. It will avoid deep copy whenever it can. That is probably the better take-away for OP's question.
The absence of reference in its core functionality is also why linked list is not obvious to make in Matlab.
-------------
##### Example Matlab linked list:
```lang-matlab
function headNode = makeLinkedList(value)
% value is the value of the initial node
% for simplicity, we will require initial node; and won't implement insert before head node
% for the purpose of this example, we accommodate only double as value
% we will also limit max list size to 2^31-1 as opposed to the usual 2^48 in Matlab vectors
m_id2ind=containers.Map('KeyType','int32','ValueType','int32'); % pre R2022b, faster to split than to array value
m_idNext=containers.Map('KeyType','int32','ValueType','int32');
%if exist('value','var') && ~isempty(value)
m_data=value; % stores value for all nodes
m_id2ind(1)=1;
m_idNext(1)=0; % 0 denotes no next node
m_id=1; % id of head node
m_endId=1;
%else
% m_data=double.empty;
% % not implemented
%end
headNode = struct('value',value,...
'next',@next,...
'head',struct.empty,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',m_id);
function nextNode=next(node)
if m_idNext(node.id)==0
warning('There is no next node.')
nextNode=struct.empty;
else
nextNode=makeNode(m_idNext(node.id));
end
end
function node=makeNode(id)
if isKey(m_id2ind,id)
node=struct('value',id2val(id),...
'next',@next,...
'head',headNode,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',id);
else
warning('No such node!')
node=struct.empty;
end
end
function temp=id2val(id)
temp=m_data(m_id2ind(id));
end
function addEnd(value)
addAfter(value,m_endId);
end
function addAfter(value,id)
m_data(end+1)=value;
temp=numel(m_data);% new id will be new list length
if (id==m_endId)
m_idNext(temp)=0;
else
m_idNext(temp)=temp+1;
end
m_id2ind(temp)=temp;
m_idNext(id)=temp;
m_endId=temp;
end
function deleteAt(id)
end
end
```
With the above .m file, the following runs:
```lang-matlab
>> clear all % remember to clear all before making new lists
>> headNode = makeLinkedList(1);
>> node2=headNode.next(headNode);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> headNode.push_back(2);
>> headNode.push_back(3);
>> node2=headNode.next(headNode);
>> node3=node2.next(node2);
>> node3=node3.next(node3);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> node0=node2.head;
>> node2=node0.next(node0);
>> node2.value
ans =
2
>> node3=node2.next(node2);
>> node3.value
ans =
3
```
`.next()` in the above can take any valid node `struct` -- not limited to itself. Similarly, `.push_back()` etc can be done from any node. But what relative node to get next node from needs to be passed in because a non-OOP [`struct`](https://www.mathworks.com/help/matlab/ref/struct.html) in Matlab cannot reference itself implicitly and automatically. It does not have a `this` pointer or `self` reference.
In the above example, nodes are given unique IDs, a dictionary is used to map ID to data (index) and to map ID to next ID. (With pre-R2022 `containers.Map()`, it's more efficient to have 2 dictionaries even though we have the same key and same value type across the two.) So when inserting new node, we simply need to update the relevant next ID. (Double) array was chosen to store the node values (which are doubles) and that is the data type Matlab is designed to work with and be efficient at. As long as no new allocation is required to append an element, insertion is constant time. Matlab automates the management of memory allocation. Since we are not doing array operations on the underlying array, Matlab is unlikely to take extra step to make copies of new contiguous arrays every time there is a resize. [Cell array](https://www.mathworks.com/help/matlab/ref/cell.html) may incur less re-allocation but with some trade-offs.
Since [dictionary](https://www.mathworks.com/help/matlab/ref/dictionary.html) is used, I am not sure if this solution qualifies as purely [functional](https://en.wikipedia.org/wiki/Functional_programming).
------------
##### re: closure vs linkage
In short, closure does not confer linkage. Matlab's nested functions have access to variables in parent functions directly -- as long as they are not shadowed by local variables of the same names. But there is no variable passing. And thus there is no pass-by-reference. And thus we can't model linkage with this non-existent referencing.
I did take advantage of closure above to make a few variables persistent and shared, since scope (called [workspace](https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html) in Matlab) being referred to means all variables in the scope will persist. That said, Matlab also has a [persistent](https://www.mathworks.com/help/matlab/ref/persistent.html) specifier. Closure is not the only way.
To showcase this distinction, the example below will not work because every time there is passing of `previousNode`, `nextNode`, they are passed-by-value. There is no way to access the original `struct` across function boundaries. And thus, even with nested function and closure, there is no linkage!
```lang-matlab
function newNode = SOtest01(value,previousNode,nextNode)
if ~exist('previousNode','var') || isempty(previousNode)
i_prev=m_prev();
else
i_prev=previousNode;
end
if ~exist('nextNode','var') || isempty(nextNode)
i_next=m_next();
else
i_next=nextNode;
end
newNode=struct('value',m_value(),...
'prev',i_prev,...
'next',i_next);
function out=m_value
out=value;
end
function out=m_prev
out=previousNode;
end
function out=m_next
out=nextNode;
end
end
```
```lang-matlab
>> newNode=SOtest01(1,[],[]);
>> newNode2=SOtest01(2,newNode,[]);
>> newNode2.prev.value=2;
>> newNode.value
ans =
1
```
But we tried to set prev node of node 2 to be have value 2! |
Is there a away to use services provided by Supabase in android studio with Java and not with Kotlin?
and if there is, then how? |
First step Set a fixed height and width for the element in css file , Adjust the height and width for smaller viewports
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
#HomeNewsEventsWrapper{
height: 200px;
width: 100%;
background:red;
}
@media (max-width: 580px) {
#HomeNewsEventsWrapper {
height: 150px;
width: 100%;
}
}
<!-- language: lang-html -->
<div id="HomeNewsEventsWrapper" class="section fixedheight1 introduction table">
<!-- end snippet -->
|
Please advise according to following issue below
If Not Intersect(Target, Me.Columns("X")) Is Nothing Then
Please your support Regarding to this issue
If Not Intersect(Target, Me.Columns("X")) Is Nothing Then |
In ChartJs I want to custamize the bar chart.I'm placed the images in empty places if i click on the legend that images cannot be hide. I made a attendance bar chart if person is absent that place will show absent image & alslo if person is working hours place in that place(bar chart in stacked). Finally I want if absent label or Leave label legend click that image will hide.[this ref for my bar chart](https://i.stack.imgur.com/yya7o.png).[my issue if i click legend hide`](https://i.stack.imgur.com/ZmMhK.png).
if i click on legend remove that image
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart Js</title>
<link rel="stylesheet" href="chart.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.2.0/chartjs-plugin-datalabels.min.js" integrity="sha512-JPcRR8yFa8mmCsfrw4TNte1ZvF1e3+1SdGMslZvmrzDYxS69J7J49vkFL8u6u8PlPJK+H3voElBtUCzaXj+6ig==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/chart.js-plugin-labels-dv/dist/chartjs-plugin-labels.min.js"></script>
</head>
<body>
<section class="container">
<div class="sub_container">
<div className="trans_header">
<div className="payment_onetxt">
<p className="box_txtone">Chart.js — Bar Chart</p>
</div>
<div className="payment_onetxt trans_selectbox">
<select id="selected_box" >
</select>
</div>
</div>
<div>
<canvas id="barChart"></canvas>
</div>
</div>
<div class="sub_container">
<h2>Chart.js — Doughnut Chart</h2>
<div>
<canvas id="donutChart"></canvas>
</div>
</div>
</section>
<script>
//select tag handle & options create
const today = new Date();
const monthNames = Array.from({ length: 12 }).map((_, i) => new Date(today.getFullYear(), i).toLocaleString('default', { month: 'long' }));
const selectElement = document.getElementById('selected_box');
let selectValue=new Date().getMonth();
const options = monthNames.map((month, index) => {
return `<option value="${index}" ${index === selectValue ? 'selected' : ''}>${month}</option>`;
});
let handleMonthChange=(event)=>{
const selectedMonthIndex = event.target.value;
barChart.data.labels=getCurrentMonthDates(Number(selectedMonthIndex));
barChart.update()
}
selectElement.innerHTML = options;
selectElement.addEventListener('change', handleMonthChange);
//get month Data
let getCurrentMonthDates=(currentMonth)=>{
const todays = new Date();
const currentYear = todays.getFullYear();
// const currentMonth = todays.getMonth();
// Get the number of days in the current month
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
// Create an acurrentMonthrray to store the dates
const dates = [];
// Loop through each day in the month
for (let day = 1; day <= daysInMonth; day++) {
// Format the date as 'M/D/YYYY'
const formattedDate ="Day"+day
dates.push(formattedDate);
}
return dates;
}
const currentMonth = new Date().getMonth();
let currentMonthDates = getCurrentMonthDates(currentMonth);
let barChartDatas={
Xlabel :currentMonthDates,
Ylabel :["Above 8 Hours","Below 8 Hours","Over Time","Leave","Early Entry","Late","Absent","Early Out"],
bgs :["blue","indianred","#2196f3","pink","purple","yellow","orange",'grey'],
attendanceDatas:{
"Working Hours":[0, 6, 9, 8, 7, 6, 7, 8, 9, 9, 9, 0, 9, 0, 6, 7, 9, 6, 9, 9, 0, 7, 9, 9, 6, 8, 9, 6, 5, 9, 6],
"Over Time":[0, 2, 1, 0, 0, 0, 0, 4, 2, 1, 2, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0,2],
"Leave":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'l', 0, 0, 0, 0, 0, 0, 'l', 0, 0, 0, 0, 0, 0, 0, 0, 0],
"Early Entry":[0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"Late": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"Absent":['a', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'a', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0],
"Early Out":[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,1],
}
}
let initialState={
absent:false,
leave:false,
}
let showImages = () => {
const numDates = barChartDatas?.Xlabel?.length || 0;
const leaveData = barChartDatas?.attendanceDatas?.["Leave"];
const absentData = barChartDatas?.attendanceDatas?.["Absent"];
const imageData = Array.from({ length: numDates }, (_, index) => {
const isAbsent = absentData?.[index] === 'a';
const isLeave = leaveData?.[index] === 'l';
// Check if the respective legend item is visible in legendItems array
return isAbsent
? { src: "ab1.png", width: 30, height: 100 }
: isLeave
? { src: "https://cdn-icons-png.flaticon.com/128/422/422930.png", width: 30, height: 30 }
: null;
});
return imageData;
};
console.log(showImages())
const userImg = new Image();
userImg.src = "user.png";
const barAvatar = {
id: "barAvatar",
afterDraw(chart, args, options) {
const { ctx, chartArea: { top, bottom }, scales: { x, y } } = chart;
ctx.save();
chart.data.datasets.forEach((dataset, datasetIndex) => {
// Check if data is an array
if (Array.isArray(dataset.data)) {
dataset.data.forEach((datapoint, index) => {
// Check if value is above 0, null, or a number
if (typeof datapoint === 'number' && !isNaN(datapoint) && datapoint > 0) {
ctx.drawImage(userImg,
x.getPixelForValue(index) - 10,
chart.getDatasetMeta(7).data[index].y - 20,
18, 18);
}
});
}
});
ctx.restore();
}
};
// Define an empty array to store datasets dynamically
let datasets = [];
// Filter data for "Above 8 Hours" and "Below 8 Hours" based on "Working Hours"
let workingHoursData = barChartDatas?.attendanceDatas["Working Hours"];
let above8HoursData = workingHoursData.map((hours, index) => (hours > 8 ? hours : 0));
let below8HoursData = workingHoursData.map((hours, index) => (hours <= 8 ? hours : 0));
// Create datasets for "Above 8 Hours" and "Below 8 Hours"
datasets.push({
label: "Above 8 Hours",
data: above8HoursData,
backgroundColor:barChartDatas?.bgs[0], // Use the first color for "Above 8 Hours"
});
datasets.push({
label: "Below 8 Hours",
data: below8HoursData,
backgroundColor: barChartDatas?.bgs[1], // Use the second color for "Below 8 Hours"
});
barChartDatas?.Ylabel.slice(2).forEach((label, index) => {
datasets.push({
label: label,
data: barChartDatas?.attendanceDatas[label],
backgroundColor: barChartDatas?.bgs[index + 2]})
})
var ctx = document.getElementById("barChart").getContext('2d');
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: barChartDatas?.Xlabel,
datasets:datasets
} ,
options: {
plugins: {
datalabels: {
color: 'black',
rotation:-90,
align: 'end',
anchor: 'end',
display: function(context) {
return context.dataset.data[context.dataIndex] > 0;
},
font: {
weight: 'bold',
},
formatter: function(value, context) {
const datasetLabel = context.dataset?.label.toLowerCase().replace(/\s/g, '')
switch(datasetLabel) {
case 'absent':
return 'Absent';
case 'leave':
return 'Leave';
default:
return '';
}
},
},
legend: {
display: true,
onClick :async(e, legendItem, legend)=>{
const index = legendItem.datasetIndex;
const ci = legend.chart;
// const legendItemCh= legendItem?.text.toLowerCase().replace(/\s/g, '');
// const isVisible=ci.isDatasetVisible(index);
if (ci.isDatasetVisible(index)) {
ci.hide(index);
legendItem.hidden = true;
} else {
ci.show(index);
legendItem.hidden = false;
}
},
labels: {
usePointStyle: true,
pointStyle: 'circle'
}
},
labels: {
render: "image",
textMargin: 0,
images: showImages(),
usePointStyle: true,
useLineStyle: true,
},
},
// Core options
aspectRatio: 5 / 3,
layout: {
padding: {
top: 24,
right: 16,
bottom: 0,
left: 8
}
},
elements: {
line: {
fill: false
},
point: {
hoverRadius: 7,
radius: 5
}
},
scales: {
x: {
stacked: true
},
y: {
stacked: true,
beginAtZero: true,
min: 0,
max: 20,
ticks: {
stepSize: 2,
},
}
}
},
plugins: [ChartDataLabels,barAvatar],
});
</script>
```
</body>
</html>
```
|
Render Image update when I click legend chartjs |
|javascript|chart.js|bar-chart|chartjs-2.6.0|chartjs-plugin-annotation| |
null |
If you wanted to use `TreeMap`, you can write a custom `Comparator` as [mentioned in the comments](https://stackoverflow.com/questions/78236814/java-not-case-sensitive-map-key-where-key-is-pairstring-string#comment137929528_78236814) by [Federico klez Culloca](https://stackoverflow.com/users/133203/federico-klez-culloca). See also the other answers on how to do this.
However, `TreeMap` should only be used if you really want your entries to by sorted by key.
If you don't need sorting, you can also create a custom key class with `hashCode` and `equals` methods and use a `HashMap`:
```java
record CaseInsensitiveStringPair(String first, String second){
@Override
public boolean equals(Object other){
return other instanceof CaseInsensitiveStringPair o &&
first().toLowerCase().equals(o.first().toLowerCase()) &&
second().toLowerCase().equals(o.second().toLowerCase())
}
@Override
public int hashCode(){
return Objects.hash(first().toLowerCase(), second().toLowerCase());
}
}
```
If it's ok if the `String`s are stored in lowercase form, you could do that as well:
```java
record CaseInsensitiveStringPair(String first, String second){
public CaseInsensitiveStringPair(String first, String second){
this.first=first.toLowerCase();
this.second=second.toLowerCase();
}
}
```
and then use a
```java
Map<CaseInsensitiveStringPair, MyClass> map = new HashMap<>();
``` |
{"Voters":[{"Id":368354,"DisplayName":"Lennart"},{"Id":307138,"DisplayName":"Ocaso Protal"},{"Id":205233,"DisplayName":"Filburt"}]} |
I have created a website, where I connected it to firebase using Js.
I want to access the array 'correct' outside of the scope of the function, i.e. I want to make it accessible globally.
[![enter image description here][1]][1]
```
var mcqq = firebase.database().ref("mcq_choice/");
mcqq.orderByChild("mcq_choice").on("value", function (data) {
data.forEach(function (data) {
correct_option = data.val().correct)
});
});
console.log(correct_option)
```
The console.log(correct_option) is showing undefined error when being called outside the function.
[1]: https://i.stack.imgur.com/jB1C6.png |
**input**
idx = pd.MultiIndex.from_product([['A', 'B'], ['C', 'D']])
`idx`
MultiIndex([('A', 'C'),
('A', 'D'),
('B', 'C'),
('B', 'D')],
)
**desired output:**
like **[level0 values, level1 values]** (values can be Index or list and so on..)
**desired output of input:**
[['A', 'A', 'B', 'B'], ['C', 'D', 'C', 'D']]
my try1:
>>> idx.to_frame().T.values.tolist()
[['A', 'A', 'B', 'B'], ['C', 'D', 'C', 'D']]
my try2:
>>> [idx.get_level_values(i) for i in range(len(idx[0]))]
[Index(['A', 'A', 'B', 'B'], dtype='object'),
Index(['C', 'D', 'C', 'D'], dtype='object')]
**Both of my attempts satisfy the desired result.**
**However, is there a function that can execute this? Or is there a simpler way?**
|
Java Jackson update json 2nd value instance in array |
|java|json|jackson|nodes|objectmapper| |
I wanted to remove dates that were formatted like so
<p>8 March</p>
<p>8 February</p>
<p>8 Dec</p>
I was able to use following reg expression
/<([\w]*)\b[^>]*>(\d).*<\/\1>/
e.g. https://regexr.com/7u3sc |
today I ran into this problem, while using server actions with react-query
```js
const { data, error, isError } = useQuery({
queryKey: ["data"],
queryFn: getDataFromServer,
});
```
At first it seems okay, but running this `isError` is true, but `error` is undefined. After hours of debugging I understood that you have to invoke server actions for them to work, like this:
```js
const { data, error, isError } = useQuery({
queryKey: ["data"],
queryFn: () => getDataFromServer(),
});
```
As I understand next.js does something behind the scenes when you invoke server action in client components, I think maybe inserting some logic for fetching from server. At first I though that just putting the server action is enough and it will act like a normal async function, but it seems without invoking it doesn't work.
Could somebody explain what is happening here? What next.js does behind the scenes? Why can't I just give it the function without invoking it first, like a normal async function would work?
I'm using next.js v14 with app router.
|
What next.js does behind the scenes when you call server actions inside client components? |
|reactjs|next.js13|react-query|app-router| |
I have spring boot BE running on port 8080 on my server with nginx and ssl cert.
I have forwarded ports on my router 80 and 443 to the server.
Also i have ddns in no-ip.
This all works correctly.
Now i started developing mobile app with React Native and Expo. When I try to call some endpoint on my BE it works correctly when I open it in web browser. After I try to open it in physical device, only network error is printed.
For example Im trying to show this image: https://prieskumnici-is.ddns.net/api/img/bg/default/day.jpg
or call this endpoint: https://prieskumnici-is.ddns.net/api/api/background
when i load the image in emulator locally it also works (http://192.168.1.35:8080/...)
the endpoints are correct as im using them in my angular webpage
So I assume the problem is in nginx or Spring boot configuration
Also there are no logs in nginx nor Interceptor in BE gets any request
There are som codes:
nginx config
```
http {
client_max_body_size 500M;
server {
listen 443 ssl;
server_name prieskumnici-is.ddns.net localhost;
ssl_certificate C:/nginx/ssl/prieskumnici-is.crt; # Path to your SSL certificate
ssl_certificate_key C:/nginx/ssl/prieskumnici-is.key; # Path to your SSL private key
large_client_header_buffers 4 8096k;
location /api/ {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
root "C:\Users\Singi\Desktop\prieskumnici\prieskumnici-ui\dist\prieskumnici-ui";
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
types {
text/html html htm shtml;
text/css css scss;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js mjs;
application/atom+xml atom;
application/rss+xml rss;
}
}
}
```
RN
```
return <ImageBackground source={{uri: "https://prieskumnici-is.ddns.net/api/img/bg/default/day.jpg"}} resizeMode="cover" style={{height: '100%'}}>
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Home</Text>
</View>
</ImageBackground>
```
I dont know what is relevant from Spring Boot for this issue
To summarize: API and nginx wont recieve request from Physical device with React Native app over internet
I tried to load any other API on the device and it works correctly, also tried to load image from other page and works fine: https://www.prieskumnici.sk/assets/img/banner_zbor.png |
I have a npc class which has a method called `chase` that is referenced inside the `update` function. when `chase` is called it says its not a function or it's not defined. I have another method being referenced in the same way that works.
chase()
{
this.Phaser.Physics.moveToObject(NPC_spr, player_spr, 100);
this.anims.play('NPC',true);
}
chase method in npcClass.js
bullet_ary = bulletGroup.getChildren();
for (let bullet_spr of bullet_ary)
{
bullet_spr.updateMe();
}
NPC_ary = npcGroup.getChildren()
for (let npc_spr of NPC_ary)
{
npc_spr.chase();
}
`chase` is called at `npc_spr.chase();` which is in the update function, this creates an error while above the `bullet_spr.updateMe()` works. `updateMe` is also a method.
what I expected to happen was for the method to be called like the one above for the bullets. I have tried many different ways of rewriting it but everything results in the not defined or not a function error.
Error in console - Uncaught TypeError: npc_spr.chase is not a function |
I am looking for a quick and easy way to integrate PayPal in my website.
So far, I have searched many hours and also found tremendous information about it. (Most of them are out of date).
I know there are many options to go, but it also makes me confused about which way I should choose.
Now, what I want is that :
1. There is only one product on my website and the price depends on hours.
Say 1 hour for $15, when users select how many hours they want to stay, the Total Price will also need to be updated automatically.
2. I want to use PayPay Payment Button, because I think it's the simplest way to go(if its abilities meet my requirement above)
But in the generated JavaScript for that button:
<script src="https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=myID"
data-button="buynow"
data-name="AP Farm Visit"
data-amount="1"
data-currency="AUD"
data-shipping="0"
data-tax="0.1"
data-callback="https://apf.azurewebsites.net/Event/PayPal"
data-env="sandbox">
</script>
<a href="javascript:close()">Cancel</a>
Now questions:
1. How to change the value for data-amount field. (I think it could be done by JavaScript?)
2. How to write the back-end method `public ActionResult PayPal(FormCollection form)` to get PayPal's responses
3. What fields does the PayPal response have?
4. What do I need to set up in the PayPal's Profile under Selling Tools?
|
If you want to use code inside `on***=""` tag
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<input type="text" onchange="{
console.log('anything');
}"
<!-- end snippet -->
You can just use {} brackets it be like a export default but you still can use this and events |
I wrote a small python package that does this for float32 arrays. **~2.3x speedup** compared to np.amax and np.amin.
Usage:
`pip install numpy-minmax`
```
import numpy_minmax
min_val, max_val = numpy_minmax.minmax(arr)
```
The algorithm is written in C and is optimized with SIMD instructions. The code repository is here: https://github.com/nomonosound/numpy-minmax |
Issue with Restricting Number Input Range in TextField using ParseableFormatStyle |
Then you are in the realm of undefined behaviour.
The C standard does not say in what order arguments are evaluated.
So on one compiler the right 'a' might be evaluated first, then ```a=a+5``` and then the first will be 15.
Then you'll get 15, 15, 10.
Another compiler will evaluate the other way around.
Then you'll get 10, 15, 15 |
> The APP explicitly states the collection and usage rules to users in the form of privacy policy pop ups. Without the user's consent, there is a behavior of collecting device MAC address, IMEI, and other information.
> [Test Action] Initiate privacy compliance detection
> Read the current running service
> Pop up privacy policy
> The stack information is as follows:
> At android.app ActivityManager. getRunningServices()
> At com. mapbox. common LifecyclUtils. hasServiceRunningInForeground (LifecyclUtils. kt: 96)
> At com. mapbox. common LifecycleUtils. getLifecycleState (LifecycleUtils. kt: 102)
> At com. mapbox. common LifecycleService.onCreate (LifecycleService. kt: 106)
> At android.app ActivityThread. handleCreatService (ActivityThread. java: 3392)
> At android.app ActivityThread- Wrap4 (Unknown Source: 0)
> At android.app ActivityThread $H.handleMessage (ActivityThread. java: 1730)
> At android.os Handler. dispatchMessage (Handler. java: 106)
> At android.os Looper. loop (Looper. java: 164)
> At android.app ActivityThread. main (ActivityThread. java: 6554)
> At Java. lang. reflect Method. invoke (Native Method)
> At com. android. international. os RuntimeInit $MethodAndArgsCaller. run (RuntimeInit. java: 558)
> At com. android. international. os ZygoteInit. main (ZygoteInit. java: 810)
> How to prevent mapbox from accessing backend running services |
How to prevent mapbox from reading the currently running service |
|android| |
null |
{"OriginalQuestionIds":[3450582],"Voters":[{"Id":4386427,"DisplayName":"Support Ukraine","BindingReason":{"GoldTagBadge":"c"}}]} |
## *JTOpen Lite* & *JTLite*
Instead of the libraries that you are trying to use, I recommend using IBM's *JTOpen Lite* and *JTLite* libraries, which are specifically designed for use on Android.
For more information, please see:
- IBM support page, [*JTOpen Lite and JTLite - enabling mobile devices which use java*][1].
- [my answer to a related question](https://stackoverflow.com/questions/15374219/app-wont-recognize-function-in-non-android-jar/15539184#15539184).
[1]: https://www.ibm.com/support/pages/jtopen-lite-and-jtlite-enabling-mobile-devices-which-use-java |
I'm creating a Vite, React project and using FCM.
I have a `src/firebase-messaging-sw.js` service worker file that accesses environment variables via `import.meta`. The FCM SDK attempts to fetch the `firebase-messaging-sw.js` file at the root level via `GET http://localhost:5173/firebase-messaging-sw.js`.
I tried configuring Vite's dev server proxy to serve `src/firebase-messaging-sw.js` for requests to `/firebase-messaging-sw.js`. Now I'm getting `Uncaught SyntaxError: Cannot use 'import.meta' outside a module (at firebase-messaging-sw.js:1:8)` for the `GET http://localhost:5173/firebase-messaging-sw.js` request.
How can I fix this while keeping the `firebase-messaging-sw.js` file in the src folder?
```ts
export default defineConfig({
// ...
server: {
proxy: {
"/firebase-messaging-sw.js": {
target: "http://localhost:5173/",
changeOrigin: true,
rewrite: (path) => (
path.replace(
/^\/firebase-messaging-sw.js/,
"/src/firebase-messaging-sw.js"
);
),
},
},
},
build: {
target: "es2022",
rollupOptions: {
input: {
"main": "./index.html",
"firebase-messaging-sw": "./src/firebase-messaging-sw.js",
},
output: {
entryFileNames: (chunkInfo) => {
return chunkInfo.name === "firebase-messaging-sw"
? "[name].js" // Put FCM service worker in root
: "assets/[name]-[hash].js"; // Other main app JS in `assets/`
},
},
},
},
}
``` |
I am developing an Office Word add-in, and the frontend is built with Vue.js 2. I am facing challenges while implementing the login functionality. My goal is to open the default browser and redirect users to my website when they click the login button on the add-in. If the user is already logged into my website, I want to redirect them directly to the authorization page. If the user is not logged in, I want them to log in first and then proceed to the authorization page.
I have referred to the implementation approach of the "IconScout" add-in, but I haven't been able to solve the problem. Are there any Vue.js 2 examples or suggestions for a similar feature?
The frontend of the add-in is developed using Vue.js 2.
The authorization page is hosted on my website.
The add-in needs to obtain relevant information after the user completes the authorization. |
How to Implement External Website Authorization Login in an Office Add-in? |
|office-addins| |
null |
I have a handful of data objects floating around my code which have a large number of fields of the same type:
```
struct AsStruct {
mass: i32,
height: i32,
energy: i32,
age: i32,
radioactivity: i32,
}
```
(actual examples would have more fields - like 20+).
Sometimes but not always, I'm dealing with these fields in a collective way, and it would be better to have something like a `Map<String, i32>`
```
pub const ALL_STATS: [&str; 5] = ["mass", "height", "energy", "age", "radioactivity"];
struct AsMap {
data: HashMap<String, i32>,
}
```
This latter model lets me treat some things in a neat programmatic way. For instance, below are functions to generate random versions of each:
```
pub fn generate_map() -> AsMap {
let mut map = HashMap::new();
for s in ALL_STATS.iter() {
map.insert(s.to_string(), rand::random::<i32>() % 10);
}
AsMap { data: map }
}
pub fn generate_struct() -> AsStruct {
AsStruct {
mass: rand::random::<i32>() % 10,
height: rand::random::<i32>() % 10,
energy: rand::random::<i32>() % 10,
age: rand::random::<i32>() % 10,
radioactivity: rand::random::<i32>() % 10,
}
}
```
Obviously, the "Map" version will scale much more easily, and require less refactoring as stats change. On the other hand, there's also times when it's preferable to have the stricter `AsStruct` definition, which can be accessed by more concise syntax and doesn't need extra code to handle missing keys, etc.
I can write translations between the two, or put some set of getters and setters on the `AsStruct` one to allow fields to be treated as keys. This would involve a great deal of boiler plate, however, and feels like a worthy use case for something like a `derive` macro. I can also imagine a lot of additional nice-to-have features that could be added to such a solution, such as typed keys, support for structs with fields of different types, etc.
So my question is: Has this already been solved? Is there a reason this is a bad idea and I should go with one or the other? Is there a standard pattern for having my cake and eating it too in such situations? |
I am curious about how major top social media apps updating their UI without user interaction. I want to implement same in flutter mobile app. I have gone through dynamic feature (On-Demand feature in android)
[Deferred Components][1]
[1]: https://docs.flutter.dev/perf/deferred-components
But, Don't know do play store allow to upload only specific component.
If anyone have please help me. |
null |
I want to implement a Google Mobile Ads in unity, and I see [RegisterEventHandlers](https://developers.google.com/admob/unity/rewarded#listen_to_rewarded_ad_events) to handle some event for `RewardedAd` and `InterstitialAd`. I've seen their [example](https://github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld) but they defined the `RegisterEventHandlers` one by one even though the event name is same, and I intend to create one `RegisterEventHandlers` to handle both `RewardedAd` and `InterstitialAd` event.
> Please forgive me if it’s a basic question, I’ve only been learning Unity and c# for less than 3 weeks.
I've tried to defined a `RegisterEventHandlers` but I'm stuck about how do I defined an input parameter that accept `RewardedAd` and `InterstitialAd` type like this
```csharp
private static RewardedAd _rewardBaseVideo;
private static InterstitialAd _interstitialAd;
private void RequestAdmobRewardVideo()
{
//another code
_rewardBaseVideo = ad;
RegisterEventHandlers(ad);
}
private void RequestAdmobInterstitial()
{
//another code
_interstitialAd = ad;
// Error: Argument 1: cannot convert from 'GoogleMobileAds.Api.InterstitialAd' to 'GoogleMobileAds.Api.RewardedAd'
RegisterEventHandlers(ad);
}
// how do I dynamically declaring `RewardedAd` and `InterstitialAd` input type
private void RegisterEventHandlers(RewardedAd ad)
{
}
```
I've also tried to defined RegisterEventHandlers like this [SO Answer](https://stackoverflow.com/a/965593/8943429):
```
private void RegisterEventHandlers<T>(T ad) where T: RewardedAd, InterstitialAd
{
}
```
but I got an error `The class type constraint 'InterstitialAd' must come before any other constraints`.
so how do i defined RegisterEventHandlers gracefully accept both `RewardedAd` and `InterstitialAd`? |
Basically exactly what is described here in the archived forum in this post from 2018!
https://developer.xero.com/community-forum-archive/discussion/70563025
It's been 6 years. Is there really still no way to edit an invoice with a $0 balance? What are some best practices to avoid this? Just create a new invoice?
An issue we are encountering - we are unable to edit Authorised Invoices that have a Total of 0, on Xero it is marked as Paid (even though no payments are applied against it) so when we want to edit the invoice we are getting back the error
"Invoice not of valid status for modification"
HOWEVER, it is possible to just log on to the Xero website, edit the Invoice line-item amount to anything, and then we are able to edit the same invoice just fine over the API.
Since we are Partner application, you can't anticipate these use cases - when we push from our side, if it is making a new invoice that doesn't exist on Xero and the Total equals 0 we always send it as a DRAFT, but if it already exists on Xero as an AUTHORISED Invoice - we have no control over that.
Essentially what I am asking is, can it be fixed so that $0 AUTHORISED Invoices can be edited via API, since if it's a $0.1 AUTHORISED Invoice - we can edit it just fine. |
Invoice API - Unable to edit Authorised $0 Invoices |
|xero-api| |
null |
Just check identifier not to be null and everything works fine. change `convertToSnakeCase` method as this:
private Identifier convertToSnakeCase(final Identifier identifier) {
if (identifier == null) {
return null;
}
final String regex = "([a-z])([A-Z])";
final String replacement = "$1_$2";
final String newName = identifier.getText().replaceAll(regex, replacement).toLowerCase();
return Identifier.toIdentifier(newName);
}
|
Serving service worker file in src in Vite dev mode |