instruction stringlengths 0 30k ⌀ |
|---|
I had a slightly different take on this
=IF(B1="","skipped",IF(B1=INDEX(A:A,COUNT(B$1:B1)),"match","difference"))
but I realise this will break after the blanks in column A and something more would be required like an mmult.
[![enter image description here][1]][1]
___
This was my thinking if the pattern continues like this, to use Mmult to find the next value in column A to compare:
=IF(B1="","skipped",IF(B1=INDEX(A:A,MATCH(COUNT(B$1:B1),
MMULT(IF(COLUMN($A$1:$J$1)<=ROW($A$1:$A$10),1,0),SIGN(A$1:A$10)),0)),
"match","difference"))
[![enter image description here][2]][2]
___
In a further test, my result (column E) would be at variance with @Scott Craner's (Column F) because I am comparing 8 against 7 and 9 against 8:
[![enter image description here][3]][3]
___
I you were able to set up a helper column starting from (say) C1 which counted the number of cells in column A containing a number up to the corresponding row, then you could use a much simpler formula which would work better with larger amounts of data:
=IF(B1="","skipped",IF(B1=INDEX(A:A,MATCH(COUNT(B$1:B1),
C$1:C$10,0)),"match","difference"))
[1]: https://i.stack.imgur.com/ziRLL.png
[2]: https://i.stack.imgur.com/bgW0g.png
[3]: https://i.stack.imgur.com/wo5Xi.png |
I am using an api which works but I am having trouble with the location header.
The api document states - If a 201 response is returned it means successful and the location of the newly created data in the http response 'location' header.
So I get the 201 response but no data. I assume the data is in the location header how to get that data.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch); |
Status code 201 http response 'location' header with curl php |
|php|php-curl| |
Using `querySelectorAll` =>
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const dialog = document.querySelector("dialog");
const showButton = document.querySelectorAll("dialog + button");
const closeButton = document.querySelectorAll("dialog button");
// "Show the dialog" button opens the dialog modally
showButton.forEach(k=> k.addEventListener("click", () => {
dialog.showModal();
}));
// "Close" button closes the dialog
closeButton.forEach(l=>l.addEventListener("click", () => {
dialog.close();
}));
<!-- language: lang-html -->
<dialog>
<img src="https://www.w3schools.com/html/img_girl.jpg" height="600">
<button autofocus>Close</button>
</dialog>
<button class="btn">
<img src="https://www.w3schools.com/html/img_girl.jpg" height="200" width="200">
</button>
<dialog>
<img src="https://www.w3schools.com/html/pic_trulli.jpg" height="600">
<button autofocus>Close</button>
</dialog>
<button class="btn">
<img src="https://www.w3schools.com/html/pic_trulli.jpg" height="200" width="200">
</button>
<!-- end snippet -->
|
null |
je veux créer une class BottleOfWater () et une fonction def __init__(self, contenance, couleur, matiere, liquid) :
puis afficher le contenu de la bouteille : bouteille = BottleOfWater (30, "green", "glass", "water")
class BottleOfWater () :
def __init__(self, contenance, couleur, matiere, liquid) :
self.contenance = contenance
self.couleur = couleur
self.matiere = matiere
self.liquid = liquid
for i in BottleOfWater () :
bouteille = BottleOfWater (30, "green", "glass", "water")
type (bouteille)
print (bouteille) |
class BottleofWater () : def __int__(self, contenance, couleur, matiere) : |
|python| |
null |
There is a task and there is no way to contact the customer.
the task is:
"You need to download the page https://nameOfTheSide through a browser or program (the site name was removed just in case) and in the saved copy change the part of this page under the logo, starting with the element with the “collection-title” class according to the design from Figma. Price block and everything below it, as well as the products on the page, do not need to be changed."
The problem now is that when you download the site, the data is already compiled, but it’s a little difficult to work with and I don’t have access to the site structure and the customer also didn’t put the link to gid.
How can I work with that? Are there any kind of ways to download pages with their structure? Is it ok that taksk is given in that way?
I am still new to this area and therefore maybe I don’t understand something, so please tell me. |
I am building an app within an application called Rhino where it has a button to call this method.
```C#
public void AttachPopupToViewportWindow()
{
_originalBound = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Bounds;
try
{
_formWindow = new SW.Win32Window(NativeHandle);
General._viewportWindow.AddControl(_formWindow);
}
catch (System.ComponentModel.Win32Exception ex)
{
}
}
```
When the method is called repeatedly in a very short time, the NativeHandle cannot be read anymore and it throws an Unhandled Exception.
[![enter image description here][1]][1]
The NativeHandle represents a IntPtr address to the WPF control.
I tried different ways of bypassing this exception. They all failed to work. Why hasn't the try-catch block catch the exception?
[1]: https://i.stack.imgur.com/LXBgx.png |
Try Catch exception is not catching the unhandled exception |
|c#|wpf|eto| |
I ran the deep learning for regression, it is a multimodal model with two loss functions. the mse and mae are acceptable, but the r2 is so horrible. any idea can explain it? what should I check? Thanks!!!!!
this is my code.
def r_squared(y_true, y_pred):
SS_res = K.sum(K.square(y_true - y_pred))
SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
return 1 - SS_res/(SS_tot + K.epsilon())
optimizer1 = keras.optimizers.Adam(1e-5, clipnorm=0.3, epsilon=1e-4)
model.compile(optimizer=optimizer1, loss=losses1, loss_weights=loss_weights1, metrics=['mse',r_squared,'mae']) |
`h2o.predict` returns an "H2OFrame". That is not expected as almost all predict methods return a data.frame. You transform the input data to a H2OFrame, but you also need to transform the output to a data.frame:
```
dnn_pred <- function(model, data, ...) {
predict(model, newdata=as.h2o(data), ...) |> as.data.frame()
}
p <- predict(logo, model=dl_model, fun=dnn_pred)
plot(p, nr=1, mar=c(1,2,1,4))
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/im7jc.png |
Assuming no date comes before Jan 1, 1970 (standard epoch time). This should suffice.
The code below basically counts up the number of seconds from 1/1/1970 at midnight accounting for leap years as it goes.
Below assumes a basic understanding that:
* Leap years have 366 days. Non leap-years have 365 days
* Leap years usually occur on years divisible by 4, but not on years divisible by 100 unless also divisible by 400 (the year 2000 is a leap year, but the year 2100 will not).
* That the `DateTime` struct will never have negative numbers, months less than 1 or greater than 12. Hours are assumed to be between 0-23 (military time).
* Months are assumed to be numbered between 1-12
```
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
struct DateTime {
int day, month, year, hour, minute;
};
const int SECONDS_IN_DAY = 86400;
int isLeapYear(int year) {
if (year % 4) return 0;
if (year % 400 == 0) return 1;
if (year % 100 == 0) return 0;
return 1;
}
int64_t seconds_since_epoch(const struct DateTime* dt) {
size_t days_in_month[13] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 };
int year = 1970;
int month = 1;
int day = 1;
int64_t total = 0;
while (year < dt->year) {
if (isLeapYear(year)) {
total += 366 * SECONDS_IN_DAY;
}
else {
total += 365 * SECONDS_IN_DAY;
}
year++;
}
if (isLeapYear(year)) {
days_in_month[2] = 29;
}
while (month < dt->month) {
total += days_in_month[month] * SECONDS_IN_DAY;
month++;
}
total += (dt->day - day) * SECONDS_IN_DAY;
total += 60 * 60 * dt->hour;
total += 60 * dt->minute;
return total;
}
// Function to calculate time difference
int calculate_time_difference(char date_in[], char time_in[], char date_out[], char time_out[]) {
struct DateTime dt1, dt2;
sscanf(date_in, "%d-%d-%d", &dt1.day, &dt1.month, &dt1.year);
sscanf(time_in, "%d:%d", &dt1.hour, &dt1.minute);
sscanf(date_out, "%d-%d-%d", &dt2.day, &dt2.month, &dt2.year);
sscanf(time_out, "%d:%d", &dt2.hour, &dt2.minute);
// Convert date and time to seconds since epoch
int64_t seconds1 = seconds_since_epoch(&dt1);
int64_t seconds2 = seconds_since_epoch(&dt2);
auto difference_in_seconds = abs(seconds1 - seconds2);
int difference_in_minutes = difference_in_seconds / 60;
return difference_in_minutes;
}
int main() {
int time_diff = calculate_time_difference("01-01-2024", "19:05", "02-01-2024", "9:05");
printf("Time difference->%i\n", time_diff);
return 0;
}
``` |
`<NuxtLink>` is just a router link. You will not be able to pass data through it for the next page.
But you can save, for example, in some `store` or `localStorage` this data after `@click` on `<NuxtLink>`, and process it on the next view. |
Inside your Canvas game object, create a Panel that will be the area in with the floating joystick can be spawn. Bellow the Panel add your Button. Now create a global `TouchInputManager` component/script which will detect which UI element has been touched by performing a raycast when the user touches the screen. You can attach it to your Canvas GO.
```
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.EnhancedTouch;
using ETouch = UnityEngine.InputSystem.EnhancedTouch;
public class TouchInputManager : MonoBehaviour
{
private GraphicRaycaster graphicRaycaster;
private PointerEventData pointerEvtData = new(null);
private List<RaycastResult> raycastResults = new();
private void Awake()
{
graphicRaycaster = GetComponent<GraphicRaycaster>();
}
private void HandleFingerDown(Finger finger)
{
pointerEvtData.position = finger.screenPosition;
raycastResults.Clear();
// Perform a raycast to find the UI element touched by the finger
graphicRaycaster.Raycast(pointerEvtData, raycastResults);
if (raycastResults.Count > 0)
{
var gameObj = raycastResults[0].gameObject;
// Notify the UI element about the touch
gameObj.SendMessage("OnFingerDown", finger, SendMessageOptions.DontRequireReceiver);
}
}
private void OnEnable()
{
EnhancedTouchSupport.Enable();
ETouch.Touch.onFingerDown += HandleFingerDown;
ETouch.Touch.onFingerUp += HandleFingerUp;
ETouch.Touch.onFingerMove += HandleFingerMove;
}
private void OnDisable()
{
EnhancedTouchSupport.Disable();
ETouch.Touch.onFingerDown -= HandleFingerDown;
ETouch.Touch.onFingerUp -= HandleFingerUp;
ETouch.Touch.onFingerMove -= HandleFingerMove;
}
// Other methods ... //
}
```
If you're using the new `EnhancedTouch` API, you need to perform a raycast by yourself (from one global component/script) to check which UI element has been touched, or you could take a silly approach and register a touch handler on every UI element that checks if the specific UI element has been touched.
We're using `GraphicRaycaster` since it registers hits with game objects that have a `Graphic` component (i.e. UI elements). |
# **This is my Schema-**
```
import mongoose from 'mongoose';
// Define the schema based on the ProductType interface
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
category: {
type: String,
},
image: {
type: String,
},
sku: {
type: String,
},
stock: {
type: Number,
},
price: {
type: String,
},
status: {
type: String,
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
});
// Create the Mongoose model
const Product =
mongoose.models.products || mongoose.model('products', productSchema);
export default Product;
```
# **and this is my api code to Update and Fetch data using product id**
```
import { NextResponse } from 'next/server';
import connectDB from '@/utils/db';
import Product from '@/utils/models/product/product';
export async function PUT(request: any, content: any) {
//extracting the id
const productId = content.params.id;
const filter = { _id: productId };
// takin the input to update
const payload = await request.json();
console.log(payload);
// Connect to the MongoDB database
await connectDB();
const result = await Product.findOneAndUpdate(filter, payload);
console.log(`Product with id: ${productId} updated`);
return NextResponse.json({ result, success: true });
}
// Define the GET request handler to fetch a product by its ID
export async function GET(request: any) {
//extracting the id
const productId = request.params?.id;
console.log(request.params);
const record = { _id: productId };
console.log(productId);
// Connect to the MongoDB database
await connectDB();
const data = await Product.findById(record);
console.log(`Product with id: ${productId} fetched`);
return NextResponse.json({ data, success: true });
}
```
# **so when I try to update the data with this api the data is getting updated and also the product data is getting printed but when I use GET to fetch only the data of the product by using the same id which is used for updating details it is giving me error-**
" ⨯ CastError: Cast to ObjectId failed for value "{ _id: undefined }" (type Object) at path "_id" for model "products"
at SchemaObjectId.cast (E:\Official\mongo based new\node_modules\mongoose\lib\schema\objectId.js:250:11)
at SchemaType.applySetters (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1221:12)
at SchemaType.castForQuery (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1636:17)
at cast (E:\Official\mongo based new\node_modules\mongoose\lib\cast.js:304:34)
at Query.cast (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4775:12)
at Query._castConditions (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2199:10)
at model.Query._findOne (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2513:8)
at model.Query.exec (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4319:80)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async GET (webpack-internal:///(rsc)/./src/app/api/products/edit/[id]/route.ts:41:18)
at async E:\Official\mongo based new\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:61856 {
stringValue: '"{ _id: undefined }"',
messageFormat: undefined,
kind: 'ObjectId',
value: { _id: undefined },
path: '_id',
reason: BSONError: input must be a 24 character hex string, 12 byte Uint8Array, or an integer
at new ObjectId (E:\Official\mongo based new\node_modules\bson\lib\bson.cjs:2147:23)
at castObjectId (E:\Official\mongo based new\node_modules\mongoose\lib\cast\objectid.js:25:12)
at SchemaObjectId.cast (E:\Official\mongo based new\node_modules\mongoose\lib\schema\objectId.js:248:12)
at SchemaType.applySetters (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1221:12)
at SchemaType.castForQuery (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1636:17)
at cast (E:\Official\mongo based new\node_modules\mongoose\lib\cast.js:304:34)
at Query.cast (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4775:12)
at Query._castConditions (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2199:10)
at model.Query._findOne (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2513:8)
at model.Query.exec (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4319:80)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async GET (webpack-internal:///(rsc)/./src/app/api/products/edit/[id]/route.ts:41:18)
at async E:\Official\mongo based new\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:61856,
valueType: 'Object',
model: Model { products }
}"
# **and if I use Product.findOne(record) instead of Product.findById(record); this is the output"**
"undefined
undefined
MongoDB connection successful
Product with id: undefined fetched
{
"data": null,
"success": true
}
"
|
CastError: Cast to ObjectId failed for value "{ _id: undefined } |
|node.js|api|next.js|backend|mern| |
null |
Watching a getter to a property of an object. Here is an example for object declaration with `reactive()` and `ref()`.
[vue playground](https://play.vuejs.org/#eNqtlG1r2zAQx7/KTQySQJqQZK9CEvbUsY3RjXWwF9Ogrn1x1NqSkWQnwfi77yTbeaBJW0bfGEn3/9/9JJ9UsndZNihyZFM2M6EWmQWDNs8WXIo0U9pCCRqXffoEoRUF9mEd2HAFFSy1SqFD3g6XXIZKGgupiWHuDN3OZ0wSBb+VTqJXnd5eYmxgceRVdcZuCSKawqgPMkhxCpxtVa4v3OSi1XAGFeU4yDBu6tTm8WnzsvG1TovGChl/EphENQKBOriH4Tb/mfDkMMylP5MulwDdHswXzSYHDqPvVyWur9wEMo2FG3lZ6WJwjDUogiRHSt9YnKTi8nyZce34n2KN9alifx5u6hzA35rgXMHJruDNOjBgtYhj1BjB7RYCuQUlEQILr0vigY+Uu9sbWPVNhUGC16SWcbdX3ewpZ8O6aaldaWIxzRIy0QxgthotytJ3ZFXNhjTzq5Eo/ICGQma5heIiVREmc84O9kd9M2xlt7m1SsLbMBHh/bGsPrhzoJwtvAdSnA3rLG1OkwXS0R03pOP0EU86bFGfZB4/j7mWvSjz+DnMp4yT08bZ8OAfsj6zhq7eUsSDO6MkvVG+pTgLVZqJBPX3zAq6mpxN22bjLKBnZ/3Vr1md1zfCe1YY3p9YvzMbt8bZD40GtXtrdjEb6BhtHb68vsINjXdB+gV5QupHgj/RqCR3jLXsfS4jwj7Qedov/qWlo/llLjcWpWk35UB9s3s9Z/TYfnhk63vcyeBNc0kqVv0DYsTzCw==)
```
<script setup>
import { ref, reactive, watch } from 'vue'
const msg = ref('Hello World!')
const state1 = reactive({ id: 1, name: "your-name-reactive" })
const state2 = ref({ id: 2, name: "your-name-ref" })
const testingField1 = ref('')
const testingField2 = ref('')
const testingField3 = ref('')
watch(
() => state1.name,
(newName, prevName) => {
testingField1.value = newName
}
)
watch(
() => state2.value.name,
(newName, prevName) => {
testingField2.value = newName
}
)
watch(
[() => state1.name, () => state2.value.name], // ⬅️
() => {
testingField3.value = `was triggered by any one at ${new Date().toLocaleString()}`
}
)
</script>
<template>
<h1>{{ msg }}</h1>
<div>
<input v-model="state1.name" />
<button @click="state1.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField1 }}</span>
</div>
<div>
<input v-model="state2.name" />
<button @click="state2.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField2 }}</span>
</div>
<div>
<span>{{ testingField3 }}</span>
</div>
</template>
```
Please notice `.value` when declaring an object with `ref()`. |
As you can see the mail.select() method is after connecting and before search, but keep getting this error(I'm using VS Code): `raise self.error("command %s illegal in state %s, "
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED`
This is my code:
```
import imaplib
import email
def delete_messages_with_phrase(folder, phrase):
# Selecting the email folder (inbox or trash)
mail.select(folder)
status, response = mail.search(None, 'ALL')
email_ids = response[0].split()
...
def delete_trash_messages(delete_option, phrase=None):
mail.select('[Gmail]/Trash')
...
username = 'email@gmail.com'
password = 'password'
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
folder_choice = input("Enter folder to delete messages (inbox/trash): ").lower()
if folder_choice == 'inbox':
delete_phrase = input("Enter phrase to delete messages: ")
delete_messages_with_phrase('inbox', delete_phrase)
elif folder_choice == 'trash':
delete_option = input("Delete all messages or messages with given phrase? (all/phrase): ").lower()
if delete_option == 'all':
delete_trash_messages('all')
elif delete_option == 'phrase':
phrase = input("Enter phrase to delete messages: ")
delete_trash_messages('phrase', phrase)
else:
print("Invalid choice.")
mail.expunge()
mail.close()
mail.logout()
```
I read that I have to paste the mail.select() method before mail.close() and I did it, but again same error. |
How to fix "search in state AUTH" errror |
|python|email|imap| |
null |
I have a simple bean called meterUtil and it depends on PrometheusMeterRegistry which is created in actuator starter. so i defined the bean as follow:
@ConditionalOnBean(PrometheusMeterRegistry.class)
public MeterUtil meterUtil(PrometheusMeterRegistry meterRegistry) {
return new MeterUtil(meterRegistry);
}
but as PrometheusMeterRegistry is created later meterUtil is never created with @ConditionalOnBean. i also tried @DependsOn("prometheusMeterRegistry") and Conditional class as follow:
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
Map<String, MeterRegistry> beansOfType = context.getBeanFactory().getBeansOfType(MeterRegistry.class);
if (beansOfType != null && beansOfType.size() == 1) {
return true;
}
} catch (BeansException e) {
return false;
}
return false;
}
but non work correctly. is there any way to achieve this?
i also wonder if we can depend bean creation on existence of specific dependency in our starter? if dependency classes not exist in our starter. in this example can we depend creation of meterUtil on existence of actuator dependency?
any help is appreciated. |
conditionalOnBean not work on beans created via starters |
|spring-boot| |
Set to `aside > div { height: 100%; display: grid; grid-template-rows: repeat(3, 1fr); }`.
And for `img { width: 100%; height: 100%; object-fit: cover; }`.
Here is an example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
article {
--gap: 10px;
border: var(--gap) solid black;
margin: 0 auto;
padding: 0;
display: flex;
max-width: 600px;
max-height: 90vh;
}
main {
padding: 20px;
}
aside {
display: flex;
flex-direction: column;
padding-left: var(--gap);
background: black;
}
aside > div {
height: 100%;
display: grid;
gap: var(--gap);
grid-template-rows: repeat(3, 1fr);
}
figure {
min-height:0;
}
img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
<!-- language: lang-html -->
<article>
<main>
<p>Hello hello hello hello</p>
</main>
<aside>
<div>
<figure>
<img src="https://picsum.photos/800/500" alt="">
</figure>
<figure>
<img src="https://picsum.photos/800/500" alt="">
</figure>
<figure>
<img src="https://picsum.photos/800/500" alt="">
</figure>
</div>
</aside>
</article>
<!-- end snippet -->
|
I'm encountering an error in my React Native application when trying to save user data and login details to Firebase using Redux. The error message I'm receiving is:
``` [Error: Actions must be plain objects. Instead, the actual type was: 'undefined'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. ```
I'm using Redux to manage my application's state, and I've configured a store using @reduxjs/toolkit. The strange thing is that the data is being saved successfully to Firebase, but I'm still getting this error.
Here's a simplified version of my Redux setup:
**Signup.js**
```js
const isTestMode = true;
const initialState = {
inputValues: {
username: isTestMode ? "John Doe" : "",
email: isTestMode ? "email@gmail.com" : "",
password: isTestMode ? "12121212" : "",
},
inputValidities: {
username: false,
email: false,
password: false,
},
formIsValid: false,
};
export default function Signup({ navigation }) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [formState, dispatchFormState] = useReducer(reducer, initialState);
const dispatch = useDispatch();
const inputChangedHandler = useCallback(
(inputId, inputValue) => {
const result = validateInput(inputId, inputValue);
dispatchFormState({ inputId, validationResult: result, inputValue });
},
[dispatchFormState]
);
const signupHandler = async () => {
try {
setIsLoading(true);
const action = signUp(
formState.inputValues.username,
formState.inputValues.email,
formState.inputValues.password
);
await dispatch(action);
Alert.alert("Account Successfully created", "Account created");
setError(null);
setIsLoading(false);
navigation.navigate("Login");
} catch (error) {
console.log(error);
setIsLoading(false);
setError(error.message);
}
};
return (
<SafeAreaProvider>
<View style={styles.container}>
<View style={styles.inputView}>
<Inputs
id="username"
placeholder="Username"
errorText={formState.inputValidities["username"]}
onInputChanged={inputChangedHandler}
/>
<Inputs
id="email"
placeholder="Enter your email"
errorText={formState.inputValidities["email"]}
onInputChanged={inputChangedHandler}
/>
<InputsPassword
id="password"
placeholder="Password"
errorText={formState.inputValidities["password"]}
onInputChanged={inputChangedHandler}
/>
</View>
<Buttons
title="SIGN UP"
onPress={signupHandler}
isLoading={isLoading}
/>
<StatusBar style="auto" />
</View>
</SafeAreaProvider>
);
}
```
**AuthSlice.js**
```js
import { createSlice } from "@reduxjs/toolkit";
const authSlice = createSlice({
name: "auth",
initialState: {
token: null,
userData: null,
didTryAutoLogin: false,
},
reducers: {
authenticate: (state, action) => {
const { payload } = action;
state.token = payload.token;
state.userData = payload.userData;
state.didTryAutoLogin = true;
},
setDidTryAutoLogin: (state, action) => {
state.didTryAutoLogin = true;
},
},
});
export const authenticate = authSlice.actions.authenticate;
export default authSlice.reducer;
```
**Store.js**
```js
import { configureStore } from "@reduxjs/toolkit";
import authSlice from "./authSlice";
export const store = configureStore({
reducer: {
auth: authSlice,
},
});
``` |
{"OriginalQuestionIds":[13095792],"Voters":[{"Id":10035985,"DisplayName":"Andrej Kesely","BindingReason":{"GoldTagBadge":"python"}}]} |
Basically I have an authentication application, where I have an authentication page where my user is sent every time the system does not recognize that he is authenticated, authentication occurs when he has a valid token registered in his localstorage with "authorization", so through "requireAuth" I created a mechanism where when a valid token is not identified in localstorage, the user is sent to the authentication page when he tries to access "/", and if he is authenticated, then he goes straight to "/ " and cannot access the auth page. This way
```
import { useContext } from "react"
import { AuthContext } from "./AuthContext"
import Authpage from "../pages/Authpage";
import { Navigate } from "react-router-dom";
export const RequireAuth = ({ children }: { children: JSX.Element }) => {
const auth = useContext(AuthContext);
if (!auth.user) {
return <Navigate to="/auth" replace />;
}
return children;
}
```
As you can see, the "/" page is protected
```
import { Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import './App.css';
import Homepage from './pages/Homepage';
import Authpage from './pages/Authpage';
import Signuppage from './pages/Signuppage/Signuppage';
import { RequireAuth } from './context/RequireAuth';
import { RequireNotAuth } from './context/RequireNotAuth';
import React from 'react';
import GoogleAuthRedirect from './pages/GoogleAuthRedirect';
export function InvalidRoute() {
const navigate = useNavigate();
React.useEffect(() => {
navigate('/');
}, [navigate]);
return null;
}
function App() {
return (
<Routes>
<Route path='/' element={<RequireAuth><Homepage /></RequireAuth>} />
<Route path='/auth' element={<Authpage />} />
<Route path='/signup' element={<Signuppage />} />
<Route path='/googleauth/:id' element={<GoogleAuthRedirect />} />
</Routes>
);
}
export default App;
```
This is the part where my user gets thrown after authentication before being sent to "/"
```
import * as C from './styles';
import { useNavigate, useParams } from 'react-router-dom';
import { useContext, useEffect, useState } from 'react';
import { useApi } from '../../hooks/useApi';
import { AuthContext } from '../../context/AuthContext';
type Props = {}
const GoogleAuthRedirect = (props: Props) => {
const { id } = useParams();
const api = useApi();
const auth = useContext(AuthContext);
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
useEffect(() => {
const getToken = async() => {
try {
if (id) {
const token = await api.verifyToken(id);
setLoading(true);
setLoading(false);
if (token.success) {
localStorage.setItem('authorization', id);
setLoading(true);
setLoading(false);
navigate('/');
}
} else {
console.log("Token não definido.");
}
} catch (err) {
console.log(err);
}
}
getToken();
}, []);
return (
<div>
<h3>Autenticando...</h3>
</div>
)
}
export default GoogleAuthRedirect;
```
The problem is that after authenticating and sending the page "/", nothing is rendered on the page and it is only rendered if I press f5 and refresh the page. Somehow I thought it could be because it is being sent before authenticating in useEffect, so I tried loading it to extend this time and without success. |
Redux: Actions must be plain objects error - How to resolve? |
|javascript|firebase|react-native|redux|redux-toolkit| |
Use TraceSource logger, bur add switch with level verbose, then all your logging goes to the trace listener test.log :)
var builder = webApplication.CreateBuilder(args);
builder.Logging.AddTraceSource(new
SourceSwitch("trace", "Verbose"),
new TextWriterTraceListener(Path.Combine(
b.Environment.ContentRootPath, "trace.log")));
|
I have a ```1``` by ```T``` double vector ```X```, where ```T = length(X)``` is the number of timesteps. I would like to fit a symbolic time dependent function ```sym F(t)``` to this vector. What is the most efficient way to do this in MATLAB? |
I have a command:
```
s5cmd --endpoint-url http://192.168.1.40:9000 ls "s3://ccdata/minhash/20*/**" | awk '{print $NF}' > minhash_listings.txt
```
I have a local Minio deployment that has 16-17 million files in it so far. the folder structure of the minhash has 84 subfolders, with 5000 subfolders underneath that, and then up to 15 files under each folder. An example would be /minhash/2014-01/0001/filename.json.gz
The underlying hardware is a Dell R370 with 40 x 16TB drives and 3 nvme drives holding metadata, on a zfs pool.
It takes about 3 days for this command to complete. I do not see any real hit to network, cpu, ram, disk IO when it is running. This makes me think this entire command is single threaded.
My question is, given what I am trying to create, is there a better/faster way? I need to regenerate this file about daily.
|
Optimizing an s5cmd command that uses awk to generate a text file |
|linux|file|amazon-s3|awk| |
null |
In Clean Architecture, you generally want to define interfaces in the Application layer. This is because all your business logic should live in and be dictated by the application/domain layer. It should define the interfaces it needs to send requests to and receive responses from the outside world. This allows you to build out your application's unique functionality without concern for how you will get/persist data, call external apis, etc.
The Infrastructure layer should be aware of the Application layer so that it can implement the interfaces. Then, the Presentation layer should invoke the Application layer. Depending on how dogmatic you want to be with CA principles, the Presentation layer should either NOT reference/use the Infrastructure layer at all (in this case, you would use some compositional root project to build a DI container), or it should reference the Infrastructure layer ONLY as a means to register the Application's interfaces with the Infrastructure's implementations for a DI container.
You shouldn't define "external service objects" in an Application layer; rather, you define only domain objects and interfaces needed by your app to do its thing. Then, the concerns of "external service" are addressed in the Infrastructure's implementation and its concerns usually look something like:
- Knowing how to call the external service
- Having models for sending requests to and receiving responses from the external service
- Mapping application/domain requests from the application/domain to the external service models
- Mapping external responses back to some application/domain model
|
Page in React only renders elements after refreshing |
|javascript|reactjs|typescript|react-hooks| |
null |
I am new to Rust but recently came across a problem I don't know how to solve. It's to work with nested (and multi-dimensional) value-key pair arrays in Rust that is dynamically generated based on string splitting.
The sample dataset looks something like the example below:
```lang-none
Species | Category
Dog | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Canidae, Canis, C. familiaris
Cat | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Feliformia, Felidae, Felinae, Felis, F. catus
Bear | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Ursoidea, Ursidae, Ursus
...
```
The goal would be to split the comma delimitation and a create a map or vector. Essentially, creating "layers" of nested keys (either as a vector array or a key to a *final value*).
From my understanding, Rust has a crate called `serde_json` which can be used to create key-value pairings like so:
let mut array = Map::new();
for (k, v) in data.into_iter() {
array.insert(k, Value::String(v));
}
As for comma delimited string splitting, it might look something like this:
let categories = "a, b, c, d, e, f".split(", ");
let category_data = categories.collect::<Vec<&str>>()
However, the end goal would be to create a recursively nested map or vector that follows the `Category` column for the array which can ultimately be serialised to a json output. How would this be implemented in Rust?
In addition, while we might know the number of rows in the sample dataset, isn't it quite resource intensive to calculate all the "comma-delimited layers" in the `Category` column to know the final size of the array as required by Rust's memory safe design to "initialize" an array by a defined or specified size? Would this need to specifically implemented as way to know the maximum number of layers in order to be doable? Or can we implement an infinitely nested multi-dimensional array without having to specify or initialise a defined map or vector size?
For further reference, in PHP, this might be implemented so:
```php
$output_array = array();
foreach($data_rows as $data_row) {
$temp =& $output_array;
foreach(explode(', ', $data_row["Category"]) as $key) {
$temp =& $temp[$key];
}
// Check if array is already initialized, if not create new array with new data
if(!isset($temp)) {
$temp = array($data_row["Species"]);
} else {
array_push($temp, $data_row["Species"]);
}
}
```
How would a similar solution like this be implemented in Rust? |
I try to use [validator.js](https://github.com/validatorjs/validator.js) via JSInterop in Blazor but got an error `Unhandled exception rendering component: Failed to fetch dynamically imported module: https://localhost:7027/_content/.../dist/JSInteropModule.js` when try to import the library.
I installed [validator.js](https://github.com/validatorjs/validator.js) using libman (unpkg) then create an interface for js interop as:
C# code:
```csharp
private readonly Lazy<Task<IJSObjectReference>> jsModuleTask;
private readonly IJSRuntime jsRuntime;
public InteropExperimentJS(IJSRuntime jsRuntime)
{
string scriptPath;
this.jsRuntime = jsRuntime;
jsModuleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
"import", $"./dist/JSInteropModule.js").AsTask());
}
public async ValueTask<bool> InvokeFunctionWithLibs(string email, CancellationToken cancellationToken = default)
{
var jsModule = await jsModuleTask.Value.ConfigureAwait(false);
return await jsModule.InvokeAsync<bool>("validateEmail", cancellationToken, email).ConfigureAwait(false);
}
```
TS code:
```js
import { validator } from "./lib/validator/validator.js";
const simpleAlert = function (input: string): void {
alert(input);
};
const returnValue = function (input: string): string {
return input;
};
const validateEmail = function (email: string): boolean {
return validator.isEmail(email);
};
export { simpleAlert, returnValue, validateEmail };
```
The problem is when I reference the validator.js separated with <script> tag without import in my TS file every function is worked well. But when I use the import statement I got return error `Unhandled exception rendering component: Failed to fetch dynamically imported module: https://localhost:7027/_content/.../dist/JSInteropModule.js`. How can I use the validator.js with import in my TS code. |
my mse and mae are low, but my R2 is negative one, but super small, why? |
|keras|deep-learning|regression| |
null |
url :-> `https://www.greenblottmetal.com/scrap-metal-prices`
problem is :->
<iframe>---> #document(another url) ---> new <html> <table></table> </html>
After inspect data available into <iframe> tag and inside iframe there is #document is there this is subtype of iframe and holding URL inside "()" and holding <html>...<table>.....</table></html> I want to scrape data from the table but I'm not able to read from Beautifsoup library object data from this URL and its HTML content. For more visit URL: `https://www.greenblottmetal.com/crap-metal-prices`
Data showing on webpage after inspect:
```none
<html>
<head>
</head>
<body>
<iframe class="nKphmK" title="Table Master" aria-label="Table Master" scrolling="no" src="https://wix-visual-data.appspot.com/index?pageId=ee1kv&compId=comp-iokfptn7&viewerCompId=comp-iokfptn7&siteRevision=148&viewMode=site&deviceType=desktop&locale=en&regionalLanguage=en&width=569&height=2957&instance=J_m2kTqVpMO94dlz4vhUuD232Kbag0irUNTSTGpGJmM.eyJpbnN0YW5jZUlkIjoiNDJjNzg3YWYtOTgwYi00MWNlLThmMGQtMjgxMzhmMDVkOTY5IiwiYXBwRGVmSWQiOiIxMzQxMzlmMy1mMmEwLTJjMmMtNjkzYy1lZDIyMTY1Y2ZkODQiLCJtZXRhU2l0ZUlkIjoiZTBmNDk5MWQtN2MxNS00ODU5LWIyYjktMzllZThhMDljZWRjIiwic2lnbkRhdGUiOiIyMDI0LTAzLTI4VDA3OjQxOjU4LjY5N1oiLCJkZW1vTW9kZSI6ZmFsc2UsImFpZCI6IjdmNGVhMTVkLTcxMzctNGZjOC05YzAwLWUwMmNmNDE3YTAwOSIsImJpVG9rZW4iOiJhMjMzMWViMi1lNDFlLTA5OTctM2RiNC0xMWZkMDUwYzE3YjUiLCJzaXRlT3duZXJJZCI6ImI0NmJjNTExLTVlMzYtNDQ3NS05NjEzLWFhNzhmZGVkYzRiZSJ9&commonConfig=%7B%22brand%22%3A%22wix%22%2C%22host%22%3A%22VIEWER%22%2C%22bsi%22%3A%2221aec005-387a-4cdb-bc29-79c09bd8fb5a%7C1%22%2C%22BSI%22%3A%2221aec005-387a-4cdb-bc29-79c09bd8fb5a%7C1%22%7D&currentRoute=.%2Fscrap-metal-prices&vsi=236d7927-567f-4b22-bd97-6cea740fe681" allowfullscreen="" allowtransparency="true" allowvr="true" frameborder="0" allow="autoplay;camera;microphone;geolocation;vr">
#document (https://wix-visual-data.appspot.com/index?pageId=ee1kv&compId=comp-iokfptn7&viewerCompId=comp-iokfptn7&siteRevision=148&viewMode=site&deviceType=desktop&locale=en®ionalLanguage=en&width=569&height=2957&instance=J_m2kTqVpMO94dlz4vhUuD232Kbag0irUNTSTGpGJmM.eyJpbnN0YW5jZUlkIjoiNDJjNzg3YWYtOTgwYi00MWNlLThmMGQtMjgxMzhmMDVkOTY5IiwiYXBwRGVmSWQiOiIxMzQxMzlmMy1mMmEwLTJjMmMtNjkzYy1lZDIyMTY1Y2ZkODQiLCJtZXRhU2l0ZUlkIjoiZTBmNDk5MWQtN2MxNS00ODU5LWIyYjktMzllZThhMDljZWRjIiwic2lnbkRhdGUiOiIyMDI0LTAzLTI4VDA3OjQxOjU4LjY5N1oiLCJkZW1vTW9kZSI6ZmFsc2UsImFpZCI6IjdmNGVhMTVkLTcxMzctNGZjOC05YzAwLWUwMmNmNDE3YTAwOSIsImJpVG9rZW4iOiJhMjMzMWViMi1lNDFlLTA5OTctM2RiNC0xMWZkMDUwYzE3YjUiLCJzaXRlT3duZXJJZCI6ImI0NmJjNTExLTVlMzYtNDQ3NS05NjEzLWFhNzhmZGVkYzRiZSJ9&commonConfig=%7B%22brand%22:%22wix%22,%22host%22:%22VIEWER%22,%22bsi%22:%2221aec005-387a-4cdb-bc29-79c09bd8fb5a%7C1%22,%22BSI%22:%2221aec005-387a-4cdb-bc29-79c09bd8fb5a%7C1%22%7D¤tRoute=.%2Fscrap-metal-prices&vsi=236d7927-567f-4b22-bd97-6cea740fe681)
<html>
<head></head>
<body class="js-focus-visible">
<div id="appContainer">
<section class="main-content ng-scope" ng-if="!main.hasError" ng-class="{'show-sortable': main.settings.tableParams.sortable}">
<div footable="" class="direction-right" style="height: 100%; width:100%; display: block" data-settings="main.settings" data-instance-id="main.instanceId" data-comp-id="main.compId" data-fixed-height="main.isFixedHeight()" data-filter-position="main.getFilterPosition()"><!-- ngIf: fixedHeight -->
<!-- ngIf: !fixedHeight --><div class="adjust-height-view ng-scope" adjust-height-view="" ng-if="!fixedHeight"><section style="width:100%;" ng-show="settings.tableParams.showHeaderFooter && !isEmptyTable" class="ng-hide">
<table id="filterTable" class="filter outerBorder" style="width:100%;" ng-class="{'mobile':isMobile}">
<thead>
<tr>
<th colspan="100%">
<div id="filterBox" ng-show="settings.tableParams.filter" class="ng-hide"></div>
</th>
</tr>
</thead>
</table>
</section>
<div id="tableWrapper" style="min-height: 2757px; height: 100%;">
<table id="theTable" style="width: 100%; display: table; height: 100%;" dir="auto" data-paging="false" data-cascade="true" data-filter-min="3" data-paging-size="5" data-useparentwidth="true" data-filter-container="#filterBox" data-filter-connectors="false" data-use-parent-width="false" data-sorting="" data-filtering="" data-filter-filters="[]" data-filter-placeholder="Search" data-filter-position="right" data-show-header="true" ng-class="{'empty-table':isEmptyTable}" class="footable table outerBorder footable-1 breakpoint-x-small"><thead><tr class="footable-header"><th class="wixColumns footable-first-visible" style="display: table-cell;">COPPER & BRASS</th><th class="wixColumns footable-last-visible" style="display: table-cell;"></th></tr></thead><tbody><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">#1 Bare Bright Wire </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$3.10/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">#1 Copper Tubing / Flashing </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$3.00/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">#2 Copper Tubing / Bus Bar </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.75/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">#3 Roofing Copper </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.40/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Brass (Plumbing, Pipe) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.15/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Red Brass or Bronze </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.25/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Brass Shells </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.15/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Brass Water Meter </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.15/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Clean Brass Auto Radiators </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.00/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum/Copper Coil (Clean) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$1.48/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum/Copper Coil (Dirty) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$.85/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">COPPER BEARING MATERIAL </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Copper Transformers </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.30/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Electric Motors </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.30/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Alternators/Starters </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.22/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Sealed Units/Compressors </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.25/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">INSULATED COPPER WIRE </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Insulated Copper Wire (Cat 5/6) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.85/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">THHN Cable </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$1.55/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">500-750 MCM (Bare Bright Inside) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$1.70/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Hollow Heliax Wire </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$1.10/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Romex Wire </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$1.35/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Insulated Cable </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.55/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Steel BX </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.45/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum BX </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.90/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">low grade insulated wire 30% </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.45/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">ALUMINUM </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Siding </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Sheet Aluminum </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Rims </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.74/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Truck Rims </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Chrome Rims </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Windows frames </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Cast Aluminum </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.42/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Bare Aluminum Wire </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.57/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">AL Thermo-pane/break (Not Glass) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.47/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">AL Litho Plates </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.60/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">AL Machine Cuts </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.60/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Aluminum Transformers </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.06/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">AL Turnings </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.18/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Unprepared aluminum </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> $0.40/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Irony aluminum </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> $0.11/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">MISCELLANEOUS SCRAP </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Car Batteries </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.17/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Steel Case Battery (forklift) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.12/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Lead </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.50/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">304 Stainless Steel (Non-Magnetic) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.35/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">316 Stainless Steel (Non-Magnetic) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.65/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Lead Wheel Weights </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.10/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Ballasts </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.06/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Scrap Generators </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.06/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Catalyic Converter </td><td class="wixColumns footable-last-visible" style="display: table-cell;">Prices Vary </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">STEEL & IRON </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Short Steel </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$225/G.t. ($0.10/lb) </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Light Iron & Tin & appliances </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$ 160/G.t. ($0.07/lb) </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Cast Iron </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$ 225/G.t. ($0.10/lb) </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Plate & Structural </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$ 235/G.t. ($0.10/lb) </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Unprepared steel torching </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> $ 160/G.t. ($0.07/lb) </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Unprepared steel shearing </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> $ 215/g.t. ($.095/lb) </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">COMPUTER SCRAP </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Motherboards </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$.60/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Power Supplies (w/Wires) </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.05/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Harddrive PC Board </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.10/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Telecom Equipment </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.07-$0.25/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Servers </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.07-$0.25/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">RARE EARTH METALS </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Carbide Inserts/Shapes </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.00-$8.50/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Monel </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$2.00-$2.80/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Titanium </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.40/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Nickel </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$3.00 and up </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;">Inconel </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$ 2.50/lb </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">Tin Solder </td><td class="wixColumns footable-last-visible" style="display: table-cell;">$0.40-$3.00/lb </td></tr><tr class="footableOdd"><td class="wixColumns footable-first-visible" style="display: table-cell;"> </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr><tr class="footableEven"><td class="wixColumns footable-first-visible" style="display: table-cell;">PRICES SUBJECT TO CHANGE WITHOUT NOTICE ... </td><td class="wixColumns footable-last-visible" style="display: table-cell;"> </td></tr></tbody></table>
</div>
<section style="width:100%;margin:0;">
<table id="pagerFilter" class="footable footer outerBorder ng-hide" style="width: 100%; margin: 0px;" ng-show="settings.tableParams.showHeaderFooter">
<tfoot id="noPager">
<tr>
<td colspan="100%" style="height:26px;"></td>
</tr>
</tfoot>
</table>
</section>
</div><!-- end ngIf: !fixedHeight -->
</div>
</section>
</div>
</body>
</html>
</iframe>
</body>
</html>
```
I have tried using beautifsoup library in python but <iframe> tag holds only below data for iframe is
```none
<iframe class="nKphmK" title="Table Master" aria-label="Table Master" scrolling="no" src="./Scrap Metal Prices _ Greenblott Metal Co. _ Binghamton, NY_files/index.html" allowfullscreen="" allowtransparency="true" allowvr="true" frameborder="0" allow="autoplay;camera;microphone;geolocation;vr">
</iframe>
```
for data for either for #document nor for table inside #document. |
I am building the Mobile app with Expo and should implement the document scanner feature.
But I could not find the solution to implement for scanning documents.
I can see only the react-native-document-scanner npm library for React Native, not for Expo.
If anybody has a good solution, Please help me...
Thanks
|
I'm adding some extra information here because the previous answer isn't quite correct.
These are the issues:
=====================
- You *need* to be specifying the current string encoding to mb_string, otherwise this may be incorrectly gathered
- In 7-bit GSM encoding, the Basic Charset Extended characters (^{}\\[~]|€) require 14-bits each to encode, so they count as two characters each.
- In UCS-2 encoding, you have to be wary of emoji and other characters outside the 16-bit BMP, because...
- GSM with UCS-2 counts 16-bit characters, so if you have a character (U+1F4A9), and your carrier and phone sneakily support UTF-16 and not just UCS-2, it will be encoded as a surrogate pair of 16-bit characters in UTF-16, and thus be counted as TWO 16-bit characters toward your string length. `mb_strlen` will count this as a single character only.
How to count 7-bit characters:
------------------------------
What I've come up with so far is the following to count 7-bit characters:
// Internal encoding must be set to UTF-8,
// and the input string must be UTF-8 encoded for this to work correctly
protected function count_gsm_string($str)
{
// Basic GSM character set (one 7-bit encoded char each)
$gsm_7bit_basic = "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
// Extended set (requires escape code before character thus 2x7-bit encodings per)
$gsm_7bit_extended = "^{}\\[~]|€";
$len = 0;
for($i = 0; $i < mb_strlen($str); $i++) {
$c = mb_substr($str, i, 1);
if(mb_strpos($gsm_7bit_basic, $c) !== FALSE) {
$len++;
} else if(mb_strpos($gsm_7bit_extended, $c) !== FALSE) {
$len += 2;
} else {
return -1; // cannot be encoded as GSM, immediately return -1
}
}
return $len;
}
How to count 16-bit characters:
-------------------------------
- Convert the string into UTF-16 representation (to preserve the emoji characters with `mb_convert_encoding($str, 'UTF-16', 'UTF-8')`.
- **do not** convert into UCS-2 as this is lossy with `mb_convert_encoding`)
- Count bytes with `count(unpack('C*', $utf16str))` and divide by two to get the number of UCS-2 16-bit characters that count toward the GSM multipart length
*caveat emptor, a word on counting bytes:
- **Do not** use `strlen` to count the number of bytes. While it may work, `strlen` is often overloaded in PHP installations with a multibyte-capable version, and is also a candidate for API change in the future
- **Avoid `mb_strlen($str, 'UCS-2')`**. While it does *currently* work, and will return, correctly, 2 for a pile of poo character (as it looks like two 16-bit UCS-2 characters), its stablemate `mb_convert_encoding` is lossy when converting from >16-bit to UCS-2. Who's to say that mb_strlen won't be lossy in the future?
- **Avoid `mb_strlen($str, '8bit') / 2`**. It also *currently* works, and is recommended in a PHP docs comment as a way to count bytes. But IMO it suffers from the same issue as the above UCS-2 technique.
- **That leaves the safest current way (IMO)** as `unpack`ing into a byte array, and counting that.
So, what does this look like?
// Internal encoding must be set to UTF-8,
// and the input string must be UTF-8 encoded for this to work correctly
protected function count_ucs2_string($str)
{
$utf16str = mb_convert_encoding($str, 'UTF-16', 'UTF-8');
// C* option gives an unsigned 16-bit integer representation of each byte
// which option you choose doesn't actually matter as long as you get one value per byte
$byteArray = unpack('C*', $utf16str);
return count($byteArray) / 2;
}
Putting it all together:
------------------------
function multipart_count($str)
{
$one_part_limit = 160; // use a constant i.e. GSM::SMS_SINGLE_7BIT
$multi_limit = 153; // again, use a constant
$max_parts = 3; // ... constant
$str_length = count_gsm_string($str);
if($str_length === -1) {
$one_part_limit = 70; // ... constant
$multi_limit = 67; // ... constant
$str_length = count_ucs2_string($str);
}
if($str_length <= $one_part_limit) {
// fits in one part
return 1;
}
if($str_length > ($max_parts * $multi_limit)) {
// too long
return -1; // or throw exception, or false, etc.
}
// divide the string length by multi_limit and round up to get number of parts
return ceil($str_length / $multi_limit);
}
----------
Turned this into a library...
=============================
https://bitbucket.org/solvam/smstools |
null |
I have the following stopwatch implementation
import { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
function TimerComponent() {
const [isActive, setIsActive] = useState(false);
const [time, setTime] = useState(0);
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
setTime(time => time + 0.1);
}, 100);
} else {
clearInterval(interval);
}
return () => {
clearInterval(interval);
};
}, [isActive]);
const handleStart = () => {
setIsActive(true);
};
const handleReset = () => {
setIsActive(false);
setTime(0);
};
const roundedTime = time.toFixed(1);
return (
<View style={styles.outerContainer}>
<Button
title="Start"
onPress={handleStart}
/>
<Text style={styles.text}>{roundedTime}</Text>
<Button
title="Stop"
onPress={handleReset}
/>
</View>
);
}
export default TimerComponent;
on Android it works as expected, when I compare to another stopwatch it reaches 30 seconds at the same time, but when I test on iOS it takes around 5 seconds longer. |
React Native stopwatch implementation slow on iOS |
|react-native|stopwatch| |
I compiled a python script using pyinstaller in a Kali Linux machine and the compilation was successful and the binary was built . However , when I try to execute this binary on a Ubuntu machine I get the following error :
[2664] Error loading Python lib '/tmp/_MEI5jZUdD/libpython3.11.so.1.0': dlopen: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.36' not found (required by /tmp/_MEI5jZUdD/libexpat.so.1)
I far as I understand there is a compatibility issue as Kali’s GLIBC version is 2.36 whereas Ubuntu ‘s is 2.35 . Is there any way to fix it ? Ideally, a GLIBC downgrade in Kali Linux Machine ( which is my main one) would be useful as each binary I compile there would not have any compatibility issues when running on other Linux machines such as Ubuntu’s system . What do you think ? What should I do?
I tried fully upgrading both machines but this did not help |
You're getting this error because the `Route` facade isn't imported inside your code. You need to import it by using the following statement:
use Illuminate\Support\Facades\Route; |
null |
newbie here. Does anyone know how to prevent the image from zooming in when i resize the browser ?
I'm trying to create a carousel using tailwind and flowbite. Here's my CSS code :
```
<main>
<section
id="hero-section"
class="bg-blue-300"
style="height: calc(100vh - 65px)"
>
<div
id="default-carousel"
class="relative h-full w-full"
data-carousel="slide"
>
<!-- Carousel wrapper -->
<div class="relative h-full overflow-hidden md:h-96">
<!-- Item 1 -->
<div class="hidden duration-1000 ease-in-out" data-carousel-item>
<img
src="sample-image2-mobile.jpg"
class="absolute block object-cover h-full w-full -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2"
alt="..."
/>
</div>
<!-- Item 2 -->
<div class="hidden duration-1000 ease-in-out" data-carousel-item>
<img
src="sample-image2-mobile.jpg"
class="absolute block object-cover h-full w-full -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2"
alt="..."
/>
</div>
</div>
<!-- Slider indicators -->
<div
class="absolute z-30 -translate-x-1/2 bottom-5 left-1/2 space-x-3 rtl:space-x-reverse"
>
<button
type="button"
class="w-3 h-3 rounded-full"
aria-current="true"
aria-label="Slide 1"
data-carousel-slide-to="0"
></button>
<button
type="button"
class="w-3 h-3 rounded-full"
aria-current="false"
aria-label="Slide 2"
data-carousel-slide-to="1"
></button>
<button
type="button"
class="w-3 h-3 rounded-full"
aria-current="false"
aria-label="Slide 3"
data-carousel-slide-to="2"
></button>
</div>
</div>
</section>
</main>
```
I've tried things like setting-up high, object-cover, and so on but still didn't work. |
How can i prevent the image from zooming in when i resize the browser? |
|css|responsive-design|frontend|tailwind-css|flowbite| |
null |
I would use a simple loop:
```
out = (np.array([mapping[l] for l in
map(tuple, input_array.reshape(-1, 2))])
.reshape(input_array.shape[:-1])
)
```
Or, if you expect many duplicated values, you could reduce the mapping step to the unique values, although the bottleneck being `np.unique` this might not be much faster if `n` is large:
```
tmp, idx = np.unique(input_array.reshape(-1, 2),
return_inverse=True, axis=0)
out = (np.array([mapping[tuple(l)] for l in tmp])[idx]
.reshape(input_array.shape[:-1])
)
```
Output:
```
array([[0.7, 0.8],
[0.7, 0.9]])
```
##### timings
On (2, 2, 2):
```
# original
86 µs ± 11.4 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
# this answer: simple loop
7.08 µs ± 811 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
# this answer: only mapping unique values
60.7 µs ± 1.6 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
```
On (200, 200, 2):
```
# original
33.7 ms ± 4.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# this answer: simple loop
45.7 ms ± 3.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# this answer: only mapping unique values
30 ms ± 854 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
```
For large `m` (or `n`) (2000, 2, 2):
```
# original
2.78 ms ± 366 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# this answer: simple loop
4.54 ms ± 191 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# this answer: only mapping unique values
2.3 ms ± 6.19 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
```
For large `m` and `n` (e.g. (2000, 2000, 2)):
```
# original
4.5 s ± 67.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# this answer: simple loop
4.29 s ± 35.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# this answer: simple loop
4.31 s ± 108 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
As noted by @MatBailie, the simple loop can be further improved using `np.fromiter`:
```
N = input_array.shape[-1]
out = (np.fromiter((mapping[l] for l in
map(tuple, input_array.reshape(-1, N))),
float, count=input_array.size//N)
.reshape(input_array.shape[:-1])
)
``` |
I have a code setup whereby the timeline is suppose to play when a gameobject collides/triggers another gameobject. Unity recognises this trigger(prints out to the console) but the timeline does not play.
Here is the code I have
```
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.Playables;
public class GenericTrigger : MonoBehaviour
{
public PlayableDirector timeline;
// Use this for initialization
void Start()
{
timeline = GetComponent<PlayableDirector>();
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
//timeline.Stop();
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Trigger Entered");
Destroy(this.gameObject);
timeline.Play();
}
}
}
```
The reason why the playable director attached to the scripts is "TriggerObject"(the name of the gameobject it is attached) is because that is the only option available for me to click when I clicked the encircled dot next to it.
[![This is the inspector on the cube that the script is attached to][1]][1]
[1]: https://i.stack.imgur.com/1Hnl8.png |
Timeline doesn't start eventhough it recognises the trigger input |
|unity-game-engine|unity-timeline| |
|linux|file|awk| |
Have you seen the dataflow cookbook examples on GitHub?
- [Reading from pubsub subscription with python](https://github.com/GoogleCloudPlatform/dataflow-cookbook/blob/main/Python/pubsub/read_pubsub_subscription.py)
- [Writing to bigtable with python](https://github.com/GoogleCloudPlatform/dataflow-cookbook/blob/main/Python/bigtable/write_bigtable.py)
Below is a code showing a apache beam pipeline that reads a pub/sub subscription and write on bigtable, using your input as an example:
```python
import logging
import apache_beam as beam
from apache_beam.io import ReadFromPubSub
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.transforms.core import DoFn
from google.cloud.bigtable.row import DirectRow
from google.cloud.bigtable.row_data import Cell
from apache_beam.io.gcp.bigtableio import WriteToBigTable
class ConvertToJson(beam.DoFn):
def process(self, element):
import json
yield json.loads(element)
class MakeBigtableRow(DoFn):
def process(self, element):
row = DirectRow(row_key=str(element['id']))
for key, value in element.items():
row.set_cell(
column_family_id='cf1',
column=key,
value=str(value)
)
yield row
def run():
class ReadPubSubOptions(PipelineOptions):
@classmethod
def _add_argparse_args(cls, parser):
parser.add_argument(
"--subscription",
required=True,
help="PubSub subscription to read.",
)
parser.add_argument(
"--project_id",
required=True,
help="Project ID"
)
parser.add_argument(
"--instance_id",
required=True,
help="Cloud Bigtable instance ID"
)
parser.add_argument(
"--table_id",
required=True,
help="Cloud Bigtable table ID"
)
options = ReadPubSubOptions(streaming=True)
with beam.Pipeline(options=options) as p:
(
p
| "Read PubSub subscription"
>> ReadFromPubSub(subscription=options.subscription)
| "Convert to JSON" >> beam.ParDo(ConvertToJson())
| 'Map to Bigtable Row' >> beam.ParDo(MakeBigtableRow())
| "Write to BigTable" >> WriteToBigTable(
project_id=options.project_id,
instance_id=options.instance_id,
table_id=options.table_id
)
| beam.Map(logging.info)
)
if __name__ == "__main__":
logging.getLogger().setLevel(logging.INFO)
run()
```
[![print of bigtable UI][1]][1]
[1]: https://i.stack.imgur.com/YRfct.png |
Failed to fetch dynamically imported module on Blazor JS Interop |
|c#|.net|blazor|javascript-interop| |
null |
{"Voters":[{"Id":600486,"DisplayName":"blurfus"},{"Id":14732669,"DisplayName":"ray"},{"Id":9267406,"DisplayName":"imhvost"}],"SiteSpecificCloseReasonIds":[13]} |
I'm trying to process multiple forms with fieldset inside
This is a test for 40 questions, each question with 4 answers.
I need to get each answer from radio button that the users picks and use it to count correct answers.
I have some comments along the code to help out, if anything is needed let me know.
Thanks for any help.
My index.js code
```
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "***", // don't post your password!
port: 5432,
});
const pool = new pg.Pool({
user: "postgres",
host: "localhost",
database: "world",
password: "***",
port: 5432,
});
const app = express();
const port = 3000;
db.connect();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
// Shuffling function based of fisher yates algorithm
const shuffle = array => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
let questions = [];
app.get("/", async (req, res) => {
//Generates random of questions IDs.
for (let i = 0; i < 3; i++) {
let questionId = Math.floor(Math.random() * 70);
questions.push(questionId);
};
// Query questions IDs from DB and shuffles the answers
let arrayToShuff = [];
let shuffledArray = [];
const result = await pool.query(`SELECT * FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]);
for (let i = 0; i < 3; i++) {
arrayToShuff = [result.rows[i].answer1, result.rows[i].answer2, result.rows[i].answer3, result.rows[i].answer4];
shuffle(arrayToShuff);
shuffledArray = [arrayToShuff[0], arrayToShuff[1], arrayToShuff[2], arrayToShuff[3]];
result.rows[i].answer1 = shuffledArray[0];
result.rows[i].answer2 = shuffledArray[1];
result.rows[i].answer3 = shuffledArray[2];
result.rows[i].answer4 = shuffledArray[3];
};
return res.render("index.ejs", {
questionsResults: result.rows,
answersShuffled: shuffledArray
});
});
for (let i = 0; i < 3; i++) {
let questionId = Math.floor(Math.random() * 70);
questions.push(questionId);
};
app.post("/submit", async (req, res) => {
const submittedAnswer = req.body.answer;
res.send(req.body);
console.log(req.body);
const result2 = await db.query(`SELECT answer1 FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]);
const correctAnswer = result2.rows[0].answer1;
if (submittedAnswer == correctAnswer) {
console.log("This is correct");
} else {
console.log("Sorry, this is incorrect");
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
```
My index.ejs file.
```
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>שאלות תאוריה</title>
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<% questionsResults.forEach(question=> { %>
<form action="/submit" method="post" name="<%= question.questionid %>">
<fieldset form="<%=question.questionid %>">
<legend>
<%= question.questiontext %>
</legend>
<div>
<input type="radio" id="answer1" name="answer" value="<%= question.answer1 %>" checked />
<label for="answer1">
<%= question.answer1 %>
</label>
</div>
<div>
<input type="radio" id="answer2" name="answer" value="<%= question.answer2 %>" />
<label for="answer2">
<%= question.answer2 %>
</label>
</div>
<div>
<input type="radio" id="answer3" name="answer" value="<%= question.answer3 %>" />
<label for="answer3">
<%= question.answer3 %>
</label>
</div>
<div>
<input type="radio" id="answer4" name="answer" value="<%= question.answer4 %>" />
<label for="answer4">
<%= question.answer4 %>
</label>
</div>
<h2>
מספר שאלה לפי מאגר שאלות: <%= question.questionid %>
</h2>
</fieldset>
</form>
<% }) %>
<button type="submit">שלח תשובה</button>
<!-- <form class="container" action="/submit" method="post">
<div class="horizontal-container">
<h3>
Total Score:
<span id="score">
</span>
</h3>
</div>
</form>
<script>
var wasCorrect = "<%= locals.wasCorrect %>";
console.log(wasCorrect)
if (wasCorrect === "false") {
alert('Game over! Final best score: <%= locals.totalScore %>');
document.getElementById("app").innerHTML = '<a href="/" class="restart-button">Restart</a>'
}
</script> -->
</body>
</html>
```
|
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 have the following controller's action:
```C#
[HttpPost("api/v1/addProduct")]
[Consumes("multipart/form-data")]
public Task<ProductDto?> AddProduct([FromForm] ProductRequest request, CancellationToken cancellationToken)
{
return _productService.AddProduct(request, cancellationToken);
}
```
and the following model:
```C#
public class ProductRequest
{
[Required]
public string Title { get; set; }
public string? Description { get; set; }
[Required]
public string PreviewDescription { get; set; }
[Required]
public IFormFile PreviewImage { get; set; }
public IFormFile[]? Images { get; set; }
[Required]
public int[] CategoryIds { get; set; }
public bool? IsAvailable { get; set; }
}
```
I successfully sent data to the server (I use formData):
[![enter image description here][1]][1]
But by some reason, I see the following in the debugger:
[![enter image description here][2]][2]
Everything is ok with `previewImage` but where are `images`? Why `previewImage` is here, but there is no `images`? I sent them in exactly the same way as I sent `previewImage`. We can see it at the request payload screen. Help me please to figure it out.
**UPDATE**
I tried `IFormFileCollection`:
[![enter image description here][3]][3]
No result.
[1]: https://i.stack.imgur.com/N6lJx.png
[2]: https://i.stack.imgur.com/oruB8.png
[3]: https://i.stack.imgur.com/3pxB9.png |
This is well defined in the [`vectorize`](https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html) documentation:
> If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs.
If you don't want this, you can define `otypes`:
```
import numpy
def test(x):
print(x)
test = numpy.vectorize(test, otypes=[float])
test([1,2,3])
1
2
3
```
In any case, be aware that `vectorize` is just a convenience around a python loop. If you need to have side effects you might rather want to use an explicit python loop. |
I'm encountering difficulties while trying to post form data, including file uploads, to MongoDB using Multer and Express. Although the files are successfully uploaded to Firebase Storage, the form data is not being posted to MongoDB. Additionally, my MongoDB connection seems to be established without any issues. Could anyone provide insights into potential solutions or debugging steps to resolve this issue? Any help would be greatly appreciated.
User Model:
```
User
+-----------------------------------------+
| User |
+-----------------------------------------+
| _id: ObjectId |
| firstname: String (required, min: 2, |
| max: 50) |
| lastname: String (required, min: 2, |
| max: 50) |
| email: String (required, max: 50, |
| unique: true) |
| password: String (required, min: 6) |
| picturepath: String (default: "") |
| friends: Array (default: []) |
| location: String |
| occupation: String |
| viewedprofile: Number |
| impression: Number |
| createdAt: Date |
| updatedAt: Date |
+-----------------------------------------+
```
index.js (Server):
```
const __filename=fileURLToPath(import.meta.url);
const __dirname= path.dirname(__filename);
dotenv.config();
const app=express();
app.use(express.json())
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({policy:"cross-origin"}));
app.use(morgan("common"));
app.use(bodyParser.json({limit:"30mb",extended:true}));
app.use(bodyParser.urlencoded({limit:"30mb",extended:true}));
app.use(cors());
app.use("/assets",express.static(path.join(__dirname,'public/assets')));
/* File Storage */
const Storage = multer.memoryStorage(); // Use memory storage for handling files in memory
const upload = multer({ storage: Storage });
/*Routes With Files*/
app.post("/auth/register", upload.single("picture"), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({erro:'No files were uploaded.'});
}
const bucket = firebaseStorage;
const file = bucket.file(req.file.originalname);
const metadata = {
metadata: {
contentType: req.file.mimetype,
},
};
await file.save(req.file.buffer, metadata);
const [url] = await file.getSignedUrl({ action: 'read', expires: '01-01-2100' });
const picturepath = url;
res.status(201).json({ picturepath });
} catch (error) {
console.error('Error uploading file to Firebase Storage:', error);
res.status(500).json({ error: 'Internal server error' });
}
},register);
/*Routes */
app.use("/auth",authRoutes);
app.use("/users",userRoutes);
app.use("/posts",postRoutes)
/*MONGOOSE SETUP */
const PORT=process.env.PORT || 6001;
mongoose.connect(process.env.MONGO_URL)
.then(()=>{
app.listen(PORT,()=>console.log(`Server Started`));
// User.insertMany(users);
// Post.insertMany(posts);
})
.catch((error)=>console.log(`${error} did not connect`));
```
Form.jsx (frontend):
```
import { useState } from "react";
import {
Box,
Button,
TextField,
useMediaQuery,
Typography,
useTheme,
} from "@mui/material";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import { Formik } from "formik";
import * as yup from "yup";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setLogin } from "../../state";
import Dropzone from "react-dropzone";
import FlexBetween from "../../components/FlexBetween";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { imageDB } from "../../firebaseConfig";
const registerSchema = yup.object().shape({
firstname: yup.string().required("required"),
lastname: yup.string().required("required"),
email: yup.string().email("invalid email").required("required"),
password: yup.string().required("required"),
location: yup.string().required("required"),
occupation: yup.string().required("required"),
picture: yup.string().required("required"),
});
const loginSchema = yup.object().shape({
email: yup.string().email("invalid email").required("required"),
password: yup.string().required("required"),
});
const initialValuesRegister = {
firstname: "",
lastname: "",
email: "",
password: "",
location: "",
occupation: "",
picture: "",
};
const initialValuesLogin = {
email: "",
password: "",
};
const Form = () => {
const [pageType, setPageType] = useState("login");
const [alertMessage, setAlertMessage] = useState("");
const { palette } = useTheme();
const dispatch = useDispatch();
const navigate = useNavigate();
const isNonMobile = useMediaQuery("(min-width:600px)");
const isLogin = pageType === "login";
const isRegister = pageType === "register";
const handleFileUpload = async (file) => {
try {
if (!file) {
throw new Error("File is undefined or null");
}
const storageRef = ref(imageDB); // Use imageDb instead of storage
const fileRef = ref(storageRef, `Users/${file.name}`);
await uploadBytes(fileRef, file);
const downloadURL = await getDownloadURL(fileRef);
console.log(downloadURL);
return downloadURL;
} catch (error) {
console.error("Error uploading image:", error);
throw error;
}
};
const register = async (values, onSubmitProps) => {
try {
values.email = values.email.toLowerCase();
const imageURL = await handleFileUpload(values.picture);
const formData = new FormData();
for (let key in values) {
formData.append(key, values[key]);
}
formData.append("picturepath", imageURL);
for (const entry of formData.entries()) {
console.log(entry);
}
const savedUserResponse = await fetch(
"http://localhost:3001/auth/register",
{
method: "POST",
body: formData,
}
);
const savedUser = await savedUserResponse.json();
console.log("SAVED USER:", savedUser.picturepath);
if (savedUser.error) {
console.log(savedUser.msg);
setAlertMessage(savedUser.msg);
} else {
onSubmitProps.resetForm();
setPageType("login");
}
} catch (error) {
console.error("Error registering:", error);
setAlertMessage(error.message || "Failed to register");
}
};
const login = async (values, onSubmitProps) => {
const loggedInResponse = await fetch("http://localhost:3001/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
const loggedIn = await loggedInResponse.json();
onSubmitProps.resetForm();
if (loggedIn.msg) {
setAlertMessage(loggedIn.msg);
} else {
dispatch(
setLogin({
user: loggedIn.user,
token: loggedIn.token,
})
);
navigate("/home");
}
};
const handleFormSubmit = async (values, onSubmitProps) => {
if (isLogin) await login(values, onSubmitProps);
if (isRegister) await register(values, onSubmitProps);
};
return (
<Formik
onSubmit={handleFormSubmit}
initialValues={isLogin ? initialValuesLogin : initialValuesRegister}
validationSchema={isLogin ? loginSchema : registerSchema}
>
{({
values,
errors,
touched,
handleBlur,
handleChange,
handleSubmit,
setFieldValue,
resetForm,
}) => (
<form onSubmit={handleSubmit}>
<Box
display="grid"
gap="30px"
gridTemplateColumns="repeat(4, minmax(0, 1fr))"
sx={{
"& > div": { gridColumn: isNonMobile ? undefined : "span 4" },
}}
>
{isRegister && (
<>
<TextField
label="First Name"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstname}
name="firstname"
error={
Boolean(touched.firstname) && Boolean(errors.firstname)
}
helperText={touched.firstname && errors.firstname}
sx={{ gridColumn: "span 2" }}
/>
<TextField
label="Last Name"
onBlur={handleBlur}
onChange={handleChange}
value={values.lastname}
name="lastname"
error={Boolean(touched.lastname) && Boolean(errors.lastname)}
helperText={touched.lastname && errors.lastname}
sx={{ gridColumn: "span 2" }}
/>
<TextField
label="Location"
onBlur={handleBlur}
onChange={handleChange}
value={values.location}
name="location"
error={Boolean(touched.location) && Boolean(errors.location)}
helperText={touched.location && errors.location}
sx={{ gridColumn: "span 4" }}
/>
<TextField
label="Occupation"
onBlur={handleBlur}
onChange={handleChange}
value={values.occupation}
name="occupation"
error={
Boolean(touched.occupation) && Boolean(errors.occupation)
}
helperText={touched.occupation && errors.occupation}
sx={{ gridColumn: "span 4" }}
/>
<Box
gridColumn="span 4"
border={`1px solid ${palette.neutral.medium}`}
borderRadius="5px"
p="1rem"
>
<Dropzone
acceptedFiles=".jpg,.jpeg,.png"
multiple={false}
onDrop={(acceptedFiles) =>
setFieldValue("picture", acceptedFiles[0])
}
>
{({ getRootProps, getInputProps }) => (
<Box
{...getRootProps()}
border={`2px dashed ${palette.primary.main}`}
p="1rem"
sx={{ "&:hover": { cursor: "pointer" } }}
>
<input {...getInputProps()} />
{!values.picture ? (
<p>Add Picture Here</p>
) : (
<FlexBetween>
<Typography>{values.picture.name}</Typography>
<EditOutlinedIcon />
</FlexBetween>
)}
</Box>
)}
</Dropzone>
</Box>
</>
)}
<TextField
label="Email"
onBlur={handleBlur}
onChange={handleChange}
value={values.email}
name="email"
error={Boolean(touched.email) && Boolean(errors.email)}
helperText={touched.email && errors.email}
sx={{ gridColumn: "span 4" }}
/>
<TextField
label="Password"
type="password"
onBlur={handleBlur}
onChange={handleChange}
value={values.password}
name="password"
error={Boolean(touched.password) && Boolean(errors.password)}
helperText={touched.password && errors.password}
sx={{ gridColumn: "span 4" }}
/>
</Box>
{/* BUTTONS */}
<Box>
{alertMessage && (
<Typography
variant="body2"
sx={{ color: "red", mb: 2 , mt:1}}
>{alertMessage}</Typography>
)}
<Button
fullWidth
type="submit"
sx={{
m: "2rem 0",
p: "1rem",
backgroundColor: palette.primary.main,
color: palette.background.alt,
"&:hover": { color: palette.primary.main },
}}
>
{isLogin ? "LOGIN" : "REGISTER"}
</Button>
<Typography
onClick={() => {
setPageType(isLogin ? "register" : "login");
resetForm();
}}
sx={{
textDecoration: "underline",
color: palette.primary.main,
"&:hover": {
cursor: "pointer",
color: palette.primary.light,
},
}}
>
{isLogin
? "Don't have an account? Sign Up here."
: "Already have an account? Login here."}
</Typography>
</Box>
</form>
)}
</Formik>
);
};
export default Form;
```
I implemented a form using React and used the react-dropzone library for file uploads. Upon form submission, I expected the file is been uploaded to file storage and also getting picturepath as imageurl.
Not getting any error in terminal as well as console but unable to see entry in db.
Please check my register function . |
LISTEN I EXPERIENCED A SIMILAR SITUATION BEFORE EVEN THOUGH I ALREADY SET MY IP: 0.0.0.0/0
just log in to Mongo Atlas then go to the network option on the left side it will be towards the bottom of the menu.
Just change your IP use choose my current IP option.
[![Image to navgate][1]][1]
[1]: https://i.stack.imgur.com/ha9Td.png |
{"OriginalQuestionIds":[77794933],"Voters":[{"Id":12738750,"DisplayName":"lorem ipsum","BindingReason":{"GoldTagBadge":"swiftui"}}]} |
Can an RPC result be included in a Supabase select function in Flutter for Data Modeling? |
|flutter|supabase|supabase-flutter| |
The following code (at [Playground here](https://www.typescriptlang.org/play?#code/MYGwhgzhAEDKCuAHApgJwMLigKAN7ekOgDN4A7YACjFQHMAuaSgW2UYBcALASwgEpoAXgB80AG4B7bgBMB+Iguipk7eKjLQatAkQC+2fdlCQYAETTcxyaZhPRkAD3bIy0mAhQYsEPDsJiabjAAIxBkIWguXgA6UgpKSgERaFxdPgBuA2wjCTIIdmgJYIArRg80WygIsmQAd2hzVEtrSohE9KA)) gives an error `Type 'DerivedClass' is not assignable to type 'SuperClass'` at the variable `obj`. How is this possible, when `DerivedClass extends SuperClass`? Does this contradict Liskov substitution principle?
```typescript
class SuperClass
{
func(arg: (me: this) => void) {
return arg
}
}
class DerivedClass extends SuperClass
{
variable = this.func(() => {});
}
const obj: SuperClass = new DerivedClass();
``` |
For example if the experimental input data like T=300 C, time= 60 min, Catalyst= Type A gives 70% biodiesel yield, I want the ANN model to predict what the input parameters to achieve 90 or even 95% biodiesel yield?
I have not found a way to solve it. |
How to predict input parameters from target parameter in a machine learning model? |
|python|tensorflow|machine-learning|keras| |
null |
The following:
```
interface IThing { virtual string A => "A"; }
```
Is the so called [default interface method][1] and virtual as far as I can see actually does nothing because:
> The `virtual` modifier may be used on a function member that would otherwise be implicitly `virtual`
I.e. it just an explicit declaration of the fact that **interface** method is virtual since the language team decided to not restrict such things.
See also the [Virtual Modifier vs Sealed Modifier][2] part of the spec:
> Decisions: Made in the LDM 2017-04-05:
> - non-`virtual` should be explicitly expressed through `sealed` or `private`.
> - `sealed` is the keyword to make interface instance members with bodies non-`virtual`
> - We want to allow all modifiers in interfaces
> - ...
Note that default implemented `IThing.A` is not part of the `Thing`, hence you can't do `new Thing().A`, you need to cast to the interface first.
If you want to override the `IThing.A` in the `Thing2` then you can implement the interface directly:
```
class Thing2: Thing, IThing
{
public string A => "!";
}
Console.WriteLine(((IThing)new Thing()).A); // Prints "A"
Console.WriteLine(((IThing)new Thing2()).A); // Prints "!"
```
Aother way would be declaring `public virtual string A` in the `Thing` so your current code for `Thing2` works:
```
class Thing: IThing
{
public virtual string A => "A";
}
class Thing2: Thing
{
public override string A => "!";
}
```
To understand meaning of `sealed`/`virtual` identifiers in interfaces you can create a second interface:
```
interface IThing { string A => "A"; }
interface IThing2 : IThing { string IThing.A => "B"; }
class Thing : IThing2 {}
Console.WriteLine(((IThing)new Thing()).A); // Prints "B"
```
While if you declare `IThing.A` as `sealed` then `IThing2` will not compile:
```csharp
interface IThing { sealed string A => "A"; }
interface IThing2 : IThing
{
// Does not compile:
// string IThing.A => "B";
}
class AntoherThing : IThing
{
// Does not compile too:
string IThing.A => "B";
}
```
Also check out the https://stackoverflow.com/q/4470446/2501279 linked by [wohlstad][3] in the comments.
[1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
[2]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#virtual-modifier-vs-sealed-modifier
[3]: https://stackoverflow.com/users/18519921/wohlstad |
To pass data from child to parent component by using callback function in prop in parent component and then pass data from child component by calling these function.
// Child
const Button = ({ text, onButtonClick }) => {
return <button onClick={() => onButtonClick("hello")}>{text}</button>;
};
// Parent
const App = () => {
const onButtonClick = (value) => {
console.log("OnButtonClick in parent", value);
};
return (
<div>
App <Button text="Add" onButtonClick={onButtonClick} />
</div>
);
};
export default App;
|
It would be helpful to include some comments in code to explain what each section does. <br>
From what I see working through the code, you are first adding the Headers from your original Sheet 'Session-2024' to a new Workbook Sheet `sheet_dcfc1` with name 'Sheet' (then reading back / printing these headers). <br>
Next follows a loop looking for a cell with value "PP/ Charger 2"<br>
There is no mention of this part in your post and the table provided does not include columns/rows with this value. Also the loop is wrong.<br>
```
for j in range(1, max_row_og +1):
for i in range(1, max_col_og +1):
c = cpsd_s1.cell(row=j, column=1)
if (c.value == "PP/ Charger 2"):
k = cpsd_s1.cell(row=j, column=i)
sheet_dcfc1.cell(row=j, column=i).value = k.value
```
You are setting j to count the rows in the origin worksheet and i to count the columns then the line `c = cpsd_s1.cell(row=j, column=1)` . So this means it always looks in the same column (A) due to 'column=1'. Presumably this should be 'column=i' <br>
If this is changed, then you're now looking in every cell from A1 to K11 (using your example data table). Is this value, "PP/ Charger 2" expected to be randomly in any column including those you have provided? If it is expected to be in a specific column then you should iterate just that column and not the whole used range. Please provide details on what/where/when of this value, as its existence seems important to the next sections. Without it the new worksheet will just contain the headers.<br>
<br>
If the previous section does find that "PP/ Charger 2" value it copies that value to the **same** cell in the new Sheet. <br>
The code then runs a delete which seems aims to remove empty rows given that presumably "PP/ Charger 2" could be on any row. While this delete achieves that it also removes the Headers previously written. If it is only necessary write that value once down the Sheet for each occurrence in the original Sheet then maybe use Openpyxl 'append' so each will be written to the next unused row. Either way these value can be added to the new sheet row by row without the need to then delete empty rows. The exact implementation would depend on where this text is expected to be found and how it should be written to the new Sheet.
Then the code loops a list of all cells in all rows looking specifically in row 9 for a value of 0, `row[9].value == 0):` <br>
Presumably this is looking for the 0 value in the Energy column. However you state *Energy is in column 11* or Column 'K' whereas row[9] is Column 'J'. And again why select the whole range and not just loop through Column K only?<br>
Then the code looking for a value of 0, but this is the new Sheet `range_x = enumerate(sheet_dcfc1.iter_rows())` , 'sheet_dcfc1' and all you have written to it is the Headers and the value "PP/ Charger 2" when it occurs, and then deleted the headers. There are no cells with a value of 0 ...
It seems may be when you find the value "PP/ Charger 2" it's the whole row you want to copy across not just that cell.
You need to better explain what your code is supposed to do, what the expected result should be.
|
I am totally new to angular. I have angular UI where we upload a `.csv` file with 6 columns and their respective data, so before I invoke .net API, I need to change the data in the 1st column: if a value consists of 9 digits then we need to change it to 10 digits just by prefixing with ‘0’. For example, if the value is ‘609878837’ it has to be changed to ‘0609878837’.
**Sample Excel Data**
UserNumber 876876876
DESCRIPTION Hello
AccountNumber State Current Premium Interest Total
1207614641 FL GG 200.51 24.58 225.09
217614234 FL GG 474.65 51.77 526.42
[Actual Excel sheet Image][1]
Here is my Angualr code which handles Upload and calls the .net API. Kindly let me know how do i change to 10 digits account numbers after checking the length
My Code:
```
<input #fileUpload type="file" class="file-upload" name="fileUpload" id="fileUpload" accept=".xlsx,.xls,.csv" required (change)="onFileChange($event)">
<button (click)="UploadFile(form.value)" type="button" mat-raised-button color="primary" [disabled]="!fileSelected">Upload</button>
onFileChange(event: any): void {
this.file = event.target.files[0];
if (this.file) {
console.log("this.file.type: " + this.file.type);
const fileName = this.file.name;
this.fileSelected = true;
this.invalidFileType = false;
this.invalidFileSize = false;
this.invalidFileRecords = false;
let file: File = this.file;
var value;
const fileReader = new FileReader();
fileReader.onload = (e: any) => {
value = e.target.result;
this.data = value;
var rows = e.target.result.split("\n");
if (rows.length > 6003) {
LoggerService.error(`upload records less than 6K.`, true, true);
}
};
fileReader.readAsBinaryString(this.file);
}
}
UploadFile(filevalue) {
const reqbody = {
filename: this.file?.name,
destinationPath: '',
lines: this.data.replace(/[^a-zA-Z0-9,\n\r.'" ]/g, "").split('\r\n')
};
var route = "CallNETAPI";
this.dataService.post(reqbody, route).subscribe(
(data: any[]) => {
console.log("Response data: " + data);
LoggerService.success(`File successfully uploaded to server`, true, false);
this.responseData = data;
},
(error: Response) => {
this.displayError = true;
this.errorText = `Error from CallNETAPI API service ${error.status}`;
});
}
```
[1]: https://i.stack.imgur.com/mynhP.png |
|javascript|angular| |
You will need to first create a `JSON` file with the actions mentioned. Below is an example taken from [link][1]:
```
[{
"Type": "authenticate-cognito",
"AuthenticateCognitoConfig": {
"UserPoolArn": "arn:aws:cognito-idp:region-code:account-id:userpool/user-pool-id",
"UserPoolClientId": "abcdefghijklmnopqrstuvwxyz123456789",
"UserPoolDomain": "userPoolDomain1",
"SessionCookieName": "my-cookie",
"SessionTimeout": 3600,
"Scope": "email",
"AuthenticationRequestExtraParams": {
"display": "page",
"prompt": "login"
},
"OnUnauthenticatedRequest": "deny"
},
"Order": 1
},
{
"Type": "forward",
"TargetGroupArn": "arn:aws:elasticloadbalancing:region-code:account-id:targetgroup/target-group-name/target-group-id",
"Order": 2
}]
```
In this, you will need to fill the lines `UserPoolArn`, `UserPoolClientId`, `UserPoolDomain`, `TargetGroupArn` and optinally `SessionCookieName` to meet your deployment. Once all is filled, below CLI will create a new HTTPS listener with Auth config:
```
aws elbv2 create-listener \
--load-balancer-arn $ALB_ARN \
--protocol HTTPS \
--port 443 \
--certificates CertificateArn=$CERT_ARN \
--default-actions file://config.json
```
`config.json` is the file with the settings
[1]: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html#configure-user-authentication |
Error when trying to execute a binary compiled in a Kali Linux machine on an Ubuntu system |
|linux|ubuntu|security| |
null |
I have set up harbor behind an nginx reverse-proxy, and when I push docker images to it, I get this error
```
5bfe9e7b484e: Retrying in 1 second
b59ac5e5fd8f: Retrying in 1 second
3a69b46a1ce6: Retrying in 1 second
473959d9af57: Retrying in 1 second
fe56a5801ec1: Retrying in 1 second
1f34686be733: Waiting
691621f13fd5: Waiting
bf27900f6443: Waiting
01fd502f0720: Waiting
first path segment in URL cannot contain colon
```
What could be causing this error? There is no error in nginx or harbor ontainer. Thanks! |