instruction stringlengths 0 30k β |
|---|
|python|ui-automation|pywinauto| |
null |
Since Mysql 8.0.19 it is possible to use the VALUES statement: https://dev.mysql.com/doc/refman/8.0/en/values.html
I have done so in some JOIN statements and have very big performance differences which I do not understand.
If I use the VALUES statement in simple INNER JOIN like:
```
SELECT *
FROM table t1
INNER JOIN (VALUES ROW(1,2), ROW(2,3)) AS val_join
```
with about 100k values, the query gets extremely slow whereas a LEFT JOIN like:
```
SELECT *
FROM table t1
LEFT JOIN (VALUES ROW(1,2), ROW(2,3)) AS val_join
WHERE val_join.column_0 IS NULL
```
is extremely fast with more than 100k values.
Is there some background information I am missing or some basic rules when a subselect is quicker than a VALUES statement or even the usage of a SELECT with explicit values? |
|python|google-chrome|selenium-webdriver|chrome-for-testing| |
I am using spring integration flow to read file from a file server. My app will be running with multiple instances. I want to insure that each instance processes any file only once. Here is what I am using so far:
1. SFTP Inbound Channel Adapter (to read messages based on a poll)
2. SftpPersistentAcceptOnceFileListFilter with JdbcMetadataStore (persistence store)
3. Transformer (to convert Message of type File to JobLaunchRequest)
4. @ServiceActivator to launch Spring Batch job with JobLaunchingGateway
Spring docs suggest using Transaction Manager with JdbcMetadataStore since it uses transactional putIfAbsent queries.
So I am providing PlatformTransactionManager bean in my Java DSL Spring integration flow. I am also using the same transaction manager in my Spring Batch step (chunk() method).
Problem: I am getting the following error "***Existing transaction detected in JobRepository. Please fix this and try again***"
Is there a better approach to fix/design this flow or a simple fix to this error?
It works with Redis Metadata Store since that one is non transactional. My overall problem is that with JdbcMetadataStore I get unique constrain violation when my multiple instances poll at exact same second and ends up getting same file to be put in metadata store table in my database.
By the way I am using Postgres db. |
I'm starting a project with dotnet 8 and graphql (hot chocolate) and I use Visual Studio editor..
Everytime I create a new Mutation for graphql, I need to remember to create the class as sealed, and to add two attributes, for example:
```
[ExtendObjectType(typeof(GraphMutation))]
[Authorize]
public sealed class CreateMutation
{
public async Task<TodoItemDto> CreateTodo(IMediator _mediator, CreateTodoItemCommand createTodoItem) =>
await _mediator.Send(createTodoItem);
}
```
For the queries the template it's a little bit different, I need to extend another class, and let's say in other folders may be different..
I'd like to help myself to don't miss nothing, so I would like that all the files that will be created under a certain path eg: src/Web/GraphQL/Mutations will have a certain template (the one showed), then all the files that will be created under src/Web/GraphQL/Queries another template, and so on.. is it possible that kind of personalization on Visual Studio?
Not sure if it matters but it's dotnet 8
I know there is a main C# template class somewhere in the C/Programs/.. and I already edited it to have the class 'public' instead of 'internal', but I would like to know if it's possible to have different templates and all of them related just to that project, so that everyone which will clone the repository and will generate a new class under Mutations folders, the class will be generated like that!
|
Custom classes templates under different folders |
|c#|asp.net|.net|visual-studio|editor| |
null |
I have a userform that gives the user 6 choices. They can either click on the appropriate choice on the userform or press a number 1 thru 6 on the keyboard. My issue is that the keypress or keydown event never triggers. I need to capture the key pressed and check if it in number 1 thru 6 "when the userform is displayed" to run the next sub. This is my latest attempt. No matter what event I try to capture nothing seems to capture a key being pressed. When I put a break point on the beginning of the sub it never get called.
Private Sub Userform_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 49 Then
MsgBox "You pressed the '1' key!"
ElseIf KeyCode = 50 Then
MsgBox "You pressed the '2' key!"
ElseIf KeyCode = 51 Then
MsgBox "You pressed the '3' key!"
ElseIf KeyCode = 52 Then
MsgBox "You pressed the '4' key!"
ElseIf KeyCode = 53 Then
MsgBox "You pressed the '5' key!"
ElseIf KeyCode = 54 Then
MsgBox "You pressed the '6' key!"
End If
End Sub |
Excel VBA: Can't capture key stroke |
|excel|vba| |
Hi i have a slider on my home page and a hamburger nav and font size change in one file, however. they do not all work unless i split them into different files. Why is this? can someone explain please?
I have added the external file link to each of my pages, if i were to take the script out and out it straight into the html it will work. So as i am new to this it is probably so simple and i apologise if this is a stupid question.
see the js file below;
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
///NAV
document.querySelector(".toggle-button").addEventListener("click", () =>
{
document.querySelector("#nav").classList.toggle("hide")
})
//FONT SIZE
document.getElementById("smallA").onclick = function(){changeSize("small")};
document.getElementById("mediumA").onclick = function(){changeSize("medium")};
document.getElementById("largeA").onclick = function(){changeSize("large")};
function changeSize(c)
{
document.getElementsByTagName("body")[0].className= c;
}
//SLIDER
let slideIndex = 0;
showSlides();
function showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].style.display = "block";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
<!-- end snippet -->
|
Remix v2 no layout file for index route? |
|remix| |
I don't have much experience using OPL and would appreciate any guidance on correcting my mistakes. I'm attempting to implement the RCPSP model by Pritsker et al. (1969).
Link : [Here](https://www.google.com/books/edition/Scheduling_of_Resource_Constrained_Proje/CNncBwAAQBAJ?hl=fr&gbpv=1&dq=RCPSP*&pg=PA79&printsec=frontcover)
```
// Example data
range J = 1..5;
range R = 1..3;
range T = 1..10;
int P[J] = [0,1,2,3,4];
int d[J] = [1, 1, 3, 5, 2];
int EF[J] = [1, 2, 1, 1, 1];
int LF[J] = [2, 3, 4, 6, 2];
int Tbar = sum(j in J) d[j];
// Resource usage matrix
int u[J][R] = [[1, 0, 2],
[1, 1, 1],
[1, 1, 0],
[2, 0, 3],
[1, 1, 2]];
// Resource availability
int a[R]= [1,2,3];
// Decision Variables
dvar boolean x[J][T];
dexpr int CT = sum(j in J, t in EF[j]..LF[j])t*x[j][t];
minimize CT;
subject to {
forall(j in J)
sum (t in EF[j]..LF[j]) x[j][t] == 1;
forall(j in J, i in J)
sum (t in EF[j]..LF[j]) (t - d[j]) * x[j][t] - sum (t in EF[i]..LF[i]) t * x[i][t] >= 0;
forall(r in R, t in 1..Tbar) {
sum(j in J) u[j][r] * sum(q in max(t, EF[j])..min(t + d[j] - 1, LF[j])) x[j][q] <= a[r];
}
}
```
|
Seeking Assistance with Resource-Constrained Project Scheduling Problem (RCPSP) Implementation in OPL for CPLEX |
|cplex|opl| |
null |
In `readux-thunk@3` there is no longer any `default` export, so with `import thunk from "redux-thunk"` `thunk` is undefined.
Compare [v2][1]
```typescript
...
const thunk = createThunkMiddleware() as ThunkMiddleware & {
withExtraArgument<
ExtraThunkArg,
State = any,
BasicAction extends Action = AnyAction
>(
extraArgument: ExtraThunkArg
): ThunkMiddleware<State, BasicAction, ExtraThunkArg>
}
// Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
thunk.withExtraArgument = createThunkMiddleware
export default thunk
```
to [v3][2]
```typescript
...
function createThunkMiddleware<
State = any,
BasicAction extends Action = AnyAction,
ExtraThunkArg = undefined
>(extraArgument?: ExtraThunkArg) {
// Standard Redux middleware definition pattern:
// See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
({ dispatch, getState }) =>
next =>
action => {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument)
}
// Otherwise, pass the action down the middleware chain as usual
return next(action)
}
return middleware
}
export const thunk = createThunkMiddleware()
...
```
Update your code to import the ***named*** `thunk` export.
```typescript
import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk'; // <-- import named export
import { composeWithDevTools } from 'redux-devtools-extension';
import taskReducer from './reducers/taskReducer';
const store = createStore(
taskReducer,
composeWithDevTools(applyMiddleware(thunk))
);
export default store;
```
[1]: https://github.com/reduxjs/redux-thunk/blob/v2.4.2/src/index.ts#L39-L53
[2]: https://github.com/reduxjs/redux-thunk/blob/v3.1.0/src/index.ts#L15-L39 |
over the weeks I have created a chunked infinite heightmap terrain. The chunk system is very simple and is not the topic of this question. The topic of this question is how to create a terrain heightmap with the possibility of blending between different textures/materials (grass, dirt, sand, etc.) smoothly.
A chunk is basically a grid of height values and texture values (so 0 is dirt, 1 is grass, 2 is something else). Then I generate the chunk mesh by taking all those values and turning them into vertex attributes (height is a buffer object and so is the texture/material; I only pass the height because I calculate the X and Z position in the shader).
Now, the vertex shader looks like this:
#version 300 es
layout (location = 0) in float height;
layout (location = 1) in float material;
out float h;
out float m;
out vec2 uv;
uniform vec4 chunkPosition;
uniform int chunkSize;
uniform mat4 view, projection;
void main () {
int col = gl_VertexID % (chunkSize + 1);
int row = gl_VertexID / (chunkSize + 1);
vec4 position = vec4 (col, height, row, 1.0);
gl_Position = projection * view * (chunkPosition + position);
uv = vec2 (float (col) / float (chunkSize), float (row) / float (chunkSize));
h = height;
m = material;
}
And the fragment shader looks like this:
#version 300 es
precision lowp float;
in vec2 uv;
in float h;
in float m;
out vec4 color;
uniform sampler2D grass, drygrass, dirt;
void main () {
vec4 grs = texture (grass, uv);
vec4 drt = texture (dirt, uv);
color = mix (grs, drt, m);
}
With the single value m representing the material at a given vertex I seem to be able to sucessfuly blend between two textures and it looks great. However, I can't wrap my head around how to implement more textures here (in this example, how to make it so drygrass is also on the terrain).
I understand that the way it works here is it does a weighed average and interpolated between the grass and dirt materials based on the value m (which for now I have not made it go beyond 1).
I already tried making it so the value does go to 2 (so in this example it could be e.g. drygrass) but I find it hard to figure out how to mix it all.
Is the way to go to have a different "m" value for every single texture type in the terrain? |
Multiple different textures/materials on 3D heightmap |
|javascript|opengl|glsl|webgl|webgl2| |
null |
I get access violation if I'm allocating memory to `list->v[list->length]`
```
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char* denumire, * producator;
int cantitate;
}produs;
typedef struct {
produs** v;
int lungime;
int capacitate;
} Lista;
produs crearePr(char* nume, char* producator, int cantitate)
{
produs material;
material.denumire = (char*)malloc(strlen(nume) + 1);
strcpy(material.denumire, nume);
material.producator = (char*)malloc(strlen(producator) + 1);
strcpy(material.producator, producator);
material.cantitate = cantitate;
return material;
}
void creareLi(Lista* lista)
{
lista->lungime = 0;
lista->capacitate = 1;
lista->v = (produs**)malloc(sizeof(produs*) * lista->capacitate);
}
void redim(Lista *l)
{
l->capacitate *= 2;
l->v = (produs**)realloc(l->v,sizeof(produs) * l->capacitate);
}
void adauga(Lista *lista, produs p)
{
if (lista->lungime == lista->capacitate) redim(&lista);
lista->v[lista->lungime] = (produs*)malloc(sizeof(produs));
*lista->v[lista->lungime] = p;
lista->lungime++;
}
int main()
{
Lista lista;
creareLi(&lista);
adauga(&lista, crearePr("Zahar", "Tarom", 100));
return 0;
}
```
Explanation:
- `crearePr` should create a `struct produs`
- `creareLi` should initialize the list, set capacity 1 and length 0
- `redim` is called to expand the capacity
- `adauga` should add `struct produs` to list
|
We can create a composable function for creating ImageRequest and inject our httpclient into the ImageRequest:
@Composable
fun coilImageRequest(): ImageRequest.Builder {
val httpClient: HttpClient = koinInject()
return ImageRequest.Builder(LocalPlatformContext.current).fetcherFactory(
KtorNetworkFetcherFactory(httpClient)
)
}
And use it like this:
AsyncImage(
modifier = Modifier,
model = coilImageRequest()
.data(imgUrl)
.crossfade(true)
.build(),
contentDescription = null,
imageLoader = SingletonImageLoader.get(LocalPlatformContext.current)) |
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
I solved the issue by providing a custom implementation of the `IApiDescriptionGroupCollectionProvider` where I adjusted the code of the `GetCollection` method:
var context = new ApiDescriptionProviderContext(actionDescriptors.Items);
foreach (var provider in _apiDescriptionProviders)
{
provider.OnProvidersExecuting(context);
}
// Added this block to change the parameter type for enumeration parameters back to their original type
foreach (var param in context.Results.SelectMany(r => r.ParameterDescriptions))
{
if (param.ModelMetadata.ModelType.IsEnum)
{
param.Type = param.ModelMetadata.ModelType;
}
}
for (var i = _apiDescriptionProviders.Length - 1; i >= 0; i--)
{
_apiDescriptionProviders[i].OnProvidersExecuted(context);
}
var groups = context.Results
.GroupBy(d => d.GroupName)
.Select(g => new ApiDescriptionGroup(g.Key, g.ToArray()))
.ToArray();
return new ApiDescriptionGroupCollection(groups, actionDescriptors.Version);
|
null |
I want to replace all "i" elements with "span" elements.
I try many things but it didn't work.
I didn't find either error messages and debug JavaScript code in my browser.
I want to replace for example:
```
<i class="icon-user"></i>
```
to
```
<span class="icon-user"></span>
```
I try those but nothing works:
**1)**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
(function($) {
$(document).ready(function() {
// Replace <i> elements with <span> elements
$('i.icon-user').replaceWith('<span class="icon-user"></span>');
});
})(jQuery);
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i>
</p>
<!-- end snippet -->
**2)**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
jQuery(document).ready(function($) {
// Check if jQuery is loaded
if (typeof jQuery === 'undefined') {
console.error('jQuery is not loaded.');
return;
}
// Check if the element exists
if ($('i.icon-user').length === 0) {
console.error('The element with class "icon-user" does not exist.');
return;
}
// Replace <i> with <span>
$('i.icon-user').each(function() {
$(this).replaceWith('<span class="icon-user"></span>');
});
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i>
</p>
<!-- end snippet -->
**3)**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.addEventListener('DOMContentLoaded', function() {
var iconUsers = document.querySelectorAll('i.icon-user');
iconUsers.forEach(function(iconUser) {
var spanElement = document.createElement('span');
spanElement.className = 'icon-user';
iconUser.parentNode.replaceChild(spanElement, iconUser);
});
});
<!-- language: lang-html -->
<p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i>
</p>
<!-- end snippet -->
|
You can fix this by removing the canary mod.
I ran into the same issue as you and after adding mods one by one, the problem was the canary mod.
|
I found a workaround
I added a plugin on my pom.xml to copy itself to each module and rename. This happens before the docker build
```
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pt.com.daniel</groupId>
<artifactId>kafka-example</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>producer</module>
<module>consumer</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
</parent>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-parent-pom</id>
<phase>initialize</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<type>pom</type>
<overWrite>false</overWrite>
<outputDirectory>${project.basedir}/producer</outputDirectory>
<destFileName>parent-pom.xml</destFileName>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<type>pom</type>
<overWrite>false</overWrite>
<outputDirectory>${project.basedir}/consumer</outputDirectory>
<destFileName>parent-pom.xml</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
``` |
Just use this property on the input tag
onInput={(e) => {e.target.value = Math.abs(e.target.value);}} |
Access violation after reallocating memory |
|sockets|mule|mulesoft|mule4|mule-connector| |
If you want to make sure specific props are not defined you can define them with `prop_name?: never`.
So for the example in the question it would become:
function dbQuery(): User[] {
return [];
}
function getAll(): GetAllUserData[] {
return dbQuery();
}
class User {
id: number = 0;
name: string = "";
}
class GetAllUserData {
id: number = 0;
name?: never;
}
[TS Playground link][1]
And if you're working with types instead of directly classes and would like to extend a type that uses `never` so you can allow that prop, you can use `Omit<>` to exclude that prop. That also allows you to 'overwrite' that prop with a concrete type:
type t1 = {
prop1: string;
prop2?: never;
}
type t2 = Omit<t1, 'prop2'> & {
prop2: string;
}
// Should not error
const obj1: t1 = {
prop1: 'foo',
}
// Should error for extra prop
const obj2: t1 = {
prop1: 'foo',
prop2: 'bar'
}
// Should error for missing prop
const obj3: t1 = {
prop2: 'bar',
}
// Should not error
const obj4: t2 = {
prop1: 'foo',
prop2: 'bar',
}
[TS Playground link][2]
[1]: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAEwEYEUQFMBOBPACgEoAuRAVQGdcBtAXUQG8BYAKEQ8RyyhByXoBuNgF82bUJFgJEAcx4BBADZLiZAOKKVVXABEAhlH30mbTlx58kaTLkJFhrMazYQl%20ypQrUcp9pxhkMjAQAFtUXEQAXkQABkdzMH1QrDJKKBwYMFloxAAiPMdnV3dPRE0oZSUdHAMjP3NA4LCI3xj4s04klIB%20YKwAN1witiA
[2]: https://www.typescriptlang.org/play?#code/C4TwDgpgBMCMUF4oG8CwAoKUwCcD2YsAXFAM7A4CWAdgOYDcGWuBATAPwnUQBuEOjdAF8MGUJBitEUAPIBbSsAA8cADRQA5CzCsNAPigAyFE2z4dJclTqCR6DAHoHUAMoALPAFcANgBMo1HjAUPz4OBgAxnjU5FB4AEYAVsQw8EhomGYEKRoAZnh4GqoYdo7O7l5+IThhUPk4IQAeFACGWWCR0bEJiawkcNIZzOY5+YXFmdp9mvEtOBolouhOrh4+-qF4DfVQCqSkNLTtnTHBPQDM-Wkmk+bTGrPzE6XL5WtVgcGb4ehRp3FJAAs-Sk6VM2lGBSK4LuJAec2hwiAA |
The **OK()** method in the controllers accepts an object that gets converted into the body of the response.
Why don't you just use *dynamic*, or *object* through the call stack and populate it with anonymous objects created from your database? |
Short answer is, no you can't, at least not easily. A bit-vector of size N encodes exactly `2^N` elements. Hence, whichever bit-vector size you choose, you can't represent exactly 3 elements. You'll have some "junk" left over even with 2-bits. This means that you have to "modify" each operation (by essentially applying remainder operation) to adjust the results properly. And none of that is going to be pretty, and if done haphazardly can cause efficiency issues.
Since you didn't really tell us what your original problem is, it's hard to opine any further. If your "universe" is 3 elements wide, then a better alternative would be to just use an enumeration of those 3 elements. Then you can encode addition by applying the distributive law: `(a + b) mod 3 = ((a mod 3) + (b mod 3)) mod 3)`, and a similar law for multiplication. Perhaps that's sufficient to transform all your constraints? It all depends on what problem you're trying to solve. If you tell us more about your original problem, perhaps we can provide a more relevant answer.
|
I'm trying to animate a sine wave made out of a Shape struct. To do this, I need to animate the phase of the wave as a continuous looping animation - and then animate the frequency and strength of the wave based on audio input.
As far as I understand it, the `animatableData` property on the Shape seems unable to handle multiple animation transactions. I've tried using `AnimatablePair` to be able set/get more values than one, but it seems they need to come from the same animation instance (and for my case I need two different instances).
The code goes something like this:
<!-- language: swiftui -->
```
@Binding var externalInput: Double
@State private var phase: Double = 0.0
@State private var strength: Double = 0.0
struct MyView: View {
var body: some View {
MyShape(phase: self.phase, strength: self.strength)
.onAppear {
/// The first animation (that needs to be continuous)
withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) {
self.phase = .pi * 2
}
}
.onChange(self.externalInput) {
/// The second animation (that is reactive)
withAnimation(.default) {
self.strength = self.externalInput
}
}
}
}
```
<!-- language: swiftui -->
```
struct MyShape: Shape {
var phase: Double
var strength: Double
var animatableData: AnimatablePair<Double, Double> {
get { .init(phase, strength) }
set {
phase = newValue.first
strength = newValue.second
}
}
/// Drawing the bezier curve that integrates the animated values
func path(in rect: CGRect) -> Path {
...
}
}
```
This approach however seems to only animate the value from the last animation transaction that's been initialised. I am guessing both animated values goes in, but when the second animation transaction fires, it sets the first value to the target value (without any animations) - as those animated values are part of the first transaction (that gets overridden by the second one).
My solution right now is to use an internal `Timer`, in a wrapper View for the Shape struct, to take care of updating the value of the `phase` value - but this is far from optimal, and quite ugly.
When setting the values in `animatableData`, is there a way to access animated values from other transactions - or is there another way to solve this?
I've also tried with implicit animations, but that seems to only render the last set animation as well - and with a lot of other weird things happening (like the whole view zooming across the screen on a repeated loop...). |
|internationalization|json-ld| |
null |
Do you need to load language specific JSON-LD script if your site is in multiple language? My site is available in 5 languages. My JSON-LD is written in English. Do I need to load JSON-LD script for the detected language?
|
Do I need to load language specific schema\JSON-LD for each language the site supports? |
|internationalization|schema|jsonschema|json-ld| |
{"OriginalQuestionIds":[41265266],"Voters":[{"Id":1746118,"DisplayName":"Naman","BindingReason":{"GoldTagBadge":"java"}}]} |
You can certainly simplify the repeated code using a custom function and avoid the double `groupby`. Using [`groupby.tranform`](https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html) for the second column:
```
def pct_cumprod(s):
return s.pct_change().fillna(0).add(1).cumprod().sub(1).mul(100).round(2)
df['Normal'] = pct_cumprod(df['open'])
df['Group_of_3'] = (df.groupby(np.arange(len(df)) // 3)['open']
.transform(pct_cumprod)
)
```
If you only need the `Group_of_3` column:
```
df['Group_of_3'] = (df.groupby(np.arange(len(df)) // 3)['open']
.transform(lambda g: g.pct_change().fillna(0).add(1)
.cumprod().sub(1).mul(100)
.round(2))
)
```
Output:
```
id open Normal Group_of_3
0 1 10 0.0 0.00
1 2 17 70.0 70.00
2 3 15 50.0 50.00
3 4 11 10.0 0.00
4 5 17 70.0 54.55
5 6 15 50.0 36.36
``` |
I receive this error on my app log:
```
[error] unsupported data type: &[]
```
What I'm trying to do is to run a `SELECT` query to a many-to-many data using `json_agg()` where the data type in the struct that I'm using is `[]string`
this is the `GetArticleById` Struct
```
type GetArticleByID struct{
ID string `json:"article_id" gorm:"column:article_id"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
Author string `json:"author"`
Category string `json:"category"`
SubCategory string `json:"sub_category"`
Keywords []string `json:"keywords"`
Unit string `json:"unit"`
}
```
and this is the Query execution
```
query := `SELECT
a.article_id, a.title, a.created_at, a.content, u.name AS author, c.name AS category, sc.name AS sub_category,
json_agg(k.name) AS keywords, unit.name AS unit
FROM
articles a
LEFT JOIN users u ON a.user_id = u.user_id
LEFT JOIN categories c ON a.category_id = c.categ_id
LEFT JOIN sub_categories sc ON a.sub_category_id = sc.sub_categ_id
LEFT JOIN article_keywords ak ON a.article_id = ak.article_refer_id
LEFT JOIN keywords k ON ak.keyword_refer_id = k.keyword_id
LEFT JOIN units unit ON a.unit_id = unit.unit_id
WHERE
a.article_id = ? AND
a.is_posted = true
GROUP BY
a.article_id, u.name, c.name, sc.name, unit.name`
err := db.Raw(query, id).Scan(&article).Error
```
I want to use Raw SQL instead of ORM because this is for a project and I want to test out the comparison of Raw SQL and ORM.
|
How To Select an Array Using GORM Raw in PostgreSQL? |
|database|postgresql|go|struct|go-gorm| |
null |
I am working on android app where I need to allow the app to access location and I am looking for a way to make the user go directly to access location setting page where he can find the options:
allow all the time,
allow only while using the app
ask every time
don't allow
I tried using the blow code but it takes the user to app info page:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", PACKAGE_NAME, null);
intent.setData(uri);
startActivity(intent);
|
{"Voters":[{"Id":13288265,"DisplayName":"jksevend"}]} |
I do have a gstreamer pipeline string running with `gst-launch` `(CreateVideoPipelineSinkWithLaunch)`.
Now I want to build the same pipeline in code with `go-gst` (golang bindings).
The resulting pipeline `(CreateVideoPipelineSink)` does run, but for some reason the webrtc frontend is showing a frame every 30s only.
Have tried to run it with `GST_DEBUG=*:3` but this does not show any meaningful (The same warnings are logged with the string launch).
```
0:00:50.268410257 109844 0x75003c000f70 WARN v4l2 gstv4l2object.c:4721:gst_v4l2_object_set_crop:<v4l2src0:src> VIDIOC_S_CROP failed
0:00:50.278151417 109844 0x75003c000f70 WARN v4l2 gstv4l2object.c:3429:gst_v4l2_object_reset_compose_region:<v4l2src0:src> Failed to get default compose rectangle with VIDIOC_G_SELECTION: Invalid argument
```
I had this problem many times that just writing the same as in a launch string, does result in trouble and I would understand why.
```
func CreateVideoPipelineSinkWithLaunch(_ *zap.Logger) (*gst.Pipeline, <-chan media.Sample, error) {
pipeline, err := gst.NewPipelineFromString(`v4l2src device=/dev/video4 ! capsfilter caps="video/x-raw,width=(int)320,height=(int)240" ! videoconvert ! queue ! capsfilter caps="video/x-raw,format=(string)I420" ! x264enc speed-preset=ultrafast tune=zerolatency key-int-max=20 ! capsfilter caps="video/x-h264,stream-format=(string)byte-stream" ! appsink name=appsink`)
if err != nil {
return nil, nil, err
}
elem, err := pipeline.GetElementByName("appsink")
if err != nil {
return nil, nil, err
}
appsink := app.SinkFromElement(elem)
ch := make(chan media.Sample, 100)
setCallback(appsink, ch)
return pipeline, ch, nil
}
func CreateVideoPipelineSink(lg *zap.Logger) (*gst.Pipeline, <-chan media.Sample, error) {
// Create a pipeline
pipeline, err := gst.NewPipeline("pion-video-pipeline")
if err != nil {
return nil, nil, err
}
elems := make([]*gst.Element, 0)
// Create the src
src, err := gst.NewElement("v4l2src")
if err != nil {
return nil, nil, err
}
elems = append(elems, src)
src.Set("device", "/dev/video4")
filter1, err := gst.NewElement("capsfilter")
if err != nil {
return nil, nil, err
}
elems = append(elems, filter1)
c := gst.NewEmptySimpleCaps("video/x-raw")
c.SetValue("width", int(320))
c.SetValue("height", int(240))
lg.Info("capsfilter", zap.String("caps", c.String()))
err = filter1.SetProperty("caps", c)
if err != nil {
return nil, nil, err
}
// just to be on the save side
conv, err := gst.NewElement("videoconvert")
if err != nil {
return nil, nil, err
}
elems = append(elems, conv)
// add a queue
queue, err := gst.NewElement("queue")
if err != nil {
return nil, nil, err
}
elems = append(elems, queue)
// add a filter before enc
filterIn, err := gst.NewElement("capsfilter")
if err != nil {
return nil, nil, err
}
elems = append(elems, filterIn)
cIn := gst.NewEmptySimpleCaps("video/x-raw")
cIn.SetValue("format", "I420")
lg.Info("capsfilter", zap.String("caps", cIn.String()))
err = filterIn.SetProperty("caps", cIn)
if err != nil {
return nil, nil, err
}
// Create the enc
enc, err := gst.NewElement("x264enc")
if err != nil {
return nil, nil, err
}
elems = append(elems, enc)
enc.SetProperty("speed-preset", "ultrafast")
enc.SetProperty("tune", "zerolatency")
enc.SetProperty("key-int-max", 20)
//enc.SetProperty("bitrate", 300)
// add a filter after enc
filterOut, err := gst.NewElement("capsfilter")
if err != nil {
return nil, nil, err
}
elems = append(elems, filterOut)
cOut := gst.NewEmptySimpleCaps("video/x-h264")
cOut.SetValue("stream-format", "byte-stream")
lg.Info("capsfilter", zap.String("caps", cOut.String()))
err = filterOut.SetProperty("caps", cOut)
if err != nil {
return nil, nil, err
}
// Create the sink
appsink, err := app.NewAppSink()
if err != nil {
return nil, nil, err
}
elems = append(elems, appsink.Element)
ch := make(chan media.Sample, 100)
setCallback(appsink, ch)
// Add the elements to the pipeline
pipeline.AddMany(elems...)
// link the elements
gst.ElementLinkMany(elems...)
return pipeline, ch, nil
}
``` |
GStreamer launch pipeline to code with different result |
|go|gstreamer| |
{"OriginalQuestionIds":[41265266],"Voters":[{"Id":1746118,"DisplayName":"Naman","BindingReason":{"GoldTagBadge":"java"}}]} |
Just put a `\` in front:
`\Context::getContext()` |
I cannot figure out what is wrong with the protobuf Python code generation (I did check a couple of other similar questions)...let me share some details below.
I have the following folder structure:
```
βββ ors-proto
βΒ Β βββ bin
βΒ Β βΒ Β βββ buf-Linux-x86_64
βΒ Β βΒ Β βββ grpc_python_plugin
βΒ Β βββ buf.yaml
βΒ Β βββ config
βΒ Β βΒ Β βββ assembly
βΒ Β βΒ Β βββ proto.xml
βΒ Β βββ ors-proto.iml
βΒ Β βββ pom.xml
βΒ Β βββ src
βΒ Β βΒ Β βββ main
βΒ Β βΒ Β βββ proto
βΒ Β βΒ Β βββ test
βΒ Β βΒ Β βββ protobuf
βΒ Β βΒ Β βββ ors
βΒ Β βΒ Β βββ common
βΒ Β βΒ Β βΒ Β βββ v1
βΒ Β βΒ Β βΒ Β βββ common_model.proto
βΒ Β βΒ Β βββ ous
βΒ Β βΒ Β βΒ Β βββ v1
βΒ Β βΒ Β βΒ Β βββ ous_api.proto
βΒ Β βΒ Β βββ server
βΒ Β βΒ Β βββ v1
βΒ Β βΒ Β βββ ors_api.proto
βΒ Β βΒ Β βββ ors_model.proto
```
The buf.yaml looks as follows:
```
version: v1beta1
build:
roots:
- ors-proto/src/main/proto
lint:
use:
- DEFAULT
except:
- FIELD_LOWER_SNAKE_CASE
- PACKAGE_DIRECTORY_MATCH
- RPC_REQUEST_STANDARD_NAME
- RPC_RESPONSE_STANDARD_NAME
- SERVICE_SUFFIX
enum_zero_value_suffix: _UNKNOWN
breaking:
use:
- FILE
```
The common_model.proto is as follows:
```
syntax = "proto3";
package test.protobuf.ors.common.v1;
option java_package = "com.test.protobuf.ors.common.v1";
option java_multiple_files = true;
option java_outer_classname = "CommonModelProto";
message Field {
string platform_field_name = 1;
string field_value = 2;
string default_value = 3;
string platform_field_description = 4;
}
enum InternalField {
INTERNAL_FIELD_UNKNOWN = 0;
INTERNAL_FIELD_SYMBOL = 1;
}
```
The relevant pom.xml sections of the proto module look as follows:
```
......................................................................................
<properties>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
<exec-maven-plugin.version>3.2.0</exec-maven-plugin.version>
<os-maven-plugin.version>1.7.1</os-maven-plugin.version>
<protobuf-sources.directory>src/main/proto</protobuf-sources.directory>
<generated-sources.directory>${project.build.directory}/generated-sources</generated-sources.directory>
<protoc-dependencies.directory>${project.build.directory}/protoc-dependencies</protoc-dependencies.directory>
<protoc-dependencies-sources.directory>
${protoc-dependencies.directory}/com/google/protobuf/protobuf-java/${protobuf.version}/protobuf-java-${protobuf.version}.jar
</protoc-dependencies-sources.directory>
<protoc-plugins.directory>${project.build.directory}/protoc-plugins</protoc-plugins.directory>
<working.directory>${project.basedir}</working.directory>
<bin.directory>${project.basedir}/bin</bin.directory>
<skip-on-deploy>false</skip-on-deploy>
</properties>
................................................................................
<!-- Generate protobuf and gRPC code -->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
</protocArtifact>
<protoSourceRoot>${protobuf-sources.directory}</protoSourceRoot>
<protocPluginDirectory>${protoc-plugins.directory}</protocPluginDirectory>
<temporaryProtoFileDirectory>${protoc-dependencies.directory}</temporaryProtoFileDirectory>
<hashDependentPaths>false</hashDependentPaths>
<clearOutputDirectory>false</clearOutputDirectory>
</configuration>
<executions>
<execution>
<id>Generate Java Protobuf sources</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<outputDirectory>${generated-sources.directory}/java</outputDirectory>
</configuration>
</execution>
<execution>
<id>Generate Java gRPC sources</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
<outputDirectory>${generated-sources.directory}/java</outputDirectory>
</configuration>
</execution>
<execution>
<id>Generate Python Protobuf sources</id>
<goals>
<goal>compile-python</goal>
</goals>
<configuration>
<outputDirectory>${generated-sources.directory}/python</outputDirectory>
</configuration>
</execution>
<execution>
<id>Generate Python gRPC sources</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-python</pluginId>
<pluginExecutable>${bin.directory}/grpc_python_plugin</pluginExecutable>
<outputDirectory>${generated-sources.directory}/python</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
```
The result I get after running mvn clean install is below:
```
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: test/protobuf/ors/common/v1/common_model.proto
# Protobuf Python Version: 4.25.3
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n>test/protobuf/ors/common/v1/common_model.proto\x12\"test.protobuf.ors.common.v1\"\x94\x01\n\x05\x46ield\x12+\n#platform_field_name\x18\x01 \x01(\t\x12\x13\n\x0b\x66ield_value\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x03 \x01(\t\x12\x32\n*platform_field_description\x18\x04 \x01(\t*F\n\rInternalField\x12\x1a\n\x16INTERNAL_FIELD_UNKNOWN\x10\x00\x12\x19\n\x15INTERNAL_FIELD_SYMBOL\x10\x01\x42\x44\n&com.test.protobuf.ors.common.v1B\x18CommonModelProtoP\x01\x62\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'test.protobuf.ors.common.v1.common_model_pb2', _globals)
if _descriptor._USE_C_DESCRIPTORS == False:
_globals['DESCRIPTOR']._options = None
_globals['DESCRIPTOR']._serialized_options = b'\n&com.test.protobuf.ors.common.v1B\030CommonModelProtoP\001'
_globals['_INTERNALFIELD']._serialized_start=253
_globals['_INTERNALFIELD']._serialized_end=323
_globals['_FIELD']._serialized_start=103
_globals['_FIELD']._serialized_end=251
# @@protoc_insertion_point(module_scope)
```
...the pb2 file does not contain the actual message definitions.
Could someone please advise on what might be wrong in my setup?
(I have to mention that I see no issues with the generated Java files).
Thank you in advance. |
Incorrect/incomplete python pb2 file generation with buf |
|python|java|maven|protocol-buffers|buf| |
I used a **ready-made template** for my **asp.net** project...
I don't know much about html and Css,
I just **deleted and customized** some of the code by trial and error.
I spent 20 days on this back end and front end...
To **test mobile response**, I **minimized my web browser** in PC...
everything was **fine**... Now I encountered this when I tested it on my **phone**...
Can I kill myself? goddd i will lose my job help me please
This is **Pc** response : its **okey**
[![enter image description here][1]][1]
This Is **PC Minimized** Response : Its **Okey** too
[![enter image description here][2]][2]
This Is In **Mobile Browser**... : **very bad** How It Possible???!!
[![enter image description here][3]][3]
How It Possibleeee ???!!!! everything is bad
see footer !! it show footer like PC not mobile ! why???
what i should to do?
The best and fastest way to solve this problem in the whole project?
i dont know what i should share... what html tag are important now?example this is my footer(one of big problems)
<!-- Footer -->
<footer class="text-center text-lg-start text-white"
style="background-color: #231556" dir="rtl">
<!-- Section: Social media -->
<section class="d-flex justify-content-between p-4"
style="background-color: rgb(81,55,162)">
<!-- Left -->
<div class="me-5">
<span>connect us :</span>
</div>
<!-- Left -->
<!-- Right -->
<div>
<a href="" class="text-white me-4">
<i class="fab fa-facebook-f"></i>
</a>
<a href="" class="text-white me-4">
<i class="fab fa-twitter"></i>
</a>
<a href="" class="text-white me-4">
<i class="fab fa-google"></i>
</a>
<a href="" class="text-white me-4">
<i class="fab fa-instagram"></i>
</a>
<a href="" class="text-white me-4">
<i class="fab fa-linkedin"></i>
</a>
<a href="" class="text-white me-4">
<i class="fab fa-github"></i>
</a>
</div>
<!-- Right -->
</section>
<!-- Section: Social media -->
<!-- Section: Links -->
<section class="">
<div class="container text-center text-md-start mt-5">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase fw-bold">about us :</h6>
<hr class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px" />
<p>
something something something something something something something something something
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase fw-bold">good link </h6>
<hr class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px" />
<p>
<a href="#!" class="text-white">Your Account</a>
</p>
<p>
<a href="#!" class="text-white">Become an Affiliate</a>
</p>
<p>
<a href="#!" class="text-white">Shipping Rates</a>
</p>
<p>
<a href="#!" class="text-white">Help</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase fw-bold">about us</h6>
<hr class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px" />
<p><i class="fas fa-home mr-3"></i> New York, NY 10012, US</p>
<p><i class="fas fa-envelope mr-3"></i> info@example.com</p>
<p><i class="fas fa-phone mr-3"></i> + 01 234 567 88</p>
<p><i class="fas fa-print mr-3"></i> + 01 234 567 89</p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
</section>
<!-- Section: Links -->
<!-- Copyright -->
<div class="text-center p-3"
style="background-color: rgba(0, 0, 0, 0.2)">
Β© 2024 Copyright:
<a class="text-white" href="">Me</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
[1]: https://i.stack.imgur.com/mTvZo.jpg
[2]: https://i.stack.imgur.com/hCwEz.jpg
[3]: https://i.stack.imgur.com/VrpZV.jpg |
I've the same problem with the test. but i mock hooks in this way:
```jest.mock("react-dom", () => ({
...jest.requireActual("react-dom"),
useFormState: () => [{}, () => {}],
useFormStatus: () => ({ pending: false }),
}));
```
when i mock both hooks the tests are passed but I'm getting other errors:
``` console.error
Warning: Invalid value for prop `action` on <form> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ``` |
I'm having an issue with JS (with which my knowledge base is not large). Excuse me if this seems like a simple fix, but I cannot figure out what my problem is. I'm pulling from an array, and displaying images with links tied to the images, that lead to an external site. My issue is, I want to display the "genre" underneath the images and JS isn't responding to any of it.
Here's my JS:
```
async function getData(type) {
const url = 'https://itunes.apple.com/search?country=us&media=podcast&term=' + type;
const containerElement = window.document.querySelector("." + type + "-content")
const options = {
method: 'GET',
}
try {
const response = await fetch(url, options);
const result = await response.json();
result.results.map((item) => {
console.log(item)
const { collectionName, artworkUrl600, trackViewUrl, collectionViewUrl, primaryGenreName } = item;
console.log(collectionName, artworkUrl600, trackViewUrl, collectionViewUrl, primaryGenreName);
const itemElement = window.document.createElement("a");
itemElement.setAttribute("href", collectionViewUrl);
const collectionNameElement = window.document.createElement("h2");
const imageElement = window.document.createElement("img");
const genreElement = window.document.createElement("small");
itemElement.style.marginRight = "20px";
imageElement.classList.add('podcast-image');
genreElement.classList.add('small-genre');
imageElement.setAttribute("src", artworkUrl600);
collectionNameElement.textContent = collectionName;
genreElement.textContent = primaryGenreName;
imageElement.after(genreElement);
itemElement.append(imageElement);
containerElement.append(itemElement);
});
} catch (error) {
console.error(error);
}
}
getData("popular")
getData("trending")
```
I want the "primaryGenreName" to be present on the site underneath each image pulled. Just can't figure it out, any ideas? |
Here is a slightly edited version that will work in the expected way:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$("form").on("input",function(){
const checked=$(".form-check-input:checked").get().map(el=>el.value)
$("#selected-cases").val(checked.join(","));
})
<!-- language: lang-css -->
#selected-cases {width:500px}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form>
<div class="col-12">
<label for="selected-cases" class="form-label">selected cases<span class="text-muted"> *</span></label>
<input type="text" id="selected-cases" name="selected-cases" class="form-control" value="3966382,4168801,4168802,4169839">
</div>
<hr class="my-4"><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966382" checked>Save CaseID : 3966382</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4029501">Save CaseID : 4029501</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168818">Save CaseID : 4168818</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168801" checked>Save CaseID : 4168801</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168802" checked>Save CaseID : 4168802</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168822">Save CaseID : 4168822</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966388">Save CaseID : 3966388</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4114087">Save CaseID : 4114087</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966385">Save CaseID : 3966385</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169838">Save CaseID : 4169838</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169843">Save CaseID : 4169843</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168829">Save CaseID : 4168829</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168828">Save CaseID : 4168828</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168835">Save CaseID : 4168835</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169835">Save CaseID : 4169835</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169836">Save CaseID : 4169836</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169837">Save CaseID : 4169837</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169839" checked>Save CaseID : 4169839</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946200">Save CaseID : 3946200</label>
</div><div class="form-check">
<label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946201">Save CaseID : 3946201</label>
</div>
<button class="w-10 btn btn-primary btn-sm" type="submit">Save</button><div class="col-md-5">
<div id="summary">
selected-cases : <br/>
</div>
</div>
</form>
<!-- end snippet -->
|
Any have idea about how to read data from a TCP connection,
In my requirement I need to read data from TCP and process that data and write response back to TCP servers.
But I don't see any receive operation with the Sockets Connector.
Need to know how can we replicate only read functionality in Mule 4 |
Sockets Connector - is there any way to read data instead of send and receive - Mule 4 |
|excel|excel-formula|count|concatenation|countif| |
I have a Blazor WASM app that references a library that uses resource files to provide translations. The culture to use is specified explicitly by an option rather than using `CultureInfo.CurrentUICulture`, _et al._. I have a selector in the UI that allows the user to select the language to output, but I can't get the output from the library to use the specified language.
Example solution: https://github.com/gregsdennis/StackOverflow-BlazorLocalization
```
- MyLibrary
- Resources/
- MyLibrary.resx
- MyLibrary.es.resx
- MyLibrary.fr.resx
- MyLibrary.it.resx
- MyService.cs
- MyBlazorApp
- Pages
- Home.razor <-- contains language selector and invokes MyService
```
It seems that the localized DLLs (created from the resource files) are copied to the output folder in their appropriate culture-code-named folders, but they're not available from Blazor.
I've only seen examples like [this one](https://stackoverflow.com/a/76795688/878701) where the goal is to add localization directly to the Blazor app, but that's not what I'm trying to do.
Other similar-but-not-quite-the-same questions:
- https://stackoverflow.com/q/63225051/878701
- https://stackoverflow.com/q/24812415/878701 |
Localization in satellite library hosted in Blazor WASM |
|localization|blazor-webassembly| |
I have two JSON files: One for Locations, another for Objects at a location.
locations.json =>
[
{
"Name": "Location#1",
"X": 0,
"Y": 20
},
{
"Name": "Location#2",
"X": 0,
"Y": 19
},
...
]
objects.json ==>
[
{
"Name": "Piano",
"CurrentLocation": "Location#1"
},
{
"Name": "Violin",
"CurrentLocation": "Location#2"
},
...
]
The objects.json references the locations instances using the location names.
I have two classes that this deserializes to (or serializes from):
public class ObjectOfInterest
{
[JsonPropertyName("Name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("CurrentLocation")]
public LocationNode CurrentLocation { get; set; } = new()
}
public class Location
{
[JsonPropertyName("Name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("X")]
public float X { get; set; }
[JsonPropertyName("Y")]
public float Y { get; set; }
}
How do I create a custom JSONSerializer or Converter that takes the string Location name JSON attribute, and assigns the correct location instance to the Objects class? |
android studio open location permission page directly |
|android| |
> I tried to pass a a child module output to another child module as variable or input using terraform and I was able to provision the requirement successfully.
This configuration require multiple steps to be followed as one resource was depends on another.
**`Step 1:`**
To pass the names of the Resource Groups to other modules, you need to create output values for each of them in your Resource Groups module (`/modules/Resource_Groups/output.tf`).
**`Step 2:`**
To use the outputs from the `Azure_Module_RG` module in your main Terraform configuration (`TF_Repo/main.tf`), you need to pass them as inputs to other modules. This is how you reference them in your main configuration.
To begin, make sure that every module that requires a Resource Group name has a corresponding variable declared in its `variable.tf` file. For example, your Storage Accounts module should have a `variable.tf` file that contains:
variable "resource_group_name" {
description = "The name of the resource group"
type = string
}
My **`file structure`** for this requirement:
TF_Repo/
βββ main.tf
βββ variables.tf
βββ modules/
βββ Resource_Groups/
β βββ main.tf
β
βββ Storage_Accounts/
βββ main.tf
**My terraform configuration:**
#### `TF_Repo/main.tf`
provider "azurerm" {
features {}
}
module "Azure_Module_RG" {
source = "./modules/Resource_Groups"
name = var.resource_group_name
location = var.location
tags = var.common_tags
}
module "Azure_Module_SA" {
source = "./modules/Storage_Accounts"
name = var.storage_account_name
resource_group_name = module.Azure_Module_RG.resource_group_name
location = module.Azure_Module_RG.resource_group_location
account_tier = var.storage_account_tier
account_replication_type = var.storage_account_replication_type
tags = var.common_tags
depends_on = [module.Azure_Module_RG]
}
### `TF_Repo/variables.tf`
variable "common_tags" {
description = "Common tags to apply to all resources."
type = map(string)
default = {
Terraform = "true"
Environment = "Development"
}
}
variable "location" {
description = "The Azure region where to deploy the resources."
type = string
default = "East US"
}
variable "resource_group_name" {
description = "The name of the Azure Resource Group."
type = string
default = "demovksb-rg"
}
variable "storage_account_name" {
description = "The name of the Azure Storage Account. Must be unique across Azure."
type = string
default = "demostorsbvktest"
}
variable "storage_account_tier" {
description = "Defines the Tier to use for this storage account."
type = string
default = "Standard"
}
variable "storage_account_replication_type" {
description = "Defines the type of replication to use for this storage account."
type = string
default = "LRS"
}
#### `modules/Resource_Groups/main.tf`
variable "name" {
description = "The name of the resource group."
type = string
default = "demovksb-rg"
}
variable "location" {
description = "The location of the resource group."
type = string
default = "east us"
}
variable "tags" {
description = "A map of tags to assign to the resource."
type = map(string)
default = {}
}
resource "azurerm_resource_group" "rg" {
name = var.name
location = var.location
tags = var.tags
}
output "resource_group_name" {
value = azurerm_resource_group.rg.name
}
output "resource_group_location" {
value = azurerm_resource_group.rg.location
}
#### `modules/Storage_Accounts/main.tf`
variable "name" {
description = "The name of the storage account."
type = string
default = "demostorsbvktest"
}
variable "resource_group_name" {
description = "The name of the resource group the storage account is in."
type = string
}
variable "location" {
description = "The location of the storage account."
type = string
}
variable "account_tier" {
description = "Defines the Tier to use for this storage account."
type = string
}
variable "account_replication_type" {
description = "Defines the type of replication to use for this storage account."
type = string
}
variable "tags" {
description = "A map of tags to assign to the resource."
type = map(string)
default = {}
}
resource "azurerm_storage_account" "sa" {
name = var.name
resource_group_name = var.resource_group_name
location = var.location
account_tier = var.account_tier
account_replication_type = var.account_replication_type
tags = var.tags
}
**Output:**


|
null |
In which order `storage` event is received?
For example, tab_1 executes code
```typescript
localStorage.set('key', 1);
localStorage.set('key', 2);
```
and tab_2 executes code
```typescript
localStorage.set('key', 3);
localStorage.set('key', 4);
```
They execute code simultaneously.
Questions:
- Can 2 be stored before 1?
- Can 3 or 4 be stored between 1 and 2?
- Can tab_3 receive `storage` events not in same order as values were stored in?(like if we stored 3, 4, 1, 2, can we receive 1, 2, 3, 4, or even in random order like 4, 1, 2, 3) |
DECLARE @date VARCHAR(10)
SELECT @date = CONVERT(varchar(10),
DATEADD(day,
CASE
-- If today is Monday, set the offset to -3 days (previous Friday)
WHEN DATEPART(dw, GETDATE()) = 2 THEN -3
-- For all other days, set the offset to -1 day (yesterday)
ELSE -1
END,
GETDATE()),
101)
PRINT @date
Demo: [https://dbfiddle.uk/3-X-iHjw][1]
[1]: https://dbfiddle.uk/3-X-iHjw |
I want to call Fortran subroutines from Matlab and get the output from them. I'm using Windows 7 x64 and Matlab R2021b.
I have tried compiling in Matlab using mex command.
At
```
mex -setup FORTRAN
```
I have choosen Intel Parallel Studio XE 2019 for Fortran with Microsoft Visual Studio 2015.
In mex settings: 'C:\Program Files\MATLAB\R2021b\bin\win64\mexopts\intel_fortran_19_vs2015.xml' I have removed \fixed option from COMPFLAGS.
It appeared that it is not able to recognise f95 files:
Unknown file extension '.f95'.
After changing extension of fortran files from f95 to f90 and trying to compile I got error:
error
#5078: Unrecognized token '@' skipped
result_logic = FEXISTS@(filename,errorcode)
I'm not sure if this is the problem of compiler, which is probably not supporting Silver-frost FTN95, or I have to include FTN95 Library in some way. |
What software is required for compiling Matlab mex file from Fortran Silver-frost FTN95 project? |
|matlab|fortran|mex|silverfrost-fortran| |
null |
I am trying to get a virtual machine to send a string/list to a second virtual machine and then have the second virtual machine return a string to the first virtual machine.
To do this, I have decided to go with a python socket server and client script.
The virtual machines are both hosted via Oracle.
Here is the code
Server:
import socket
SERVER_IP = "localhost"
SERVER_PORT = 8000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((SERVER_IP, SERVER_PORT))
server_socket.listen(1)
print("Server listening on", SERVER_IP, "port", SERVER_PORT)
client_socket, client_address = server_socket.accept()
print("Connection from:", client_address)
data = client_socket.recv(1024)
print("Received data:", data.decode())
response = "Hello from the server!"
client_socket.send(response.encode())
client_socket.close()
server_socket.close()
Client:
import socket
SERVER_IP = "(Server Public IP Address)"
SERVER_PORT = 8000
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_IP, SERVER_PORT))
data = "Hello from the client!"
client_socket.send(data.encode())
response = client_socket.recv(1024)
print("Response from server:", response.decode())
client_socket.close()
I have opened up the port 8000 (tcp) with this tutorial:
https://www.youtube.com/watch?v=6Vgzvh2jqRQ
I have tried making the "localhost" with the actual public ip address
OSError: [Errno 99] Cannot assign requested address
I have made both machines ping each other successfully.
using ping (public ip)
Additionally, I tried to allow all protocols, but then when i run the code,
OSError: [Errno 113] No route to host
When running the code, the code does not show any indication of connection.
(with specifying src:8000 dst:8000 ip protcol" tcp)
I have no idea what to do
|
I implemented my own custom router which routes request coming into my server.
router.use('/admin/', adminRouter);
the router here is that of express.router()
The adminRouter:
function makeAdminAPIRouter({
adminAuthController,
electionController,
}: Controllers) {
return function route(req: Request, res: Response, next: NextFunction) {
// TODO: Refactor routing logic
if (req.path.startsWith('/auth')) {
adminAuthController(req, res, next);
}
if (req.path.startsWith('/elections')) {
console.log(req);
electionController(req, res, next);
}
}}
export const adminRouter = makeAdminAPIRouter({
adminAuthController,
electionController,
})
and i have a `PUT` route `/admin/elections/update/:id`, which matches `/admin/`, but the id is returning undefined. i can access the req.body and req.query, but the req.params is returning undefined.
Is there something wrong with my implementation? |
Req.params is undefined |
|node.js|express| |
env variable and path is setting done but graalvm is not available.
```sh
java --version
java 22 2024-03-19
Java(TM) SE Runtime Environment (build 22+36-2370)
Java HotSpot(TM) 64-Bit Server VM (build 22+36-2370, mixed mode, sharing)
gu install native-image
'gu' is not recognized as an internal or external command,
operable program or batch file.
```
when using java --version - output is graalvm with version it will be displayed
gu list - it should be shown
|
{"Voters":[{"Id":1255289,"DisplayName":"miken32"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":2756409,"DisplayName":"TylerH"}],"SiteSpecificCloseReasonIds":[11]} |
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[18]} |
{"Voters":[{"Id":522444,"DisplayName":"Hovercraft Full Of Eels"},{"Id":794749,"DisplayName":"gre_gor"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
When using diffusers like
```
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
```
I get the following error:
```
ImportError: cannot import name 'DIFFUSERS_SLOW_IMPORT' from 'diffusers.utils' (/opt/conda/lib/python3.10/site-packages/diffusers/utils/__init__.py)
```
Also tried downgrading the version to 0.26.3 , but didn't help.
Diffusers version : 0.27.2 |
|python| |
I updated **readOnlyRootFilesystem: true** in my cronjob yaml but started getting the error
OSError: [Errno 30] Read-only file system: '/absolute/path/to/your/folder'
I further added an empty directory
volumeMounts:
- name: tmp-volume
mountPath: absolute/path/to/your/folder
volumes:
- name: tmp-volume
emptyDir: {}
After adding this I am starting to get
```
**python3.11: can't open file 'absolute/path/to/your/folder/text.py': [Errno 2] No such file or directory**
```
I have attached the cronjob yaml
```
containers:
- env:
- name: ENV_VAR
value: value
- name: MAINTAIN_HA_POOL
value: "true"
- name: PROCESS_SCHEDULER_REQUESTS
value: "true"
- name: MAINTAIN_NODE_POOL
value: "false"
- name: ENABLE_LSV3
value: "false"
image: us.icr.io/nz-cloud/nzsaas-common-pool-cronjob:master-2.1.2.0-20240329-111245
imagePullPolicy: Always
name: common-machine-pool-cronjob-container
resources: {}
securityContext:
privileged: true
readOnlyRootFilesystem: true
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /opt/ibm/common-pool-cronjob/
name: tmp-volume
volumes:
- emptyDir: {}
name: tmp-volume
```
FYI I have given CHMOD 777 to the particular folder |
having problems with my js external file with html |
|javascript| |
pipeline {
agent any
stages {
stage('checkout') {
steps {
git 'https://github url'
}
}
stage('mvn compile') {
steps {
sh 'mvn compile'
}
}
stage('mvn tests') {
steps {
sh 'mvn test'
}
}
}
} |
Your parameter declaration is a bit incorrect. This results in an invalid OpenAPI definition being generated by FastAPI, which in turn causes codegen errors.
In FastAPI, query parameters are required by default unless the parameter is nullable (e.g. `string | None`) or has a default value. So you don't need the `required=True` annotation.
Also, required parameters cannot have default values. Providing a default value is a hint to FastAPI to make the parameter optional. If you want to provide an _example_ value for documentation purposes, use the `example` keyword instead.
For more information, see FastAPI documentation on [Required query parameters](https://fastapi.tiangolo.com/tutorial/query-params/#required-query-parameters).
<br/>
To resolve the issue, change your parameter declaration to:
```python
group_mode: GroupMode = Query(
example="1d",
description="Group by a parameter. Options are Minute, Hour, Day, Week, Month, Year.",
),
``` |
@Giulio Centorame
as I said before: your data lacks a clear/unique separator. I did some research on your example file (file1_header.txt) and took a closer look at the file, and what you can see immediately is that there is no unique separator.
Your first column (f.eid) is seperated from the 2nd one (f.3.0.0 ) by a tab... whereas column #2 is seperated from column #3 (f.3.1.0 ) by a space.
Tabs are shown below with the regular expression \t and space with \s :
So, this is the beginning of your header:
f.eid\t{1}f.3.0.0\s{1}f.3.1.0\s{1}f.3.2.0 ....
And so on with spaces up to column 14, where there is again a tabulator as a separator. There is also a change in the tab width ( 1 -> 2, ie. \t{2})
.... f.6.2.0\s{1}f.19.0.0\t{2}f.21.0.0\t{2}f.21.1.0 ....
Hence I'm not surprised at all that mlr can't cope with this.
I cleaned up your header data, appended a stupid line of data below it (sorry for that) and voila: mlr has no probem with it:
New (cropped) sample file with 1 space as separator:
"f.eid f.3.0.0 f.3.1.0 f.3.2.0 f.4.0.0 f.4.1.0 f.4.2.0 f.5.0.0 f.5.1.0 f.5.2.0 f.6.0.0 f.6.1.0 f.6.2.0 f.19.0.0 f.21.0.0 f.21.1.0
data_f.eid data_f.3.0.0 data_f.3.1.0 data_f.3.2.0 data_f.4.0.0 data_f.4.1.0 data_f.4.2.0 data_f.5.0.0 data_f.5.1.0 data_f.5.2.0 data_f.6.0.0 data_f.6.1.0 data_f.6.2.0 data_f.19.0.0 data_f.21.0.0 data_f.21.1.0"
$ mlr --csv --fs ' ' --opprint --from guilio-file1_header-cropped.txt cut -f f.4.1.0,f.6.2.0,f.21.1.0
--->
f.4.1.0 f.6.2.0 f.21.1.0
data_f.4.1.0 data_f.6.2.0 data_f.21.1.0
It would be interesting to have some real world data. Just a few lines, Guilio. |
I have table which represents sequence of points, I need to get sum by all possible combinations. The main problem is how to do it with minimum actions because the Real table is huge
|Col1|col2|col3|col4|col5|col6|ct|
|:---|:---|:---|:---|:---|:---|:-|
|Id1 |id2 |id3 |id4 |id5 |id6 |30|
|Id8 |id3 |id5 |id2 |id4 |id6 |45|
The expected result is
|p1 |p2 |ct|
|:--|:--|:-|
|Id3|id5|75|
|Id3|id4|75|
|Id3|id6|75|
|Id5|id6|75|
|Id2|id4|75|
|Id2|id6|75|
|Id4|id6|75|
I would be grateful for any help
|
C# Map JSON Serialization and Deserialization to Reference Object Using Object Property |
|c#|json|deserialization|jsonserializer| |