instruction stringlengths 0 30k ⌀ |
|---|
Child component not re-rendering after parent component gets updated |
|reactjs| |
|python|nicegui| |
I am coding app in expo using sqlite databse. On ios everthing is OK, but on android its not working.
LOG Error [Error: Error code : no such table: cars]
import React, { useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import * as SQLite from 'expo-sqlite';
import * as Notifications from 'expo-notifications';
import HomeScreen from './Screens/HomeScreen';
import AddCarScreen from './Screens/AddCarScreen';
import CarDetailScreen from './Screens/CarDetailScreen';
import EditCarScreen from './Screens/EditCarScreen.js';
// Funkce pro inicializaci databáze
const initializeDatabase = () => {
const db = SQLite.openDatabase('MyCars.db');
db.transaction((tx) => {
tx.executeSql(
`CREATE TABLE IF NOT EXISTS cars (
id INTEGER PRIMARY KEY AUTOINCREMENT,
brand TEXT,
model TEXT,
licensePlate TEXT,
vin TEXT,
technicalInspectionDate TEXT,
serviceInspectionDate TEXT,
highwayStampValidityDate TEXT,
techInspNotif1 TEXT,
techInspNotif2 TEXT,
servInspNotif1 TEXT,
servInspNotif2 TEXT,
highwayStampNotif1 TEXT,
highwayStampNotif2 TEXT
);`,
[],
() => console.log('Table cars created successfully'),
(error) => console.log('Error creating table: ' + error.message)
);
});
};
const Stack = createNativeStackNavigator();
const App = () => {
useEffect(() => {
initializeDatabase();
registerForPushNotificationsAsync();
}, []);
// Funkce pro požádání o zapnutí notifikací
async function registerForPushNotificationsAsync() {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
alert('Omlouváme se, nemáme povolení zasílat vám push notifikace.');
return;
}
// Pokud chcete získat a využít token, doplňte kód zde
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Home'>
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='AddCar' component={AddCarScreen} />
<Stack.Screen name='CarDetail' component={CarDetailScreen} />
<Stack.Screen name='EditCar' component={EditCarScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
i have no idead why its not working on android, i tried emulator in android stuio, expo go app and even installed apk on physical device
|
Expo - Android sqlite no such table |
|android|sqlite|expo| |
null |
This is the pubspec.yaml. I defined the fonts that I am going to use and I copied the font file to fonts directory of my android project.
```
name: your_flutter_app
description: A new Flutter project
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
math_expressions: ^2.0.0 # Add this line to include the math_expressions package
flutter:
fonts:
- family: My-font
fonts:
- asset: fonts/Yarndings20Charted-regular.ttf
```
And this is my main.dart:
```
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Scaffold (
appBar: AppBar(
title: Text('my First App'),
centerTitle: true,
backgroundColor: Colors.amber.shade100,
),
body: Center(
child: Text(
'I am Haroon',
style: TextStyle(
fontSize: 20,
color: Colors.green,
fontFamily: 'My-font',
),
),
),
floatingActionButton: FloatingActionButton(
child: Text('click'),
onPressed: () {
//Something Here;
},
backgroundColor: Colors.green,
),
),
));
```
I used pub.get and update dependencies. But none worked! |
There is a problem with the request entity - You are not allowed to create 'iOS' profile with App ID 'XXXX' |
|ios|react-native|expo|eas| |
For anyone coming from SwiftUI, adding an empty image name to `Info.plist` should work as well.
<key>UILaunchScreen</key>
<dict>
<key>UIImageName</key>
<string></string>
</dict>
[![Info.plist configuration][1]][1]
[1]: https://i.stack.imgur.com/cCSGx.png |
I would like to know how to add a soft constraint in the scenario below:
There a group with total 4 people and they are allowed to conduct 1 / 2 tasks, and the preference is 4 people in one task —> evenly split 2 teams (2 people per team) for 2 tasks —> 3 people for 1 task and the rest 1 for another task
How can I compose the soft constraint that if 2 out of 4 / all 4 are true, there will has no penalty, otherwise will do the penalty.
Thanks for your advise and instruction !! |
Google or-tools soft constraint issue |
|python|optimization|or-tools| |
|mysql|inno-setup| |
`psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin"`
Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker.
I build a project on docker with django-cookiecutter template, all settings are default. I put a gin index to one of my string fields, migrations running successfully, `pg_trgm` extention is being created successfully, but if I try to test my project with pytest I got this error.
Here is my `pytest.ini`
```
[pytest]
DJANGO_SETTINGS_MODULE = config.settings.test
```
Here is my test settings file's database configuration: `test.py`
```
DATABASES['test'] = { # noqa
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'test',
'PASSWORD': 'test',
'USER': 'test',
'HOST': 'localhost',
'PORT': 5454,
}
```
This is part of the migration which creates the extention `pg_trgm` and puts an index to the field given
```
migrations.AddIndex(
model_name='<model_name>',
index=django.contrib.postgres.indexes.GinIndex(fields=['field_name'], name='field_name_gin_idx', opclasses=['gin_trgm_ops']),
),
```
And this is the whole traceback which I am getting:
```
self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>
sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None
ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>})
def _execute(self, sql, params, *ignored_wrapper_args):
self.db.validate_no_broken_transaction()
with self.db.wrap_database_errors:
if params is None:
# params default might be backend specific.
> return self.cursor.execute(sql)
E psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin"
/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:82: UndefinedObject
The above exception was the direct cause of the following exception:
request = <SubRequest '_django_setup_unittest' for <TestCaseFunction test_correct_insurance_company_name>>
django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0xffff7fe702b0>
@pytest.fixture(autouse=True, scope="class")
def _django_setup_unittest(
request,
django_db_blocker: "_DatabaseBlocker",
) -> Generator[None, None, None]:
"""Setup a django unittest, internal to pytest-django."""
if not django_settings_is_configured() or not is_django_unittest(request):
yield
return
# Fix/patch pytest.
# Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991
# After pytest 5.4: https://github.com/pytest-dev/pytest-django/issues/824
from _pytest.unittest import TestCaseFunction
original_runtest = TestCaseFunction.runtest
def non_debugging_runtest(self) -> None:
self._testcase(result=self)
try:
TestCaseFunction.runtest = non_debugging_runtest # type: ignore[assignment]
> request.getfixturevalue("django_db_setup")
/usr/local/lib/python3.9/site-packages/pytest_django/plugin.py:490:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.9/site-packages/pytest_django/fixtures.py:122: in django_db_setup
db_cfg = setup_databases(
/usr/local/lib/python3.9/site-packages/django/test/utils.py:179: in setup_databases
connection.creation.create_test_db(
/usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py:74: in create_test_db
call_command(
/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py:181: in call_command
return command.execute(*args, **defaults)
/usr/local/lib/python3.9/site-packages/django/core/management/base.py:398: in execute
output = self.handle(*args, **options)
/usr/local/lib/python3.9/site-packages/django/core/management/base.py:89: in wrapped
res = handle_func(*args, **kwargs)
/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py:244: in handle
post_migrate_state = executor.migrate(
/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:117: in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:147: in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py:227: in apply_migration
state = migration.apply(state, schema_editor)
/usr/local/lib/python3.9/site-packages/django/db/migrations/migration.py:126: in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
/usr/local/lib/python3.9/site-packages/django/db/migrations/operations/models.py:761: in database_forwards
schema_editor.add_index(model, self.index)
/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py:218: in add_index
self.execute(index.create_sql(model, self, concurrently=concurrently), params=None)
/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py:145: in execute
cursor.execute(sql, params)
/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:66: in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:75: in _execute_with_wrappers
return executor(sql, params, many, context)
/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:84: in _execute
return self.cursor.execute(sql, params)
/usr/local/lib/python3.9/site-packages/django/db/utils.py:90: in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>
sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None
ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>})
def _execute(self, sql, params, *ignored_wrapper_args):
self.db.validate_no_broken_transaction()
with self.db.wrap_database_errors:
if params is None:
# params default might be backend specific.
> return self.cursor.execute(sql)
E django.db.utils.ProgrammingError: operator class "gin_trgm_ops" does not exist for access method "gin"
/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py:82: ProgrammingError
```
I want to run tests with pytest and got this problem which is actually not causing any problem while project is running, gin index is actually working. But only when I run a test no matter its django's `manage.py test` or `pytest` it fails with the error above. If I comment out the part of migration which should generate an index it works. |
# Current Problem
I am trying to productionize a Python application. This is not easy because Python does not support a way of creating a single compiled binary from the source code. Furthermore Python does not support a natural way of creating shared libraries. I will explain this in further detail in the following section.
## Python and Shared Libraries
Most languages offer some relatively convenient way of productionizing code. This usually involves:
- Creating some shared libraries containing code which is common to a project
- Creating executable files which use the shared libraries (and maybe other libraries)
Examples:
- Java has a way to bundle code into a `.jar` file. There are tools like Maven and Gradle to assist with the process of deployment and bundling.
- With languages like C++ and C, typically one builds binary libraries and binary executable files. These can then be deployed. There is a way to link a binary executable such that it contains all the shared library code.
- Rust has Cargo which typically builds individual binary executables containing all relevant code.
Python works a bit differently, because the interpreter process only knows about the current working directory path and any paths which have been added to the `PYTHONPATH` environment variable.
- Modifying the `PYTHONPATH` environment variable isn't generally advisable as it doesn't scale well and results in an additional overhead in maintaining its value.
This means that either;
- Python executables must be a single file and there can be no shared code between executables
- or, any shared code has to go in a libary which must be placed in the same current working directory as the executables themselves
This suggests a project structure like this:
```
my-project/
bin/
executable1.py
executable2.py
...
lib1/
__init__.py
...
lib2/
__init__.py
...
```
Clearly we don't build projects like this. Putting all the shared library code in the same directory as executable files is already weird enough. The stucture also breaks if we want to have shared library code and multiple directories under `bin` for different "groups" of executables. For example, it is not possible to create two subdirectories under `bin` called `group1` and `group2` and share common Python code in a shared library used by both groups.
**This is why I say *Python does not support shared libraries*.** You can build a shared library, but you need to use some other tool to do it. (Unless you resort to modifying `PYTHONPATH`. Let's assume we don't want to do that.)
## Solutions to Python Shared Libraries Problems
In reality, we would use a tool like virtualenv (venv) or Poetry (which essentially manages virtualenvs) to allow us to defer common library code to some other directory, and to enable the Python interpreter to find it.
# My current workflow situation
Until now, I have been using venv in interactive mode to develop Python software.
This means that I have a project structure like this
```
my-project
.venv/...
bin/
...
src/
lib1/...
lib2/...
pyproject.toml
```
and I have been using the venv in interactive mode:
```
$ .venv/bin/activate
$ pip3 install -e .
```
This is great for development, because if the library code under `src` is changed, those changes show up "live". (Meaning there is no bundle, install step required. Just run the executable and the "current" code is in use.)
It isn't so good for deployment.
# Why Docker?
My first approach to trying to "install" a production ready version of the code was to do the following:
- Use `systemd` to manage processes (starting and stopping)
- Copy the executable code from the `bin` folder to some "deployment" location on the system (for example `/opt/my-project/bin/`)
- Build a wheel (`.whl`) file
- Install the `whl` system-wide
I did not get as far as the final two steps, as I realized this was probably not a good approach. There are some problems with this:
- The point of using a virtual environment was to avoid having to install packages with `pip` system wide. It therefore doesn't make a lot of sense to create a `whl` and install that system wide.
- I also do not know how I would use a virtual environment in this context. I described copying the executable Python files to some directory like `/opt` which is (obviously) outside of the "development" directory which contains the `.venv`.
- This whole idea doesn't seem to make a lot of sense
**This leads me to believe using Docker results in a much more sensible approach.** We *can* install a `whl` system-wide inside a Docker container.
- On reflection, I actually don't think there is a sensible way to productionize and deploy Python code *without using Docker*. If anyone has any thoughts on that it would be great to get some feedback.
# The Docker Approach and Current Issues
I don't currently understand how to create a Docker image and how to install a `whl` file into it.
Here's how I think the process should work:
1. Build the Python Shared Libraries Code into a Wheel
2. Create a Docker container using a Python distribution image as a base
3. Copy the Wheel to the Docker container
4. Install the Wheel within the Docker container
5. Copy remaining executable Python code to the Docker container (where should it go?)
6. Set the default entry point of the Container to be one of the Python executables
7. There are then additional questions about "nice extras", for example adding to the `PATH` or possibly renaming a `.py` executable so that it looks like a regular executable... maybe?
The reason I am confused is that I am using Poetry to manage the virtual envs for the development process (these are not needed in the production Docker image) and I do not understand how to perform the above steps becuase the Docker container will not have a venv or Poetry installed. But I am using both to run my code during the development process. (Outside of the Docker container.)
Here's what I have in a `pyproject.toml` right now:
```
[tool.poetry]
name = "docker-python-poetry-example"
version = "0.1.0"
description = ""
authors = ["Example <example@example.com>"]
readme = "README.md"
[tool.poetry.scripts]
example-executable = 'bin.example_executable:main'
[tool.poetry.dependencies]
python = "^3.11"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
```
I am confused because I do not understand where and when I should be using Poetry. Does the Docker container need Poetry installed to install the wheel? I don't think it should have this. |
Your problem is that you echo out the `$data` variable in PHP, so it's rendered initially.
Instead, you can fetch it from the `$wire` object.
```
@script
<script>
$wire.on('dataUpdated', () => {
var rawData = $wire.data;
console.log(rawData);
console.log('updated');
});
</script>
@endscript
``` |
A windowed function is processed at the same time as SELECT.
More specifically, this is the order of operations:
- FROM and JOINS
- WHERE
- GROUP BY
- HAVING
- ORDER BY
- SELECT
Notice how SELECT is processed last.
Therefore your queries are not the same. Your first query is filtering before the windowed function. The second query is filtering after. |
Here is the scenario / task:
The user is browsing online and as soon as he/she runs into a website that uses CDN (for example CloudFlare or any other reverse proxy) the browser the user is using has to do the following:
Either
1. Warn the user that the site is on CDN / reverse proxy.
or
2. Block the site by saying it's on CDN / reverse proxy.
Are there any extensions / plug in / scripts to achieve this? Would appreciate any comments / suggestions / insights. Many thanks in advance!
|
CDN Detector Extension / Script |
|proxy|reverse-proxy|cdn| |
I'm a basic developer working on a pet project and getting myself in knots on the best approach for displaying this in a React Native app via Flatlist.
First off, this is the format of the JSON file. There are approx 7,000 of these records in the file.
```
name: "Meeting 1"
timezone: "America/Los_Angeles"
day: 2
time: "19:00"
url: "https://teams.meetings.com/xyz321"
```
What I would like to do is;
1. Get the local timezone of the user and
2. Use this timezone to display all meetings occurring on the current day only in the local timezone and
3. only display the meetings that are happening within the next hour based on the user's current time.
4. Display these meeting as individual items within a React Native Flatlist.
I'd really appreciate if someone could offer some guidance. The DateTime functions are very difficult to get a handle on.
```
function calculateTimeDifference(timezone1, timezone2) {
// Get current date and time
const now = new Date();
const hourBefore = now.setHours(now.getHours() -1);
// Create DateTimeFormat instances for both timezones
const formatter1 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone1,
hour12: false,
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
const formatter2 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone2,
hour12: false,
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
const day1 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone1,
weekday: 'long',
});
const day2 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone2,
weekday: 'long',
});
// Format the current time in both timezones
const timeInZone1 = formatter1.format(hourBefore);
const timeInZone2 = formatter2.format(hourBefore);
const dayInZone1 = day1.format(now);
const dayInZone2 = day2.format(now);
// Convert the formatted times to Date objects
const dateInZone1 = new Date(`1970-01-01T${timeInZone1}Z`);
const dateInZone2 = new Date(`1970-01-01T${timeInZone2}Z`);
// Calculate the time difference in milliseconds
const timeDifferenceMs = dateInZone1 - dateInZone2;
// Convert milliseconds to hours
const hoursDifference = Math.abs(timeDifferenceMs / (1000 * 60 * 60));
console.log('-----------')
console.log(`The time at ${timezone1} is ${timeInZone1}.`);
console.log(`The time at ${timezone2} is ${timeInZone2}.`);
console.log(`The day at ${timezone1} is ${dayInZone1}.`);
console.log(`The day at ${timezone2} is ${dayInZone2}.`);
console.log(`The time difference between ${timezone1} and ${timezone2} is ${hoursDifference} hours.`);
// const hourSearch = hourBefore.substring(0,3);
const searchHour = timeInZone1.toString().substring(0,2) + ':00';
console.log(searchHour);
return searchHour;
}
```
|
I only wanted to hide the right sidebar, so after I dragged all icons to the left sidebar, the right sidebar automatically disappeared.
You could also right click on each icon and click "Hide" or "Move to" a different sidebar. |
Your code has circular dependencies: `game` imports `encounter` and `encounter` imports `game`. You also have a lot of logic in the module scope in `game`; module level logic is evaluated the first time a module is imported -- however, a module isn't finished importing until all its code is evaluated, so if you end up importing the module again in the course of its module definition code, weird things happen.
Firstly, don't have module level code -- use `if __name__ == "__main__":` blocks. This means your code won't run on import, only on direct execution.
See https://stackoverflow.com/questions/419163/what-does-if-name-main-do
Secondly, don't have circular imports -- if you need to share logic and can't justify keeping it in the imported module, create a third module imported by both. Here though, it looks like you can just move `current_hp` to `encounter` and remove the `import game` from `encounter`.
|
null |
Your code has circular dependencies: `game` imports `encounter` and `encounter` imports `game`. You also have a lot of logic in the module scope in `game`; module level logic is evaluated the first time a module is imported -- however, a module isn't finished importing until all its code is evaluated, so if you end up importing the module again in the course of its module definition code, weird things happen.
Firstly, don't have module level code -- use `if __name__ == "__main__":` blocks. This means your code won't run on import, only on direct execution.
See [What does `if __name__ == "__main__":` do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do)
Secondly, don't have circular imports -- if you need to share logic and can't justify keeping it in the imported module, create a third module imported by both. Here though, it looks like you can just move `current_hp` to `encounter` and remove the `import game` from `encounter`.
|
I had the same problem it was because of my web server configuration according to the doc: https://router.vuejs.org/guide/essentials/history-mode.html
You should have this for Apache
```
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
```
Or this for Nginx:
```
location / {
try_files $uri $uri/ /index.html;
}
``` |
Include `<fenv.h>` and use:
```c
int r = fesetenv(FE_DFL_DISABLE_DENORMS_ENV);
// check r == 0
```
From `man fegetenv`:
```none
The fesetenv() function attempts to establish the floating-point environment
represented by the object pointed to by envp. This object shall have been
set by a call to fegetenv() or feholdexcept(), or be equal to a floating-point
environment macro defined in <fenv.h>.
```
And from `/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/fenv.h` (gated behind an `__arm64__` ifdef check):
```c
/* FE_DFL_DISABLE_DENORMS_ENV
A pointer to a fenv_t object with the default floating-point state modified
to set the FZ (flush to zero) bit in the FPCR. When using this environment
denormals encountered by floating-point calculations will be treated as
zero. Denormal results of floating-point operations will also be treated
as zero. This calculation mode is not IEEE-754 compliant, but it may
prevent lengthy stalls that occur in code that encounters denormals. It is
suggested that you do not use this mode unless you have established that
denormals are the source of measurable performance problems.
Note that the math library, and other system libraries, are not guaranteed
to do the right thing if called in this mode. Edge cases may be incorrect.
Use at your own risk. */
extern const fenv_t _FE_DFL_DISABLE_DENORMS_ENV;
#define FE_DFL_DISABLE_DENORMS_ENV &_FE_DFL_DISABLE_DENORMS_ENV
```
Test code:
```c
#include <fenv.h>
#include <stdint.h>
#include <stdio.h>
typedef volatile union
{
float f;
uint32_t u;
} num_debug_t;
int main(void)
{
num_debug_t n = { .u = 0x00800001 };
printf("Hex value: 0x%08x\n", n.u);
printf("Float value: %e\n", n.f);
printf("===== Normalised =====\n");
num_debug_t d = { .f = n.f / 2.0f };
printf("Division result hex: 0x%08x\n", d.u);
printf("Division result float: %e\n", d.f);
int r = fesetenv(FE_DFL_DISABLE_DENORMS_ENV);
if(r != 0)
{
fprintf(stderr, "fesetenv returned %d\n", r);
return -1;
}
printf("===== Denormalised =====\n");
d.f = n.f / 2.0f;
printf("Division result hex: 0x%08x\n", d.u);
printf("Division result float: %e\n", d.f);
return 0;
}
```
Output:
```
Hex value: 0x00800001
Float value: 1.175494e-38
===== Normalised =====
Division result hex: 0x00400000
Division result float: 5.877472e-39
===== Denormalised =====
Division result hex: 0x00000000
Division result float: 0.000000e+00
```
Under the hood, this simply sets bit 24 (FZ) in the `FPCR` system register. |
I had a wrong connection manager in the Data Source pane. The Development PBI server could not reach the production connection that was chosen by mistake. That is why the Windows authentification failed. It worked once I changed the connection order to the dev server database. |
# Definition of STDIN, STDOUT, and STDERR
<br>
The OS' kernel of all operating systems use these 3 main **I/O (Input/Output)** streams, and these are **STDIN**, **STDOUT**, and **STDERR**. **STDIN** is the **I/O** stream that is processing information related to input, **STDOUT** is the **I/O** stream that is processing information related to output, and **STDERR** is the **I/O** stream that is processing information related to errors. All services, applications, and components of the OS' kernel use these streams to manipulate **I/O** information on any OS.
<br>
<br>
# Solution using STDOUT redirection
In the code provided by you, the issue defined is that you want to process the information provided by the operation of a **Batch** script without redirecting the **STDOUT** stream. The ways in which the **C#** application can read the output of the **Batch** script is either by using **files** (**e.g.** JSON configuration files), **Sockets**, **Pipes**, and the **STDOUT** stream. The aforementioned methods are **Inter-Process** communication methods ( You can check this link for more information: https://stackoverflow.com/a/76196178/16587692 ). These methods must be used because there is no direct communication channel between the **C#** application and the **Batch** script. In this situation the most viable method is to use the **STDOUT** stream. You can preserve the console colors by changing them through the **C#** application rather than changing them by passing arguments to the **Batch** script. You can also write the output in real time to the desired log file, but as a word of caution, do not read from the log file while the C# application is writing to that file because it will trigger a **Race Condition** and this may corrupt your **HDD/SSD** cells where the file is located.
```
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Operation().Wait();
Console.ReadLine();
}
private static void SetPermissions(string file_name)
{
#pragma warning disable CA1416 // Validate platform compatibility
// CHECK IF THE CURRENT OS IS WINDOWS
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) == true)
{
// GET THE SPECIFIED FILE INFORMATION OF THE SELECTED FILE
FileInfo settings_file_info = new FileInfo(file_name);
// GET THE ACCESS CONTROL INFORMATION OF THE SELECTED FILE AND STORE THEM IN A 'FileSecurity' OBJECT
System.Security.AccessControl.FileSecurity settings_file_security = settings_file_info.GetAccessControl();
// ADD THE ACCESS RULES THAT ALLOW READ, WRITE, AND DELETE PERMISSIONS ON THE SELECTED FILE FOR THE CURRENT USER
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow));
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Read, System.Security.AccessControl.AccessControlType.Allow));
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Delete, System.Security.AccessControl.AccessControlType.Allow));
// UPDATE THE ACCESS CONTROL SETTINGS OF THE FILE BY SETTING THE
// MODIFIED ACCESS CONTROL SETTINGS AS THE CURRENT SETTINGS
settings_file_info.SetAccessControl(settings_file_security);
}
else
{
// IF THE OS IS A UNIX BASED OS, SET THE FILE PERMISSIONS FOR READ AND WRITE OPERATIONS
// WITH THE 'UnixFileMode.UserRead | UnixFileMode.UserWrite' BITWISE 'OR' OPERATION
File.SetUnixFileMode(file_name, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
#pragma warning restore CA1416 // Validate platform compatibility
}
private static async Task<bool> Operation()
{
// Process object
System.Diagnostics.Process proc = new System.Diagnostics.Process();
string file_name = String.Empty;
string arguments = String.Empty;
// CHECK IF THE CURRENT OS IS WINDOWS AND SET THE FILE PATH AND ARGUMETS ACCORDINGLY
if(System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) == true)
{
file_name = @"C:\Users\teodo\PycharmProjects\Test\.venv\Scripts\python.exe";
arguments = @"C:\Users\teodo\PycharmProjects\Test\main.py";
}
else
{
file_name = @"python3";
arguments = @"/mnt/c/Users/teodo/PycharmProjects/Test/main.py";
}
// Path where the python executable is located
proc.StartInfo.FileName = file_name;
// Path where python executable is located
proc.StartInfo.Arguments = arguments;
// Start the process
proc.Start();
// Named pipe server object with an "In" direction. This means that this pipe can only read messages. On Windows it creates a pipe at the
// '\\.\pipe\pipe-sub-directory\pipe-name' virtual directory, on Linux it creates a Unix Named Socket in the '/tmp' directory
System.IO.Pipes.NamedPipeServerStream fifo_pipe_connection = new System.IO.Pipes.NamedPipeServerStream("/tmp/fifo_pipe", System.IO.Pipes.PipeDirection.In);
// Create a backlog text file if none is existent, set its permissions as Read/Write,
// and create a stream that allows direct read and write operations to the file
FileStream fs = File.Open("backlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
SetPermissions("backlog.txt");
try
{
// Wait for a client to connect synchronously
fifo_pipe_connection.WaitForConnection();
while (true)
{
// Initiate a binary buffer byte array with a size of 1 Kb
byte[] buffer = new byte[1024];
// Read the received bytes into the buffer byte array and also
// store the number of bytes read into an integer named 'read'
int read = await fifo_pipe_connection.ReadAsync(buffer, 0, buffer.Length);
// Write the received bytes into the 'backlog.txt' file
await fs.WriteAsync(buffer, 0, read);
// Flush the bytes within the stream's buffer into the file
await fs.FlushAsync();
// If the number of bytes read is equal to '0' there are no bytes
// left to read on the Pipe's stream and the read loop is closed
if (read == 0)
{
break;
}
}
}
catch
{
}
finally
{
fs?.DisposeAsync();
fifo_pipe_connection?.DisposeAsync();
}
return true;
}
}
}
```
# STDOUT redirection method output
[![Program STDOUT output][1]][1]
[![Program STDOUT file output][2]][2]
# Definition of FIFO Pipes
**FIFO Pipes**, also known as **Named Pipes**, are a type of socket that use the operating system's file system in order to facilitate information exchange between applications. **FIFO Pipes** are categorised into 3 categories and these are, **Inward Pipes**, **Outward Pipes**, and **Two-way Pipes**. **Inward Pipes** are pipes on which the **Pipe Server** can only receive information from the **Pipe Clients**, **Outward Pipes** are pipes on which the **Pipe Server** can only send information to the **Pipe Clients**, and **Two-way Pipes** are pipes on which the **Pipe Server** can both send and receive information to and from the **Pipe Clients**.
# Cross-platform solution using FIFO Pipes
If the integrity of the output must be preserved, FIFO pipes are the best option for an inter-process communication method. In this scenario an **Inward Pipe** will be the best solution due to the fact that the **C#** application must receive information from the **Python** application. In order to have cross-platform capabilities, both the **C#** and **Python** application use conditional statements to verify which OS platform the applications are running on.
<br>
## C# Application
```
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Operation().Wait();
Console.ReadLine();
}
private static void SetPermissions(string file_name)
{
#pragma warning disable CA1416 // Validate platform compatibility
// CHECK IF THE CURRENT OS IS WINDOWS
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) == true)
{
// GET THE SPECIFIED FILE INFORMATION OF THE SELECTED FILE
FileInfo settings_file_info = new FileInfo(file_name);
// GET THE ACCESS CONTROL INFORMATION OF THE SELECTED FILE AND STORE THEM IN A 'FileSecurity' OBJECT
System.Security.AccessControl.FileSecurity settings_file_security = settings_file_info.GetAccessControl();
// ADD THE ACCESS RULES THAT ALLOW READ, WRITE, AND DELETE PERMISSIONS ON THE SELECTED FILE FOR THE CURRENT USER
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow));
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Read, System.Security.AccessControl.AccessControlType.Allow));
settings_file_security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.Delete, System.Security.AccessControl.AccessControlType.Allow));
// UPDATE THE ACCESS CONTROL SETTINGS OF THE FILE BY SETTING THE
// MODIFIED ACCESS CONTROL SETTINGS AS THE CURRENT SETTINGS
settings_file_info.SetAccessControl(settings_file_security);
}
else
{
// IF THE OS IS A UNIX BASED OS, SET THE FILE PERMISSIONS FOR READ AND WRITE OPERATIONS
// WITH THE 'UnixFileMode.UserRead | UnixFileMode.UserWrite' BITWISE 'OR' OPERATION
File.SetUnixFileMode(file_name, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
#pragma warning restore CA1416 // Validate platform compatibility
}
private static async Task<bool> Operation()
{
// Process object
System.Diagnostics.Process proc = new System.Diagnostics.Process();
string file_name = String.Empty;
string arguments = String.Empty;
// CHECK IF THE CURRENT OS IS WINDOWS AND SET THE FILE PATH AND ARGUMETS ACCORDINGLY
if(System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) == true)
{
file_name = @"C:\Users\teodo\PycharmProjects\Test\.venv\Scripts\python.exe";
arguments = @"C:\Users\teodo\PycharmProjects\Test\main.py";
}
else
{
file_name = @"python3";
arguments = @"/mnt/c/Users/teodo/PycharmProjects/Test/main.py";
}
// Path where the python executable is located
proc.StartInfo.FileName = file_name;
// Path where python executable is located
proc.StartInfo.Arguments = arguments;
// Start the process
proc.Start();
// Named pipe server object with an "In" direction. This means that this pipe can only read messages. On Windows it creates a pipe at the
// '\\.\pipe\pipe-sub-directory\pipe-name' virtual directory, on Linux it creates a Unix Named Socket in the '/tmp' directory
System.IO.Pipes.NamedPipeServerStream fifo_pipe_connection = new System.IO.Pipes.NamedPipeServerStream("/tmp/fifo_pipe", System.IO.Pipes.PipeDirection.In);
// Create a backlog text file if none is existent, set its permissions as Read/Write,
// and create a stream that allows direct read and write operations to the file
FileStream fs = File.Open("backlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
SetPermissions("backlog.txt");
try
{
// Wait for a client to connect synchronously
fifo_pipe_connection.WaitForConnection();
while (true)
{
// Initiate a binary buffer byte array with a size of 1 Kb
byte[] buffer = new byte[1024];
// Read the received bytes into the buffer byte array and also
// store the number of bytes read into an integer named 'read'
int read = await fifo_pipe_connection.ReadAsync(buffer, 0, buffer.Length);
// Print the bytes sent by the Python application on the pipe
Console.WriteLine(Encoding.UTF8.GetString(buffer));
// Write the received bytes into the 'backlog.txt' file
await fs.WriteAsync(buffer, 0, read);
// Flush the bytes within the stream's buffer into the file
await fs.FlushAsync();
// If the number of bytes read is equal to '0' there are no bytes
// left to read on the Pipe's stream and the read loop is closed
if (read == 0)
{
break;
}
}
}
catch
{
}
finally
{
fs?.DisposeAsync();
fifo_pipe_connection?.DisposeAsync();
}
return true;
}
}
}
```
<br>
## Python Application
```
import os
import sys
import time
from rich.progress import track
import platform
import socket
fifo_write = None
unix_named_pipe = None
def operation():
try:
write("!!! Python Test !!!\n\n")
# Simulate work being done
set_range = range(20)
for i in track(set_range, description="Processing..."):
time.sleep(0.1)
# SEND THE CURRENT PROGRESS AS A PERCENTAGE OVER THE PIPE
write("Processing..." + str((100 / set_range.stop) * (i + 1)) + "%\n")
# CHANGE THE TERMINAL COLOR TO GREY
if platform.system() == "Windows":
os.system("color 08")
else:
print("\n\n")
os.system(r"echo '\e[91m!!! COLOR !!!'")
# PAUSE THE CURRENT THREAD FOR 2 SECONDS
time.sleep(2)
# CHANGE THE TERMINAL COLOR TO WHITE
if platform.system() == "Windows":
os.system("color F")
else:
os.system(r"echo '\e[00m!!! COLOR !!!'")
print("\n\n")
write("[ Finished ]")
except KeyboardInterrupt:
sys.exit(0)
def write(msg):
if platform.system() == "Windows":
fifo_pipe_write(msg)
else:
unix_named_socket_write(msg)
def fifo_pipe_write(msg):
try:
global fifo_write
if fifo_write is not None:
# WRITE THE STRING PASSED TO THE FUNCTION'S AS AN ARGUMENT
# IN THE FIFO PIPE FILE USING THE GLOBAL STREAM
fifo_write.write(msg)
except KeyboardInterrupt:
sys.exit(0)
def unix_named_socket_write(msg):
try:
global unix_named_pipe
if unix_named_pipe is not None:
unix_named_pipe.send(str(msg).encode(encoding="utf-8"))
except KeyboardInterrupt:
pass
def stream_finder() -> bool:
is_found = False
try:
# INITIATE A PIPE SEARCH SEQUENCE FOR 10 SECONDS
for t in range(0, 10):
try:
try:
# IF THE OS IS WINDOWS SEARCH FOR A PIPE FILE
if platform.system() == "Windows":
# IF PIPE IS FOUND RETURN TRUE AND STORE THE OPENED PIPE FILE STREAM GLOBALLY
global fifo_write
fifo_write = open(r"\\.\pipe\tmp\fifo_pipe", "w")
is_found = True
break
# ELSE, SEARCH FOR A NAMED UNIX SOCKET
else:
# IF SOCKET IS FOUND RETURN TRUE AND STORE THE OPENED SOCKET GLOBALLY
global unix_named_pipe
unix_named_pipe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
unix_named_pipe.connect("/tmp/fifo_pipe")
is_found = True
break
except FileNotFoundError:
# IF PIPE IS NOT FOUND
print("\n\n[ Searching pipe ]")
except OSError:
# IF PIPE IS NOT FOUND
print("\n\n[ Searching pipe ]")
# MAKE THE LOOP WAIT 1 SECOND FOR EACH ITERATION
time.sleep(1)
except KeyboardInterrupt:
sys.exit(0)
return is_found
if __name__ == "__main__":
try:
# INITIATE THE PIPE SEARCHING OPERATION
found = stream_finder()
# IF PIPE SEARCHING OPERATION IS SUCCESSFUL
if found is True:
print("\n\n[ Pipe found ]\n\n")
# INITIATE THE MAIN OPERATION
operation()
except KeyboardInterrupt:
sys.exit(0)
```
<br>
# FIFO Pipes output Windows
[![FIFO pipes output Windows][3]][3]
[![FIFO Pipes file output Windows][4]][4]
# FIFO Pipes output Linux
## Linux OS Details
[![Linux OS details][5]][5]
## Linux OS Output
[![FIFO pipes output Linux][6]][6]
[![FIFO Pipes file output Linux][7]][7]
[1]: https://i.stack.imgur.com/SrWv9.gif
[2]: https://i.stack.imgur.com/mFhJD.png
[3]: https://i.stack.imgur.com/78Q2v.gif
[4]: https://i.stack.imgur.com/7wc4B.jpg
[5]: https://i.stack.imgur.com/SDLYE.jpg
[6]: https://i.stack.imgur.com/P9il7.gif
[7]: https://i.stack.imgur.com/voxkv.jpg |
I am fairly new to Java, currently learning about lambda expressions.
so I wanted to use generic with the Consumer function to make it accept any type of parameter passed to it and just print it out
The consumer accepts the first generic as the type that must be passed to it as the first param
I specified it to be (? extends Object) (I thinks it means anything that extends object which means anything in java that is not primitive) so it should accept any parameter passed to it including the list I am creating, but no error happens.
```
Supplier<List<String>> listSupplier = () -> new ArrayList<>();
Supplier<List<String>> listSupplierTwo = ArrayList::new;
Consumer<? super Object> logger = (a) -> System.out.println(a);
Consumer<? extends Object> loggerTwo = System.out::println;
var result = listSupplier.get();
var resultTwo = listSupplierTwo.get();
logger.accept("fooooo"); // compiles
logger.accept(result); // compiles
loggerTwo.accept(resultTwo); // error
loggerTwo.accept("fooooo"); // error
```
when replacing the extends with super(? super Object)(I think it means anything that is super class of Object class which is nothing as super dosent extend anything) it accepts any param and everything works
I asked chatgpt which replied with
The code you provided should compile without errors because String does indeed extend Object in Java.
Consumer<? extends Object> loggerTwo = System.out::println;
loggerTwo.accept("fooooo");
I searched a lot maybe I have incorrect understanding of how extends and super works may be I am incorrectly using the wildcard ? should I only use it with only collections ?[code-clarification](https://i.stack.imgur.com/svqPt.png) |
Using java super and exends with lambda expressions |
|java|super|extends| |
null |
I want to make my code read a sheet of IDs and when someone enters the wrong ID the code removes the unmatched response from the google response sheet. Ok the code reads a sheet of ID numbers in the frirst column and then when someone fills out the google form the first question is ID Number. When they fill out the form and click submit if the ID number they typed in does not match an ID number in the google sheet then the code will remove the response from the form responses of the google form. The code should only keep the matched ID number responses submitted by the google form. It currently does not do that.
My current code below I am a bit of a newbie at this. I would appreciate any help in this its been driving me crazy for awhile. I am dying to get this to work and read the IDs sheet and remove the unmatched responses from the form responses sheet and keep only the matched responses. I am a teacher and the form is for Seniors only and I want to prevent students who are not seniors from having their responses recorded in the spreadsheet so thats why I am using a sheet called IDs because it contains all the ID numbers of just the seniors.
My current code below I am a bit of a newbie at this. I would appreciate any help in this its been driving me crazy for awhile. I am dying to get this to work and read the IDs sheet and remove the unmatched responses from the form responses sheet and keep only the matched responses. I am a teacher and the form is for Seniors only and I want to prevent students who are not seniors from having their responses recorded in the spreadsheet so thats why I am using a sheet called IDs because it contains all the ID numbers of just the seniors.
function removeUnmatchedResponses() {
try {
// Replace 'SPREADSHEET_ID' with the ID of your Google Sheets document
var spreadsheet = SpreadsheetApp.openById('1sh5dcQJPRJtbFpe7qVjpo7yIUwi5_mCGKrAnhWm-Hng');
// Get the "IDs" sheet by index (assuming it's the first sheet)
var idsSheet = spreadsheet.getSheets()[0]; // Change the index if the "IDs" sheet is not the first one
// Check if "IDs" sheet exists
if (!idsSheet) {
throw new Error("IDs sheet not found.");
}
// Get the Form Responses sheet
var formResponsesSheet = spreadsheet.getSheetByName("Form Responses");
// Check if Form Responses sheet exists
if (!formResponsesSheet) {
throw new Error("Form Responses sheet not found.");
}
// Get all the IDs from the "IDs" sheet
var idsRange = idsSheet.getRange("A:A");
var idsValues = idsRange.getValues().flat().filter(Boolean); // Assuming IDs are in column A
// Get the data range from the Form Responses sheet
var formResponsesRange = formResponsesSheet.getDataRange();
var formResponsesValues = formResponsesRange.getValues();
// Separate matched and unmatched responses
var matchedResponses = [];
var unmatchedResponses = [];
for (var i = 0; i < formResponsesValues.length; i++) {
var responseId = formResponsesValues[i][0]; // Assuming the ID is in the first column of the Form Responses sheet
if (idsValues.includes(responseId)) {
matchedResponses.push(formResponsesValues[i]);
} else {
unmatchedResponses.push(formResponsesValues[i]);
}
}
// Clear existing data in the Form Responses sheet
formResponsesRange.clear();
// Write back the matched responses
if (matchedResponses.length > 0) {
formResponsesSheet.getRange(1, 1, matchedResponses.length, matchedResponses[0].length).setValues(matchedResponses);
}
// Append the unmatched responses
if (unmatchedResponses.length > 0) {
formResponsesSheet.getRange(formResponsesSheet.getLastRow() + 1, 1, unmatchedResponses.length, unmatchedResponses[0].length).setValues(unmatchedResponses);
}
Logger.log("Unmatched responses removed successfully.");
} catch (error) {
Logger.log("Error: " + error.message);
}
}
|
i have made a web based project on school managment system in laravel . Now i want to add API in it.what changes or addtion do i need to make in application for example in the routes or controller.
i have'nt tried anything . just want to add the functionality of API. |
API addition to web based application (Laravel) |
|php|api|laravel-10| |
null |
Azure Scale Sets and Parallel Jobs |
I am writing code for _Roman Numeral Converter_ in the browser, currently learning Javascript. The problem is right on checking return statements in `console.log` I am getting the right answers, but somehow all tests are failing.
CODE:
```
let resstr = "";
let resarr = [];
function convertToRoman(num) {
let robj = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let okeys = Object.keys(robj); //getting keys for iteration
//loop to check numbers and adding roman numerals in array
okeys.some((key) => {
if (num >= robj[key]) {
//console.log(robj[key]);
resarr.push(key);
num = num - robj[key];
//console.log("number after subtraction is: " + num);
return true;
}
});
//end cases
if (num === 0) {
resstr = resarr.join("").toString();
console.log("operation done", resstr);
return resstr;
} else if (num !== 0) {
console.log("no 0", num);
return convertToRoman(num);
} else {
console.log("ended");
return true;
}
// console.log(resstr);
// return resstr;
}
```
For `convertToRoman(3999)`, `convertToRoman(1)`, `convertToRoman(2)` etc. I am getting the right answers on `console.log`, but browser tests are all failing like it is getting something else than the right answer. |
I have 2 SQL queries.
Query #1:
SELECT
SUM(PrincipalBalance)
FROM
(SELECT
lt.AccountId,
SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END)
- SUM(CASE
WHEN TransactionTypeId NOT IN (1, 2)
THEN PrincipalPortionAmount
ELSE 0
END) AS PrincipalBalance
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.STATUS <> - 1
GROUP BY
lt.AccountId
HAVING
SUM(Debit - Credit) > 1) T
Query #2:
SELECT
ISNULL(SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
- ISNULL(SUM(CASE
WHEN TransactionTypeId IN (43, 38, 4, 12, 7, 10)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.Status <> -1
Query #1 result is 80773498.0599999
Query #2 result is 81060946.8400006
but both result should be same. I don't get it, why the differences. How can i find what causing the differences
|
I want to change the return type of memoizer to `Future<List<MyModel>>` However, I can't seem to find a way to change it. It always return as `Future<dynamic>`
Here's my code:
final AsyncMemoizer _memoizer = AsyncMemoizer();
Future<List<MyModel>> getSometing() async {
return this._memoizer.runOnce(() async {
return await getData();
});
}
|
How to change the return type of memoizer? |
|flutter|dart| |
I would like to ask everyone, I have downloaded the SIDD Benchmark Noisy data set, and then used my denoising model to remove the noise. How do I check the PSNR and SSIM results of my denoising? Where can I find SIDD Benchmark GT? Let me calculate, or get the score through other methods? Thank you.
I don't know how to calculate PSNR and SSIM of SIDD Benchmark. |
How to calculate PSNR and SSIM of SIDD Benchmark, |
|python| |
null |
Playwright provides the option to use line numbers as well as the filename for debugging purpose via the command line.
As per documentation the below format needs to be used for debugging using line numbers
**npx playwright test example.spec.ts:10 --debug**
Note: I've tried the same but got an error.(Using a .js file)
**Playwright Version: 1.41.2**
**Steps to reproduce**
I've a file named UIBasicsTest.spec.js
And when I try to run the below command to open the debug mode, it throws an error
npx playwright test UIBasicsTest.spec.js:4 --debug
**Expected behavior**
I expect the debug functionality to work for specific lines as well just as mentioned in the official documentation.
**Actual behavior**
Error:
Error: No tests found.
Make sure that arguments are regular expressions matching test files.
You may need to escape symbols like "$" or "*" and quote the arguments. |
In my Flutter Project, I want to customize the font of a text, but it doesn't work |
|android|flutter|fonts| |
null |
Transforming the text in the URL, rather than just substituting it, can be achieved using the `RewriteMap` directive. The Apache httpd user guide has [a page detailing how to use RewriteMap](https://httpd.apache.org/docs/2.4/rewrite/rewritemap.html), which includes this example:
> Redirect a URI to an all-lowercase version of itself
>
> RewriteMap lc int:tolower \
> RewriteRule "(.*)" "${lc:$1}" [R]
The first line defines the map "lc" to be the built-in "tolower" function, and the second line applies that map to the back-reference $1 in a rewrite rule.
So in your example, you could use:
```
RewriteMap lc int:tolower
RewriteRule ^([^/]+)/*$ x/{lc:$1}.html [L,NC,END]
``` |
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}]} |
I am using reactive_forms for handling user input in my flutter project. Once double click ReactiveTextField copy/paste functionalities don't work only on iOS (working on android). What is the problem? Here is my code:
```
Widget _buildTextField() {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: ReactiveTextField<String>(
formControl: formControl as FormControl<String>?,
formControlName: name,
autofocus: autoFocus,
textAlign: TextAlign.start,
textAlignVertical: TextAlignVertical.top,
inputFormatters: [
LengthLimitingTextInputFormatter(maxLength),
...(formatters ?? []),
],
keyboardType: inputType,
obscureText: obscureText,
maxLines: maxLines,
style: size14weight400.copyWith(color: secondaryTextColor),
decoration: InputDecoration(
prefix: prefix,
suffixIcon: suffix,
labelText: style == CustomTextFieldStyle.withHint ? name.tr() : null,
labelStyle: size14weight400.copyWith(color: brandBlack60Color),
hintStyle: size14weight400.copyWith(color: secondaryTextColor),
floatingLabelBehavior: FloatingLabelBehavior.always,
fillColor: textFieldBackgroundColor,
filled: true,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
borderSide: BorderSide(color: primaryColor, width: 1.5),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
borderSide: BorderSide(color: errorColor, width: 1.5),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
borderSide: BorderSide(color: textFieldBorderColor, width: 1.5),
),
contentPadding:
EdgeInsets.symmetric(vertical: 15.5, horizontal: 16.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
borderSide: BorderSide(color: textFieldBorderColor, width: 1.5),
),
),
),
);
}
```
I am expecting to use default copy/paste funcs. |
copy/paste functionalities don’t work only on iOS |
|ios|flutter|dart|flutter-reactive-forms| |
I'm making a macro like this:
```swift
@attached(peer, names: arbitrary)
public macro Lazify(name: String, lock: Protectable) = #externalMacro(module: "MacroModule", type: "LazifyMacro")
```
It should be used to attach to a function declaration, to generate some other variables.
But I got the error `Circular reference expanding peer macros on <function_name>`, the code is below:
```swift
class SomeClass {
var _internal_lock: NSLock = .init()
static let classLock: NSLock = .init()
// Error: Circular reference expanding peer macros on 'createLazyVariable()'
@Lazify(name: "internalClassName", lock: SomeClass.classLock)
func createLazyVariable() -> String {
return "__" + NSStringFromClass(type(of: self))
}
}
```
If I change the `lock: Protectable` to `lock: String` then it's ok, but it won't have type check when using the macro.
And further if I use a instance property lock `_internal_lock` and the error will change to `Instance member '_internal_lock' cannot be used on type 'SomeClass'; did you mean to use a value of this type instead?`
So I wonder why I can't use the `classLock` or the `_internal_lcok` here?
---
- Edit1
If I use a global instance lock then it can compile:
```swift
let globalLock: NSLock = .init()
class SomeClass {
@Lazify(name: "internalClassName", lock: globalLock)
func createLazyVariable() -> String {
return "__" + NSStringFromClass(type(of: self))
}
}
``` |
I am encountering an issue while attempting to print a Jasper report within a Docker container using an Alpine-based OpenJDK image. The application runs smoothly when using a non-Alpine base image, but encounters problems when using Alpine-based images.
I am using `JasperFillManager.fillReport(String sourceFileName, Map<String, Object> params, Connection connection)` method for report printing in java.
# Here's my Dockerfile that works fine with a non-Alpine base image:
FROM openjdk:17-jdk-slim
MAINTAINER timestreamgroup.com
RUN apt-get update && apt-get install fontconfig libfreetype6 -y && apt-get update
COPY target/classes/static/fonts/*.ttf /usr/local/share/fonts/
RUN fc-cache -fv
COPY target/my-java-app-?.?*.jar .
ENTRYPOINT ["java", "-jar", "/my-java-app-2.0.0.jar"]
EXPOSE 8040
# However, when I switch to an Alpine-based OpenJDK image with the following Dockerfile, the reports are not printed, and no exceptions are thrown:
FROM bellsoft/liberica-openjdk-alpine:17
MAINTAINER my-company.com
RUN apk update && apk add fontconfig freetype
COPY target/classes/static/fonts/*.ttf /usr/local/share/fonts/
RUN fc-cache -fv
COPY target/my-java-app-?.?*.jar .
ENTRYPOINT ["java", "-jar", "/my-java-app-2.0.0.jar"]
EXPOSE 8040
The application is responsible for printing Jasper reports, and it works fine with a non-Alpine base image. However, when using the Alpine-based OpenJDK image, the reports are not printed, and no exceptions are thrown.
I think the issue is with freetype library which is not allowing me to print the report.
I've ensured that the necessary fonts are copied and cached properly. Is there anything specific I need to configure or install in the Alpine-based image to enable Jasper report printing? Are there any known compatibility issues or additional dependencies required for Jasper printing within Alpine-based images?
Any insights or suggestions would be greatly appreciated. Thank you!
|
I have interfaces
**Angular Typescript Class**
interface A_DTO {
type: string,
commonProperty: string,
uniquePropertyA: string,
etc..
}
interface B_DTO {
type: string,
commonProperty: string,
uniquePropertyB: string,
etc...
}
type AnyDTO = A_DTO | B_DTO
I have an object, fetched from an API. When it is fetched, it immediately gets cast to A_DTO or B_DTO, by reading the 'type' property. But after that, it then it gets saved to a service, for storage, where it gets saved to a single variable, but of typ AnyDTO (I call that service variable with the components I work with - casting back to AnyDTO, doesn't cause any properties to be lost, so I'm happy)
**Angular Template**
But, in a component, I have some template code,
@if(object.type == "Type_A") {
// do something
// I can do object.commonProperty
// but I cannot access object.uniquePropertyA
} @ else { object.type == "Type_B") {
// do something
// I can do object.commonProperty
// but I cannot access object.uniquePropertyB
}
Note, above, object gets read as type, AnyDTO = A_DTO | B_DTO
**Angular Typescript Class**
I tried creating a type guard on the interface, in the typescript class code, e.g.
protected isTypeA(object: any): object is A_DTO {
return object?.Type === "Type_A";
},
**Angular Template**
Then
@if(isTypeA(object)) {
// do something
// I can do object.commonProperty
// but I still cannot access object.uniquePropertyA...
} @ else { object.type == "Type_B") {
// do something
// but I cannot access object.uniquePropertyB
}
Even with the typeguard being called in the template, inside the @if, 'object' still gets treated as type: A_DTO | B_DTO. Despite what I read on the internet, type narrowing does not happen. So can only access the common properties from 'object'.
I also tried to explicity type cast in the template, using things like (object as A_DTO).uniquePropertyA, but that doesn't work in the Angular template area
Any ideas on a ***dynamic*** solution, (that ideally does not involve create separate variables for each subtype in the Typescript class)?
Cheers,
ST
|
I have a TCP server written in C++ and a React.js application on the client side.
All you need to know is that the send() method in \<winsock.h\> sends an empty string to the client instead of data as a string.
Сlass method that defines the logic for sending data to the client:
```
void TcpServer::sendDataToClient()
{
nlohmann::json jsonData = readData();
std::string jsonDataStr = jsonData.dump();
if (jsonData.empty())
{
log("No data to send to client.\n\n");
return;
}
std::string headers =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-Length: " + std::to_string(jsonDataStr.size()) + "\r\n"
"Connection: close\r\n"
"\r\n";
send(m_new_socket, headers.c_str(), headers.size(), 0);
send(m_new_socket, jsonDataStr.c_str(), jsonDataStr.size(), 0);
log("------ Data sent to client ------\n\n");
}
```
Buffer size and CORS:
```
namespace
{
const int BUFFER_SIZE = 500000000;
void log(const std::string& message)
{
std::cout << message << std::endl;
}
void exitWithError(const std::string& errorMessage)
{
std::cout << WSAGetLastError() << std::endl;
log("ERROR: " + errorMessage);
exit(1);
}
void setCorsHeaders(SOCKET clientSocket)
{
const char* headers =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n"
"Access-Control-Allow-Headers: Content-Type\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n"
"\r\n";
send(clientSocket, headers, strlen(headers), 0);
}
}
```
This is how I send a GET request to a c++ server:
```
const handleFetchServer = async () => {
try {
const response = await axios.get('http://127.0.0.1:5174')
console.log('Response:', response)
console.log('Data from server:', response.data)
} catch (error) {
console.error('Error fetching data: ', error)
}
}
```
1\. The data is exactly stored in the jsonDataStr variable
2\. No compiler or linker errors
3\. Everything works as it should, just when sending data to the client an empty string is sent instead of the data in the jsonDataStr variable
4\. On the client I get an empty string - The GET request itself is executed with code 200, which means that the server responded and everything was successful.
5\. I also tried passing a very small string from the server to the client but I again saw an empty string |
Error after command biogeme = biogeme.BIOGEME (database, logprob) |
|jupyter-notebook|anaconda| |
null |
I have developed an Android application that includes a background service (MainService) designed to run automatically after the device restarts. To achieve this functionality, I have implemented a BootReceiver class and added it to the AndroidManifest.xml file to handle the ACTION_BOOT_COMPLETED intent. However, despite these efforts, the MainService is not starting automatically after the device restarts.
I have created a BroadcastReceiver class named BootReceiver and added it to my AndroidManifest.xml file to start a background service (MainService) after the device restarts. However, the service is not starting automatically after the device restarts. Below are the relevant parts of my code:
BootReceiver.java:
```
package com.sithum.mediatracker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// Start your service here
Intent serviceIntent = new Intent(context, MainService.class);
context.startService(serviceIntent);
}
}
}
```
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MediaTracker"
tools:targetApi="31">
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name=".MainService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="dataSync|location|mediaPlayback"
android:permission="android.permission.BIND_JOB_SERVICE">
<!-- Intent filter if needed -->
<intent-filter>
<action android:name="com.sithum.mediatracker.ACTION_START_SERVICE" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have also declared the necessary permissions in the manifest file. And I tested this in android 9 and 11. What could be causing the background service not to start automatically after device restart, and how can I resolve this issue? |
I'm trying to run a local Postgres database with the PostGIS extension, and then populate the database with a shapefile, without having to load the data in manually.
I have a ```docker-compose.yml``` where I'm first using the postgis docker image and using port 5432. I've already tested this when the container is running and I can successfully connect.
The second part, ```import-shapefile``` uses the postgres image and installs the needed extensions, converts the shapefile and should add the results into the db running in the postgis container.
docker-compose.yml:
```
services:
postgis:
image: postgis/postgis
restart: always
env_file:
- .env
ports:
- 5432:5432
platform: linux/amd64
volumes:
- ./dataset:/dataset
import-shapefile:
image: postgres
depends_on:
- postgis
volumes:
- ./dataset:/dataset
entrypoint: sh
command: -c "apt-get update && apt-get install -y postgis && shp2pgsql -s 4326 -I -D -W UTF-8 dataset/my_shapefile.shp my_table | psql -U username -d my_db"
environment:
- POSTGRES_USER
- POSTGRES_DB
```
When looking at the container logs I see the error in the import-shapefile container:
```
sql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
Is the server running locally and accepting connections on that socket?
```
Does anyone know how to resolve this within the docker-compose.yml file? |
I am practicing on C programming language. I had Win 10 systems and I was practicing on it and I always get addresses which are multiples of 2. Know, I am practicing on Macbook Pro M3 and I get 9 digit addresses.
Also, here is the code and result:
```
#include <stdio.h>
int main(void)
{
int m = 10, n, o, *z;
z = &m;
printf("z stores the address of m = %p\n", z);
printf("*z stores the value of m = %d\n", *z);
printf("&m is the address of m = %p\n", &m);
printf("&n stores the address of n = %p\n", &n);
printf("&o stores the address of o = %p\n", &o);
printf("&z stores the address of z = %p\n", &z);
return 0;
}
```
```
z stores the address of m = 0x16fa13228
*z stores the value of m = 10
&m is the address of m = 0x16fa13228
&n stores the address of n = 0x16fa13224
&o stores the address of o = 0x16fa13220
&z stores the address of z = 0x16fa13218
```
I researched about it however I couldn't get good answers. Here what I found:
[why the value of address in c s always even?](https://stackoverflow.com/questions/58380087/why-the-value-of-address-in-c-s-always-even)
[Strange address of a C variable in Mac OS X](https://stackoverflow.com/questions/51305965/strange-address-of-a-c-variable-in-mac-os-x)
I was expecting to see addresses in multiple digits. |
9 Digit Addresses in Hexadecimal System in MacOS |
|c|macos|memory|memory-address|digits| |
null |
I've really been struggling with one of my FlatLists. Sometimes (seemingly at random) my FlatList will only show the first 10 items and will not display more items when I scroll to the bottom. I have no idea what is triggering this, it just happens sometimes when using my app.
I am aware that the default number of initial items loaded is 10 and that's why the first 10 are showing. I don't want to just increase this as that defeats the whole point of the FlatList to efficiently display the dataset. I've verified that more than 10 users are being supplied to the FlatList even when this issue happens.
This is has been driving me crazy, if anyone can point out any problems in my component I would very much appreciate it. I have many other FlatLists in my app which don't have this problem ever.
Here is my code:
```
import React, {useState, useEffect, useMemo, useCallback} from 'react';
import {
View,
Text,
TouchableOpacity,
Image,
FlatList,
RefreshControl,
} from 'react-native';
import styles from './UserGalleryStyles'; // StyleSheet file
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome';
import {faCheck} from '@fortawesome/free-solid-svg-icons';
import Config from 'react-native-config';
const UserGallery = ({
users2,
navigation2,
userId2,
selectedCategoryName2,
setUpdateFilters,
}) => {
// Render each user
const [localUsers, setLocalUsers] = useState(users2);
const [refreshing, setRefreshing] = useState(false);
const apiUrl = Config.REACT_APP_BACKEND_URL;
useEffect(() => {
setLocalUsers(users2);
}, [users2]);
const onRefresh = () => {
setRefreshing(true);
setUpdateFilters(prevFilters => prevFilters + 1);
// Add any other logic you need to perform during refresh
// After the data is fetched or updated, set refreshing to false
setRefreshing(false);
};
const handleSendFriendRequest = async profileId => {
const updatedUsers = localUsers.map(user => {
if (user.user_id === profileId) {
return {
...user,
friend_request: true, // Update the user_rating.
};
}
return user; // Leave all other products unchanged.
});
// Update the state with the modified products array.
setLocalUsers(updatedUsers);
// Define the payload
const payload = {
user_id: userId2,
profile_id: profileId,
};
// Send the POST request
try {
const response = await fetch(`${apiUrl}/send_friend_request`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
// Check if the POST request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// You may want to do something with the response here
const data = await response.json();
// Optionally, you could confirm the change happened on the backend
// and update the state again if necessary
} catch (error) {
console.error('Failed to send friend request:', error);
}
};
const handleFollow = async profileId => {
// Update the local state first to reflect the change optimistically
const updatedUsers = localUsers.map(user => {
if (user.user_id === profileId) {
return {
...user,
is_following: true, // Update the user_rating.
};
}
return user; // Leave all other products unchanged.
});
// Update the state with the modified products array.
setLocalUsers(updatedUsers);
// Define the payload
const payload = {
user_id: userId2,
profile_id: profileId,
relationship: 'Following',
};
// Send the POST request
try {
const response = await fetch(`${apiUrl}/add_usertag`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
// Check if the POST request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// You may want to do something with the response here
const data = await response.json();
// Optionally, you could confirm the change happened on the backend
// and update the state again if necessary
} catch (error) {
console.error('Failed to send follow', error);
}
};
const renderItem = ({item: user}) => (
<View style={styles.galleryCard}>
<View style={styles.cardMain}>
<View style={styles.cardLeft}>
<TouchableOpacity
onPress={() =>
navigation2.navigate('UserProfile', {
profile_id: user.user_id,
})
}>
<Image source={{uri: user.photo_url}} style={styles.cardImage} />
</TouchableOpacity>
</View>
<View style={styles.cardMiddle}>
<Text style={styles.userName}>@{user.username}</Text>
<Text style={styles.userInfo}>
{/*{user.user_type} User
{'\n'} */}
Ratings: {user.rating_count}{' '}
{user.common_ratings > 0 ? `(${user.common_ratings} Mutual)` : ''}
</Text>
</View>
<View style={styles.cardRight}>
<View>
{user.similarity > 0 ? (
<Text style={styles.similarity}>{user.similarity}%</Text>
) : (
<Text style={styles.similarity}>?</Text>
)}
{selectedCategoryName2 !== 'None' &&
selectedCategoryName2 != null && (
<Text style={styles.text}>{selectedCategoryName2}</Text>
)}
<Text style={styles.text}>Similarity</Text>
</View>
</View>
</View>
<View style={styles.cardFooter}>
{userId2 && (
<View style={styles.cardRelations}>
<View style={styles.followStatus}>
{user.is_following ? (
<View style={styles.friends_container}>
<Text style={styles.friends}>Following</Text>
<FontAwesomeIcon icon={faCheck} style={styles.tick} />
</View>
) : (
<TouchableOpacity
style={styles.follow}
onPress={() => handleFollow(user.user_id)}>
<Text style={styles.followText}>Follow</Text>
</TouchableOpacity>
)}
</View>
<View style={styles.friendStatus}>
{user.is_friend ? (
<View style={styles.friends_container}>
<Text style={styles.friends}>Friends</Text>
<FontAwesomeIcon icon={faCheck} style={styles.tick} />
</View>
) : user.friend_request ? (
<Text style={styles.friendRequestSent}>Request Sent</Text>
) : (
<TouchableOpacity
style={styles.friendRequest}
onPress={() => handleSendFriendRequest(user.user_id)}>
<Text style={styles.friendRequestText}>Add Friend</Text>
</TouchableOpacity>
)}
</View>
</View>
)}
</View>
</View>
);
return (
<FlatList
data={localUsers}
renderItem={renderItem}
keyExtractor={item => item.user_id.toString()}
contentContainerStyle={styles.gallery}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
/>
);
};
export default UserGallery;
```
And it being called like this in my screen:
```
<UserGallery users2={users} userId2={userId} navigation2={navigation} selectedCategoryName2={selectedCategoryName} setUpdateFilters={setUpdateFilters} />
```
Want a FlatList which works as normal showing more items as you scroll down. |
Playwright JS: Getting an error when debugging using line numbers |
|javascript|debugging|command-line|playwright| |
null |
I watched [this video](https://www.youtube.com/watch?v=VLk45JBe8L8) and everything works in dev and local, but I deployed the proyect in vercel and everytime I want to submit the form I get the 405 method not allowed. There are no logs about the error.
```js
const ref = useRef<HTMLFormElement>(null)
...
...
<form
onSubmit={form.handleSubmit(()=>ref.current?.submit())}
action={logInAction}
ref={ref}
/>
```
I have tried only working with the action, but then i can't validate the data on the client side. I would like to preserve the same behavior of the video |
405 Method not allowed RHF + Server Actions in Next.js and deploying it in Vercel |
|reactjs|next.js|vercel|react-hook-form|server-action| |
null |
{"Voters":[{"Id":16217248,"DisplayName":"CPlus"},{"Id":18157,"DisplayName":"Jim Garrison"},{"Id":5468463,"DisplayName":"Vega"}]} |
I have set up a Kubernetes cluster with a single master node and three worker nodes running in VMs. Within this cluster, I deployed an nginx pod and created a LoadBalancer service using MetalLB to allocate an external IP address. The LoadBalancer service is exposing port 80, and when I SSH into the VM hosting the Kubernetes cluster and curl the external IP address, I receive the expected response from nginx.
However, when attempting to access the service from my local device using the same external IP address, I encounter a connection failure with the error message: "Failed to connect to <IP> port 80 after 348 ms: Couldn't connect to server."
I suspect the issue may lie in the IP address range specified in the IPAddressPool of MetalLB. Currently, I've assigned an external IP address within the range of my master node. How can I determine the appropriate value for the IP address range in MetalLB's IPAddressPool to enable access to the LoadBalancer service from devices outside the Kubernetes cluster?
Any guidance or suggestions would be greatly appreciated.
I created an nginx pod using below command
```
kubectl create deploy nginx --image=quay.io/redhattraining/hello-world-nginx
```
The result of `kubectl get deploy -oyaml` looks like
```
apiVersion: v1
items:
- apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2024-03-30T08:34:01Z"
generation: 1
labels:
app: nginx
name: nginx
namespace: default
resourceVersion: "5748"
uid: ff20a336-075e-45cd-9a2e-29110d3e9bce
spec:
progressDeadlineSeconds: 600
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: quay.io/redhattraining/hello-world-nginx
imagePullPolicy: Always
name: hello-world-nginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
status:
availableReplicas: 1
conditions:
- lastTransitionTime: "2024-03-30T08:34:20Z"
lastUpdateTime: "2024-03-30T08:34:20Z"
message: Deployment has minimum availability.
reason: MinimumReplicasAvailable
status: "True"
type: Available
- lastTransitionTime: "2024-03-30T08:34:02Z"
lastUpdateTime: "2024-03-30T08:34:20Z"
message: ReplicaSet "nginx-774b9c499f" has successfully progressed.
reason: NewReplicaSetAvailable
status: "True"
type: Progressing
observedGeneration: 1
readyReplicas: 1
replicas: 1
updatedReplicas: 1
kind: List
metadata:
resourceVersion: ""
```
**IPAddressPool**
```
apiVersion: metallb.io/v1beta1
kind: IPAddressPool
metadata:
name: first-pool
namespace: metallb-system
spec:
addresses:
- <IP Range>
autoAssign: true
avoidBuggyIPs: false
```
**Service**
```
apiVersion: v1
kind: Service
metadata:
name: nginx-lb-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
```
`kubectl get svc` gives below result
```
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
nginx-lb-service LoadBalancer <CLUSTER-IP> <First IP in the pool> 80:30732/TCP 13h
```
when I take ssh into the vm which host k8s cluster and then run curl <EXTERNAL-IP> I get the expected response
```
<html>
<body>
<h1>Hello, world from nginx!</h1>
</body>
</html>
```
but when I try the same from my local device it is giving me below response
```
curl: (7) Failed to connect to <IP> port 80 after 348 ms: Couldn't connect to server.
```
when nothing was not working I created L2Advertisement like
```
apiVersion: metallb.io/v1beta1
kind: L2Advertisement
metadata:
name: nginx-expose
namespace: metallb-system
spec:
ipAddressPools:
- first-pool
```
But that also didn't helped.
Note: I am not using minikube or kind cluster. |
I had RNDocument Picker, the below worked for me:
Remove the package to start with: npm remove react-native-document-picker Install version 8.0.0
```$ npm install react-native-document-picker@8.0.0```
You can also try:
`$ npx react-native-asset react-native-document-picker`
If you get an error saying react-natiuve.config.js not found create a new file with that name in the root folder and add this:
module.Exports = { project: {ios: {},android: {},},assets: ['./src/assets/fonts/'], // path of your assert file};
then `npm start -- --reset-cache` |
1. Return a pointer to the `Node` of interest instead of updating the out parameter `head_dest`. The stack will implicitly hold `cur_list_dest`.
1. The original implementation changes the original list. To create a new list you need to return a pointer to *copy* of the smallest node or NULL. To emphasize that I made the argument constant with `const Node *head`.
1. Observe that `pairWiseMinimumInNewList_Rec()` copy of the 1st or 2nd node or NULL if head is NULL. The recursive case is two nodes ahead otherwise we are done and will subsequently invoke the base case.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int val;
struct Node *pt_next;
} Node;
Node *linked_list_new(int val, Node *pt_next) {
Node *n = malloc(sizeof *n);
if(!n) {
printf("malloc failed\n");
exit(1);
}
n->val = val;
n->pt_next = pt_next;
return n;
}
Node *linked_list_create(size_t n, int *vals) {
Node *head = NULL;
Node **cur = &head;
for(size_t i=0; i < n; i++) {
*cur = linked_list_new(vals[i], NULL);
if(!head) head = *cur;
cur = &(*cur)->pt_next;
}
return head;
}
void linked_list_print(Node *head) {
for(; head; head=head->pt_next)
printf("%d->", head->val);
printf("NULL\n");
}
void linked_list_free(Node *head) {
while(head) {
Node *tmp = head->pt_next;
free(head);
head=tmp;
}
}
Node *pairWiseMinimumInNewList_Rec(const Node* head) {
return head ?
linked_list_new(
(head->pt_next && head->val < head->pt_next->val) ||
(!head->pt_next) ?
head->val :
head->pt_next->val,
pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL)
) :
NULL;
}
int main() {
Node *head=linked_list_create(7, (int []) {2,1,3,4,5,6,7});
Node* head_dest=pairWiseMinimumInNewList_Rec(head);
linked_list_free(head);
linked_list_print(head_dest);
linked_list_free(head_dest);
}
```
Example run that exercises the 3 code paths:
```
1->3->5->7->NULL
``` |
null |
Dear team facing attached error while launching emulator on VM. I Have attached error screenshot and System specification. [Error Msg](https://i.stack.imgur.com/IMvnq.png)
[System specification](https://i.stack.imgur.com/AQ5rV.jpg)
I tried to launch emulator on on VM DESKTO OS 11 we created on Nutanix AHV. Facing error |
Android studio emulator launch on VM |
|android-emulator| |
null |
THIS IS MY TRUFFLE-CONFIG.JS
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
require("babel-register");
const HDWalletProvider = require("truffle-hdwallet-provider");
require("dotenv").config();
module.exports = {
networks: {
Sepolia: {
provider: function() {
return new HDWalletProvider(
process.env.MNEMONIC,
process.env.PROJECT_ENDPOINT,
address_index=0,
num_addresses=2
);
},
network_id: 11155111[enter image description here][1] ,
gas: 4500000,
gasPrice: 10000000000,
},
development: {
host: process.env.LOCAL_ENDPOINT.split(":")[1].slice(2),
port: process.env.LOCAL_ENDPOINT.split(":")[2],
network_id: "*",
},
compilers: {
solc: {
version: "^0.4.24",
},
},
},
};
<!-- end snippet -->
I AM UNABLE TO GET THE NETWORK ID FOR SEPOLIA TEST NETWORK
BELOW IS THE LINK OF THE ERROR COMING-
[1]: https://i.stack.imgur.com/HPl09.png |
Sepolia test network ID |
|javascript|testing|blockchain| |
Currently, I'm trying to get down basics of jetpack compose, and I'd like to ask you about the view model. Let's say we have an app which will make a few different api calls. As far as I know, beofre jetpack compose, we could have a few fragments for each api call (because they will serve completely different data). So we had to make separated ViewModel for each fragment, right? But how should I approach ViewModels in jetpack compose, when we can have a single activity, that display many composables? Should I stay with one ViewModel then? |
Jetpack compose ViewModels - should I have one ViewModel for different api calls? |
|android|kotlin|mvvm|android-jetpack-compose|retrofit2| |
Your algorithm essentially performs a bread-first search, where you extend all partial matches you found in a previous iteration by one character and keep those that still match. So for a worst case scenario we would want to have as many partial matches as possible for as many iterations as possible.
One such worst case input could be a haystack with an even size, with times the letter "a", and a needle with =/2 characters that are all "a", except the last letter, which would be a "b". So for instance, if is 10:
haystack = "aaaaaaaaaa"
needle = "aaaab"
The `while 1:` loop will make /2−2 iterations (the "minus-2" is the consequence of already having matches with 2 letters before that loop starts).
The inner `for first, start, check in new` loop will make /2+1 iterations
Taking that together, the inner `if` statement will be executed (/2-2)(/2+1) times, i.e. ²/4−/2−2 times, which is O(²), and is therefore the time complexity of your algorithm.
> people were saying that O(n * m) solutions weren't passing at all
You have given proof that their claim is false. Here it is important to realise that time complexity says absolutely *nothing* about how much time an algorithm will need to process *actual* (finite!) inputs. Time complexity is about *asymptotic* behaviour. |
Sending data from C++ server to React.js client |
|c++|reactjs|server|backend|winsock| |
null |
I cannot execute a procedure stored on mssql server from django.
Here is the configuration for the db.
DATABASES = {
'default': {
'ENGINE': 'mssql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'OPTION':{
'driver': 'ODBC Driver 17 for SQL Server',
'trusted_connection': 'yes'
}
}
}
In my view:
def test(request):
if request.method == "POST":
with connection.cursor() as cursor:
P1 = request.data["p1"]
P2 = request.data["p2"]
try:
cursor.callproc('[dbo].[SP_TEXT]',[P1,P2])
if cursor.return_value == 1:
result_set = cursor.fetchall()
print(result_set)
finally:
cursor.close()
return Response({"msg":"post"})
else:
return Response({"msg": "get"}) |