instruction stringlengths 0 30k ⌀ |
|---|
Array related question, cant find the pattern |
|arrays| |
null |
So first of all what we're talking about here is not strictly the CQRS pattern, but designing of the domains. Where does the "user" end, and where does the "student" (who's also a "user") start. Encapsulation of logic, stuff like that. Domain-driven development says "hello" :)
First things first.
> Right now what I am doing is, in createStudent handler, I have injected repositories for user, userAddresses and userContacts and using them in the handler to get/create/update records related to user, address or contacts.
I'm pretty sure this can be handled with one repository only. If you define relations for user (1:M addresses), any mutation of the data layer can be done with cascade updates:
```typescript
let user = await this.userRepo.getOne(userId);
const newAddress = new Address({...});
user.addresses.push(newAddress);
await this.userRepo.save(user);
```
(of course, that's in pseudocode).
I'd think of a general rule to keep one repository, always, per CQRS handler. If something cannot be done with one repository, then it means the scope of that handler is too vast (leaking boundaries, something that's of user's shouldn't be doing direct mutations on address, which is a separate domain).
---
> If I switch to a microservices approach where the user and student will be different microservices with different databases, I will not be able to inject the repository
Why different _databases_, by default? You can have your microservices interacting with your one and only data layer, and that's still valid, unless there are certain reasons for separating databases. You can have your microservices doing their stuff and not interacting with data layer at all, but receiving everything over messaging bus, and over messaging bus responding to the main app that's responsible for data handling. But still, if you inject repository for _one_ entity or schema (if you're using eg. `mongoose`), and define your relations well, you can still inject a single repository (recommended, definitely) to a microservice, and cascading will work.
But if you will say sth like "but I need to have more than one repository", then it means that domain boundaries should be most likely reconsidered :) |
Selenium error: java.awt.AWTException: headless environment |
|java|selenium-webdriver|selenium-chromedriver|devtools| |
null |
|active-directory|windows-server|papercut| |
You could try this approach using a helper `struct FontModel` to
hold the font results and make it easier to use in the `ForEach` loop.
struct ContentView: View {
var body: some View {
AddFontStyleItems(DrawModel(curFont: "Helvetica"))
}
}
// for testing
struct DrawModel {
var curFont: String
}
struct FontModel: Identifiable { // <--- here
let id = UUID()
var fontType: String
var fontName: String
var fontWeight: Int
var fontTrait: Int
init(_ arr: [Any]) {
if arr.count < 5 {
self.fontType = arr[0] as? String ?? ""
self.fontName = arr[1] as? String ?? ""
self.fontWeight = arr[2] as? Int ?? 0
self.fontTrait = arr[3] as? Int ?? 0
} else {
self.fontType = ""
self.fontName = ""
self.fontWeight = 0
self.fontTrait = 0
}
}
}
struct AddFontStyleItems: View {
var dm: DrawModel
@State private var fontStyles: [FontModel] = [] // <--- here
init(_ dm: DrawModel) { self.dm = dm }
var body: some View {
ForEach(fontStyles) { curStyle in // <--- here
Button(curStyle.fontName) {
print("---> Style: \(curStyle)")
}
}
.onAppear {
fontStyles = getFontStyles(for: dm.curFont) // <--- here
}
}
func getFontStyles(for fontFamily: String) -> [FontModel] {
var results: [FontModel] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
results.append(FontModel(member))
}
}
return results
}
}
EDIT-1:
if just want an array of Strings
struct AddFontStyleItems: View {
var dm: DrawModel
@State private var fontStyles: [String] = [] // <--- here
init(_ dm: DrawModel) { self.dm = dm }
var body: some View {
ForEach(fontStyles, id: \.self) { curStyle in // <--- here
Button(curStyle) {
print("---> Style: \(curStyle)")
}
}
.onAppear {
fontStyles = getFontStyles(for: dm.curFont) // <--- here
}
.onChange(of: dm.curFont) { // <--- here
fontStyles = getFontStyles(for: dm.curFont)
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
Or simply:
struct AddFontStyleItems: View {
var dm: DrawModel
var body: some View {
VStack {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
print("---> dm: \(dm) Style: \(curStyle)")
}
}
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
EDIT-2:
Here is my full test code that shows, changing the `curFont` of the `drawModel` in the parent view,
changes the `AddFontStyleItems` view displaying the Font Styles. Tested on MacOS 14.4.
struct ContentView: View {
@State private var drawModel = DrawModel(curFont: "Helvetica") // <--- here
var body: some View {
VStack {
Button("Change curFont") {
drawModel.curFont = "Times" // <--- here
}.padding(20)
Divider()
Text(drawModel.curFont).foregroundStyle(.red)
Divider()
AddFontStyleItems(dm: drawModel)
Spacer()
}
}
}
struct AddFontStyleItems: View {
var dm: DrawModel
var body: some View {
VStack {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
print("---> dm: \(dm) Style: \(curStyle)")
}
}
}
}
func getFontStyles(for fontFamily: String) -> [String] {
var results: [String] = []
if let members = NSFontManager.shared.availableMembers(ofFontFamily: fontFamily) {
for member in members {
if member.count > 1 {
results.append(member[1] as? String ?? "")
}
}
}
return results
}
}
struct DrawModel: Identifiable {
let id = UUID()
var curFont: String
}
EDIT-3:
try this approach to `select` the `font` and the `style` for your `DrawModel`.
Example code:
struct ContentView: View {
@State private var drawModel = DrawModel(curFont: "Helvetica") // <--- here
var body: some View {
VStack {
Text(drawModel.curFont).foregroundStyle(.red)
Divider()
AddFontItems(dm: $drawModel) // <--- here $
Spacer()
}
}
}
struct AddFontItems: View {
@Binding var dm: DrawModel // <--- here
var uniqueFontFamilies = NSFontManager.shared.availableFontFamilies //.unique()
var body: some View {
HStack {
ScrollView {
ForEach(uniqueFontFamilies, id: \.self) { curFont in
Button(curFont) {
dm.curFont = curFont
print("---> curFont: \(curFont)")
}
}
}
Spacer()
ScrollView {
ForEach(getFontStyles(for: dm.curFont), id: \.self) { curStyle in
Button(curStyle) {
dm.curFont = dm.curFont + " " + curStyle
print("Set Style:\t \(curStyle)")
}
}
}
}
}
func getFontStyles(for font: String) -> [String] {
var justStyles: [String] = []
if let fontInfo = NSFontManager.shared.availableMembers(ofFontFamily: font ) {
for curFontInfo in fontInfo {
if curFontInfo.count > 1 {
justStyles.append(curFontInfo[1] as? String ?? "")
}
}
}
return justStyles
}
}
|
while in a specific page i need to know the name of the page, which was set by named routes. i could know with normal 'context', but i couldn't do using global context.
my code:
```
// ModalRoute.of(context)?.settings.name with global context, trying!
import 'package:flutter/material.dart';
void main(){runApp(const MyApp()); }
class MyApp extends StatelessWidget {
const MyApp({super.key});
static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); // <---
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: MyApp.navigatorKey, // set property // <---
//home: const HomeScreen(),
initialRoute: '/home',
routes: { // ---------------> hash routing
'/home':(context)=> const HomeScreen(),
'/details':(context)=> const DetailsScreen(),
},
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
//MyApp.navigatorKey.currentState!.context =context,
return Scaffold(
appBar: AppBar(title: const Text('Home Page'),backgroundColor: Colors.blue,),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: (){
print("print context: ${MyApp.navigatorKey.currentContext}"); //print context: Navigator-[LabeledGlobalKey<NavigatorState>#a6af1](dependencies: [HeroControllerScope, UnmanagedRestorationScope], state: NavigatorState#d0a98(tickers: tracking 1 ticker))
},
child: const Text('button 1.1')
),
ElevatedButton(
onPressed: (){
print(ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name ?? "Unknown"); //Unknown //or, MyApp.navigatorKey.currentState!.context
},
child: const Text('button 1.2')
),
ElevatedButton(
onPressed: (){
print("${ModalRoute.of(context)?.settings.name}"); //: /home
},
child: const Text('button 1.3')
),
ElevatedButton(
// onPressed: () {
// Navigator.push(context, MaterialPageRoute(
// settings: const RouteSettings(name: "/detailsScreen"),
// builder: (context)=> const DetailsScreen())
// );
// //Navigator.pushReplacement(context,MaterialPageRoute(builder: (context)=> const DetailsScreen()));
// },
onPressed: (){
Navigator.pushNamed(context, '/details');
},
child: const Text('go to details page'),
),
],
),
),
);
}
@override
void dispose() {
print("Dispose called");
super.dispose();
}
}
class DetailsScreen extends StatefulWidget {
const DetailsScreen({super.key});
@override
State<DetailsScreen> createState() => _DetailsScreenState();
}
class _DetailsScreenState extends State<DetailsScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Details Page'),
backgroundColor: Colors.blue,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: (){
print("print context: ${MyApp.navigatorKey.currentContext}"); //print context: Navigator-[LabeledGlobalKey<NavigatorState>#ebadf](dependencies: [HeroControllerScope, UnmanagedRestorationScope], state: NavigatorState#5dfff(tickers: tracking 2 tickers))
},
child: const Text('button 2.1')
),
ElevatedButton(
onPressed: (){
print(ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name ?? "Unknown"); //Unknown
},
child: const Text('button 2.2')
),
ElevatedButton(
onPressed: (){
print("${ModalRoute.of(context)?.settings.name}");
},
child: const Text('button 2.3') //: /details
),
],
),
),
);
}
}
```
in above example button 1.2 and 2.2 should print their corresponding page name.
looks like button 1.3 and 2.3 are printing as expected. but
```
ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name
is sending null value.
``` |
This is an android project and I need to load a website in a webview.
And one more request here is the website needs to be loaded in a iframe.
This is done by the following step:
1. create a webview
2. I have a sample html file
3. I load my sample html file
4. I call `wewbview.loadHTMLString(sampleHtmlString, "")` to load the site from string;
Sample html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
</style>
</head>
<body>
<script>
document.addEventListener('touchstart', function(event) {
console.log("document touchstart");
});
</script>
</body>
</html>
```
And webview show all good on device also i can see touch event triggered.
___
Then I will add the iframe part:
1. User input a url to load for example: "https://www.facebook.com"
2. Still I load my sample html file
3. Then I replace the PLACE HOLDER in sample file to the one user input for example: `"https://www.facebook.com"`
4. Then call `wewbview.loadHTMLString(sampleHtmlString, "")`;
Updated sample html:
``` html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.webview-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body>
<div class="webview-container" id="webview-container">
</div>
<script>
function loadWebView(url) {
var iframe = document.createElement('iframe');
iframe.src = url;
document.getElementById('webview-container').innerHTML = '';
document.getElementById('webview-container').appendChild(iframe);
iframe.onload = function() {
console.log("iframe onload");
};
}
document.addEventListener('touchstart', function(event) {
console.log("document touchstart");
});
loadWebView('https://www.example.com');
</script>
</body>
</html>
```
I can see the site loaded in iframe correctly but this time touchstart not trigggered when touched.
I searched few posts then tried:
``` javascript
function loadWebView(url) {
var iframe = document.createElement('iframe');
iframe.src = url;
document.getElementById('webview-container').innerHTML = '';
document.getElementById('webview-container').appendChild(iframe);
iframe.onload = function() {
console.log("iframe onload");
iframe.contentWindow.document.addEventListener('touchstart', function(event) {
console.log("iframe touchstart");
});
};
}
```
But still not working and I am getting the error in console:
```
Uncaught SecurityError: Failed to read a named property 'document' from 'Window':
Blocked a frame with origin "null" from accessing a frame with origin
"https://www.grandbrowser.com".
The frame requesting access has a protocol of "about",
the frame being accessed has a protocol of "https".
Protocols must match.", source: about:blank (41)
```
I also tried to remove the `"https:"` from the url according to this post:
https://stackoverflow.com/questions/21525511/the-frame-requesting-access-has-a-protocol-of-https-the-frame-being-accessed
But then the error in console is gone but the site will not load anymore.
___
Any advice on this issue will be appreciated, thanks in advance.
___
If is ok that if there will issues to use event listener inside a iframe in different domain.
The main feature I want to achieve here is to detect:
To detect touchstart / touchmove / touchend event and then add some css animation above the loaded website in iframe.
|
I am fetching birt report using RE API using birt engine in struts2, working fine but pagination
navbar is not showing on reports. please give suggestion with example in java.
I have .rptdesign File which is runnable file. i don't have IReportDocument type file. due to which "org.eclipse.birt.report.engine.api.EngineException: Render task is not finished." error occured. trying to achive pagination for birt report in struts2. please give any reference with example for pagination in birt report. |
how to get using RE API for birt report in struts2, trying to render birt report with pagination(paginated html) with navbar |
|javascript|java|pagination|struts2|birt| |
null |
I have a left section menu with a list that has pagination implemented. Now I am unsure as to how to handle a situation when the list updates and a new item is added to the top of the current list or multiple new items are added to the top of the list, how do I handle this scenario so that I am still on the selected item before the list was updated?
P.S.- Is it a good idea to recursively search for the order by changing pages when the selected item is not present in the updated list, or is there any better cost effective way to handle this. |
Handling selected item in a list with pagination on autoupdating the list in a react app ui |
|javascript|reactjs|user-interface|user-experience| |
null |
I have trained my model with
```python
import tensorflow as tf
import os
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose
from keras.layers import concatenate, BatchNormalization, Dropout, Lambda
from tensorflow.keras import backend as K
os.environ["SM_FRAMEWORK"] = "tf.keras"
import segmentation_models as sm
def jaccard_coef(y_true, y_pred):
y_true_flatten = K.flatten(y_true)
y_pred_flatten = K.flatten(y_pred)
intersection = K.sum(y_true_flatten * y_pred_flatten)
final_coef_value = (intersection + 1.0) / (K.sum(y_true_flatten) + K.sum(y_pred_flatten) - intersection + 1.0)
return final_coef_value
def multi_unet_model(n_classes=7, image_height=512, image_width=512, image_channels=3):
inputs = Input((image_height, image_width, image_channels))
source_input = inputs
c1 = Conv2D(16, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(source_input)
c1 = Dropout(0.2)(c1)
c1 = Conv2D(16, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c1)
p1 = MaxPooling2D((2,2))(c1)
c2 = Conv2D(32, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(p1)
c2 = Dropout(0.2)(c2)
c2 = Conv2D(32, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c2)
p2 = MaxPooling2D((2,2))(c2)
c3 = Conv2D(64, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(p2)
c3 = Dropout(0.2)(c3)
c3 = Conv2D(64, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c3)
p3 = MaxPooling2D((2,2))(c3)
c4 = Conv2D(128, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(p3)
c4 = Dropout(0.2)(c4)
c4 = Conv2D(128, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c4)
p4 = MaxPooling2D((2,2))(c4)
c5 = Conv2D(256, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(p4)
c5 = Dropout(0.2)(c5)
c5 = Conv2D(256, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c5)
u6 = Conv2DTranspose(128, (2,2), strides=(2,2), padding="same")(c5)
u6 = concatenate([u6, c4], axis=3)
c6 = Conv2D(128, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(u6)
c6 = Dropout(0.2)(c6)
c6 = Conv2D(128, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c6)
u7 = Conv2DTranspose(64, (2,2), strides=(2,2), padding="same")(c6)
u7 = concatenate([u7, c3], axis=3)
c7 = Conv2D(64, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(u7)
c7 = Dropout(0.2)(c7)
c7 = Conv2D(64, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c7)
u8 = Conv2DTranspose(32, (2,2), strides=(2,2), padding="same")(c7)
u8 = concatenate([u8, c2], axis=3)
c8 = Conv2D(32, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(u8)
c8 = Dropout(0.2)(c8)
c8 = Conv2D(32, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c8)
u9 = Conv2DTranspose(16, (2,2), strides=(2,2), padding="same")(c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(16, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(u9)
c9 = Dropout(0.2)(c9)
c9 = Conv2D(16, (3,3), activation="relu", kernel_initializer="he_normal", padding="same")(c9)
outputs = Conv2D(n_classes, (1,1), activation="softmax")(c9)
model = Model(inputs=[inputs], outputs=[outputs])
return model
# Percentages of data for each class
class_percentages = {
'urban_land': 7.8383,
'agriculture_land': 5.6154,
'rangeland': 9.6087,
'forest_land': 1.2616,
'water': 2.9373,
'barren_land': 1.0828,
'unknown': 0.00017716
}
# Calculate the inverse of percentages
inverse_percentages = {cls: 1 / pct for cls, pct in class_percentages.items()}
# Normalize weights
sum_inverse_percentages = sum(inverse_percentages.values())
weights = [weight / sum_inverse_percentages for cls, weight in inverse_percentages.items()]
print("Class Weights:", weights)
# Loss function
dice_loss = sm.losses.DiceLoss(class_weights=weights)
focal_loss = sm.losses.CategoricalFocalLoss()
total_loss = dice_loss + (1 * focal_loss)
# Metrics
metrics = ["accuracy", jaccard_coef]
with strategy.scope():
# Build the model
model = multi_unet_model()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
# Compile the model
model.compile(optimizer=optimizer, loss=total_loss, metrics=metrics)
# Print model summary
model.summary()
train_size = int(len(dataset)*0.8)
train_dataset = dataset.take(train_size)
val_dataset = dataset.skip(train_size)
train_dataset = train_dataset.batch(batch_size=16)
train_dataset = strategy.experimental_distribute_dataset(train_dataset)
val_dataset = val_dataset.batch(batch_size=16)
val_dataset = strategy.experimental_distribute_dataset(val_dataset)
history = model.fit(train_dataset,
validation_data=val_dataset,
epochs=3,
)
```
then I saved model with
```python
with strategy.scope():
model.save("new_3_epoch_model.h5")
```
and when I load the model with
```python
load_model("/kaggle/working/data/imgs/new_3_epoch_model.h5", custom_objects={"dice_loss_plus_1focal_loss": total_loss, "jaccard_coef":jaccard_coef})
```
it shows this error:
```python
TypeError Traceback (most recent call last)
Cell In[46], line 1
----> 1 load_model("/kaggle/working/data/imgs/new_3_epoch_model.h5", custom_objects={"dice_loss_plus_1focal_loss": total_loss, "jaccard_coef":jaccard_coef})
File /usr/local/lib/python3.10/site-packages/keras/src/saving/saving_api.py:183, in load_model(filepath, custom_objects, compile, safe_mode)
176 return saving_lib.load_model(
177 filepath,
178 custom_objects=custom_objects,
179 compile=compile,
180 safe_mode=safe_mode,
181 )
182 if str(filepath).endswith((".h5", ".hdf5")):
--> 183 return legacy_h5_format.load_model_from_hdf5(filepath)
184 elif str(filepath).endswith(".keras"):
185 raise ValueError(
186 f"File not found: filepath={filepath}. "
187 "Please ensure the file is an accessible `.keras` "
188 "zip file."
189 )
File /usr/local/lib/python3.10/site-packages/keras/src/legacy/saving/legacy_h5_format.py:155, in load_model_from_hdf5(filepath, custom_objects, compile)
151 training_config = json_utils.decode(training_config)
153 # Compile model.
154 model.compile(
--> 155 **saving_utils.compile_args_from_training_config(
156 training_config, custom_objects
157 )
158 )
159 saving_utils.try_build_compiled_arguments(model)
161 # Set optimizer weights.
File /usr/local/lib/python3.10/site-packages/keras/src/legacy/saving/saving_utils.py:145, in compile_args_from_training_config(training_config, custom_objects)
143 loss = _deserialize_nested_config(losses.deserialize, loss_config)
144 # Ensure backwards compatibility for losses in legacy H5 files
--> 145 loss = _resolve_compile_arguments_compat(loss, loss_config, losses)
147 # Recover metrics.
148 metrics = None
File /usr/local/lib/python3.10/site-packages/keras/src/legacy/saving/saving_utils.py:245, in _resolve_compile_arguments_compat(obj, obj_config, module)
237 """Resolves backwards compatiblity issues with training config arguments.
238
239 This helper function accepts built-in Keras modules such as optimizers,
(...)
242 this does nothing.
243 """
244 if isinstance(obj, str) and obj not in module.ALL_OBJECTS_DICT:
--> 245 obj = module.get(obj_config["config"]["name"])
246 return obj
TypeError: string indices must be integers
``` |
Can't load Keras model with Custom objects trained on Kaggle TPU |
If necessary add to `housing_labels['median_house_value']` all missing indices starting with `0` and maximal index and set to `0` first and then use advanced numpy indexing `b[idx]` with `np.median`:
maximal = housing_labels.index.max()
b = housing_labels['median_house_value'].reindex(range(maximal+1), fill_value=0).to_numpy()
out = np.median(b[idx], axis=1)
print (out) |
how to check google sing in token is expired or not |
hope you are well. My code is not working properly and I have no idea what is wrong or how to fix it.
I only know that when I add the numbers for a square or rectangle it shows that my shape is a parallelogram.
I have tried my code and the output is showing incorrectly.
I have also looked at you tube videos but nothing is helping me. Please advise as soon as possible.
```
<pre>
let side1 = prompt("Please enter the side of the shape");
let side2 = prompt("Please enter the side of the shape");
let side3 = prompt("Please enter the side of the shape");
let side4 = prompt("Please enter the side of the shape");
let corner1 = prompt("Please enter the corners of the shape");
let corner2 = prompt("Please enter the corners of the shape");
let corner3 = prompt("Please enter the corners of the shape");
let corner4 = prompt("Please enter the corners of the shape");
if (
side1 === side2 &&
side2 === side3 &&
side3 === side4 &&
((corner1 === corner2) === corner3) === corner4
) {
console.log(`The shape is a Square`);
} else if (
side1 === side3 &&
side2 === side4 &&
((corner1 < 90 && corner3 > 90 && corner2 < 90 && corner4 > 90) ||
(corner1 > 90 && corner3 < 90 && corner2 > 90 && corner4 < 90))
) {
console.log(`The shape is a Rhombus`);
} else if (
side1 === side3 &&
side2 === side4 &&
corner1 === corner3 &&
corner2 === corner4
) {
console.log(`The shape is a Parallelogram`);
} else if (
side1 === side3 &&
side2 === side4 &&
corner1 === corner2 &&
corner3 === corner4
) {
console.log(`The shape is a Rectangle`);
} else console.log("Your shape is weird");
<code>
``` |
Hello StackOverflow community,
I'm encountering issues while attempting to generate PDFs using Playwright within a Docker container for my AdonisJS application. Despite successful local development, I faced challenges with Dockerizing the project and encountered issues with TailwindCSS styles not rendering correctly within the container.
Here's a summary of the key points:
- I chose AdonisJS for its MVC architecture and seamless integration of
TailwindCSS and the Edge HTML templating engine.
- While the local setup worked smoothly, Dockerizing the project proved challenging,
with TailwindCSS styles not rendering correctly within the container.
- After extensive troubleshooting, I discovered that the only way to
properly generate PDF styles within the container was to use
TailwindCSS as a CDN in the template header.
- Additionally, the container crashed after the 20th request, with Playwright throwing a "browsertype.launch: timeout 180000ms exceeded" error. This mirrors an issue I previously encountered with Puppeteer and Express on an AWS-hosted server.
I've provided my Dockerfile, which was graciously shared by a community member, for reference:
[Playwright browser launch error in Docker container with AdonisJS project][1]
I'm struggling to understand the inner workings of these PDF libraries and how to optimize them effectively. I've read the documentation and explored possible optimizations, but my limited understanding may be hindering me from fully grasping how they function underneath and how to leverage them to their fullest potential
The error you're seeing, Error during navigation: page.setContent: Timeout 30000ms exceeded, indicates a timeout while setting the content of the page. Upon closer inspection, it seems that the error occurs during my initialization of the browser.
One potential reason for this issue could indeed be related to the contents of the HTML header. Specifically, the inclusion of external resources, such as fonts and stylesheets loaded via CDN, might be contributing to the delay in page rendering.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Signature fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Mali&family=Mrs+Saint+Delafield&family=The+Nautigal&display=swap"
rel="stylesheet">
<style>
html {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
h1 {
@apply text-3xl font-bold mb-3 mt-6;
}
.comment-container {
width: 100%;
border: 1px solid #E2E2E2;
border-radius: 0.25rem;
margin: 0.5rem 0;
}
.comment-header {
padding: 0.5rem;
background-color: #F3F4F6;
font-size: 8px;
}
.comment-content {
padding: 1rem;
}
.comment-reason,
.comment-text {
color: #545454;
}
.comment-text {
color: #141414;
font-size: 10px;
font-weight: bold;
}
</style>
<script
src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
<script>
tailwind.config = {
theme: {
extend: {
screens: {
print: { raw: 'print' },
screen: { raw: 'screen' },
},
},
},
important: true,
}
</script>
</head>
I'd appreciate any insights or guidance on how to address these issues effectively.
Thank you.
**Here's my service:**
import { inject } from '@adonisjs/core'
import { HttpContext } from '@adonisjs/core/http'
import { chromium } from 'playwright'
import { ConfigPdfInterface } from '../interface/config_pdf_interface.js'
// @ts-ignore
import { JSDOM } from 'jsdom'
@inject()
export default class PlaywrightService {
constructor(protected ctx: HttpContext) {}
async generatePdfPlaywright(
response: HttpContext['response'],
path: string,
documents: any,
config: ConfigPdfInterface,
isPagedJS: boolean
) {
// The first try/catch handles any errors that occur during browser launch and navigation to the webpage.
try {
const browser = await chromium.launch({
headless: true,
args: ['--no-sandbox']
})
const page = await browser.newPage()
// try-catch to handle potential errors during navigation and rendering
try {
await page.goto('about:blank', { waitUntil: 'domcontentloaded' })
const html = await this.ctx.view.render(`${path}`, documents)
await page.setContent(html, {
waitUntil: 'networkidle',
})
} catch (navigationError) {
console.error('Error during navigation:', navigationError)
}
// try-catch to handle potential errors when generating the PDF
try {
const pdfBuffer = await page.pdf(config)
console.log('isPagedJS', isPagedJS)
response.header('Content-type', 'application/pdf')
response.header('Content-Length', pdfBuffer.length)
response.status(200).send(pdfBuffer)
} catch (pdfError) {
console.error('Error generating PDF:', pdfError)
} finally {
await browser.close()
}
} catch (launchError) {
console.error('Error launching the browser:', launchError)
// response.status(500).send('Error launching the browser')
}
}
}
**Here's my controller**
async findOne({ request, response, view }: HttpContext) {
const requisitionModel = request.body()
const pathTemplate = 'inventory/requisitions/requisition'
const pathFooterTemplate = 'partials/footer_requisitions'
let footerHtml = await view.render(`${pathFooterTemplate}`, requisitionModel)
const optionsPdfConfig = {
format: 'A4',
margin: {
top: '30px',
right: '25px',
bottom: '100px',
left: '25px',
},
footerTemplate: footerHtml,
displayHeaderFooter: true,
printBackground: true,
}
await this.pdfService.generatePdfPlaywright(
response,
pathTemplate,
requisitionModel,
optionsPdfConfig,
false
)
}
router.post('/api/inventory/test', [RequisitionsController, 'testingfindOne'])
**Edit Question**
After reading several blogs discussing the issue, I understand that the problem lies in Playwright being unable to open the page within the minimum wait time. In other words, during that time, it couldn't finish loading the HTML resources. Most blogs suggest two solutions: either increasing the default timeout value or deactivating it by setting it to zero. The second option is not highly recommended.
However, I see these solutions applied when making a request to a webpage. In this case, I'm not making a request to any webpage. The resources are supposed to have been previously loaded when Playwright receives the content. It then opens the browser, sets the content of the previously loaded HTML as a string, and draws the PDF. If I understand correctly and this is how it works, then why does it encounter timeout issues when loading the PDF?
Reference: [Puppeteer timeout][2] [Dealing with timeouts in Puppeteer][3] [Constantly getting Navigation Timeout Error #782
][4] [node-js-puppeteer-how-to-set-navigation-timeout][5] [Common Errors and Solutions in Puppeteer][6] [Fix: navigation timeout of 30000 ms exceeded in puppeteer?][7]
[1]: https://stackoverflow.com/questions/78207733/playwright-browser-launch-error-in-docker-container-with-adonisjs-project
[2]: https://pocketadmin.tech/en/puppeteer-timeout/
[3]: https://releasecandidate.dev/posts/2022/puppeteer-timeouts/
[4]: https://github.com/puppeteer/puppeteer/issues/782
[5]: https://stackoverflow.com/questions/52163547/node-js-puppeteer-how-to-set-navigation-timeout
[6]: https://medium.com/@mansisingh_28001/common-errors-and-solutions-in-puppeteer-cd38b306cb1e
[7]: https://www.youtube.com/watch?v=8XjlRtq_1bQ |
Since you're discarding things after 11pm, we can do this:
```r
library(dplyr)
library(tidyr) # unnest
doseq <- function(z) {
z <- as.integer(z)
if (length(z) > 1) {
if (z[2] < z[1]) z[2] <- 23
z <- (1+z[1]):z[2]
}
z
}
df1 |>
mutate(time = lapply(strsplit(time, "-"), doseq)) |>
unnest(time) |>
print(n=99)
# # A tibble: 23 × 2
# time temperature
# <int> <int>
# 1 0 0
# 2 1 0
# 3 2 1
# 4 3 1
# 5 4 2
# 6 5 2
# 7 6 2
# 8 8 3
# 9 9 3
# 10 10 3
# 11 11 3
# 12 12 3
# 13 13 3
# 14 14 4
# 15 15 4
# 16 16 4
# 17 17 4
# 18 18 4
# 19 19 4
# 20 20 1
# 21 21 1
# 22 22 1
# 23 23 1
``` |
null |
If you try to implement a `ListStyle`, you can let Xcode add stubs for protocol conformance. You will then see, that the required functions all start with `_`. This is a clue, that you're not really supposed to be implementing your own `ListStyle`.
However, you might be able to achieve what you're after by creating a wrapper for a `List` that accepts a `ViewBuilder` as parameter. Something like:
```swift
struct CustomList<Content>: View where Content: View {
@ViewBuilder let content: () -> Content
var body: some View {
List {
content()
.foregroundStyle(.pink)
.listRowBackground(
Color.yellow
.clipShape(RoundedRectangle(cornerRadius: 10))
)
}
.listStyle(.plain)
.listRowSpacing(10)
.padding()
.background(.gray)
}
}
struct ContentView: View {
var body: some View {
CustomList {
ForEach(0..<100, id: \.self) { item in
Text("Item \(item)")
}
}
}
}
```
 |
You could try:
lapply(
my_list,
\(x) if ('col3' %in% names(x)) transform(x, col3 = replace(col3, is.na(col3) & tolower(col1) %in% c('v2', 'v3'), 'VAL')) else x
)
Output:
[[1]]
col1 col2 col3 col4
1 v1 wood cup <NA>
2 v2 <NA> VAL pear
3 v3 water fork banana
4 V2 <NA> VAL <NA>
5 V1 water <NA> apple
[[2]]
col1 col2 col4
1 v1 wood <NA>
2 v2 <NA> pear
[[3]]
col1 col3 col4
1 v1 cup <NA>
2 v2 VAL pear
3 v3 VAL banana
4 V3 VAL <NA> |
Alert! I am feeling so embarassed asking such an entry level question here!!!!
Hey guys, I have been working on a project that involves timeseries total electron content data. My goal is to apply statistical analysis and find anomalies in TEC due to earthquake.
I am following [this research paper for sliding IQR method][1]. But for some reason I am not getting results as shown in the paper with the given formulas. So I decided to use the rolling mean + 1.6 STD method.
The problem is when I use ax.fill_between(x1 = index, y1 = ub, y2=lb) method my confidence interval band is being plotted a step further than the data point. Please see the given figure for a better understanding.
Here's what I am currently doing:
```
df = DAEJ.copy()
window = 12
hourly = df.resample(rule="h").median()
hourly["ma"] = hourly["TEC"].rolling(window=window).mean()
hourly["hour"] = hourly.index.hour
hourly["std_err"] = hourly["TEC"].rolling(window=window).std()
hourly["ub"] = hourly["ma"] + (1.67* hourly["std_err"])
hourly["lb"] = hourly["ma"] - (1.67* hourly["std_err"])
hourly["sig2"] = hourly["TEC"].rolling(window=window).var()
hourly["kur"] = hourly["TEC"].rolling(window=window).kurt()
hourly["pctChange"] = hourly.TEC.pct_change(12, fill_method="bfill")
hourly = hourly.dropna()
dTEC = hourly[(hourly["TEC"] > hourly["ub"])]
fig, ax = plt.subplots(figsize=(12,4))
hourly["TEC"].plot(ax=ax, title="TEC Anomaly", label="Station: DAEJ")
ax.fill_between(x=hourly.index, y1=hourly["ub"], y2=hourly["lb"], color="red", label="Conf Interval", alpha=.4)
ax.legend()
```
And here's the result I got!
[TEC Anomaly detection using rolling std method](https://i.stack.imgur.com/cFifC.png)
as seen in the given figure the data and the colored band aren't alinged properly, I know after calculating a rolling mean with a window of 12 hours will result in a 12 hour shifted value but even after dropping the first values I am still not getting an aligned figure.
[1]: https://www.researchgate.net/publication/375029615_A_comprehensive_study_on_the_synchronized_outgoing_longwave_radiation_and_relative_humidity_anomalies_related_to_global_Mw_65_earthquakes |
You can build two masks, one to identify the Role change, and one to identify the difference of index above threshold:
```
m1 = df.Role!= df.Role.shift()
m2 = df['Index'].diff().gt(5)
out = df.groupby((m1|m2).cumsum()).agg(
Role = ('Role', 'first'),
Name = ('Name', ' '.join),
Grade = ('Grade', 'mean')
).reset_index(drop=True)
```
Output:
```
Role Name Grade
0 Provider Alex William Juan 6.666667
1 Provider Pedro 4.500000
2 Client George 8.000000
3 Provider Mark 9.400000
4 Client James 8.100000
5 Transporter Anthony 9.500000
6 Transporter Jason 7.000000
``` |
Exclude blank cells from weighted average in pivot table |
Im developping a web app using reactjs and nextjs. When i run it in dev mode, my ram is used up 100%. Im having a 12gb ram and almost 6gb is used up by node js runtime. My colleague has a 24gb ram and when he run it, node js uses almost 15gb ram. When a modification is done to the code, the node js runtime uses up 100% and everything else crashes.
The versions are as follows (as per package.json);
"next": "^13.2.1",
"react": "^18.2.0"
In the terminal, the below error is displayed.
`<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: RangeError: Array buffer allocation failed`
[Terminal log](https://i.stack.imgur.com/bSL96.png)
Ive added the folloing code block to the next.config.js
```
webpack(config, { webpack }) {
config.infrastructureLogging = { debug: /PackFileCache/ }; // Define infrastructureLogging inside the webpack function
return config;
}
```
According to those logs, when the web app starts, it creates a cache file and its size is almost 10gb. Everytime a change is made, the cache file is recreated.
|
My React Nextjs web app is using up 100% of my ram and crashing when i try to do changes. Does anyone know how to fix this or what may be the cause? |
|reactjs|node.js|memory-leaks|out-of-memory| |
null |
I have been working on a classifier for a few days on Azure Auto ML and when I tried disabling some variables that I do not need, I encountered the below error.
I have never encountered this type of error before. Even after creating a new dataset with just the variables I am interested in, the error persists. I need help to resolve this issue. Thank you
The only SQL code that you will on my Data sets on Auto ML is SELECT * FROM my_table and it works since I can see the data on Azure ML studio. Plus I only started to have this error yesterday and I do not know why.
Encountered error while fetching data. Error:
Error Code: ScriptExecution.Database.Unexpected
Native Error: Dataflow visit error: ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 }))))))
VisitError(ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 })))))))
=> Failed with execution error: An error occur when executing database query.
ExecutionError(DatabaseError(Unknown("SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))", Some(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: "Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.", server: "data-platform-sql-data-warehouse-server", procedure: "", line: 1 }))))))
Error Message: Database execution failed with "SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 }))". "Ok(SQLError(Server(TokenError { code: 103010, state: 1, class: 16, message: \"Parse error at line: 1, column: 22: Incorrect syntax near 'stmt'.\", server: \"data-platform-sql-data-warehouse-server\", procedure: \"\", line: 1 })))"| session_id=af8ac40c-2ffe-410f-8ecb-70e45405ef78
Thank you
I just swicthed off some of the variables that my model does not need. So I would just create a new version of that data set with less variables that I could use for a new version of the model, which is something I have been constantly doing for the last couple of weeks.
I created a new dataset containing just the variables I need but I get the same error. Now I seem to be getting the same error always, no matter what I do. |
Correcting the Database URL worked for me. |
I want to set axisItems to a PlotItem useing pyqtgraph, I encountered an error while running my code.
Here is my code:
```
import numpy as np
import pyqtgraph as pg
app = pg.mkQApp("app")
x = np.linspace(0, 10, 1000)
y = np.sin(x)
plot_item = pg.PlotItem()
plot_item.setAxisItems(axisItems={'bottom':pg.AxisItem('bottom')}) # error occurs here
plot_item.plot(x, y)
plot_item.setTitle("Sine Wave Plot")
plot_item.setLabel("left", "Amplitude", units="V")
plot_item.setLabel("bottom", "Time", units="s")
plot_item.showGrid(True, True)
win = pg.GraphicsLayoutWidget()
win.setWindowTitle("PlotItem Example")
win.resize(800, 600)
win.addItem(plot_item)
win.show()
app.exec()
```
----------------------------------------------------------------------------------------------------
When I run this code, it shows the error as below:
```
Traceback (most recent call last):
File "E:\Workspace\Python\VNPY-master\examples\candle_chart\tick\item\main.py", line 42, in <module>
plotItem.setAxisItems(axisItems={'bottom':pg.AxisItem('bottom')})
File "E:\home\.conda\envs\Python310\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 312, in setAxisItems
oldAxis.scene().removeItem(oldAxis)
AttributeError: 'NoneType' object has no attribute 'removeItem'
```
I tried to set axises when initialzing PlotItem, it succeeded. but how to set axises after initialized PlotItem?
```
import pyqtgraph as pg
import numpy as np
app = pg.mkQApp("app")
x = np.linspace(0, 10, 1000)
y = np.sin(x)
plot_item = pg.PlotItem(axisItems={'bottom':pg.AxisItem('bottom')}) #run successfully
plot_item.plot(x, y)
plot_item.setTitle("Sine Wave Plot")
plot_item.setLabel("left", "Amplitude", units="V")
plot_item.setLabel("bottom", "Time", units="s")
plot_item.showGrid(True, True)
win = pg.GraphicsLayoutWidget()
win.setWindowTitle("PlotItem Example")
win.resize(800, 600)
win.addItem(plot_item)
win.show()
app.exec()
```
|
This works well, though the blur was a bit abrupt with a larger blur and a 1s Swiper speed. In my case, I also used a transition to match the speed:
.swiper-slide {
filter: blur(40px);
transition: 1s filter linear;
}
.swiper-slide-active {
filter: blur(0);
} |
check your babel.config.js has the runtime set to automatic
"plugins": [
["@babel/plugin-transform-react-jsx", {
"runtime": "automatic"
}] |
import tensorflow as tf
from keras.preprocessing.sequence import Tokenizer
from keras.utils import pad_sequences
# Set parameters
vocab_size = 5000
embedding_dim = 64
max_length = 100
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_size = len(processed_data)
# Create tokenizer
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_sequences(processed_data)
word_index = tokenizer.word_index
# Create sequences
sequences = tokenizer.texts_to_sequences(processed_data)
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Create training data
training_data = padded_sequences[:training_size]
training_labels = padded_sequences[:training_size]
# Build model
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Conv1D(64, 5, activation='relu'),
tf.keras.layers.MaxPooling1D(pool_size=4),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(vocab_size, activation='softmax')
])
# Compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train model
num_epochs = 50
history = model.fit(training_data, training_labels, epochs=num_epochs, verbose=2)
def predict_answer(model, tokenizer, question):
# Preprocess question
question = preprocess(question)
# Convert question to sequence
sequence = tokenizer.texts_to_sequences([question])
# Pad sequence
padded_sequence = pad_sequences(sequence, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Predict answer
pred = model.predict(padded_sequence)[0]
# Get index of highest probability
idx = np.argmax(pred)
# Get answer
answer = tokenizer.index_word[idx]
return answer
# Start chatbot
while True:
question = input('You: ')
answer = predict_answer(model, tokenizer, question)
print('Chatbot:', answer)
There is an opportunity to write to the chat in the terminal. When I write my message, it gives an error: Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'model' is not defined |
|python-3.x|regex|string|list-comprehension|python-3.12| |
`If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version` As mentioned in their docs.
Doc Link :- https://create-react-app.dev/docs/getting-started/
If you still face the same issue try this :-
`npx create-react-app@latest your-project-name --use-npm`
|
My drawables are on the folder drawable-xxhdpi and the background size is 1080 x 1920.
For the screens with this resolution, all is OK.
But when I test on a samsung A34 for example with the resolution 1080 X 2340, I have a black strip under my screen game and I don't know how to scale my background and the position of the other graphics elements to this specfic screen.
Thank you
Gigi
```
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
// Affichage du background
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.backgame), 0, 0, paint);
```
|
I have an Angular HTML document for a `product catalog` page.
products.componet.ts:
```js
showCategories = true;
showProductsInCategoriesSwitcher = true;
showProductsAll = false;
showProductsInCategories = false;
fetchingProducts = false;
showProductsByCategory(categoryId: string) {
this.showCategories = !this.showCategories;
this.showProductsInCategoriesSwitcher = !this.showProductsInCategoriesSwitcher;
this.showProductsInCategories = !this.showProductsInCategories;
//further code
}
showAllProducts() {
this.showCategories = !this.showCategories;
this.showProductsAll = !this.showProductsAll;
//further code
}
```
products.component.html:
```html
<div *ngIf="showProductsInCategoriesSwitcher" class="mb-4">
<input type="checkbox" checked (click)="showAllProducts()"/>
<label class="ms-1">Show products in categories</label>
</div>
<div *ngIf="showCategories">
<div *ngIf="categories$ | async as categories; else loader">
<div *ngIf="categories.length !== 0">
<c-row [gutter]="2" class="mb-2" [lg]="6" [md]="4" [xs]="1">
<c-card *ngFor="let category of categories" class="mx-1">
<div *ngIf="category._id"
(click)="showProductByCategory(category._id)">
<img cCardImg="top" [src]="category.imageSrc" />
<c-card-body>
<h2 cCardTitle>{{ category.name }}</h2>
</c-card-body>
</div></c-card>
</c-row>
</div>
</div>
</div>
<ng-container *ngIf="
(!showCategories && !showProductsInCategoriesSwitcher) ||
(!showProductsAll && showProductsInCategories)">
<ng-container *ngTemplateOutlet="
ProductsByCategory; context: { categoryId: selectedCategoryId }">
</ng-container>
</ng-container>
<ng-container *ngIf="!showCategories && !showProductsInCategories">
<ng-container *ngTemplateOutlet="ProductsAll"></ng-container>
</ng-container>
<ng-template #ProductsByCategory let-categoryId="categoryId">
<div *ngIf="!fetchingProducts; else loader">
<ng-container *ngIf="productsInCategories.length !== 0">
<a (click)="
(showCategories = !showCategories) &&
(showProductsInCategoriesSwitcher = !showProductsInCategoriesSwitcher)"
>Back to categories</a>
</ng-container>
<!-- Code for product card -->
<ng-container *ngIf="!productsInCategories || productsInCategories.length === 0">
<a href="javascript:void(0);"
(click)="(showCategories = !showCategories) &&
(showProductsInCategoriesSwitcher = !showProductsInCategoriesSwitcher)">
Back to categories</a>
<p>No products available for this category.</p>
</ng-container>
</div>
</ng-template>
<ng-template #ProductsAll><div *ngIf="!fetchingProducts; else loader">
<ng-container *ngIf="productsAll.length !== 0">
<!-- Code for product card -->
</ng-container>
<ng-container *ngIf="!productsAll || productsAll.length === 0">
<p>No products available.</p>
</ng-container>
</div>
</ng-template>
<ng-template #loader>
<div class="myspinner">
<c-spinner></c-spinner>
</div>
</ng-template>
```
As you can see, the page is loaded with templates for product categories and a switch for displaying types of products in categories or all products at once.
I need to implement this logic:
When you click on a category element, show products from this category and the “Return to categories” link, while hiding the “Show products by category” switch. When you click on the "Return to Categories" link, everything should return to its original state.
When you click the "Show products in categories" switch, show all products at once, while hiding the product categories template. When you press the switch again, everything should return to its original state.
I'm stuck trying out options for displaying templates, but the logic of their behavior changes every time.
Please explain to me how this logic is implemented, or tell me how to correctly ask in Google. Thank you. |
null |
You could use `labeller` per below to suppress the `layout_order`.
(It is better if you can supply a small amount of sample data with the question.)
``` r
library(tidyverse)
df <- tibble(
Time = 1:8,
nPVI = 21:28,
Group = rep(letters[1:4], 2),
Participant = 1:8,
layout_order = 1:8
)
df$layout_order <- factor(rep(1:ceiling(nrow(df) / 4), each = 4), levels = unique(rep(1:ceiling(nrow(df) / 4), each = 4))[1:nrow(df)])
ggplot(df, aes(x = Time, y = nPVI, group = Time, fill = Group)) +
geom_bar(stat = "identity", position = "dodge", color = "black") +
labs(
title = "nPVI scores by Participant, Time and Group",
x = "Time",
y = "nPVI",
group = "Time"
) +
facet_wrap(~ Participant + layout_order,
scales = "free", ncol = 4,
labeller = labeller(layout_order = \(x) rep("", length(x)))
) +
coord_cartesian(ylim = c(20, 60)) +
scale_fill_manual(values = c("Oral" = "#86CB92", "Prosody" = "#0E7C7B")) +
theme_minimal()
```
<!-- -->
<sup>Created on 2024-03-27 with [reprex v2.1.0](https://reprex.tidyverse.org)</sup> |
I can't add constructor in my event listener.Laravel 11 there is no EventService provider also. I need an example for this
```
public function handle(NewUserEvent $event): void
{
Mail::send('3_Emails.1_CommonMailTemplate', $mailData, function ($message) use ($Name, $Email) {
$message->to($Email)
->subject("Contact | $Name")
->cc('example@gmail.com') // Add CC recipient
->bcc('example@gmail.com'); // Add BCC recipient
});
}
hete i cant get $event in it.
``` |
null |
Check your network tab in your browser to ensure your scripts are downloaded |
Alert! I am feeling so embarassed asking such an entry level question here!!!!
Hey guys, I have been working on a project that involves timeseries total electron content data. My goal is to apply statistical analysis and find anomalies in TEC due to earthquake.
I am following [this research paper for sliding IQR method][1]. But for some reason I am not getting results as shown in the paper with the given formulas. So I decided to use the rolling mean + 1.6 STD method.
The problem is when I use ax.fill_between(x1 = index, y1 = ub, y2=lb) method my confidence interval band is being plotted a step further than the data point. Please see the given figure for a better understanding.
Here's what I am currently doing:
```
df = DAEJ.copy()
window = 12
hourly = df.resample(rule="h").median()
hourly["ma"] = hourly["TEC"].rolling(window=window).mean()
hourly["hour"] = hourly.index.hour
hourly["std_err"] = hourly["TEC"].rolling(window=window).std()
hourly["ub"] = hourly["ma"] + (1.67* hourly["std_err"])
hourly["lb"] = hourly["ma"] - (1.67* hourly["std_err"])
hourly["sig2"] = hourly["TEC"].rolling(window=window).var()
hourly["kur"] = hourly["TEC"].rolling(window=window).kurt()
hourly["pctChange"] = hourly.TEC.pct_change(12, fill_method="bfill")
hourly = hourly.dropna()
dTEC = hourly[(hourly["TEC"] > hourly["ub"])]
fig, ax = plt.subplots(figsize=(12,4))
hourly["TEC"].plot(ax=ax, title="TEC Anomaly", label="Station: DAEJ")
ax.fill_between(x=hourly.index, y1=hourly["ub"], y2=hourly["lb"], color="red", label="Conf Interval", alpha=.4)
ax.legend()
```
And here's the result I got!

as seen in the given figure the data and the colored band aren't alinged properly, I know after calculating a rolling mean with a window of 12 hours will result in a 12 hour shifted value but even after dropping the first values I am still not getting an aligned figure.
[1]: https://www.researchgate.net/publication/375029615_A_comprehensive_study_on_the_synchronized_outgoing_longwave_radiation_and_relative_humidity_anomalies_related_to_global_Mw_65_earthquakes |
I write code for the ESP32 microcontroller.
I set up a class named "dmhWebServer".
This is the call to initiate my classes:
An object of the dmhFS class is created and I give it to the constructor of the dmhWebServer class by reference. For my error see the last code block that I posted. The other code block could explain the way to where the error shows up.
```
#include <dmhFS.h>
#include <dmhNetwork.h>
#include <dmhWebServer.h>
void setup()
{
// initialize filesystems
dmhFS fileSystem = dmhFS(SCK, MISO, MOSI, CS); // compiler is happy I have an object now
// initialize Activate Busy Handshake
dmhActivateBusy activateBusy = dmhActivateBusy();
// initialize webserver
dmhWebServer webServer(fileSystem, activateBusy); // compiler also happy (call by reference)
}
```
The class dmhFS has a custom constructor (header file, all good in here):
```
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#include <LittleFS.h>
#include <dmhPinlist.h>
#ifndef DMHFS_H_
#define DMHFS_H_
class dmhFS
{
private:
// serial peripheral interface
SPIClass spi;
String readFile(fs::FS &fs, const char *path);
void writeFile(fs::FS &fs, const char *path, const char *message);
void appendFile(fs::FS &fs, const char *path, const char *message);
void listDir(fs::FS &fs, const char *dirname, uint8_t levels);
public:
dmhFS(uint16_t sck, uint16_t miso, uint16_t mosi, uint16_t ss);
void writeToSDCard();
void saveData(std::string fileName, std::string contents);
String readFileSDCard(std::string fileName);
};
#endif
```
Header file of the dmhWebServer class (not the whole thing):
```
public:
dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake);
};
```
This is the dmhWebServer class:
```
class dmhWebServer
{
private:
// create AsyncWebServer object on port 80
AsyncWebServer server = AsyncWebServer(80);
// server to client communication
AsyncEventSource events = AsyncEventSource("/events");
void setupHandlers();
void setupWebServer();
void serveFiles();
void setupStaticFilesHandlers();
void setupEventHandler();
void setupPostHandler();
void onRequest(AsyncWebServerRequest *request);
// http communication
void sendToClient(const char *content, const char *jsEventName);
void receiveFromClient(std::array<const char *, 2U> par);
// uses SD Card
dmhFS sharedFileSystem;
// uses shared memory for data exchange with a activate busy handshake
dmhActivateBusy abh;
public:
dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake);
};
```
This is the constructor of the dmhWebServer class:
```
#include <dmhWebServer.h>
#include <dmhFS.h>
#include <dmhActivateBusy.h>
// This is the line where the compiler throws an error ,character 85 is ")"
dmhWebServer::dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake)
{
// webserver sites handlers
setupHandlers();
abh = activateBusyHandshake;
sharedFileSystem = fileSystem;
// start web server, object "server" is instantiated as private member in header file
server.begin();
}
```
My compiler says: "src/dmhWebServer.cpp:5:85: error: no matching function for call to 'dmhFS::dmhFS()'"
Line 5:85 is at the end of the constructor function declaration
This is my first question on stackoverflow since only lurking around here :) I try to clarify if something is not alright with the question.
I checked that I do the call by reference in c++ right. I am giving the constructor "dmhWebServer" what he wants. What is the problem here? |
This problem is often called 'assigning agents to tasks'. There are several algorithms that can solve this. I use the Ford-Fulkerson Maximum Flow Algorithm ( theory.stanford.edu/~tim/w16/l/l1.pdf )
The trick is, as always, adapting the algorithm to your particular constraints so that the max flow algorithm operates without violating any of them.
I do not understand some of your constraints ( 'workdays' in particular, see my comments on your question for the clarifications needed ). So I cannot apply all your constraints. But, I thought you might find it useful to see some code ( C++, sorry ) implementing the max flow allocation applied to a simplified version of your problem. This code uses the implementation of Ford-Fulkerson supplied by the PathFinder graph theory library. ( https://github.com/JamesBremner/PathFinder )
```C++
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include "GraphTheory.h"
class cAgent
{
public:
std::string myID;
std::vector<std::string> myTasks;
bool cando( const std::string& task )
{
return std::find(
myTasks.begin(),myTasks.end(),
task )
!= myTasks.end();
}
};
std::set<std::string> theTasks;
std::vector<cAgent> theAgents;
void readfile()
{
std::ifstream ifs("../dat/data1.txt");
if (!ifs.is_open())
throw std::runtime_error(
"Cannot read input");
std::string line;
while (getline(ifs, line))
{
// std::cout << line << "\n";
if (line.find("id:") != -1)
{
int p = line.find("\"");
int q = line.find("\"", p + 1);
line = line.substr(p + 1, q - p - 1);
if (line[0] == 'T')
{
cAgent A;
A.myID = line;
theAgents.push_back(A);
}
}
else if (line.find("subjects:") != -1)
{
int p = line.find("\"", p + 1);
while (p != -1)
{
int q = line.find("\"", p + 1);
auto task = line.substr(p + 1, q - p - 1);
theTasks.insert(task);
theAgents.back().myTasks.push_back(task);
p = line.find("\"", q + 1);
}
}
else if (line.find("const subjects") != -1)
break;
}
std::cout << "Teachers:\n ";
for (auto &a : theAgents)
{
std::cout << a.myID << " can teach ";
for (auto &t : a.myTasks)
std::cout << t << " ";
std::cout << "\n";
}
}
void allocateMaxFlow()
{
raven::graph::cGraph g;
g.directed();
// loop over the tasks in timeslot
for (auto & task : theTasks)
{
// loop over agents that can do task
for (cAgent &a : theAgents)
{
if( ! a.cando( task ))
continue;
// add link from agent to task agent is able to do
g.add(
a.myID,
task );
}
}
// apply pathfinder maximum flow allocation algorithm
raven::graph::sGraphData gd;
gd.g = g;
auto sg = alloc(gd);
std::cout << "\nAssignments:\n";
for (std::pair<int, int> p : sg.edgeList())
{
std::cout << "teacher " << sg.userName(p.first )
<< " assigned to " << sg.userName (p.second)
<< "\n";
}
}
main()
{
readfile();
allocateMaxFlow();
return 0;
}
```
The output from this is
```
Teachers:
T1 can teach M1 M2 M3
T2 can teach Q1 Q2 Q3
T3 can teach I1 I2 I3
T4 can teach B1 B2 B3
T5 can teach H1
T6 can teach P1 P2 P3
T7 can teach I1 I2 I3
T8 can teach C1 C2 C3
T9 can teach M1
T10 can teach A1 A2
Assignments:
teacher T10 assigned to A1
teacher T4 assigned to B1
teacher T8 assigned to C1
teacher T5 assigned to H1
teacher T3 assigned to I1
teacher T7 assigned to I2
teacher T9 assigned to M1
teacher T1 assigned to M2
teacher T6 assigned to P1
teacher T2 assigned to Q1
```
You can find the complete project at https://github.com/JamesBremner/78250368 |
I've got a React component that I have made aware of its own width using ResizeObserver. Inside this component I'm rendering two divs, each one is "flex: 1" so they take equal width. When the component is small enough and certain state conditions are met, I set "display: none" on the first div, allowing the second to take the full width of the flex container.
It is working well to respond to changes in the browser width, but my application also has a side bar that can be opened and closed. When the side bar is closed and enough width is made available by this action, my component recognizes that and adjusts itself to display the "dashboard_monitors" div once again. The problem is, we get one paint where the side bar is closed and the second "dashboard_activity" div is still taking up the full width, and only after this paint does the component update itself and display the "dashboard_monitors" div, which causes a perceivable "jump" as the component positions each div with equal width again.
It seems that I'd need to have the side bar disappear and the component update itself, so they can both paint in the correct state at the same time, but I'm not sure how to accomplish this.
This is the component I'm speaking of:
import './Dashboard.css'
import MonitorComponent from '../../components/Monitor/Monitor';
import DetailComponent from '../../components/Monitor/Detail';
import { Monitor } from '../../monitor'
import { useEffect, useMemo, useState } from 'react';
import { useWidth } from '../../hooks/useWidth';
interface DashboardProps {
monitors: Monitor[]
focused: Monitor | null,
drafting: boolean,
}
export default function Dashboard(props: DashboardProps) {
const {
monitors,
focused,
drafting,
} = props;
const isEditing = useMemo(() => focused || drafting, [focused, drafting]);
const { width: dashboardWidth, ref: dashboardRef } = useWidth<HTMLDivElement>();
const [sorted, setSorted] = useState<Monitor[]>([])
useEffect(() => {
const sorted = monitors.sort((a, b) => {
if (a.strategy.name > b.strategy.name) {
return 1;
} else {
return -1;
}
});
setSorted(sorted);
}, [monitors])
const dashboardClasses = ['dashboard', isEditing && dashboardWidth < 700 ? 'single' : '']
return (
<div className={dashboardClasses.join(' ')} ref={dashboardRef}>
<div className="dashboard_monitors">
{sorted.map((n, i) =>
<MonitorComponent key={i} monitor={n} />)
}
</div>
{isEditing ?
<div className="dashboard_activity">
<DetailComponent monitor={focused} />
</div>
: null}
</div>
)
}
The CSS applied to the component in "Dashboard.css" is here:
.dashboard {
display: flex;
height: 100%;
}
.dashboard.single .dashboard_monitors {
display: none;
}
.dashboard.single .dashboard_activity {
margin-left: 0;
}
.dashboard > * {
flex: 1;
overflow-x: hidden;
overflow-y: auto;
}
.dashboard_activity {
margin-left: var(--padding-2);
}
.dashboard_monitors {
display: grid;
gap: var(--padding-2);
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
grid-auto-rows: 200px;
padding-right: var(--padding-0);
padding-bottom: var(--padding-0);
}
The ResizeObserver is in my useWidth hook here:
import { useState, useRef, useEffect } from "react";
export const useWidth = <T extends HTMLElement>() => {
const [width, setWidth] = useState(0);
const ref = useRef<T>(null);
useEffect(() => {
const observer = new ResizeObserver((entries) => {
setWidth(entries[0].contentRect.width);
});
const refElement = ref.current;
if (refElement) {
observer.observe(refElement);
}
return () => {
refElement && observer.unobserve(refElement);
};
}, []);
return { width, ref };
};
If you have any suggestions or questions, thanks for your time. |
Width aware React component rendering twice |
|javascript|html|css|reactjs| |
I am using Linux (Ubuntu 22.04) and wanted to run `gitlab-runner` with the following YAMK file locally:
```yaml
image: ubuntu:latest
test:
script:
- echo "Hello Gitlab-Runner"
```
When I execute `gitlab-runner exec docker test`, I get the following error:
```
Running with gitlab-runner 11.2.0 (11.2.0)
Using Docker executor with image ubuntu:latest ...
ERROR: Preparation failed: Error response from daemon: {"message":"client version 1.18 is too old. Minimum supported API version is 1.24, please upgrade your client to a newer version"} (executor_docker.go:1147:0s)
Will be retried in 3s ...
```
I checked the docker version I have:
```
Client: Docker Engine - Community
Version: 26.0.0
API version: 1.45
Go version: go1.21.8
Git commit: 2ae903e
Built: Wed Mar 20 15:17:51 2024
OS/Arch: linux/amd64
Context: default
Server: Docker Engine - Community
Engine:
Version: 26.0.0
API version: 1.45 (minimum version 1.24)
Go version: go1.21.8
Git commit: 8b79278
Built: Wed Mar 20 15:17:51 2024
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.6.28
GitCommit: ae07eda36dd25f8a1b98dfbf587313b99c0190bb
runc:
Version: 1.1.12
GitCommit: v1.1.12-0-g51d5e94
docker-init:
Version: 0.19.0
GitCommit: de40ad0
```
Any ideas?
|
I have a problem with `drop_na()` function. I wanted to clean the dataset and erase the "NA" values, but when I entered the code, all datas are disseapperad. I do not understand why it happens. note:Im beginner level.
[You can see clearly what my codes are in this picture](https://i.stack.imgur.com/ORaUW.png)
```
library(tidyverse)
WDI_GNI<read_csv("C:/Users/sudes/Downloads/P_Data_Extract_From_World_Development_Indicators/a7b778c6-9827-4c45-91b7-8f497087ca17_Data.csv")WDI_GNI <- WDI_GNI %>%
mutate(across(contains("[YR"),~na_if(.x, ".."))) %>%
mutate(across(contains("[YR"), as.numeric)) WDI_GNI <- drop_na(WDI_GNI)
```
|
null |
--Remove Duplciates[SKR]
--Option A:
select *
--delete t
from(
select rowNumber=row_number() over (partition by SomeKey order by SomeKey), SomeKey from YourTable m
)t where rowNumber > 1
--Option B:
with cte as (
select rowNumber=row_number() over (partition by SomeKey order by SomeKey), SomeKey from YourTable m
)
--delete from cte where rowNumber > 1
select * from cte where rowNumber > 1 |
null |
null |
null |
null |
null |
The part of the code giving me the error is borrowed from research on how to find a specific value, match it to a value on another worksheet and delete that row of data. The code has multi tasks to complete:
1. Copy the row on sheet22 and paste it to the next empty row on
sheet13
2. Find a match to Sheet22 cell C2 on Sheet 11 column A and
delete the matching row on sheet 11
3. Add formulas into columns F:M &
Q on row 2 of sheet22
Sub LineArchive_DD118()
Dim TMLastDistRow
Dim Answer As VbMsgBoxResult
Dim LastRowInRange As Long, RowCounter As Long
TMLastDistRow = Worksheets("Trailer Archives").Cells(Sheet13.Rows.Count, "B").End(xlUp).Row + 1
LastRowInRange = Sheets(Sheet11).Range("A:A").Find("*", , xlFormulas, , xlByRows, xlPrevious).Row ' Returns a Row Number
Application.ScreenUpdating = False
Application.EnableEvents = False
If Sheets("Dock Door Status").Range("P2").Value = "F" Then
With Sheets("Dock Door Status")
.Range("P2").Value = "F"
.Range("C2:R2").Copy
End With
With Sheets("Trailer Archives")
.Range("B" & TMLastDistRow).PasteSpecial Paste:=xlPasteValues
End With
Else
Exit Sub
End If
Answer = MsgBox("Are you sure you want to clear DD118?", vbYesNo + vbCritical + vbDefaultButton2, "Dock Door 118 Data")
If Answer = vbYes Then
For RowCounter = LastRowInRange To 1 Step -1 ' Count Backwards
If Sheets("Sheet11").Range("A" & RowCounter) = Sheets("Sheet22").Range("C2") Then ' If Cell matches our 'Delete if' value then
Sheets("Sheet11").Rows(RowCounter).EntireRow.Delete ' Delete the row
End If
Next
With Sheets("Dock Door Status")
.Range("D2:Q2").ClearContents
.Range("D2") = "CLOSED"
End With
With Sheets("Dock Door Status")
.Range("F2").Formula = "=IFERROR(INDEX('SSP Data'!B$2:B$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("G2").Formula = "=IFERROR(INDEX('SSP Data'!C$2:C$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("H2").Formula = "=IFERROR(INDEX('SSP Data'!D$2:D$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("I2").Formula = "=IFERROR(INDEX('SSP Data'!E$2:E$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("J2").Formula = "=IFERROR(INDEX('SSP Data'!F$2:F$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("K2").Formula = "=IFERROR(INDEX('SSP Data'!G$2:G$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("L2").Formula = "=IFERROR(INDEX('SSP Data'!H$2:H$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("M2").Formula = "=IFERROR(INDEX('SSP Data'!I$2:I$50,MATCH($C2,'SSP Data'!$A$2:$A$50,0)),"""")"
.Range("Q2").Formula = "=IF(G2="""","""",IF(AND(M2="""",N2>G2),""Future"",""Current""))"
End With
Else
Exit Sub
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
The line that is throwing the error is:
LastRowInRange = Sheets(Sheet11).Range("A:A").Find("*", , xlFormulas, , xlByRows, xlPrevious).Row ' Returns a Row Number
I think that part of it is I would like to replace the wildcard with a static text string, i.e. "*" with "DD118". I am sure there is more to the error than that.
All help is appreciated.
|
You can use it mock library for testing file upload;
```
from unittest.mock import MagicMock
from django.core.files import File
mock_image = MagicMock(file=File)
mock_image.name="sample.png"
# Another test operations...
def test_file_upload(self):
# file_content is a bytest object
request = client.patch(
"/fake-url/",
{"file" : mock_image},
format="multipart",
)
```
Detailed another answer; https://stackoverflow.com/questions/11170425/how-to-unit-test-file-upload-in-django |
null |
try to use
pipwin install gdal
and then rasterio, etc. This worked for me! |
I am learning vhdl and fpga, I have a digilent board Nexys 4. I am trying to send via UART a string. I have been sucessful in sending a character every time a button is clicked on the board.
Now I want to send the whole string after every button click, but I don't get any output from the terminal (I use putty). What am I doing wrong?
This is the top module, I believe the problem may be here but I am not 100% sure.
```
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity UART_tx_top is
port(btnC : in std_logic;
clk : in std_logic;
RsTx : out std_logic);
end UART_tx_top;
architecture behavioral of UART_tx_top is
signal string_to_send : string := "Hello World!";
constant string_length : integer := 12;
signal tx_index : integer := 0;
type state_type is (TX_WAIT_BTN, TX_SEND_CHAR, TX_SEND_WAIT);
signal state : state_type := TX_WAIT_BTN;
signal uartRdy : std_logic;
signal uartSend: std_logic;
signal uartData: std_logic_vector (7 downto 0);
signal initStr : std_logic_vector (7 downto 0) := x"41";
signal btnCclr : std_logic;
signal btnC_prev : std_logic;
component UART_tx_ctrl
generic(baud : integer);
port(send : in std_logic;
clk : in std_logic;
data : in std_logic_vector (7 downto 0);
ready : out std_logic;
uart_tx : out std_logic);
end component;
component debounce is
port(clk : in std_logic;
btn : in std_logic;
btn_clr : out std_logic);
end component;
begin
process(clk)
begin
if rising_edge(clk) then
btnC_prev <= btnCclr;
case state is
when TX_WAIT_BTN =>
if btnC_prev = '0' and btnCclr = '1' then
state <= TX_SEND_CHAR;
end if;
when TX_SEND_CHAR =>
if tx_index < string_length then
uartData <= std_logic_vector(to_unsigned(character'pos(string_to_send(tx_index + 1)), 8));
--initStr <= std_logic_vector(unsigned(initStr) + 1);
tx_index <= tx_index + 1;
--state <= TX_SEND_WAIT;
else
uartData <= (others => '0');
tx_index <=0;
state <= TX_WAIT_BTN;
end if;
when TX_SEND_WAIT =>
if uartRdy = '1' then state <= TX_WAIT_BTN;
end if;
end case;
end if;
end process;
uartSend <= '1' when (state = TX_SEND_CHAR) else '0';
SX : UART_tx_ctrl generic map(baud => 19200)
port map(send => uartSend, data => uartData, clk => clk, ready => uartRdy, uart_tx => RsTx);
dbc : debounce port map(clk => clk, btn => btnC, btn_clr => btnCclr);
end behavioral;
``` |
Whenever you have a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) of the form `{[K in keyof T]: ⋯}`, with `in keyof` in there directly, it will be a *homomorphic mapped type* as described in https://stackoverflow.com/q/59790508/2887218. That means [`readonly`](https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties) and [optional](https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties) properties in the input type will become readonly and optional properties in the output type. Optional properties will always include `undefined` in their domain.
So that means your `KeyPath<T>` type will end up including `undefined` if any of the keys of `T` (or perhaps even subkeys, given the recursion) are optional. You can test the type to see this (it looks like you tried to do this but didn't fully expand the type. One way to do this is to [intersect](https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types) with `{} | null | undefined`, a type more or less equivalent to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown)):
type TestKey = KeyPath<Domain> & ({} | null | undefined);
// ^? type TestKey = "id" | "value" | "user" | "user.id" | "user.name" |
// "user.emails" | "user.isActive" | "user.type" | "user.name.first" |
// "user.name.last" | undefined
Now, ideally, TypeScript would be smart enough to prevent you from using `undefined` as a key in an [indexed access type](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html). But sometimes if generics are complicated enough, the compiler fails to see the problem:
type Hmm<T> = { [K in keyof T]: K }[keyof T]
type Grr<T> = T[Hmm<T>]; // <-- this should be an error but it's not
type Okay = Grr<{a: string}> // string
type Bad = Grr<{ a?: string }> // unknown
The `unknown` is what happens when the compiler is trying to figure out `{a?: string}[undefined]`. Allowing `undefined` to sneak in as a key is a known design limitation, according to [this comment on microsoft/TypeScript#56515](https://github.com/microsoft/TypeScript/pull/56515#issuecomment-1829898710), because trying to fix it was causing way too much breakage in real world code. So they allow it, and recommend that if you're writing a type function to extract keys, you should perform the following fix:
----
The recommended fix here is to use the `-?` [mapping modifier](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#mapping-modifiers) to make keys required in the mapping and to prevent `undefined` from being included in the domain. (The `-?` modifier is used in the definition of [the `Required<T>` utility type](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype)):
type KeyPath<T, TParentKey = undefined> = {
[K in keyof T]-?: K extends string ? (
// ^^
TParentKey extends undefined ? `${K}` : `${TParentKey & string}.${K}`
) : never; }[keyof T]
| {
[K in keyof T]-?: T[K] extends object ? (
// ^^
K extends string ? KeyPath<
T[K], TParentKey extends undefined ? `${K}` : `${TParentKey & string}.${K}`
> : never
) : never;
}[keyof T];
which removes `undefined` from the list of keys:
type TestKey = KeyPath<Domain> & ({} | null | undefined);
// ^? type TestKey = "id" | "value" | "user" | "user.id" | "user.name" |
// "user.emails" | "user.isActive" | "user.type" | "user.name.first" |
// "user.name.last"
which unbreaks `SortKey`:
type DomainSortKey = SortKey<Domain>;
/* type DomainSortKey = {
key: "id";
order: 'asc' | 'desc';
getter: Getter<Domain, "id">;
comparer: Comparer<number>;
} | {
key: "value";
order: 'asc' | 'desc';
getter: Getter<Domain, "value">;
comparer: Comparer<...>;
} | ... 7 more ... | {
...;
} */
[Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gWzAQwE4VQHgCoD4oC8UAFMgFxTYA0UARhdgJSH4B2ArgrRgNwBQfVsgQQAzigDG0APKoAlgHMoAbz5QooSFADSEEAAVkwABY4a2Q+lbBdIQlHasAJhABmc1hCf4iq9eoBtbSgPKABrPThXSgBdCmCIAA9gCGdRKFFgeVYlAH4SCzRUmz0oJJS0h2c3Dy8ofIADABJlbQBfBqgKZuVCqxK7ADIMrI8FNoA6FvaG5gpPADdeNSg2gIiQKNiV9QAfFR3-IJDWcMjo7DjKIJiy5NSndLhaACsICWB6nTuKx5HsvI6PSGEw4G7mSzFWw-B7pRwudyeJxfHozLpQHp9KGlYaZAGTaYdfDzCBLVDoxbLfyrdbnbbU-grAD0TKgADk4AB3KAAGwgwAA5OlMmhPilMmMNMZoNgAMoacBiCYrTQysQDey2EGmAAiiGQHnww2IyjaUH2HB5PPNVQRtScjH46hZ-gAevlVZR1bYAIz2ABEcic-pt-oWyB57AgIf2-vYogwMagcYTqAmQaTKYwEyEIhjzNZ1OT8ezEAQBp5okzJbTclEAEEPnIltXUxNVa3s7mIBN3KhMkmC0Xi23uxMecgBzb4TUkXw2gJPQAJBAIHA+FRQY6hDZbS7xGm7i4xPiegDiqCweHs2ACK7XeBiPCgLswAFo31K6xljHB2DzkW4KBkFODBUDgclaHYT45EFdJWDgYBT0VKBpDCZA7CIC8sGUYCKDxSU2nwF0CJyZCtAAIWQZEsMvTBcOQXJ8NGHJVmI1lHDCBDOVYARyOgLUjFMahKEhaxoSIGdES8Dc-C3YIdzpS43yY75ylhf5JXyYhDhdYc3VdQ4sXE0p1MqKT7RRQlOm6FpjI1XEWPGKZWg6FY5igSlUGfNYj3pG05MCBTTj85TVNvbRbjMv5njeD4vh04c9P0qBXUM4cEnuSpSMBQTQUOakIpiCEihMuxorhappORRprPRTExIczScgJVyGgKqBiU80kMEODyvKdQ8lKfRcUIANQjKN62AbUzCgbUN21GFKlClZ8lvbUT3UCgloqjEWg8VwMCBEBWsO46ACV1Tc9R8mhPbVtuqAJsjCBptmiK9GKqArsyXAVhJMkAe6slGXPfkUivGhMt+YUnI3YgEDgFweQYGgNniZgCHwF6ppmoS5u0XAwZQ2UIIGHAAFlkYgHlZJWbdTjy4TqZR3ArkCs4QHiQb1AglxUAoAVJwkAUbQFFxRFF3moAUCGMAoM95avVnaeh4nDgkRAUHQQXYG1oosFxt78dBbBVZ5dWNfUBc1mZqmabpkbRq0ABVVN7DkoN5k4bhvJWbsKE5vtMmYgEZYnUPmoUQa2kGssK1EVScoCEb1DrRtgGbCAKFoOA4D5EDBtVIWJHjYBEAwMX9iFdgwDAcmBXnEmtD1ctQl8FZvc832qSgcNXrDsZBprCh3eWOOXbVTIJJO2a24NVgjRIU0bUta19gspFHT4F1PWwb1SiIQNg1DAeo07VBL-TU-YxrHNhGjUN74TuRK0HZKR2zDOmxbZ+2w7P-Lsj9exyH7MAa+Y5I4QKnlABeHgyaoA1EQRBFN4FL34EyAAVAqVu+oEHk1npzDGyYMwy35grKAwspbVyoZLaWhw5bAEhorZWmB0E0BPv6a2-gtZIENhQeA-DdaYA4FwDAGszT7GIXoCgYZJrRnIagAWQsRa0IlmIBh1ImEsKgErZhGB2H4NYJw8+0YeHqD4TrShQjrFYAmA4yRNoHETCgAAdigEjdAUAXEBUOC4-gZosFMiAA) |
Here is my code:
```
import csv
def addr():
with open('csvfile.csv','a',newline='') as f:
w=csv.writer(f,delimiter=',')
tid=int(input('Teacher ID: '))
nm=input('Enter Name: ')
mo=int(input('Mobile Number: '))
w.writerow(tid,nm,mo)
def countr():
with open('csvfile.csv') as f:
c=csv.rowcount
print('Number of records:',c)
while True:
addr()
if input('Do you Wish to Continue? (Y/N): ').lower() in ('n','no'):
break
```
[enter image description here](https://i.stack.imgur.com/cpfdW.png)
It showed no error when I tried to use the normal file.write() |
I try to have a button to add ppl to the enlistment of a game. i have a function in another cog that updates the enlistment. so once someone press the button i want it to run that function it adds the person to a mySQL database and then the enlistment cog runs it and displays it on an message in the discord.
```
class reserve(commands.Cog):
def __init__(self, client):
self.client = client
class MyView(discord.ui.View):
@discord.ui.button(style=discord.ButtonStyle.success, label="Enlist me")
async def on_button_one_click(self, interaction: discord.Interaction, button: discord.ui.Button):
enlistment = self.client.get_cog("Embed") #This part is not working
await enlistment.enlistment(self) #This part is not working
```
This is the error i get
File "f:\SeaWolf\pythonbot\cogs\reserves.py", line 31, in on_button_one_click
enlistment = self.client.get_cog("Embed")
^^^^^^^^^^^
AttributeError: 'MyView' object has no attribute 'client'
I can load the function from other cogs doing the same thing but with a slash command instead of a button but i wanted to make it a bit easier with a button.
|
Call a function in a cog using a discord button |
|python|discord.py|discord-buttons| |
null |
import random
def create_matrix(n, m, d):
total_elements = n * m
total_ones = int(total_elements * d)
matrix = [[0] * m for _ in range(n)]
ones_indices = random.sample(range(total_elements), total_ones)
for idx in ones_indices:
row = idx // m
col = idx % m
matrix[row][col] = 1
return matrix
# Example usage:
n = 3
m = 5
d = 0.3
result = create_matrix(n, m, d)
for row in result:
print(row)
Output:
[0, 0, 0, 0, 0]
[0, 0, 0, 1, 0]
[0, 0, 1, 1, 1]
Note: If you provide d=0, there are no ones and if d=1 the elements are all ones. |
It worked fine after switching from work account to personal account on the oculus.
it seems [work][1] account was having issues with the spatial anchors.
[1]: https://work.meta.com/ |
This is my code for the rest api in spring boot and jpa that has a function of performance report for employees but something is not working here, i dont know what.
Controller:
```
@GetMapping("/my-report")
public ResponseEntity<?> getReport(String name, String date){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false); // Strict check to ensure the entered string follows the format yyyy-MM-dd
Date newDate;
try {
newDate = dateFormat.parse(date);
} catch (Exception e) {
return ResponseEntity.badRequest().body("Invalid date format");
}
try {
byte[] report = service.generateReport(name, newDate);
if (report == null) { // In case there are no performances for the entered parameters
return ResponseEntity.ok("No performances found for the given parameters.");
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData("attachment", "report.pdf");
return ResponseEntity.ok()
.headers(headers)
.body(report);
} catch(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating report.");
```
Service:
```
public byte[] generateReport(String name, Date date) throws JRException, IOException {
if (performanceRepository.getPerformances(name, date).size() > 0) {
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(performanceRepository.getPerformances(name, date));
InputStream inputStream = this.getClass().getResourceAsStream("/jasperreports/performanceReport.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(inputStream);
Map<String, Object> params = new HashMap<>();
params.put("dateParam", date);
params.put("nameParam", name);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
inputStream.close();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(byteArrayOutputStream));
exporter.exportReport();
return byteArrayOutputStream.toByteArray();
}
return null;
}
```
Also i didnt forget to add `@EntityScan("model")` to main java file |
|csv|input|file-writing|csvwriter| |
null |
|python|csvwriter| |
Microsoft Visual studio sign in -
When sign in steps at the end of the process it shows this error "Your browser is not supported or up-to-date. Try updating it, or else download and install the latest version of Microsoft Edge." I reinstall it and change the default browser too. but no any changes
I reinstalled edge and changed the default browser from Edge to chrome, and updated the Edge also. Need to fixed this error "Your browser is not supported or up-to-date. Try updating it, or else download and install the latest version of Microsoft Edge." |
couldn't sign in visual studio code |
|visual-studio-code|microsoft-edge| |
null |
import tensorflow as tf
from keras.preprocessing.sequence import Tokenizer
from keras.utils import pad_sequences
# Set parameters
vocab_size = 5000
embedding_dim = 64
max_length = 100
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_size = len(processed_data)
# Create tokenizer
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_sequences(processed_data)
word_index = tokenizer.word_index
# Create sequences
sequences = tokenizer.texts_to_sequences(processed_data)
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Create training data
training_data = padded_sequences[:training_size]
training_labels = padded_sequences[:training_size]
# Build model
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Conv1D(64, 5, activation='relu'),
tf.keras.layers.MaxPooling1D(pool_size=4),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(vocab_size, activation='softmax')
])
# Compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train model
num_epochs = 50
history = model.fit(training_data, training_labels, epochs=num_epochs, verbose=2)
def predict_answer(model, tokenizer, question):
# Preprocess question
question = preprocess(question)
# Convert question to sequence
sequence = tokenizer.texts_to_sequences([question])
# Pad sequence
padded_sequence = pad_sequences(sequence, maxlen=max_length, padding=padding_type, truncating=trunc_type)
# Predict answer
pred = model.predict(padded_sequence)[0]
# Get index of highest probability
idx = np.argmax(pred)
# Get answer
answer = tokenizer.index_word[idx]
return answer
# Start chatbot
while True:
question = input('You: ')
answer = predict_answer(model, tokenizer, question)
print('Chatbot:', answer)
There is an opportunity to write to the chat in the terminal. When I write my message, it gives an error:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'model' is not defined |
Strange Error encountered when running a model on Azure Auto ML |
|azure|machine-learning|azure-machine-learning-service|automl|azure-auto-ml| |
null |
You just need to handle the [IFRAMES](https://www.selenium.dev/documentation/webdriver/interactions/frames/#:~:text=Iframes%20allow%20the%20insertion%20of,and%20are%20still%20commonly%20used.&text=However%2C%20if%20there%20are%20no,in%20the%20top%20level%20document.)
Check the working code below:
````
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
url = 'https://www.bursamalaysia.com/market_information/announcements/company_announcement/announcement_details?ann_id=3434107'
driver.get(url)
wait = WebDriverWait(driver,10)
try:
# Below line will switch into the IFRAME
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "bm_ann_detail_iframe")))
wait.until(EC.text_to_be_present_in_element((By.TAG_NAME, "body"), "Annual Audited Accounts"))
print("Found: Annual Audited Accounts")
except:
print("Text not found")
# Below line will come out of the IFRAME
driver.switch_to.default_content()
driver.quit()
````
Result:
````
Found: Annual Audited Accounts
Process finished with exit code 0
```` |
Please be gentle... I don't do much C++ and am trying to tidy up some code.... I'm trying to compile the code below in Arduino Studio, and it keeps throwing a `no matching function for call to 'devPort::devPort()'`
on the following line
` Sensor(String type, float adjustment, devPort port) {`
I've tried moving the devPort part to a new .cpp file and #include'ing it, but I get the same error.
I also tried
`Sensor(String type, float adjustment, devPort::devPort port)`
But still the same error.....
```
class devPort { // There will be 10 'Port's, all pre-defined as unavailable until the boardtype is known
public:
devPort(String name, int pin1, int pin2, int mode) {
this->name = name;
this->pin1 = pin1;
this->pin2 = pin2;
this->mode = mode;
}
String name;
int pin1;
int pin2;
int mode; // -1 = Disabled, 0 = SDA/SCL, 1=DAC, 2=ADC, 3=GPIO
};
// The 'Sensor's will be stored in the flash memory
class Sensor {
public:
Sensor(String type, float adjustment, devPort port) { // <--- This is where it complains
this->type = type;
this->adjustment = adjustment;
this->port = port;
}
String type; // Derived from *sensorTypes
float adjustment; // +/- adjustment value
devPort port; // Custom Port
};
```
I would expect that it should just allow this (and I've tried moving them above/below each other in case of linear compilation) |
Declaring classes in C++ constructor for another class reports "No matching function" |
|c++|arduino| |
null |
{"OriginalQuestionIds":[588004],"Voters":[{"Id":6870253,"DisplayName":"chtz"},{"Id":898348,"DisplayName":"Jabberwocky","BindingReason":{"GoldTagBadge":"c"}}]} |
How to create jasper report in spring boot rest api with jpa |
|spring-boot|spring-data-jpa|jasper-reports| |
null |