instruction stringlengths 0 30k ⌀ |
|---|
ERROR: failed to solve: failed to read dockerfile: failed to create lease: read-only file system |
|node.js|docker|dockerfile| |
Function for making the code wait in javafx |
|java|javafx|java-threads|pause| |
null |
CUDA Toolkit 12.4 (latest up to March 2024) doesn't provide xgetri function which is used in LAPACK for matrix inversion, in their cuSolver collection of LAPACK functions for dense matrices. I really don't know why they have not included xgetri in CUDA Toolkit, but if I want to implement matrix inversion using xgetrf+xgetrs, then I need to compose an identity matrix as right-hand-side which has leading dimension like the coefficient matrix and just fill its diagonal with one and leave large part of the memory on the device i.e., graphic card as zeros. This is not optimal from memory point of view, so I am wondering if anyone has any suggestion to do this task efficiently? I was also wondering if right-hand-side matrix (identity matrix in this case) can be stored in sparse format, but the library doesn't support it. |
You can create a utility type like this:
```ts
type PartialKeys<T, K extends keyof T> = Partial<Pick<T, K>> & Omit<T, K>;
```
And use it like this :
```ts
type I2 = PartialKeys<I1, 'field1' | 'field2'>
```
You can't easily "say I want the first N items" because TypeScript's type system doesn't support enforcing order in an object's properties
|
Im trying to mock `listObjects` function in `AmazonS3` interface, in order to return specific objects when running tests without calling s3.
The code I want to test is doing this logic:
```
val objects = s3Client.listObjects(
new ListObjectsRequest()
.withBucketName(bucketName)
.withMaxKeys(2000)
)
val latestSchemaKey = objects.getObjectSummaries.toList
.map(s => s.getKey)
.sorted(Ordering[String].reverse)
.head
```
I wanted to create a new `ObjectListing` and add `objectSummaries` to it, but seems like there are not setters for `objectSummaries`.
Is there something Im missing out?
Thanks for helping!
Looked into `ObjectListing` class functions and noticed its not possible to set objects :) |
Mocking AmazonS3 listObjects function in scala |
|scala|amazon-s3|testing| |
null |
{"OriginalQuestionIds":[53741993],"Voters":[{"Id":2887218,"DisplayName":"jcalz","BindingReason":{"GoldTagBadge":"typescript"}}]} |
You need to allocate those dynamically allocated arrays when your object is initialized and `count_sides` has a value. Since this is C++, you can give your struct a constructor.
```
struct regular_polygon {
int count_sides;
double length;
double square;
double perimeter;
double *x;
double *y;
regular_polygon(int count_sides, double length, double square, double perimeter)
: count_sides(count_sides),
length(length),
square(...),
perimeter(...),
x(new double[count_sides]),
x(new double[count_sides])
{ }
};
```
Now you also need to worry about a destructor and the [rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three).
You probably want to use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) or [`std::array`](https://en.cppreference.com/w/cpp/container/array).
|
if the user only enters spaces into the input field, it triggers a validation error |
I am planning to use AWS DMS to migrate Oracle data with the CDC option. It has a limitation on "AWS DMS doesn't support long object names (over 30 bytes)". As renaming the column will impact Datamodel and code changes, so i can't opt for that.
I tried research on Oracle Golden Gate but was not able to find any similar limitations or not.
Do we have any other options to migrate data with real-time data availability for the Oracle database?
|
AWS DMS VS Oracle Golden Gate for object names (over 30 bytes) |
|amazon-web-services|oracle-database|dms|oracle-golden-gate| |
{"OriginalQuestionIds":[61750222],"Voters":[{"Id":442760,"DisplayName":"cafce25","BindingReason":{"GoldTagBadge":"rust"}}]} |
import glob
import os
import zipfile
def remove_parent_path(parent_path, file_path):
# Get the relative path of the file_path with respect to the parent_path
relative_path = os.path.relpath(file_path, parent_path)
return relative_path
def compress_to(parent_path, out_file_path, structured_files=None, include_parent_dir=False):
with zipfile.ZipFile(out_file_path, 'w') as zipf:
for file in structured_files:
if not include_parent_dir:
zip_archive_name = remove_parent_path(parent_path, file)
else:
zip_archive_name = file
zipf.write(file, zip_archive_name)
if __name__ == '__main__':
parent_dir = 'out'
files_with_sub_dir = os.path.join(parent_dir, '*', '*.*')
out_file_path = 'sample.zip'`enter code here`
files_list = glob.glob(files_with_sub_dir, recursive=True)
compress_to(parent_dir, out_file_path, files_list, include_parent_dir=True)
|
So I have a model (made from realitykit pro) and I've added it as an Entity in my project on Xcode. The model is a simply rectangular prism (meant to simulate a block of skin). When a user drags their mouse in a line across a face of the model, I want to simulate making an incision by perhaps indenting/splitting the model on the axis the user has drawn. How would I go about this?
I'm not sure if you can animate an Entity based on a user's mouse position.
I've already importing a pre-made animation that splits a rectangle in half, but it does not rely on user's mouse position, which is something I'd like to implement so that incisions are made where the user wants.
Thank you! |
Animating Entity in VisionOS based on mouse gesture? |
|animation|entity|virtual-reality|realitykit|visionos| |
null |
I'm interested in developing extensions for Chrome OS. Is there any way to autofill password in Chrome OS login screen? |
Autofill password on Chrome OS login screen |
|google-chrome-extension|google-chrome-os| |
I am trying to display the route between two points in NEXTJS 13 using leaflet and the leaflet routing machine as the routing library. I don't know how to get the leaflet-routing-machine to work. I've tried creating functions but I'm so lost. Nothing seems to work Any help would be really appreciated.
```'use client';
import Image from 'next/image'
import 'leaflet/dist/leaflet.css'
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet';
import { GoogleMap, InfoWindowF, MarkerF, useJsApiLoader, LoadScript} from '@react-google-maps/api'
import bus from '../public/bus.jpg'
import { createControlComponent } from "@react-leaflet/core";
import "leaflet-routing-machine";
import { useState } from 'react';
import { Switch } from '@headlessui/react';
import bus1 from '../public/bus.jpg'
import L, { Routing, map } from "leaflet";
import {
LayersControl
} from "react-leaflet";
const containerStyle = {
width: '80%',
height: '100%'
};
const center = {
lat: -3.745,
lng: -38.523
};
const busStops: string[] = [
"ATM/ LIBRARY",
"ADMIN",
"MURNI",
"BW",
"AMANAH",
"DSS",
"ILMU",
"COE",
];
const maps = {
base: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
};
function route () {
const map = useMap;
};
export default function Home() {
const [map, setMap] = useState(null);
const [start, setStart] = useState([38.9072, -77.0369])
const [end, setEnd] = useState([37.7749, -122.4194])
const [show, setShow] = useState (false);
return (
<div className='w-screen bg-red-500 h-screen flex'>
<div className='w-[400px] bg-white flex flex-col '>
<div className='w-full h-[80px] flex justify-center items-center'>
<h1 className=' text-black'>Route Infomation</h1>
</div>
<div className=' h-full bg-white justify-center items-center flex flex-col p-10 space-y-12'>
<div className=' w-full bg-white text-black text-center'>Uniten Library</div>
<div className=' w-full bg-white text-black text-center'>Uniten Admin</div>
<div className=' w-full bg-white text-black text-center'>Cendekiawan</div>
<div className=' w-full bg-white text-black text-center'>Murni</div>
<div className=' w-full bg-white text-black text-center'>Amanah</div>
</div>
</div>
<MapContainer center={[2.976644517019155, 101.73402673751899]} zoom={30} scrollWheelZoom={true} className=' w-full h-full z-10'>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[2.9776400979295072, 101.73074640990319]}>
<Popup>
UNITEN Admin Building<br />
</Popup>
</Marker>
<Marker position={[2.976644517019155, 101.73402673751899]}>
<Popup >
<div className='w-[300px] h-[400px] flex flex-col rounded-lg'>
<div className=' h-1/3 w-full bg-white ease-in-out'> <Image className='rounded-xl h-full' src={bus} alt='/'/> </div>
<div className='flex justify-between items-center px-5'>
<div className=''> Uniten Library</div>
<p>ETA</p>
<p>Arrival Status</p>
</div>
<div className='flex'>
<div className=' h-1/3 w-full p-5'>Driver 1 </div>
<div className=' h-1/3 w-full p-5'>ETA: 7:45 AM</div>
<Switch
checked={show}
onChange={setShow}
className={`${show ? 'bg-green-500' : 'bg-gray-700'}
relative inline-flex h-[28px] w-[64px] shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75`}
>
<span className="sr-only">Use setting</span>
<span
aria-hidden="true"
className={`${show ? 'translate-x-9' : 'translate-x-0'}
pointer-events-none inline-block h-[24px] w-[24px] transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out`}
/>
</Switch>
</div>
</div>
</Popup>
</Marker>
<div>
</div>
{/* <Routing /> */}
</MapContainer>
</div>
)
}
``` |
Leaflet routing machine with NEXTJS |
|javascript|next.js|leaflet| |
> My expectation would be that creating the instance `Base` with the specified type `str` it is used for `V` which should be compatible in the `test()` return value as it converts to `Test[str](t)`
Your `b = Base[str]()` line has no retroactive effect on the definition of `class Base(Generic[V]):` whatsoever - the definition of `Base.test` simply fails the type check because `t` is `str` (via `t = '1'`), and so what's being returned is `Test[str]` and not a generic `Test[V]` - it's not a way to return "mix" types (see the [`typing.AnyStr`](https://docs.python.org/3/library/typing.html#typing.AnyStr) as an example and the documentation there has a discussion on this). Changing that assignment to `t = 1` and to `b = Base[int]()`, mypy will complain about the opposite:
```lang-text
error: Argument 1 to "Test" has incompatible type "int"; expected "str" [arg-type]
```
Using `pyright` actually gives a somewhat better error message:
```lang-text
/tmp/so_78174062.py:16:24 - error: Argument of type "Literal['1']"
cannot be assigned to parameter "a" of type "V@Base" in function "__init__"
Type "Literal['1']" cannot be assigned to type "V@Base" (reportArgumentType)
```
Which clearly highlights that these are two distinct types (one being a `str` and the other being a [`TypeVar` (type variable)](https://docs.python.org/3/library/typing.html#typing.TypeVar)").
Moreover, using the syntax introduced in [PEP 695](https://peps.python.org/pep-0695/) may in fact clear up some confusion (refer to the PEP for details); reformatting your example code in that syntax may help make clear what the intent actually is:
```python
@dataclass
class Test[V: (str, int)]:
a: V
class Base[V: (str, int)]:
def test(self) -> Test[V: (str, int)]:
t = 1
return Test[V: (str, int)](t)
```
It's a bit more clear that defining a return type `Test[V: (str, int)]` under this paradigm is not sensible, as the return type isn't one of the constrained types (so either `int` or `str`, and not whatever that `V: ...` tries to do). Not to mention that without the `class` prefixing `Test` pyright interpreted the subsequent `Test[V: (str, int)]` as a `slice` operation which is also nonsensical in that context.
Based on the given code in the question, the `test` method really should have this signature:
```lang-python
def test(self) -> Test[str]:
t = '1'
return Test[str](t)
```
The above would type check correctly.
|
null |
|flutter|dart|slider| |
```
@override
Widget build(BuildContext context) {
double currentSliderValue = 100.0;
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Slider(
value: currentSliderValue,
onChanged: (double value) {
setState(() {
currentSliderValue = value;
});
},
label: '$currentSliderValue',
),
),
);
}
}
```
I tyied to make a slider , its very similir as other example, its value could be changed, but didnt move at all |
It would be better for you to set your board in a different way. So far you have a unique list, `row`, which you print ten times to simulate a board. This will make it uncomfortable to keep track of changes, as you whish to do. Use a 2d list instead:
```
board = [[" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "],
[" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "],
...
]
```
Of course, you can generate this board automatically:
```python
board = [["#" for _ in range(10)] for _ in range(10)]
```
Then you can ask for two integers as input, call them `i` and `j`, and set `board[i][j] = "X"`. This will produce the desired result. |
I get two errors when using google maps API:
1. Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
2. a is null (main.js)
I don't know if there is any connection between the two, but the final result is that my page cannot load the map.
Here is my head tag:
<script type="text/javascript" src="../s/Jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="../s/jquery.placeholder.min.js"></script>
<script type="text/javascript" src="../s/index.js"></script>
<script type="text/javascript" src="../s/Jquery/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="../s/Jquery/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../s/Jquery/ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="../s/Jquery/ui/jquery.ui.autocomplete.js"></script>
<script src="../dd/markerclusterer_compiled.js" type="text/javascript"></script><script src="../dd/dealers_js.js" type="text/javascript"></script><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Here is the function which I call the google map:
function set_google_map(set_region)
{
var zoom;
var center;
switch (set_region) {
case "usa":
zoom = 3;
center = new google.maps.LatLng(37.09, -95.71);
break;
case "europe":
zoom = 3;
center = new google.maps.LatLng(48.58, 7.71);
break;
case "east":
zoom = 3;
center = new google.maps.LatLng(31, 121);
break;
default:
zoom = 1;
center = new google.maps.LatLng(35, 5);
}
// Creating the map
map = new google.maps.Map(document.getElementById('map'), options);
google.maps.event.addListener(map, 'click', function(){
clean_icons();
if (infowindow)
infowindow.close();
});
map.setCenter(center);
map.setZoom(zoom);
//bounds = new google.maps.LatLngBounds();
}
These are my variables:
var UseridEncr;
var super_category="ATE";
var infowindow;
var map;
var bounds;
var image="../dd/i/green.png";
var image_active="../dd/i/red.png";
var mc ;
var location_changed=true;
var current_region="usa";
var mcOptions = {gridSize:30, maxZoom: 8};
var last_marker;
var last_marker_z;
var DealersData ;
var markers=[];
var markers_selected=[];
claster_markers=[];
var current_view=0;
myData={};
var selected_items=[];
var total_selected=0;
Thanks for your prompt answer. |
I'm trying to rejigger my usage of web worker pooling to eliminate redundant server requests. In my existing solution, I'm loading workers pretty straightforwardly like this:
```js
const worker = new Worker(`${src}?v=${version}`);
```
This happens `N` times for each worker pool. WebPack has no problem with this. But, in production, the `N` requests are superfluous, wasteful, and seem to introduce a little unnecessary latency. So, I'd like to get rid of them. To that end, I'm trying to load my worker code with a cached/debounced `fetch()` and feed the contents into the worker with a blob URL.
```js
const worker = getBundleBlobURI(src).then(uri => {
return new Worker(uri);
});
```
Functionally, the worker is loading and operational. But locally, WebPack is now trying and failing to reconnect to `ws://0.0.0.0:9999/ws` on repeat, *flooding* the console with errors in the process.
How do make it stop?
---
My current workaround is *essentially* to use blobs only in staging + prod:
```js
const isLocal = checkIfHostnameIsLocalhost(); // more or less
if (isLocal) {
const worker = new Worker(src);
} else {
const worker = getBundleBlobURI(src).then(uri => {
return new Worker(uri);
});
}
```
But, because I'm running slightly different code in dev environments, this comes with the risk of caching catastrophic regressions *late* (possibly even in production). |
null |
Can you try to create a constructor for a tool adapter like this
activity = activity.getActivity();
you were trying to assign the activity to the value.
|
{"Voters":[{"Id":9223839,"DisplayName":"Joakim Danielson"},{"Id":1974224,"DisplayName":"Cristik"},{"Id":12738750,"DisplayName":"lorem ipsum"}]} |
Just use this property on the input tag
onInput={(e) => {e.target.value = Math.abs(e.target.value);}}
|
1. You cannot use an async method in this case (or at least, you cannot use the promise returned from it). Your `isActive` method should be synchronous.
```
methods: {
isActive(){
return this.editor.isActive(this.title.toLowerCase())
}
}
```
Also, you can call the editor directly in template:
```
<button
class="menu-item"
:class="{ 'is-active bg-zinc-800 rounded-sm': editor.isActive(title.toLowerCase()) }"
@click="(e) => {
e.preventDefault();
action();
}"
:title="title"
>
<i :class="`ri-${icon} ri-fw`"></i>
</button>
```
2. The error is stating that the editor is undefined. You have to options:
Make sure the editor is initiated before mounting the menu-bar.
```
<menu-bar v-if="editor" :editor="editor"></menu-bar>
```
Or, check if the editor is defined before calling it.
```
isActive() {
return !!this.editor && this.editor.isActive(this.title.toLowerCase());
}
```
Working [sandbox](https://codesandbox.io/p/sandbox/vigilant-wave-jzvdsw?file=%2Fsrc%2FMenuItem.vue%3A29%2C22).
|
|python|pandas|dataframe|csv| |
New Azure Function App processes blobs that were already processed by another Function App |
I have a lambda processing kinesis events.
Kinesis has 3 retries in case of failure.
The lambda process the events properly but it is called 4 times.
I have looking for what can be the cause and I have found this:
[cloudshell-user@ip-10-130-89-49 ~]$ aws lambda list-event-source-mappings --event-source-arn arn:aws:kinesis:us-east-1:xxxx:stream/xxxx
{
"EventSourceMappings": [
{
"UUID": "xxx-xx-xx-xx-xxxx",
"StartingPosition": "LATEST",
"BatchSize": 100,
"MaximumBatchingWindowInSeconds": 3,
"ParallelizationFactor": 1,
"EventSourceArn": "arn:aws:kinesis:us-east-1:xxxxxx:stream/xxxxx-ingestion-kinesis",
"FunctionArn": "arn:aws:lambda:us-east-1:xxxxx:function:yyyyyy:PROD",
"LastModified": "2024-03-26T12:46:00+00:00",
"LastProcessingResult": "PROBLEM: Function response syntax is invalid. Please check function implementation.",
"State": "Enabled",
"StateTransitionReason": "User action",
"DestinationConfig": {
"OnFailure": {}
},
"MaximumRecordAgeInSeconds": 3600,
"BisectBatchOnFunctionError": true,
"MaximumRetryAttempts": 3,
"TumblingWindowInSeconds": 60,
"FunctionResponseTypes": []
}
]
}
I have been searching for
> "PROBLEM: Function response syntax is invalid. Please check function implementation."
but I don´t find anything about it.
Any idea? |
It's an array of pointers to C strings (or char arrays). Where each element in the array is in [], and each string of chars is an array of characters typically terminated by a null character or a zero byte.
In main() the argc parameter specifies how many strings there are in the char *arcv[] array.
The operating system when calling into main will specify the number of parameters, the int argc value as well as the command line parameters provided to main() in the char *argv[] parameter.
The first argv parameter is typically the program name itself, and this is followed by any additional parameters specified on the command line.
So for instance if you did:
./program.bin parameter1 --option1
And the data in it would be dereferenced like this:
puts(argv[0]) // would be "./program.bin"
puts(argv[1]) // would be "parameter1"
puts(argv[2]) // would be "--option1"
and argc would be 3.
The way i'd think of this is as char **argv, in fact you can replace char *argv[] as char **argv.
And I would think of this in the layout char *(argv[stringnum]) or (argv[stringnum])[letternum] or just argv[stringnum][letternum]
|
Since .Net 4.5, the preferred way to implement data validation is to implement [`INotifyDataErrorInfo`][1] (example from [Technet][2], example from [MSDN (Silverlight)][3]).
Note: `INotifyDataErrorInfo` replaces the obsolete `IDataErrorInfo`.
The new framework infrastructure related to the `INotifyDataErrorInfo` interface provides many advantages like
- support of multiple errors per property
- custom error objects and customization of visual error feedback (e.g. to adapt visual cues to the custom error object)
- asynchronous validation using async/await
----------
How `INotifyDataErrorInfo` works
================================
When the `ValidatesOnNotifyDataErrors` property of `Binding` is set to `true`, the binding engine will search for an `INotifyDataErrorInfo` implementation on the binding source and subscribe to the [`INotifyDataErrorInfo.ErrorsChanged`][4] event.
If the `ErrorsChanged` event of the binding source is raised and `INotifyDataErrorInfo.HasErrors` evaluates to `true`, the binding engine will invoke the [`INotifyDataErrorInfo.GetErrors(propertyName)`][5] method for the actual source property to retrieve the corresponding error message and then apply the customizable validation error template to the target control to visualize the validation error.
By default, a red border is drawn around the element that has failed to validate.
In case of an error, which is when `INotifyDataErrorInfo.HasErrors` returns `true`, the binding engine will also set the attached [`Validation`][6] properties on the binding target, for example `Validation.HasError` and `Validation.ErrorTemplate`.
To customize the visual error feedback, we can override the default template provided by the binding engine, by overriding the value of the attached `Validation.ErrorTemplate` property (see example below).
The described validation procedure only executes when `Binding.ValidatesOnNotifyDataErrors` is set to `true` on the particular data binding and the `Binding.Mode` is set to either `BindingMode.TwoWay` or `BindingMode.OneWayToSource`.
How to implement `INotifyDataErrorInfo`
=======================================
The following examples show three variations of property validation using
1) `ValidationRule` (class to encapsulate the actual data validation implementation)
2) lambda expressions (or delegates)
3) validation attributes (used to decorate the validated property).
Of course, you can combine all three variations to provide maximum flexibility.
The code is not tested. The snippets should all work, but may not compile due to typing errors. This code is intended to provide a simple example on how the `INotifyDataErrorInfo` interface could be implemented.
----------
Preparing the view
------------------
**MainWindow.xaml**
To enable the visual data validation feedback, the [`Binding.ValidatesOnNotifyDataErrors`][9] property must be set to `true` on each relevant `Binding` i.e. where the source of the `Binding` is a validated property. The WPF framework will then show the control's default error feedback.
**Note:** to make this work, the **`Binding.Mode` must be either `OneWayToSource` or `TwoWay`** (which is the default for the `TextBox.Text` property):
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<!-- Important: set ValidatesOnNotifyDataErrors to true to enable visual feedback -->
<TextBox Text="{Binding UserInput, ValidatesOnNotifyDataErrors=True}"
Validation.ErrorTemplate="{DynamicResource ValidationErrorTemplate}" />
</Window>
The following is an example of a custom validation error template.
The default visual error feedback is a simple red border around the validated element. In case you like to customize the visual feedback e.g., to allow showing error messages to the user, you can define a custom `ControlTemplate` and assign it to the validated element (in this case the `TextBox`) via the attached property [`Validation.ErrorTemplate`][10] (see above).
The following `ControlTemplate` enables showing a list of error messages that are associated with the validated property:
[![enter image description here][11]][11]
<ControlTemplate x:Key="ValidationErrorTemplate">
<StackPanel>
<Border BorderBrush="Red"
BorderThickness="1">
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="AdornedElement" />
</Border>
<Border Background="White"
BorderBrush="Red"
Padding="4"
BorderThickness="1,0,1,1"
HorizontalAlignment="Left">
<ItemsControl ItemsSource="{Binding}" HorizontalAlignment="Left">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ErrorContent}"
Foreground="Red"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</StackPanel>
</ControlTemplate>
----------
The view model is responsible for validating its own properties to ensure the data integrity of the model.
I recommend moving the implementation of `INotifyDataErrorInfo` into a base class (e.g. an abstract `ViewModel` class) together with the `INotifyPropertyChanged` implementation and letting all your view models inherit it. This makes the validation logic reusable and keeps your view model classes clean.
1 Data validation using `ValidationRule`
------------------------
**ViewModel.cs**
When using [`ValidationRule`][7], the key is to have separate `ValidationRule` implementations for each property or rule.
Extending `ValidationRule` is optional. I chose to extend `ValidationRule` because it the implementations can be reused with binding validation if necessary.
Basically, the result of the property validation should be a `bool` to indicate fail or success of the validation and a message that can be displayed to the user to help him to fix his input.
> When implementing the MVVM design pattern it is recommended to create a custom `ValidationRule` base class and a custom `ValidationResult`.
This is because the framework's `ValidationRule` and its `ValidationResult` are both located in the `System.Windows.Controls` namespace that requires a reference to the *PresentationFramework.dll* assembly.
You may want to avoid this reference.
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
// Example property, which validates its value before applying it
private string userInput;
public string UserInput
{
get => this.userInput;
set
{
// Validate the value
bool isValueValid = IsPropertyValid(value);
// Optionally reject value if validation has failed
if (isValueValid)
{
this.userInput = value;
OnPropertyChanged();
}
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
this.ValidationRules = new Dictionary<string, HashSet<ValidationRule>>();
// Create a Dictionary of validation rules for fast lookup.
// Each property name of a validated property maps to one or more ValidationRule.
RegisterValidationRule(nameof(this.UserInput), new UserInputValidationRule());
}
protected void RegisterValidationRule(string propertyName, IEnumerable<ValidationRule> validationRules)
{
foreach (ValidationRule validationRule in validationRules)
{
RegisterValidationRule(propertyName, validationRule);
}
}
protected void RegisterValidationRule(string propertyName, ValidationRule validationRule)
{
if (!this.ValidationRules.TryGetValue(propertyName, out HashSet<ValidationRule> validationRulesForProperty))
{
validationRulesForProperty = new HashSet<ValidationRule>();
this.ValidationRules.Add(propertyName, validationRulesForProperty);
}
validationRulesForProperty.Add(validationRule);
}
// Validation method.
// Is called from each property which needs to validate its value.
// Because the parameter 'propertyName' is decorated with the 'CallerMemberName' attribute.
// this parameter is automatically generated by the compiler.
// The caller only needs to pass in the 'propertyValue', if the caller is the target property's set method.
public bool IsPropertyValid<TValue>(TValue propertyValue, [CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
_ = ClearErrors(propertyName);
if (this.ValidationRules.TryGetValue(propertyName, out HashSet<ValidationRule> propertyValidationRules))
{
// Apply all the rules that are associated with the current property
// and validate the property's value
IEnumerable<object> errorMessages = propertyValidationRules
.Select(validationRule => validationRule.Validate(propertyValue, CultureInfo.CurrentCulture))
.Where(result => !result.IsValid)
.Select(invalidResult => invalidResult.ErrorContent);
AddErrorRange(propertyName, errorMessages);
return !errorMessages.Any();
}
// No rules found for the current property
return true;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional method to check if a particular property has validation errors
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
// The WPF binding engine will listen to this event
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// This implementation of GetErrors returns all errors of the specified property.
// If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
// This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnumerable<object>)errors
: new List<object>();
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
// Maps a property name to a list of ValidationRules that belong to this property
private Dictionary<string, HashSet<ValidationRule>> ValidationRules { get; }
}
**UserInputValidationRule.cs**
This example validation rule extends [`ValidationRule`][7] and checks if the input starts with the '@' character. If not, it returns an invalid [`ValidationResult`][8] with an error message that is automatically displayed as feedback to the user (with help of the previouisly defined error template).
public class UserInputValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (!(value is string userInput))
{
return new ValidationResult(false, "Value must be of type string.");
}
return userInput.StartsWith("@")
? ValidationResult.ValidResult
: new ValidationResult(false, "Input must start with '@'.");
}
}
----------
2 Data validation using lambda expressions and delegates
----------------------------------------
As an alternative approach, the `ValidationRule` can be replaced (or combined) with delegates to enable the use of Lambda expressions or Method Groups.
The validation expressions in this example return a tuple containing a boolean to indicate the validation state and a collection of `string` error objects for the actual messages. Since all error object related properties are of type `object`, the expressions can return any custom data type, in case you need more advanced error feedback and `string` is not a sufficient. In this case, we would have to adjust the validation error template, to enable it to handle the data type.
**ViewModel.cs**
// Example uses System.ValueTuple
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
// This property is validated using a lambda expression
private string userInput;
public string UserInput
{
get => this.userInput;
set
{
// Validate the new property value.
bool isValueValid = IsPropertyValid(value,
newValue => newValue.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." }));
// Optionally, reject value if validation has failed
if (isValueValid)
{
// Accept the valid value
this.userInput = value;
OnPropertyChanged();
}
}
}
// Alternative usage example property, which validates its value
// before applying it, using a Method Group.
private string userInputAlternative;
public string UserInputAlternative
{
get => this.userInputAlternative;
set
{
// Use Method Group
if (IsPropertyValid(value, IsUserInputValid))
{
this.userInputAlternative = value;
OnPropertyChanged();
}
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
}
// The validation method for the UserInput property
private (bool IsValid, IEnumerable<object> ErrorMessages) IsUserInputValid(string value)
{
return value.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." });
}
// Example uses System.ValueTuple
public bool IsPropertyValid<TValue>(
TValue value,
Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate,
[CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
_ = ClearErrors(propertyName);
// Validate using the delegate
(bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>());
if (!validationResult.IsValid)
{
AddErrorRange(propertyName, validationResult.ErrorMessages);
}
return validationResult.IsValid;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional method to check if a particular property has validation errors
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
// The WPF binding engine will listen to this event
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// This implementation of GetErrors returns all errors of the specified property.
// If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
// This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnumerable<object>)errors
: new List<object>();
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
}
----------
3 Data validation using `ValidationAttribute`
-------------------------------------------
This is an example implementation of `INotifyDataErrorInfo` with [`ValidationAttribute`][12] support e.g., [`MaxLengthAttribute`][13].
This solution combines the previous Lambda version to additionally support validation using a Lambda expression/delegate simultaneously.
While validation using a lambda expression or a delegate must be explicitly invoked by calling the `TryValidateProperty` method in the property's setter, the attribute validation is executed implicitly from the `OnPropertyChanged` event invocator (as soon the property was decorated with validation attributes):
**ViewModel.cs**
// Example uses System.ValueTuple
public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
private string userInput;
// Validate property using validation attributes
[MaxLength(Length = 5, ErrorMessage = "Only five characters allowed.")]
public string UserInput
{
get => this.userInput;
set
{
// Optional call to 'IsPropertyValid' to combine with attribute validation
// with a delegate
bool isValueValid = IsPropertyValid(value, newValue => newValue.StartsWith("@")
? (true, Enumerable.Empty<object>())
: (false, new[] { "Value must start with '@'." }));
this.userInput = value;
// Triggers checking for validation attributes and their validation,
// if any validation attributes were found (like 'MaxLength' in this example)
OnPropertyChanged();
}
}
// Constructor
public ViewModel()
{
this.Errors = new Dictionary<string, IList<object>>();
// Collect all properties that are decorated with validation attributes
this.DecoratedPropertyInfoMap = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)
.Where(entry => entry.Value.GetCustomAttributes(typeof(ValidationAttribute)).Any())
.ToDictionary(propertyInfo => propertyInfo.Name);
}
// Validate property using attributes.
// Is invoked by 'OnPropertyChanged' (see below).
protected bool IsAttributedPropertyValid<TValue>(string propertyName)
{
// The result flag
bool isValueValid = true;
if (!this.DecoratedPropertyInfoMap.TryGetValue(propertyName, out PropertyInfo propertyInfo))
{
return true;
}
object value = propertyInfo.GetValue(this);
var validationContext = new ValidationContext(this, null, null) { MemberName = propertyName };
var validationResults = new List<ValidationResult>();
if (!Validator.TryValidateProperty(value, validationContext, validationResults))
{
isValueValid = false;
AddErrorRange(propertyName, validationResults.Select(attributeValidationResult => attributeValidationResult.ErrorMessage));
}
return isValueValid;
}
public bool IsPropertyValid<TValue>(
TValue value,
Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate = null,
[CallerMemberName] string propertyName = null)
{
// Clear previous errors of the current property to be validated
ClearErrors(propertyName);
// Validate using the delegate
(bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>());
if (!validationResult.IsValid)
{
// Store the error messages of the failed validation
AddErrorRange(propertyName, validationResult.ErrorMessages);
}
return validationResult.IsValid;
}
// Adds the specified errors to the errors collection if it is not
// already present, inserting it in the first position if 'isWarning' is
// false. Raises the ErrorsChanged event if the Errors collection changes.
// A property can have multiple errors.
private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false)
{
if (!newErrors.Any())
{
return;
}
if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors))
{
propertyErrors = new List<object>();
this.Errors.Add(propertyName, propertyErrors);
}
if (isWarning)
{
foreach (object error in newErrors)
{
propertyErrors.Add(error);
}
}
else
{
foreach (object error in newErrors)
{
propertyErrors.Insert(0, error);
}
}
OnErrorsChanged(propertyName);
}
// Removes all errors of the specified property.
// Raises the ErrorsChanged event if the Errors collection changes.
public bool ClearErrors(string propertyName)
{
if (this.Errors.Remove(propertyName))
{
OnErrorsChanged(propertyName);
return true;
}
return false;
}
// Optional
public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any();
#region INotifyDataErrorInfo implementation
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// Returns all errors of a property. If the argument is 'null' instead of the property's name,
// then the method will return all errors of all properties.
public System.Collections.IEnumerable GetErrors(string propertyName)
=> string.IsNullOrWhiteSpace(propertyName)
? this.Errors.SelectMany(entry => entry.Value)
: this.Errors.TryGetValue(propertyName, out IList<object> errors)
? (IEnuemrable<object>)errors
: new List<object>();
public bool HasErrors => this.Errors.Any();
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (this.DecoratedPropertyInfoMap.ContainsKey(propertyName))
{
_ = IsAttributedPropertyValid(propertyName);
}
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnErrorsChanged(string propertyName)
{
this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
// Maps a property name to a list of errors that belong to this property
private Dictionary<string, IList<object>> Errors { get; }
// List of property names of properties tha are decorated with a ValidationAttribute
// to improve performance by avoiding unnecessary reflection.
private readonly Dictionary<string, PropertyInfo> DecoratedPropertyInfoMap { get; }
}
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2
[2]: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx
[3]: https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ee652637(v=vs.95)#examples
[4]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.errorschanged?view=net-5.0#remarks
[5]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.geterrors?view=net-5.0#remarks
[6]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation?view=windowsdesktop-6.0
[7]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationrule?view=netcore-3.1#examples
[8]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationresult?view=netcore-3.1#examples
[9]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.binding.validatesonnotifydataerrors?view=net-5.0#remarks
[10]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation.errortemplate?view=net-5.0#remarks
[11]: https://i.stack.imgur.com/CjikQ.png
[12]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?view=netcore-3.1
[13]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netcore-3.1 |
I have to create a mail layout using Javas GUI.... I have managed to create a layout in which textfields increase in size horizontally which is a requirement ,and I have stacked them vertically using Y_Axis of Box Layout. But they are also increasing in size when i resize vertically and i dont want that.
import javax.swing.*;
import java.awt.*;
public class MailLayout {
public static void main(String\[\] args) {
String title = "New Message";
MyWindow myWindow = new MyWindow(title);
myWindow.setVisible(true);
}
}
class MyWindow extends JFrame {
//private static final int WIDTH = 500, HEIGHT = 400;
private JPanel myPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel myPanel2 = new JPanel();
private JPanel myPanel21 = new JPanel();
private JPanel myPanel3= new JPanel();
private JPanel myPanel31= new JPanel();
private JLabel label1 = new JLabel("To:");
private JLabel label2 = new JLabel("Cc:");
private JLabel label3 = new JLabel("Bcc:");
private JLabel label4 = new JLabel("Subject:");
private JLabel label5 = new JLabel("From:");
private JButton button = new JButton("Send");
private JTextField textfield1 = new JTextField("");
private JTextField textfield2 = new JTextField("");
private JTextField textfield3 = new JTextField("");
private JTextField textfield4 = new JTextField("");
public MyWindow(String title) {
super(title);
myPanel1.add(button);
this.add(myPanel1,BorderLayout.NORTH);
//myPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.setLayout(new BoxLayout(myPanel21, BoxLayout.Y_AXIS));
//label1.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.add(label1);
//label2.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.add(label2);
//label3.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.add(label3);
//label4.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.add(label4);
// label5.setBorder(BorderFactory.createLineBorder(Color.black));
myPanel21.add(label5);
myPanel2.add(myPanel21);
this.add(myPanel2,BorderLayout.WEST);
myPanel3.setLayout(new BoxLayout(myPanel3, BoxLayout.Y_AXIS));
myPanel3.add(textfield1);
myPanel3.add(textfield2);
myPanel3.add(textfield3);
myPanel3.add(textfield4);
this.add(myPanel3);
this.setSize(500,400);
this.setLocationRelativeTo(null);
// Tell jvm to kill program when window closes.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} |
I'm pretty sure I'm missing something simple here (hopefully) but I can't figure out what it is so any help will be very much appreciated.
I have the following procedure
CREATE OR REPLACE PROCEDURE schema_name.procedure_to_insert(
in input_schema character varying,
IN input_name character varying,
in input_data character varying,
IN input_hash character varying,
IN input_description text,
IN input_user_id int2
)
LANGUAGE plpgsql
AS $procedure$
begin
execute format('
insert
into %1$I.table_name (
col_name,
col_data,
col_hash,
col_description,
col_user_id
)
values(
%2$s,
%3$s,
%4$s,
%5$s,
%6$s
)
on conflict (name) do nothing;
', input_schema, input_name, input_data, input_hash, input_description, input_user_id );
end;
$procedure$
;
I call that procedure as follows:
call schema_name.procedure_to_insert(
'val_schema',
'val_name',
'val_data',
'val_hash',
'val_desc',
'1'
);
The table where the insert has to happen has the previously mentioned fields plus some other fields with default values
Running the call produces the following error message:
> SQL Error [42703]: ERROR: column "val_name" does not exist Where:
> PL/pgSQL function procedure_to_insert(character varying,character
> varying,character varying,character varying,text,smallint) line 3 at
> EXECUTE
Replacing the values part of the procedure for the following gives the same error:
values(
input_name,
input_data,
input_hash,
input_description,
input_user_id
)
|
value for insert on a procedure call is taken as column name generating an error that reports such column doesn't exist |
|postgresql|stored-procedures|parameter-passing|sql-insert| |
I have a parameter packed fuction as follows,
```
template<typename... Args>
void foo(const Args&... args)
{
bar( SomeClass<Args, ??> { args }... );
}
```
Without the `??` part above, this is a normal parameter pack expansion.
However, I would like ?? to be a type from `typedef std::tuple<(a list of types computed somewhere else)> typeLists;`, with the same sequence as the parameter pack.
I.e., for the first type in parameter pack, ?? should be the first type in `typeLists`, etc.
It's ensured that the number of types in `typeLists` is the same as the size of parameter pack.
Is there a way to implement this? I read some similar questions but none is exactly the same. I think it probably requires to use `index_sequence` but I'm not sure how.
Thanks a lot. |
The issue is with the **connection string** name. Make sure that the connection string key in `app_settings` block matches with the `config_json` connection name value.
```bash
app_settings = {
"connectionjahn" = azurerm_eventhub_namespace.example.default_primary_connection_string
}
```
```bash
config_json = jsonencode({
"bindings" = [
{
"authLevel" = "function"
"direction" = "in"
"name" = "req"
"type" = "eventHubTrigger"
"connection" = "connectionjahn"
}
]
})
```
***Note***: The connection name `"connectionjahn"` remains consistent in both of the above provided code snippets. Modify in your code accordingly.
***Complete terraform code is given below:***
```bash
provider "azurerm"{
features{}
}
data "azurerm_resource_group" "example" {
name = "xxxx"
}
resource "azurerm_storage_account" "example" {
name = "functionsapptejstsa"
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "LRS"
}
resource "azurerm_service_plan" "example-linux-serviceplan" {
name = "linux-service-planj"
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
os_type = "Linux"
sku_name = "S1"
}
resource "azurerm_eventhub_namespace" "example" {
name = "examplejanamespace"
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
sku = "Standard"
capacity = 2
}
resource "azurerm_linux_function_app" "example-linux-app" {
name = "example-linux-appja"
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
service_plan_id = azurerm_service_plan.example-linux-serviceplan.id
storage_account_name = azurerm_storage_account.example.name
storage_account_access_key = azurerm_storage_account.example.primary_access_key
app_settings = {
"connectionjahn" = azurerm_eventhub_namespace.example.default_primary_connection_string
}
site_config {
application_stack {
python_version = "3.11"
}
}
}
resource "azurerm_function_app_function" "example" {
name = "example-function-apjahfunction"
function_app_id = azurerm_linux_function_app.example-linux-app.id
language = "Python"
test_data = jsonencode({
"name" = "Azure"
})
config_json = jsonencode({
"bindings" = [
{
"authLevel" = "function"
"direction" = "in"
"name" = "req"
"type" = "eventHubTrigger"
"connection" = "connectionjahn"
}
]
})
}
```
***Deployment succeeded:***

 |
You're looking for [`.layoutPriority()`][1] !
This view modifier basically shrinks the least prioritized views before the more prioritized views when resizing is necessary.
This is how you could use it:
```
VStack(alignment: .leading) {
Text("Title")
.lineLimit(2)
.layoutPriority(1)
Text("Subtitle")
.lineLimit(2)
// The default layout priority is 0 so you don't need to set it explicitly
}
```
[1]: https://developer.apple.com/documentation/swiftui/view/layoutpriority(_:) |
I am trying to access the below iframe:
But everything I try it is unable to locate it, therefore the first_name_value element cannot be found to interact with and populate the text box.
Two avenues included in the code below, one is accessing normally with xpath and the other is hard defining of the iframe name and using js. Neither work.
Here is the HTML for the iframe, no src may be the issue? If so how can I overcome this
<iframe tabindex="-1" id="swift-registration-306700405343797-2" name="swift-registration-306700405343797-2" title="swift-registration-306700405343797-2" allow="screen-wake-lock" src="about:blank" style="width: 100%; height: 684px; position: relative; top: 0px; right: 0px; z-index: 10;"> </iframe>
This is the code
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import pyautogui
# Path to your Chrome WebDriver executable
chromedriver_path = '/Users/nickyoung/Downloads/chromedriver-mac-x64/chromedriver'
# Set Chrome options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
# Initialize Chrome WebDriver
driver = webdriver.Chrome(service=Service(executable_path=chromedriver_path), options=chrome_options)
# Navigate to the login page
driver.get('https://luxury3.gameassists.co.uk/gambit/en/registration?atk=wizfulloccupation')
WebDriverWait(driver, 15).until(EC.url_contains('https://luxury3.gameassists.co.uk/gambit/en/registration'))
time.sleep(10) #wait for page to fully load, its slow
#test to access another iframe, works fine
login_iframe_locator = (By.XPATH, '//*[@id="login-proxy"]')
WebDriverWait(driver, 15).until(EC.frame_to_be_available_and_switch_to_it(login_iframe_locator))
#SAME PROCESS FOR THE REGISTRATION IFRAME, BUT THIS FAILS
#reg_iframe_locator = (By.XPATH, '//*[@id="swift-registration-306700405343797-2"]')
#WebDriverWait(driver, 15).until(EC.frame_to_be_available_and_switch_to_it(reg_iframe_locator))
# Instead try to Execute JavaScript to switch to the iframe using its ID
iframe_name = "swift-registration-306700405343797-2"
driver.execute_script(f"document.getElementByName('{iframe_name}').contentWindow.document.body")
# Also Fails
# Wait for the first name input field to be visible
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '/html/body/div/div/div/mgs-text-input-v-01[1]/div/input')))
first_name_input = driver.find_element(By.XPATH, '/html/body/div/div/div/mgs-text-input-v-01[1]/div/input')
# Click on the input field to focus on it
first_name_input.click()
# Send keys to the first name input field
first_name_input.send_keys('ITSAutomation')
# After interacting with elements within the iframe, switch back to the default content
driver.switch_to.default_content()
Thanks |
How to use Layout to create textfields which dont increase in size? |
|java|swing| |
null |
No, similar to sections in a typical printed book, this is not possible in reStructuredText. Neither the rST syntax nor the Dotutils document model provide for main section content after a subsection.
The "[topic](https://docutils.sourceforge.io/docs/ref/rst/directives.html#topic)" and "sidebar" directives provide for nested text parts with a title. They are intended for parts outside the main flow of the document and the title does not appear in the table of contents.
A transition may be used to denote a break after one or more paragraphs, although technically the part after a transition is at the same section level as before. |
You link to the path to your document (less the file extension), not the title, so to link to `another-page.rst`, the link is inserted as follows:
```
Link to another page :doc:`another-page`
``` |
Dynamic query creation with Array like implementation |
just use conditional rendering on the image or set timeout if you want to toggle the image
That is really any easy task use another image with light bulb on and use conditional rendering |
If you want a single plot with two y-axes, it's possible with ggplo2 but requires a bit of fiddling.
1) You can add a second y-axis with a magnitude scaled relative to the first one using
```
+ scale_y_continuous(
# Add a second axis and specify its features
sec.axis = sec_axis(~./6000, name="Belysning")
)
```
Here, I'm taking the first axis to go up to 6000. I would recommend manually setting the first y-axis-limit so the two are 100% congruent.
2. Now you add the points/lines for "Belysning" to the plot.
Note, they're plotted relative to y-axis 1, so you need to rescale them.
```
+ geom_line( aes(y=Belysning * 6000), color=gold2)
```
3. Combined, it should look something like (I haven't been able to test this due to no data sample):
```
plot_data <- cbind(complete_july_data,complete_august_data)
plot_data <- full_join(result_df, plot_data, join_by(Dato == DATE))
plot <- ggplot(plot_data, aes(x=Dato)) +
geom_bar(aes(y = Count, fill = MANUAL.ID.),
stat = "identity", width = 0.7, position = "dodge") +
geom_line(aes(y = Belysning*6000), color = "gold2") +
geom_point(aes(y = Belysning*6000), color = "goldenrod", size = 2) +
labs(title = "Kumulative kurver for juli og august ved Borupgård 2018",
x = "Dato",
y = "Kumulative observationer",
fill = "Art") +
scale_y_continuous(
limits = c(0,6000)
name = "Kumulative observationer",
sec.axis = sec_axis(~./6000, name="Belysning")
) +
scale_x_date(limits = as.Date(c("2018-07-26", "2018-08-29")),
date_breaks = "5 day",
date_labels = "%Y-%m-%d")+
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme_bw()
```
I tried simplifying by merging all three datasets into one. If that causes issues just add them in singularly like you were doing. |
Using SOAP with WSDL in python with the suds-py3 library:
Why doesn't it show me anything when I use the following code?
What am I doing wrong?
config:
https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?WSDL
https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?xsd=1
```lang-python3
from suds.client import Client
url = "https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?xsd=1"
results = Client(url)
print(results)
```
Solution:
Solution to the problem: use the zeep library.
implementation:
https://github.com/oigonzalezp2024/cliente-webservice-sipsa/blob/main/consultarInsumosSipsaMesMadr.py
[show console][1]
[1]: https://i.stack.imgur.com/KIvoV.png |
I had been made a custom auth server wiht `org.springframework.security:spring-security-oauth2-authorization-server:1.2.2` and `spring boot 3.x`.
And I tried to make a server like documents.
but there was a problem.
```
@Configuration
@EnableWebSecurity
public class SecurityCon {
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain( HttpSecurity http)
throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer( OAuth2AuthorizationServerConfigurer.class)
.oidc( oidc -> oidc
.providerConfigurationEndpoint( provider -> provider
.providerConfigurationCustomizer( config->config
.issuer( "http://localhost:8000" )
.userInfoEndpoint( "/user" )
.authorizationEndpoint( "/login/oauth2/oidc-client" ) ) )
.userInfoEndpoint( userinfo -> userinfo.authenticationProvider( new AuthenticationProvider() {
@Override
public Authentication authenticate( Authentication authentication ) throws AuthenticationException {
return null;
}
@Override
public boolean supports( Class< ? > authentication ) {
return false;
}
} ) )); // Enable OpenID Connect 1.0
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().permitAll()
)
.csrf( httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable());
// Form login handles the redirect to the login page from the
// authorization server filter chain
// .formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(userDetails);
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient oidcClient = RegisteredClient.withId( UUID.randomUUID().toString())
.clientId("oidc-client")
.clientSecret("{noop}secret")
.scope( OidcScopes.OPENID )
// .clientAuthenticationMethod( ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType( AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8000/login/oauth2/code/oidc-client")
.postLogoutRedirectUri("http://127.0.0.1:8000/")
.clientSettings( ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
return new InMemoryRegisteredClientRepository(oidcClient);
}
@Bean
public JWKSource< SecurityContext > jwkSource() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
@Bean
public JwtDecoder jwtDecoder( JWKSource< SecurityContext > jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder().build();
}
}
```
I made a configuration.
And I called `http://localhost:8000/oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client`
url with GET Method.
but Spring occurred error and this is my debug log.
```
2024-03-13T14:50:18.625+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.security.web.FilterChainProxy : Securing GET /oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client
2024-03-13T14:50:18.626+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8000/oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client&continue to session
2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [Ant [pattern='/oauth2/token', POST], Ant [pattern='/oauth2/introspect', POST], Ant [pattern='/oauth2/revoke', POST], Ant [pattern='/oauth2/device_authorization', POST]]
2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer$BearerTokenRequestMatcher@74a820bf, RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]]
2024-03-13T14:50:18.631+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.HttpStatusEntryPoint@1060c298
```
I tested one more things.
did Oidc auth endpoint work well??
so I called http://localhost:8000/login/oauth2/oidc-client.
but spring give me a 404 error.
why didn't accept oidc custom config??
i apparently set custom config like this.
```
http.getConfigurer( OAuth2AuthorizationServerConfigurer.class)
.oidc( oidc -> oidc
.providerConfigurationEndpoint( provider -> provider
.providerConfigurationCustomizer( config->config
.issuer( "http://localhost:8000" )
.userInfoEndpoint( "/user" )
.authorizationEndpoint( "/login/oauth2/oidc-client" ) ) )
.userInfoEndpoint( userinfo -> userinfo.authenticationProvider( new AuthenticationProvider() {
@Override
public Authentication authenticate( Authentication authentication ) throws AuthenticationException {
return null;
}
@Override
public boolean supports( Class< ? > authentication ) {
return false;
}
} ) )); // Enable OpenID Connect 1.0
return http.build();
``` |
Hey here's my settings and value of confPath String, it worked after I moved the file to src/main/resources
I use:
protected String confPath = "/EcpayPayment.xml";
[ide pic][1]
[1]: https://i.stack.imgur.com/iPQ6I.png
|
I have a function written in Typescript in my CDK code:
```
export function getS3FileLocation(dirName: string) {
return sfn.JsonPath.stringAt(`$.myS3Bucket.${dirName}[0].location`);
}
```
Not surprise, here is the generated Cloudformation code if I pass `my-dir` as `dirName`:
```
$.myS3Bucket.my-dir[0].location
```
However, due to the minus symbol `-`, Cloudformation throws exception
```
The value for the field 'MyField.$' must be a valid JSONPath or a valid intrinsic function call at /States/My State/Parameters'
```
If I pass `my_dir` as `dirName`, the generated Cloudformation code would be `$.myS3Bucket.my_dir[0].location`, and Cloudformation does not throw exception.
How to handle the minus symbol `-`? For some reason, I have to pass `my-dir` as `dirName`. |
AWS CDK SFN JsonPath.stringAt to handle minus symbol |
|amazon-web-services|aws-cdk|aws-step-functions|aws-cdk-typescript| |
three call GetDetailData,but only "BOML" call when error Must declare the scalar variable "@pDBMode",other call not error
string SQLStr = "Exec PR_SPSA03_Qry @pDBMode, @pDBKind, @pCompNo, @pProdNo, @pflow, @pSeq "
add spapec "@pDBMode ," , after not error
What is the reason?
```
C#
switch (DBKind)
{
case "BOML":
bls = GetDetailData<BOMDTO>(DBKind, ProdNo, ref boms, ref Msg);
if (bls)
{
HF_BData.Set("BOML", JsonConvert.SerializeObject(boms));
grid_BOM.DataSource = boms;
grid_BOM.DataBind();
}
break;
case "PDML":
bls = GetDetailData<PDMDTO>(DBKind, ProdNo, ref pdms, ref Msg);
if (bls)
{
HF_BData.Set("PDML", JsonConvert.SerializeObject(pdms));
grid_PDM.DataSource = pdms;
grid_PDM.DataBind();
}
break;
case "PDFL":
bls = GetDetailData<PDFDTO>(DBKind, ProdNo, ref pdfs, ref Msg);
if (bls)
{
HF_BData.Set("PDFL", JsonConvert.SerializeObject(pdfs));
grid_PDF.DataSource = pdfs;
grid_PDF.DataBind();
}
break;
}
private bool GetDetailData<T>(string DBKind, string ProdNo, ref List<T> Data, ref string Msg)
{
string SQLStr = "Exec PR_SPSA03_Qry @pDBMode, @pDBKind, @pCompNo, @pProdNo, @pflow, @pSeq ";
Function fn = new Function();
DynamicParameters dynParams = new DynamicParameters();
dynParams.Add("@pDBMode", "B");
dynParams.Add("@pDBKind", DBKind);
dynParams.Add("@pCompNo", Session["CompNo"].ToString());
dynParams.Add("@pProdNo", ProdNo);
dynParams.Add("@pflow", "");
dynParams.Add("@pSeq", "");
bool bls = fn.GetData<T>("SPS", SQLStr, dynParams, ref Data, ref Msg);
return bls;
}
public bool GetData<T>(string ConStr, string SqlStr, DynamicParameters parameters, ref List<T> ReturnData, ref string Msg)
{
bool bls = false;
ConStr = GetConStr(ConStr);
try
{
using (SqlConnection conn = new SqlConnection(ConStr))
{
conn.Open();
ReturnData = conn.Query<T>(SqlStr, parameters).ToList();
}
bls = true;
}
catch (Exception ex)
{
Msg = ex.Message;
}
return bls;
}
```
add spapec "@pDBMode ," , after not error
What is the reason? |
Accessing iframe issues - python selenium for automation test |
|python|selenium-webdriver|xpath|iframe|src| |
I am having trouble connecting to my EMQX broker that is deployed on the cloud. It is a serverless free deployment. I am trying to connect to the broker from my Node MCU. The board connects to the WiFi without an issue and also connects to the publicly available broker i.e.
```broker.emqx.io``` But whenever I try to connect to my private broker, the connection fails and I get a return code of either -2 or -4. Why am I getting this problem?
Any sort of help is appreciated.
Thanks! |
Connecting to EMQX cloud broker with a node mcu |
|mqtt|nodemcu|emqx| |
One way to do this would be to split the schema down into three parts. The first part checks there is at least one contact method, but it doesn't care data all what `email` or `phone` is by using `z.any()`.
This is then intersected with two other schemas. One to handle `email` and one to handle `phone`. Each of those schemas is a union of the two possibilities for each respective one:
* `phone`/`email` is not in contact methods.
* `phone`/`email` is in contact methods, and `phone/email` is valid.
```
const contactMethods = z.enum(['email', 'phone'])
const schema = z
.object({
// other fields...
contactMethods: z
.array(contactMethods, {
invalid_type_error: 'At least one contact method is required',
})
.min(1, 'At least one contact method is required'),
email: z.any(),
phone: z.any(),
})
.and(
z.union([
z.object({
contactMethods: z
.array(contactMethods)
.refine((val) => val.includes(contactMethods.Enum.email)),
email: z
.string({ invalid_type_error: 'Enter an email1' })
.trim()
.email('Enter a valid email'),
}),
z.object({
contactMethods: z
.array(contactMethods)
.refine((val) => !val.includes(contactMethods.Enum.email)),
}),
]),
)
.and(
z.union([
z.object({
contactMethods: z
.array(contactMethods)
.refine((val) => val.includes(contactMethods.Enum.phone)),
phone: z
.string({ invalid_type_error: 'Enter a phone number' })
.trim()
.transform((val) => val.replaceAll(' ', '')) // spaces confuse validator function below
.refine((val) => validator.isMobilePhone(val), {
message: 'Enter a valid phone number',
}) // check value is parsable as phone number
.transform((val) => parsePhoneNumber(val, 'GB')?.number), // parse into +44 e.164 format if not already
}),
z.object({
contactMethods: z
.array(contactMethods)
.refine((val) => !val.includes(contactMethods.Enum.phone)),
}),
]),
)
``` |

for the given example html page:
I need to extract the innermost nested links from this sort of a page tree. Given the title within which, I need to get all the links, how can I find all the innermost nested links. I want to write a python script for the same which dynamically extracts the innermost nested links of the various html pages provided. Take note that the nesting levels may not be the same.
thus for the example I should get:
```
<a href="#">Subtopic 1</a>
<a href="#">Subtopic 2</a>
```
I tried extracting all the links in the same nesting structure but it didn't work
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div class="ia-secondary-content">
<div class="plugin_pagetree conf-macro output-inline" data-hasbody="false" data-macro-name="pagetree">
<div class="plugin_pagetree_children_list plugin_pagetree_children_list_noleftspace">
<div class="plugin_pagetree_children" id="children1326817570-0">
<ul class="plugin_pagetree_children_list" id="child_ul1326817570-0">
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 1" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="1630374642" data-tree-id="0" data-type="toggle" href="" id="plusminus1630374642-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan1630374642-0"> <a href="#">Topic 1</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children1630374642-0"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 2" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="1565544568" data-tree-id="0" data-type="toggle" href="" id="plusminus1565544568-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan1565544568-0"> <a href="#">Topic 2</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children1565544568-0"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="true" aria-label="Expand item Topic 3" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-down" data-children-loaded="true" data-expanded="true" data-page-id="3733362288" data-tree-id="0" data-type="toggle"
href="" id="plusminus3733362288-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan3733362288-0"> <a href="#">Topic 3</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children3733362288-0">
<ul class="plugin_pagetree_children_list" id="child_ul3733362288-0">
<li>
<div class="plugin_pagetree_childtoggle_container">
<span class="no-children icon"></span>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span"> <a href="#">Subtopic 1</a></span>
</div>
<div class="plugin_pagetree_children_container"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<span class="no-children icon"></span>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span"> <a href="#">Subtopic 2</a></span>
</div>
<div class="plugin_pagetree_children_container"></div>
</li>
</ul>
</div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 4" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="2238798992" data-tree-id="0" data-type="toggle" href="" id="plusminus2238798992-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan2238798992-0"> <a href="#">Topic 4</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children2238798992-0"></div>
</li>
</ul>
</div>
</div>
<fieldset class="hidden">
</fieldset>
</div>
</div>
<!-- end snippet -->
|
When a generic type does extends check. Type and interface have different behaviors.
Typescript playground:
https://www.typescriptlang.org/play?#code/C4TwDgpgBAKu0F4oG8BQUNQNoEsB2AJhAB5QBcAzsAE74DmAumXgK4C2ARhNepgIZkorTt1QBfVKnzBuAMz4BjaAEk8M6vKUpeGAUPZceE1KEhQAglCRwzJGYQpQAShAUB7agQA8VWnjoANPoi1AB8UAD8UDQs0ILyADYU0AD0KTEQJvBQAEJWUKrqmtB2EA7Orh7evvRBwobhURnkUInJUGltmUA
1, Why it throws the error?
2, What is the difference between interface and type?
> The question https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript doesn't explain my question. |
Lambda retries kinesis event properly processed |
|node.js|amazon-web-services|aws-lambda|amazon-kinesis| |
Dialogflow messenger ONLY shows a text response. If you log into Dialogflow webui and try any intent with a "card" response you will see it shows correctly, but wont show the card in Dialogflow messenger. This JSON is a working example:
{
"source": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaa-aaaaaaaa",
"fulfillmentMessages": [{"card": {
"title": "Title",
"subtitle": "text sample",
"imageUri": "www.domain.com/img.png",
"buttons": [ {
"text": "Read",
"postback": "www.domain.com"
}]
}}]
} |
I have a table with a string column that is formatted as json. I want to query my table by json. This is achievable with SQL
```
SELECT *
FROM [db].[dbo].[table]
WHERE JSON_VALUE(ColName, '$.jsonkey') = "value"
```
Is it possible with GraphQl and Hot Chocolate?
I tried
```
public IQueryable<Class> GetById([ScopedService] AppDbContext context, string id)
{
return context.Classes.AsQueryable().Where(p => JObject.Parse(p.JsonCol)["id"].ToString() == id);
}
```
Got an error:
> "message": "The LINQ expression 'DbSet<Platform>()\r\n .Where(p =>
> JObject.Parse(p.JsonCol).get_Item(\"id\").ToString() == __id_0)' could
> not be translated.
Any help would be appreciated.
|
In terms of Hibernate your deletion is not deletion, but just `update`, so it doesn't have to propagate this operation to the associated entities. I recommend you to consider using Hibernate's out-of-box [soft delete][1].
Also, don't use Lombok's `@Data` for entities, it implicitly generates equals/hashcode which use fields-associations and may cause unexpected behavior.
[1]: https://docs.jboss.org/hibernate/orm/6.4/userguide/html_single/Hibernate_User_Guide.html#soft-delete |
I have a csv file with multiple columns that are formatted as currency, what is the best way to remove the formatting but keeping the values. I would like to automate the process if possible.

I tried using the data conversion tool but I must be doing something wrong.
This is what the raw file looks like in NotePad. :
1-2-1,2020,1,1,Ada,2,County,1,Ada County," $144,552,433 ",," $27,710 "," $57,836 ",0.00,,,,,,," $12,251,223 |
Use a simple GROUP BY with the GROUP CONCAT:
select tbl_news.id as id , GROUP_CONCAT(tbl_imgs.imgName)
from tbl_news
JOIN tbl_imgs on tbl_imgs.newsId = tbl_news.newsId
Though the grouped values will be comma separated and you can convert them into an array easily.
|
On Mongodb, I have a "conversations2" collection where I keep chat data and a "user_blocked" collection that I keep blocked by the system. While pulling the chats according to userId, I need to pull the IDs in user_blocked that do not match otherUserId. My query below works, but it is too slow for users with a high number of messages (for example, there are 450 thousand records for a user with 32 IDs). Is there a chance I can speed this up or receive this query via a different route? (My goal is to get the user's unread message count, excluding any blocking) Thanks in advance for your help. By the way, userId_1 and otherUserId_1 indexes in conversations2 are added. The id_1 index is added in user_blocked.
```
[
{
$match: {
userId: 32
}
},
{
$lookup: {
from: "user_blocked",
localField: "otherUserId",
foreignField: "id",
as: "blockedUsers"
}
},
{
$match: {
blockedUsers: { $not: { $elemMatch: { id: { $in: ["$otherUserId"] } } } }
}
},
{
$group: {
_id: "$userId",
unreadMessageCount: { $sum: "$unreadMessageCount" }
}
}
]
```
conversations2 collection example data ;
```
{
"_id": {
"$oid": "65c0f64030054c4b8f0481a0"
},
"otherUserId": {
"$numberLong": "45"
},
"userId": {
"$numberLong": "32"
},
"lastMessage": "test",
"lastMessageTime": {
"$date": "2024-02-21T10:36:44.592Z"
},
"lastMessageType": 1,
"lastMessageWay": "in",
"unreadMessageCount": 29
}
```
user_blocked example data;
```
{
"_id": {
"$oid": "660285eb2be53086024608e6"
},
"id": 45
}
```
|
I have a frame (events) which I want to join into another frame (fr), joining on Date and Symbol. There aren't necessarily any date overlaps. The date in events would match with the first occurrence only on the same or later date in fr, so if the event date is 2010-12-01, it would join on the same date or if not present then the next available date (2010-12-02).
I've tried to do this using search_sorted and join_asof but I'd like to group by the Symbol column and also this isn't a proper join. This somewhat works for a single Symbol only.
fr = pl.DataFrame(
{
'Symbol': ['A']*5,
'Date': ['2010-08-29', '2010-09-01', '2010-09-05',
'2010-11-30', '2010-12-02'],
}
).with_columns(pl.col('Date').str.strptime(pl.Date, '%Y-%m-%d')).with_row_index().set_sorted("Date")
events = pl.DataFrame(
{
'Symbol': ['A']*3,
'Earnings_Date': ['2010-06-01', '2010-09-01', '2010-12-01'],
'Event': [1, 4, 7],
}
).with_columns(pl.col('Earnings_Date').str.strptime(pl.Date, '%Y-%m-%d')).set_sorted("Earnings_Date")
idx = fr["Date"].search_sorted(events["Earnings_Date"], "left")
fr = fr.with_columns(
pl.when(
pl.col("index").is_in(idx)
)
.then(True)
.otherwise(False)
.alias("Earnings")
)
fr = fr.join_asof(events, by="Symbol", left_on="Date", right_on="Earnings_Date")
fr = fr.with_columns(
pl.when(
pl.col("Earnings") == True
)
.then(pl.col("Event"))
.otherwise(False)
.alias("Event")
) |
Can you do it dynamically? Maybe, it will depend on the details of your file and how it varies.
As you've noted, you can write a query
select * from [sheet$A7:H]
And if that is in an SSIS Variable, then as long as the query is correct before the Data Flow begins, possibly validates, then you'll be able to skip N rows.
Of course, the devil is in the details in that you would need a preprocessing step, like a Script Task to open the same Excel file and identify the first non-empty row in column A (or whatever column is determined to be of interest)
An alternative approach would involve adding a Conditional Split to your Data Flow.
It could be as simple of a condition as
(IsNULL(Col1))
or maybe
(IsNULL(Col1) || Col1 == "")
- Option 1 Col1 is null
- Option 2 Col1 is NULL or Col1 is the empty string
Whatever your data evaluates to when you bring it into the data flow will tell you what condition you want.
Route those rows to nothing. Leave the Default path out of the Conditional Split to the rest of your Data Flow and the data flow will read all the rows from the worksheet. Only the rows matching our criteria will flow to the rest of downstream components. |
Trying to put multiple arguments into a string in Bash is generally not a good idea. Sometimes the only way to make it work is to use `eval`, and that often just gives you more problems (some of which may be very unobvious). See [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/4154375).
In this case I'd avoid the problem by defining the (Bash) function like this:
function myFunc
{
codesign "${@:2}" "$1"
}
and calling it like this:
myFunc "/MyFolder/MyFile.dylib" -f -vvvv --strict --deep --timestamp -s "Developer ID Application: My Company Inc. (123456)" --options runtime
I.e. put the path of the file to be signed as the first argument and the arguments to `codesign` as the following, all separate, arguments. Any arguments that work with `codesign` itself are guaranteed to work when provided as arguments (2 and following) to `myFunc`.
|
dapper must decalre Must declare the scalar variable "@pDBMode" |
|c|asp.net| |
null |
I am new to bootstrap and setting up all bootstrap in local server in my system.
So instead of linking online stylesheet I have linked with local server like below.
<link href="http://127.0.0.1/bootstrap-5.3.3-dist/css/bootstrap.min.css" rel="stylesheet">
And for linking script file I have linked like below
<script src="http://127.0.0.1/bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
Till now It is working fine.
When it comes to use bootstrap icons, Bootstrap provides below link for using icons.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
Now, I have downloaded the same css file and linking it like below.
<link rel="stylesheet" href="http://127.0.0.1/bootstrap-icons-1.11.3/font/bootstrap-icons.min.css">
Now, If I use Icon Font like below. It's not working, however if I use the same css through online it's working.
<i class="bi-alarm"></i>
I am wondering how can I achieve this using local server.
**Update-After Comment**
I am getting below error.
```
Access to font at 'http://127.0.0.1/bootstrap-icons-1.11.3/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
bootstrap-icons.woff2:1
Failed to load resource: net::ERR_FAILED
index.html:1 Access to font at 'http://127.0.0.1/bootstrap-icons-1.11.3/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
bootstrap-icons.woff:1
Failed to load resource: net::ERR_FAILED
```
|
I am trying formula `if` with multi conditions in Excel.
but the result `#VALUE!`is there is something wrong with my formula please guide me
Thanks
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 | |
| | IN | | | | |
```
=IF(A2="",""),IF(AND(B2="OUT",E2<=C2,),"NORMAL","LATE"),IF(AND(B2="IN",D2<=C2),"NORMAL","LATE")
```
Result from above formula
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |#VALUE! |
| | IN | | | |#VALUE! |
[![enter image description here][1]][1]
Desired Result
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |LATE |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |LATE |
| | IN | | | | |
[1]: https://i.stack.imgur.com/qCgFE.png |
I am new to python stt, so I started with this speech_recognition library
```
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
print("Transcribing...")
text = recognizer.recognize_google(audio)
print("You said:", text)
return text
except sr.UnknownValueError:
print("Sorry, could not understand audio.")
return ""
except sr.RequestError as e:
print("Error fetching results; {0}".format(e))
return ""
```
I am getting this error
`----> 5 with sr.Microphone() as source:
6 print("Listening...")
7 recognizer.adjust_for_ambient_noise(source)
AttributeError: module 'speech_recognition' has no attribute 'Microphone'`
I tried opening up the sr directory
```
>>> import speech_recognition as sr
>>> dir(sr)
['AudioData', 'AudioSource', 'Microphone', 'Recognizer', 'Request', 'URLError', 'WavFile', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'audioop', 'collections', 'io', 'json', 'math', 'os', 'pyaudio', 'shutil_which', 'subprocess', 'urlopen', 'wave']
```
I upgraded both pyaudio and speech_recognition packages
I work in an anaconda environment in jupyter notebook |
AttributeError: module 'speech_recognition' has no attribute 'Microphone' |
|python|speech-recognition|speech-to-text|pyaudio| |
null |
```
git log --name-status --pretty=%ci | awk -F$'\t' '
NF==1 { stamp=$0; next }
!seen[$2]++ { print stamp,$0 }
' | sort -t$'\t' -k2,2
```
and as always season to taste. Are you running on spinning rust? I do that on the SDL default checkout with a cheap ssd it takes 0.548s, so more than a hundred times faster. But then, it's doing 1500+ times fewer walks through history so there's that. |
```java
public enum Category {
HIGH_CARD, PAIR, TWO_PAIR, TRIPS, STRAIGHT, FLUSH, FULL_HOUSE, QUADS, STRAIGHT_FLUSH
}
```
```java
public enum Rank {
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
```
```java
public enum Suit {
DIAMONDS, CLUBS, HEARTS, SPADES
}
```
```java
public record Card(Rank rank, Suit suit) {}
```
```java
import java.util.*; // Arrays, Set
import java.util.Map.Entry;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*; // counting, groupingBy;
public record Hand(Category category, Rank... ranks) implements Comparable<Hand> {
public static Hand evaluate(Set<Card> cards) {
if (cards.size() != 5) throw new IllegalArgumentException();
var flush = cards.stream().map(Card::suit).distinct().count() == 1;
var counts = cards.stream().collect(groupingBy(Card::rank, counting()));
var ranks = counts.entrySet().stream().sorted(
comparing(Entry<Rank,Long>::getValue).thenComparing(Entry::getKey).reversed()
).map(Entry::getKey).toArray(Rank[]::new);
if (ranks.length == 4)
return new Hand(PAIR, ranks);
else if (ranks.length == 3)
return new Hand(counts.get(ranks[0]) == 2 ? TWO_PAIR : TRIPS, ranks);
else if (ranks.length == 2)
return new Hand(counts.get(ranks[0]) == 3 ? FULL_HOUSE : QUADS, ranks);
else if (ranks[0].ordinal() - ranks[4].ordinal() == 4)
return new Hand(flush ? STRAIGHT_FLUSH : STRAIGHT, ranks[0]);
else if (ranks[0] == ACE && ranks[1] == FIVE) // wheel
return new Hand(flush ? STRAIGHT_FLUSH : STRAIGHT, FIVE);
else
return new Hand(flush ? FLUSH : HIGH_CARD, ranks);
}
@Override
public int compareTo(Hand that) { // compare categories, then ranks lexicographically
return comparing(Hand::category).thenComparing(Hand::ranks, Arrays::compare)
.compare(this, that);
}
}
``` |
Using SOAP with WSDL in python with the suds-py3 library:
Why doesn't it show me anything when I use the following code?
What am I doing wrong?
config:
https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?WSDL
https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?xsd=1
```lang-python3
from suds.client import Client
url = "https://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?xsd=1"
results = Client(url)
print(results)
```
**Solution:**
Solution to the problem: use the zeep library.
**implementation:**
https://github.com/oigonzalezp2024/cliente-webservice-sipsa/blob/main/consultarInsumosSipsaMesMadr.py
[show console][1]
[1]: https://i.stack.imgur.com/KIvoV.png |