instruction stringlengths 0 30k ⌀ |
|---|
null |
The error "No object exists at the desired reference" in Firebase Storage usually indicates that the path you provided does not correspond to any object in the storage bucket. Here are a few things to check and troubleshoot:
1. **Check Firebase Storage Path**: Ensure that the path you're providing to `FirebaseStorage.instance.ref()` matches the path where your images are stored in Firebase Storage. You mentioned that your images are stored in the root directory, so the path should indeed be correct.
2. **Verify Firebase Storage Rules**: Even though you mentioned that you've set Firebase Storage rules to allow read and write without authentication, it's a good idea to double-check them to ensure they are correctly configured. Here's an example of rules that allow public read access to all files:
```plaintext
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read;
allow write: if false; // or any other conditions for write operations
}
}
}
```
3. **Check for Errors in URL Fetching**: Although you have a catch block to handle errors when fetching URLs, you might want to print out the specific error messages to help with troubleshooting. Modify the catch block in `fetchImages()` like this:
```dart
} catch (error) {
print("Error fetching URL: $error");
}
```
This way, you can see the exact error message if there are any issues with fetching the download URLs.
4. **Verify Firebase Initialization**: Ensure that Firebase is initialized correctly in your app. You've already done this in your `main()` function, but it's good to double-check.
If you've verified all of the above and you're still encountering issues, try checking the Firebase console for any error logs or additional information that might help pinpoint the problem. Also, make sure that your Firebase project is properly set up and linked to your Flutter app.
|
Brick Breaker Ball Bounce |
|c++|sdl|collision|breakout| |
null |
Every time i run my Streamlit Web app terminal sends a warning message always that i interact with the app:
> \`label\` got an empty value. This is discouraged for accessibility reasons and may be disallowed in the future by raising an exception. Please provide a non-empty label and hide it with label_visibility if needed
I checked the widgets and widgets arguments but maybe i am not watching something.
Steps to Reproduce
1. Copy python code into a python file in your Visual Studio Code 'form.py'
2. Install python library: `streamlit==1.32.2`
* Example command to use: `pip install`
* Extra information: Use virtual environment`venv`
3. Run web app from file directory of main file `streamlit run ./form.py`
Environment information
* Python version: `Python 3.12.2`
* SO: Windows
* Streamlit version: `streamlit==1.32.2`
* Code Editor: Visual Studio Code
Code
```
import streamlit as st
import pandas as pd
import os
from datetime import datetime
with st.form('myform'):
st.subheader('Registration Form')
c1, c2, c3 = st.columns(3)
select_box = c1.selectbox('',('Mr','Mrs','Miss'))
first_name = c2.text_input('First Name', '')
last_name = c3.text_input('Last Name', '')
# Role
role = st.selectbox('Designation',('Software',
'Sr. Software','Technical Lead',
'Manager','Sr. Manager','Project Manager'))
# Date of Birth
dob = st.date_input('Date of Birth',
min_value=datetime(year=1900,month=1,day=1))
# Gender
gender = st.radio(
"Select Gender",
('Male','Female','Prefered Not to Say')
)
# age
age = st.slider('Age',min_value=1,max_value=100,step=1,value=20)
submitted = st.form_submit_button('Submit')
if submitted:
st.success('Form Subimitted Sucessfully')
details = {
'Name': f"{select_box} {first_name} {last_name}",
'Age': age,
'Gender':gender,
'Data of Birth': dob,
'Designation':role
}
st.json(details)
``` |
When I connect the HDMI from my computer to the TV, the TV screen does not show the image correctly and sometimes does not detect the computer, I clarify that I have Ubuntu and not Windows, does anyone know a possible solution? The HDMI cable is working properly and so is the TV, I have already checked it several times.
I searched the internet for information but found noth[enter image description here](https://i.stack.imgur.com/4pyiC.jpg)ing. |
Problems sharing the screen of my laptop with hdmi in Ubuntu |
|screen|sharing|hdmi|ubuntu-23.10| |
null |
So I'm having a problem when building my Flutter app in release mode for flutter.
When I build my Flutter app in debug mode it works fine and I can use my app in any emulator without any problem. But when I click edit scheme and try to run it in release mode the build fails and I get cloud_firestore module not found.
The reason I'm trying to build for release mode is that when I submitted my app for the app store it got rejected almost immediately and the reason was that the app crashed when launching.
Information you should know:
Mac Version:
[](https://i.stack.imgur.com/ZAMyP.png)
App works fine in debug mode
XCode version: v14.2
Flutter doctor: No errors
Cocoapods version: 1.15.2
Flutter version: 3.19.5 (Stable version)
Dart version: 3.3.3
Podfile content:
```
platform :ios, '12.0'
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
target 'RunnerTests' do
inherit! :search_paths
end
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
```
Pubspec.yaml content:
```
name: lifenavigator
version: 1.0.0+1
publish_to: none
description: A new Flutter project.
environment:
sdk: '>=3.2.3 <4.0.0'
dependencies:
cupertino_icons: ^1.0.2
get: 4.6.6
flutter:
sdk: flutter
google_fonts: 6.1.0
firebase_core: ^2.27.0
firebase_auth: ^4.17.8
font_awesome_flutter: ^10.7.0
convex_bottom_bar: ^3.2.0
cloud_firestore: ^4.15.8
firebase_messaging: ^14.7.19
google_sign_in: ^6.2.1
flutter_facebook_auth: ^6.1.1
flutter_dotenv: ^5.1.0
dio: ^5.4.1
url_launcher: ^6.2.5
flutter_launcher_icons: ^0.13.1
google_mobile_ads: ^5.0.0
dev_dependencies:
flutter_lints: ^3.0.2
flutter_test:
sdk: flutter
flutter_launcher_icons: "^0.13.1"
flutter_launcher_icons:
android: "launcher_icon"
ios: true
image_path: "assets/applogo.png"
flutter:
uses-material-design: true
assets:
- assets/
- .env
```
Solutions I tried:
I tried cleaning the previous builds and building again.
I tried `Flutter upgrade` and `pod repo update` and `flutter pub get` and `pod install`
I tried adding cloudFirestore in Podfile as `pod 'FirebaseCore', :modular_headers => true` (trigggered a new error)
I was trying to build my application for release mode but the build failed and I got module "cloud_firestore" not found |
As mentioned by @Doug Stevenson:
>You're supposed to replace the use of the old functions.config() with environment variables from the documentation you read.
**Use environment variables to access configuration values**
```
const fbToken = process.env.FB_TOKEN; // Configure this as a variable in the environment
async function deletePath(path) {
await firebaseTools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
force: true,
token: fbToken,
});
}
```
Then
Use `firebase deploy --only functions` to deploy v2 functions.
Reference:
* [Configure your environment](https://firebase.google.com/docs/functions/config-env?gen=2nd#env-variables)
* [V2 and examples: Extend Cloud Firestore with Cloud Functions (2nd gen)](https://firebase.google.com/docs/firestore/extend-with-functions-2nd-gen) |
I found the problem, I did not include proper LDFLAGS. This is the correct main.go:
```go
package main
/*
#cgo LDFLAGS: -L${SRCDIR}/lib -l calc
#cgo CFLAGS: -I${SRCDIR}/include
#include "include/calc.h"
*/
import "C"
func main() {
C.execute()
}
``` |
If you were to use PHP to generate the `brands` checkboxes ( something that has merit if there are many brands which can be altered any time by an administrator for example ) then perhaps the following might give an idea how to maintain the `checked` status of each checkbox.
The following is a rough idea how you might accomplish the stated goal - I hope you might find it of help.
<form method='get'>
<fieldset>
<?php
# an array of brands.. this could likely be from the database
$brands=['iPhone','iPad','Samsung','Huawei','Nokia','Sony','LG','Motorola','Blackberry','Vodafone','Alcatel','Razer','Google'];
# get either the current GET array or an empty array
$params=$_GET;
# add the brands checkboxes
foreach( $brands as $brand ){
# maintain the checked status by checking if the current brand is in the `brand[]` querystring value
$checked=isset( $_GET['brand'] ) && in_array( $brand, $_GET['brand'] ) ? ' checked' : '';
# print the checkbox
printf('<input type="checkbox" name="brand[]" value="%1$s"%2$s>%1$s<br />', $brand, $checked );
}
?>
<!-- a hidden field will ensure the page variable is set each time the form is submitted -->
<input type='hidden' name='page' value='<?=isset( $_GET['page'] ) ? $_GET['page'] : 1;?>' />
<input type='submit' />
</fieldset>
<fieldset id='paging'>
<?php
# some pseudo paging links... should be derived dynamically ~ this is just for demo
for( $i=1; $i <= 10; $i++ ){
$params['page']=$i;
$active=isset( $_GET['page'] ) && intval( $_GET['page'] )==$i ? ' class="active"' : '';
printf('<a href="?%2$s" %3$s>[ %1$d ]</a>', $i, http_build_query( $params ), $active );
}
?>
</fieldset>
</form>
|
when I try to install pynput on pydroid3 on android it says this
**/storage/emulated/0 $ pip install pynput
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x70a5137690>: Failed to establish a new connection: [Errno 7] No address associated with hostname')': /simple/pynput/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x70a4d9bfd0>: Failed to establish a new connection: [Errno 7] No address associated with hostname')': /simple/pynput/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x70a4dac610>: Failed to establish a new connection: [Errno 7] No address associated with hostname')': /simple/pynput/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x70a4dad3d0>: Failed to establish a new connection: [Errno 7] No address associated with hostname')': /simple/pynput/**
actually in every package installation it says same like this.
How can I solve this I hava installed pydroid repository plugin also |
How much accuracy is lost due to representing time as a IEEE 754 binary64 number? |
|floating-point|double|ieee-754|floating-accuracy| |
I need your help.
I’m automating a task.
I would like to automatically select 5 numbers on the game card using my Excel program (created using VBA language).
I would place a symbol (chr 149) on the selected numbers using the printer.
Numbers are printed on the game card and I need to select them.
At the moment, I’m able to select and print only one number at a time.
So, I ask you how I can select 5 numbers printing for five times the character 149 on the same card at once.
Following the code I use to select only one number at once.
Thank you in advance
```
Sub PrintNumbers()
With ActiveSheet
With .PageSetup
.LeftMargin = Application.InchesToPoints(1.13)
.RightMargin = Application.InchesToPoints(0.707)
.TopMargin = Application.InchesToPoints(1.528)
.BottomMargin = Application.InchesToPoints(0.748031496062992)
.HeaderMargin = Application.InchesToPoints(0.31496062992126)
.FooterMargin = Application.InchesToPoints(0.31496062992126)
End With
End With
ActiveSheet.PrintOut
End Sub
```
I tried using repeated cycles |
*Adequate block deployment is not working html/css. Blocks do not work properly. There are blocks, and if you click on one block, the next block expands, this happens on the tablet version, what to do?* **Example: in the picture, when one block is expanded, another block is expanded behind it.I want to make sure that when you click on one block, the second does not open**[
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.team {
width: 688px;
margin: 0 auto;
margin-top: 29px;
margin-bottom: 29px;
display: flex;
flex-direction: column;
}
.container_team {
width: 744px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.input {
display: none;
}
.input:checked~.p {
max-width: 100vw;
max-height: 100vh;
position: relative;
white-space: normal;
clip-path: none;
margin-top: 15px;
}
.input:checked+.item_label::after {
transform: rotate(315deg);
}
.h3 {
font-family: 'Inter';
font-size: 18px;
font-weight: 700;
line-height: 25px;
letter-spacing: 0em;
text-align: center;
}
.im {
margin-top: 20px;
margin-bottom: 20px;
}
.team {
max-width: 743px;
}
.team h3 {
font-size: 18px;
font-weight: 700;
font-family: 'Inter';
line-height: 25px;
}
.team picture {
width: 330px;
height: 203px;
}
.team .le {
width: 550px;
display: flex;
flex-direction: column;
align-items: center;
}
.team .lea {
display: flex;
flex-direction: column;
align-items: center;
}
.team .pZ {
width: 550px;
display: flex;
flex-direction: column;
align-items: center;
}
.team .zp {
width: 550px;
display: flex;
align-items: center;
flex-direction: column;
}
.team label {
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 10px;
padding-right: 10px;
}
.team label::after {
content: '+';
width: 30px;
height: 30px;
font-size: 30px;
font-weight: bolder;
}
.team input:checked~label::after {
transform: rotateZ(315deg);
}
.team .men {
width: 300px;
font-size: 18px;
}
.team .buzne {
width: 300px;
}
.team .tele {
width: 300px;
margin-top: 10px;
background: #F5FFD9;
}
.team .Ar {
width: 300px;
margin-top: 10px;
}
.team .Di {
width: 300px;
margin-top: 10px;
}
.team .ro {
width: 300px;
margin-top: 10px;
}
.team .te {
width: 300px;
margin-top: 10px;
}
.team .su {
width: 300px;
margin-top: 10px;
}
.team .container_team .p {
position: absolute;
max-width: 1px;
max-height: 1px;
margin: -1px;
border: 0;
padding: 0;
white-space: nowrap;
clip-path: inset(100%);
clip: rect(0 0 0 0);
overflow: hidden;
padding: 20px;
}
.team picture {
order: 1;
margin-left: 190px;
}
.team picture img {
width: 330px;
height: 203px;
}
.h2 {
margin-left: 190px;
}
.team .container_team .input:checked~.p {
max-height: 100vh;
max-width: 100vw;
position: relative;
white-space: normal;
clip-path: none;
}
.Ar>.team input:checked {
z-index: 1;
}
<!-- language: lang-html -->
<section class="team">
<h2 class="h2">Команда розробників</h2>
<div class="container_team">
<div class="men">
<input class="input" type="checkbox" name="" id="checks1">
<label for="checks1">
<h3 class="h3">Менеджер проекту</h3>
</label>
<p class="p">Менеджер проекту розподіляє завдання між командою, планує хід роботи, мотивує команду, контролює процес та координує спільні дії. Також він несе відповідальність за тайм-менеджмент, управління ризиками та дії у разі непередбачених ситуацій. Основний
обов’язок і відповідальність PM – довести ідею замовника до реалізації у встановлений термін, використовуючи наявні ресурси. В рамках цієї задачі PM’у необхідно створити план розробки, організувати команду, налаштувати процес роботи над проектом,
забезпечити зворотній зв’язок між командами та замовником, усувати перешкоди для команд, контролювати якість і виконання термінів. Його основне завдання полягає в управлінні проектом. Як і бізнес-аналітик, менеджер проекту також може бути включений
у комунікацію з клієнтом, проте головним завданням PM є робота безпосередньо з командою розробників програмного забезпечення. Середній вік в Україні- 30 років. Вирізняються високим рівнем освіти (тільки 6% не мають вищої освіти). Зарплата 1700-2500$.</p>
</div>
<div class="buzne">
<input class="input" type="checkbox" name="" id="checks2">
<label for="checks2">
<h3 class="h3">Бізнес аналітик</h3>
</label>
<p class="p">Це фахівець, який досліджує проблему замовника, шукає рішення і оформлює його концепцію в формі вимог, на які надалі будуть орієнтуватися розробники при створенні продукту. Середньому українському бізнес-аналітику 28 років, він має зарплату $ 1300-2500
і досвід роботи 3 роки.</p>
</div>
<div class="tele">
<input type="checkbox" name="" id="checks3">
<label for="checks3">
<h3 class="h3">Team Lead</h3>
</label>
<p class="p">Це IT-фахівець, який керує своєю командою розробників, володіє технічною стороною, бере участь у роботі над архітектурою проекту, займається рев'ю коду, а також розробкою деяких складних завдань на проекті. За статистикою ДНЗ, середній вік українських
тімлідів – 28 років, середній досвід роботи – 6,5 років, середня зарплата – $2800.</p>
</div>
<div class="Ar">
<input type="checkbox" id="checks4">
<label for="checks4">
<h3 class="h3">Архітектор ПЗ</h3>
</label>
<p class="p">
Приймає рішення щодо внутрішнього устрою і зовнішніх інтерфейсів програмного комплексу з урахуванням проектних вимог і наявних ресурсів.Головна задача архітектора – пошук оптимальних (простих, зручних, дешевих) рішень, які будуть максимально відповідати
потребам замовника і можливостям команди. За статистикою ДОУ, середньому українському архітектору 30 років, він має 9-річний досвід роботи і отримує $ 4000.</p>
</div>
<div class="Di">
<input type="checkbox" name="" id="checks5">
<label class="label_comamnd" for="checks5">
<h3 class="h3">Дизайнер</h3>
</label>
<p class="p">Спеціаліст, який займається проектуванням інтерфейсів користувача. В середньому українському дизайнеру – 26 років, він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 1000-200</p>
</div>
<picture>
<source media="(min-width:1280px)" srcset="img/team1x.png 1x,img/team2x.png 2x,img/team3x.png 3x">
<img class="im" src="https://picsum.photos/200" alt="Проект">
</picture>
<div class="ro">
<input type="checkbox" name="" id="checks6">
<label for="checks6">
<h3 class="h3">Розробник</h3>
</label>
<p class="p">Фахівець, який пише вихідний код програм і в кінцевому результаті створює технології. Програмісти також мають різні галузі експертизи, вони пишуть різними мовами та працюють з різними платформами. Тому і існує така “різноманітність” розробників,
залучених до одного проекту. На одному проекті переважно завжди є як мінімум два програмісти- перший, який займається back-end розробкою та інший, відповідальний за front-end. Існує два напрямки програмування - системне та прикладне. Системні
програмісти мають справу з ОС, інтерфейсами баз даних, мережами. Прикладні – з сайтами, програмним забезпеченням, програмами, редакторами, соцмережами, іграми тощо. Програміст розробляє програми за допомогою математичних алгоритмів. Перед початком
роботи йому необхідно скласти алгоритм або знайти оптимальний спосіб вирішення конкретного завдання. В середньому українському програмісту 27 років, його зарплата в середньому дорівнює $ 1500-2500, а досвід роботи становить 4,5 років.</p>
</div>
<div class="te">
<input type="checkbox" name="" id="checks7">
<label for="checks7">
<h3 class="h3">Тестувальник</h3>
</label>
<p class="p">Фахівець, необхідний для кожного процесу розробки для забезпечення високої якості продукту. Вони тестують його, проходять через усі додатки та визначають баги та помилки з подальшим наданням звіту команді розробки, яка проводить їх виправлення За
даними ДОУ, середньому українському QA-інженеру 26 років. Він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 600-2700.</p>
</div>
<div class="su">
<input type="checkbox" name="" id="checks8">
<label for="checks8">
<h3 class="h3">Support</h3>
</label>
<p class="p">Ключове завдання support-фахівця (або Customer Support Representative) — відповідати на запитання і допомагати клієнтам у телефонному режимі, поштою або у чаті. Решта завдань залежать від процесів у конкретній компанії.</p>
</div>
</div>
</section>
<!-- end snippet -->
I still haven't found out the problem I looked on the Internet, no solution!
I'm studying html/css/js at a computer school and they haven't solved this problem yet. I hope you can help us) |
Calling `NestedReference.builder()` should work.
Which version of Java and Lombok are you using?
Have you tried calling the `NestedReferenceBuilder` constructor directly?
```java
public static NestedReference of(ReferenceId referenceId) {
return new NestedReferenceBuilder()
.referenceId(referenceId)
.build();
}
```
### Alternative to builder
You can leverage the power of records and Lombok in a different way:
```java
import lombok.NonNull;
public record NestedReference(@NonNull ReferenceId referenceId) {}
```
```java
public static void main(String[] args) {
NestedReference ref = new NestedReference(null);
System.out.println(ref);
}
```
```
Exception in thread "main" java.lang.NullPointerException: referenceId is marked non-null but is null
at org.example.NestedReference.<init>(NestedReference.java:5)
at org.example.Main.main(Main.java:6)
```
If you cannot use records yet, you can use `@Value`:
```
import lombok.NonNull;
import lombok.Value;
@Value
public class NestedReference {
@NonNull ReferenceId referenceId;
}
``` |
it works I put this code :
var soapMessage = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body> ' +
'<CheckPalletInLocation xmlns="http://tempuri.org/"> ' +
'<location>110-01-03-10</location> ' +
'</CheckPalletInLocation> ' +
'</soap:Body>`' +
'</soap:Envelope>';
|
I would like to typehint, that my pure mixin (`MyMixin`) expects the super class to have the `get_context_data` method.
```
class HasViewProtocol(Protocol):
kwargs: dict
@abstractmethod
def get_context_data(self, **kwargs) -> dict:
pass
class MyMixin(HasViewProtocol):
def get_context_data(self, **kwargs) -> dict:
return super().get_context_data(**kwargs) | {
"extra_data": "bla"
}
```
Here Pycharm's inspection issues:
```
type of 'get_context_data' is incompatible with 'HasViewProtocol`
```
- Are protocols the right aproach to annotate my expectation on the super class?
- Why is the `get_context_data` incompatible with the `HasViewProtocol`? |
Module not found when building flutter app for IOS |
|ios|flutter|build|cocoapods|podfile| |
null |
I've been trying to use copywriter to extract the copy number information of some exomes from mice (mm10) and kept encountering the same error:
Error in if (nrow(peaks) > 0) { : argument is of length zero Calls: CopywriteR ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous> Execution halted
```
library("CopywriteR")
library("BiocParallel")
library("matrixStats")
library("gtools")
library("data.table")
library("S4Vectors")
library("chipseq")
library("IRanges")
library("Rsamtools")
library("DNAcopy")
library("GenomicAlignments")
library("GenomicRanges")
library("CopyhelpeR")
library("GenomeInfoDb")
library("futile.logger")
data.folder <- tools::file_path_as_absolute(file.path(getwd()))
bp.param <- SnowParam(workers = 1, type = "SOCK")
path <- "/mnt/atgc-d1/drobles/ftalavera/copywriter_test"
samples <- list.files(path = path, pattern = ".bam$", full.names = TRUE)
controls <- samples
sample.control <- data.frame(samples, controls)
CopywriteR(sample.control = sample.control,
destination.folder = file.path(data.folder),
reference.folder = file.path(data.folder, "mm10_4_20kb"),
bp.param = bp.param)
```
I have tried everything in the troubleshooting section in github but I still can't figure out what is happening, do you have any idea?
I would really appreciate your help. |
Error in if (nrow(peaks) > 0) { : argument is of length zero Calls: CopywriteR ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous> Execution ha |
|r| |
null |
I think you could change your code here
tree.plot_tree(classifier.fit(Xtest, Ytest))
into
tree.plot_tree(decision_tree.named_steps['cls'])
as named_steps is an attribute of your fitted pipeline https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html.
It works for me. |
Let's start by not bothering with rows vs. columns, because (and this is the nice thing about the game of life), it doesn't matter. The only thing that matters is what the eight values _around_ a cell are doing, so as long as we stick to one ordering, the code will simply do the right thing.
Which means we can get rid of that `Cell` function (on that note, that's not how you name things in JS. Variables and functions use lowerCamelCase, classes/constructor functions use UpperCamelCase and constant values use UPPER_SNAKE_CASE).
Then, let's fix `Nsum` because it's ignoring the edges right now, which is not how the game of life works: in order to count how many neighbours a cell has, we need to sum _up to_ eight values, but not every cell has eight neighbours. For instance, (0,0) has nothing to the left/above it. So let's rewrite that to a loop:
```lang-js
function getNeighbourCount(i, j) {
const cells = currentCells;
let sum = 0;
// run over a 3x3 block, centered on i,j:
for (let u = -1; u <= 1; u++) {
// ignore any illegal values, thanks to "continue";
if (i + u < 0 || i + u >= cellCount) continue;
for (let v = -1; v <= 1; v++) {
// again, ignore any illegal values:
if (j + v < 0 || j + v >= cellCount) continue;
// and skip over [i][j] itself:
if (u === 0 && v === 0) continue;
sum += cells[i + u][j + v];
}
}
return sum;
}
```
We can also take advantage of the fact that we _know_ that we're setting our update board to zeroes before we start calculating updates, so we don't need to set any cells to 0: they already are.
```lang-js
...
// by copying the empty cells array, we start with
// all-zeroes, so we don't need to set anything to 0.
const next = structuredClone(emptyCells);
for (let i = 0; i < cellCount; i++) {
for (let j = 0; j < cellCount; j++) {
// is this cell alive?
const alive = currentCells[i][j] === 1;
// we only need to calculate this once, not three times =)
const neighbourCount = getNeighbourCount(i, j);
if (alive && (neighbourCount === 2 || neighbourCount === 3)) {
next[i][j] = 1;
} else if (neighbourCount === 3) {
next[i][j] = 1;
}
}
}
...
```
So if we put all that together, and instead of using a canvas we just use a preformatted HTML element that we print our grid into, we get:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const cellCount = 10;
// Let's define the same grid, but rather than harcoding it,
// let's just generate it off of a single number:
const emptyCells = [...new Array(cellCount)].map((_) => [...new Array(cellCount)].fill(0));
// Then, initialize the current cells from that empty grid.
let currentCells = structuredClone(emptyCells);
// To see things work, let's add a "glider"
[[0, 1],[1, 2],[2, 0],[2, 1],[2, 2]].forEach(([i, j]) => (currentCells[i][j] = 1));
// Then, our control logic: we'll have the sim run
// with a button to pause-resume the simulation.
let nextRun;
let paused = false;
toggle.addEventListener(`click`, () => {
paused = !paused;
if (paused) clearTimeout(nextRun);
else runSimulation();
});
// And then: run the program!
showBoard();
runSimulation();
// It doesn't matter where we put functions in JS: the parser first
// reads in every function, and only *then* starts running, letting
// us organize things in terms of "the overall program" first, and
// then "the functions that our program relies on" after.
// draw our board with □ and ■ for dead and live cells, respectively.
function showBoard() {
board.textContent = currentCells
.map((row) => row.join(`,`).replaceAll(`0`, `□`).replaceAll(`1`, `■`))
.join(`\n`);
}
// our simulation just runs through the grid, updating
// an initially empty "next" grid based on the four
// Game of Life rules.
function runSimulation() {
const next = structuredClone(emptyCells);
for (let i = 0; i < cellCount; i++) {
for (let j = 0; j < cellCount; j++) {
const alive = currentCells[i][j] === 1;
const neighbourCount = getNeighbourCount(i, j);
if (alive && (neighbourCount === 2 || neighbourCount === 3)) {
next[i][j] = 1;
} else if (neighbourCount === 3) {
next[i][j] = 1;
}
}
}
// update our grid, draw it, and then if we're not paused,
// schedule the next call half a second into the future.
currentCells = next;
showBoard();
if (!paused) {
nextRun = setTimeout(runSimulation, 500);
}
}
// In order to count how many neighbours we have, we need to
// sum *up to* eight values. This requires making sure that
// we check that a neighbour even exists, of course, because
// (0,0), for instance, has nothing to the left/above it.
function getNeighbourCount(i, j, cells = currentCells) {
let sum = 0;
for (let u = -1; u <= 1; u++) {
if (i + u < 0 || i + u >= cellCount) continue;
for (let v = -1; v <= 1; v++) {
if (j + v < 0 || j + v >= cellCount) continue;
if (u === 0 && v === 0) continue;
sum += cells[i + u][j + v];
}
}
return sum;
}
<!-- language: lang-html -->
<pre id="board"></pre>
<button id="toggle">play/pause</button>
<!-- end snippet -->
|
I want to develop a custom plugin for my expo app to make some changes to my MainActivity file on Android.
I saw [some examples in the documentation](https://docs.expo.dev/config-plugins/plugins-and-mods/#create-a-mod) where the plugin was written using `import/export`, however that does not seem to work for me.
I am getting the following error:
```
import { ConfigPlugin, withDangerousMod } from "expo/config-plugins";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:77:18)
at wrapSafe (node:internal/modules/cjs/loader:1288:20)
at Module._compile (node:internal/modules/cjs/loader:1340:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at requirePluginFile (<path>/node_modules/@expo/config-plugins/build/utils/plugin-resolver.js:214:12)
at resolveConfigPluginFunctionWithInfo (<path>/node_modules/@expo/config-plugins/build/utils/plugin-resolver.js:155:14)
```
I change the code to use `require`, however that degrades the DX since I can't import types and I lose the benefits of ts.
|
Can't install pynput package on pydroid3 |
|python| |
**EDIT**
After refactor my code, and be careful to use useState in thinking about next render, I've a new problem, my sub-menu flashes on mobile inspector on click even with preventDefault() method.
<hr>
_previous issue_ :
Info: *li* is one of main menu.
While I hover over the li, it works but from the moment I click on it, it breaks down.
i.e that all is reversed, when I leave my cursor from li, the sub-menu appears, and if I hover again, it disappears.
I use React.js, Next.js and TailWind.
*updated code*
```javascript
function MenuItems({title, link, hasSubMenu}) {
const [isHover, setHover] = useState(false);
const [isOpen, setOpen] = useState(false);
function toggleHoverState() {
setHover(!isHover);
handleDisplayOfSubNav();
}
function handleDisplayOfSubNav() {
if (!isHover && !isOpen) {
setOpen(true);
} else if (isHover && isOpen) {
setOpen(false);
}
}
const menuItemsClasses; // ... lots of css classes list
if (hasSubMenu) {
return (
<li
onPointerEnter={
(e) => {
toggleHoverState();
e.preventDefault();
}
}
onPointerLeave={
(e) => {
toggleHoverState();
e.preventDefault();
}
}
>
<h3 className={`${menuItemsClasses}`}>
{title}
// a svg
</h3>
// a svg
<ul className={`${isOpen ? "block" : "hidden"} md:absolute md:bg-primary md:border-secondary md:border-4 rounded-3xl -translate-y-2`} >
{
[...Array(hasSubMenu.length)].map((e, i) => (
<li key={i}>
<Link href={link} className={`${menuItemsClasses} text-sm ${hasSubMenu[i].hasSubMenu ? "underline" : "no-underline"}`}>
{hasSubMenu[i].title}
</Link>
</li>
))
}
</ul>
</li>
);
} else {
return (
<li>
<Link href={link} className={menuItemsClasses}>{title}</Link>
</li>
);
}
}
``` |
How to prevent flashes sub-menu on click on mobile with React? |
I have camel route definition as below:
from(source).routeId("source processor")
.filter(liabilityMessageFilter)
.log(LoggingLevel.INFO, LOGGER, "Some log")
.process("myMessageProcessor");
and I have a test to check route defininiton:
@Test
public void myTest() {
ModelCamelContext mcc = camelContext.adapt(ModelCamelContext.class);
final List<RouteDefinition> routeDefinitions = mcc.getRouteDefinitions();
assertThat(((LogDefinition) routeDefinitions.get(0).getOutputs().get(1)).getMessage(), is("some log"));
}
Problem is `routeDefinitions.get(0).getOutputs()` returns only filter object but not the rest. But if I change order of filter and log in route definition it works. I cannot reach rest of the route element with this given route definition above ? What is the reason for it and if I am doing something wrong ?
For ex: if I do not have filter, `routeDefinitions.get(0).getOutputs()` returns log and process elements. |
To delete variables in the current cmd instance, do this:
set http_proxy=
set https_proxy=
or (even better):
set "http_proxy="
set "https_proxy="
To delete variables for future cmd instances, do this:
setx http_proxy ""
setx https_proxy "" |
I've used to include bootstrap inside my `main.js` file via
```js
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.js'
```
When I needed actual JS functionality (a Dropdown) it didn't work. After playing around a bit I got it working with
```js
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap'
```
My Question: Why? Whats the difference between `bootstrap/dist/js/bootstrap.js` and `bootstrap`? Is it Vue specific? I mean `bootstrap/dist/css/bootstrap.css` seems to work just fine for the CSS?
(I'm still new to npm and stuff, so sorry if it's obvious.) |
import 'bootstrap/dist/js/bootstrap.js' vs import 'bootstrap' |
|vuejs3|bootstrap-5| |
<!-- language-all: sh -->
I suggest using a [delay-bind script block](https://stackoverflow.com/a/52807680/45375) with [`Move-Item`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/move-item)'s `-Destination` parameter, which allows you to determine the destination directory for each input file _dynamically_, based on the input file's properties (such as the name):
```
Get-ChildItem -File -Path $sourceDirectory |
Move-Item -Destination {
# Wildcard pattern that the destination dir. must match.
$destDirPattern =
'{0}\{1}*\Correspondence' -f $destination, $_.Name.Substring(0, 6)
# Look for a (the first) matching dir., and pass it out
# as the destination dir.
Get-ChildItem -ErrorAction Ignore -Directory $destDirPattern |
Select-Object -First 1
} -WhatIf
```
<sup>Note: The [**`-WhatIf`** common parameter](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#-whatif) in the command above **_previews_ the operation**. Remove `-WhatIf` and re-execute once you're sure the operation will do what you want.</sup>
Note:
* If no matching destination directory is found for a given input file, the inner `Get-ChildItem` call will produce no output, and you'll therefore get a non-terminating `Move-Item : Cannot evaluate parameter 'Destination' because its argument input did not produce any output.` error, and processing continues.
* Should more than one directory match the destination pattern, the first one returned by `Get-ChildItem` is used. |
# Issue
The issue here is that the `Link` component effects a navigation action *immediately* when it is clicked, and the passed `state` prop will include whatever the `data` value is ***at the time*** the link is clicked.
The `DetailsPage` also isn't accessing into the passed state reference the `data` property, it's only declaring a local variable named `data` and setting it to the value of `location.state`. `DetailsPage` would need to access `data.data.title` to get the passed information.
# Solution
You can prevent the default link action from happening and effect the navigation action manually later. Unfortunately because enqueued React state updates are processed asynchronously you also can't use the `data` state in the route state. What you *can* do however is to enqueue the state update alongside the imperative navigation action with the same value.
Example:
```javascript
import { Link, useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
const toggledItem = (e) => {
e.preventDefault(); // <-- prevent link navigation
let data = {};
switch(id) {
case 1:
data = softiesInfo;
break;
case 2:
data = palcoInfo;
break;
case 3:
default:
data = tlaxInfo;
break;
}
setData(data);
navigate( // <-- imperative navigation
"/DetailsPage",
{ state: { data } }
);
};
```
...
```jsx
<Link
to="/DetailsPage"
onClick={toggledItem}
className="primary-ff boxyButton"
>
{buttonText}
</Link>
```
```jsx
export default function DetailsPage() {
const location = useLocation();
const { data } = location.state ?? {};
return (
<div className="header-wrap">
<h1 className="primary-ff">{data.title}</h1>
<img src={data.logoImg} alt={data.altLogo} />
</div>
)
});
``` |
Not able to access route elements in test when using a camel filter |
|apache-camel|spring-camel| |
I would appreciate help on parallelism with RabbitMQ.
Given a large json file, let's say it has 1 million items, I want to go through it in parallel so that each item is passed to Rabbit using multithreading.
I read quite a few blogs and it seems that there is a problem with using one connection with one channel with multithreading and if I understood correctly it was recommended to add channels, in practice I didn't really understand how this was implemented in the code, I tried all kinds of things and nothing worked.
I would like to know if my desire is possible, or if I have to parse the file iteratively one after the other, and if it is possible if I can get help with the code?
Here I define the connection and the publish to rabbit function :
```
class RabbitMQClient:
def __init__(
self,
queues_connection_config: Dict[str, Any],
queue_name: str,
) -> None:
self.__logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")
self.__queue_name = queue_name
self.__exchange = queues_connection_config.get("exchange")
self._connection = Connection(
queues_connection_config.get("hostname"),
queues_connection_config.get("username"),
queues_connection_config.get("password"),
queues_connection_config.get("port"),
virtual_host=queues_connection_config.get("virtual_host"),
)
self.channel=self._connection.channel()
self.channel.confirm_deliveries()
def enqueue(self, queues_item: Dict[str, Any]) -> str:
message = Message.create(self.channel, json.dumps(queues_item))
message.publish(routing_key=self.__queue_name, exchange=self.__exchange, mandatory=True)
self.__logger.debug(f"Enqueued {message.correlation_id}")
return str(message.correlation_id)
```
Here I try to divide the task into multi threading without success:
```
for i in range(checkpoint, 10 + 1):
batch_data = [next(items) for _ in range(1000)]
try:
start_time = time.time()
futures = [
self.executor.submit(self.__queue_client.enqueue, item)
for item in batch_data
]
# Wait for all threads to complete
concurrent.futures.wait(futures)
```
|
How to publish messages to RabbitMQ by using Multi threading? |
If I read your requirements as:
*select any text node that is a* child *of `u` (i.e. not inside another element such as `desc` or `del`), but exclude text nodes that are between two `anchor` elements*
then I arrive at the following expression:
//u/text()[not(preceding-sibling::anchor and following-sibling::anchor)]
Applying it to the given input produces:
"
I want this but
**
I want this
"
which is different from the output you *say* you want, but nevertheless conforms to the stated requirements.
|
change it like this:
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<item>
<bitmap
android:gravity="center"
android:src="@drawable/logo" />
</item>
</layer-list> |
expo config plugin use import instead of require |
|react-native|expo| |
I'm encountering an issue during the compilation of my project using CMake. When attempting to build the project, I receive the following error message:
```
Copy error :
FAILED: CMakeFiles/TestOpencv.dir/main.c.obj
C:\PROGRA~1\MIB055~1\2022\COMMUN~1\VC\Tools\MSVC\1439~1.335\bin\Hostx64\x64\cl.exe /nologo -external:ID:\lilia\Documents\libs\opencv\build\include -external:W0 /DWIN32 /D_WINDOWS /Zi /Ob0 /Od /RTC1 -MDd /showIncludes /FoCMakeFiles\TestOpencv.dir\main.c.obj /FdCMakeFiles\TestOpencv.dir\ /FS -c C:\Users\lilia\CLionProjects\TestOpencv\main.c
D:\lilia\Documents\libs\opencv\build\include\opencv2/core.hpp(49): fatal error C1189: #error: core.hpp header must be compiled as C++
ninja: build stopped: subcommand failed.
```
I believe this error is related to the inclusion of the core.hpp header file from OpenCV, but I'm uncertain about the exact cause or how to resolve it. I'm using CLion as my development environment and CMake for project configuration.
In attempting to resolve the compilation issue I encountered with my project, I've taken the following steps:
- Dependency check: I verified that all necessary dependencies, including OpenCV, are correctly installed on my system.
- CMake configuration: I carefully reviewed my CMakeLists.txt file to ensure that OpenCV is properly included and configured.
- Compilation options: I checked the compilation options to ensure they're correctly set.
Despite these efforts, I haven't been able to resolve the error. I was expecting the project to compile successfully without encountering the mentioned error related to the core.hpp header file from OpenCV.
Could you please provide guidance on further troubleshooting steps or possible solutions? |
There are two options
1. install the driver using `chromedriver-autoinstaller`
install package `chromedriver-autoinstaller` `pip install chromedriver-autoinstaller`
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import chromedriver_autoinstaller
chromedriver_autoinstaller.install()
options = webdriver.ChromeOptions()
options.add_argument('--start-maximized')
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(service=Service(), options=options)
2. add the `chromedriver.exe` service path directly
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(service=Service("C:/Users/yourusername/.cache/selenium/chromedriver/win32/112.0.5615.49/chromedriver.exe"),options=options)
|
Vue 3.4.21
I have a form and when I add elements to it without using a custom component, validation works:
<div class="form-group element">
<input type="text" :name="name" class="form-control" placeholder=" "
required pattern="([\w]{2,})" />
<label :for='x.slug' class="form-control-placeholder">
Name:
</label>
<span class="error-msg">Please type at least 2 characters </span>
</div>
</div>
The error message appears as it's supposed to.
Now, I've created a custom component like so:
<template>
<div class="form-group element">
<input type="text" :name="name" class="form-control :required='required'>
<label :for='name' class="form-control-placeholder">
{{ name }}:
</label>
<span class="error-msg">{{ errorMsg }}</span>
</div>
</template>
<script setup>
import { toRefs } from 'vue'
const props = defineProps({
pattern: String,
errorMsg: String,
name: String,
required: Boolean,
})
const { pattern, name, errorMsg, required } = toRefs(props);
</script>
And I use it like this:
<CustomInput
:errorMsg="'Please write at least 2 characters'"
:required="true"
:name="'name'"
:pattern="'([\w]{2,})'"
/>
The error message appears even when I meet the criteria (typing at least 2 characters)
How do I make validation function correctly when passing in props to a custom component as opposed to hard coding them on the page?
Thanks
|
Python Protocol incompatible warning |
|python|python-typing| |
I have the following JSON returning from a Java service
{"Test":{
"value": 1,
"message": "This is a test"
}}
I have the following C# class
class Test {
public int value { get; set; }
public String message { get; set; }
}
However, because the root tag "Test" is returned I cannot directly deserialize this with
Test deserializedTest = JsonConvert.DeserializeObject<Test>(jsonString);
I find I have to wrap the the Test class inside another class for this to work. Is there an easy way to avoid this other than
JToken root = JObject.Parse(jsonString);
JToken testToken = root["Test"];
Test deserializedTest = JsonConvert.DeserializeObject<Test>(testToken.toString());
Most of the services I'm calling can return an Exception object as well. I figured I'd read the "root" tag of the JSON to determine how to deserialize the object.
How do I get the first root tag and/or is there a better, more elegant method to handle exceptions from a service? |
|c#|json|serialization|json.net| |
I had the same problem and really wanted to get rid of this 'container'. I found this solution, though you need to use an extra string to find the root object:
// Container I wanted to discard
public class TrackProfileResponse
{
[JsonProperty("response")]
public Response Response { get; set; }
}
// Code for discarding it
var jObject = JObject.Parse(s);
var jToken = jObject["response"];
var response = jToken.ToObject<Response>();
|
I have a domain dataclass:
from pydantic import BaseModel
from pydantic.dataclasses import dataclass
@dataclass(frozen=False)
class ValueObject:
"""
Base class for value objects
"""
@dataclass(frozen=False)
class Rss(ValueObject):
index: int
title: str
titleDetail: str
and then I have a service called "RssFeedReader"
"""Services module."""
from typing import Any
from dataclasses import dataclass,field
import feedparser
from pydantic import BaseModel
from DomainModels import Rss
'''force Rss to be a DM & not a module'''
class Rss(BaseModel):
def __next__(self):
yield self
@dataclass(kw_only=True)
class RssFeedReader:
krssResult: list[Rss] = field(default_factory=list)
#public commands
async def Read(self, url:str):
feed = feedparser.parse(url)["entries"]
kRss = Rss
for i in range(len(feed)):
kRss.index = i
kRss.title = feed[i]["title"]
kRss.titleDetail =feed[i]["title_detail"]
self.AddResult(i,kRss)
return self.krssResult
def AddResult(self, i, rss:Rss):
print(i)
self.krssResult.append(rss)
now for some reason even tho it's iterating over the items and print(i) is stating the index, when I can this all 50 items are a repeat of the last index, its whipped out the first 49 values with a duplicate of the last result,
I have also tried to use insert(i,rss) but that gives me the same issue.
I am calling this in a flask app, and using DI
main.py
from flask import Flask
from flask_bootstrap import Bootstrap
from .wiring import init_app
from .Container import Container
from . import views
def create_app() -> Flask:
container = Container()
app = Flask("rssfeed")
app.container = container
init_app()
app.add_url_rule("/", "index", views.index)
bootstrap = Bootstrap()
bootstrap.init_app(app)
return app
views.py
""" app moudle """
from flask import Flask
from dependency_injector.wiring import inject, Provide
from .Container import Container
from .RssFeedService import RssFeedReader
@inject
async def index(rss_feed_service: RssFeedReader = Provide[Container.rss_feed_service]):
read = await rss_feed_service.Read(url="https://kotaku.com/rss")
return "<h1>News system</h1>" + str(read)
container.py
from dependency_injector import containers, providers
from . import RssFeedService
class Container(containers.DeclarativeContainer):
wiring_config = containers.WiringConfiguration(modules=[".views"])
rss_feed_service = providers.Factory(
RssFeedService.RssFeedReader
)
If I add the title to a black array that travels to the front end fine, its only if I bind to the "krssResult: list[Rss]" it gives me the issue |
I've ran into an odd issue in Playwright (an Automation test library) and I have a basic function like this in my page object classes:
```
async open() {
await super.open("some/url/here");
}
```
(The base class is basically just a:
```
async open(path: string) {
await this.page.goto(path);
}
```
That being said I was mistakenly calling just `someInstance.open()` instead of `await someInstance.open()`
Adding the `await` did fix the issue I was having. However it made me question whether I really needed the `await` within the test if I already have an `await` on the only command in the function?
So is an `await` needed in both places?
Thanks! |
Do I need to use await on a function that itself uses await? |
I’m working on a USB sound interface, using a STM32F7 and an external DAC chip offering 8 stereo output channels.
Most of the DAC are offering multiple serial data inputs ports. For example, the Analog Device ADAU1966A is offering 8x data lines inputs. That’s great to lower the clock speed.
On the STM32F7, each SAI drivers has two blocs, SAI_A and SAI_B, so two serial data outputs that I can use to transfert the audio data to the DAC.
Image of the envisaged communication:
[![enter image description here][2]][2]
I have 2 questions:
- Am I right to suppose that I can use SD_A and SD_B in parallel to send audio data to the DAC? (I can configure this DAC to use only DSDATA1 and DSDATA2 to control OUT1 … OUT16)
- It’s a shame that I can’t have more serial data outputs on the STM32. A lot of high end DACs have multiple serial data inputs, and can work at 32-bit and 192kHz and more. Maybe I miss something? Do you have an idea on how to get the best out of this SAI transmission?
Thanks a lot, have a nice day!
Jean
[1]: https://i.stack.imgur.com/Qmmr9.png
[2]: https://i.stack.imgur.com/snKMZ.png |
I'm working on a React Native app that utilizes Vision Camera for capturing photos, and I aim to enable users to select text from these photos, akin to the functionality found on iPhones. Thus, I prefer not to employ an image processor like Firebase ML Kit; it's a preliminary step.
[![Here's what I mean:][1]][1]
[1]: https://i.stack.imgur.com/XXt6m.jpg |
How to perform text selection inside images in React Native |
|react-native|react-native-firebase| |
I use a workspace into my app
"workspaces": [
"firstapp/web",
"secondapp"
]
Into second app, into package.json I get into dependencies:
"anotherapp": "https://github.com/me/anotherapp.git",
From root I run `yarn workspaces foreach -Apt install` everething is ok
I run `yarn workspaces foreach -Apt build` but get `Cannot find module 'anotherapp' or its corresponding type declarations.`
I get this both in CI and during dev (on local)
I don't know what is wrong
If I import my anotherapp as `"anotherapp": "../anotherapp"` on local it's working.
So I don't know how to fix it. |
unable to install npm package from github |
|reactjs|npm|npm-install|yarnpkg|yarn-workspaces| |
Form Validation not working in custom component Vue |
|vue.js| |
I have a class called Task in which I have properties like Date, Id, priority and Name. I have a list where I store objects of this class. The problem is that when I do the sorting and then display it in my Listview (I am working in WPF framework coz it is a part of the assigment) all the tasks get renamed tothe same thing (TODO-list.task.Task) from their original name and I have no idea if the sorting actually worked.
I use this to sort the list:
```
List\<Task\> sort_by_date = tasks.OrderBy(x =\> x.Date).ToList();
```
And then write it out to list view like this:
```
MainWindow.withDate.Item.Clear();
MainWindow.withDate.ItemsSource = sort_by_date;
```
|
Sorting a List by its property renames all the objects in the List |
|c#|wpf|list|sorting|listview| |
null |
I am trying to run the momentum program for Trading Evolved (Chapter 12 – Momentum/Momentum Model.ipynb), contained below.
I am having a terrible time with the dates.
Running the code as it was originally provided gives me the error
AttributeError: 'UTC' object has no attribute 'key'
After a large amount of google searching I was able to get around this error for a different program (First Zipleine Backtest.ipynb) by changing
start_date = datetime(1996, 1, 1, tzinfo=pytz.UTC)
end_date = datetime(2017, 12, 31, tzinfo=pytz.UTC)
to
start_date=pd.to_datetime('1996-01-01')
end_date =pd.to_datetime('2017-12-31')
However, when I make this change to the Momentum Model program changing
start = datetime(1997, 1, 1, 8, 15, 12, 0, pytz.UTC)
end = datetime(2017, 12, 31, 8, 15, 12, 0, pytz.UTC)
which initially produces the error
NameError: name 'datetime' is not defined
So I change the format of the start and end to
start=pd.to_datetime('1996-01-01')
end =pd.to_datetime('2017-12-31')
I get the error
TypeError: Invalid comparison between dtype=datetime64[ns] and Timestamp
After searching the program for references to ‘start’, I came across
date_rule=date_rules.month_start(),
Now, I know that dates in python can take a couple of different forms and after I made the change, the form of start is
type(start)
Out[21]: pandas._libs.tslibs.timestamps.Timestamp
But I don’t know the format of the date in
date_rule=date_rules.month_start(),
So I don’t know how to make the comparison legitimate, if this indeed the source of the error.
I am trying to develop these programs into teaching material at the university at which I am employed but can’t do that if I can’t get passed the sticking point of the date formats. I would really, really, appreciate some help. Thanks.
--John Sparks
Tried to run the momentum program as is provided in the Trading Evolved website (https://www.dropbox.com/s/tj85sufbsi820ya/Trading%20Evolved.zip?dl=0) under Chapter 12 Momentum / Momentum Model.ipynb
Was expecting the program to run but it produced an error when using the dates.
I tried to change the form of the dates but just got a different error.
I tried to paste in the program here, but stack overflow won't accept the indenting and says that the submission has too many characters.
Run the program for momentum from the Tading Evolved book.
Tried changing the format of the dates but no joy. |
Use the `JsonMerge` [intrinsic function](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html#asl-intrsc-func-json-manipulate) to "spread" `obj1`'s keys.
```yaml
Input:
payload.$: "States.JsonMerge($.obj1, $, false)"
```
Given your input, the task receives the 3 desired keys in the right shape, but keeps a redundant `obj1` key:
```json
"payload": {
"a": 1, ✅
"b": "foo", ✅
"obj1": {"a": 1, "b": "foo"},
"obj2": {"c": 2, "d": "bar"} ✅
}
``` |
null |
i have a question regarding fill null values, is it possible to backfill data from other columns as in pandas?
Working pandas example on how to backfill data :
```python
df.loc[:, ['A', 'B', 'C']] = df[['A', 'B', 'C']].fillna(
value={
'A': df['D'],
'B': df['D'],
'C': df['D'],
}
)
```
Polars example as i tried to backfill data from column D to column A if the value is null, but it's not working:
df = pl.DataFrame(
{"date": ["2020-01-01 00:00:00", "2020-01-07 00:00:00", "2020-01-14 00:00:00"],
"A": [3, 4, 7],
"B": [3, 4, 5],
"C": [0, 1, 2],
"D": [1, 2, 5]})
df = df.with_column(pl.col("date").str.strptime(pl.Datetime, "%Y-%m-%d %H:%M:%S"))
date_range = df.select(pl.arange(df["date"][0], df["date"]
[-1] + 1, step=1000*60*60*24).cast(pl.Datetime).alias("date"))
df = (date_range.join(df, on="date", how="left"))
df['D'] = df['D'].fill_null("forward")
print(df)
df[:, ['A']] = df[['A']].fill_null({
'A': df['D']
}
)
print(df)
Kind regards,
Tom |
```js
import React from 'react';
import logo from './img/logo1.png';
import { Link, BrowserRouter as Router } from 'react-router-dom'; // Import BrowserRouter
export default function Navbar() {
return (
<Router> {/* Wrap your Link components inside Router */}
<div>
{/* theme switch and login signup */}
<div className="border-2 border-blue-600 h-full">
<Link to="/">Home</Link>
</div>
</div>
</Router> {/* Close Router */}
);
}
``` |
![image showing output from below code][1]
homes_by_state = df_south.groupby(["state"])["property_type"].value_counts()
I want to output only "state" and total number of "property_type"
[1]: https://i.stack.imgur.com/DwhmA.png |
{"OriginalQuestionIds":[8028957],"Voters":[{"Id":1007220,"DisplayName":"aynber","BindingReason":{"GoldTagBadge":"php"}}]} |
I'm taking an OOP approach of creating a login module. I've self initialised a list and a dictionary which both already contain admin and password within it.
Within that class I have created a login function which requests input from a user.
Based on the input I am attempting to write a code to read the dictionary and to return 'logged in' as True if the inputs match of that in the dictionary.
I've been attempting this issue in multiples ways; for loop, calling for the dict.items but its been the same outputs, that the user does not exits
class LoginSection:
def __init__(self):
self.user_data = ['admin','password']
self.username_password = {admin:password}
def login(self):
'''
Login interface
'''
logged_in = False
while not logged_in:
print("\nLOGIN")
curr_user = input("Username: ")
curr_pass = input("Password: ")
if curr_user not in self.username_password.keys():
print("User does not exist")
continue
if curr_pass != self.username_password[curr_user]:
print("incorrect password")
continue
print("Login Successful!")
logged_in = True |
I have a Canvas app connected to an on-premise SQL Server gateway. The connection is successful, and records can be viewed using the data table preview.
I used a button underneath the data table to navigate to an "Edit" screen that will edit the record selected on the data table (DT). The form preloads with the DT data successfully and everything appears to work correctly. However, when using a button with the `SubmitForm(form)` function I received the error
> Network error when using patch function: the specified record was not found.
With no success, I tried changing the `SubmitForm(FormName)` function to Patch instead.
Example trying to edit a single field using patch:
```
Patch(OnPremiseSQLDB,dt_DataTable.Selected,
{Notes: DataCardValue46.Text});
```
Same error.
I have spent well over 2 hours trying to figure out this issue and have been unsuccessful.
I turned on monitoring and received the following logs:
1. Network - patchRow - Error - Not Found
```
{
"status": 404,
"duration": 74.39,
"dataSource": "OnPremiseSQLDB",
"responseSize": 54,
"controlName": "btn_FormSave",
"propertyName": "OnSelect",
"nodeId": 7,
"formulaData": {
"script": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})",
"spanStart": 0,
"spanEnd": 74
},
"data": {
"context": {
"entityName": "btn_FormSave",
"propertyName": "OnSelect",
"id": 13538,
"nodeId": 7,
"diagnosticContext": {
"span": {
"start": 0,
"end": 74
},
"dataOperation": {
"protocol": "cdp",
"operation": "patchRow",
"apiId": "/providers/microsoft.powerapps/apis/shared_sql",
"dataSource": "UT_IVCustom",
"table": "[dbo].[UT_IVCustom]",
"operationName": "CdpConnector.patchRowAsync"
},
"formula": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})"
}
},
```
2. Function - Patch - Error -
```
{
"status": null,
"duration": null,
"dataSource": null,
"responseSize": null,
"controlName": "btn_UT_IVCustomSave",
"propertyName": "OnSelect",
"nodeId": 7,
"formulaData": {
"script": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})",
"spanStart": 0,
"spanEnd": 74
},
"data": {
"errorMessage": "Network error when using Patch function: The specified record was not found.",
"raiseToastNotification": false,
"wasReported": false,
"functionName": "Patch",
"context": {
"entityName": "btn_FormSavee",
"propertyName": "OnSelect",
"id": 13538,
"nodeId": 7,
"diagnosticContext": {
"span": {
"start": 0,
"end": 74
},
"formula": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})"
}
},
"info": "Network error when using Patch function: The specified record was not found."
}
}
```
Any help is much appreciated thank you. |
null |
I have a Canvas app connected to an on-premise SQL Server gateway. The connection is successful, and records can be viewed using the data table preview.
I used a button underneath the data table to navigate to an "Edit" screen that will edit the record selected on the data table (DT). The form preloads with the DT data successfully and everything appears to work correctly. However, when using a button with the `SubmitForm(form)` function I received the error
> Network error when using patch function: the specified record was not found.
With no success, I tried changing the `SubmitForm(FormName)` function to Patch instead.
Example trying to edit a single field using patch:
```
Patch(OnPremiseSQLDB,dt_DataTable.Selected,
{Notes: DataCardValue46.Text});
```
Same error.
I have spent well over 2 hours trying to figure out this issue and have been unsuccessful.
I turned on monitoring and received the following logs:
1. Network - patchRow - Error - Not Found
```
{
"status": 404,
"duration": 74.39,
"dataSource": "OnPremiseSQLDB",
"responseSize": 54,
"controlName": "btn_FormSave",
"propertyName": "OnSelect",
"nodeId": 7,
"formulaData": {
"script": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})",
"spanStart": 0,
"spanEnd": 74
},
"data": {
"context": {
"entityName": "btn_FormSave",
"propertyName": "OnSelect",
"id": 13538,
"nodeId": 7,
"diagnosticContext": {
"span": {
"start": 0,
"end": 74
},
"dataOperation": {
"protocol": "cdp",
"operation": "patchRow",
"apiId": "/providers/microsoft.powerapps/apis/shared_sql",
"dataSource": "UT_IVCustom",
"table": "[dbo].[UT_IVCustom]",
"operationName": "CdpConnector.patchRowAsync"
},
"formula": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})"
}
},
```
2. Function - Patch - Error -
```
{
"status": null,
"duration": null,
"dataSource": null,
"responseSize": null,
"controlName": "btn_UT_IVCustomSave",
"propertyName": "OnSelect",
"nodeId": 7,
"formulaData": {
"script": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})",
"spanStart": 0,
"spanEnd": 74
},
"data": {
"errorMessage": "Network error when using Patch function: The specified record was not found.",
"raiseToastNotification": false,
"wasReported": false,
"functionName": "Patch",
"context": {
"entityName": "btn_FormSavee",
"propertyName": "OnSelect",
"id": 13538,
"nodeId": 7,
"diagnosticContext": {
"span": {
"start": 0,
"end": 74
},
"formula": "Patch(OnPremiseSQLDB,dt_DataTable.Selected,\r\n{Notes: DataCardValue46.Text})"
}
},
"info": "Network error when using Patch function: The specified record was not found."
}
}
``` |
Python Zipline Date Trouble |
|python|trading|zipline| |
null |
I am trying to send a music file from my app to WhatsApp using Apple Share sheet which is UIActivityViewController.
I am able to share the music file but the problem is I cannot add metadata to this. I mean I can share audio with url and it can be open and listen in WhatsApp but I cannot figure out how to add metadata to this url, I want to add title, description and image to my url as Apple Music do, then when shared in WhatsApp you can see some data with the file url, not only the audio file. Is It possible ?
When I open the share sheet with my code I can set metadata image, title and description in the header as you can see in the following image :
https://i.stack.imgur.com/Ymzec.jpg
This following image is when I share an audio music file from my app to WhatsApp, you can see I want to share metadata too but I cannot add these datas :
https://i.stack.imgur.com/3qHK9.jpg
The following image it is almost what I want, it is shared from Apple Music app to WhatsApp, you can see the metadata (image, title and some description text) :
https://i.stack.imgur.com/WuVus.jpg
Is it possible to do the same thing as the third image in my app please ?
Here is my current code :
```
func openShareSheet(shareItem: ShareFile, completion: @escaping (String?) -> Void) {
var item: ShareItem = ShareItem(title: shareItem.title, artist: shareItem.artist, url: shareItem.url, coverImage: UIImage(named: "defaultImage"))
getImage(shareItem.coverImage) { image in
if let image = image {
item.coverImage = image
let itemToShare: [Any] = [
item
]
let activityViewController = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.navigationController?.navigationBar
activityViewController.excludedActivityTypes = [UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.assignToContact]
activityViewController.completionWithItemsHandler = { (activityType, completed: Bool, returnedItems: [Any]?, error: Error?) in
if completed {
doSomething()
}
self.deleteFile(filePath: shareItem.url)
completion(nil)
}
self.present(activityViewController, animated: true, completion: nil)
} else {
completion("Image error")
}
}
}
import LinkPresentation
class ShareFile {
var title: String
var artist: String
var url: URL
var coverImage: String
init(title: String, artist: String, url: URL, coverImage: String) {
self.title = title
self.artist = artist
self.url = url
self.coverImage = coverImage
}
}
class ShareItem: UIActivityItemProvider {
var title: String
var artist: String
var url: URL
var coverImage: UIImage?
init(title: String, artist: String, url: URL, coverImage: UIImage?) {
self.title = title
self.artist = artist
self.url = url
self.coverImage = coverImage
super.init(placeholderItem: "")
}
override var item: Any {
return url
}
override func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return url
}
override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return url
}
override func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return title
}
@available(iOS 13.0, *)
override func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
let metadata: LPLinkMetadata = LPLinkMetadata()
metadata.title = title
metadata.originalURL = URL(fileURLWithPath: artist)
metadata.url = url
metadata.imageProvider = NSItemProvider(object: coverImage ?? UIImage())
return metadata
}
}
``` |
If you try to implement a `ListStyle`, you can let Xcode add stubs for protocol conformance. You will then see, that the required functions all start with `_`. This is a clue, that the protocol `ListStyle` is not intended to be used for custom implementations.
However, you might be able to achieve what you're after by creating a wrapper for a `List` that accepts a `ViewBuilder` as parameter. Something like:
```swift
struct CustomList<Content>: View where Content: View {
@ViewBuilder let content: () -> Content
var body: some View {
List {
content()
.listRowBackground(
Color.yellow
.clipShape(RoundedRectangle(cornerRadius: 10))
)
}
.listStyle(.plain)
.listRowSpacing(10)
.foregroundStyle(.pink)
.padding()
.background(.gray)
}
}
struct ContentView: View {
var body: some View {
CustomList {
ForEach(0..<100, id: \.self) { item in
Text("Item \(item)")
}
}
}
}
```
 |
I am currently developing a T5 model (encoder-decoder architecture) from scratch for educational purposes. While working on this project, I've encountered some confusion regarding the pre-training objective, specifically the *denoising objective*. I would like to clarify my understanding and have some questions about the process.
Given the sentence:
> Thank you for inviting me to your party last week.
Based on my understanding, during the pre-training phase with a denoising objective, the model works as follows:
- **Encoder input**: `Thank you <X> me to your party <Y> week`
- **Decoder input**: `<X> for inviting <Y> last`
- **Decoder labels (true labels)**: `for inviting <Y> last <Z>`
Here are my questions:
1. Is my interpretation of how the encoder input, decoder input, and decoder labels are constructed correct?
2. In this setup, the model is expected to predict sentinel tokens (e.g., `<X>`, `<Y>`). Could this potentially introduce confusion for the model, for example, it may take the idea that it is possible for the word "last" to come after the token <Y>? Or does the model naturally learn to interpret these situations correctly?
---
**Accordingly to the paper:**
[![denoising objective][1]][1]
> we process the sentence `Thank you for inviting me to your party last week.` The words `for`, `inviting` and `last` are randomly chosen for corruption. Each consecutive span of corrupted tokens is replaced by a sentinel token (shown as `<X>` and `<Y>`) that is unique over the example. Since `for` and `inviting` occur consecutively, they are replaced by a single sentinel `<X>`. The output sequence then consists of the dropped-out spans, delimited by the sentinel tokens used to replace them in the input plus a final sentinel token `<Z>`.
[1]: https://i.stack.imgur.com/QYUco.png |
Clarification on T5 Model Pre-training Objective and Denoising Process |
The official solution to retrieve updated translations:
let languageLocale = 'en'; //Any language locale like fr, es, ja, etc.
this.translateService.reloadLang(languageLocale).subscribe((response)=>{
this.translateService.use(languageLocale);
});
|
I am needing to return all of the content within the body tags of an HTML document, including any subsequent HTML tags, etc. I'm curious to know what the best way to go about this is. I had a working solution with the Gokogiri package, however I am trying to stay away from any packages that depend on C libraries. Is there a way to accomplish this with the go standard library? or with a package that is 100% Go?
Since posting my original question I have attempted to use the following packages that have yielded no resolution. (Neither of which seem to return subsequent children or nested tags from inside the body. For example:
```html
<!DOCTYPE html>
<html>
<head>
<title>
Title of the document
</title>
</head>
<body>
body content
<p>more content</p>
</body>
</html>
```
will return body content, ignoring the subsequent `<p>` tags and the text they wrap):
- pkg/encoding/xml/ (standard library xml package)
- golang.org/x/net/html
The overall goal would be to obtain a string or content that would look like:
```html
<body>
body content
<p>more content</p>
</body>
``` |
I have these 2 tables,
[Table 1 and Table 2](https://i.stack.imgur.com/at3CP.png)
Project, area, cost category and total cost
i was hoping to have a a cost per sqm for each project and per zone. [Desired output](https://i.stack.imgur.com/7r0O4.png)
I tried to have this measure
```
cost per sqm =
DIVIDE(
SUM('Table 2'[total cost]),
LOOKUPVALUE('Table 1'[Area],'Table 1'[Project],'Table 2'[Project])
)
```
the idea is to sum the total cost / area for cost per sqm each project
and
sum of the total cost / total area for each zone
I tried to put SUM() on lookupvalue too but it doesnt work. |
DIVIDE function with LOOKUPVALUE on measure |
|powerbi|dax| |
null |
```
function App() {
const [userData, setData] = useState([]);
const getData = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
setData(data);
console.log(userData);
};
return (
<>
<button onClick={getData}>get data</button>
<div>
{userData?.map((user) => {
return (
<p key={user.id}>
{user.name} {user.email}
</p>
);
})}
</div>
</>
);
}
export default App;
```
I tried to fetch the data and then store it in my state variable `userData`. Upon console logging `userData`, it should show the data fetched as per my knowledge. I know that `await` stops further execution until the promise returned by the Fetch Api is either resolved or rejected. In that case, `userData` should be updated using `setData`. But why is `userData` still an empty array upon logging, even after awaiting the result? |