instruction stringlengths 0 30k ⌀ |
|---|
|reactjs| |
null |
|javascript|frontend|backend|z-index|web-frontend| |
|jmeter| |
how to solve this error Possible Unhandled Promise Rejection (id: 11):
TypeError: Cannot read property 'cancelToken' of undefined
Possible Unhandled Promise Rejection (id: 11):
TypeError: Cannot read property 'cancelToken' of undefined |
Possible Unhandled Promise Rejection (id: 11): TypeError: Cannot read property 'cancelToken' of undefined |
|reactjs|react-native|axios| |
null |
If you want the words with Jack and there must be at least `Jack#` you can match the part without comma's containing Jack# and then filter the result:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /[^,]*\bJack#[^,]*/g;
const m = text.match(regexpWords);
if (m) console.log(m[0].split(/\s+/).filter(s => s.match(/\bJack\b/)));
<!-- end snippet -->
|
null |
|python|google-cloud-firestore| |
null |
Capacitor IOS application can't find keys set with Xcode launch arguments.
It can find other keys set using Preferences.set. |
Capacitor Preferences not seeing UserDefaults key value pairs set with Xcode Launch Arguments |
|xcode|capacitor| |
You need to start your launch argument with CapacitorStorage.
Eg: CapacitorStorage.yourKey value |
Here is my current code:
Here is my current wire:model called spk:
```
<?php
namespace App\Http\Livewire\Spk;
use App\Models\Spk;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;
class Form extends Component
{
use WithFileUploads;
public $spk;
public $submitButtonName;
protected $rules = [
'spk.file_path' => 'required|mimes:pdf,xlsx,xls,csv,txt,png,gif,jpg,jpeg|max:8192',
];
public function mount() {
// Check if the spk property is set
if (!$this->spk){
$this->spk = new Spk();
$this->submitButtonName = 'Create';
} else {
$this->submitButtonName = 'Edit';
}
}
public function save()
{
$this->validate();
// Handle file upload
if ($this->spk->file_path) {
// Generate a unique filename with microtime
$filename = 'spk' . microtime(true) . '.' . $this->spk->file_path->getClientOriginalExtension();
// Save the file to the storage directory
$this->spk->file_path->storeAs('spk', $filename, 'public');
// Update the file_path attribute with the new filename
$this->spk->file_path = $filename;
}
$this->spk->save();
session()->flash('message', 'SPK Saved!');
return redirect()->route('spks.index');
}
public function render()
{
return view('livewire.spk.form');
}
}
```
Here is my current wire blade view:
```
<form wire:submit.prevent="save" method="POST" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="px-4 py-2">
<x-label for="file_path" value="{{ __('File Path') }}" />
<x-input wire:model="spk.file_path" type="file" name="file_path" :value="old('file_path')" class="w-full"
required autofocus />
@error('spk.file_path')
<div>{{ $message }}</div>
@enderror
</div>
<div class="px-4 pt-8 pb-4">
<button type="submit"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md w-full">
{{ __($submitButtonName) }}
</button>
</div>
</div>
</form>
```
I already do `php artisan storage:link`
I'm confused what's wrong with my code. file_path can't be saved on database.
[Images when file submited](https://i.stack.imgur.com/0ZOK3.png)
I try to do `dd($this->spk->file_path);` and here is the result. It show "disk" => "local"
[Image when debugging using dd](https://i.stack.imgur.com/YfVMd.png)
Please help me to resolve this file upload using livewire. Thanks! |
null |
The first argument of `add_job` is `regproc` not `text`:
https://docs.timescale.com/api/latest/actions/add_job/#add_job
```
pg:adn@localhost/target=> \df add_job
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+---------+------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------
public | add_job | integer | proc regproc, schedule_interval interval, config jsonb, initial_start timestamp with time zone, scheduled boolean, check_config regproc, fixed_schedule boolean, timezone text | FUNCTION
```
Change `proc_name_in::text` to `proc_name_in::regproc`:
```plpgsql
CREATE OR REPLACE FUNCTION check_and_add_job(proc_name_in TEXT, schedule_interval_in TEXT) RETURNS VOID AS
$$
BEGIN
-- Here is the logic for checking if job exists, will RETURN in case it does
-- This part will run only when there are no jobs with the same name
PERFORM public.add_job(
proc_name_in::regproc,
schedule_interval_in::interval,
NULL,
NULL,
true,
NULL,
true,
NULL
);
RAISE NOTICE 'New job added successfully.';
RETURN;
END;
$$ LANGUAGE plpgsql;```
|
I'm not sure, but I think your problem is that you've enabled the irq, before you requested it in the probe function. Try doing this instead:
spin_lock_init(&RWLock);
init_waitqueue_head(&WaitQueue);
int irqNum = gpio_to_irq(SpiioNum);
if (request_irq(irqNum, spiio_irq_handler, IRQF_TRIGGER_RISING, "spiio_irq", NULL) < 0)
{
pr_err("requst_irq failed\n");
free_irq(irqNum, NULL);
goto out_free;
}
enable_irq(irqNum);
Notice that the `enable_irq()` call is now after the `request_irq` call. |
```
public HashMap<Player, Boolean> running = new HashMap<>();
public void load(Player player){
running.put(player, true);
}
@Eventhandler
public void onInteract(PlayerInteractEvent event){
if(!running.get(player)) return;
//More stuff happening here
}
```
I run the "load"-method at the start of my main-class, so the "check"-part cannot happen before "load()" is finished. I use the same player for both methods, but I always get an error:
`Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.Map.get(Object)" is null`
I don't know why it's not working, so I'd be very thankful if someone could help me :) |
Cannot get content from HashMap in Java/Bukkit |
|java|minecraft|bukkit| |
null |
|powerbi|dax| |
in Hello everyone, my work I use both STATA and R. Currently I want to perform a dose-response meta-analysis and use the "dosresmeta" package in R. The following syntax is used:
```
DRMeta \<- dosresmeta(
formula = logRR \~ dose,
type = type,
cases = n_cases,
n = n,
lb = RR_lo,
ub = RR_hi,
id = ID,
data = DRMetaAnalysis
)
```
When executing this syntax, however, I encounter a problem. The error message appears:
`Error in if (delta \< tol) break : missing value where TRUE/FALSE needed.`
The reason for this error message is that I am missing some values for the variables "n_cases" and "n", which the authors have not provided. Interestingly, STATA does not require this information for the calculation of the dose-response meta-analysis.
Is there a way to perform the analysis in R without requiring the values for "n_cases" and "n"? What can I do if I have not given these values?
I have already asked the authors for the missing values, unfortunately without success. However, I need these studies for the dose-response meta-analysis, so it is not an option to exclude them.
Best regards
David |
User
TextFormField(
enableInteractiveSelection: false,
controller: _runningKmsController,
keyboardType: TextInputType.number,
inputFormatters: [
LengthLimitingTextInputFormatter(3)
],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
cursorColor: AppTheme.appColors,
textAlign: TextAlign.center,
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
TextFormField(
enableInteractiveSelection: false,
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
cursorColor: AppTheme.appColors,
controller: _noOfWorkDaysController,
inputFormatters: [LengthLimitingTextInputFormatter(2)],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
// borderRadius: BorderRadius.circular(2.0),
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
|
The error message here shows that while your PATH is set to use RVM's Ruby, the **GEM_HOME** and/or **GEM_PATH** environment variables are not set.
These variables are important because they tell Ruby where to install and look for gems.
To fix this, you need to set the GEM_HOME and GEM_PATH environment variables. You can do this by adding the following lines to your shell profile file (like `.bashrc`, `.bash_profile`, or `.zshrc`):
```bash
export GEM_HOME="$HOME/.gem"
export GEM_PATH="$HOME/.gem"
```
After adding these lines, you need to source your shell profile file to apply the changes:
```bash
source ~/.bashrc # or
source ~/.bash_profile # or
source ~/.zshrc
```
Then, you can check if the environment variables are set correctly by running:
```bash
echo $GEM_HOME
echo $GEM_PATH
```
*If everything is set up correctly, both commands should output the path to your .gem directory.* |
How to change the color of the liquid when two pipes merge to a given one, depending on which of the flows prevails?
The output is the color of the liquid, which is the first to reach the confluence point. Used Pipeline and Fluid Merge. |
Anylogic - liquid color |
|anylogic| |
null |
def create_media_container_for_reel(video_url, access_token, caption, user_id):
graph_url = f'https://graph.facebook.com/v19.0/{user_id}/media'
payload = {
'media_type': 'REELS', # Updated as per the new requirement
'video_url': video_url,
'caption': caption,
'access_token': access_token
}
response = requests.post(graph_url, json=payload)
if response.status_code in [200, 201]:
media_container_id = response.json().get('id')
return media_container_id
else:
logging.error(f"Failed to create media container. Status code: {response.status_code}, Response: {response.text}")
return None
import time
def publish_media_container_as_reel(media_container_id, access_token, user_id, retries=5, delay=10):
print(media_container_id)
publish_endpoint = f'https://graph.facebook.com/v19.0/{user_id}/media_publish'
publish_payload = {
'creation_id': media_container_id,
'access_token': access_token
}
while retries > 0:
response = requests.post(publish_endpoint, data=publish_payload)
if response.status_code in [200, 201]:
logging.info("Reel published successfully.")
return True
else:
error = response.json().get('error', {})
if error.get('code') == 9007 and retries > 0:
logging.warning(f"Media not ready for publishing, waiting {delay} seconds before retrying...")
time.sleep(delay)
retries -= 1
else:
logging.error(f"Failed to publish reel. Status code: {response.status_code}, Response: {response.text}")
return False
logging.error("Failed to publish reel after retries. Giving up.")
return False
def post_reel_to_instagram(video_url, access_token, caption, user_id):
# Step 1: Create Media Container
media_container_id = create_media_container_for_reel(video_url, access_token, caption, user_id)
if not media_container_id:
return False
# Step 2: Publish the Media Container as a Reel
return publish_media_container_as_reel(media_container_id, access_token, user_id)
I'm using the above code, all the token and id is same for image and reel, but image upload works flawlessly but reel one doesn't work.
`create_media_container_for_reel` also returns a media id, it only gives error when i try to post ot on my feed using `publish_media_container_as_reel`
what am I doing wrong? |
403 Permission Error When Tryna Upload Reel To Instagram Using Graph API, But Image works? |
|python|instagram|instagram-api|instagram-graph-api|instagram-reels| |
If you need to check what is alaready installed version of any packages you can simply use Pip command as below
**Template**
pip show <PACKAGE_NAME> | grep Version or pip show <PACKAGE_NAME>
**with pip3**
pip3 show <PACKAGE_NAME> | grep Version or pip3 show <PACKAGE_NAME>
**Example**
pip show PyYAML | grep Version
Version: 3.12
pip3 show PyYAML | grep Version
Version: 3.12
|
I recently encountered nearly the same error when building with `go1.21`:
```
vendor/github.com/gin-gonic/gin/context.go:1085:11: predeclared any requires go1.18 or later (-lang was set to go1.16; check go.mod)
```
I checked the `vendor/github.com/gin-gonic/gin/go.mod` only to find it declares using `go 1.18` already.
So where is the heck `go1.16` comes from?
After struggling hours I found my `vendor/modules.txt` have the following content:
```
380 github.com/gin-contrib/sse
381 ## explicit; go 1.18
382 github.com/gin-gonic/gin
...
1282 ## explicit
1283 github.com/gin-contrib/sse
1284 # github.com/gin-gonic/gin v1.8.1
1285 ## explicit
1286 github.com/gin-gonic/gin
1287 # github.com/go-playground/locales v0.14.0
1288 ## explicit
...
```
To clarify that, `vendor/modules.txt` consists of three types of content:
1. package name, without '#' prefix, e.g. `github.com/gin-contrib/sse`,
2. module and version, starting with '#', e.g. `# github.com/gin-gonic/gin v1.8.1`
3. an explicit mark, e.g. `## explicit` or `## explicit; go1.18`(with go version)
In my `vendor/modules.txt`, `# github.com/gin-gonic/gin v1.8.1` appears once, but following it is not a `## explicit` with go version, so `go 1.16` is assumed, that's where the weired message comes from.
To fix this, just add a line after `# github.com/gin-gonic/gin v1.8.1`:
```
## explicit; go1.18
```
Or just go `go mod vendor` if possible. |
I am trying to log users into my Chrome extension with `chrome.identity.launchWebAuthFlow`, yet I keep getting the following error: `Error 400: redirect_uri_mismatch` (see screenshot below).
**Context**
- I use Google Workspace and the extension is private to my domain
- I have created a dedicated OAuth 2.0 Client ID of type "Chrome Extension" in the Google Cloud console Credentials, and have verified app ownership
- I try to authenticate using the code below - I have double checked that the extension ID matches the redirect URI
- My intention is to use the Google token to [log users into Supabase][1]
```js
function login() {
const manifest = chrome.runtime.getManifest();
if (!manifest.oauth2?.scopes) throw new Error('No OAuth2 scopes defined in the manifest file');
const url = new URL('https://accounts.google.com/o/oauth2/auth');
url.searchParams.set('client_id', manifest.oauth2.client_id);
url.searchParams.set('response_type', 'id_token');
url.searchParams.set('access_type', 'offline');
url.searchParams.set('redirect_uri', `https://${chrome.runtime.id}.chromiumapp.org`);
url.searchParams.set('scope', manifest.oauth2.scopes.join(' '));
return new Promise((resolve, reject) =>
chrome.identity.launchWebAuthFlow(
{
url: url.href,
interactive: true,
},
async (redirectedTo) => {
if (chrome.runtime.last
1. Error) {
reject(`Could not login - ${chrome.runtime.lastError.message}`);
} else {
const url = new URL(redirectedTo!);
const params = new URLSearchParams(url.hash);
resolve(params.get('id_token'))
}
},
),
);
}
```
```json
{
"manifest_version": 3,
"permissions": ["identity", ...],
"oauth2": {
"client_id": "<client ID>",
"scopes": ["openid", "email", "profile"]
},
...
}
```
**What else I have tried**
- For redirect_uri, in addition to the code below, I have also tried `chrome.identity.getRedirectURL()` and `chrome.identity.getRedirectURL('oauth2')`, all leading to the same result
- I have tried [this solution][2] - use a "Web application" client ID instead of a "Chrome extension" client ID, and add the redirect URL to the list of Authorized redirect URIs - still leads to the same result
What am I missing?
[![Screenshot of Oauth error][3]][3]
[1]: https://supabase.com/docs/guides/auth/social-login/auth-google?platform=chrome-extensions
[2]: https://stackoverflow.com/questions/52903191/redirect-uri-mismatch-when-using-identity-launchwebauthflow-for-google-chrome-ex
[3]: https://i.stack.imgur.com/KO9IS.png |
After upgrading from Angular 15 to 17 my bundle increased by 141KB. I'm not sure what to make of it. Did I do something wrong? Or is this to be expected? |
significan bundle increase after upgrading from Angular 15 to 17 |
|angular| |
Answering my own question:
I needed to add these configs instead:
```java
springdoc:
api-docs:
path: '/api/admin/v3/api-docs'
swagger-ui:
path: '/api/admin/swagger-ui.html'
url: '/api/admin/v3/api-docs'
```
Importantly, I had to remove `springdoc.swagger-ui.config-url` and add `springdoc.swagger-ui.url`. The reason is that there's a check inside `org.springdoc.ui.AbstractSwaggerIndexTransformer.defaultTransformations()` like this:
```java
if(StringUtils.isNotEmpty(swaggerUiConfig.getUrl()) && StringUtils.isEmpty(swaggerUiConfig.getConfigUrl())){
html = setConfiguredApiDocsUrl(html);
}
```
Setting a url and not setting a config-url will trigger the logic needed to make this work. |
# What are the details of your problem?
Why does Eclipse's Maven's plug-in overwrite the Java version set with a lower version?
When the Eclipse Maven-plugin runs `Project Update...`, the [JDK gets switched from 11 to 8](https://stackoverflow.com/questions/28509928/java-version-automatically-change-to-java-1-5-after-maven-update).
This causes Java version 11+ stuff in the code to break and unable to compile or run.
When I try to switch the project back to 11+ and compile, the Maven dependency imports break.
To get the Maven packaged packages from Nexus, I end up running `Project Update` to resolve.
This causes Eclipse-Maven to set the JDK to 8. The project needs Java-11 or higher.
What needs to happen to allow the Maven dependencies to resolve and the correct Java version be used?
## Environment Versions:
1. Eclipse: 2023-06 (4.28.0)
2. Java-8: 1.8.0_301
3. Java-11: 11.0.15.1
4. Maven: 3.9.1/3.9.100.20230519-1558 (EMBEDDED)
5. OS: Windows 10
# What did you try and what were you expecting?
1. Running Maven `mvn compile` , `mvn install` , `mvn package`, `mvn clean compile` and any other combinations anyways
1. Result: Maven Build Failed
1. [Project has been able to run before even when the Eclipse-Maven-plugin did not work](https://stackoverflow.com/questions/14807869/eclipse-does-not-recognize-existing-resolved-maven-dependencies)
2. Changing the [Eclipse-Project-Properties](https://stackoverflow.com/questions/13949928/eclipse-project-properties-dont-show-build-path): `Java Build Path` , `Java Code Style` , `Java Compiler` ; to be JDK-11
1. [Java Build Path](https://stackoverflow.com/questions/27333582/java-eclipse-build-path)
1. Editing the JRE-Selection with its `System library` selection: `Execution environment` , `Alternate JRE` , and `Workspace default JRE` (which I set with the Eclipse-Preferences)
1. Result: Maps, Lists, and other Java imports break
2. Removing and Readding the `JRE System Library`
1. Result: Maps, Lists, and other Java imports break
3. Checkbox-Selecting in `Order and Export` for `Maven Dependencies` and `JRE System Library`
1. Result: Nothing notable to the situation changed
2. [Java Code Style](https://stackoverflow.com/questions/1601793/how-do-i-modify-eclipse-code-formatting)
1. Enabling and Disabling explicit `Enable project specific settings` to Java-11
1. Result: No notable changes
3. [Java Compiler](https://stackoverflow.com/questions/50127132/how-do-i-change-the-default-eclipse-oxygen-compiler-compliance-level-from-9-to-1)
1. Enabling and Disabling explicit `Enable project specific settings` to Java-11
1. Result: Maps, Lists, and other Java imports break
3. Adding the [POM Java Versions](https://stackoverflow.com/questions/38882080/specifying-java-version-in-maven-differences-between-properties-and-compiler-p) in the `properties.java.version` and `properties.maven.compiler.[source, target]`
1. Result: No Change
4. Setting `JAVA_HOME` is [jdk-11](https://stackoverflow.com/questions/56481756/java-version-shows-java-8-while-java-11-is-installed)
1. Result: no change (correct location)
5. Reverting back the [Eclipse-Maven changes](https://stackoverflow.com/a/38819808/11705601) in `.classpath` XML for its `classpath.classpathentry` for the `org.eclipse.jdt.launching` to be `<attribute name="maven.pomderived" value="true"/>` and no reference to `JavaSE-1.8`
1. Result: Eclipse-Maven reverts this back
6. Editing `org.eclipse.jdt.core.prefs` to explicitly be Java 11 and/or remove references to "1.8"
1. Result: Eclipse-Maven reverts this back
7. Checking [Oomph](https://stackoverflow.com/questions/55395802/update-the-jdk-path-of-eclipse-installed-by-oomph-setup) wasn't setting the Java version in `org.eclipse.oomph.setup/setup/user.setup`
1. Result: No reference to Java or its versions |
How to upload pdf file with livewire (Laravel)? |
|laravel|file-upload|laravel-blade|laravel-livewire| |
null |
While having deep dive into how the built-in `unittest.mock` was designed, I run into [these lines](https://github.com/python/cpython/blob/3.12/Lib/unittest/mock.py#L401C1-L409C29) in the official source code of `mock.py`:
```python
class Base(object):
_mock_return_value = DEFAULT
_mock_side_effect = None
def __init__(self, /, *args, **kwargs):
pass
class NonCallableMock(Base):
...
# and later in the init
def _init__ (...):
...
_safe_super(NonCallableMock, self).__init__(
spec, wraps, name, spec_set, parent,
_spec_state
)
```
What is the role of `Base` class besides providing common class attributes `_mock_return_value` and `_mock_side_effect` as it has just an empty `__init__` ?
And why `NonCallableMock` has to call `_safe_super(NonCallableMock, self).__init__()`, which I believe is exactly just the empty `__init__` method of the `Base` class ?
Thanks a lot for your answers in advance.
I tried to understand the code but couldn't see the rationale behind the design. |
What is the role of `Base` class used in the built-in module `unittest.mock`? |
|python|python-3.x|metaprogramming|python-unittest.mock| |
null |
I developed a lightweight Kubernetes tool [URunner][1] in order to **automatically** restart deployment resources while maintaining the same tag (es. `:latest`)
**URunner** can also be installed using **Helm** ([Artifacthub link][2])
It uses **Docker V2 API** standard in order to continuously check if a **Tag Digest** is changed and eventually perform the needed restarts.\
So basically it is compatible with ALL available container registries (ex. AWS ECR, GCP, Harbor, DigitalOcean registry..)
[1]: https://github.com/texano00/urunner
[2]: https://artifacthub.io/packages/helm/urunner/urunner |
I would like to access my log::Log impl instance in order to access a particular field, but once I receive the ref 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 [link](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) to the rust playground.
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. |
Eclipse-Maven Forcefully Overwrites Java Version Set Every Update Project |
|maven-3|java-11|maven-eclipse-plugin|oomph|eclipse-2021-09| |
null |
in my work I use both STATA and R. Currently I want to perform a dose-response meta-analysis and use the "dosresmeta" package in R. The following syntax is used:
```
DRMeta \<- dosresmeta(
formula = logRR \~ dose,
type = type,
cases = n_cases,
n = n,
lb = RR_lo,
ub = RR_hi,
id = ID,
data = DRMetaAnalysis
)
```
When executing this syntax, however, I encounter a problem. The error message appears:
`Error in if (delta \< tol) break : missing value where TRUE/FALSE needed.`
The reason for this error message is that I am missing some values for the variables "n_cases" and "n", which the authors have not provided. Interestingly, STATA does not require this information for the calculation of the dose-response meta-analysis.
Is there a way to perform the analysis in R without requiring the values for "n_cases" and "n"? What can I do if I have not given these values?
I have already asked the authors for the missing values, unfortunately without success. However, I need these studies for the dose-response meta-analysis, so it is not an option to exclude them.
Best regards
David |
I have recently authored a new hierarchical clustering algorithm specifically for 1D data. I think it would be suitable to the case in your question. It is called `hlust1d` and it is written in `R`. It is available under [this link](https://CRAN.R-project.org/package=hclust1d).
The algorithm addresses @Anony-Mousse's concern: it takes advantages of the particular structure of 1D data and runs in O(n*log n) time. This is much faster than general-purpose hierarchical clustering algorithms.
To segment your data into 3 bins (clusters) as you require in your question, you could run the following code
```
library(hclust1d)
dendrogram <- hclust1d(c(1, 1, 2, 3, 10, 11, 13, 67, 71))
plot(dendrogram)
```
Now, having a look at the dendrogram tree (which I cannot attach here) one can see that cutting at the height of 10 results in the segmentation required.
```
cutree(dendrogram, h=10)
# 1 1 2 3 10 11 13 67 71
# 1 1 1 1 2 2 2 3 3
```
The clustering is hierarchical, meaning that what you get is a hierarchy of clusters (a dendrogram) and it is up to you to decide, which number of clusters fits your particular data best. It is both an advantage (flexibility) and disadvantage (you have to decide something) of this method. For instance, another good cut of the dendrogram, as can be seen on a plot, is located somewhere near the height of 20, resulting in two clusters:
```
cutree(dendrogram, h=20)
# 1 1 2 3 10 11 13 67 71
# 1 1 1 1 1 1 1 2 2
```
For more complex data, you could also experiment with other linkage functions using the `method` argument, like this:
```
dendrogram <- hclust1d(c(1, 1, 2, 3, 10, 11, 13, 67, 71), method="ward.D2")
```
The list of all supported linkage methods can be read with a use of
```
> supported_methods()
# [1] "complete" "average" "centroid" "true_median" "median" "mcquitty" "ward.D" "ward.D2" "single"
``` |
Html
```
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<title>Projet Abonnez-vous</title>
</head>
<body>
<div class="container">
<div class="bloc-central">
<h1>Projet Abonnez-vous</h1>
<iframe width="560" height="315" src="https://www.youtube.com/embed/ggGT2N4l_08?si=hFk7Xzw16cEEzi6x"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
<div class="bloc-btn">
<i class="far fa-meh-blank"></i>
<button class="btn">Abonnez-vous</button>
</div>
</div>
</div>
<script src="/script.js"></script>
</body>
```
JavaScript
```
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');
});
```
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?
Thank you. |
chrome.identity.launchWebAuthFlow with Chrome Extension OAuth 2.0 Client ID leads to Error 400: redirect_uri_mismatch |
|google-chrome-extension|oauth-2.0|supabase| |
I am brand new front end development and svelte kit.
I am trying to make pair of dynamic dropdowns I have a pocektbase collection named "users" that contains 2 fealds User and Asset. First dropdown contains list of users and second one will show list of assets for the selected user.
I am using daisyui and tailwindcss. This is my +page.svelte code.
```
<script>
export let data;
let selectedUser = '';
let selectedAsset = '';
function handleUserChange(event) {
selectedUser = event.target.value;
selectedAsset = ''; // Reset selected course when user changes
}
function handleCourseChange(event) {
selectedAsset = event.target.value;
}
async function showSelection() {
console.log('Selected User:', selectedUser);
console.log('Selected Course:', selectedAsset);
}
</script>
<div>
{#if data}
<form action="?/userSelection" method="POST">
<select
class="select select-accent w-full max-w-xs"
value={selectedUser}
on:change={handleUserChange}
>
<option disabled selected>Select a User</option>
{#each data.userData as user}
<option name="user" value={user.user}>{user.user}</option>
{/each}
</select>
{#if selectedUser !== ''}
<select
class="select select-accent w-full max-w-xs"
value={selectedAsset}
on:change={handleCourseChange}
>
<option disabled selected>Select a Course</option>
{#each data.userData.find((user) => user.user === selectedUser)?.courses || [] as course}
<option name="course" value={course}>{course}</option>
{/each}
</select>
{/if}
<button type="button" on:click={showSelection}>Get Data</button>
</form>
{:else}
<p>Loading...</p>
{/if}
</div>
```
And this is my backend code that requests form data.
```
export const actions = {
userSelection: async ({ request }) => {
const formData = await request.formData();
const user = Object.fromEntries(formData);
console.log(user);
}
```
The problem I am facing is colsolel.log from front end is showing correct selection but the back end is console logging empty object.
What am I doing wrong here?
Thank you for help,
```
<script>
export let data;
let selectedUser = '';
let selectedAsset = '';
function handleUserChange(event) {
selectedUser = event.target.value;
selectedAsset = ''; // Reset selected course when user changes
}
function handleCourseChange(event) {
selectedAsset = event.target.value;
}
async function showSelection() {
console.log('Selected User:', selectedUser);
console.log('Selected Course:', selectedAsset);
}
</script>
<div>
{#if data}
<form action="?/userSelection" method="POST">
<select
class="select select-accent w-full max-w-xs"
value={selectedUser}
on:change={handleUserChange}
>
<option disabled selected>Select a User</option>
{#each data.userData as user}
<option name="user" value={user.user}>{user.user}</option>
{/each}
</select>
{#if selectedUser !== ''}
<select
class="select select-accent w-full max-w-xs"
value={selectedAsset}
on:change={handleCourseChange}
>
<option disabled selected>Select a Course</option>
{#each data.userData.find((user) => user.user === selectedUser)?.courses || [] as course}
<option name="course" value={course}>{course}</option>
{/each}
</select>
{/if}
<button type="button" on:click={showSelection}>Get Data</button>
</form>
{:else}
<p>Loading...</p>
{/if}
</div>
```
And this is my backend code that requests form data.
```
export const actions = {
userSelection: async ({ request }) => {
const formData = await request.formData();
const user = Object.fromEntries(formData);
console.log(user);
}
```
The problem I am facing is colsolel.log from front end is showing correct selection but the back end is console logging empty object.
What am I doing wrong here?
Thank you for help,
|
How do i make a dynamic dropdown or Data select and use Svelte kit form actions to pass that data to backend file and make api call |
|sveltekit| |
null |
User
TextFormField(
enableInteractiveSelection: false,
controller: _runningKmsController,
keyboardType: TextInputType.number,
inputFormatters: [
LengthLimitingTextInputFormatter(3)
],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
cursorColor: AppTheme.appColors,
textAlign: TextAlign.center,
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
TextFormField(
enableInteractiveSelection: false,
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
cursorColor: AppTheme.appColors,
controller: _noOfWorkDaysController,
inputFormatters: [LengthLimitingTextInputFormatter(2)],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
// borderRadius: BorderRadius.circular(2.0),
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
I have 2 text form fields. Restrictions are required from 50 to 250 in the runningkmscontroller. A pop-up should be shown once the user shifts to the next tab. If the user enters a value less than or greater than the given range, validation should be performed. Additionally, onChange() function calculates different values. How can I achieve this? Please provide a solution.
|
After one years later, I found a way to figure out this with LUA script
```php
$get_lua = <<<LUA
local key = KEYS[1]
local expireAt = ARGV[1]
local value = redis.call('GET', key)
if value == false then
redis.call('SET', key, 100)
redis.call('EXPIREAT', key, expireAt)
value = 100
end
return value
LUA;
$set_lua = <<<LUA
local key = KEYS[1]
local value = ARGV[1]
local expireAt = ARGV[2]
redis.call('SET', key, value)
redis.call('EXPIREAT', key, expireAt)
LUA;
$redis = new Redis();
$expired_at = strtotime(date('Y-m-d')) + 864000; // end of today
$key = "store_of_today";
$left = $redis->eval($get_lua, [$key, $expired_at], 1);
// code
$redis->eval($set_lua, [$key, $new_left, $expired_at], 1);
```
The redis ensure that a lua script is an atomic operation, so the `$set_lua` will always set a value and then set an `expireAt` on the key in once atomic operation, and if `expireAt` is a past timestamp, the key will be invalid. |
Here's my two cents on the matter,
Dependency Injection is about passing the required dependencies (objects or services) into a class from an external source, rather than creating instances of those dependencies within the class itself.
Why?
So that we can achieve loose coupling between classes by taking advantage of interfaces and abstract classes.
(or one can say to achieve IoC)
Why?
Because this allows us to:
1. Adhere to the Open/Closed Principle.
2. Write polymorphic code.
3. Facilitate unit testing of classes that depend on external APIs
or services by providing mock or stub implementations of those
dependencies.
4. Clearly define and manage the dependencies of classes, making the codebase more maintainable and easier to reason about.
There is a concept part of it and a design pattern part of it
The concept part of it is that understanding DI can achieves separating concern, IoC. Above are few benefits comes from these concepts, It’s about what you trying to achieve by delegating object creation.
The design pattern is how to achieve it in terms of managing dependencies; by controlling the object creation and "injecting" into a class rather than the class creating its dependencies.
> Design patterns are half-baked solutions for common problems.
Example of DI design pattern implementation.
In the .NET Framework, controller objects are managed by the .NET Core framework itself, it provides a means to inject objects into controllers using the `services.AddScoped` method.
So we can see .NET Framework itself implements its version of the DI design pattern providing us a way to register our dependencies and make it available to all of our controllers.
|
I have seen similar topic with answers about size in % or vh, but its a bit different.
I have a set of different plots with sizes 900x600 by default using this CSS:
```
.chartbox {
display: flex;
flex-wrap: wrap;
background-color: DodgerBlue;
justify-content: space-around;
}
.chart {
background-color: #f1f1f1;
width: 900px;
height: 600px;
margin: 10px;
position: center;
}
```
[how it looks](https://i.stack.imgur.com/wMdw3.png)
And I want them to resize automaticly when the window is resizing (or there is a small screen)
Im using charts from ECharts, with js code smth like:
```
var myChart = echarts.init(document.getElementById('main'));
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}
]
};
myChart.setOption(option)
```
I tried to use % and vh to .chart height and width, but they conflict with default size.
I tried to use max-width and max-height without width and height, but charts do not appear (mb its a ECharts feature).
I expect the following:
1. if 3 charts 900x600 can fit the screen then place them
2. else if 3 charts 600x400 can fit the screen then place them
3. else if 2 charts 900x600 can fit the screen then place them
4. else if 2 charts 600x400 can fit the screen then place them
5. else if 1 charts 900x600 can fit the screen then place it
6. else if 1 charts 600x400 can fit the screen then place it
7. else resize as it possible |
Resize divs with default size risizing window |
|javascript|html|css|flexbox| |
Icone of font awesome dont change |
|javascript|html|font-awesome| |
null |
Why the fields of ConditionObject are not decorated as **volatile**?
ConditionObject has two fields *firstWaiter* and *lastWaiter*, both are not volatile.
I known ConditionObject can only be modified by thread which hold the exclusive lock, but what if one thread modified these two fields and late another thread read them, and did not read the recently updated value due to the cpu cache?
So why fields *firstWaiter* and *lastWaiter* can keep memory consistant without **volatile**?
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** These two fields are not volatile, may be modified by different thread */
private transient ConditionNode firstWaiter;
private transient ConditionNode lastWaiter;
} |
ConditionObject of ReentranentLock: fields are not decorated as volatile |
|java|volatile|reentrantlock| |
You should check for multipart content
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
}
}
} catch (Exception e) {
Example of such servlet you can find [here][1].
[1]: http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp
|
That is almost the same use-case given as example in the [documentation](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Map.html#computeIfAbsent(K,java.util.function.Function)) of `Map.computeIfAbsent()`, which is implemented by `ConcurrentHashMap`:
> The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in:
> ...
> Or to implement a multi-value map, Map<K,Collection<V>>, supporting multiple values per key:
> ````java
> map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);
> ````
It can be changed to use an `ArrayList` instead of the `HashSet`:
````java
Map<String,List<Integer>> map = new ConcurrentHashMap<>();
void insertVal(String key, int value) {
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
```` |
|c#|blazor|blazor-webassembly| |
Cannot downcast logger back to original struct |
|rust|traits|downcast| |
null |
I'm currently studying on how to create a pie-chart with a legend. But the thing is while i'm trying to re-code the program I encountered this error:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nSUcA.png
As per checking the code error: `var color = d3.scaleOrdinal(d3.schemeCategory20c);` i don't know why this became an error since it's usually working.
The code snippet is my code below:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// define data
var dataset = [
{label: "Assamese", count: 100},
{label: "Bengali", count: 83},
{label: "Bodo", count: 1.4},
{label: "Dogri", count: 2.3},
{label: "Gujarati", count: 46},
{label: "Hindi", count: 300},
{label: "Kannada", count: 38},
{label: "Kashmiri", count: 5.5},
{label: "Konkani", count: 5},
{label: "Maithili", count: 20},
{label: "Malayalam", count: 33},
{label: "Manipuri", count: 1.5},
{label: "Marathi", count: 72},
{label: "Nepali", count: 2.9},
{label: "Oriya", count: 33},
{label: "Punjabi", count: 29},
{label: "Sanskrit", count: 0.01},
{label: "Santhali", count: 6.5},
{label: "Sindhi", count: 2.5},
{label: "Tamil", count: 61},
{label: "Telugu", count: 74},
{label: "Urdu", count: 52}
];
// chart dimensions
var width = 1200;
var height = 800;
// a circle chart needs a radius
var radius = Math.min(width, height) / 2;
// legend dimensions
var legendRectSize = 25; // defines the size of the colored squares in legend
var legendSpacing = 6; // defines spacing between squares
// define color scale
var color = d3.scaleOrdinal(d3.schemeCategory20c);
// more color scales: https://bl.ocks.org/pstuffa/3393ff2711a53975040077b7453781a9
var svg = d3.select('#pieChart') // select element in the DOM with id 'chart'
.append('svg') // append an svg element to the element we've selected
.attr('width', width) // set the width of the svg element we just added
.attr('height', height) // set the height of the svg element we just added
.append('g') // append 'g' element to the svg element
.attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')'); // our reference is now to the 'g' element. centerting the 'g' element to the svg element
var arc = d3.arc()
.innerRadius(0) // none for pie chart
.outerRadius(radius); // size of overall chart
var pie = d3.pie() // start and end angles of the segments
.value(function(d) { return d.count; }) // how to extract the numerical data from each entry in our dataset
.sort(null); // by default, data sorts in oescending value. this will mess with our animation so we set it to null
// define tooltip
var tooltip = d3.select('#pieChart') // select element in the DOM with id 'chart'
.append('div') // append a div element to the element we've selected
.attr('class', 'tooltip'); // add class 'tooltip' on the divs we just selected
tooltip.append('div') // add divs to the tooltip defined above
.attr('class', 'label'); // add class 'label' on the selection
tooltip.append('div') // add divs to the tooltip defined above
.attr('class', 'count'); // add class 'count' on the selection
tooltip.append('div') // add divs to the tooltip defined above
.attr('class', 'percent'); // add class 'percent' on the selection
// Confused? see below:
// <div id="chart">
// <div class="tooltip">
// <div class="label">
// </div>
// <div class="count">
// </div>
// <div class="percent">
// </div>
// </div>
// </div>
dataset.forEach(function(d) {
d.count = +d.count; // calculate count as we iterate through the data
d.enabled = true; // add enabled property to track which entries are checked
});
// creating the chart
var path = svg.selectAll('path') // select all path elements inside the svg. specifically the 'g' element. they don't exist yet but they will be created below
.data(pie(dataset)) //associate dataset wit he path elements we're about to create. must pass through the pie function. it magically knows how to extract values and bakes it into the pie
.enter() //creates placeholder nodes for each of the values
.append('path') // replace placeholders with path elements
.attr('d', arc) // define d attribute with arc function above
.attr('fill', function(d) { return color(d.data.label); }) // use color scale to define fill of each label in dataset
.each(function(d) { this._current - d; }); // creates a smooth animation for each track
// mouse event handlers are attached to path so they need to come after its definition
path.on('mouseover', function(d) { // when mouse enters div
var total = d3.sum(dataset.map(function(d) { // calculate the total number of tickets in the dataset
return (d.enabled) ? d.count : 0; // checking to see if the entry is enabled. if it isn't, we return 0 and cause other percentages to increase
}));
var percent = Math.round(1000 * d.data.count / total) / 10; // calculate percent
tooltip.select('.label').html(d.data.label); // set current label
tooltip.select('.count').html('$' + d.data.count); // set current count
tooltip.select('.percent').html(percent + '%'); // set percent calculated above
tooltip.style('display', 'block'); // set display
});
path.on('mouseout', function() { // when mouse leaves div
tooltip.style('display', 'none'); // hide tooltip for that element
});
path.on('mousemove', function(d) { // when mouse moves
tooltip.style('top', (d3.event.layerY + 10) + 'px') // always 10px below the cursor
.style('left', (d3.event.layerX + 10) + 'px'); // always 10px to the right of the mouse
});
// define legend
var legend = svg.selectAll('.legend') // selecting elements with class 'legend'
.data(color.domain()) // refers to an array of labels from our dataset
.enter() // creates placeholder
.append('g') // replace placeholders with g elements
.attr('class', 'legend') // each g is given a legend class
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing; // height of element is the height of the colored square plus the spacing
var offset = height * color.domain().length / 2; // vertical offset of the entire legend = height of a single element & half the total number of elements
var horz = 18 * legendRectSize; // the legend is shifted to the left to make room for the text
var vert = i * height - offset; // the top of the element is hifted up or down from the center using the offset defiend earlier and the index of the current element 'i'
return 'translate(' + horz + ',' + vert + ')'; //return translation
});
// adding colored squares to legend
legend.append('rect') // append rectangle squares to legend
.attr('width', legendRectSize) // width of rect size is defined above
.attr('height', legendRectSize) // height of rect size is defined above
.style('fill', color) // each fill is passed a color
.style('stroke', color) // each stroke is passed a color
.on('click', function(label) {
var rect = d3.select(this); // this refers to the colored squared just clicked
var enabled = true; // set enabled true to default
var totalEnabled = d3.sum(dataset.map(function(d) { // can't disable all options
return (d.enabled) ? 1 : 0; // return 1 for each enabled entry. and summing it up
}));
if (rect.attr('class') === 'disabled') { // if class is disabled
rect.attr('class', ''); // remove class disabled
} else { // else
if (totalEnabled < 2) return; // if less than two labels are flagged, exit
rect.attr('class', 'disabled'); // otherwise flag the square disabled
enabled = false; // set enabled to false
}
pie.value(function(d) {
if (d.label === label) d.enabled = enabled; // if entry label matches legend label
return (d.enabled) ? d.count : 0; // update enabled property and return count or 0 based on the entry's status
});
path = path.data(pie(dataset)); // update pie with new data
path.transition() // transition of redrawn pie
.duration(750) //
.attrTween('d', function(d) { // 'd' specifies the d attribute that we'll be animating
var interpolate = d3.interpolate(this._current, d); // this = current path element
this._current = interpolate(0); // interpolate between current value and the new value of 'd'
return function(t) {
return arc(interpolate(t));
};
});
});
// adding text to legend
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; }); // return label
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DASHBOARD</title>
<!--Lib css-->
<!--bootstrap-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!--fontawesome-->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!--jquery-->
<script src="https://code.jquery.com/jquery-3.5.0.js"
integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
<!--own css-->
<style>
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";
body {
font-family: 'Poppins', sans-serif;
background: #fafafa;
}
p {
font-family: 'Poppins', sans-serif;
font-size: 1.1em;
font-weight: 300;
line-height: 1.7em;
color: #999;
}
a,
a:hover,
a:focus {
color: inherit;
text-decoration: none;
transition: all 0.3s;
}
.navbar {
padding: 15px 10px;
background: #fff;
border: none;
border-radius: 0;
margin-bottom: 40px;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}
.navbar-btn {
box-shadow: none;
outline: none !important;
border: none;
}
/* ---------------------------------------------------
SIDEBAR STYLE
----------------------------------------------------- */
.wrapper {
display: flex;
width: 100%;
align-items: stretch;
}
#sidebar {
min-width: 250px;
max-width: 250px;
background: rgb(60, 95, 238);
color: #fff;
transition: all 0.3s;
}
#sidebar.active {
margin-left: -250px;
}
#sidebar .sidebar-header {
padding: 20px;
background: rgb(90, 121, 243);
}
#sidebar ul.components {
padding: 20px 0;
border-bottom: 1px solid #47748b;
}
#sidebar ul p {
color: #fff;
padding: 10px;
}
#sidebar ul li a {
padding: 10px;
font-size: 1.1em;
display: block;
}
#sidebar ul li a:hover {
color: #7386D5;
background: #fff;
}
#sidebar ul li.active>a,
a[aria-expanded="true"] {
color: #fff;
background: #6d7fcc;
}
a[data-toggle="collapse"] {
position: relative;
}
.dropdown-toggle::after {
display: block;
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
ul ul a {
font-size: 0.9em !important;
padding-left: 30px !important;
background: #6d7fcc;
}
ul.CTAs {
padding: 20px;
}
ul.CTAs a {
text-align: center;
font-size: 0.9em !important;
display: block;
border-radius: 5px;
margin-bottom: 5px;
}
a.download {
background: #fff;
color: #7386D5;
}
a.article,
a.article:hover {
background: #6d7fcc !important;
color: #fff !important;
}
/* ---------------------------------------------------
CONTENT STYLE
----------------------------------------------------- */
#content {
width: 100%;
padding: 20px;
min-height: 100vh;
transition: all 0.3s;
}
/* ---------------------------------------------------
MEDIAQUERIES
----------------------------------------------------- */
@media (max-width: 768px) {
#sidebar {
margin-left: -250px;
}
#sidebar.active {
margin-left: 0;
}
#sidebarCollapse span {
display: none;
}
}
/* ---------------------------------------------------
CHART STYLE
-----------------------------------------------------
body {
font-family: 'Open Sans', sans-serif;
}
.title-holder {
text-align: center;
}
.title {
font-family: 'Lato', sans-serif;
}
.subtitle {
font-size: 20px;
}
.font {
font-size: 18px;
}
/* legend */
.title-holder {
text-align: center;
}
.title {
font-family: 'Lato', sans-serif;
}
.subtitle {
font-size: 20px;
}
.font {
font-size: 18px;
}
.legend {
font-size: 14px;
}
rect {
cursor: pointer;
stroke-width: 2;
}
rect.disabled {
fill: transparent !important;
}
/* chart */
#pieChart {
height: 800px;
margin: 0 auto;
position: relative;
display: block;
width: 1200px;
}
/* tooltip */
.tooltip {
background: #eee;
box-shadow: 0 0 5px #999999;
color: #333;
display: none;
font-size: 18px;
left: 130px;
padding: 10px;
position: absolute;
text-align: center;
top: 95px;
width: 80px;
z-index: 10;
}
.footer {
padding-top: 50px;
text-align: center;
list-style-type: none;
}
</style>
<!--lib js-->
<!--bootstrap-->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<!--fontawesome js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
<!--d3(chart) js-->
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div class="wrapper">
<!-- Sidebar -->
<nav id="sidebar">
<ul class="list-unstyled components">
<li class="active">
<a href="/">DASHBOARD</a>
</li>
</ul>
<!--End of nav.sidebar-->
</nav>
<!--Page content-->
<div id="content">
<!-- navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button type="button" id="sidebarCollapse" class="btn btn-info">
<i class="fas fa-align-justify"></i>
</button>
</div>
</nav>
<!--End of div.row-->
<div class="row">
<div class="col-12">
<div class="card shadow mb-5">
<div class="title-holder">
<h1 class="title">Language Use in India</h1>
<p class="subtitle">Calculated in the Millions</p>
<p class="font">Uncheck labels to recalculate.</p>
</div>
<div class="card-body">
<div id="pieChart">
</div>
</div>
<footer>
<ul class="footer">
<li><a href="http://www.censusindia.gov.in/Census_Data_2001/Census_Data_Online/Language/Statement5.aspx"
target="_blank">Data Source</a></li>
<li><a href="www.lisaofalltrades.com" target="_blank">lisaofalltrades.com</a></li>
</ul>
</footer>
</div>
</div>
</div>
<!--End of div.row-->
</div>
</div>
<!--End of div.content-->
</div>
<!--End of div.wrapper-->
<!--Lib <script>-->
<!--own <script>-->
<script src="js/script.js"></script>
</body>
</html>
<!-- end snippet -->
I've researched on how to use the `d3.schemeCategorry20c` it seems there is no problem in the way I used it. What could be the problem?
|
In the WordPress core, WordPress uses the sanitize_title hook to apply its own filter (you can find that in this code):
https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php
Here you can see it calls sanitize_title_with_dashes:
https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/
That's the function you are looking for. |
Breadcrumbs::for replaces the old Breadcrumbs::register in the Routes\Breadcrumbs.php file. |
This is possible with **static** fields.Because, interfaces cannot contains instance fields. Static fields are not instance fields.
Or you can use literal values. For example, I use Age property in interface below.
public interface IMyDefault
{
private static string _name = "Yusif";
// Has default implementation
string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
int Age { get => 18; }
// Hasn't default implementation
string Surname { get; set; }
}
public class MyDefault : IMyDefault
{
// We only implement Surname in MyDefault.cs
public string Surname { get; set; }
}
But, you can access default implemented properties only after cast object to interface.
For example:
Code below **will not compile**
MyDefault myDefault1 = new MyDefault();
Console.WriteLine(myDefault1.Name);
Code below **will compile**
IMyDefault myDefault2 = new MyDefault();
Console.WriteLine(myDefault2.Name); |
The technique described in the answer to [Is it possible to detect which View currently falls under the location of a DragGesture?](https://stackoverflow.com/q/77796978/20386264) can be used to detect, which of the squares is closest to the drag position (it was my answer).
`matchedGeometryEffect` then provides a convenient way to match the position of the blue rectangle to the identified square.
Like this:
```swift
@State private var dragLocation = CGPoint.zero
@State private var indexForDragLocation = 0
@Namespace private var ns
let spacing: CGFloat = 50
private func dragDetector(for index: Int) -> some View {
GeometryReader { proxy in
let width = proxy.size.width
let midX = proxy.frame(in: .global).midX
let dx = abs(midX - dragLocation.x)
let isClosest = dx < (width + spacing) / 2
Color.clear
// pre iOS 17: .onChange(of: isClosest) { newVal in
.onChange(of: isClosest) { oldVal, newVal in
if newVal {
indexForDragLocation = index
}
}
}
}
var body: some View {
HStack(spacing: spacing) {
ForEach(0...4, id: \.self) { index in
Color(white: 0.2)
.frame(width: 20, height: 20)
.matchedGeometryEffect(id: index, in: ns, isSource: index == indexForDragLocation)
.background {
dragDetector(for: index)
}
}
}
.background {
RoundedRectangle(cornerRadius: 4)
.fill(.blue)
.frame(width: 40, height: 80)
.matchedGeometryEffect(
id: indexForDragLocation,
in: ns,
properties: .position,
isSource: false
)
.animation(.spring, value: indexForDragLocation)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(UIColor.systemBackground))
.gesture(
DragGesture(coordinateSpace: .global)
.onChanged { val in
dragLocation = val.location
}
)
}
```
 |
null |
How to update remote module without refreshing the window in Angular module federation |
|angular|webpack|micro-frontend|webpack-module-federation|angular-module-federation| |
I feel it is good for stateless apps on frontend. |
null |
{"Voters":[{"Id":1116230,"DisplayName":"Nico Haase"},{"Id":476,"DisplayName":"deceze"}]} |
I have interface `PackItemStack` and `ItemStackMixin` that implement it. Mixin is registered in mixin.json config.
But when I try to cast main class ItemStack to interface, IDE gives an error `Inconvertible types; cannot cast 'net.minecraft.item.ItemStack' to 'net.smok.PackItemStack'`
Fabric 0.92.0+1.20.1, Java 17.
I have interface `PackItemStack` and `ItemStackMixin` that implement it. Mixin is registered in mixin.json config.
But when I try to cast main class ItemStack to interface, IDE gives an error `Inconvertible types; cannot cast 'net.minecraft.item.ItemStack' to 'net.smok.PackItemStack'`
Fabric 0.92.0+1.20.1, Java 17.
In all guides it is just work without any other steps. Fabricmc wiki says that I need somehow register injected interface with reference to compiled class. But I don't understand how to do it. |
Fabricmc cannot cast minecraft class to injected interface |
|java|minecraft-fabric| |
null |
I am using Oracle APE 23.1.
I created an app, then enabled PWA after I created it. I have enabled persistent authentication on the instance and in the application.
But now, deep linking isnt working. All deep links take me to the Home page (authenticated, so peristent authentication is working).
So I can only have deep linking working when I disable persistent authentication apparently, unless I am missing some setting.
If I log on and press "Rememeber me" to enable persistent authentication, persistent authentication works but deep linking fails.
If I log out and then log in again and DONT press "Remember me", when I use a deep link, I am asked to authenticate and then am taking to the correct deep link location.
|
Oracle APEX - Enabling Persistent Authentication Breaks Deep Linking |