content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
Can you use .NET Active Directory for authentication from a MAUI Windows Desktop app and is there a code sample?
Has anyone been able to get a MAUI Windows desktop app to work with either .NET Active Directory or Active Directory Federation Services for authentication?
For small companies and even medium size companies operating with tight margins, .NET Active Directory is all they need or can afford.
Blazor Server supported the following code:
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
UserId = user.Identity.Name;
}
Which made it really easy to work with .NET Windows Active Directory. But, I haven't been able to get that to work in a MAUI Windows Desktop app. MAUI Blazor Desktop apps have more in common with Blazor Server than MAUI Blazor Mobile apps from security requirements standpoint.
A:
MAUI Blazor, since it is cross platform, uses the security of the underlying platform. So, for Windows it is simply:
using System.Security.Principal;
using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
{
UserId = windowsIdentity.Name;
}
|
Can you use .NET Active Directory for authentication from a MAUI Windows Desktop app and is there a code sample?
|
Has anyone been able to get a MAUI Windows desktop app to work with either .NET Active Directory or Active Directory Federation Services for authentication?
For small companies and even medium size companies operating with tight margins, .NET Active Directory is all they need or can afford.
Blazor Server supported the following code:
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
UserId = user.Identity.Name;
}
Which made it really easy to work with .NET Windows Active Directory. But, I haven't been able to get that to work in a MAUI Windows Desktop app. MAUI Blazor Desktop apps have more in common with Blazor Server than MAUI Blazor Mobile apps from security requirements standpoint.
|
[
"MAUI Blazor, since it is cross platform, uses the security of the underlying platform. So, for Windows it is simply:\nusing System.Security.Principal;\n\nusing (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())\n{\n UserId = windowsIdentity.Name;\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"active_directory",
"c#",
"maui_windows"
] |
stackoverflow_0074644942_active_directory_c#_maui_windows.txt
|
Q:
Keep the trailing newlines when reading a PEM with yq
I have the following use case. I need to read from an YAML file using yq v4 PEM keys. It's then important to keep the trailing newlines otherwise a future reading of those PEM keys would miserably fail.
I haven't found a way in Bash to read a PEM from an Yaml file and store it in a variable keeping the trailing newlines.
Naturally if I would use $() Bash would remove the trailing new lines.
Do you have any other idea?
A:
I seriously doubt that you genuinely need to do this (see comments on the question), but using a process substitution to feed input to the read command (configured to expect end-of-input to be signified by a NUL rather than a newline) will work:
IFS='' read -r -d '' input < <(yq ... && printf '\0')
Be sure you check stored contents with echo "$input" or declare -p input, not echo $input. (That's true in the command-substitution case too).
|
Keep the trailing newlines when reading a PEM with yq
|
I have the following use case. I need to read from an YAML file using yq v4 PEM keys. It's then important to keep the trailing newlines otherwise a future reading of those PEM keys would miserably fail.
I haven't found a way in Bash to read a PEM from an Yaml file and store it in a variable keeping the trailing newlines.
Naturally if I would use $() Bash would remove the trailing new lines.
Do you have any other idea?
|
[
"I seriously doubt that you genuinely need to do this (see comments on the question), but using a process substitution to feed input to the read command (configured to expect end-of-input to be signified by a NUL rather than a newline) will work:\nIFS='' read -r -d '' input < <(yq ... && printf '\\0')\n\nBe sure you check stored contents with echo \"$input\" or declare -p input, not echo $input. (That's true in the command-substitution case too).\n"
] |
[
3
] |
[] |
[] |
[
"bash",
"yq"
] |
stackoverflow_0074662330_bash_yq.txt
|
Q:
What is the name of the following file format [category] key=value
What is the name of the file format that is mostly used for profiles. Example below:
[profile 1]
key1=value1
key2=value2
key3=value3
[profile 2]
key1=value1a
key2=value2a
key3=value3a
A:
The format matches that of an INI file.
|
What is the name of the following file format [category] key=value
|
What is the name of the file format that is mostly used for profiles. Example below:
[profile 1]
key1=value1
key2=value2
key3=value3
[profile 2]
key1=value1a
key2=value2a
key3=value3a
|
[
"The format matches that of an INI file.\n"
] |
[
0
] |
[] |
[] |
[
"file",
"file_format",
"text"
] |
stackoverflow_0070454869_file_file_format_text.txt
|
Q:
Superset Graph chart rollover/tooltip
I'm new to Superset and am trying to amend the information displayed on tooltip/mouse rollover of a node when using the Graph Chart (the network chart viz).
Any ideas? What/where is the javascript tooltip generator?
Tried using the default settings and tried info found here
A:
The javascript tooltip generator is only used by the DeckGL plugins, and is also turned off by default in Superset's configuration anyway, since it's an inroad to XSS exploits. I believe to customize these tooltips for the Graph Chart, you/we would need to modify the plugin and add extra controls to the control panel. Feel free to join us on the #customizing-superset channel in the Superset community Slack workspace if you'd like to have a discussion about how to get involved designing/building this feature.
|
Superset Graph chart rollover/tooltip
|
I'm new to Superset and am trying to amend the information displayed on tooltip/mouse rollover of a node when using the Graph Chart (the network chart viz).
Any ideas? What/where is the javascript tooltip generator?
Tried using the default settings and tried info found here
|
[
"The javascript tooltip generator is only used by the DeckGL plugins, and is also turned off by default in Superset's configuration anyway, since it's an inroad to XSS exploits. I believe to customize these tooltips for the Graph Chart, you/we would need to modify the plugin and add extra controls to the control panel. Feel free to join us on the #customizing-superset channel in the Superset community Slack workspace if you'd like to have a discussion about how to get involved designing/building this feature.\n"
] |
[
0
] |
[] |
[] |
[
"apache_superset",
"javascript"
] |
stackoverflow_0074629455_apache_superset_javascript.txt
|
Q:
Sample python code provided by GCP - service variable undefined
The following sample code is provided by GCP to use the restAPI to list out group membership when you provide the group_id. Code sample can be found here. I can run the sample directly from the URI given, but when trying to run it from Python with the sample code provided. My IDE intellisense says that service in the very last line is an undefined variable. I can find nothing in GCP to indicate what library this might come from or what I should replace it with.
def search_transitive_memberships(service, parent, page_size):
try:
memberships = []
next_page_token = ''
while True:
query_params = urlencode(
{
"page_size": page_size,
"page_token": next_page_token
}
)
request = service.groups().memberships().searchTransitiveMemberships(parent=parent)
request.uri += "&" + query_params
response = request.execute()
if 'memberships' in response:
memberships += response['memberships']
if 'nextPageToken' in response:
next_page_token = response['nextPageToken']
else:
next_page_token = ''
if len(next_page_token) == 0:
break;
print(memberships)
except Exception as e:
print(e)
# Return results with a page size of 50
search_transitive_memberships(service, 'groups/01234567abcdefg', 50) ## <- service undefined
Appreciate assistance in identifying what I need to add to have service recognized.
A:
Ok, it appears what is missing from the code samples provided by GCP are the steps to build and use a service object.
Documentation on that can be found here: https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md#building-and-calling-a-service
So for my sample above the last line would actually be:
service = build('cloudidentity', 'v1')
search_transitive_memberships(service, 'groups/01234567abcdefg', 50)
service.close
After importing build from googleapiclient.discovery
Github link above also details how to provide oauth creds for it to work.
|
Sample python code provided by GCP - service variable undefined
|
The following sample code is provided by GCP to use the restAPI to list out group membership when you provide the group_id. Code sample can be found here. I can run the sample directly from the URI given, but when trying to run it from Python with the sample code provided. My IDE intellisense says that service in the very last line is an undefined variable. I can find nothing in GCP to indicate what library this might come from or what I should replace it with.
def search_transitive_memberships(service, parent, page_size):
try:
memberships = []
next_page_token = ''
while True:
query_params = urlencode(
{
"page_size": page_size,
"page_token": next_page_token
}
)
request = service.groups().memberships().searchTransitiveMemberships(parent=parent)
request.uri += "&" + query_params
response = request.execute()
if 'memberships' in response:
memberships += response['memberships']
if 'nextPageToken' in response:
next_page_token = response['nextPageToken']
else:
next_page_token = ''
if len(next_page_token) == 0:
break;
print(memberships)
except Exception as e:
print(e)
# Return results with a page size of 50
search_transitive_memberships(service, 'groups/01234567abcdefg', 50) ## <- service undefined
Appreciate assistance in identifying what I need to add to have service recognized.
|
[
"Ok, it appears what is missing from the code samples provided by GCP are the steps to build and use a service object.\nDocumentation on that can be found here: https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md#building-and-calling-a-service\nSo for my sample above the last line would actually be:\nservice = build('cloudidentity', 'v1')\nsearch_transitive_memberships(service, 'groups/01234567abcdefg', 50)\nservice.close\n\nAfter importing build from googleapiclient.discovery\nGithub link above also details how to provide oauth creds for it to work.\n"
] |
[
1
] |
[] |
[] |
[
"gcloud",
"google_cloud_platform",
"google_iam",
"python"
] |
stackoverflow_0074662133_gcloud_google_cloud_platform_google_iam_python.txt
|
Q:
Svelte transition not working properly when going in
Two divs that have both transition:fade work properly on going out, but they just appear as going in, I don't understand this behavior... The transition work if I only specify in:transition, but I would like to have both stages of the transition
A:
Since the transitions are coming from the same element, the starting and ending animation get triggered and end at the same time, so there is no time for the starting animation to show. To fix this I added a delay on the starting animation:
<div out:blur={{ duration: 400 }} in:blur={{ delay: 400, duration: 400 }}>
and it works perfectly
|
Svelte transition not working properly when going in
|
Two divs that have both transition:fade work properly on going out, but they just appear as going in, I don't understand this behavior... The transition work if I only specify in:transition, but I would like to have both stages of the transition
|
[
"Since the transitions are coming from the same element, the starting and ending animation get triggered and end at the same time, so there is no time for the starting animation to show. To fix this I added a delay on the starting animation:\n<div out:blur={{ duration: 400 }} in:blur={{ delay: 400, duration: 400 }}>\nand it works perfectly\n"
] |
[
0
] |
[] |
[] |
[
"css_transitions",
"frontend",
"javascript",
"svelte",
"typescript"
] |
stackoverflow_0074660584_css_transitions_frontend_javascript_svelte_typescript.txt
|
Q:
Mongo JSInterpreter SyntaxError: unexpected token: keyword 'function'
I am using MongoDB 4.4.8, according to mongo reference, $function is new in 4.4, but running the following code, the server responded:
In my config file, security.javascriptEnabled is not set, so I think it should be default to true
Command failed with error 139 (JSInterpreterFailure): 'SyntaxError: unexpected token: keyword 'function'' on server {}. The full response is {"ok": 0.0, "errmsg": "SyntaxError: unexpected token: keyword 'function'", "code": 139, "codeName": "JSInterpreterFailure"}
db.my_collection.aggregate(
[
{$addFields:{
query: {
$function:{
body: function(ss){
arr = ss.split('|');
result = {};
arr.forEach(element => {
kv = element.split(':');
result[kv[0]] = kv[1];
});
return result['q']},
args: ['my_field'],
lang:'js'
}
}
}}
]);
The function can be executed successfully on my computer, but mongo seemed not be able to parse the keyword function, what happened?
A:
I had the same problem but I tried in the mongo shell directly and it worked, might be a problem with DataGrip rather than with mongo surprisingly
|
Mongo JSInterpreter SyntaxError: unexpected token: keyword 'function'
|
I am using MongoDB 4.4.8, according to mongo reference, $function is new in 4.4, but running the following code, the server responded:
In my config file, security.javascriptEnabled is not set, so I think it should be default to true
Command failed with error 139 (JSInterpreterFailure): 'SyntaxError: unexpected token: keyword 'function'' on server {}. The full response is {"ok": 0.0, "errmsg": "SyntaxError: unexpected token: keyword 'function'", "code": 139, "codeName": "JSInterpreterFailure"}
db.my_collection.aggregate(
[
{$addFields:{
query: {
$function:{
body: function(ss){
arr = ss.split('|');
result = {};
arr.forEach(element => {
kv = element.split(':');
result[kv[0]] = kv[1];
});
return result['q']},
args: ['my_field'],
lang:'js'
}
}
}}
]);
The function can be executed successfully on my computer, but mongo seemed not be able to parse the keyword function, what happened?
|
[
"I had the same problem but I tried in the mongo shell directly and it worked, might be a problem with DataGrip rather than with mongo surprisingly\n"
] |
[
0
] |
[] |
[] |
[
"aggregation_framework",
"function",
"javascript",
"mongodb"
] |
stackoverflow_0072641353_aggregation_framework_function_javascript_mongodb.txt
|
Q:
Cannot redeclare block scoped variable
I'm building a node app, and inside each file in .js used to doing this to require in various packages.
let co = require("co");
But getting
etc. So using typescript it seems there can only be one such declaration/require across the whole project?
I'm confused about this as I thought let was scoped to the current file.
I just had a project that was working but after a refactor am now getting these errors all over the place.
Can someone explain?
A:
The best explanation I could get is from Tamas Piro's post.
TLDR;
TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.
To solve this:
Rename the variable, or
Use TypeScript modules, and add an empty export{}:
export {};
or
Configure your compiler options by not adding DOM typings:
Edit tsconfig.json in the TypeScript project directory.
{
"compilerOptions": {
"lib": ["es6"]
}
}
A:
Regarding the error itself, let is used to declare local variables that exist in block scopes instead of function scopes. It's also more strict than var, so you can't do stuff like this:
if (condition) {
let a = 1;
...
let a = 2;
}
Also note that case clauses inside switch blocks don't create their own block scopes, so you can't redeclare the same local variable across multiple cases without using {} to create a block each.
As for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.
Try importing an external module the standard ES6 way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:
import * as co from "./co"
This will still result in a compile error if you have something named co already, as expected. For example, this is going to be an error:
import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;
If you are getting an error "cannot find module co"...
TypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declare your module in a .d.ts definition file that doesn't contain module-level exports:
declare module "co" {
declare var co: any;
export = co;
}
A:
For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.
Just add:
export {};
at the top of any files with code without an existing export.
Credit to EUGENE MURAVITSKY
A:
I was receiving this similar error when compiling my Node.JS Typescript application:
node_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.
The fix was to remove this:
"files": [
"./node_modules/@types/node/index.d.ts"
]
and to replace it with this:
"compilerOptions": {
"types": ["node"]
}
A:
I have also dealt with this issue while working with ts on vscode. The way i fix this is easy, but it might not be the same as your problem.
My editor shows this error when i have the typescript file and the javascript file open at the same time in the recent tabs. I just close it and the error goes away.
Hope this helps someone who may also be scratching their head from this simple bug.
A:
Use IIFE(Immediately Invoked Function Expression), IIFE
(function () {
all your code is here...
})();
A:
That´s the editor warning, becaouse, when you have open index.js which is compiled and also index.ts. you will see this.. but when you close index.js it will be ok.
A:
The solution for me was to convert my code from using CommonJS (require, module.exports, etc) to ES Modules (import, export, etc.)
The TypeScript documentation also appears to recommend ES Module syntax: TypeScript Modules
Of course there's a lot more to it than this, but as a start:
Replace instances of require with import, e.g.
Replace:
const https = require('https');
With:
import https from 'https';
Replace the default module.exports with export default, e.g.
Replace:
module.exports = myVar ...
With:
export default myVar ...
Replace other module.exports with export, e.g.
Replace:
module.exports.myVar =
or:
module.export = { myVar ... }
With:
export myVar ...
More here: From CommonJS to ES Modules: How to modernize your Node.js app
A:
Here is my fix for my situation. Simple and Fast!!!
This happening when the block-scoped variable have declared somewhere in the source code.
To fix this, remove module.exports = and replace by export default.
A:
In my case the following tsconfig.json solved problem:
{
"compilerOptions": {
"esModuleInterop": true,
"target": "ES2020",
"moduleResolution": "node"
}
}
There should be no type: module in package.json.
A:
I got the same problem, and my solution looks like this:
// *./module1/module1.ts*
export module Module1 {
export class Module1{
greating(){ return 'hey from Module1'}
}
}
// *./module2/module2.ts*
import {Module1} from './../module1/module1';
export module Module2{
export class Module2{
greating(){
let m1 = new Module1.Module1()
return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
}
}
}
Now we can use it on the server side:
// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';
export module Server {
export class Server{
greating(){
let m2 = new Module2.Module2();
return "hello from server & loaded modules: " + m2.greating();
}
}
}
exports.Server = Server;
// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());
And on the client side too:
// *./public/javscripts/index/index.ts*
import {Module2} from './../../../module2/module2';
document.body.onload = function(){
let m2 = new Module2.Module2();
alert(m2.greating());
}
// ./views/index.jade
extends layout
block content
h1= title
p Welcome to #{title}
script(src='main.js')
//
the main.js-file created by gulp-task 'browserify' below in the gulpfile.js
And, of course, a gulp-file for all of this:
// *./gulpfile.js*
var gulp = require('gulp'),
ts = require('gulp-typescript'),
runSequence = require('run-sequence'),
browserify = require('gulp-browserify'),
rename = require('gulp-rename');
gulp.task('default', function(callback) {
gulp.task('ts1', function() {
return gulp.src(['./module1/module1.ts'])
.pipe(ts())
.pipe(gulp.dest('./module1'))
});
gulp.task('ts2', function() {
return gulp.src(['./module2/module2.ts'])
.pipe(ts())
.pipe(gulp.dest('./module2'))
});
gulp.task('ts3', function() {
return gulp.src(['./public/javascripts/index/index.ts'])
.pipe(ts())
.pipe(gulp.dest('./public/javascripts/index'))
});
gulp.task('browserify', function() {
return gulp.src('./public/javascripts/index/index.js', { read: false })
.pipe(browserify({
insertGlobals: true
}))
.pipe(rename('main.js'))
.pipe(gulp.dest('./public/javascripts/'))
});
runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})
Updated.
Of course, it's not neccessary to compile typescript files separatly.
runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback) works perfect.
A:
In my case (using IntelliJ) File - Invalidate Caches / Restart... did the trick.
A:
I got the similar error when I was importing express incorrectly.
All I had to do was replace
const router = require('express').Router();
with
import express from 'express';
const router = express.Router();
A:
In my case I was using angular and I was trying to assign a variable in a method with colon instead of equal, like this:
const user$ : this.service.getUser();
It should've been:
const user$ = this.service.getUser();
A:
another solution namespace
IIFE function & closure
demo.ts
// 1. namespace function
namespace a {
const func = () => {
//
}
}
// 2. function
const test = () => {
//
}
demo.js
"use strict";
// 1. namespace function
var a;
(function (a) {
const func = () => {
//
};
})(a || (a = {}));
// 2. function
const test = () => {
//
};
refs
https://www.typescriptlang.org/docs/handbook/namespaces.html
https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html
A:
In my case refactor to use namespace solved most issues
A:
So... I did something, and it seemed to solve the problem, but I'm not really sure of unseen consequences, but it seems really simple.
I just put { at the start of the file and } at the end, therefore making a new block in the file...
file1.ts
{
let co=require('co');
//...
module.exports=...
}
file2.ts
let co=require('co');
let f1=require('./file1');
//...
module.exports=...
|
Cannot redeclare block scoped variable
|
I'm building a node app, and inside each file in .js used to doing this to require in various packages.
let co = require("co");
But getting
etc. So using typescript it seems there can only be one such declaration/require across the whole project?
I'm confused about this as I thought let was scoped to the current file.
I just had a project that was working but after a refactor am now getting these errors all over the place.
Can someone explain?
|
[
"The best explanation I could get is from Tamas Piro's post.\nTLDR;\nTypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.\nTo solve this:\n\nRename the variable, or\n\nUse TypeScript modules, and add an empty export{}:\nexport {};\n\nor\n\nConfigure your compiler options by not adding DOM typings:\n\n\nEdit tsconfig.json in the TypeScript project directory.\n{\n \"compilerOptions\": {\n \"lib\": [\"es6\"]\n }\n}\n\n",
"Regarding the error itself, let is used to declare local variables that exist in block scopes instead of function scopes. It's also more strict than var, so you can't do stuff like this:\nif (condition) {\n let a = 1;\n ...\n let a = 2;\n}\n\nAlso note that case clauses inside switch blocks don't create their own block scopes, so you can't redeclare the same local variable across multiple cases without using {} to create a block each.\n\nAs for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.\nTry importing an external module the standard ES6 way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:\nimport * as co from \"./co\"\n\nThis will still result in a compile error if you have something named co already, as expected. For example, this is going to be an error:\nimport * as co from \"./co\"; // Error: import definition conflicts with local definition\nlet co = 1;\n\n\nIf you are getting an error \"cannot find module co\"...\nTypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declare your module in a .d.ts definition file that doesn't contain module-level exports:\ndeclare module \"co\" {\n declare var co: any;\n export = co;\n}\n\n",
"For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.\nJust add:\nexport {};\n\nat the top of any files with code without an existing export.\nCredit to EUGENE MURAVITSKY\n",
"I was receiving this similar error when compiling my Node.JS Typescript application:\nnode_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.\nThe fix was to remove this:\n\"files\": [\n \"./node_modules/@types/node/index.d.ts\"\n]\n\nand to replace it with this:\n\"compilerOptions\": {\n \"types\": [\"node\"]\n}\n\n",
"I have also dealt with this issue while working with ts on vscode. The way i fix this is easy, but it might not be the same as your problem.\nMy editor shows this error when i have the typescript file and the javascript file open at the same time in the recent tabs. I just close it and the error goes away.\nHope this helps someone who may also be scratching their head from this simple bug.\n",
"Use IIFE(Immediately Invoked Function Expression), IIFE\n(function () {\n all your code is here...\n\n })();\n\n",
"That´s the editor warning, becaouse, when you have open index.js which is compiled and also index.ts. you will see this.. but when you close index.js it will be ok.\n",
"The solution for me was to convert my code from using CommonJS (require, module.exports, etc) to ES Modules (import, export, etc.)\nThe TypeScript documentation also appears to recommend ES Module syntax: TypeScript Modules\nOf course there's a lot more to it than this, but as a start:\n\nReplace instances of require with import, e.g.\nReplace:\nconst https = require('https');\n\nWith:\nimport https from 'https';\n\n\nReplace the default module.exports with export default, e.g.\nReplace:\nmodule.exports = myVar ...\n\nWith:\nexport default myVar ...\n\n\nReplace other module.exports with export, e.g.\nReplace:\nmodule.exports.myVar = \n\nor:\nmodule.export = { myVar ... }\n\nWith:\nexport myVar ...\n\n\n\nMore here: From CommonJS to ES Modules: How to modernize your Node.js app\n",
"Here is my fix for my situation. Simple and Fast!!!\n\nThis happening when the block-scoped variable have declared somewhere in the source code.\nTo fix this, remove module.exports = and replace by export default.\n",
"In my case the following tsconfig.json solved problem:\n{\n \"compilerOptions\": {\n \"esModuleInterop\": true,\n \"target\": \"ES2020\",\n \"moduleResolution\": \"node\"\n }\n}\n\nThere should be no type: module in package.json.\n",
"I got the same problem, and my solution looks like this:\n// *./module1/module1.ts*\nexport module Module1 {\n export class Module1{\n greating(){ return 'hey from Module1'}\n }\n}\n\n\n// *./module2/module2.ts*\nimport {Module1} from './../module1/module1';\n\nexport module Module2{\n export class Module2{\n greating(){\n let m1 = new Module1.Module1()\n return 'hey from Module2 + and from loaded Model1: '+ m1.greating();\n }\n }\n}\n\nNow we can use it on the server side:\n// *./server.ts*\n/// <reference path=\"./typings/node/node.d.ts\"/>\nimport {Module2} from './module2/module2';\n\nexport module Server {\n export class Server{\n greating(){\n let m2 = new Module2.Module2();\n return \"hello from server & loaded modules: \" + m2.greating();\n }\n }\n}\n\nexports.Server = Server;\n\n// ./app.js\nvar Server = require('./server').Server.Server;\nvar server = new Server();\nconsole.log(server.greating());\n\nAnd on the client side too:\n// *./public/javscripts/index/index.ts*\n\nimport {Module2} from './../../../module2/module2';\n\ndocument.body.onload = function(){\n let m2 = new Module2.Module2();\n alert(m2.greating());\n}\n\n// ./views/index.jade\nextends layout\n\nblock content\n h1= title\n p Welcome to #{title}\n script(src='main.js')\n //\n the main.js-file created by gulp-task 'browserify' below in the gulpfile.js\n\nAnd, of course, a gulp-file for all of this:\n// *./gulpfile.js*\nvar gulp = require('gulp'),\n ts = require('gulp-typescript'),\n runSequence = require('run-sequence'),\n browserify = require('gulp-browserify'),\n rename = require('gulp-rename');\n\ngulp.task('default', function(callback) {\n\n gulp.task('ts1', function() {\n return gulp.src(['./module1/module1.ts'])\n .pipe(ts())\n .pipe(gulp.dest('./module1'))\n });\n\n gulp.task('ts2', function() {\n return gulp.src(['./module2/module2.ts'])\n .pipe(ts())\n .pipe(gulp.dest('./module2'))\n });\n\n gulp.task('ts3', function() {\n return gulp.src(['./public/javascripts/index/index.ts'])\n .pipe(ts())\n .pipe(gulp.dest('./public/javascripts/index'))\n });\n\n gulp.task('browserify', function() {\n return gulp.src('./public/javascripts/index/index.js', { read: false })\n .pipe(browserify({\n insertGlobals: true\n }))\n .pipe(rename('main.js'))\n .pipe(gulp.dest('./public/javascripts/'))\n });\n\n runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);\n})\n\nUpdated.\nOf course, it's not neccessary to compile typescript files separatly.\nrunSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback) works perfect.\n",
"In my case (using IntelliJ) File - Invalidate Caches / Restart... did the trick.\n",
"I got the similar error when I was importing express incorrectly.\nAll I had to do was replace\nconst router = require('express').Router();\n\nwith\nimport express from 'express';\nconst router = express.Router();\n\n",
"In my case I was using angular and I was trying to assign a variable in a method with colon instead of equal, like this:\nconst user$ : this.service.getUser();\nIt should've been:\nconst user$ = this.service.getUser();\n",
"another solution namespace\n\nIIFE function & closure\n\ndemo.ts\n// 1. namespace function\nnamespace a {\n const func = () => {\n //\n }\n}\n\n// 2. function\nconst test = () => {\n //\n}\n\ndemo.js\n\n\"use strict\";\n// 1. namespace function\nvar a;\n(function (a) {\n const func = () => {\n //\n };\n})(a || (a = {}));\n\n// 2. function\nconst test = () => {\n //\n};\n\n\nrefs\nhttps://www.typescriptlang.org/docs/handbook/namespaces.html\nhttps://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html\n",
"In my case refactor to use namespace solved most issues\n\n",
"So... I did something, and it seemed to solve the problem, but I'm not really sure of unseen consequences, but it seems really simple.\nI just put { at the start of the file and } at the end, therefore making a new block in the file...\nfile1.ts\n{\n let co=require('co');\n //...\n module.exports=...\n}\n\nfile2.ts\nlet co=require('co');\nlet f1=require('./file1');\n//...\nmodule.exports=...\n\n"
] |
[
94,
93,
44,
14,
14,
12,
6,
5,
3,
2,
1,
1,
1,
0,
0,
0,
0
] |
[
"just add the below line in TSconfig file\n\"compilerOptions\": {\n\"skipLibCheck\": true\n}\n",
"The simplest solution is to change the:\n\"target\": \"es5\" to \"target\": \"es6\" at tsconfig.json file.\nIf you cannot access this file just run:\ntsc --init in the main directory.\nBecause initially the typescript will be sat to JavaScript es5 and that cannot understand the latest JavaScript syntax.\n",
"It happens when variable co is already defined in the scope (maybe window/global object has it) and you are again declaring the variable with the same name.\nif you replace let with var then it will not give an error but since you are using let then it is not allowed to re-declare the same variable using let\nrename the variable to something else and the error will be gone.\n",
"working on today's date: 12/22\nexample:\n button const =() {}\n export default button;\n\n export const button2(){}\n \n\n--------------Import------------\nimport button, {ButtonIcon} from '../Button';\n\n"
] |
[
-1,
-1,
-1,
-1
] |
[
"require",
"typescript"
] |
stackoverflow_0035758584_require_typescript.txt
|
Q:
Python Regex: capture all optional groups, regardless of order
For a string "I have a dog, a fish, and a cat", I would like to capture the groups in the order "dog", "fish", and "cat".
I have a Python regex that works the way I want, making the groups optional in case the string doesn't contain the groups. So "I have a dog and a cat" would still give me groups of "dog" and "cat".
^(?:.*(dog))?(?:.*(fish))?(?:.*(cat))?.*$
However I would like to capture the groups regardless of the orders of the groups in the regex. If the string is "I have a fish, a dog, and a cat", I only get the groups "dog" and "cat" when I would still like "dog", "fish", and "cat"
I originally used lookaheads with capture groups to ignore the order, but that only works if all of the groups are in the string. I've tried combining lookaheads with non-capture groups but can't seem to make it work.
Any help would be appreciated!
Here's a link to my regex: https://regex101.com/r/lhT55K/2
A:
Try this code:
import re
# The regular expression with named capture groups
regex = r"(?P<dog>dog)?(?P<fish>fish)?(?P<cat>cat)?"
# The string to match against
string = "I have a dog, a fish, and a cat"
# Use a lambda function to extract the groups in the order that you want
match = re.match(regex, string, flags=re.IGNORECASE)
groups = [match.groupdict()[g] for g in ["dog", "fish", "cat"]]
# Print the groups
print(groups)
This code should print the groups in the order ["dog", "fish", "cat"], regardless of the order in which they appear in the string.
|
Python Regex: capture all optional groups, regardless of order
|
For a string "I have a dog, a fish, and a cat", I would like to capture the groups in the order "dog", "fish", and "cat".
I have a Python regex that works the way I want, making the groups optional in case the string doesn't contain the groups. So "I have a dog and a cat" would still give me groups of "dog" and "cat".
^(?:.*(dog))?(?:.*(fish))?(?:.*(cat))?.*$
However I would like to capture the groups regardless of the orders of the groups in the regex. If the string is "I have a fish, a dog, and a cat", I only get the groups "dog" and "cat" when I would still like "dog", "fish", and "cat"
I originally used lookaheads with capture groups to ignore the order, but that only works if all of the groups are in the string. I've tried combining lookaheads with non-capture groups but can't seem to make it work.
Any help would be appreciated!
Here's a link to my regex: https://regex101.com/r/lhT55K/2
|
[
"Try this code:\nimport re\n\n# The regular expression with named capture groups\nregex = r\"(?P<dog>dog)?(?P<fish>fish)?(?P<cat>cat)?\"\n\n# The string to match against\nstring = \"I have a dog, a fish, and a cat\"\n\n# Use a lambda function to extract the groups in the order that you want\nmatch = re.match(regex, string, flags=re.IGNORECASE)\ngroups = [match.groupdict()[g] for g in [\"dog\", \"fish\", \"cat\"]]\n\n# Print the groups\nprint(groups)\n\nThis code should print the groups in the order [\"dog\", \"fish\", \"cat\"], regardless of the order in which they appear in the string.\n"
] |
[
0
] |
[] |
[] |
[
"regex",
"regex_group"
] |
stackoverflow_0074662373_regex_regex_group.txt
|
Q:
How to add a dataframe placeholder when naming a variable in a ggpacket function?
Using ggpacket() to create a function and I'd like to name a specific variable edtriage that will be in the dataframe that gets named when using the function (different dataframes supplied each time).
I tried both date_breaks() and breaks() with the same issue. When I supplied the same variable name in geom_text, it worked through aes().
geom_gradient <- ggpacket() +
geom_link2(aes(group = 1), size = 3, show.legend = FALSE) + # Gradient line
geom_point ( size = 5 ) +
# Below naming always worked
geom_text_repel(aes(label = if_else(edtriage == max(edtriage), sprintf("%1.1f%%", Percent), "" )) , size = 15 ) +
scale_x_date(date_labels="%b\n%y",
breaks = seq(from = min(.$edtriage), to = max(.$edtriage), by = 0.25), # Not working
# breaks = seq(from = min(edtriage), to = max(edtriage), by = 0.25), # Not working either
date_minor_breaks = "1 month" ) +
theme_minimal()
A:
You can't add a placeholder directly inside a scale function. I'm not convinced you actually need to here, since you can pass a function to breaks, but one way to achieve what you want is to put a small wrapper round your code that takes a data argument:
library(ggpackets)
geom_gradient <- function(data) {
ggpacket() +
ggforce::geom_link2(aes(group = 1), linewidth = 3, show.legend = FALSE) +
geom_point(size = 5) +
ggrepel::geom_text_repel(
aes(label = dplyr::if_else(edtriage == max(edtriage),
sprintf("%1.1f%%", Percent), "")),
size = 15) +
scale_x_date(date_labels = "%b\n%y",
breaks = seq(min(data$edtriage), max(data$edtriage), 31)) +
theme_minimal()
}
This allows:
ggplot(df, aes(edtriage, Percent)) +
geom_gradient(df)
Data used
set.seed(1)
df <- data.frame(edtriage = seq(as.Date("2021-01-01"), by = "month", len = 24),
Percent = runif(24, 60, 100))
|
How to add a dataframe placeholder when naming a variable in a ggpacket function?
|
Using ggpacket() to create a function and I'd like to name a specific variable edtriage that will be in the dataframe that gets named when using the function (different dataframes supplied each time).
I tried both date_breaks() and breaks() with the same issue. When I supplied the same variable name in geom_text, it worked through aes().
geom_gradient <- ggpacket() +
geom_link2(aes(group = 1), size = 3, show.legend = FALSE) + # Gradient line
geom_point ( size = 5 ) +
# Below naming always worked
geom_text_repel(aes(label = if_else(edtriage == max(edtriage), sprintf("%1.1f%%", Percent), "" )) , size = 15 ) +
scale_x_date(date_labels="%b\n%y",
breaks = seq(from = min(.$edtriage), to = max(.$edtriage), by = 0.25), # Not working
# breaks = seq(from = min(edtriage), to = max(edtriage), by = 0.25), # Not working either
date_minor_breaks = "1 month" ) +
theme_minimal()
|
[
"You can't add a placeholder directly inside a scale function. I'm not convinced you actually need to here, since you can pass a function to breaks, but one way to achieve what you want is to put a small wrapper round your code that takes a data argument:\nlibrary(ggpackets)\n\ngeom_gradient <- function(data) {\n ggpacket() +\n ggforce::geom_link2(aes(group = 1), linewidth = 3, show.legend = FALSE) +\n geom_point(size = 5) + \n ggrepel::geom_text_repel(\n aes(label = dplyr::if_else(edtriage == max(edtriage), \n sprintf(\"%1.1f%%\", Percent), \"\")), \n size = 15) + \n scale_x_date(date_labels = \"%b\\n%y\",\n breaks = seq(min(data$edtriage), max(data$edtriage), 31)) + \n theme_minimal()\n}\n\nThis allows:\nggplot(df, aes(edtriage, Percent)) +\n geom_gradient(df)\n\n\n\nData used\nset.seed(1)\n\ndf <- data.frame(edtriage = seq(as.Date(\"2021-01-01\"), by = \"month\", len = 24),\n Percent = runif(24, 60, 100))\n\n"
] |
[
0
] |
[] |
[] |
[
"ggplot2",
"r"
] |
stackoverflow_0074661742_ggplot2_r.txt
|
Q:
How to store global variable in intellij plugin?
I'm trying to develop the plugin for JetBrains IDEA. I have some input fields, which I need to do some kind of plugin configuration. So, let's imagine that I have custom tool window.
class DemoToolWindow(toolWindow: ToolWindow?) {
private var panel: JPanel? = null
private var ratioInput: JTextField? = null
private var refreshButton: JButton? = null
init {
refreshButton?.addActionListener {
val ratioValue = ratioInput?.text
// this somehow saves value in storage
saveInGlobalStorage(ratioValue)
}
}
val content: JComponent?
get() = panel
}
Then I need to get saved value when action is performed by user.
/**
* Activation via shortcut
*/
class SuperCleanerAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
// read value that where saved after user input
val ratioValue = getFromGlobalStorage()
// ...working with ratioValue...
}
What is the best way to save such variables? Is it even possible?
A:
To store global variables in an IntelliJ plugin, you can use the Application class in the IntelliJ API. The Application class provides methods to access global application-level components, such as the ApplicationManager and ProjectManager, as well as the ability to register global listeners and access application-level settings.
To store a global variable in an IntelliJ plugin, you can do the following:
Create a new class to represent your global variable. This class should implement the ApplicationComponent interface from the IntelliJ API.
In your class, define a public static field to hold the value of your global variable.
In the initComponent method of your class, use the ApplicationManager.getApplication() method to get the current Application instance, and register your class as an ApplicationComponent using the registerComponent method.
To access or modify the value of your global variable, you can use the getInstance method of your class to get the instance of your ApplicationComponent, and then access the static field that holds the value of your global variable.
Here is an example of a class that stores a global variable called globalValue:
public class MyGlobalVariable implements ApplicationComponent {
public static int globalValue = 0;
public void initComponent() {
ApplicationManager.getApplication().registerComponent(this);
}
public static MyGlobalVariable getInstance() {
return ApplicationManager.getApplication().getComponent(MyGlobalVariable.class);
}
}
You can then access the value of the globalValue variable in other parts of your plugin by calling MyGlobalVariable.getInstance().globalValue.
|
How to store global variable in intellij plugin?
|
I'm trying to develop the plugin for JetBrains IDEA. I have some input fields, which I need to do some kind of plugin configuration. So, let's imagine that I have custom tool window.
class DemoToolWindow(toolWindow: ToolWindow?) {
private var panel: JPanel? = null
private var ratioInput: JTextField? = null
private var refreshButton: JButton? = null
init {
refreshButton?.addActionListener {
val ratioValue = ratioInput?.text
// this somehow saves value in storage
saveInGlobalStorage(ratioValue)
}
}
val content: JComponent?
get() = panel
}
Then I need to get saved value when action is performed by user.
/**
* Activation via shortcut
*/
class SuperCleanerAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
// read value that where saved after user input
val ratioValue = getFromGlobalStorage()
// ...working with ratioValue...
}
What is the best way to save such variables? Is it even possible?
|
[
"To store global variables in an IntelliJ plugin, you can use the Application class in the IntelliJ API. The Application class provides methods to access global application-level components, such as the ApplicationManager and ProjectManager, as well as the ability to register global listeners and access application-level settings.\nTo store a global variable in an IntelliJ plugin, you can do the following:\nCreate a new class to represent your global variable. This class should implement the ApplicationComponent interface from the IntelliJ API.\nIn your class, define a public static field to hold the value of your global variable.\nIn the initComponent method of your class, use the ApplicationManager.getApplication() method to get the current Application instance, and register your class as an ApplicationComponent using the registerComponent method.\nTo access or modify the value of your global variable, you can use the getInstance method of your class to get the instance of your ApplicationComponent, and then access the static field that holds the value of your global variable.\nHere is an example of a class that stores a global variable called globalValue:\npublic class MyGlobalVariable implements ApplicationComponent {\n public static int globalValue = 0;\n\n public void initComponent() {\n ApplicationManager.getApplication().registerComponent(this);\n }\n\n public static MyGlobalVariable getInstance() {\n return ApplicationManager.getApplication().getComponent(MyGlobalVariable.class);\n }\n}\n\nYou can then access the value of the globalValue variable in other parts of your plugin by calling MyGlobalVariable.getInstance().globalValue.\n"
] |
[
0
] |
[] |
[] |
[
"intellij_plugin",
"kotlin"
] |
stackoverflow_0074657288_intellij_plugin_kotlin.txt
|
Q:
Why is the Parallax scrolling not working? (Next.js Image + Tailwind)
What did I miss to make parallax scrolling working?
<div className="h-screen">
<div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat">
<Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'" objectFit="cover" alt="test" layout="fill" priority={true} />
</div>
</div>
A:
I think instead of Image component you should apply backGroundImage style to the div where you used bg-fixed class.
Parallax scrolling is a web design technique in which the website
background moves at a slower pace than the foreground.
If you visit tailwindcss:
Utilities for controlling how a background image behaves when
scrolling.
<div
className="relative h-full w-full bg-cover bg-center bg-fixed bg-no-repeat"
style={{
backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,
}}
></div>
I created a component to test it out:
const Test = () => {
return (
<div className="h-screen">
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div
className="relative h-full w-full bg-cover bg-center bg-fixed bg-no-repeat"
style={{
backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,
}}
></div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
<div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
Welcome to my site!
</div>
</div>
);
};
export default Test;
A:
To make parallax scrolling work, you need to add a parallax attribute to the div element containing the Image component, and set its value to the speed at which you want the parallax effect to occur. For example:
<div className="h-screen" parallax="0.5">
<div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat">
<Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'" objectFit="cover" alt="test" layout="fill" priority={true} />
</div>
</div>
The value of the parallax attribute can be any number between 0 and 1, with 0 representing no parallax effect and 1 representing the maximum parallax effect. The value you choose will depend on your personal preference and the specific design of your website. You may need to experiment with different values to find the one that looks best.
|
Why is the Parallax scrolling not working? (Next.js Image + Tailwind)
|
What did I miss to make parallax scrolling working?
<div className="h-screen">
<div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat">
<Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'" objectFit="cover" alt="test" layout="fill" priority={true} />
</div>
</div>
|
[
"I think instead of Image component you should apply backGroundImage style to the div where you used bg-fixed class.\n\nParallax scrolling is a web design technique in which the website\nbackground moves at a slower pace than the foreground.\n\nIf you visit tailwindcss:\n\nUtilities for controlling how a background image behaves when\nscrolling.\n\n <div\n className=\"relative h-full w-full bg-cover bg-center bg-fixed bg-no-repeat\"\n style={{\n backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,\n }}\n ></div>\n\nI created a component to test it out:\nconst Test = () => {\n return (\n <div className=\"h-screen\">\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div\n className=\"relative h-full w-full bg-cover bg-center bg-fixed bg-no-repeat\"\n style={{\n backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,\n }}\n ></div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n <div className=\"p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl\">\n Welcome to my site!\n </div>\n </div>\n );\n};\n\nexport default Test;\n\n",
"To make parallax scrolling work, you need to add a parallax attribute to the div element containing the Image component, and set its value to the speed at which you want the parallax effect to occur. For example:\n<div className=\"h-screen\" parallax=\"0.5\">\n <div className=\"relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat\">\n <Image src=\"https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'\" objectFit=\"cover\" alt=\"test\" layout=\"fill\" priority={true} />\n </div>\n</div>\n\nThe value of the parallax attribute can be any number between 0 and 1, with 0 representing no parallax effect and 1 representing the maximum parallax effect. The value you choose will depend on your personal preference and the specific design of your website. You may need to experiment with different values to find the one that looks best.\n"
] |
[
1,
0
] |
[] |
[] |
[
"css",
"next.js",
"parallax",
"tailwind_css"
] |
stackoverflow_0074661787_css_next.js_parallax_tailwind_css.txt
|
Q:
Create a dynamic Union type with mapped property
I have the following types
enum Types {
Email = 'email',
Checkbox = 'checkbox',
}
type MappedValues = {
[Types.Email]: string;
[Types.Checkbox]: boolean;
};
type T1<T extends Types> = { type: T } & {
[key in T]: MappedValues[T];
};
type T2 = T1<Types.Email | Types.Checkbox>
With the above example T2 is:
{
type: 'email' | 'checkbox',
email: string,
checkbox: boolean
}
But I am looking for:
{
type: 'email',
email: string
} | {
type: 'checkbox',
checkbox: boolean
}
I went through the whole typescript documentation about typings and discover a lot of interesting things but nothing about my specific case.
Is it possible to do it or do I have to change my base types (Types, MappedValues) ?
A:
It is possible to create a type with all the possible values:
type T1<T extends Types> = {
[key in T]: {
type: key,
data: MappedValues[key]
}
}
type T2 = T1<Types.Email | Types.Checkbox>
Here T2 is:
{
email: {
type: 'email',
data: string
},
checkbox: {
type: 'checkbox',
data: boolean
}
}
Then you can use your generic to index this map to transform it into an union:
type T1<T extends Types> = {
[key in T as string]: {
type: key;
} & {
[property in key]: MappedValues[key];
};
}[T];
And T2 become:
({
type: Types.Email;
} & {
email: string;
}) | ({
type: Types.Checkbox;
} & {
checkbox: boolean;
})
|
Create a dynamic Union type with mapped property
|
I have the following types
enum Types {
Email = 'email',
Checkbox = 'checkbox',
}
type MappedValues = {
[Types.Email]: string;
[Types.Checkbox]: boolean;
};
type T1<T extends Types> = { type: T } & {
[key in T]: MappedValues[T];
};
type T2 = T1<Types.Email | Types.Checkbox>
With the above example T2 is:
{
type: 'email' | 'checkbox',
email: string,
checkbox: boolean
}
But I am looking for:
{
type: 'email',
email: string
} | {
type: 'checkbox',
checkbox: boolean
}
I went through the whole typescript documentation about typings and discover a lot of interesting things but nothing about my specific case.
Is it possible to do it or do I have to change my base types (Types, MappedValues) ?
|
[
"It is possible to create a type with all the possible values:\ntype T1<T extends Types> = {\n [key in T]: {\n type: key,\n data: MappedValues[key]\n }\n}\n\ntype T2 = T1<Types.Email | Types.Checkbox>\n\nHere T2 is:\n{\n email: {\n type: 'email',\n data: string\n },\n checkbox: {\n type: 'checkbox',\n data: boolean\n }\n}\n\nThen you can use your generic to index this map to transform it into an union:\ntype T1<T extends Types> = {\n [key in T as string]: {\n type: key;\n } & {\n [property in key]: MappedValues[key];\n };\n}[T];\n\nAnd T2 become:\n({\n type: Types.Email;\n} & {\n email: string;\n}) | ({\n type: Types.Checkbox;\n} & {\n checkbox: boolean;\n})\n\n"
] |
[
0
] |
[] |
[] |
[
"types",
"typescript"
] |
stackoverflow_0074662244_types_typescript.txt
|
Q:
How to trigger an event when a web notification is displayed in React.js
I want to update the UI when a new web push notification is received from OneSignal. I am using the npm package of OneSignal, I tried to create an event listener but I'm not sure what's wrong here. The App is able to get notifications and show them.
import OneSignal from "react-onesignal";
export async function runOneSignalOnLogin(data) {
await OneSignal.init({
appId: process.env.REACT_APP_ONE_SIGNAL_ID,
allowLocalhostAsSecureOrigin: true,
});
OneSignal.showSlidedownPrompt();
OneSignal.setExternalUserId(`${data?.user?.organization_id}`);
OneSignal.on("notificationDisplay", function (isSubscribed) {
console.log("The user's subscription state is now:", isSubscribed);
});
}
export function runOneSignalOnLogout() {
OneSignal.removeExternalUserId();
}
A:
The code you provided seems correct for adding an event listener for the notificationDisplay event in OneSignal. When the event is triggered, the callback function you provided will be executed, and the isSubscribed parameter will contain the subscription state of the user.
In the callback function, you can update the UI based on the value of isSubscribed and any other information included in the notification. For example, you could use the isSubscribed value to determine whether the user has subscribed to push notifications, and update the UI accordingly.
It's worth noting that the notificationDisplay event is triggered whenever a notification is displayed to the user, regardless of whether it's a web push notification or a native push notification. You can check the notification parameter in the callback function to determine the type of notification that was displayed.
If you are still having trouble with the event listener, it may be helpful to check the OneSignal documentation for more information on the notificationDisplay event and how to use it. You can also try logging the notification and isSubscribed parameters in the callback function to see what values they contain when the event is triggered.
|
How to trigger an event when a web notification is displayed in React.js
|
I want to update the UI when a new web push notification is received from OneSignal. I am using the npm package of OneSignal, I tried to create an event listener but I'm not sure what's wrong here. The App is able to get notifications and show them.
import OneSignal from "react-onesignal";
export async function runOneSignalOnLogin(data) {
await OneSignal.init({
appId: process.env.REACT_APP_ONE_SIGNAL_ID,
allowLocalhostAsSecureOrigin: true,
});
OneSignal.showSlidedownPrompt();
OneSignal.setExternalUserId(`${data?.user?.organization_id}`);
OneSignal.on("notificationDisplay", function (isSubscribed) {
console.log("The user's subscription state is now:", isSubscribed);
});
}
export function runOneSignalOnLogout() {
OneSignal.removeExternalUserId();
}
|
[
"The code you provided seems correct for adding an event listener for the notificationDisplay event in OneSignal. When the event is triggered, the callback function you provided will be executed, and the isSubscribed parameter will contain the subscription state of the user.\nIn the callback function, you can update the UI based on the value of isSubscribed and any other information included in the notification. For example, you could use the isSubscribed value to determine whether the user has subscribed to push notifications, and update the UI accordingly.\nIt's worth noting that the notificationDisplay event is triggered whenever a notification is displayed to the user, regardless of whether it's a web push notification or a native push notification. You can check the notification parameter in the callback function to determine the type of notification that was displayed.\nIf you are still having trouble with the event listener, it may be helpful to check the OneSignal documentation for more information on the notificationDisplay event and how to use it. You can also try logging the notification and isSubscribed parameters in the callback function to see what values they contain when the event is triggered.\n"
] |
[
0
] |
[] |
[] |
[
"onesignal",
"reactjs",
"web_push"
] |
stackoverflow_0074661752_onesignal_reactjs_web_push.txt
|
Q:
How to cover 100% Sonarqube code coverage on Java bean class with @Getter @Builder Lombok annotation
I am calling a third party REST endpoint.
Request sample
{
"body": {
"accountNumber": "12345"
},
"header": {
"username": "someusername",
"password": "somepassword"
}
}
I have created 3 bean classes
MyRequest.java
@Builder
@JsonDeserialize(builder = MyRequest.MyRequestBuilder.class)
public class MyRequest {
@JsonProperty("header")
private MyHeader header;
@JsonProperty("body")
private MyBody body;
}
MyBody.java
@Getter
@Builder
public class MyBody {
private String accountNumber;
}
MyHeader.java
@Getter
@Builder
public class MyHeader {
private String username;
private String password;
}
I'm creating request object using
MyBody body = MyBody.builder().accountNumber("12345").build();
MyHeader header = MyHeader.builder().username("someusername").password("somepassword").build();
MyRequest request = MyRequest.builder().body(body).header(header).build();
Everything is working as expected. The code coverage for MyRequest.java is 100% but my MyBody.java and MyHeader.java is not.
For all the fields I get the error message "Not covered by tests".
Normally I add @Getter and @Setter for Response objects. For request, I just add @Builder annotation.
In this case, if I remove @Getter from MyBody and MyHeader, the third party REST endpoint is getting null values.
It looks like @Getter is invoked when setting the objects to MyRequest.java. But for some reason it is not covered by my test cases.
How to make this work without @Getter or is there a way to cover all the fields (accountNumber, username and password) with @Getter annotation? Any help is appreciated.
A:
Create a lombok.config and add the following attribute to it.
lombok.addLombokGeneratedAnnotation = true
For Maven projects, a file named lombok.config at project’s basedir is the right spot, but other ways/locations may apply, see https://projectlombok.org/features/configuration
A:
You need to instruct Jackson somehow which data should be included during serialization. The default mechanism is to use getters for that purpose.
Replace @Getter with @JsonProperty to get 100% code coverage.
@Builder
public class MyBody {
@JsonProperty
private String accountNumber;
}
This is not my answer. I got this answer from my other post
Why 3rd party REST API's gets null values for request fields when removing @Getter Lombok annotation
Thanks @Alexander Ivanchenko
|
How to cover 100% Sonarqube code coverage on Java bean class with @Getter @Builder Lombok annotation
|
I am calling a third party REST endpoint.
Request sample
{
"body": {
"accountNumber": "12345"
},
"header": {
"username": "someusername",
"password": "somepassword"
}
}
I have created 3 bean classes
MyRequest.java
@Builder
@JsonDeserialize(builder = MyRequest.MyRequestBuilder.class)
public class MyRequest {
@JsonProperty("header")
private MyHeader header;
@JsonProperty("body")
private MyBody body;
}
MyBody.java
@Getter
@Builder
public class MyBody {
private String accountNumber;
}
MyHeader.java
@Getter
@Builder
public class MyHeader {
private String username;
private String password;
}
I'm creating request object using
MyBody body = MyBody.builder().accountNumber("12345").build();
MyHeader header = MyHeader.builder().username("someusername").password("somepassword").build();
MyRequest request = MyRequest.builder().body(body).header(header).build();
Everything is working as expected. The code coverage for MyRequest.java is 100% but my MyBody.java and MyHeader.java is not.
For all the fields I get the error message "Not covered by tests".
Normally I add @Getter and @Setter for Response objects. For request, I just add @Builder annotation.
In this case, if I remove @Getter from MyBody and MyHeader, the third party REST endpoint is getting null values.
It looks like @Getter is invoked when setting the objects to MyRequest.java. But for some reason it is not covered by my test cases.
How to make this work without @Getter or is there a way to cover all the fields (accountNumber, username and password) with @Getter annotation? Any help is appreciated.
|
[
"Create a lombok.config and add the following attribute to it.\nlombok.addLombokGeneratedAnnotation = true\n\nFor Maven projects, a file named lombok.config at project’s basedir is the right spot, but other ways/locations may apply, see https://projectlombok.org/features/configuration\n",
"You need to instruct Jackson somehow which data should be included during serialization. The default mechanism is to use getters for that purpose.\nReplace @Getter with @JsonProperty to get 100% code coverage.\n@Builder\npublic class MyBody {\n @JsonProperty\n private String accountNumber;\n}\n\nThis is not my answer. I got this answer from my other post\nWhy 3rd party REST API's gets null values for request fields when removing @Getter Lombok annotation\nThanks @Alexander Ivanchenko\n"
] |
[
0,
0
] |
[] |
[] |
[
"java",
"junit",
"lombok",
"sonarqube",
"spring_boot"
] |
stackoverflow_0074592390_java_junit_lombok_sonarqube_spring_boot.txt
|
Q:
Opening and Reading files in Python
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
A:
This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:
If, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.
In short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.
Hope this helps!
image with terminal open on desktop and in text editor to show working directory difference
A:
I used full path of the file along with r, which is for raw string. Worked for me.
example:
filename = **r**'C:\Python\CrashCourse\pi_digits.txt'
with open(filename) as file_object:
content = file_object.read()
print(content)
A:
The path to the file is relative to where you run the python file from, not from where the python file is located.
Either run your code from the same directory as the files, or make the file path absolute, based on the python file's location.
import os
with open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:
contents = file_object.read()
print(contents)
Hope that helps
A:
You can try getting the full path to the file
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
pi_digits = os.path.join(dir_path, 'pi_digits.txt')
with open(pi_digits, r) as file_object:
print(file_object.read())
A:
Try this:
with open('c:\\Workspace\\Crash Course\\Lessons\\Ch 10\\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
|
Opening and Reading files in Python
|
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
|
[
"This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:\nIf, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.\nIn short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.\nHope this helps!\nimage with terminal open on desktop and in text editor to show working directory difference\n",
"I used full path of the file along with r, which is for raw string. Worked for me.\nexample:\nfilename = **r**'C:\\Python\\CrashCourse\\pi_digits.txt'\n\nwith open(filename) as file_object:\n content = file_object.read()\n print(content)\n\n",
"The path to the file is relative to where you run the python file from, not from where the python file is located. \nEither run your code from the same directory as the files, or make the file path absolute, based on the python file's location.\nimport os\n\nwith open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:\n contents = file_object.read()\n print(contents)\n\nHope that helps\n",
"You can try getting the full path to the file\nimport os\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\npi_digits = os.path.join(dir_path, 'pi_digits.txt')\n\nwith open(pi_digits, r) as file_object:\n print(file_object.read())\n\n",
"Try this:\nwith open('c:\\\\Workspace\\\\Crash Course\\\\Lessons\\\\Ch 10\\\\pi_digits.txt') as file_object:\n contents = file_object.read()\n print(contents)\n\n"
] |
[
2,
2,
0,
0,
0
] |
[
"You might have to enable \"Execute in file dir\"\nvscode setting\n",
"The comment that Travis1797 posted is much better for VS code users that are just starting out with learning python.\nClick on the cog icon in the bottom left hand of corner of vscode\nThen click settings.\nThen type: execute in file dir\n(WARNING: this is only useful when calling upon files saved in the same directory as your python file using the method explained in the python crash course)\nTHE HIGHER VOTED POSTS WORK WITHOUT THE NEED TO CHANGE SETTINGS WITHIN VSCODE.\nClick the checkbox next to the wording thats states \"When executing a file...\" and run your code again and it works.\nPs(I spent over an hour trying to figure out what I was doing wrong and also solving it with the comments above but this was the most python elegant solution )\n"
] |
[
-1,
-1
] |
[
"python"
] |
stackoverflow_0055695410_python.txt
|
Q:
How to navigate programmatically is checkbox true
It is necessary for me at a choice chekboksom that the Page2 component was drawn. I created a useState where I keep track of the value of the checkbox, but I don't know how to navigate programmatically when the checkbox is selected. How can I do this?
export default function Home() {
const [checked, setChecked] = useState(false);
const navigate = useNavigate();
const handleChange = () => {
setChecked(!checked);
};
return (
<>
<input type="checkbox" onChange={handleChange}></input>
</>
);
}
A:
const handleChange = () => {
setChecked(!checked);
if (!checked) {
navigate('/')
}
};
A:
You don't need any state for this, just use the onChange event object. React state updates are asynchronously processed, so trying to enqueue a state update in the handler and navigate based on the updated state won't work.
export default function Home() {
const navigate = useNavigate();
const handleChange = (e) => {
const { checked } = e.target;
if (checked) {
navigate("targetPath");
}
};
return (
<>
<input type="checkbox" onChange={handleChange}></input>
</>
);
}
|
How to navigate programmatically is checkbox true
|
It is necessary for me at a choice chekboksom that the Page2 component was drawn. I created a useState where I keep track of the value of the checkbox, but I don't know how to navigate programmatically when the checkbox is selected. How can I do this?
export default function Home() {
const [checked, setChecked] = useState(false);
const navigate = useNavigate();
const handleChange = () => {
setChecked(!checked);
};
return (
<>
<input type="checkbox" onChange={handleChange}></input>
</>
);
}
|
[
"const handleChange = () => {\n setChecked(!checked);\n if (!checked) {\n navigate('/')\n }\n};\n\n",
"You don't need any state for this, just use the onChange event object. React state updates are asynchronously processed, so trying to enqueue a state update in the handler and navigate based on the updated state won't work.\nexport default function Home() {\n const navigate = useNavigate();\n\n const handleChange = (e) => {\n const { checked } = e.target;\n if (checked) {\n navigate(\"targetPath\");\n }\n };\n\n return (\n <>\n <input type=\"checkbox\" onChange={handleChange}></input>\n </>\n );\n}\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"javascript",
"react_router",
"reactjs"
] |
stackoverflow_0074662228_javascript_react_router_reactjs.txt
|
Q:
Geom to add a moving average to ggplot
I'm looking for the geom_ function to add a moving average line onto a plot generated by ggplot from dplyr package.
Can anyone help me?
I can find this function by using google or any browser, and I need for a project
|
Geom to add a moving average to ggplot
|
I'm looking for the geom_ function to add a moving average line onto a plot generated by ggplot from dplyr package.
Can anyone help me?
I can find this function by using google or any browser, and I need for a project
|
[] |
[] |
[
"the geom_smooth() function can be used to add a moving average line to a plot..\nggplot(df, aes(x, y)) +\n geom_point() +\n geom_smooth(method = \"ma\")\n\n"
] |
[
-1
] |
[
"ggplot2",
"r"
] |
stackoverflow_0074661821_ggplot2_r.txt
|
Q:
JavaScript how to get element by xpath from HTML text
I am trying to get elements from the different pages by XPath.
So I managed to get HTML as text and used DOMParser.parseFromString() to make it HTMLDocument
then I tried to use document.evaluate() but it doesn't return any elements.
Here is the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xhttp.responseText, "text/html");
const headings = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
console.log(headings)
let Heading = headings.iterateNext();
console.log(Heading)
let items = []
while (Heading) {
items.push(Heading.textContent);
Heading = headings.iterateNext();
console.log(items)
}
}
};
xhttp.open("GET", "url within the same domain", true);
xhttp.send();
and that's the output from console.log (headings):
XPathResult { resultType: 4, invalidIteratorState: false }
invalidIteratorState: false
resultType: 4*
And the eading is null
example that i run in console on 'https://www.aliexpress.com'
expected result is: '1. Contact Seller'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
parser = new DOMParser();
xmlDoc = parser.parseFromString(xhttp.responseText, "text/html");
const headings = xmlDoc.evaluate('/html/body/div[3]/div[3]/section/span[1]', xmlDoc, null, XPathResult.ANY_TYPE, null);
console.log(headings)
let Heading = headings.iterateNext();
console.log(Heading)
let items = []
while (Heading) {
items.push(Heading.textContent);
Heading = headings.iterateNext();
console.log(items)
}
}
};
xhttp.open("GET", "https://www.aliexpress.com/p/buyerprotection/index.html", true);
xhttp.send();
I could probably make some function that changes the XPath expression to a regular expression and find the element in the HTML string but I think there is a better way
A:
That page you are using XPath against is probably built dynamically by loading/filling parts with JavaScript so while your XPath /html/body/div[3] finds a div elements with children when used inside the browser console on a window that has the page loaded the attempt against the raw/pure HTML result loaded with a HTTP GET request finds an empty div element. That way the selection deeper down the tree with e.g. /html/body/div[3]/div[3]/section/span[1] finds no elements at all.
Thus if you expect to use XPath against some fully loaded/Javascript enhanced HTML document you might need Puppeteer https://pptr.dev/ or similar.
|
JavaScript how to get element by xpath from HTML text
|
I am trying to get elements from the different pages by XPath.
So I managed to get HTML as text and used DOMParser.parseFromString() to make it HTMLDocument
then I tried to use document.evaluate() but it doesn't return any elements.
Here is the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xhttp.responseText, "text/html");
const headings = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
console.log(headings)
let Heading = headings.iterateNext();
console.log(Heading)
let items = []
while (Heading) {
items.push(Heading.textContent);
Heading = headings.iterateNext();
console.log(items)
}
}
};
xhttp.open("GET", "url within the same domain", true);
xhttp.send();
and that's the output from console.log (headings):
XPathResult { resultType: 4, invalidIteratorState: false }
invalidIteratorState: false
resultType: 4*
And the eading is null
example that i run in console on 'https://www.aliexpress.com'
expected result is: '1. Contact Seller'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
parser = new DOMParser();
xmlDoc = parser.parseFromString(xhttp.responseText, "text/html");
const headings = xmlDoc.evaluate('/html/body/div[3]/div[3]/section/span[1]', xmlDoc, null, XPathResult.ANY_TYPE, null);
console.log(headings)
let Heading = headings.iterateNext();
console.log(Heading)
let items = []
while (Heading) {
items.push(Heading.textContent);
Heading = headings.iterateNext();
console.log(items)
}
}
};
xhttp.open("GET", "https://www.aliexpress.com/p/buyerprotection/index.html", true);
xhttp.send();
I could probably make some function that changes the XPath expression to a regular expression and find the element in the HTML string but I think there is a better way
|
[
"That page you are using XPath against is probably built dynamically by loading/filling parts with JavaScript so while your XPath /html/body/div[3] finds a div elements with children when used inside the browser console on a window that has the page loaded the attempt against the raw/pure HTML result loaded with a HTTP GET request finds an empty div element. That way the selection deeper down the tree with e.g. /html/body/div[3]/div[3]/section/span[1] finds no elements at all.\nThus if you expect to use XPath against some fully loaded/Javascript enhanced HTML document you might need Puppeteer https://pptr.dev/ or similar.\n"
] |
[
1
] |
[] |
[] |
[
"html",
"javascript",
"xpath"
] |
stackoverflow_0074661644_html_javascript_xpath.txt
|
Q:
Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element:
I'm trying to make a script in python that fills out the form on this website: (https://freesim.vodafone.co.uk/check-out-payasyougo-campaign) multiple times.
However, I get this error when running the program : Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import random
web = webdriver.Chrome()
web.get('https://freesim.vodafone.co.uk/check-out-payasyougo-campaign')
time.sleep(10)
random_words = ["Adriel", "Anabelle", "Abagail", "Milo", "Raven", "Halle", "Max", "Collin", ['Dane', 'Jaylynn', 'Micah']
FirstName = "Max"
first = web.find_element("xpath", '//*[@id="txtFirstName"]/div[5]/div[5]/div/div/div[1]/div[1]/div/input')
first.send_keys(FirstName)
LastName = "Lombardo"
last = web.find_element("xpath", '//*[@id="txtLastName"]/div[5]/div[5]/div/div/div[1]/div[2]/div/input')
last.send_keys(LastName)
Email = random.choice(random_words) + "@westlondonmail.xyz"
emailpath = web.find_element("xpath", '/html/body/form/div[5]/div[5]/div/div/div[1]/div[3]/div/input')
emailpath.send_keys(Email)
i tried putting in the XPATH, the full XPATH and none work
Any ideas ?
Thank you
A:
It looks like you're using the webdriver.Chrome() syntax to create a new instance of the Chrome web driver, but this is incorrect. Instead, you need to use the webdriver.Chrome(ChromeDriverManager().install()) syntax to create a new instance of the Chrome web driver and automatically download and install the appropriate version of the Chrome driver.
Try this code:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import random
web = webdriver.Chrome(ChromeDriverManager().install())
web.get('https://freesim.vodafone.co.uk/check-out-payasyougo-campaign')
time.sleep(10)
random_words = ["Adriel", "Anabelle", "Abagail", "Milo", "Raven", "Halle", "Max", "Collin", "Dane", "Jaylynn", "Micah"]
FirstName = "Max"
first = web.find_element("xpath", '//*[@id="txtFirstName"]/div[5]/div[5]/div/div/div[1]/div[1]/div/input')
first.send_keys(FirstName)
LastName = "Lombardo"
last = web.find_element("xpath", '//*[@id="txtLastName"]/div[5]/div[5]/div/div/div[1]/div[2]/div/input')
last.send_keys(LastName)
Email = random.choice(random_words) + "@westlondonmail.xyz"
emailpath = web.find_element("xpath", '/html/body/form/div[5]/div[5]/div/div/div[1]/div[3]/div/input')
emailpath.send_keys(Email)
|
Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element:
|
I'm trying to make a script in python that fills out the form on this website: (https://freesim.vodafone.co.uk/check-out-payasyougo-campaign) multiple times.
However, I get this error when running the program : Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import random
web = webdriver.Chrome()
web.get('https://freesim.vodafone.co.uk/check-out-payasyougo-campaign')
time.sleep(10)
random_words = ["Adriel", "Anabelle", "Abagail", "Milo", "Raven", "Halle", "Max", "Collin", ['Dane', 'Jaylynn', 'Micah']
FirstName = "Max"
first = web.find_element("xpath", '//*[@id="txtFirstName"]/div[5]/div[5]/div/div/div[1]/div[1]/div/input')
first.send_keys(FirstName)
LastName = "Lombardo"
last = web.find_element("xpath", '//*[@id="txtLastName"]/div[5]/div[5]/div/div/div[1]/div[2]/div/input')
last.send_keys(LastName)
Email = random.choice(random_words) + "@westlondonmail.xyz"
emailpath = web.find_element("xpath", '/html/body/form/div[5]/div[5]/div/div/div[1]/div[3]/div/input')
emailpath.send_keys(Email)
i tried putting in the XPATH, the full XPATH and none work
Any ideas ?
Thank you
|
[
"It looks like you're using the webdriver.Chrome() syntax to create a new instance of the Chrome web driver, but this is incorrect. Instead, you need to use the webdriver.Chrome(ChromeDriverManager().install()) syntax to create a new instance of the Chrome web driver and automatically download and install the appropriate version of the Chrome driver.\nTry this code:\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nimport random \n\nweb = webdriver.Chrome(ChromeDriverManager().install())\nweb.get('https://freesim.vodafone.co.uk/check-out-payasyougo-campaign')\n\ntime.sleep(10)\n\nrandom_words = [\"Adriel\", \"Anabelle\", \"Abagail\", \"Milo\", \"Raven\", \"Halle\", \"Max\", \"Collin\", \"Dane\", \"Jaylynn\", \"Micah\"]\n\nFirstName = \"Max\"\nfirst = web.find_element(\"xpath\", '//*[@id=\"txtFirstName\"]/div[5]/div[5]/div/div/div[1]/div[1]/div/input')\nfirst.send_keys(FirstName)\n\nLastName = \"Lombardo\"\nlast = web.find_element(\"xpath\", '//*[@id=\"txtLastName\"]/div[5]/div[5]/div/div/div[1]/div[2]/div/input')\nlast.send_keys(LastName)\n\nEmail = random.choice(random_words) + \"@westlondonmail.xyz\"\nemailpath = web.find_element(\"xpath\", '/html/body/form/div[5]/div[5]/div/div/div[1]/div[3]/div/input')\nemailpath.send_keys(Email)\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074662400_python.txt
|
Q:
Error: Could not find or load main class Game.GUI.Start Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
I'm new to maven and am having issues. I have a JavaFx app but I keep getting the error in the title. I have tried many different versions of the POM but can't get it to work. Here is the POM:
`
<?xml version="1.0" encoding="UTF-8"?>
<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>groupId</groupId>
<artifactId>Coursework2013</artifactId>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<javafx.version>19</javafx.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>Snake.GUI.Start</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>javazoom</groupId>
<artifactId>jlayer</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
</project>
and the start of Start (as I'm guessing thats related):
package Snake.GUI;
import Snake.GUI.controller.DataHandler;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class Start extends Application {
`
I tried many different ways of telling it where main was and all that, but it didn't help. I've looked at many similar issues but their questions on stack but their solutions have not worked for me. Thanks for your time.
A:
Do not blindly follow any obscure recomendations. Start with the official documentation that you can find here: https://openjfx.io/openjfx-docs/#maven
You do not have to copy any dependencies into some build folder.
|
Error: Could not find or load main class Game.GUI.Start Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
|
I'm new to maven and am having issues. I have a JavaFx app but I keep getting the error in the title. I have tried many different versions of the POM but can't get it to work. Here is the POM:
`
<?xml version="1.0" encoding="UTF-8"?>
<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>groupId</groupId>
<artifactId>Coursework2013</artifactId>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<javafx.version>19</javafx.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>Snake.GUI.Start</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>javazoom</groupId>
<artifactId>jlayer</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
</project>
and the start of Start (as I'm guessing thats related):
package Snake.GUI;
import Snake.GUI.controller.DataHandler;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class Start extends Application {
`
I tried many different ways of telling it where main was and all that, but it didn't help. I've looked at many similar issues but their questions on stack but their solutions have not worked for me. Thanks for your time.
|
[
"Do not blindly follow any obscure recomendations. Start with the official documentation that you can find here: https://openjfx.io/openjfx-docs/#maven\nYou do not have to copy any dependencies into some build folder.\n"
] |
[
1
] |
[] |
[] |
[
"build",
"java",
"javafx",
"maven",
"pom.xml"
] |
stackoverflow_0074662013_build_java_javafx_maven_pom.xml.txt
|
Q:
Nexts.js 13 + Supabase > What's the proper way to create a user context
I'm building an app with Next.js 13 and Supabase for the backend, and I've been stuck on figuring out the best/proper way to go about creating a context/provider for the current logged in user.
The flow to retrieve the user from Supabase is this:
Sign in with an OAuth Provider.
Grab the user ID from the session from the supabase onAuthState Changed hook.
Fetch the full user object from the supabase DB with the user ID mentioned above.
I have a supabase listener in my layout that listens for the auth state changes, and works well for setting and refreshing current session.
My initial approach was to add the fetchUser call from within the onAuthState changed hook, however I was running into late update hydration errors.
Taken directly from the examples, this is how the app looks:
// layout.tsx
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const supabase = createServerComponentSupabaseClient<Database>({
headers,
cookies,
});
const {
data: { session },
} = await supabase.auth.getSession();
return (
<html>
<head />
<body>
<NavMenu session={session} />
<SupabaseListener accessToken={session?.access_token} />
{children}
</body>
</html>
);
}
// supabase-listener.tsx
// taken directly from the supabase-auth-helpers library.
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import supabase from "../lib/supabase/supabase-browser";
export default function SupabaseListener({
accessToken,
}: {
accessToken?: string;
}) {
const router = useRouter();
useEffect(() => {
supabase.auth.onAuthStateChange(async (event, session) => {
if (session?.access_token !== accessToken) {
router.refresh();
}
});
}, [accessToken, router]);
return null;
}
I basically just need to wrap my root layout with a LoggedInUserProvider, make the fetch user call somewhere in the initial page load, and set the state of the current logged in user provider.
The other approaches I tried was making the fetch user call from the root layout, and having a LoggedInUserListener client component that takes the user as a property and simply sets the state if the profile exists. This was causing improper set state errors.
Thank you so much.
A:
It sounds like you're trying to avoid late-update hydration errors in Next.js by fetching the user data after the initial render. One way to do this is to use the getInitialProps lifecycle method in your layout component. This method allows you to asynchronously fetch data that you need to render the page, and then pass that data as props to the layout component.
Here's an example of how you might implement this:
// layout.tsx
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import supabase from "../lib/supabase/supabase-browser";
function Layout({ children, user }: { children: React.ReactNode; user: User }) {
const [currentUser, setCurrentUser] = useState(user);
const router = useRouter();
useEffect(() => {
supabase.auth.onAuthStateChange(async (event, session) => {
if (session?.access_token !== accessToken) {
router.refresh();
}
});
}, [accessToken, router]);
return (
<html>
<head />
<body>
<NavMenu session={session} />
<SupabaseListener accessToken={session?.access_token} />
{children}
</body>
</html>
);
}
Layout.getInitialProps = async ({ cookies, headers }) => {
const supabase = createServerComponentSupabaseClient<Database>({
headers,
cookies,
});
const {
data: { session },
} = await supabase.auth.getSession();
// Fetch the user object here
const user = await supabase.from("users").find(session.user_id);
return { user };
};
export default Layout;
In this example, the Layout component fetches the user data in getInitialProps and passes it as a prop to the component. The component then uses the useState hook to store the current user in local state, which you can use to set the user context for the rest of your app.
You can also use the getInitialProps method in your pages to fetch data and pass it to the page components as props.
I hope this helps!
|
Nexts.js 13 + Supabase > What's the proper way to create a user context
|
I'm building an app with Next.js 13 and Supabase for the backend, and I've been stuck on figuring out the best/proper way to go about creating a context/provider for the current logged in user.
The flow to retrieve the user from Supabase is this:
Sign in with an OAuth Provider.
Grab the user ID from the session from the supabase onAuthState Changed hook.
Fetch the full user object from the supabase DB with the user ID mentioned above.
I have a supabase listener in my layout that listens for the auth state changes, and works well for setting and refreshing current session.
My initial approach was to add the fetchUser call from within the onAuthState changed hook, however I was running into late update hydration errors.
Taken directly from the examples, this is how the app looks:
// layout.tsx
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const supabase = createServerComponentSupabaseClient<Database>({
headers,
cookies,
});
const {
data: { session },
} = await supabase.auth.getSession();
return (
<html>
<head />
<body>
<NavMenu session={session} />
<SupabaseListener accessToken={session?.access_token} />
{children}
</body>
</html>
);
}
// supabase-listener.tsx
// taken directly from the supabase-auth-helpers library.
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import supabase from "../lib/supabase/supabase-browser";
export default function SupabaseListener({
accessToken,
}: {
accessToken?: string;
}) {
const router = useRouter();
useEffect(() => {
supabase.auth.onAuthStateChange(async (event, session) => {
if (session?.access_token !== accessToken) {
router.refresh();
}
});
}, [accessToken, router]);
return null;
}
I basically just need to wrap my root layout with a LoggedInUserProvider, make the fetch user call somewhere in the initial page load, and set the state of the current logged in user provider.
The other approaches I tried was making the fetch user call from the root layout, and having a LoggedInUserListener client component that takes the user as a property and simply sets the state if the profile exists. This was causing improper set state errors.
Thank you so much.
|
[
"It sounds like you're trying to avoid late-update hydration errors in Next.js by fetching the user data after the initial render. One way to do this is to use the getInitialProps lifecycle method in your layout component. This method allows you to asynchronously fetch data that you need to render the page, and then pass that data as props to the layout component.\nHere's an example of how you might implement this:\n// layout.tsx\nimport React, { useState } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport supabase from \"../lib/supabase/supabase-browser\";\n\nfunction Layout({ children, user }: { children: React.ReactNode; user: User }) {\n const [currentUser, setCurrentUser] = useState(user);\n const router = useRouter();\n\n useEffect(() => {\n supabase.auth.onAuthStateChange(async (event, session) => {\n if (session?.access_token !== accessToken) {\n router.refresh();\n }\n });\n }, [accessToken, router]);\n\n return (\n <html>\n <head />\n <body>\n <NavMenu session={session} />\n <SupabaseListener accessToken={session?.access_token} />\n {children}\n </body>\n </html>\n );\n}\n\nLayout.getInitialProps = async ({ cookies, headers }) => {\n const supabase = createServerComponentSupabaseClient<Database>({\n headers,\n cookies,\n });\n const {\n data: { session },\n } = await supabase.auth.getSession();\n\n // Fetch the user object here\n const user = await supabase.from(\"users\").find(session.user_id);\n\n return { user };\n};\n\nexport default Layout;\n\nIn this example, the Layout component fetches the user data in getInitialProps and passes it as a prop to the component. The component then uses the useState hook to store the current user in local state, which you can use to set the user context for the rest of your app.\nYou can also use the getInitialProps method in your pages to fetch data and pass it to the page components as props.\nI hope this helps!\n"
] |
[
0
] |
[] |
[] |
[
"next.js",
"next.js13",
"react_context",
"reactjs",
"supabase"
] |
stackoverflow_0074661653_next.js_next.js13_react_context_reactjs_supabase.txt
|
Q:
Beginner C : Dynamic memory allocation
Switching to C from Java, and I'm having some troubles grasping memory management
Say I have a function *check_malloc that behaves as such:
// Checks if malloc() succeeds.
void *check_malloc(size_t amount){
void *tpt;
/* Allocates a memory block in amount bytes. */
tpt = malloc( amount );
/* Checks if it was successful. */
if ( tpt == NULL ){
fprintf(stderr, "No memory of %lu bytes\n", amount);
exit(1);
}
return tpt;
}
I also have the following variables to work with:
FILE *f = fopen("abc.txt", "r"); // Pointer to a file with "mynameisbob" on the first line and
// "123456789" on the second line
char *pname; // Pointer to a string for storing the name
}
My goal is to use *check_malloc to dynamically allocate memory so that the String pointed to by *pname is just the correct size for storing "mynamisbob", which is the only thing on the first line of the text file.
Here is my (failed) attempt:
int main(int argc, char *argv[]){
FILE *f = fopen("abc.txt", "r"); // A file with "mynameisbob" on the first line and
// "123456789" on the second line
char *pname; // Pointer to a string for storing the name
char currentline[150]; // Char array for storing current line of file
while(!feof(f)){
fgets(currentline,100,f);
pname = ¤tline;
}
But I know this probably isn't the way to go about this, because I need to use my nice check_malloc* function.
Additionally, in my actual text file there is a "<" symbol before the name on the first line.But I just want the *pname to point to a String saying "mynameisbob" without the "<" symbol. This isn't that important now, it just is reinforcement to me that I know I can't just set the pointer to point straight to currentline.
Can anyone help me fix my thinking on this one? Thanks a lot.
A:
In C you need to copy chars, not the "strings" (which are just pointers). Check out strcpy() and strlen(). Use strlen() to determine how long the line actually is which fgets has read, then use your malloc() to allocate exactly that (plus 1 for the 0). Then copy the chars over with strcpy().
A:
There are several problems in your code, see my comments in this example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Checks if malloc() succeeds.
void *check_malloc (size_t amount) {
void *tpt;
/* Allocates a memory block in amount bytes. */
tpt = malloc( amount );
/* Checks if it was successful. */
if (tpt == NULL) {
fprintf (stderr, "No memory of %lu bytes\n", amount);
exit (EXIT_FAILURE);
}
return tpt;
}
// To avoid subtle errors I have defined buffer size here
#define BUFFER_SIZE 150
// I have used the (void) version of main () here, while not strictly neccessary, you where not using argc and argv anyway, so the can be left out in this case
int main (void) {
// It might be a good idea to make the filename a char[] as well, but I leave that as an exercise to the reader.
FILE *f = fopen("abc.txt", "r"); // A file with "mynameisbob" on the first line and
// "123456789" on the second line
// You have to check whether the file was *actually openend*
if (f == NULL) {
fprintf (stderr, "Could not open file abc.txt\n"); // '"...%s\n", filename);' might better.
exit (EXIT_FAILURE);
}
char *pname; // Pointer to a string for storing the name
char currentline[BUFFER_SIZE]; // Char array for storing current line of file
while(!feof (f)) {
char *res = fgets (currentline, BUFFER_SIZE, f);
// fgets returns NULL when EOF was encountered before the next '\n'
if (res) {
size_t read = strlen (res);
// The line might have been empty
if (read) {
// Better use "sizeof *varname", while char is always 1 byte it is a good practice
pname = check_malloc ((read + 1) * sizeof *pname); // + 1 because we have to provide an extra char für '\0'
strncpy (pname, currentline, read); // You have to use strcpy or strncpy to copy the contents of the string rather than just assigning the pointer
// What was allocated must be freed again
free (pname);
}
}
}
fclose(f); // Always close everything you open!
return EXIT_SUCCESS;
}
Actually you really don't have to use pname in this simple case, because currentline already contains the line, but since you're trying to learn about memory management this should give you a general idea of how things work.
In your code you had this line:
pname = ¤tline;
There are two problems here:
As already mentioned in my code assigning currentline to pname only copies the pointer not the contents.
The correct assignment would be pname = currentline (without the address operator &), because currentline is also a pointer under the hood (it behaves like char *currentline even though it's statically allocated).
A:
In other to get the get the exact memory the string with pointer *pname you simply take the size of the string using using sizeof("variable name") of the string and there by managing the memory.
|
Beginner C : Dynamic memory allocation
|
Switching to C from Java, and I'm having some troubles grasping memory management
Say I have a function *check_malloc that behaves as such:
// Checks if malloc() succeeds.
void *check_malloc(size_t amount){
void *tpt;
/* Allocates a memory block in amount bytes. */
tpt = malloc( amount );
/* Checks if it was successful. */
if ( tpt == NULL ){
fprintf(stderr, "No memory of %lu bytes\n", amount);
exit(1);
}
return tpt;
}
I also have the following variables to work with:
FILE *f = fopen("abc.txt", "r"); // Pointer to a file with "mynameisbob" on the first line and
// "123456789" on the second line
char *pname; // Pointer to a string for storing the name
}
My goal is to use *check_malloc to dynamically allocate memory so that the String pointed to by *pname is just the correct size for storing "mynamisbob", which is the only thing on the first line of the text file.
Here is my (failed) attempt:
int main(int argc, char *argv[]){
FILE *f = fopen("abc.txt", "r"); // A file with "mynameisbob" on the first line and
// "123456789" on the second line
char *pname; // Pointer to a string for storing the name
char currentline[150]; // Char array for storing current line of file
while(!feof(f)){
fgets(currentline,100,f);
pname = ¤tline;
}
But I know this probably isn't the way to go about this, because I need to use my nice check_malloc* function.
Additionally, in my actual text file there is a "<" symbol before the name on the first line.But I just want the *pname to point to a String saying "mynameisbob" without the "<" symbol. This isn't that important now, it just is reinforcement to me that I know I can't just set the pointer to point straight to currentline.
Can anyone help me fix my thinking on this one? Thanks a lot.
|
[
"In C you need to copy chars, not the \"strings\" (which are just pointers). Check out strcpy() and strlen(). Use strlen() to determine how long the line actually is which fgets has read, then use your malloc() to allocate exactly that (plus 1 for the 0). Then copy the chars over with strcpy().\n",
"There are several problems in your code, see my comments in this example:\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n// Checks if malloc() succeeds.\nvoid *check_malloc (size_t amount) {\n\n void *tpt;\n\n /* Allocates a memory block in amount bytes. */\n tpt = malloc( amount );\n\n /* Checks if it was successful. */\n if (tpt == NULL) {\n fprintf (stderr, \"No memory of %lu bytes\\n\", amount);\n exit (EXIT_FAILURE);\n }\n\n return tpt;\n}\n\n// To avoid subtle errors I have defined buffer size here\n#define BUFFER_SIZE 150\n\n// I have used the (void) version of main () here, while not strictly neccessary, you where not using argc and argv anyway, so the can be left out in this case\nint main (void) {\n // It might be a good idea to make the filename a char[] as well, but I leave that as an exercise to the reader.\n FILE *f = fopen(\"abc.txt\", \"r\"); // A file with \"mynameisbob\" on the first line and\n // \"123456789\" on the second line\n // You have to check whether the file was *actually openend*\n if (f == NULL) {\n fprintf (stderr, \"Could not open file abc.txt\\n\"); // '\"...%s\\n\", filename);' might better.\n exit (EXIT_FAILURE);\n }\n\n char *pname; // Pointer to a string for storing the name\n\n char currentline[BUFFER_SIZE]; // Char array for storing current line of file\n\n while(!feof (f)) {\n char *res = fgets (currentline, BUFFER_SIZE, f);\n // fgets returns NULL when EOF was encountered before the next '\\n'\n if (res) {\n size_t read = strlen (res);\n // The line might have been empty\n if (read) {\n // Better use \"sizeof *varname\", while char is always 1 byte it is a good practice\n pname = check_malloc ((read + 1) * sizeof *pname); // + 1 because we have to provide an extra char für '\\0'\n strncpy (pname, currentline, read); // You have to use strcpy or strncpy to copy the contents of the string rather than just assigning the pointer\n // What was allocated must be freed again\n free (pname);\n }\n }\n }\n fclose(f); // Always close everything you open!\n return EXIT_SUCCESS;\n}\n\nActually you really don't have to use pname in this simple case, because currentline already contains the line, but since you're trying to learn about memory management this should give you a general idea of how things work.\nIn your code you had this line:\npname = ¤tline; \n\nThere are two problems here:\n\nAs already mentioned in my code assigning currentline to pname only copies the pointer not the contents.\nThe correct assignment would be pname = currentline (without the address operator &), because currentline is also a pointer under the hood (it behaves like char *currentline even though it's statically allocated).\n\n",
"In other to get the get the exact memory the string with pointer *pname you simply take the size of the string using using sizeof(\"variable name\") of the string and there by managing the memory.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"c",
"memory"
] |
stackoverflow_0026150981_c_memory.txt
|
Q:
Check if KendoGrid selected checkbox is checked or not
I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
A:
You can use the e.checked property of the event object to check if the checkbox is checked or not.
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
// check if checkbox is checked or not
if (e.checked) {
// add to array
stations.push(grid.dataItem(this).StationId);
} else {
// remove from array
const index = stations.indexOf(grid.dataItem(this).StationId);
if (index > -1) {
stations.splice(index, 1);
}
}
})
}
|
Check if KendoGrid selected checkbox is checked or not
|
I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
|
[
"You can use the e.checked property of the event object to check if the checkbox is checked or not.\nfunction onChange(e) {\n const grid = $(\"#grid\").data(\"kendoGrid\");\n var items = grid.items();\n let ids = '';\n grid.select().each(function() {\n if (ids === '')\n ids = grid.dataItem(this).StationId.toString();\n else\n ids = ids + ',' + grid.dataItem(this).StationId.toString();\n\n // check if checkbox is checked or not\n if (e.checked) {\n // add to array\n stations.push(grid.dataItem(this).StationId);\n } else {\n // remove from array\n const index = stations.indexOf(grid.dataItem(this).StationId);\n if (index > -1) {\n stations.splice(index, 1);\n }\n }\n })\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"c#",
"javascript",
"kendo_asp.net_mvc",
"kendo_grid",
"kendo_ui"
] |
stackoverflow_0074662206_c#_javascript_kendo_asp.net_mvc_kendo_grid_kendo_ui.txt
|
Q:
Mongoose - Find from 2 collections
I want to search 2 models at the same time in a find().
What I have:
const one = await Model1.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
const two = await Model2.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
But, this returns 2 pages worth of results. Thereotically what I need (I know this code is not valid):
const models = [Model1, Model2]
const result = await models.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
To return only 1 page of results, including results from both collections - both limited, skipped & sorted in the same way.
How could I do this?
A:
You can use an aggregation with $unionWith to merge the two collections and query them together
const result = await Model1.aggregate([
{ $match: { example: 'test' } },
{
$unionWith: {
coll: 'model2',
pipeline: [
{
$match: { example: 'test' },
},
],
},
},
{ $sort: { $created_at: -1 } },
{ $limit: limit * 1 },
{ $skip: (page - 1) * limit },
]);
|
Mongoose - Find from 2 collections
|
I want to search 2 models at the same time in a find().
What I have:
const one = await Model1.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
const two = await Model2.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
But, this returns 2 pages worth of results. Thereotically what I need (I know this code is not valid):
const models = [Model1, Model2]
const result = await models.find()
.where('example').equals('test')
.limit(limit * 1)
.skip((page - 1) * limit)
.sort({ created_at: desc })
.exec()
To return only 1 page of results, including results from both collections - both limited, skipped & sorted in the same way.
How could I do this?
|
[
"You can use an aggregation with $unionWith to merge the two collections and query them together\nconst result = await Model1.aggregate([\n { $match: { example: 'test' } },\n {\n $unionWith: {\n coll: 'model2',\n pipeline: [\n {\n $match: { example: 'test' },\n },\n ],\n },\n },\n { $sort: { $created_at: -1 } },\n { $limit: limit * 1 },\n { $skip: (page - 1) * limit },\n]);\n\n"
] |
[
0
] |
[] |
[] |
[
"mongoose",
"node.js"
] |
stackoverflow_0074662049_mongoose_node.js.txt
|
Q:
Using user input function in Classes
I am making a simple game with multiple players, which each player can insert their first name, last name and each player is assigned 100 poins at the begging. In my code once I am done with coding the "essential" information, but when it comes to user input it does not work.
The "base" for the player class: (this part works)
class Players():
def __init__ (self, firstname, lastname, coins): #initialising attributes
self.firstname = firstname
self.lastname = lastname
self.coins= coins
def full_info(self):
return self.firstname + self.lastname + self.coins
This is the second part where the problem is, the input is not stored in the attributes
def get_user_input(self):
firstname= input("Please enter your first name:")
lastname= input ("Please enter your second name: ")
coins= 100 #they are assigned automatically
return self(firstname, lastname, coins)
I would appriciate any suggesting regarding the user input.
A:
Your function to build a new instance from user input should be a classmethod or a staticmethod, since you want to call it to create a new instance.
I'd also suggest using @dataclass so you don't need to copy and paste all the variable names in __init__, and using an f-string in your full_info function so you don't hit an error when you try to add coins to the name strings.
All together it might look like:
from dataclasses import dataclass
@dataclass
class Player:
firstname: str
lastname: str
coins: int
def full_info(self) -> str:
return f"{self.firstname} {self.lastname} {self.coins}"
@classmethod
def from_user_input(cls) -> 'Player':
return cls(
firstname=input("Please enter your first name:"),
lastname=input("Please enter your second name: "),
coins=100,
)
Then you can call Player.from_user_input() to prompt the user for a name and return a new Player object:
>>> player = Player.from_user_input()
Please enter your first name:Bob
Please enter your second name: Small
>>> player
Player(firstname='Bob', lastname='Small', coins=100)
>>> player.full_info()
'Bob Small 100'
A:
If you want to stay close to your original code, a few changes will work:
class Players():
def __init__ (self, firstname, lastname, coins): #initialising attributes
self.firstname = firstname
self.lastname = lastname
self.coins= coins
def full_info(self):
return self.firstname + ' ' + self.lastname + ' ' + str(self.coins)
def get_user_input():
firstname= input("Please enter your first name:")
lastname= input ("Please enter your second name: ")
coins= 100 #they are assigned automatically
return Players(firstname, lastname, coins)
An example:
a=get_user_input()
Please enter your first name:UN
Please enter your second name: Owen
a.full_info()
Out[21]: 'UN Owen 100'
|
Using user input function in Classes
|
I am making a simple game with multiple players, which each player can insert their first name, last name and each player is assigned 100 poins at the begging. In my code once I am done with coding the "essential" information, but when it comes to user input it does not work.
The "base" for the player class: (this part works)
class Players():
def __init__ (self, firstname, lastname, coins): #initialising attributes
self.firstname = firstname
self.lastname = lastname
self.coins= coins
def full_info(self):
return self.firstname + self.lastname + self.coins
This is the second part where the problem is, the input is not stored in the attributes
def get_user_input(self):
firstname= input("Please enter your first name:")
lastname= input ("Please enter your second name: ")
coins= 100 #they are assigned automatically
return self(firstname, lastname, coins)
I would appriciate any suggesting regarding the user input.
|
[
"Your function to build a new instance from user input should be a classmethod or a staticmethod, since you want to call it to create a new instance.\nI'd also suggest using @dataclass so you don't need to copy and paste all the variable names in __init__, and using an f-string in your full_info function so you don't hit an error when you try to add coins to the name strings.\nAll together it might look like:\nfrom dataclasses import dataclass\n\n@dataclass\nclass Player: \n firstname: str\n lastname: str\n coins: int\n\n def full_info(self) -> str:\n return f\"{self.firstname} {self.lastname} {self.coins}\"\n\n @classmethod\n def from_user_input(cls) -> 'Player':\n return cls(\n firstname=input(\"Please enter your first name:\"),\n lastname=input(\"Please enter your second name: \"),\n coins=100,\n )\n\nThen you can call Player.from_user_input() to prompt the user for a name and return a new Player object:\n>>> player = Player.from_user_input()\nPlease enter your first name:Bob\nPlease enter your second name: Small\n>>> player\nPlayer(firstname='Bob', lastname='Small', coins=100)\n>>> player.full_info()\n'Bob Small 100'\n\n",
"If you want to stay close to your original code, a few changes will work:\nclass Players(): \n def __init__ (self, firstname, lastname, coins): #initialising attributes\n self.firstname = firstname \n self.lastname = lastname\n self.coins= coins\n \n def full_info(self):\n return self.firstname + ' ' + self.lastname + ' ' + str(self.coins)\n \ndef get_user_input():\n firstname= input(\"Please enter your first name:\")\n lastname= input (\"Please enter your second name: \")\n coins= 100 #they are assigned automatically \n return Players(firstname, lastname, coins)\n\nAn example:\na=get_user_input()\n\nPlease enter your first name:UN\n\nPlease enter your second name: Owen\n\na.full_info()\nOut[21]: 'UN Owen 100'\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"input",
"object",
"oop",
"python"
] |
stackoverflow_0074662334_input_object_oop_python.txt
|
Q:
SQL - applying multiple pivots in one query, and finding the sum of resulting rows
I am attempting to create an SQL query which will compress multidimentional data using PIVOT, but need to do some operations on the pivoted data.
I have coding experience but very little experience with SQL and am using SQLPathfinder3 to create and execute queries, so what I am looking for is top level approach - what order of operations should I be going for here to achieve the desired result?
An example of my initial result table, gotten with SELECT, is as follows:
Item
Property
Subproperty
Thing
item1
propertyA
subproperty1
value1_A_1
item1
propertyA
subproperty2
value1_A_2
item1
propertyB
subproperty1
value1_B_1
item1
propertyB
subproperty2
value1_B_2
item2
propertyA
subproperty1
value2_A_1
item2
propertyA
subproperty2
value2_A_2
item2
propertyB
subproperty1
value2_B_1
item2
propertyB
subproperty2
value2_B_2
By executing one pivot, assigning Subproperty as the CTHEADER, and Thing as the CTVALUE, I can create this:
Item
Property
Subproperty1
Subproperty2
item1
propertyA
value1_A_1
value1_A_2
item1
propertyB
value1_B_1
value1_B_2
item2
propertyA
value2_A_1
value2_A_2
item2
propertyB
value2_B_1
value2_B_2
Similarly, I can pivot around "Subproperty" to get something analogous:
Item
Subproperty
Property A
Property B
item1
subproperty1
value1_A_1
value1_A_2
item1
subproperty2
value1_B_1
value1_B_2
item2
subproperty1
value2_A_1
value2_A_2
item2
subproperty2
value2_B_1
value2_B_2
The final result that I need is this - a combination of the above values:
Item
Property A
Property B
item1
value1_A_1 + value1_A_2
value1_B_1 + value1_B_2
item2
value2_A_1 + value2_A_2
value2_B_1 + value2_B_2
I don't know how to go about doing this in a single query, but I would very much like to, because this is something that needs to be automated.
I can't simply SELECT the sums that I want, because those values are on four separate lines. I could workaround in excel or python, especially if I can effect the result below, but I'm not sure how to do this.
Item
PropA Sub1
PropA Sub2
PropB Sub1
PropB Sub2
item1
value1_A_1
value1_A_2
value1_B_1
value1_B_2
item2
value2_A_1
value2_A_2
value2_B_1
value2_B_2
Any help, or pointers towards educational material would be appreciated, thanks.
A:
Try:
SELECT
P.Item,
STRING_AGG(P.propertyA, ' + ') WITHIN GROUP (ORDER BY Subproperty) AS propertyA,
STRING_AGG(P.propertyB, ' + ') WITHIN GROUP (ORDER BY Subproperty) AS propertyB
FROM @Data
PIVOT (
MAX(Thing)
FOR Property IN (propertyA, propertyB)
) P
GROUP BY P.Item
ORDER BY P.Item
See this db<>fiddle.
The initial PIVOT will yield:
Item
Subproperty
propertyA
propertyB
item1
subproperty1
value1_A_1
value1_B_1
item2
subproperty1
value2_A_1
value2_B_1
item1
subproperty2
value1_A_2
value1_B_2
item2
subproperty2
value2_A_2
value2_B_2
and the GROUP BY and STRING_AGG() will yield the desired result:
Item
propertyA
propertyB
item1
value1_A_1 + value1_A_2
value1_B_1 + value1_B_2
item2
value2_A_1 + value2_A_2
value2_B_1 + value2_B_2
The WITHIN GROUP(...) clause is not actually required, but guarantees consistent results.
ADDENDUM: For the case where a sum of numbers is need, the STRING_AGG() WITHIN GROUP() can be replaced with a simple SUM(). Using SUM() instead of MAX() in the pivot is also recommended.
-- Pivot plus group by aggregation (Sum of numeric values)
SELECT
P.Item,
SUM(P.propertyA) AS propertyA,
SUM(P.propertyB) AS propertyB
FROM @Data
PIVOT (
SUM(Thing)
FOR Property IN (propertyA, propertyB)
) P
GROUP BY P.Item
ORDER BY P.Item
The Query can be further simplified to a plain old PIVOT by eliminating unwanted columns from the initial select that feeds the PIVOT.
-- Using just a regular PIVOT after excluding unwanted columns
SELECT P.Item, P.propertyA, P.propertyB
FROM (SELECT Item, Property, Thing FROM @Data) D
PIVOT (
SUM(Thing)
FOR Property IN (propertyA, propertyB)
) P
Lastly (I hope), a technique called "Conditional Aggregation" can be used in place of the PIVOT. Sometimes this is actually easier to read, understand, and maintain.
-- Using conditional aggregation instead of PIVOT
SELECT
D.Item,
SUM(CASE WHEN D.Property = 'propertyA' THEN D.Thing END) AS propertyA,
SUM(CASE WHEN D.Property = 'propertyB' THEN D.Thing END) AS propertyB
FROM @Data D
GROUP BY D.Item
ORDER BY D.Item
See this db<>fiddle for the above techniques.
A:
I would choose a dynamic approach, as property will have morwe than 2 item i guess.
I choose to use integers for thig as you wante4d sums
CREATE TABLE tab1
([Item] varchar(5), [Property] varchar(9), [Subproperty] varchar(12), [Thing] int)
;
INSERT INTO tab1
([Item], [Property], [Subproperty], [Thing])
VALUES
('item1', 'propertyA', 'subproperty1', 1),
('item1', 'propertyA', 'subproperty2', 2),
('item1', 'propertyB', 'subproperty1', 3),
('item1', 'propertyB', 'subproperty2', 4),
('item2', 'propertyA', 'subproperty1', 5),
('item2', 'propertyA', 'subproperty2', 6),
('item2', 'propertyB', 'subproperty1', 7),
('item2', 'propertyB', 'subproperty2', 8)
;
8 rows affected
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = (SELECT STRING_AGG([Property],',') FROM (SELECT DISTINCT [Property] FROM tab1 WHERE [Property] IS NOT NULL)t);
set @query = '
SELECT [Item], ' + @cols + ' from
(
SELECT
[Item], [Property], SUM([Thing]) as SumThing
FROM tab1
GROUP BY [Item], [Property]
) x
pivot
(
SUM(SumThing)
for [Property] in (' + @cols + ')
) p ';
execute(@query);
Item
propertyA
propertyB
item1
3
7
item2
11
15
fiddle
|
SQL - applying multiple pivots in one query, and finding the sum of resulting rows
|
I am attempting to create an SQL query which will compress multidimentional data using PIVOT, but need to do some operations on the pivoted data.
I have coding experience but very little experience with SQL and am using SQLPathfinder3 to create and execute queries, so what I am looking for is top level approach - what order of operations should I be going for here to achieve the desired result?
An example of my initial result table, gotten with SELECT, is as follows:
Item
Property
Subproperty
Thing
item1
propertyA
subproperty1
value1_A_1
item1
propertyA
subproperty2
value1_A_2
item1
propertyB
subproperty1
value1_B_1
item1
propertyB
subproperty2
value1_B_2
item2
propertyA
subproperty1
value2_A_1
item2
propertyA
subproperty2
value2_A_2
item2
propertyB
subproperty1
value2_B_1
item2
propertyB
subproperty2
value2_B_2
By executing one pivot, assigning Subproperty as the CTHEADER, and Thing as the CTVALUE, I can create this:
Item
Property
Subproperty1
Subproperty2
item1
propertyA
value1_A_1
value1_A_2
item1
propertyB
value1_B_1
value1_B_2
item2
propertyA
value2_A_1
value2_A_2
item2
propertyB
value2_B_1
value2_B_2
Similarly, I can pivot around "Subproperty" to get something analogous:
Item
Subproperty
Property A
Property B
item1
subproperty1
value1_A_1
value1_A_2
item1
subproperty2
value1_B_1
value1_B_2
item2
subproperty1
value2_A_1
value2_A_2
item2
subproperty2
value2_B_1
value2_B_2
The final result that I need is this - a combination of the above values:
Item
Property A
Property B
item1
value1_A_1 + value1_A_2
value1_B_1 + value1_B_2
item2
value2_A_1 + value2_A_2
value2_B_1 + value2_B_2
I don't know how to go about doing this in a single query, but I would very much like to, because this is something that needs to be automated.
I can't simply SELECT the sums that I want, because those values are on four separate lines. I could workaround in excel or python, especially if I can effect the result below, but I'm not sure how to do this.
Item
PropA Sub1
PropA Sub2
PropB Sub1
PropB Sub2
item1
value1_A_1
value1_A_2
value1_B_1
value1_B_2
item2
value2_A_1
value2_A_2
value2_B_1
value2_B_2
Any help, or pointers towards educational material would be appreciated, thanks.
|
[
"Try:\nSELECT\n P.Item,\n STRING_AGG(P.propertyA, ' + ') WITHIN GROUP (ORDER BY Subproperty) AS propertyA,\n STRING_AGG(P.propertyB, ' + ') WITHIN GROUP (ORDER BY Subproperty) AS propertyB\nFROM @Data\nPIVOT (\n MAX(Thing)\n FOR Property IN (propertyA, propertyB)\n) P\nGROUP BY P.Item\nORDER BY P.Item\n\nSee this db<>fiddle.\nThe initial PIVOT will yield:\n\n\n\n\nItem\nSubproperty\npropertyA\npropertyB\n\n\n\n\nitem1\nsubproperty1\nvalue1_A_1\nvalue1_B_1\n\n\nitem2\nsubproperty1\nvalue2_A_1\nvalue2_B_1\n\n\nitem1\nsubproperty2\nvalue1_A_2\nvalue1_B_2\n\n\nitem2\nsubproperty2\nvalue2_A_2\nvalue2_B_2\n\n\n\n\nand the GROUP BY and STRING_AGG() will yield the desired result:\n\n\n\n\nItem\npropertyA\npropertyB\n\n\n\n\nitem1\nvalue1_A_1 + value1_A_2\nvalue1_B_1 + value1_B_2\n\n\nitem2\nvalue2_A_1 + value2_A_2\nvalue2_B_1 + value2_B_2\n\n\n\n\nThe WITHIN GROUP(...) clause is not actually required, but guarantees consistent results.\nADDENDUM: For the case where a sum of numbers is need, the STRING_AGG() WITHIN GROUP() can be replaced with a simple SUM(). Using SUM() instead of MAX() in the pivot is also recommended.\n-- Pivot plus group by aggregation (Sum of numeric values)\nSELECT\n P.Item,\n SUM(P.propertyA) AS propertyA,\n SUM(P.propertyB) AS propertyB\nFROM @Data\nPIVOT (\n SUM(Thing)\n FOR Property IN (propertyA, propertyB)\n) P\nGROUP BY P.Item\nORDER BY P.Item\n\nThe Query can be further simplified to a plain old PIVOT by eliminating unwanted columns from the initial select that feeds the PIVOT.\n-- Using just a regular PIVOT after excluding unwanted columns\nSELECT P.Item, P.propertyA, P.propertyB\nFROM (SELECT Item, Property, Thing FROM @Data) D\nPIVOT (\n SUM(Thing)\n FOR Property IN (propertyA, propertyB)\n) P\n\nLastly (I hope), a technique called \"Conditional Aggregation\" can be used in place of the PIVOT. Sometimes this is actually easier to read, understand, and maintain.\n-- Using conditional aggregation instead of PIVOT\nSELECT\n D.Item,\n SUM(CASE WHEN D.Property = 'propertyA' THEN D.Thing END) AS propertyA,\n SUM(CASE WHEN D.Property = 'propertyB' THEN D.Thing END) AS propertyB\nFROM @Data D\nGROUP BY D.Item\nORDER BY D.Item\n\nSee this db<>fiddle for the above techniques.\n",
"I would choose a dynamic approach, as property will have morwe than 2 item i guess.\nI choose to use integers for thig as you wante4d sums\nCREATE TABLE tab1\n ([Item] varchar(5), [Property] varchar(9), [Subproperty] varchar(12), [Thing] int)\n;\n \nINSERT INTO tab1\n ([Item], [Property], [Subproperty], [Thing])\nVALUES\n ('item1', 'propertyA', 'subproperty1', 1),\n ('item1', 'propertyA', 'subproperty2', 2),\n ('item1', 'propertyB', 'subproperty1', 3),\n ('item1', 'propertyB', 'subproperty2', 4),\n ('item2', 'propertyA', 'subproperty1', 5),\n ('item2', 'propertyA', 'subproperty2', 6),\n ('item2', 'propertyB', 'subproperty1', 7),\n ('item2', 'propertyB', 'subproperty2', 8)\n;\n\n\n8 rows affected\n\nDECLARE @cols AS NVARCHAR(MAX),\n @query AS NVARCHAR(MAX);\n\nSET @cols = (SELECT STRING_AGG([Property],',') FROM (SELECT DISTINCT [Property] FROM tab1 WHERE [Property] IS NOT NULL)t);\n\nset @query = '\n \n SELECT [Item], ' + @cols + ' from \n (\n SELECT\n [Item], [Property], SUM([Thing]) as SumThing\n FROM tab1\n GROUP BY [Item], [Property]\n ) x\n pivot \n (\n SUM(SumThing)\n for [Property] in (' + @cols + ')\n ) p ';\n\nexecute(@query);\n\n\n\n\n\n\n\nItem\npropertyA\npropertyB\n\n\n\n\nitem1\n3\n7\n\n\nitem2\n11\n15\n\n\n\n\nfiddle\n"
] |
[
2,
2
] |
[] |
[] |
[
"sql",
"sql_server"
] |
stackoverflow_0074661880_sql_sql_server.txt
|
Q:
Yii 2 error - Trying to get a property of non object
I was trying to search the needed information, but couldn't find any of that. Somehow, I get this error and I don't know where I'm doing a mistake.
Here is my action:
public function actionFilter()
{
$filterParams = Yii::$app->request->get();
unset($filterParams['r']);
$model = new Sale();
$dataProvider = $model->filterParameters($filterParams);
return $this->render('filter', [
'dataProvider' => $dataProvider,
'filterParams' => $filterParams,
]);
}
And here is my view:
'attribute' => 'sale_id',
'width' => '14%',
'value' => function (Sale $model) {
return $model->sale->client->getClientName();
}
],
[
'attribute' => '',
'value' => function (Sale $model) {
return $model->sale->client->getClientSale();
}
],
I'm getting the error on the 'value' return line. The function getClientName() is in client model. Could someone explain what I'm doing wrong? Thanks for any help.
A:
Propably there's no model linked to your main $model. You should check if it's set by:
return $model->debtor && $model->debtor->client ? $model->debtor->client->getFullName() : null;
AND
return $model->debtor && $model->debtor->user ? $model->debtor->user->getFullName() : null;
|
Yii 2 error - Trying to get a property of non object
|
I was trying to search the needed information, but couldn't find any of that. Somehow, I get this error and I don't know where I'm doing a mistake.
Here is my action:
public function actionFilter()
{
$filterParams = Yii::$app->request->get();
unset($filterParams['r']);
$model = new Sale();
$dataProvider = $model->filterParameters($filterParams);
return $this->render('filter', [
'dataProvider' => $dataProvider,
'filterParams' => $filterParams,
]);
}
And here is my view:
'attribute' => 'sale_id',
'width' => '14%',
'value' => function (Sale $model) {
return $model->sale->client->getClientName();
}
],
[
'attribute' => '',
'value' => function (Sale $model) {
return $model->sale->client->getClientSale();
}
],
I'm getting the error on the 'value' return line. The function getClientName() is in client model. Could someone explain what I'm doing wrong? Thanks for any help.
|
[
"Propably there's no model linked to your main $model. You should check if it's set by:\nreturn $model->debtor && $model->debtor->client ? $model->debtor->client->getFullName() : null;\n\nAND\n return $model->debtor && $model->debtor->user ? $model->debtor->user->getFullName() : null;\n\n"
] |
[
1
] |
[
"The answer is simple: \nTurn-off PHP Notice Errors in PHP.ini\nerror_reporting E_ALL & ~E_NOTICE\n",
"In your view; just add @ before the $model to override the problem. Find an example below:\nreturn @$model->sale->client->getClientName();\n\n"
] |
[
-1,
-1
] |
[
"yii2"
] |
stackoverflow_0045588051_yii2.txt
|
Q:
How to open the keybord when the fragment start?
I want to make the keyboard open automatically when the fragment starts. Now my code looks like this:
class NewPostFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentNewPostBinding.inflate(inflater, container, false)
binding.editText.requestFocus()
AndroidUtils.showKeyboard(binding.editText)
binding.OK.setOnClickListener {
AndroidUtils.hideKeyboard(requireView())
findNavController().navigateUp()
}
return binding.root
}
}
AndroidManifest.xml file:
<activity
android:name=".activity.AppActivity"
android:exported="true"
android:windowSoftInputMode="stateVisible|adjustResize">
<nav-graph android:value="@navigation/nav_main" />
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And AndroidUtils file:
object AndroidUtils {
fun hideKeyboard(view: View) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
The problem is that the keyboard does not open, but the focus in the editText field is displayed.
Calling the binding.editText.callOnClick() method does not give any result.
I also tried this code on showKeybord function:
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
}
But keybord is opens only after the first start fragment and method toggleSoftInput() is marked is deprecated. And it does not opens for the second and next times. It is run again only after the application is hard closed.
When I did the same thing in the activity (not in the fragment), the keyboard opened after calling the requestFocus() function.
I have read the documentation on https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility and I have read other similar questions on the stackoverflow, but I still don't get the expected result.
What could be the problem?
How do I get the keyboard to open automatically when the fragment start?
A:
To open the keyboard when a fragment starts in Kotlin, you can use the requestFocus and showSoftInput methods of the EditText widget that you want to focus on.
First, in your fragment's layout file, add an EditText widget that you want to focus on when the fragment starts. Then, in the onCreateView method of your fragment, find the EditText widget using the findViewById method and call the requestFocus method on it to request focus for the EditText widget. Finally, call the showSoftInput method of the InputMethodManager class to open the keyboard.
Here is an example of how to open the keyboard when a fragment starts in Kotlin:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_my, container, false)
// Find the EditText widget
val editText = view.findViewById<EditText>(R.id.editText)
// Request focus for the EditText widget
editText.requestFocus()
// Get the InputMethodManager instance
val inputMethodManager =
context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// Show the keyboard
inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
return view
}
Keep in mind that this code will only work if the EditText widget is focused when the fragment is created. If the user has touched a different view before the fragment is created, the keyboard will not be opened automatically.
|
How to open the keybord when the fragment start?
|
I want to make the keyboard open automatically when the fragment starts. Now my code looks like this:
class NewPostFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentNewPostBinding.inflate(inflater, container, false)
binding.editText.requestFocus()
AndroidUtils.showKeyboard(binding.editText)
binding.OK.setOnClickListener {
AndroidUtils.hideKeyboard(requireView())
findNavController().navigateUp()
}
return binding.root
}
}
AndroidManifest.xml file:
<activity
android:name=".activity.AppActivity"
android:exported="true"
android:windowSoftInputMode="stateVisible|adjustResize">
<nav-graph android:value="@navigation/nav_main" />
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And AndroidUtils file:
object AndroidUtils {
fun hideKeyboard(view: View) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
The problem is that the keyboard does not open, but the focus in the editText field is displayed.
Calling the binding.editText.callOnClick() method does not give any result.
I also tried this code on showKeybord function:
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
}
But keybord is opens only after the first start fragment and method toggleSoftInput() is marked is deprecated. And it does not opens for the second and next times. It is run again only after the application is hard closed.
When I did the same thing in the activity (not in the fragment), the keyboard opened after calling the requestFocus() function.
I have read the documentation on https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility and I have read other similar questions on the stackoverflow, but I still don't get the expected result.
What could be the problem?
How do I get the keyboard to open automatically when the fragment start?
|
[
"To open the keyboard when a fragment starts in Kotlin, you can use the requestFocus and showSoftInput methods of the EditText widget that you want to focus on.\nFirst, in your fragment's layout file, add an EditText widget that you want to focus on when the fragment starts. Then, in the onCreateView method of your fragment, find the EditText widget using the findViewById method and call the requestFocus method on it to request focus for the EditText widget. Finally, call the showSoftInput method of the InputMethodManager class to open the keyboard.\nHere is an example of how to open the keyboard when a fragment starts in Kotlin:\noverride fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n): View? {\n // Inflate the layout for this fragment\n val view = inflater.inflate(R.layout.fragment_my, container, false)\n\n // Find the EditText widget\n val editText = view.findViewById<EditText>(R.id.editText)\n\n // Request focus for the EditText widget\n editText.requestFocus()\n\n // Get the InputMethodManager instance\n val inputMethodManager =\n context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager\n\n // Show the keyboard\n inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)\n\n return view\n}\n\nKeep in mind that this code will only work if the EditText widget is focused when the fragment is created. If the user has touched a different view before the fragment is created, the keyboard will not be opened automatically.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"android_fragments",
"android_manifest",
"java",
"kotlin"
] |
stackoverflow_0074656404_android_android_fragments_android_manifest_java_kotlin.txt
|
Q:
Find new blobs comparing two different binary images
I have two images taken on same sample at t=0 and t=t. There are few new blobs present in image taken at t. I need to find these new blobs (new blobs are the blobs which are present in new XY location at t=t). I am wondering if someone can help?
I tried OR,AND,XOR, reconstructions but the issue is the blobs which are same between two images are not exactly the same. Sometimes they might have size difference which makes the problem complicated.
Image at t=0
Image at t=t
A:
Instead of using OR,AND,XOR, we may sum the two images.
Before summing the images, replace the 255 values with 100 (keeping the range of uint8 [0, 255]).
In the summed image, there are going to be three values:
0 - Background
100 - Non-overlapping area
200 - Overlapping area
We may assume that pixels with value 100 that touches value 200 belongs to the same original blob.
For clearing the overlapping pixels (200) with the touching pixels (100 around them), we may use cv2.floodFill.
After clearing the overlapping pixels and the pixels around them, the pixels that are left (with value 100) are the new blobs.
Example for clearing the pixels using cv2.floodFill:
if sum_img[y, x] == 200:
cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0)
Setting loDiff=100 is used for filling pixels=100 (and pixels=200) with 0 value (200-loDiff=100, so the 100 is filled with zero).
For making the solution better, we may find contours (of pixels=200), and ignore the tiny contours.
Code sample:
import cv2
import numpy as np
# Read input images as Grayscale.
img1 = cv2.imread('image1.png', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('image2.png', cv2.IMREAD_GRAYSCALE)
# Replace 255 with 100 (we want the sum img1+img2 not to overflow)
img1[img1 >= 128] = 100
img2[img2 >= 128] = 100
# Sum two images - in the sum, the value of overlapping parts of blobs is going to be 200
sum_img = img1 + img2
cv2.floodFill(sum_img, None, (0, 0), 0, loDiff=0, upDiff=0) # Remove the white frame.
cv2.imshow('sum_img before floodFill', sum_img) # Show image for testing.
# Find pixels with value 200 (the overlapping blobs).
thesh = cv2.threshold(sum_img, 199, 255, cv2.THRESH_BINARY)[1]
# Find contours (of overlapping blobs parts)
cnts = cv2.findContours(thesh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
# Iterate contours and fill the overlapping part, and the non-zero pixels around it (i.e with value 100) with zero.
for c in cnts:
area_tresh = 50
area = cv2.contourArea(c)
if area > area_tresh: # Ignore very tiny contours
x, y = tuple(c[0, 0]) # Get coordinates of first pixel in the contour
if sum_img[y, x] == 200:
cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0) # Setting loDiff=100 is set for filling pixels=100 (and pixels=200)
sum_img[sum_img == 200] = 0 # Remove the small remainders
#thesh = cv2.cvtColor(thesh, cv2.COLOR_GRAY2BGR) # Convert to BGR for testing (for drawing the contours)
#cv2.drawContours(thesh, cnts, -1, (0, 255, 0), 2) # Draw contours for testing
# Show images for testing.
cv2.imshow('thesh', thesh)
cv2.imshow('sum_img after floodFill', sum_img)
cv2.waitKey()
cv2.destroyAllWindows()
Note:
We may dilate the images first, if the two blobs in proximity are considered to be the same blob (I don't no if a blob can "swim")
Output sum_img (after floodFill):
Update:
The above solution finds the blobs that exist in image1 and not in image2 and blobs exist in image2 and not in image1.
In case we want to find only the blobs that are new in image2, and we also assume that blobs that are close in both images are the same one, we may add the following stages:
Dilate img1 and img2 before summing (two close blobs are going to be overlapping).
Remove the dilated pixels from sum_img at the end.
Remove from sum_img all the blobs that exist only in img1 (and not in img2).
Code sample:
import cv2
import numpy as np
# Read input images as Grayscale.
img1 = cv2.imread('image1.png', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('image2.png', cv2.IMREAD_GRAYSCALE)
# Replace 255 with 100 (we want the sum img1+img2 not to overflow)
img1[img1 >= 128] = 100
img2[img2 >= 128] = 100
# Dilate both images - assume close blobs are the same blob (two blobs are considered overlapped even if they are close but not tuching).
dilated_img1 = cv2.dilate(img1, np.ones((11, 11), np.uint8))
dilated_img2 = cv2.dilate(img2, np.ones((11, 11), np.uint8))
# Sum two images - in the sum, the value of overlapping parts of blobs is going to be 200
sum_img = dilated_img1 + dilated_img2
cv2.floodFill(sum_img, None, (0, 0), 0, loDiff=0, upDiff=0) # Remove the white frame.
#cv2.imshow('sum_img before floodFill', sum_img) # Show image for testing.
# Find pixels with value 200 (the overlapping blobs).
thesh = cv2.threshold(sum_img, 199, 255, cv2.THRESH_BINARY)[1]
# Find contours (of overlapping blobs parts)
cnts = cv2.findContours(thesh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
# Iterate contours and fill the overlapping part, and the non-zero pixels around it (i.e with value 100) with zero.
for c in cnts:
area_tresh = 0 # Optional
area = cv2.contourArea(c)
if area > area_tresh: # Ignore very tiny contours
x, y = tuple(c[0, 0]) # Get coordinates of first pixel in the contour
if sum_img[y, x] == 200:
cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0) # Setting loDiff=100 is set for filling pixels=100 (and pixels=200)
sum_img[sum_img == 200] = 0 # Remove the small remainders
sum_img[(img1 == 0) & (dilated_img1 == 100)] = 0 # Remove dilated pixels from dilated_img1
sum_img[(img2 == 0) & (dilated_img2 == 100)] = 0 # Remove dilated pixels from dilated_img2
sum_img[(img1 == 100) & (img2 == 0)] = 0 # Remove all the blobs that are only in first image (assume new blobs are "bored" only in image2)
# Visualization:
merged_img = cv2.merge((sum_img*2, img1*2, img2*2))
# The output image is img1, without the
output_image = img1.copy()
output_image[sum_img == 100] = 0
# Show images for testing.
cv2.imshow('sum_img', sum_img)
cv2.imshow('merged_img', merged_img)
cv2.waitKey()
cv2.destroyAllWindows()
Output (sum_img*2):
Visualization for testing (merged_img):
Green - exist only in img1
Yellow - exist both in img1 and img2
Magenta - exist only in img2, and not too close to blob in img1 (we are looking for the magenta blobs).
|
Find new blobs comparing two different binary images
|
I have two images taken on same sample at t=0 and t=t. There are few new blobs present in image taken at t. I need to find these new blobs (new blobs are the blobs which are present in new XY location at t=t). I am wondering if someone can help?
I tried OR,AND,XOR, reconstructions but the issue is the blobs which are same between two images are not exactly the same. Sometimes they might have size difference which makes the problem complicated.
Image at t=0
Image at t=t
|
[
"Instead of using OR,AND,XOR, we may sum the two images.\nBefore summing the images, replace the 255 values with 100 (keeping the range of uint8 [0, 255]).\nIn the summed image, there are going to be three values:\n\n0 - Background\n100 - Non-overlapping area\n200 - Overlapping area\n\nWe may assume that pixels with value 100 that touches value 200 belongs to the same original blob.\nFor clearing the overlapping pixels (200) with the touching pixels (100 around them), we may use cv2.floodFill.\nAfter clearing the overlapping pixels and the pixels around them, the pixels that are left (with value 100) are the new blobs.\nExample for clearing the pixels using cv2.floodFill:\nif sum_img[y, x] == 200:\n cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0)\n\nSetting loDiff=100 is used for filling pixels=100 (and pixels=200) with 0 value (200-loDiff=100, so the 100 is filled with zero).\nFor making the solution better, we may find contours (of pixels=200), and ignore the tiny contours.\n\nCode sample:\nimport cv2\nimport numpy as np\n\n# Read input images as Grayscale.\nimg1 = cv2.imread('image1.png', cv2.IMREAD_GRAYSCALE)\nimg2 = cv2.imread('image2.png', cv2.IMREAD_GRAYSCALE)\n\n# Replace 255 with 100 (we want the sum img1+img2 not to overflow)\nimg1[img1 >= 128] = 100\nimg2[img2 >= 128] = 100\n\n# Sum two images - in the sum, the value of overlapping parts of blobs is going to be 200\nsum_img = img1 + img2\n\ncv2.floodFill(sum_img, None, (0, 0), 0, loDiff=0, upDiff=0) # Remove the white frame.\n\ncv2.imshow('sum_img before floodFill', sum_img) # Show image for testing.\n\n# Find pixels with value 200 (the overlapping blobs).\nthesh = cv2.threshold(sum_img, 199, 255, cv2.THRESH_BINARY)[1]\n\n# Find contours (of overlapping blobs parts)\ncnts = cv2.findContours(thesh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]\n\n\n# Iterate contours and fill the overlapping part, and the non-zero pixels around it (i.e with value 100) with zero.\nfor c in cnts:\n area_tresh = 50\n area = cv2.contourArea(c)\n if area > area_tresh: # Ignore very tiny contours\n x, y = tuple(c[0, 0]) # Get coordinates of first pixel in the contour\n if sum_img[y, x] == 200:\n cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0) # Setting loDiff=100 is set for filling pixels=100 (and pixels=200)\n\nsum_img[sum_img == 200] = 0 # Remove the small remainders\n\n#thesh = cv2.cvtColor(thesh, cv2.COLOR_GRAY2BGR) # Convert to BGR for testing (for drawing the contours)\n#cv2.drawContours(thesh, cnts, -1, (0, 255, 0), 2) # Draw contours for testing\n\n# Show images for testing.\ncv2.imshow('thesh', thesh)\ncv2.imshow('sum_img after floodFill', sum_img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n\nNote:\nWe may dilate the images first, if the two blobs in proximity are considered to be the same blob (I don't no if a blob can \"swim\")\nOutput sum_img (after floodFill):\n\n\nUpdate:\nThe above solution finds the blobs that exist in image1 and not in image2 and blobs exist in image2 and not in image1.\nIn case we want to find only the blobs that are new in image2, and we also assume that blobs that are close in both images are the same one, we may add the following stages:\n\nDilate img1 and img2 before summing (two close blobs are going to be overlapping).\nRemove the dilated pixels from sum_img at the end.\nRemove from sum_img all the blobs that exist only in img1 (and not in img2).\n\n\nCode sample:\nimport cv2\nimport numpy as np\n\n# Read input images as Grayscale.\nimg1 = cv2.imread('image1.png', cv2.IMREAD_GRAYSCALE)\nimg2 = cv2.imread('image2.png', cv2.IMREAD_GRAYSCALE)\n\n# Replace 255 with 100 (we want the sum img1+img2 not to overflow)\nimg1[img1 >= 128] = 100\nimg2[img2 >= 128] = 100\n\n# Dilate both images - assume close blobs are the same blob (two blobs are considered overlapped even if they are close but not tuching).\ndilated_img1 = cv2.dilate(img1, np.ones((11, 11), np.uint8))\ndilated_img2 = cv2.dilate(img2, np.ones((11, 11), np.uint8))\n\n# Sum two images - in the sum, the value of overlapping parts of blobs is going to be 200\nsum_img = dilated_img1 + dilated_img2\n\ncv2.floodFill(sum_img, None, (0, 0), 0, loDiff=0, upDiff=0) # Remove the white frame.\n\n#cv2.imshow('sum_img before floodFill', sum_img) # Show image for testing.\n\n# Find pixels with value 200 (the overlapping blobs).\nthesh = cv2.threshold(sum_img, 199, 255, cv2.THRESH_BINARY)[1]\n\n# Find contours (of overlapping blobs parts)\ncnts = cv2.findContours(thesh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]\n\n\n# Iterate contours and fill the overlapping part, and the non-zero pixels around it (i.e with value 100) with zero.\nfor c in cnts:\n area_tresh = 0 # Optional\n area = cv2.contourArea(c)\n if area > area_tresh: # Ignore very tiny contours\n x, y = tuple(c[0, 0]) # Get coordinates of first pixel in the contour\n if sum_img[y, x] == 200:\n cv2.floodFill(sum_img, None, (x, y), 0, loDiff=100, upDiff=0) # Setting loDiff=100 is set for filling pixels=100 (and pixels=200)\n\nsum_img[sum_img == 200] = 0 # Remove the small remainders\n\nsum_img[(img1 == 0) & (dilated_img1 == 100)] = 0 # Remove dilated pixels from dilated_img1\nsum_img[(img2 == 0) & (dilated_img2 == 100)] = 0 # Remove dilated pixels from dilated_img2\nsum_img[(img1 == 100) & (img2 == 0)] = 0 # Remove all the blobs that are only in first image (assume new blobs are \"bored\" only in image2)\n\n# Visualization:\nmerged_img = cv2.merge((sum_img*2, img1*2, img2*2))\n\n# The output image is img1, without the \noutput_image = img1.copy()\noutput_image[sum_img == 100] = 0\n\n# Show images for testing.\ncv2.imshow('sum_img', sum_img)\ncv2.imshow('merged_img', merged_img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n\nOutput (sum_img*2):\n\nVisualization for testing (merged_img):\n\nGreen - exist only in img1\nYellow - exist both in img1 and img2\nMagenta - exist only in img2, and not too close to blob in img1 (we are looking for the magenta blobs).\n\n\n"
] |
[
3
] |
[] |
[] |
[
"computer_vision",
"matlab",
"object_tracking",
"opencv",
"python"
] |
stackoverflow_0074657074_computer_vision_matlab_object_tracking_opencv_python.txt
|
Q:
Upgrading Hibernate to 6.1 - How to specify the equivalent of @Type(type="text")?
We're currently using Hibernate 5.6 but are trying to upgrade to Hibernate 6.1. In one entity we have this property:
@Type(type = "text")
private String someText;
But in Hibernate 6.1, the type field in the @Type annotation is removed. Now the @Type annotation is defined like this:
@java.lang.annotation.Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Type {
/**
* The implementation class which implements {@link UserType}.
*/
Class<? extends UserType<?>> value();
/**
* Parameters to be injected into the custom type after it is
* instantiated. The {@link UserType} implementation must implement
* {@link org.hibernate.usertype.ParameterizedType} to receive the
* parameters.
*/
Parameter[] parameters() default {};
}
Question: What's the equivalent of @Type(type = "text") in Hibernate 6.1?
A:
Based on Hibernate 5.0 documentation - For text BasicTypeRegistry key corresponds LONGVARCHAR Jdbc type.
And in Hibernate 6.1.5 documentation is offered the option to use @JdbcTypeCode annotation:
@JdbcTypeCode(Types.LONGVARCHAR)
private String text;
A:
I don't know the proper syntax for using @Type with Hibernate 6+, but as a workaround, you may try using the @Column annotation:
@Column(columnDefinition="TEXT")
private String someText;
A:
The answer by Georgii Lvov is a great one. I would just like to add that there's an alternative:
@JdbcType(LongVarcharJdbcType.class)
is almost synonymous with @JdbcTypeCode(Types.LONGVARCHAR). Which one you use is, I guess, a bit of a matter of taste.
|
Upgrading Hibernate to 6.1 - How to specify the equivalent of @Type(type="text")?
|
We're currently using Hibernate 5.6 but are trying to upgrade to Hibernate 6.1. In one entity we have this property:
@Type(type = "text")
private String someText;
But in Hibernate 6.1, the type field in the @Type annotation is removed. Now the @Type annotation is defined like this:
@java.lang.annotation.Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Type {
/**
* The implementation class which implements {@link UserType}.
*/
Class<? extends UserType<?>> value();
/**
* Parameters to be injected into the custom type after it is
* instantiated. The {@link UserType} implementation must implement
* {@link org.hibernate.usertype.ParameterizedType} to receive the
* parameters.
*/
Parameter[] parameters() default {};
}
Question: What's the equivalent of @Type(type = "text") in Hibernate 6.1?
|
[
"Based on Hibernate 5.0 documentation - For text BasicTypeRegistry key corresponds LONGVARCHAR Jdbc type.\nAnd in Hibernate 6.1.5 documentation is offered the option to use @JdbcTypeCode annotation:\n@JdbcTypeCode(Types.LONGVARCHAR)\nprivate String text;\n\n",
"I don't know the proper syntax for using @Type with Hibernate 6+, but as a workaround, you may try using the @Column annotation:\n@Column(columnDefinition=\"TEXT\")\nprivate String someText;\n\n",
"The answer by Georgii Lvov is a great one. I would just like to add that there's an alternative:\n@JdbcType(LongVarcharJdbcType.class)\n\nis almost synonymous with @JdbcTypeCode(Types.LONGVARCHAR). Which one you use is, I guess, a bit of a matter of taste.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"hibernate",
"java"
] |
stackoverflow_0074601781_hibernate_java.txt
|
Q:
401 Unauthorized in Nuxt Authentication with Laravel
I'm getting a 401 return
Unauthorized in Next authentication with Laravel, and locally it is working correctly.
I already configured the environment variables for the correct domain.
Another detail is that the API is at: api.domain.com and the front at: app.domain.com.
I've tried to configure the variables, and even remove the CORS to test, but the error continues!
A:
It sounds like there may be an issue with your CORS configuration. The 401 Unauthorized error often indicates that the request is being blocked by the server due to CORS policies.
To resolve this issue, you will need to configure your server to properly handle CORS requests from your frontend. This typically involves setting appropriate headers in your server responses that allow the frontend to access the API.
Here is an example of how you might do this in Laravel:
// Add this to the top of your routes/api.php file
header('Access-Control-Allow-Origin: https://app.domain.com');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');
This will allow requests from app.domain.com to access your API. You will also need to ensure that your frontend is sending the appropriate credentials with the request, such as an API key or token.
|
401 Unauthorized in Nuxt Authentication with Laravel
|
I'm getting a 401 return
Unauthorized in Next authentication with Laravel, and locally it is working correctly.
I already configured the environment variables for the correct domain.
Another detail is that the API is at: api.domain.com and the front at: app.domain.com.
I've tried to configure the variables, and even remove the CORS to test, but the error continues!
|
[
"It sounds like there may be an issue with your CORS configuration. The 401 Unauthorized error often indicates that the request is being blocked by the server due to CORS policies.\nTo resolve this issue, you will need to configure your server to properly handle CORS requests from your frontend. This typically involves setting appropriate headers in your server responses that allow the frontend to access the API.\nHere is an example of how you might do this in Laravel:\n// Add this to the top of your routes/api.php file\nheader('Access-Control-Allow-Origin: https://app.domain.com');\nheader('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');\n\nThis will allow requests from app.domain.com to access your API. You will also need to ensure that your frontend is sending the appropriate credentials with the request, such as an API key or token.\n"
] |
[
0
] |
[] |
[] |
[
"api",
"laravel",
"nuxt.js"
] |
stackoverflow_0074662425_api_laravel_nuxt.js.txt
|
Q:
Are serial port settings permanent in Linux?
I have two programs to read from serial port, some device is connected at the other end.
First program is written using Qt framework and it uses QextSerialPort to communicate with serial. Second program is written in pure C.
Problem is like this:
Right after system boot, pure C program has a problem with reading data from serial, I know that it sends data properly because device reacts for data, although pselect (that is monitoring serial_fd) never returns with serial_fd to read data from device.
When I start second program (written in Qt) it is sending and receiving data from device right away, no problem.
What is more, after I start Qt program, and then pure C program, pure C is suddenly working flawlessly, until I reboot system again.
So it looks like program written in Qt changes some settings of serial port permanently during initialization, is this possible?
Below is snippet of code from Qt program that initializes serial port:
if (rs232->open(QIODevice::ReadWrite)) {
rs232->setBaudRate(BAUD38400);
rs232->setFlowControl(FLOW_OFF);
rs232->setParity(PAR_NONE);
rs232->setDataBits(DATA_8);
rs232->setStopBits(STOP_1);
connect(rs232, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
} else {
qDebug() << "Rs232::rs232Connect OPEN PORT FAILURE";
exit(1);
}
And this is from pure C program:
fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
/*
* Could not open the port.
*/
error_exit(ERROR,"open_port: Unable to open /dev/ttyAMA0");
}
else
fcntl(fd, F_SETFL, 0);
/*
* Get the current options for the port...
*/
tcgetattr(fd, &options);
/*
* Set the baud rates to 19200...
*/
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
/*
* Enable the receiver and set local mode...
*/
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
/*
* Set the new options for the port...
*/
tcsetattr(fd, TCSANOW, &options);
Is there something missing or what ?
best regards
Marek
A:
I'm grasping at straws here, but before doing anything else, I would suggest connecting another terminal to the other side and see if anything is happening at all. Your problem might be the fact you're not setting a flow control mode in the C application, try
options.c_cflag &= ~CRTSCTS;
If it still doesn't work, have a look at the accepted answer here; I've used the code a couple of times in the past and never had any problems with serial comms.
A:
I know the question is old, but still there is no answer to the original question in the title.
So, yes, serial port settings are persistent in Linux in the sense that settings done to the port from one process may be visible to another process, even if the first process is ended already.
The settings are reset during system boot process.
Also, there is a special command line utility to query and set serial port settings: stty.
E.g., to query serial port settings, you may use:
stty -F /dev/ttyS0
which might be useful in your case to compare serial port settings after running both applications and find the difference that make the second application work.
|
Are serial port settings permanent in Linux?
|
I have two programs to read from serial port, some device is connected at the other end.
First program is written using Qt framework and it uses QextSerialPort to communicate with serial. Second program is written in pure C.
Problem is like this:
Right after system boot, pure C program has a problem with reading data from serial, I know that it sends data properly because device reacts for data, although pselect (that is monitoring serial_fd) never returns with serial_fd to read data from device.
When I start second program (written in Qt) it is sending and receiving data from device right away, no problem.
What is more, after I start Qt program, and then pure C program, pure C is suddenly working flawlessly, until I reboot system again.
So it looks like program written in Qt changes some settings of serial port permanently during initialization, is this possible?
Below is snippet of code from Qt program that initializes serial port:
if (rs232->open(QIODevice::ReadWrite)) {
rs232->setBaudRate(BAUD38400);
rs232->setFlowControl(FLOW_OFF);
rs232->setParity(PAR_NONE);
rs232->setDataBits(DATA_8);
rs232->setStopBits(STOP_1);
connect(rs232, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
} else {
qDebug() << "Rs232::rs232Connect OPEN PORT FAILURE";
exit(1);
}
And this is from pure C program:
fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
/*
* Could not open the port.
*/
error_exit(ERROR,"open_port: Unable to open /dev/ttyAMA0");
}
else
fcntl(fd, F_SETFL, 0);
/*
* Get the current options for the port...
*/
tcgetattr(fd, &options);
/*
* Set the baud rates to 19200...
*/
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
/*
* Enable the receiver and set local mode...
*/
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
/*
* Set the new options for the port...
*/
tcsetattr(fd, TCSANOW, &options);
Is there something missing or what ?
best regards
Marek
|
[
"I'm grasping at straws here, but before doing anything else, I would suggest connecting another terminal to the other side and see if anything is happening at all. Your problem might be the fact you're not setting a flow control mode in the C application, try\noptions.c_cflag &= ~CRTSCTS;\n\nIf it still doesn't work, have a look at the accepted answer here; I've used the code a couple of times in the past and never had any problems with serial comms.\n",
"I know the question is old, but still there is no answer to the original question in the title.\nSo, yes, serial port settings are persistent in Linux in the sense that settings done to the port from one process may be visible to another process, even if the first process is ended already.\nThe settings are reset during system boot process.\nAlso, there is a special command line utility to query and set serial port settings: stty.\nE.g., to query serial port settings, you may use:\nstty -F /dev/ttyS0\n\nwhich might be useful in your case to compare serial port settings after running both applications and find the difference that make the second application work.\n"
] |
[
0,
0
] |
[] |
[] |
[
"c",
"linux",
"qextserialport",
"qt",
"serial_port"
] |
stackoverflow_0021452790_c_linux_qextserialport_qt_serial_port.txt
|
Q:
How to count number of occurrences per day over a large data set?
I have a dataset that looks something like this but much larger, over 1000 unique products:
| Hour | Date || Pallet ID| PRODUCT || Move Type|
| -------- | -------- || -------- | -------- || -------- |
| 1 PM | 10/01 || 101 | Shoes || Storage |
| 1 PM | 10/01 || 202 | Pants || Load |
| 1 PM | 10/01 || 101 | Shoes || Storage |
| 1 PM | 10/01 || 101 | Shoes || Load |
| 1 PM | 10/01 || 202 | Pants || Storage |
| 3 PM | 10/01 || 202 | Pants || Storage |
| 3 PM | 10/01 || 101 | Shoes || Load |
| 3 PM | 10/01 || 202 | Pants || Storage |`
What I want to do is create a new table that looks like this:
| Hour | Date || Pallet ID| PRODUCT || Move Type| Total Moves |
| -------- | -------- || -------- | -------- || -------- | -------- |
| 1 PM | 10/01 || 101 | Shoes || Storage | 2 |
| 1 PM | 10/01 || 101 | Shoes || Load | 1 |
| 1 PM | 10/01 || 202 | Pants || Load | 1 |
| 1 PM | 10/01 || 202 | Pants || Storage | 1 |
| 3 PM | 10/01 || 101 | Shoes || Load | 1 |
| 3 PM | 10/01 || 202 | Pants || Storage | 2 |
Here is my attempt at doing this. This cannot be the correct way as this takes hours to fully run completely. Is there any way of doing this better than I am currently?
listy = df['PROD_CODE'].unique().tolist()
calc_df = pd.DataFrame()
count = 0
for x in listy:
new_df = df.loc[df['PROD_CODE'] == x]
dates = new_df['Date'].unique().tolist()
count = count + 1
print(f'{count} / {len(listy)} loops have been completed')
for z in dates:
dates_df = new_df[new_df['Date'] == z]
hours = new_df['Hour'].unique().tolist()
for h in hours:
hours_df = dates_df.loc[new_df['Hour'] == h]
hours_df[['Hour','Date','PALLET_ID','PROD_CODE','CASE_QTY','Move Type']]
hours_df['Total Moves'] = hours_df.groupby('Move Type')['Move Type'].transform('count')
calc_df = calc_df.append(hours_df,ignore_index=False)
A:
You should be able to use df.groupby() with .size() to get the counts for moves of the same date/time/pallet id/product/move type.
df.groupby(['Hour','Date','PALLET_ID','PROD_CODE','CASE_QTY','Move Type']).size().reset_index(name='Total Moves')
Source: Get statistics for each group (such as count, mean, etc) using pandas GroupBy?
|
How to count number of occurrences per day over a large data set?
|
I have a dataset that looks something like this but much larger, over 1000 unique products:
| Hour | Date || Pallet ID| PRODUCT || Move Type|
| -------- | -------- || -------- | -------- || -------- |
| 1 PM | 10/01 || 101 | Shoes || Storage |
| 1 PM | 10/01 || 202 | Pants || Load |
| 1 PM | 10/01 || 101 | Shoes || Storage |
| 1 PM | 10/01 || 101 | Shoes || Load |
| 1 PM | 10/01 || 202 | Pants || Storage |
| 3 PM | 10/01 || 202 | Pants || Storage |
| 3 PM | 10/01 || 101 | Shoes || Load |
| 3 PM | 10/01 || 202 | Pants || Storage |`
What I want to do is create a new table that looks like this:
| Hour | Date || Pallet ID| PRODUCT || Move Type| Total Moves |
| -------- | -------- || -------- | -------- || -------- | -------- |
| 1 PM | 10/01 || 101 | Shoes || Storage | 2 |
| 1 PM | 10/01 || 101 | Shoes || Load | 1 |
| 1 PM | 10/01 || 202 | Pants || Load | 1 |
| 1 PM | 10/01 || 202 | Pants || Storage | 1 |
| 3 PM | 10/01 || 101 | Shoes || Load | 1 |
| 3 PM | 10/01 || 202 | Pants || Storage | 2 |
Here is my attempt at doing this. This cannot be the correct way as this takes hours to fully run completely. Is there any way of doing this better than I am currently?
listy = df['PROD_CODE'].unique().tolist()
calc_df = pd.DataFrame()
count = 0
for x in listy:
new_df = df.loc[df['PROD_CODE'] == x]
dates = new_df['Date'].unique().tolist()
count = count + 1
print(f'{count} / {len(listy)} loops have been completed')
for z in dates:
dates_df = new_df[new_df['Date'] == z]
hours = new_df['Hour'].unique().tolist()
for h in hours:
hours_df = dates_df.loc[new_df['Hour'] == h]
hours_df[['Hour','Date','PALLET_ID','PROD_CODE','CASE_QTY','Move Type']]
hours_df['Total Moves'] = hours_df.groupby('Move Type')['Move Type'].transform('count')
calc_df = calc_df.append(hours_df,ignore_index=False)
|
[
"You should be able to use df.groupby() with .size() to get the counts for moves of the same date/time/pallet id/product/move type.\ndf.groupby(['Hour','Date','PALLET_ID','PROD_CODE','CASE_QTY','Move Type']).size().reset_index(name='Total Moves')\n\nSource: Get statistics for each group (such as count, mean, etc) using pandas GroupBy?\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074662368_python.txt
|
Q:
What happened to Apple's sample code for writing a Stickies app?
I don't remember if it shipped with Xcode, or if I downloaded it from developer.apple.com, but there used to be sample code available to create a Stickies-style app in Xcode. It was probably in Objective-C, since it was several years ago that I remember seeing it.
It might very well have been the same code Apple uses for their own Stickies app.
Where can I find it? (Preferably in Swift, but probably in Objective-C.)
I've Googled, DuckDuckGo'ed, etc. I've searched on https://developer.apple.com, all finding nothing.
TO THE CLOSERS
We don’t allow questions seeking recommendations for books, tools, software libraries, and more.
Your criticism is 100% off-the-mark. Show me where I'm asking for recommendations for books/tools/software and I'll buy you a beer. Seriously.
That said, I'm well aware that this question is a better fit for the Apple site, but they closed it and sent me here. If your own SE moderators don't know how to categorize questions appropriately, how can you expect the general public to do so?
A:
Here it is:
https://developer.apple.com/library/archive/samplecode/SyncServices_SimpleStickies/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009051
There is also this: https://developer.apple.com/library/archive/samplecode/SyncServices_StickiesWithCoreData/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009052
This is what I googled: apple sample code old
Which got me here: https://developer.apple.com/library/archive/navigation/
And searching for sample code called stickies got me to it.
|
What happened to Apple's sample code for writing a Stickies app?
|
I don't remember if it shipped with Xcode, or if I downloaded it from developer.apple.com, but there used to be sample code available to create a Stickies-style app in Xcode. It was probably in Objective-C, since it was several years ago that I remember seeing it.
It might very well have been the same code Apple uses for their own Stickies app.
Where can I find it? (Preferably in Swift, but probably in Objective-C.)
I've Googled, DuckDuckGo'ed, etc. I've searched on https://developer.apple.com, all finding nothing.
TO THE CLOSERS
We don’t allow questions seeking recommendations for books, tools, software libraries, and more.
Your criticism is 100% off-the-mark. Show me where I'm asking for recommendations for books/tools/software and I'll buy you a beer. Seriously.
That said, I'm well aware that this question is a better fit for the Apple site, but they closed it and sent me here. If your own SE moderators don't know how to categorize questions appropriately, how can you expect the general public to do so?
|
[
"Here it is:\nhttps://developer.apple.com/library/archive/samplecode/SyncServices_SimpleStickies/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009051\nThere is also this: https://developer.apple.com/library/archive/samplecode/SyncServices_StickiesWithCoreData/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009052\nThis is what I googled: apple sample code old\nWhich got me here: https://developer.apple.com/library/archive/navigation/\nAnd searching for sample code called stickies got me to it.\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"objective_c",
"swift"
] |
stackoverflow_0074661490_macos_objective_c_swift.txt
|
Q:
Excel VBA table manipulation: transpose column based on first column
I want to organize a table generated by importing from multiple text files. Importing the multiple text files into excel creates a table similar to the dataset below. It has the text file name in column A and the values are in Column B.
Number of groups is around 400
Number of "IDs" is always 160
Using a formula would be great, but I figured that wouldn't be possible
Here is my data set.
It has only two columns as described but needs to be transposed so that there is one row per distinct column 1 entry, which will then have multiple columns:
|Group|Value|
|-----|-----|
|A.txt| 1a |
|A.txt| 2a |
|A.txt| 3a |
|B.txt| 1b |
|B.txt| 2b |
|B.txt| 3b |
|C.txt| 1c |
|C.txt| 2c |
|C.txt| 3c |
Here's the desired result!
|Group|ID1|ID2|ID3|
|:----|:-:|:-:|--:|
|A.txt|1a |2a |3a |
|B.txt|1b |2b |3b |
|C.txt|1c |2c |3c |
The number of IDs are the same for each entry.
I have used VBA in excel many years ago, but I haven't since 2015! Needing some help.
A:
I know you asked for an Excel/VBA solution, but I will give you a very easy Google Sheets one. You can easily open you Excel over at goolge sheets and work there. You may even get the Idea and port it to Excel then.
Just put in the same places and write the formulas at the assigned cells, or adjust the formulas...
I paste the code here as well:
D2: =UNIQUE(A2:A)
E1: = ARRAYFORMULA("ID" & TEXT(SEQUENCE(1,COUNTA(E2:2),1,1),"00"))
E2: =TRANSPOSE( filter($B$2:$B,$A$2:$A=$D2))
e3... drag down from E2
A:
Here is the solution I came up. It took me a year to have 3 hours to work on this project. I'll likely at some point in the near future extend this to sort and use VLOOKUP(), but this exercise was the starting point I needed to remember how to use VBA.
This is a first draft requiring to create a button, but will have VBA load a each of the txt files from a folder and create the initial set than run the macro below against that.
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim group As Integer
Dim str1 As String
Private Sub CommandButton1_Click()
str1 = ""
group = 0
j = 0
k = 1
For i = 1 To 10
If str1 = Cells(i, 1).Value Then
k = k + 1
Cells(group, 4 + k).Value = Cells(i, 2).Value
Else
str1 = Cells(i, 1).Value
If group = 0 Then
Cells(1, 4).Value = Cells(i, 1).Value
j = j + 1
Else
Cells(1, 4 + group).Value = CStr(group)
Cells(group + 1, 4).Value = str1
Cells(group + 1, 4 + j).Value = Cells(i, 2).Value
End If
group = group + 1
k = 1
End If
Next i
End Sub
Sincerely
|
Excel VBA table manipulation: transpose column based on first column
|
I want to organize a table generated by importing from multiple text files. Importing the multiple text files into excel creates a table similar to the dataset below. It has the text file name in column A and the values are in Column B.
Number of groups is around 400
Number of "IDs" is always 160
Using a formula would be great, but I figured that wouldn't be possible
Here is my data set.
It has only two columns as described but needs to be transposed so that there is one row per distinct column 1 entry, which will then have multiple columns:
|Group|Value|
|-----|-----|
|A.txt| 1a |
|A.txt| 2a |
|A.txt| 3a |
|B.txt| 1b |
|B.txt| 2b |
|B.txt| 3b |
|C.txt| 1c |
|C.txt| 2c |
|C.txt| 3c |
Here's the desired result!
|Group|ID1|ID2|ID3|
|:----|:-:|:-:|--:|
|A.txt|1a |2a |3a |
|B.txt|1b |2b |3b |
|C.txt|1c |2c |3c |
The number of IDs are the same for each entry.
I have used VBA in excel many years ago, but I haven't since 2015! Needing some help.
|
[
"I know you asked for an Excel/VBA solution, but I will give you a very easy Google Sheets one. You can easily open you Excel over at goolge sheets and work there. You may even get the Idea and port it to Excel then.\nJust put in the same places and write the formulas at the assigned cells, or adjust the formulas...\n\nI paste the code here as well:\nD2: =UNIQUE(A2:A)\nE1: = ARRAYFORMULA(\"ID\" & TEXT(SEQUENCE(1,COUNTA(E2:2),1,1),\"00\"))\nE2: =TRANSPOSE( filter($B$2:$B,$A$2:$A=$D2))\ne3... drag down from E2\n\n",
"Here is the solution I came up. It took me a year to have 3 hours to work on this project. I'll likely at some point in the near future extend this to sort and use VLOOKUP(), but this exercise was the starting point I needed to remember how to use VBA.\nThis is a first draft requiring to create a button, but will have VBA load a each of the txt files from a folder and create the initial set than run the macro below against that.\nDim i As Integer\nDim j As Integer\nDim k As Integer\nDim group As Integer\nDim str1 As String\nPrivate Sub CommandButton1_Click()\n str1 = \"\"\n group = 0\n j = 0\n k = 1\n For i = 1 To 10\n If str1 = Cells(i, 1).Value Then\n k = k + 1\n Cells(group, 4 + k).Value = Cells(i, 2).Value\n Else\n str1 = Cells(i, 1).Value\n If group = 0 Then\n Cells(1, 4).Value = Cells(i, 1).Value\n j = j + 1\n Else\n Cells(1, 4 + group).Value = CStr(group)\n Cells(group + 1, 4).Value = str1\n Cells(group + 1, 4 + j).Value = Cells(i, 2).Value\n End If\n group = group + 1\n k = 1\n End If\n Next i\nEnd Sub\n\nSincerely\n"
] |
[
0,
0
] |
[] |
[] |
[
"excel",
"vba"
] |
stackoverflow_0069929036_excel_vba.txt
|
Q:
Compile and upload to Arduino programmatically
I know basic arduino development using the default Arduino IDE. I am using the Arduino Pro Mini 5V board for my project.
I need to be able to compile and upload the program onto the board programmatically (rather than using the buttons in the Arduino IDE). As an experiment, I have written a basic "blink LED" sample code that I want to be able to compile and then upload to the Arduino Pro Mini board - all programmatically - rather than through the default Arduino IDE.
How can I compile and upload the code to the Arduino Pro Mini through avrdude through a terminal rather than using the native Arduino IDE?
/////////////////////////////////////////////////////
// BLINK LED ON ARDUINO PRO MINI (5V)
//
// http://arduino.cc/en/Main/ArduinoBoardProMini
/////////////////////////////////////////////////////
// For blinking an LED in arduino Pro Mini 5V
int blink_led = 13;
// the setup routine runs once when you press reset:
void setup() {
// Blink LED is an output pin.
pinMode(blink_led, OUTPUT);
}
void loop() {
// BLINK LED
digitalWrite(blink_led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(blink_led, LOW); // turn the LED off by making the voltage LOW
delay(50); // wait for a second
}
A:
Have you tried Ino?. It's a command line toolkit to build and upload Arduino sketches. They have a really good Getting Started Guide.
A:
avrgirl is a library that might do what you want. Since I need to upload to ESP32, I'm going to try using Arduino-CLI which seems to allow it.
|
Compile and upload to Arduino programmatically
|
I know basic arduino development using the default Arduino IDE. I am using the Arduino Pro Mini 5V board for my project.
I need to be able to compile and upload the program onto the board programmatically (rather than using the buttons in the Arduino IDE). As an experiment, I have written a basic "blink LED" sample code that I want to be able to compile and then upload to the Arduino Pro Mini board - all programmatically - rather than through the default Arduino IDE.
How can I compile and upload the code to the Arduino Pro Mini through avrdude through a terminal rather than using the native Arduino IDE?
/////////////////////////////////////////////////////
// BLINK LED ON ARDUINO PRO MINI (5V)
//
// http://arduino.cc/en/Main/ArduinoBoardProMini
/////////////////////////////////////////////////////
// For blinking an LED in arduino Pro Mini 5V
int blink_led = 13;
// the setup routine runs once when you press reset:
void setup() {
// Blink LED is an output pin.
pinMode(blink_led, OUTPUT);
}
void loop() {
// BLINK LED
digitalWrite(blink_led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(blink_led, LOW); // turn the LED off by making the voltage LOW
delay(50); // wait for a second
}
|
[
"Have you tried Ino?. It's a command line toolkit to build and upload Arduino sketches. They have a really good Getting Started Guide.\n",
"avrgirl is a library that might do what you want. Since I need to upload to ESP32, I'm going to try using Arduino-CLI which seems to allow it.\n"
] |
[
1,
0
] |
[] |
[] |
[
"arduino",
"c",
"c++",
"embedded",
"terminal"
] |
stackoverflow_0023777716_arduino_c_c++_embedded_terminal.txt
|
Q:
How do i resolve the compilation error on my react app?
[eslint] Plugin "react" was conflicted between "package.json » eslint-config-rea ct-app » C:\Users\user\desktop\robofriends\node_modules\eslint-config-react-app\ base.js" and "BaseConfig » C:\Users\user\Desktop\robofriends\node_modules\eslint -config-react-app\base.js". ERROR in [eslint] Plugin "react" was conflicted between "package.json » eslint-c onfig-react-app » C:\Users\user\desktop\robofriends\node_modules\eslint-config-r eact-app\base.js" and "BaseConfig » C:\Users\user\Desktop\robofriends\node_modul es\eslint-config-react-app\base.js".
I tried re-install everything from the start all over but still didnt work.
A:
It looks like you are encountering an error with the eslint plugin for React. To fix this error, try the following steps:
1.Check your package.json file to make sure that you have only one version of the eslint-config-react-app package installed. If you have multiple versions installed, try removing one of them.
2.If step 1 does not fix the problem, try running the npm ls eslint command to list all of the installed versions of the eslint package. This will help you identify any conflicts between different versions of the package.
3.If you are still unable to resolve the error, try uninstalling and reinstalling the eslint-config-react-app package. This may help to reset any conflicting configurations.
4.If none of the above steps work, you may need to manually edit your eslint configuration to resolve the conflict. You can find more information about how to do this in the eslint documentation.
A:
It looks like you are encountering a conflict between two different versions of the eslint-plugin-react package. One version is specified in your package.json file, while the other version is specified in the eslint-config-react-app package.
To resolve this error, you will need to make sure that you are using the same version of the eslint-plugin-react package in both places.
To do this, you can run the following command in your project's root directory:
npm ls eslint-plugin-react
This will show you the version of the eslint-plugin-react package that is installed in your project, as well as the versions of the package that are installed by any other dependencies in your project.
If you see multiple versions of the eslint-plugin-react package, you will need to update your package.json file to use the same version as the one specified in the eslint-config-react-app package.
You can do this by running the following command:
npm install eslint-plugin-react@<version> --save-dev
|
How do i resolve the compilation error on my react app?
|
[eslint] Plugin "react" was conflicted between "package.json » eslint-config-rea ct-app » C:\Users\user\desktop\robofriends\node_modules\eslint-config-react-app\ base.js" and "BaseConfig » C:\Users\user\Desktop\robofriends\node_modules\eslint -config-react-app\base.js". ERROR in [eslint] Plugin "react" was conflicted between "package.json » eslint-c onfig-react-app » C:\Users\user\desktop\robofriends\node_modules\eslint-config-r eact-app\base.js" and "BaseConfig » C:\Users\user\Desktop\robofriends\node_modul es\eslint-config-react-app\base.js".
I tried re-install everything from the start all over but still didnt work.
|
[
"It looks like you are encountering an error with the eslint plugin for React. To fix this error, try the following steps:\n1.Check your package.json file to make sure that you have only one version of the eslint-config-react-app package installed. If you have multiple versions installed, try removing one of them.\n2.If step 1 does not fix the problem, try running the npm ls eslint command to list all of the installed versions of the eslint package. This will help you identify any conflicts between different versions of the package.\n3.If you are still unable to resolve the error, try uninstalling and reinstalling the eslint-config-react-app package. This may help to reset any conflicting configurations.\n4.If none of the above steps work, you may need to manually edit your eslint configuration to resolve the conflict. You can find more information about how to do this in the eslint documentation.\n",
"It looks like you are encountering a conflict between two different versions of the eslint-plugin-react package. One version is specified in your package.json file, while the other version is specified in the eslint-config-react-app package.\nTo resolve this error, you will need to make sure that you are using the same version of the eslint-plugin-react package in both places.\nTo do this, you can run the following command in your project's root directory:\nnpm ls eslint-plugin-react\n\nThis will show you the version of the eslint-plugin-react package that is installed in your project, as well as the versions of the package that are installed by any other dependencies in your project.\nIf you see multiple versions of the eslint-plugin-react package, you will need to update your package.json file to use the same version as the one specified in the eslint-config-react-app package.\nYou can do this by running the following command:\nnpm install eslint-plugin-react@<version> --save-dev\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"javascript"
] |
stackoverflow_0074662424_javascript.txt
|
Q:
HTML Div in my project sticks to the bottom, how to center it?
I just cloned this github-sidebar-project And when i am trying to add an div element at the body of the page, it sticks to the bottom of the page and i have to scroll to it.
Also, the sidebar ends when my div begins.
This is the HTML Code i have used in the body:
<div class="display">Display</div>
CSS Code:
body .display {
margin: auto;
color: #ff328e;
text-align: center;
width: 50%;
background: rgba(10, 10, 10, .65);
box-shadow: 0 8px 32px rgb(2, 4, 24);
border: 2px solid rgba(255, 255, 255, .09);
padding: 10px;
}
I tried centering it by trying all of the CSS margin options, But they would only let me control the horizontal position and not the vertical.
With this i am trying to add an main element where all the content will be shown for the different options on the sidebar.
Also, i want the div to stretch out to the left side if the sidebar is folded, and make it smaller when its unfolded.
I have these 2 screenshots where i have drawn an red square to showcase where i want this main element to be.
Please note on these screenshots that i have changed some resources but the issue also exists on the original project.
(Sorry, i don't have enough reputation to post these images directly)
Screenshot with folded sidebar:
https://media.discordapp.net/attachments/1036248150907826282/1048229904124215356/Screenshot_2022-12-02_at_14-30-17_Cashylte.png?width=878&height=440
Screenshot with unfolded sidebar:
https://media.discordapp.net/attachments/1036248150907826282/1048229335548559390/Screenshot_2022-12-02_at_14-25-12_Cashylte.png?width=878&height=440
A:
It seems that this could be solved by styling the layout of body to contain the sidebar and the display div, for example perhaps try give body a grid layout:
body {
display: grid;
/* Column names are optional and added just so it is more clear here */
grid-template-columns: [side-start] min-content [side-end main-start] 1fr [main-end];
}
And specify display to take the main column:
.display {
/* Specify this to be placed in the main column */
grid-column: main;
color: #ff328e;
text-align: center;
background: rgba(10, 10, 10, 0.65);
box-shadow: 0 8px 32px rgb(2, 4, 24);
border: 2px solid rgba(255, 255, 255, 0.09);
padding: 10px;
}
There might be easier approaches or other issues that needed to be addressed, but hopefully this would still help as a reference.
|
HTML Div in my project sticks to the bottom, how to center it?
|
I just cloned this github-sidebar-project And when i am trying to add an div element at the body of the page, it sticks to the bottom of the page and i have to scroll to it.
Also, the sidebar ends when my div begins.
This is the HTML Code i have used in the body:
<div class="display">Display</div>
CSS Code:
body .display {
margin: auto;
color: #ff328e;
text-align: center;
width: 50%;
background: rgba(10, 10, 10, .65);
box-shadow: 0 8px 32px rgb(2, 4, 24);
border: 2px solid rgba(255, 255, 255, .09);
padding: 10px;
}
I tried centering it by trying all of the CSS margin options, But they would only let me control the horizontal position and not the vertical.
With this i am trying to add an main element where all the content will be shown for the different options on the sidebar.
Also, i want the div to stretch out to the left side if the sidebar is folded, and make it smaller when its unfolded.
I have these 2 screenshots where i have drawn an red square to showcase where i want this main element to be.
Please note on these screenshots that i have changed some resources but the issue also exists on the original project.
(Sorry, i don't have enough reputation to post these images directly)
Screenshot with folded sidebar:
https://media.discordapp.net/attachments/1036248150907826282/1048229904124215356/Screenshot_2022-12-02_at_14-30-17_Cashylte.png?width=878&height=440
Screenshot with unfolded sidebar:
https://media.discordapp.net/attachments/1036248150907826282/1048229335548559390/Screenshot_2022-12-02_at_14-25-12_Cashylte.png?width=878&height=440
|
[
"It seems that this could be solved by styling the layout of body to contain the sidebar and the display div, for example perhaps try give body a grid layout:\nbody {\n display: grid;\n /* Column names are optional and added just so it is more clear here */\n grid-template-columns: [side-start] min-content [side-end main-start] 1fr [main-end];\n}\n\nAnd specify display to take the main column:\n.display {\n /* Specify this to be placed in the main column */\n grid-column: main;\n color: #ff328e;\n text-align: center;\n background: rgba(10, 10, 10, 0.65);\n box-shadow: 0 8px 32px rgb(2, 4, 24);\n border: 2px solid rgba(255, 255, 255, 0.09);\n padding: 10px;\n}\n\nThere might be easier approaches or other issues that needed to be addressed, but hopefully this would still help as a reference.\n"
] |
[
0
] |
[] |
[] |
[
"css",
"html",
"javascript"
] |
stackoverflow_0074661996_css_html_javascript.txt
|
Q:
TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
i have this error when i trying use the update component with my app, and i don't know, why is that error
Error:
TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
at HttpHeaders.applyUpdate (http.mjs:244:22)
at http.mjs:211:56
at Array.forEach (<anonymous>)
at HttpHeaders.init (http.mjs:211:33)
at HttpHeaders.forEach (http.mjs:274:14)
at Observable._subscribe (http.mjs:1811:25)
at Observable._trySubscribe (Observable.js:37:25)
at Observable.js:31:30
at errorContext (errorContext.js:19:9)
at Observable.subscribe (Observable.js:22:21)
And this is the code of my app, i use Laravel 9 in the Back-end, but the problem appears to me as if it were from the front, just in case i leave the code from back at the end
**UpdateComponent.ts: **
onSubmit(form:any){
this._userService.update(this.token, this.user).subscribe(
response => {
console.log(response)
},
error => {
this.status = 'error'
console.log(error)
}
)
}
ModelUser.ts:
export class User{
constructor(
public id: number,
public name: string,
public surname: string,
public role: string,
public email: string,
public password: string,
public description: string,
public image: string
){}
}
UserService.ts
update(token:any, user:any):Observable<any>{
let json = JSON.stringify(user)
let params = 'json=' + json
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded').set('Authorization', token)
return this._http.put(this.url + 'user/update', params, { headers: headers })
}
UserController/update.php
public function update(Request $request){
//Recoger los datos por POST
$json = $request->input('json', null);
$params_array = json_decode($json, true);
if($checkToken && !empty($params_array)){
//Sacar usuario identificado
$user = $jwtAuth->checkToken($token, true);
//Validar los datos
$validate = \Validator::make($params_array, [
'name' => 'required|alpha',
'surname' => 'required|alpha',
'email' => 'required|email|unique:users,'.$user->sub
]);
//Quitar los campos que no se actualizan
unset($params_array['id']);
unset($params_array['role']);
unset($params_array['password']);
unset($params_array['created_at']);
unset($params_array['remember_token']);
//Actualizar el usuario en la DB
$user_update = User::where('id', $user->sub)->update($params_array);
//Devolver array con resultado
$data = array(
'code' => 200,
'status' => 'success',
'user' => $user,
'changes' => $params_array
);
}else{
$data = array(
'code' => 400,
'status' => 'error',
'message' => 'Usuario no identificado'
);
}
return response()->json($data, $data['code']);
}
A:
The error appears to be related to the spread syntax used in the HttpHeaders.applyUpdate() method. You may need to update your code to use the spread syntax properly. Alternatively, you can use the HttpHeaders.set() method, which allows you to set a single header value instead of multiple ones.
|
TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
|
i have this error when i trying use the update component with my app, and i don't know, why is that error
Error:
TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
at HttpHeaders.applyUpdate (http.mjs:244:22)
at http.mjs:211:56
at Array.forEach (<anonymous>)
at HttpHeaders.init (http.mjs:211:33)
at HttpHeaders.forEach (http.mjs:274:14)
at Observable._subscribe (http.mjs:1811:25)
at Observable._trySubscribe (Observable.js:37:25)
at Observable.js:31:30
at errorContext (errorContext.js:19:9)
at Observable.subscribe (Observable.js:22:21)
And this is the code of my app, i use Laravel 9 in the Back-end, but the problem appears to me as if it were from the front, just in case i leave the code from back at the end
**UpdateComponent.ts: **
onSubmit(form:any){
this._userService.update(this.token, this.user).subscribe(
response => {
console.log(response)
},
error => {
this.status = 'error'
console.log(error)
}
)
}
ModelUser.ts:
export class User{
constructor(
public id: number,
public name: string,
public surname: string,
public role: string,
public email: string,
public password: string,
public description: string,
public image: string
){}
}
UserService.ts
update(token:any, user:any):Observable<any>{
let json = JSON.stringify(user)
let params = 'json=' + json
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded').set('Authorization', token)
return this._http.put(this.url + 'user/update', params, { headers: headers })
}
UserController/update.php
public function update(Request $request){
//Recoger los datos por POST
$json = $request->input('json', null);
$params_array = json_decode($json, true);
if($checkToken && !empty($params_array)){
//Sacar usuario identificado
$user = $jwtAuth->checkToken($token, true);
//Validar los datos
$validate = \Validator::make($params_array, [
'name' => 'required|alpha',
'surname' => 'required|alpha',
'email' => 'required|email|unique:users,'.$user->sub
]);
//Quitar los campos que no se actualizan
unset($params_array['id']);
unset($params_array['role']);
unset($params_array['password']);
unset($params_array['created_at']);
unset($params_array['remember_token']);
//Actualizar el usuario en la DB
$user_update = User::where('id', $user->sub)->update($params_array);
//Devolver array con resultado
$data = array(
'code' => 200,
'status' => 'success',
'user' => $user,
'changes' => $params_array
);
}else{
$data = array(
'code' => 400,
'status' => 'error',
'message' => 'Usuario no identificado'
);
}
return response()->json($data, $data['code']);
}
|
[
"The error appears to be related to the spread syntax used in the HttpHeaders.applyUpdate() method. You may need to update your code to use the spread syntax properly. Alternatively, you can use the HttpHeaders.set() method, which allows you to set a single header value instead of multiple ones.\n"
] |
[
0
] |
[] |
[] |
[
"angularjs",
"javascript",
"laravel_9",
"typescript"
] |
stackoverflow_0074662303_angularjs_javascript_laravel_9_typescript.txt
|
Q:
Image won't appear from www folder in Shiny App
I'm following the code from this previous question: R Shiny add picture to box in fluid row with text
Here is my code:
box(title = "Instructions",
status = "primary",
solidHeader = F,
collapsible = F,
width = 12,
fluidRow(column(width=10,textOutput("instructions")),
column(width=2, align="center",
img(src="no1.jpeg", width=100))))
server <- function(input, output) {
output$instructions <-renderText(print("test"))}
##Create and Run Shiny App Object---------------
shinyApp(ui, server)
runApp("~/shinyapp")
I think the location of my www folder is wrong. I put it in the same folder as my .Rpoj. I'm using a Mac
/Users/myname/Desktop/ProjFolder/www:
I'm really not sure where else to put it, or how to get to the place where I need to put the www folder.
A:
The www folder should be in the same directory as the app.R file if your app is invoked with runApp("path/to/appfolder"). Your working directory only matters if you run shinyApp(ui, server) directly in the console. That is because runApp changes your working directory temporarily to the appfolder you point to.
If you want to use an absolute path to an image you can use addResourcePath like so
addResourcePath(prefix = 'pics', directoryPath = '~/pictures')
ui <- fluidPage(
tags$img(src = "pics/my_picture.jpg") ## use the prefix defined in
## addResourcePath
)
server <- function(...) { }
shinyApp(ui, server)
addResourcePath can also be used to load JavaScript and CSS resources into your app.
More on runApp()
Since this came up in the comments, I want to clarify some things about the behavior of shiny::runApp(). The first argument of this function can either be a path to an app or an app object. Examples
dummy_app <- shinyApp(getwd(), function(...) {})
runApp("path/to/appfolder") # path
runApp("path/to/app.R") # path
runApp(dummy_app) # app object
If a path is used, runApp() will change the working directory to the app directory (path/to/appfolder or path/to) until the app is finished. If an app object is passed, the current working directory is used as-is.
If an app object is printed as in
class(dummy_app)
#> [1] "shiny.appobj"
dummy_app
this will invoke shiny:::print.shiny.appobj which references to runApp(<appobj>) so again, the working directory is preserved.
A:
Check out the suggestion here. Solved the issue for me.
Move the "www" folder to "inst" and create a new R script containing the following in the folder .R.
.onLoad <- function(libname, pkgname) {
shiny::addResourcePath(
prefix = "www",
directoryPath = system.file(
"www",
package = "name of your package"
)
)
}
.onUnload <- function(lib name, pkgname) {
shiny::removeResourcePath("www")
}
When referring to images in the UI, it should look like this:
img(src = "www/image.jpg") # prefix + filename
|
Image won't appear from www folder in Shiny App
|
I'm following the code from this previous question: R Shiny add picture to box in fluid row with text
Here is my code:
box(title = "Instructions",
status = "primary",
solidHeader = F,
collapsible = F,
width = 12,
fluidRow(column(width=10,textOutput("instructions")),
column(width=2, align="center",
img(src="no1.jpeg", width=100))))
server <- function(input, output) {
output$instructions <-renderText(print("test"))}
##Create and Run Shiny App Object---------------
shinyApp(ui, server)
runApp("~/shinyapp")
I think the location of my www folder is wrong. I put it in the same folder as my .Rpoj. I'm using a Mac
/Users/myname/Desktop/ProjFolder/www:
I'm really not sure where else to put it, or how to get to the place where I need to put the www folder.
|
[
"The www folder should be in the same directory as the app.R file if your app is invoked with runApp(\"path/to/appfolder\"). Your working directory only matters if you run shinyApp(ui, server) directly in the console. That is because runApp changes your working directory temporarily to the appfolder you point to.\nIf you want to use an absolute path to an image you can use addResourcePath like so\naddResourcePath(prefix = 'pics', directoryPath = '~/pictures')\nui <- fluidPage(\n tags$img(src = \"pics/my_picture.jpg\") ## use the prefix defined in\n ## addResourcePath\n)\nserver <- function(...) { }\nshinyApp(ui, server)\n\naddResourcePath can also be used to load JavaScript and CSS resources into your app.\nMore on runApp()\nSince this came up in the comments, I want to clarify some things about the behavior of shiny::runApp(). The first argument of this function can either be a path to an app or an app object. Examples\ndummy_app <- shinyApp(getwd(), function(...) {})\nrunApp(\"path/to/appfolder\") # path\nrunApp(\"path/to/app.R\") # path\nrunApp(dummy_app) # app object\n\nIf a path is used, runApp() will change the working directory to the app directory (path/to/appfolder or path/to) until the app is finished. If an app object is passed, the current working directory is used as-is.\nIf an app object is printed as in\nclass(dummy_app)\n#> [1] \"shiny.appobj\"\ndummy_app\n\nthis will invoke shiny:::print.shiny.appobj which references to runApp(<appobj>) so again, the working directory is preserved.\n",
"Check out the suggestion here. Solved the issue for me.\nMove the \"www\" folder to \"inst\" and create a new R script containing the following in the folder .R.\n.onLoad <- function(libname, pkgname) {\n shiny::addResourcePath(\n prefix = \"www\",\n directoryPath = system.file(\n \"www\",\n package = \"name of your package\"\n )\n )\n}\n\n.onUnload <- function(lib name, pkgname) {\n shiny::removeResourcePath(\"www\")\n}\n\nWhen referring to images in the UI, it should look like this:\nimg(src = \"www/image.jpg\") # prefix + filename\n\n"
] |
[
12,
0
] |
[] |
[] |
[
"shiny"
] |
stackoverflow_0051561179_shiny.txt
|
Q:
Single sign on failing with LinkedIn account to a microsoft website
We are seeing an issue with users unable to access our production and PPE apps via LinkedIn sign in. The redirection is not happening to specified redirect URL once users provides user name and password. The network trace shows login is successful but not going to redirect URL. This has been working last 4 years or so and suddenly started failing in both environments from yesterday.
Bummer. Something went wrong
We tried verifying the network trace and a support case is raised to LinkedIn with recording. Finally we are redirected to raise the issue here.
A:
I had the same issue and found that it was caused by using JSON.stringify to "overload" the state parameter with other parameters. In my case, I add other parameters in the following way:
providerCfg.auth_params.state = JSON.stringify({
state: providerCfg.auth_params.state,
redirectPageUrl,
redirectParams,
userTypeBit,
isLogin
})
const authUrl = new URL(providerCfg.auth_url)
Object.entries(providerCfg.auth_params).forEach(([key, val]) => {
authUrl.searchParams.append(key, encodeURIComponent(val))
})
return buildURL(providerCfg.auth_url, providerCfg.auth_params)
When I removed the call to JSON.stringify and just passed in a state parameter, the oauth flow worked correctly. Obviously, the other parameters that I passed in were important so I created my own functions to serialize and deserialize the values. The code below works well for anything other than deeply nested objects. You will need to update the metaDataCfg based on your own requirements.
const META_STRING_DELIMITER = '|'
const serializeBasicObject = (targetObj) => {
if (!targetObj) {
return ''
}
return Object.entries(targetObj).reduce((objString, [key, val]) => {
const param = `${key}=${val || ''}`
if (!objString.length) {
return param
}
return `${objString}${META_STRING_DELIMITER}${param}`
}, '')
}
const deserializeBasicObject = (targetStr) => {
if (!targetStr) {
return ''
}
const keyValPairs = targetStr.split(META_STRING_DELIMITER)
return keyValPairs.reduce((targetObj, keyValPair) => {
const splitIdx = keyValPair.indexOf('=')
const key = keyValPair.slice(0, splitIdx)
targetObj[key] = keyValPair.slice(splitIdx + 1, keyValPair.length)
return targetObj
}, {})
}
const metaDataCfg = {
state: {},
redirectPageUrl: {},
redirectParams: {
serialize: serializeBasicObject,
deserialize: deserializeBasicObject
},
userTypeBit: { deserialize: Number },
isLogin: { deserialize: dataUtil.getBoolean }
}
const getMetaString = (metaData) => {
return Object.entries(metaDataCfg).reduce((metaString, [metaDataKey, cfg]) => {
const val = (cfg.serialize) ? cfg.serialize(metaData[metaDataKey]) : metaData[metaDataKey]
const param = `${metaDataKey}=${dataUtil.isNil(val) ? '' : val}`
if (!metaString.length) {
return param
}
return `${metaString}${META_STRING_DELIMITER}${param}`
}, '')
}
export const getDataFromMetaString = (metaString) => {
const params = metaString.split(META_STRING_DELIMITER)
const data = params.reduce((metaData, param) => {
const splitIdx = param.indexOf('=')
const key = param.slice(0, splitIdx)
let val = param.slice(splitIdx + 1, param.length)
if (dataUtil.isNil(val) || !val.length) {
return metaData
}
const deserializer = metaDataCfg[key].deserialize
if (deserializer && val) {
val = deserializer(val)
}
metaData[key] = val
return metaData
}, {})
return data
}
|
Single sign on failing with LinkedIn account to a microsoft website
|
We are seeing an issue with users unable to access our production and PPE apps via LinkedIn sign in. The redirection is not happening to specified redirect URL once users provides user name and password. The network trace shows login is successful but not going to redirect URL. This has been working last 4 years or so and suddenly started failing in both environments from yesterday.
Bummer. Something went wrong
We tried verifying the network trace and a support case is raised to LinkedIn with recording. Finally we are redirected to raise the issue here.
|
[
"I had the same issue and found that it was caused by using JSON.stringify to \"overload\" the state parameter with other parameters. In my case, I add other parameters in the following way:\nproviderCfg.auth_params.state = JSON.stringify({\n state: providerCfg.auth_params.state,\n redirectPageUrl,\n redirectParams,\n userTypeBit,\n isLogin\n})\nconst authUrl = new URL(providerCfg.auth_url)\nObject.entries(providerCfg.auth_params).forEach(([key, val]) => {\n authUrl.searchParams.append(key, encodeURIComponent(val))\n})\nreturn buildURL(providerCfg.auth_url, providerCfg.auth_params)\n\nWhen I removed the call to JSON.stringify and just passed in a state parameter, the oauth flow worked correctly. Obviously, the other parameters that I passed in were important so I created my own functions to serialize and deserialize the values. The code below works well for anything other than deeply nested objects. You will need to update the metaDataCfg based on your own requirements.\nconst META_STRING_DELIMITER = '|'\nconst serializeBasicObject = (targetObj) => {\n if (!targetObj) {\n return ''\n }\n return Object.entries(targetObj).reduce((objString, [key, val]) => {\n const param = `${key}=${val || ''}`\n if (!objString.length) {\n return param\n }\n return `${objString}${META_STRING_DELIMITER}${param}`\n }, '')\n}\n\nconst deserializeBasicObject = (targetStr) => {\n if (!targetStr) {\n return ''\n }\n const keyValPairs = targetStr.split(META_STRING_DELIMITER)\n return keyValPairs.reduce((targetObj, keyValPair) => {\n const splitIdx = keyValPair.indexOf('=')\n const key = keyValPair.slice(0, splitIdx)\n targetObj[key] = keyValPair.slice(splitIdx + 1, keyValPair.length)\n return targetObj\n }, {})\n}\n\nconst metaDataCfg = {\n state: {},\n redirectPageUrl: {},\n redirectParams: {\n serialize: serializeBasicObject,\n deserialize: deserializeBasicObject\n },\n userTypeBit: { deserialize: Number },\n isLogin: { deserialize: dataUtil.getBoolean }\n}\n\nconst getMetaString = (metaData) => {\n return Object.entries(metaDataCfg).reduce((metaString, [metaDataKey, cfg]) => {\n const val = (cfg.serialize) ? cfg.serialize(metaData[metaDataKey]) : metaData[metaDataKey]\n const param = `${metaDataKey}=${dataUtil.isNil(val) ? '' : val}`\n if (!metaString.length) {\n return param\n }\n return `${metaString}${META_STRING_DELIMITER}${param}`\n }, '')\n}\n\nexport const getDataFromMetaString = (metaString) => {\n const params = metaString.split(META_STRING_DELIMITER)\n const data = params.reduce((metaData, param) => {\n const splitIdx = param.indexOf('=')\n const key = param.slice(0, splitIdx)\n let val = param.slice(splitIdx + 1, param.length)\n if (dataUtil.isNil(val) || !val.length) {\n return metaData\n }\n const deserializer = metaDataCfg[key].deserialize\n if (deserializer && val) {\n val = deserializer(val)\n }\n metaData[key] = val\n return metaData\n }, {})\n return data\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"linkedin",
"oauth",
"single_sign_on"
] |
stackoverflow_0074569081_linkedin_oauth_single_sign_on.txt
|
Q:
Multi Level Bash Completion
I currently have a Bash completion file which completes a single parameter from a list of allowed commands for a script called pbt. This is the working Bash completion file:
_pbt_complete()
{
local cur goals
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
goals='asadmin clean deploy'
cur=`echo $cur`
COMPREPLY=($(compgen -W "${goals}" ${cur}))
}
complete -F _pbt_complete pbt
So if I call
pbt <tab>
Bash completes to all allowed commands (asadmin, clean, deploy), which is okay. Now I want to add a second level to the completion. So for example if I type
pbt asadmin <tab>
I want it to complete only options that are available inside the asadmin "environment" (which I'll also define inside the Bash completion file). For example pbt asadmin [start-domain|stop-domain]. But if I type
pbt deploy <tab>
It should complete to another set of options. For example, pbt deploy [all|current]. So the options for the second command should always depend on the first command.
How can I do that in the completion file?
A:
Thanks to mkb's comment, I looked into the p4 example, which was—unlike the Git example—simple enough for me to adapt to my case. Here is the working version which does exactly what I asked for:
have pbt &&
_pbt_complete()
{
local cur prev
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
if [ $COMP_CWORD -eq 1 ]; then
COMPREPLY=( $(compgen -W "asadmin deploy" -- $cur) )
elif [ $COMP_CWORD -eq 2 ]; then
case "$prev" in
"asadmin")
COMPREPLY=( $(compgen -W "start-domain stop-domain" -- $cur) )
;;
"deploy")
COMPREPLY=( $(compgen -W "all current" -- $cur) )
;;
*)
;;
esac
fi
return 0
} &&
complete -F _pbt_complete pbt
A:
Btw, here are two useful tips on better tab completion:
use bind 'set show-all-if-ambiguous on' # this makes only one Tab necessary to show possible completions
use this Fish-like package for Bash that automatically shows possibles and history as you type: https://superuser.com/a/1644033/388883
Here is a link the the GH repo for Debian bash-completion: https://github.com/scop/bash-completion
Q. What is the search order for the completion file of each target command?
A. The completion files of commands are looked up by the shell function __load_completion. Here, the search order in bash-completion >= 2.12 is explained.
BASH_COMPLETION_USER_DIR. The subdirectory completions of each paths in BASH_COMPLETION_USER_DIR separated by colons is considered for a completion directory.
The location of the main bash_completion file. The subdirectory completions in the same directory as bash_completion is considered.
The location of the target command. When the real location of the command is in the directory /bin or /sbin, the directory /share/bash-completion/completions is considered.
XDG_DATA_DIRS (or the system directories /usr/local/share:/usr/share if empty). The subdirectory bash-completion/completions of each paths in XDG_DATA_DIRS separated by colons is considered.
The completion files of the name or .bash, where is the name of the target command, are searched in the above completion directories in order. The file that is found first is used. When no completion file is found in any completion directories in this process, the completion files of the name _ is next searched in the completion directories in order.
A:
You may want to look at how the completion for git is done, as an example. (This takes 2257 lines of function definitions and additional 14 variables in my bash setup.)
|
Multi Level Bash Completion
|
I currently have a Bash completion file which completes a single parameter from a list of allowed commands for a script called pbt. This is the working Bash completion file:
_pbt_complete()
{
local cur goals
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
goals='asadmin clean deploy'
cur=`echo $cur`
COMPREPLY=($(compgen -W "${goals}" ${cur}))
}
complete -F _pbt_complete pbt
So if I call
pbt <tab>
Bash completes to all allowed commands (asadmin, clean, deploy), which is okay. Now I want to add a second level to the completion. So for example if I type
pbt asadmin <tab>
I want it to complete only options that are available inside the asadmin "environment" (which I'll also define inside the Bash completion file). For example pbt asadmin [start-domain|stop-domain]. But if I type
pbt deploy <tab>
It should complete to another set of options. For example, pbt deploy [all|current]. So the options for the second command should always depend on the first command.
How can I do that in the completion file?
|
[
"Thanks to mkb's comment, I looked into the p4 example, which was—unlike the Git example—simple enough for me to adapt to my case. Here is the working version which does exactly what I asked for:\nhave pbt &&\n_pbt_complete()\n{\n local cur prev\n\n COMPREPLY=()\n cur=${COMP_WORDS[COMP_CWORD]}\n prev=${COMP_WORDS[COMP_CWORD-1]}\n\n if [ $COMP_CWORD -eq 1 ]; then\n COMPREPLY=( $(compgen -W \"asadmin deploy\" -- $cur) )\n elif [ $COMP_CWORD -eq 2 ]; then\n case \"$prev\" in\n \"asadmin\")\n COMPREPLY=( $(compgen -W \"start-domain stop-domain\" -- $cur) )\n ;;\n \"deploy\")\n COMPREPLY=( $(compgen -W \"all current\" -- $cur) )\n ;;\n *)\n ;;\n esac\n fi\n\n return 0\n} &&\ncomplete -F _pbt_complete pbt\n\n",
"Btw, here are two useful tips on better tab completion:\n\nuse bind 'set show-all-if-ambiguous on' # this makes only one Tab necessary to show possible completions\nuse this Fish-like package for Bash that automatically shows possibles and history as you type: https://superuser.com/a/1644033/388883\n\nHere is a link the the GH repo for Debian bash-completion: https://github.com/scop/bash-completion\nQ. What is the search order for the completion file of each target command?\nA. The completion files of commands are looked up by the shell function __load_completion. Here, the search order in bash-completion >= 2.12 is explained.\n\nBASH_COMPLETION_USER_DIR. The subdirectory completions of each paths in BASH_COMPLETION_USER_DIR separated by colons is considered for a completion directory.\nThe location of the main bash_completion file. The subdirectory completions in the same directory as bash_completion is considered.\nThe location of the target command. When the real location of the command is in the directory /bin or /sbin, the directory /share/bash-completion/completions is considered.\nXDG_DATA_DIRS (or the system directories /usr/local/share:/usr/share if empty). The subdirectory bash-completion/completions of each paths in XDG_DATA_DIRS separated by colons is considered.\n\nThe completion files of the name or .bash, where is the name of the target command, are searched in the above completion directories in order. The file that is found first is used. When no completion file is found in any completion directories in this process, the completion files of the name _ is next searched in the completion directories in order.\n",
"You may want to look at how the completion for git is done, as an example. (This takes 2257 lines of function definitions and additional 14 variables in my bash setup.)\n"
] |
[
35,
2,
1
] |
[] |
[] |
[
"bash",
"bash_completion"
] |
stackoverflow_0005302650_bash_bash_completion.txt
|
Q:
why this function is not working in Kotlin
fun nonSpaceString(s: String): String {
var result = " "
for (index in 0..s.length-1) {
if (s[index] != ' ') {
result += s[index]
}
}
return result
}
fun main(){
nonSpaceString("abc d e")
}
I tried to eleminate spaces in string.
but result is holding "a" and then holding "ab" but at the end result holds nothing
|
why this function is not working in Kotlin
|
fun nonSpaceString(s: String): String {
var result = " "
for (index in 0..s.length-1) {
if (s[index] != ' ') {
result += s[index]
}
}
return result
}
fun main(){
nonSpaceString("abc d e")
}
I tried to eleminate spaces in string.
but result is holding "a" and then holding "ab" but at the end result holds nothing
|
[] |
[] |
[
"You have initialized the result with a space character. So the result starts with a space that may confuse you. Apart from that, your function is working fine.\nAdditionally, you can use the replace function to remove all spaces from a string\n\"abc d e\".replace(\"\\\\s+\".toRegex(), \"\")\n\n"
] |
[
-1
] |
[
"function",
"java",
"kotlin"
] |
stackoverflow_0074660175_function_java_kotlin.txt
|
Q:
Any way to force PyCharm to refresh its understanding of a virtual environment, other than quit & restart?
I'm using PyCharm 3.4.1, and I've configured it to use an interpreter from a Python 3.4 venv.
However, when I do an external "pip install" of additional packages to the venv, PyCharm's code analysis still highlights references as being unsatisfied. (Most recently, after installing a package as editable source.)
Quitting & restarting resolves the issue. But is there any other way to kick/refresh PyCharm's idea of what's available to the venv interpreter?
A:
Help > Find Action:
→ Rescan Available Python Modules and Packages
Available from PyCharm 2020.1.2 (YouTrack Issue)
A:
I was able to solve this by editing the interpreter path of the environment you are using, then editing it back and applying. Still not perfect, but you don't have to restart PyCharm.
You can edit it in Preferences/Project/Project Interpreter. Click on cog wheel next to the dropdown interpreters.
A:
I tried using the terminal in Pycharm. It worked for me.If not you can try below
Interpreter Settings..
Look for the packages updated, if not press "+" and add.
Python Interpreter
A:
For Anaconda env, please make sure, you're pip install some_package with pip.exe from the correct environment, i.e.:
c:\Users\some_user\.conda\envs\py38\Scripts\pip.exe install some_package
A:
What works for me is pressing File->Reload all from disk
(or simply Ctrl+Alt+Y)
A:
I had similar issues but with replacing venv in PyCharm. First, I initialized venv with one version of Python. I opened PyCharm and it has been cached somewhere. I removed venv and created another one with different Python version. Unfortunately I PyCharm was still using the old, not existing venv.
I needed to add existing interpreter, coming from venv:
Pycharm / Settings
Project <> / Python Interpreter
Open the list, Show all
Choose the one connected to the project (the cached one) and remove it. Click ok
Add Interpreter / Add Local Interpreter
Environment: Existing
Path: <path to your project>/venv/bin/python
|
Any way to force PyCharm to refresh its understanding of a virtual environment, other than quit & restart?
|
I'm using PyCharm 3.4.1, and I've configured it to use an interpreter from a Python 3.4 venv.
However, when I do an external "pip install" of additional packages to the venv, PyCharm's code analysis still highlights references as being unsatisfied. (Most recently, after installing a package as editable source.)
Quitting & restarting resolves the issue. But is there any other way to kick/refresh PyCharm's idea of what's available to the venv interpreter?
|
[
"Help > Find Action:\n→ Rescan Available Python Modules and Packages\nAvailable from PyCharm 2020.1.2 (YouTrack Issue)\n",
"I was able to solve this by editing the interpreter path of the environment you are using, then editing it back and applying. Still not perfect, but you don't have to restart PyCharm.\nYou can edit it in Preferences/Project/Project Interpreter. Click on cog wheel next to the dropdown interpreters.\n",
"I tried using the terminal in Pycharm. It worked for me.If not you can try below\nInterpreter Settings..\nLook for the packages updated, if not press \"+\" and add.\nPython Interpreter\n",
"For Anaconda env, please make sure, you're pip install some_package with pip.exe from the correct environment, i.e.:\nc:\\Users\\some_user\\.conda\\envs\\py38\\Scripts\\pip.exe install some_package\n\n",
"What works for me is pressing File->Reload all from disk\n(or simply Ctrl+Alt+Y)\n",
"I had similar issues but with replacing venv in PyCharm. First, I initialized venv with one version of Python. I opened PyCharm and it has been cached somewhere. I removed venv and created another one with different Python version. Unfortunately I PyCharm was still using the old, not existing venv.\nI needed to add existing interpreter, coming from venv:\n\nPycharm / Settings\nProject <> / Python Interpreter\nOpen the list, Show all\nChoose the one connected to the project (the cached one) and remove it. Click ok\nAdd Interpreter / Add Local Interpreter\nEnvironment: Existing\nPath: <path to your project>/venv/bin/python\n\n"
] |
[
19,
5,
1,
0,
0,
0
] |
[] |
[] |
[
"pycharm"
] |
stackoverflow_0025761273_pycharm.txt
|
Q:
error Code 404 not found when run project from root from public run normal
In my issue when i am try to call any route from subdomain root return laravel error 404 not Found
however when i am try to run project from subfolder /public inside project run normal and route call normal
for example :
when i am call url : www.example.com/myprojectroot
Return : 404 not found like screenshot
enter image description here
But when i am call any route from url : www.example.com/myprojectroot/public/anydefine route
in this case route call normal but some assest not working
so that i need to call any route from main root not from subfolder public how can i do that
and this my .htaccess code on subdomain root
`
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
I AM TRY TO CHANGE ON .HTACCESS BUT RETURN 403 FORBIDDEN
A:
I think you are using Apache. Try to add this to its configuration (Usually its here /etc/httpd/conf/httpd. conf)
<Directory /var/www/yourproject/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
And you also need to enable pretty urls (I think your laravel version is old)
https://laravel.com/docs/5.0/configuration#pretty-urls
|
error Code 404 not found when run project from root from public run normal
|
In my issue when i am try to call any route from subdomain root return laravel error 404 not Found
however when i am try to run project from subfolder /public inside project run normal and route call normal
for example :
when i am call url : www.example.com/myprojectroot
Return : 404 not found like screenshot
enter image description here
But when i am call any route from url : www.example.com/myprojectroot/public/anydefine route
in this case route call normal but some assest not working
so that i need to call any route from main root not from subfolder public how can i do that
and this my .htaccess code on subdomain root
`
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
I AM TRY TO CHANGE ON .HTACCESS BUT RETURN 403 FORBIDDEN
|
[
"I think you are using Apache. Try to add this to its configuration (Usually its here /etc/httpd/conf/httpd. conf)\n<Directory /var/www/yourproject/> \n Options Indexes FollowSymLinks\n AllowOverride All\n Require all granted\n</Directory>\n\nAnd you also need to enable pretty urls (I think your laravel version is old)\nhttps://laravel.com/docs/5.0/configuration#pretty-urls\n"
] |
[
0
] |
[] |
[] |
[
"404_page",
"laravel",
"php",
"routes"
] |
stackoverflow_0074662377_404_page_laravel_php_routes.txt
|
Q:
Laravel ::pluck multiple columns
I need to populate a blade format <select> tag.
I'm aware of the Model::pluck('column1', 'column2') method to populate a select tag.
But in my case, I have to concatenate two columns , and get the id. something like
Model::pluck('column_1 && column_2', 'id')
Is it possible like that ? If yes, what would be the proper syntax?
If not, what would be the best alternative then ?
A:
Best solution is to create accessor function into your model, let's assume if you want to get full name then you can do like this.
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
and you can easily get full name.
$users = User::where('id', 1)->get()->pluck('full_name', 'id');
Eloquent will call getFullNameAttribute function and get concatenated value.
A:
You could use selectRaw():
Model::selectRaw("CONCAT ('column1', 'column2') as columns, id")->pluck('columns', 'id');
Or you could do this manually:
$collection = Model::get(['column1', 'column2', 'id']);
foreach ($collection as $item) {
$plucked[$item->id] = $item->column1 . $item->column2;
}
dd($plucked);
A:
Model results retrieved by the get() method are just children of the regular Support-Collection class, so you actually get access to all the same goodies. Try this:
$eloquentCollection = app(YourModel::class)
->where('field', 'value')
->get(['id', 'column_1', 'column_2']);
$mapped = $eloquentCollection->mapWithKeys(function (YourModel $model) {
return [$model->id => $model->column_1 . $model->column_2];
})
A:
Another simple way:
return User::select(DB::raw('CONCAT(first_name, " - ", last_name) AS full_name, id'))
->pluck('full_name', 'id');
A:
Just so people who come here know, the pluck method returns an object, and if you want to pluck multiple columns and return an array at the same time without using the toArray method, you could just pass the names of the column to the all() function, and it will return the wanted columns as an array.
YourModelName::all('id', 'name');
A:
It's pretty late but you could do something like this:
$data = Model::select('id','column_1','column_2')->get()
and then use it inside blade like:
$data->first_name." ".$data->last_name
A:
You can select the columns of your choice with this:
YourModel::select('column1', 'columns2')->whereColumnId('1')->get()
->map(function($model){
return $model->column1.','.$model->column2;
})->toArray();
|
Laravel ::pluck multiple columns
|
I need to populate a blade format <select> tag.
I'm aware of the Model::pluck('column1', 'column2') method to populate a select tag.
But in my case, I have to concatenate two columns , and get the id. something like
Model::pluck('column_1 && column_2', 'id')
Is it possible like that ? If yes, what would be the proper syntax?
If not, what would be the best alternative then ?
|
[
"Best solution is to create accessor function into your model, let's assume if you want to get full name then you can do like this.\npublic function getFullNameAttribute()\n{\n return $this->first_name . ' ' . $this->last_name;\n}\n\nand you can easily get full name.\n$users = User::where('id', 1)->get()->pluck('full_name', 'id');\n\nEloquent will call getFullNameAttribute function and get concatenated value.\n",
"You could use selectRaw():\nModel::selectRaw(\"CONCAT ('column1', 'column2') as columns, id\")->pluck('columns', 'id');\n\nOr you could do this manually:\n$collection = Model::get(['column1', 'column2', 'id']);\nforeach ($collection as $item) {\n $plucked[$item->id] = $item->column1 . $item->column2;\n}\ndd($plucked);\n\n",
"Model results retrieved by the get() method are just children of the regular Support-Collection class, so you actually get access to all the same goodies. Try this:\n$eloquentCollection = app(YourModel::class)\n ->where('field', 'value')\n ->get(['id', 'column_1', 'column_2']);\n\n$mapped = $eloquentCollection->mapWithKeys(function (YourModel $model) {\n return [$model->id => $model->column_1 . $model->column_2];\n})\n\n",
"Another simple way:\n return User::select(DB::raw('CONCAT(first_name, \" - \", last_name) AS full_name, id'))\n ->pluck('full_name', 'id');\n\n",
"Just so people who come here know, the pluck method returns an object, and if you want to pluck multiple columns and return an array at the same time without using the toArray method, you could just pass the names of the column to the all() function, and it will return the wanted columns as an array.\nYourModelName::all('id', 'name');\n\n",
"It's pretty late but you could do something like this:\n$data = Model::select('id','column_1','column_2')->get()\nand then use it inside blade like:\n$data->first_name.\" \".$data->last_name\n",
"You can select the columns of your choice with this:\nYourModel::select('column1', 'columns2')->whereColumnId('1')->get() \n ->map(function($model){\n return $model->column1.','.$model->column2;\n })->toArray();\n\n"
] |
[
39,
6,
4,
1,
0,
0,
0
] |
[] |
[] |
[
"laravel",
"laravel_5"
] |
stackoverflow_0049188577_laravel_laravel_5.txt
|
Q:
Apollo cache update is not reflected on paginated query
I have two components, one of the components creates new items, the other one displays them using an "infinite scroll list". These two components do not have a parent/child relationship and they're not rendered at the same time (they're on different "pages").
I've followed these docs and included the modified object in the mutation of my first component. And I can see the new object in the Apollo cache using dev tools. (Car:<some UUID> gets added in the cache after the mutation runs)
My paginated component is configured with relay style pagination, and the pagination works fine, but when I add a new item it doesn't appear in the list until I refresh the page.
My InMemoryCache looks like this:
...
typePolicies: {
// paginated results
Query: {
fields: {
cars: relayStylePagination()
}
},
CarsResult: {
fields: {
edges: {
// Concatenate the incoming list items with
// the existing list items.
merge(existing = [], incoming) {
return [...existing, ...incoming]
}
}
}
},
PageInfo: {
fields: {
endCursor: {
merge(existing, incoming) {
return incoming
}
}
}
}
}
The mutation looks like this:
${CAR_SUMMARY_FRAGMENT}
mutation CreateCar($name: String!) {
createCar(
input: {
name: $name
}
) {
...CarSummary
}
}
The CreateCar return type is Car
Then my paginated query:
query CarsPaginated($after: Cursor) {
cars(
page: { first: 25, after: $after }
orderBy: { field: CREATE_TIME, direction: DESC }
) {
edges {
node {
...CarSummary
}
}
totalCount
pageInfo {
hasNextPage
endCursor
}
}
}
The CarsPaginated return type is CarsResult:
type CarsResult {
edges: [CarEdge]
pageInfo: PageInfo!
totalCount: Int!
}
type CarEdge {
node: Car
cursor: Cursor!
}
Ideally, I'd like the new item to show up at the top of my items list on the other component.
I've tried to use the "refetchQueries" attribute but the paginated query is not active since the list component is not rendered at that time.
Maybe there's something I need to do in the typePolicies?
A:
It sounds like you're using Apollo Client and you're running into some issues with your paginated query not updating when you add a new item.
One solution to this problem would be to use the refetchQueries option in your mutation to refetch the paginated query after you create the new item. The refetchQueries option takes an array of query names or query options objects that you want to refetch after the mutation has completed.
Here's how you could use the refetchQueries option in your mutation:
mutation CreateCar($name: String!) {
createCar(
input: {
name: $name
}
) {
...CarSummary
}
}
refetchQueries: ['CarsPaginated']
This will cause Apollo Client to refetch the CarsPaginated query after the mutation has completed, which will update the paginated results in your cache and update the component that displays the list of cars.
|
Apollo cache update is not reflected on paginated query
|
I have two components, one of the components creates new items, the other one displays them using an "infinite scroll list". These two components do not have a parent/child relationship and they're not rendered at the same time (they're on different "pages").
I've followed these docs and included the modified object in the mutation of my first component. And I can see the new object in the Apollo cache using dev tools. (Car:<some UUID> gets added in the cache after the mutation runs)
My paginated component is configured with relay style pagination, and the pagination works fine, but when I add a new item it doesn't appear in the list until I refresh the page.
My InMemoryCache looks like this:
...
typePolicies: {
// paginated results
Query: {
fields: {
cars: relayStylePagination()
}
},
CarsResult: {
fields: {
edges: {
// Concatenate the incoming list items with
// the existing list items.
merge(existing = [], incoming) {
return [...existing, ...incoming]
}
}
}
},
PageInfo: {
fields: {
endCursor: {
merge(existing, incoming) {
return incoming
}
}
}
}
}
The mutation looks like this:
${CAR_SUMMARY_FRAGMENT}
mutation CreateCar($name: String!) {
createCar(
input: {
name: $name
}
) {
...CarSummary
}
}
The CreateCar return type is Car
Then my paginated query:
query CarsPaginated($after: Cursor) {
cars(
page: { first: 25, after: $after }
orderBy: { field: CREATE_TIME, direction: DESC }
) {
edges {
node {
...CarSummary
}
}
totalCount
pageInfo {
hasNextPage
endCursor
}
}
}
The CarsPaginated return type is CarsResult:
type CarsResult {
edges: [CarEdge]
pageInfo: PageInfo!
totalCount: Int!
}
type CarEdge {
node: Car
cursor: Cursor!
}
Ideally, I'd like the new item to show up at the top of my items list on the other component.
I've tried to use the "refetchQueries" attribute but the paginated query is not active since the list component is not rendered at that time.
Maybe there's something I need to do in the typePolicies?
|
[
"It sounds like you're using Apollo Client and you're running into some issues with your paginated query not updating when you add a new item.\nOne solution to this problem would be to use the refetchQueries option in your mutation to refetch the paginated query after you create the new item. The refetchQueries option takes an array of query names or query options objects that you want to refetch after the mutation has completed.\nHere's how you could use the refetchQueries option in your mutation:\nmutation CreateCar($name: String!) {\n createCar(\n input: {\n name: $name\n }\n ) {\n ...CarSummary\n }\n}\n\nrefetchQueries: ['CarsPaginated']\n\nThis will cause Apollo Client to refetch the CarsPaginated query after the mutation has completed, which will update the paginated results in your cache and update the component that displays the list of cars.\n"
] |
[
0
] |
[] |
[] |
[
"apollo_client",
"react_apollo"
] |
stackoverflow_0074576851_apollo_client_react_apollo.txt
|
Q:
What does the @ symbol do to a variable? i.e. @variable name?
I (sadly) came across some old c# .NET 4.8 code that I wrote and I noticed a typo. The code has been functioning fine in production for many years, but I was wondering if there is a difference between
static public DataTable GetReportIDRange(int BeginningID, int @EndingID)
and
static public DataTable GetReportIDRange(int BeginningID, int EndingID)
I removed the @ and it is still working fine.
A:
@ allows a reserved keyword to be used as a variable name
static DataTable GetReportIDRange(int BeginningID, int @static)
{
return null;
}
but in your case, you have to check if "EndingID" is being declared as some specific type or keyword.
Normally it is always says to avoid using @ with parameters or variables but, we can have situations where third party API requesting to pass a parameter with reserved keywords, for example, lets say some API need an input and variable name has to be "event" , which is reserved keyword in C# in that case @ is helpful.
hope this clears the things in better way.
|
What does the @ symbol do to a variable? i.e. @variable name?
|
I (sadly) came across some old c# .NET 4.8 code that I wrote and I noticed a typo. The code has been functioning fine in production for many years, but I was wondering if there is a difference between
static public DataTable GetReportIDRange(int BeginningID, int @EndingID)
and
static public DataTable GetReportIDRange(int BeginningID, int EndingID)
I removed the @ and it is still working fine.
|
[
"@ allows a reserved keyword to be used as a variable name\n\nstatic DataTable GetReportIDRange(int BeginningID, int @static)\n{\n return null;\n}\n\nbut in your case, you have to check if \"EndingID\" is being declared as some specific type or keyword.\nNormally it is always says to avoid using @ with parameters or variables but, we can have situations where third party API requesting to pass a parameter with reserved keywords, for example, lets say some API need an input and variable name has to be \"event\" , which is reserved keyword in C# in that case @ is helpful.\nhope this clears the things in better way.\n"
] |
[
0
] |
[] |
[] |
[
".net",
"c#_4.0"
] |
stackoverflow_0074662432_.net_c#_4.0.txt
|
Q:
Changing value of mat-option based off a conditonal in *ngIf
I have two options for values when it comes to my mat-option
tempTime: TempOptions[] = [
{ value: 100, viewValue: '100 points' },
{ value: 200, viewValue: '200 points' }
];
tempTimesHighNumber: TempOptions[] = [
{ value: 1000, viewValue: '1000 points' },
{ value: 2000, viewValue: '2000 points' }
];
I want to set a conditional in my html based off of two variables I have:
public SentDate;
public CurrentDate;
I'm getting these values from a datepicker. My desired result is, if the dates are the same, display tempTime in mat-options
if not display temptimesHighNumber
Here is what I've tried:
<mat-form-field>
<mat-label>Tally up that score!</mat-label>
<mat-select
[(value)]="selectedTempTime"
>
<ng-container>
<mat-option
*ngIf="checkConditionSentDate === checkConditionCurrentDate"
[value]="option.value"
*ngFor="let option of tempTimes"
>{{ option.viewValue }}</mat-option
>
<mat-option
[value]="option.value"
*ngFor="let option of tempTimesIfNotTodaysDate"
>{{ option.viewValue }}</mat-option
>
</ng-container>
</mat-select>
</mat-form-field>
Here is the error I'm getting:
Can't have multiple template bindings on one element. Use only one attribute prefixed with * ("heckConditionSentDate === checkConditionCurrentDate"
What is the proper way to use *ngIf or am I approaching this the wrong way?
A:
You can wrap each mat-option with ng-container and put *ngIf on ngContainer like this :
<ng-container *ngIf="checkConditionSentDate === checkConditionCurrentDate">
<mat-option [value]="option.value"
*ngFor="let option of tempTimes">{{ option.viewValue }}
</mat-option>
</ng-container>
<ng-container *ngIf="otherCondition">
<mat-option
[value]="option.value"
*ngFor="let option of tempTimesIfNotTodaysDate"
>{{ option.viewValue }}</mat-option
>
</ng-container>
|
Changing value of mat-option based off a conditonal in *ngIf
|
I have two options for values when it comes to my mat-option
tempTime: TempOptions[] = [
{ value: 100, viewValue: '100 points' },
{ value: 200, viewValue: '200 points' }
];
tempTimesHighNumber: TempOptions[] = [
{ value: 1000, viewValue: '1000 points' },
{ value: 2000, viewValue: '2000 points' }
];
I want to set a conditional in my html based off of two variables I have:
public SentDate;
public CurrentDate;
I'm getting these values from a datepicker. My desired result is, if the dates are the same, display tempTime in mat-options
if not display temptimesHighNumber
Here is what I've tried:
<mat-form-field>
<mat-label>Tally up that score!</mat-label>
<mat-select
[(value)]="selectedTempTime"
>
<ng-container>
<mat-option
*ngIf="checkConditionSentDate === checkConditionCurrentDate"
[value]="option.value"
*ngFor="let option of tempTimes"
>{{ option.viewValue }}</mat-option
>
<mat-option
[value]="option.value"
*ngFor="let option of tempTimesIfNotTodaysDate"
>{{ option.viewValue }}</mat-option
>
</ng-container>
</mat-select>
</mat-form-field>
Here is the error I'm getting:
Can't have multiple template bindings on one element. Use only one attribute prefixed with * ("heckConditionSentDate === checkConditionCurrentDate"
What is the proper way to use *ngIf or am I approaching this the wrong way?
|
[
"You can wrap each mat-option with ng-container and put *ngIf on ngContainer like this :\n <ng-container *ngIf=\"checkConditionSentDate === checkConditionCurrentDate\">\n <mat-option [value]=\"option.value\"\n *ngFor=\"let option of tempTimes\">{{ option.viewValue }}\n </mat-option>\n </ng-container>\n <ng-container *ngIf=\"otherCondition\">\n <mat-option\n [value]=\"option.value\"\n *ngFor=\"let option of tempTimesIfNotTodaysDate\"\n >{{ option.viewValue }}</mat-option\n >\n </ng-container>\n\n"
] |
[
0
] |
[] |
[] |
[
"angular",
"angular_ng_if",
"mat_option",
"mat_select",
"typescript"
] |
stackoverflow_0074662321_angular_angular_ng_if_mat_option_mat_select_typescript.txt
|
Q:
move superposed elements in javaFX
I'm strugguling to make my javaFX program fonctionnal. I'd like some advice.
There is a drawing of what I have done:
The screen is a set of images (The little rectangles).
My goal is to put a card on the top when it is clicked.
To do so, i've set the principal contener as a StackPane.
I've thought about putting the cards directly into the StackPane but it seems that the setLayoutX and setLayoutY methods don't seem to move my images.
The solution I came out with is putting in my StackPane multiples AnchorPane (one for each card). Each AnchorPane has the size of the StackPane contener,
and contains a sigle card. Like that, I can set the position of each card.
My problem with this method is the following : because each AnchorPane has the size of the principal conteneur, the AnchorPane that contains the last card
is placed in front of the pther AnchorPanes.
Consequently, when I click on my last card, I works perfectly, but I can't click the other cards because there is a invisible Node in front of them.
It would be very nice if someone could give me some advice.
A:
Here is an example.
Click on each of the cards to play them. After all of the cards are played, the game will reset when the clicks anywhere on the playing table. Then a new hand will be dealt to the player.
It uses placeholders for empty card positions on the playing table.
For layout, it uses a VBox for the playing table and an HBox for the cards in hand.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CardApp extends Application {
private static final int NUM_CARDS = 5;
private HBox hand;
private VBox table;
private Scene scene;
@Override
public void start(Stage stage) {
scene = new Scene(deal());
stage.setScene(scene);
stage.show();
}
private Parent deal() {
List<Card> cards =
IntStream.rangeClosed(1, NUM_CARDS)
.mapToObj(Card::new)
.collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(cards);
hand = new HBox(20,
cards.toArray(new Card[0])
);
table = new VBox(30,
new CardPlaceholder(),
hand
);
table.setStyle("-fx-background-color: mintcream;");
table.setPadding(new Insets(30));
// click on cards to play them.
for (Card card: cards) {
card.setOnMouseClicked(e -> {
playCard(card, hand, table);
// when all cards are played, click anywhere to re-deal on a new table.
if (hand.getChildren().stream().noneMatch(c -> c instanceof Card)) {
table.setOnMouseClicked(me -> scene.setRoot(deal()));
}
});
}
return table;
}
private void playCard(Card card, HBox hand, VBox table) {
int index = hand.getChildren().indexOf(card);
hand.getChildren().set(index, new CardPlaceholder());
table.getChildren().set(0, card);
card.setOnMouseClicked(null);
}
static class Card extends StackPane {
public Card(int value) {
Rectangle background = new Rectangle(55, 80, Color.LIGHTSTEELBLUE);
background.setStroke(Color.LIGHTSTEELBLUE.darker());
background.setStrokeWidth(3);
background.setArcWidth(15);
background.setArcHeight(15);
Label foreground = new Label("" + value);
foreground.setStyle("-fx-font-size: 30; -fx-text-fill: rgb(60,63,74);");
getChildren().setAll(background, foreground);
}
}
static class CardPlaceholder extends StackPane {
public CardPlaceholder() {
Rectangle background = new Rectangle(
55, 80,
Color.SILVER.deriveColor(
0,1,1, .4
)
);
background.setStroke(
Color.SILVER.deriveColor(
0,1,1, .6
)
);
background.setStrokeWidth(3);
background.setArcWidth(15);
background.setArcHeight(15);
background.getStrokeDashArray().addAll(10d, 5d);
getChildren().setAll(background);
}
}
}
For simplicity in answering this limited question, everything is in one file. For a more substantial app, the game logic and game model would be separated from the UI (using MVC), the layout might be done in FXML and styling would be done via CSS.
|
move superposed elements in javaFX
|
I'm strugguling to make my javaFX program fonctionnal. I'd like some advice.
There is a drawing of what I have done:
The screen is a set of images (The little rectangles).
My goal is to put a card on the top when it is clicked.
To do so, i've set the principal contener as a StackPane.
I've thought about putting the cards directly into the StackPane but it seems that the setLayoutX and setLayoutY methods don't seem to move my images.
The solution I came out with is putting in my StackPane multiples AnchorPane (one for each card). Each AnchorPane has the size of the StackPane contener,
and contains a sigle card. Like that, I can set the position of each card.
My problem with this method is the following : because each AnchorPane has the size of the principal conteneur, the AnchorPane that contains the last card
is placed in front of the pther AnchorPanes.
Consequently, when I click on my last card, I works perfectly, but I can't click the other cards because there is a invisible Node in front of them.
It would be very nice if someone could give me some advice.
|
[
"Here is an example.\n\nClick on each of the cards to play them. After all of the cards are played, the game will reset when the clicks anywhere on the playing table. Then a new hand will be dealt to the player.\nIt uses placeholders for empty card positions on the playing table.\nFor layout, it uses a VBox for the playing table and an HBox for the cards in hand.\nimport javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Parent;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.layout.*;\nimport javafx.scene.paint.Color;\nimport javafx.scene.shape.Rectangle;\nimport javafx.stage.Stage;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class CardApp extends Application {\n private static final int NUM_CARDS = 5;\n\n private HBox hand;\n private VBox table;\n private Scene scene;\n\n @Override\n public void start(Stage stage) {\n scene = new Scene(deal());\n\n stage.setScene(scene);\n stage.show();\n }\n\n private Parent deal() {\n List<Card> cards =\n IntStream.rangeClosed(1, NUM_CARDS)\n .mapToObj(Card::new)\n .collect(Collectors.toCollection(ArrayList::new));\n Collections.shuffle(cards);\n\n hand = new HBox(20,\n cards.toArray(new Card[0])\n );\n\n table = new VBox(30,\n new CardPlaceholder(),\n hand\n );\n table.setStyle(\"-fx-background-color: mintcream;\");\n table.setPadding(new Insets(30));\n\n // click on cards to play them.\n for (Card card: cards) {\n card.setOnMouseClicked(e -> {\n playCard(card, hand, table);\n\n // when all cards are played, click anywhere to re-deal on a new table.\n if (hand.getChildren().stream().noneMatch(c -> c instanceof Card)) {\n table.setOnMouseClicked(me -> scene.setRoot(deal()));\n }\n });\n }\n\n return table;\n }\n\n private void playCard(Card card, HBox hand, VBox table) {\n int index = hand.getChildren().indexOf(card);\n hand.getChildren().set(index, new CardPlaceholder());\n table.getChildren().set(0, card);\n card.setOnMouseClicked(null);\n }\n\n static class Card extends StackPane {\n public Card(int value) {\n Rectangle background = new Rectangle(55, 80, Color.LIGHTSTEELBLUE);\n background.setStroke(Color.LIGHTSTEELBLUE.darker());\n background.setStrokeWidth(3);\n background.setArcWidth(15);\n background.setArcHeight(15);\n\n Label foreground = new Label(\"\" + value);\n foreground.setStyle(\"-fx-font-size: 30; -fx-text-fill: rgb(60,63,74);\");\n\n getChildren().setAll(background, foreground);\n }\n }\n\n static class CardPlaceholder extends StackPane {\n public CardPlaceholder() {\n Rectangle background = new Rectangle(\n 55, 80,\n Color.SILVER.deriveColor(\n 0,1,1, .4\n )\n );\n\n background.setStroke(\n Color.SILVER.deriveColor(\n 0,1,1, .6\n )\n );\n background.setStrokeWidth(3);\n background.setArcWidth(15);\n background.setArcHeight(15);\n background.getStrokeDashArray().addAll(10d, 5d);\n\n getChildren().setAll(background);\n }\n }\n}\n\nFor simplicity in answering this limited question, everything is in one file. For a more substantial app, the game logic and game model would be separated from the UI (using MVC), the layout might be done in FXML and styling would be done via CSS.\n"
] |
[
2
] |
[] |
[] |
[
"javafx"
] |
stackoverflow_0074659481_javafx.txt
|
Q:
How to concatenate all the rows linked with a same id into one row? consedring null values
I'm trying to concatenate all rows for same ID, the rows for a ID can have null or empty value:
country
value
FR
NULL
FR
1
FR
3
MA
5
MA
NULL
MA
4
ES
9
ES
10
ES
NULL
I would like to consider this case in my query to get this result:
country
value
FR
NULL,1,3
MA
4,NULL,9
ES
9,10,NULL
We can consider to replace null value to get this result
country
value
FR
,1,3
MA
4,,9
ES
9,10,
sql server version : Microsoft SQL Server 2014 (SP2-GDR) (KB4505217) - 12.0.5223.6 (X64)
I have tried this query
SELECT IDENT_0, PAYS_0 = STUFF
SELECT ', ' + TEXTE_0
FROM UAI.YORIGINELOT AS T2
LEFT JOIN UAI.ATEXTRA ON T2.YOMP_0 = ATEXTRA.IDENT1_0 AND CODFIC_0 = 'TABCOUNTRY' AND LANGUE_0 = 'FRA' And ZONE_0 = 'CRYDES'
WHERE T2.IDENT_0 = T1.IDENT_0
ORDER BY IDENT_0
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
1, 1, '')
FROM UAI.YORIGINELOT AS T1
LEFT JOIN UAI.ATEXTRA ON T1.YFABEN_0 = ATEXTRA.IDENT1_0 AND LANGUE_0='FRA' AND CODFIC_0='TABCOUNTRY' AND ZONE_0 = 'CRYDES'
WHERE OBJ_0 = 'ITM'
GROUP BY IDENT_0
Thank you
A:
Since SQLServer 2017, we can use STRING_AGG to produce the expected result.
In order to replace NULL values by any other string - even if it just should be "NULL" - we can use COALESCE.
So this query will do:
SELECT country,
STRING_AGG(COALESCE(value,'NULL'),',') AS value
FROM yourtable
GROUP BY country
ORDER BY country;
Of course, this is just a sample based on one table because I don't know your table structure. Just use this concept in your query.
The result of this query will be this one:
country
value
ES
9,10,NULL
FR
NULL,1,3
MA
5,NULL,4
Try out: db<>fiddle
Here the documentation about STRING_AGG
If you still use an older version, I highly recommend to update.
If this isn't possible, there are lot of articles (for example here on SO) how to do this with other functions.
Here one of them: Question on SO
A:
As you have SQL server 2014, you better use sTUFF
But you should consoder an upgrade, as the ned of life was Jul 9, 2019 so if you haven't an extended support, you will become vulnerable.l
SELECT country,
val =
STUFF (
(SELECT
',' +value
FROM yourtable
WHERE value IS NOT NULL AND y1.country = country
FOR XML PATH('')
), 1, 1, ''
)
FROM yourtable y1
GROUP by country
ORDER BY country
country
val
ES
9,10
FR
1,3
MA
5,4
fiddle
If you want also the NULL values represnted
SELECT country,
val =
STUFF (
(SELECT
',' + COALESCE(value,'')
FROM yourtable
WHERE y1.country = country
ORDER BY COALESCE(value,0)
FOR XML PATH('')
), 1, 1, ''
)
FROM yourtable y1
GROUP by country
ORDER BY country
country
val
ES
,9,10
FR
,1,3
MA
,4,5
fiddle
|
How to concatenate all the rows linked with a same id into one row? consedring null values
|
I'm trying to concatenate all rows for same ID, the rows for a ID can have null or empty value:
country
value
FR
NULL
FR
1
FR
3
MA
5
MA
NULL
MA
4
ES
9
ES
10
ES
NULL
I would like to consider this case in my query to get this result:
country
value
FR
NULL,1,3
MA
4,NULL,9
ES
9,10,NULL
We can consider to replace null value to get this result
country
value
FR
,1,3
MA
4,,9
ES
9,10,
sql server version : Microsoft SQL Server 2014 (SP2-GDR) (KB4505217) - 12.0.5223.6 (X64)
I have tried this query
SELECT IDENT_0, PAYS_0 = STUFF
SELECT ', ' + TEXTE_0
FROM UAI.YORIGINELOT AS T2
LEFT JOIN UAI.ATEXTRA ON T2.YOMP_0 = ATEXTRA.IDENT1_0 AND CODFIC_0 = 'TABCOUNTRY' AND LANGUE_0 = 'FRA' And ZONE_0 = 'CRYDES'
WHERE T2.IDENT_0 = T1.IDENT_0
ORDER BY IDENT_0
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
1, 1, '')
FROM UAI.YORIGINELOT AS T1
LEFT JOIN UAI.ATEXTRA ON T1.YFABEN_0 = ATEXTRA.IDENT1_0 AND LANGUE_0='FRA' AND CODFIC_0='TABCOUNTRY' AND ZONE_0 = 'CRYDES'
WHERE OBJ_0 = 'ITM'
GROUP BY IDENT_0
Thank you
|
[
"Since SQLServer 2017, we can use STRING_AGG to produce the expected result.\nIn order to replace NULL values by any other string - even if it just should be \"NULL\" - we can use COALESCE.\nSo this query will do:\nSELECT country, \nSTRING_AGG(COALESCE(value,'NULL'),',') AS value\nFROM yourtable\nGROUP BY country\nORDER BY country;\n\nOf course, this is just a sample based on one table because I don't know your table structure. Just use this concept in your query.\nThe result of this query will be this one:\n\n\n\n\ncountry\nvalue\n\n\n\n\nES\n9,10,NULL\n\n\nFR\nNULL,1,3\n\n\nMA\n5,NULL,4\n\n\n\n\nTry out: db<>fiddle\nHere the documentation about STRING_AGG\nIf you still use an older version, I highly recommend to update.\nIf this isn't possible, there are lot of articles (for example here on SO) how to do this with other functions.\nHere one of them: Question on SO\n",
"As you have SQL server 2014, you better use sTUFF\nBut you should consoder an upgrade, as the ned of life was Jul 9, 2019 so if you haven't an extended support, you will become vulnerable.l\nSELECT country,\n val = \n STUFF (\n (SELECT \n ',' +value \n FROM yourtable\n WHERE value IS NOT NULL AND y1.country = country\n FOR XML PATH('')\n \n ), 1, 1, ''\n \n )\nFROM yourtable y1\nGROUP by country\nORDER BY country\n\n\n\n\n\ncountry\nval\n\n\n\n\nES\n9,10\n\n\nFR\n1,3\n\n\nMA\n5,4\n\n\n\n\nfiddle\nIf you want also the NULL values represnted\nSELECT country,\n val = \n STUFF (\n (SELECT \n ',' + COALESCE(value,'') \n FROM yourtable\n WHERE y1.country = country\n ORDER BY COALESCE(value,0)\n FOR XML PATH('')\n \n ), 1, 1, ''\n \n )\nFROM yourtable y1\nGROUP by country\nORDER BY country\n\n\n\n\n\ncountry\nval\n\n\n\n\nES\n,9,10\n\n\nFR\n,1,3\n\n\nMA\n,4,5\n\n\n\n\nfiddle\n"
] |
[
1,
0
] |
[] |
[] |
[
"concatenation",
"null",
"sql",
"sql_server",
"unique_values"
] |
stackoverflow_0074661592_concatenation_null_sql_sql_server_unique_values.txt
|
Q:
How to Make column names the first row in r?
I have seen may tutorials on making the first row the column names, but nothing explaining how to do the reverse. I would like to have my column names as the first row values and change the column names to something like var1, var2, var3. Can this be done?
I plan to row bind a bunch of data frames later, so they all need the same column names.
q = structure(list(shootings_per100k = c(8105.47466098618, 6925.42653239307
), lawtotal = c(3.00137104283906, 0.903522788541896), felony = c(0.787418655097614,
0.409578330883717)), row.names = c("mean", "sd"), class = "data.frame")
Have:
shootings_per100k lawtotal felony
mean 8105.475 3.0013710 0.7874187
sd 6925.427 0.9035228 0.4095783
Want:
var1 var2 var3
var shootings_per100k lawtotal felony
mean 8105.475 3.0013710 0.7874187
sd 6925.427 0.9035228 0.4095783
edit: I just realized that since I plan to row bind several data frames later, it may be best for them to all have the same column names. I changed the 'want' section to reflect the desired outcome.
A:
you can used the names() function to extract column names of the data frame and row bind that to your data frame. Then use the names() function again to override the existing names to any standard value you want.
A:
q <- rbind(colnames(q), round(q, 4))
colnames(q) <- paste0("var", seq_len(ncol(q)))
rownames(q)[1] <- "var"
q
var1 var2 var3
var shootings_per100k lawtotal felony
mean 8105.4747 3.0014 0.7874
sd 6925.4265 0.9035 0.4096
A:
You can also do as follows.
library(tidyverse)
names <- enframe(colnames(df)) %>%
pivot_wider(-name, names_from = value) %>%
rename_with( ~ LETTERS[1:length(df)])
data <- as_tibble(df) %>%
mutate(across(everything(), ~ as.character(.))) %>%
rename_with(~ LETTERS[1:length(df)])
bind_rows(names, data)
# A tibble: 3 × 3
# A B C
# <chr> <chr> <chr>
# 1 shootings_per100k lawtotal felony
# 2 8105.475 3.001371 0.7874187
# 3 6925.427 0.9035228 0.4095783
|
How to Make column names the first row in r?
|
I have seen may tutorials on making the first row the column names, but nothing explaining how to do the reverse. I would like to have my column names as the first row values and change the column names to something like var1, var2, var3. Can this be done?
I plan to row bind a bunch of data frames later, so they all need the same column names.
q = structure(list(shootings_per100k = c(8105.47466098618, 6925.42653239307
), lawtotal = c(3.00137104283906, 0.903522788541896), felony = c(0.787418655097614,
0.409578330883717)), row.names = c("mean", "sd"), class = "data.frame")
Have:
shootings_per100k lawtotal felony
mean 8105.475 3.0013710 0.7874187
sd 6925.427 0.9035228 0.4095783
Want:
var1 var2 var3
var shootings_per100k lawtotal felony
mean 8105.475 3.0013710 0.7874187
sd 6925.427 0.9035228 0.4095783
edit: I just realized that since I plan to row bind several data frames later, it may be best for them to all have the same column names. I changed the 'want' section to reflect the desired outcome.
|
[
"you can used the names() function to extract column names of the data frame and row bind that to your data frame. Then use the names() function again to override the existing names to any standard value you want.\n",
"q <- rbind(colnames(q), round(q, 4))\ncolnames(q) <- paste0(\"var\", seq_len(ncol(q)))\nrownames(q)[1] <- \"var\"\nq\n var1 var2 var3\nvar shootings_per100k lawtotal felony\nmean 8105.4747 3.0014 0.7874\nsd 6925.4265 0.9035 0.4096\n\n",
"You can also do as follows.\nlibrary(tidyverse)\n\nnames <- enframe(colnames(df)) %>%\n pivot_wider(-name, names_from = value) %>%\n rename_with( ~ LETTERS[1:length(df)])\n\ndata <- as_tibble(df) %>%\n mutate(across(everything(), ~ as.character(.))) %>%\n rename_with(~ LETTERS[1:length(df)])\n\nbind_rows(names, data)\n\n# A tibble: 3 × 3\n# A B C \n# <chr> <chr> <chr> \n# 1 shootings_per100k lawtotal felony \n# 2 8105.475 3.001371 0.7874187\n# 3 6925.427 0.9035228 0.4095783\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"dataframe",
"r"
] |
stackoverflow_0074662287_dataframe_r.txt
|
Q:
How to Pass Data to A Modal in React.js
I want to pass a Value to a Modal
I have the following table with map data
const [edit, setEdit] = useState(false)
const [editId, setEditId] = useState(null);
task.map((data) => {
return (
<tr>
<td>{data.Name}</td>
<td>{data.Assigned}</td>
<td>
<Link onClick={() => setEdit(true).setEditId = data.Id}>Edit</Link>
<Edit data={editId} open={edit} onClose={() => setEdit(false)}></Edit>
</td>
</tr>
)
})
On my Edit page, I opened with a function with the data as a parameter, and i tried putting the value of the data inside an input field but nothing is passed
function Edit({ data, open, children, onClose }) {
<input type="text" id="tName" name="tName" defaultValue={data} placeholder={data}} /><br />
}
A:
you might want to consider using the useState hook to manage the value of the input field, so that you can update the input field when the user makes changes to the value. This will allow you to keep the data prop as a read-only prop that is passed to the Edit component, and manage the value of the input field separately.
Here is an example of how you could do this:
function Edit({ data, open, children, onClose }) {
const [value, setValue] = useState(data);
return (
<input type="text" id="tName" name="tName" value={value} placeholder={data} onChange={event => setValue(event.target.value)} /><br />
);
}
|
How to Pass Data to A Modal in React.js
|
I want to pass a Value to a Modal
I have the following table with map data
const [edit, setEdit] = useState(false)
const [editId, setEditId] = useState(null);
task.map((data) => {
return (
<tr>
<td>{data.Name}</td>
<td>{data.Assigned}</td>
<td>
<Link onClick={() => setEdit(true).setEditId = data.Id}>Edit</Link>
<Edit data={editId} open={edit} onClose={() => setEdit(false)}></Edit>
</td>
</tr>
)
})
On my Edit page, I opened with a function with the data as a parameter, and i tried putting the value of the data inside an input field but nothing is passed
function Edit({ data, open, children, onClose }) {
<input type="text" id="tName" name="tName" defaultValue={data} placeholder={data}} /><br />
}
|
[
"you might want to consider using the useState hook to manage the value of the input field, so that you can update the input field when the user makes changes to the value. This will allow you to keep the data prop as a read-only prop that is passed to the Edit component, and manage the value of the input field separately.\nHere is an example of how you could do this:\nfunction Edit({ data, open, children, onClose }) {\n const [value, setValue] = useState(data);\n\n return (\n <input type=\"text\" id=\"tName\" name=\"tName\" value={value} placeholder={data} onChange={event => setValue(event.target.value)} /><br />\n );\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"react_hooks",
"reactjs"
] |
stackoverflow_0074662471_javascript_react_hooks_reactjs.txt
|
Q:
why backtracking does / does not happen (ending search with false or not)?
This is a question asking why backtracking happens in one simple program and not another.
Example 1.
% water/2 relates temperature to state
water(Temp, solid) :- Temp =< 0.
water(Temp, liquid) :- Temp > 0, Temp < 100.
water(Temp, gas) :- Temp >= 100.
?- water(50,X).
X = liquid
false
Example 2.
% parent facts
parent(john, jane).
parent(john, james).
parent(sally, jane).
parent(martha, sally).
?- parent(X, jane).
X = john
X = sally
In example 1, prolog finds X=liquid as one solution, then prompts to search for more solutions. When none are found it returns false.
In example 2, prolog correctly finds X=john, prompts to continue the search, and then finds X=sally, but then does not prompt to continue searching. It does not finish with a false to indicate it tried the remaining rules (eg parent(martha,sally) the last rule) and failed.
Question: Why does the first example finish with a false, but the second does not?
A:
Simply write a rule which disallows water to be in more than one state. There's several methods (mostly using e.g. cut), here's one:
water_temp_state(Temp, State) :-
( Temp =< 0 -> State = solid
; Temp < 100 -> State = liquid
; State = gas
).
Results:
?- water_temp_state(-5, S).
S = solid.
?- water_temp_state(5, S).
S = liquid.
?- water_temp_state(500, S).
S = gas.
Use multiple predicates when there is an actual possibility of multiple states.
Here's another method, just for fun:
water_state_comparison(solid, =<, 0).
water_state_comparison(liquid, <, 100).
water_state_comparison(gas, >=, 100).
water_temp_state_compare(Temp, State) :-
water_state_comparison(State, Comp, Num),
Pred =.. [Comp, Temp, Num],
call(Pred),
!.
... with same results.
|
why backtracking does / does not happen (ending search with false or not)?
|
This is a question asking why backtracking happens in one simple program and not another.
Example 1.
% water/2 relates temperature to state
water(Temp, solid) :- Temp =< 0.
water(Temp, liquid) :- Temp > 0, Temp < 100.
water(Temp, gas) :- Temp >= 100.
?- water(50,X).
X = liquid
false
Example 2.
% parent facts
parent(john, jane).
parent(john, james).
parent(sally, jane).
parent(martha, sally).
?- parent(X, jane).
X = john
X = sally
In example 1, prolog finds X=liquid as one solution, then prompts to search for more solutions. When none are found it returns false.
In example 2, prolog correctly finds X=john, prompts to continue the search, and then finds X=sally, but then does not prompt to continue searching. It does not finish with a false to indicate it tried the remaining rules (eg parent(martha,sally) the last rule) and failed.
Question: Why does the first example finish with a false, but the second does not?
|
[
"Simply write a rule which disallows water to be in more than one state. There's several methods (mostly using e.g. cut), here's one:\nwater_temp_state(Temp, State) :-\n ( Temp =< 0 -> State = solid\n ; Temp < 100 -> State = liquid\n ; State = gas\n ).\n\nResults:\n?- water_temp_state(-5, S).\nS = solid.\n\n?- water_temp_state(5, S).\nS = liquid.\n\n?- water_temp_state(500, S).\nS = gas.\n\nUse multiple predicates when there is an actual possibility of multiple states.\nHere's another method, just for fun:\nwater_state_comparison(solid, =<, 0).\nwater_state_comparison(liquid, <, 100).\nwater_state_comparison(gas, >=, 100).\n\nwater_temp_state_compare(Temp, State) :-\n water_state_comparison(State, Comp, Num),\n Pred =.. [Comp, Temp, Num],\n call(Pred),\n !.\n\n... with same results.\n"
] |
[
0
] |
[] |
[] |
[
"backtracking",
"prolog"
] |
stackoverflow_0074660753_backtracking_prolog.txt
|
Q:
jq pass an array that should be converted into json array
I have script
#!/bin/bash
ARR=("a" "b")
collection_init_msg=$( jq -n --arg arr $ARR '{arr: [$arr]}')
echo some command "$collection_init_msg"
that should convert the ARR and print it as a JSON array.
Current result
some command {
"arr": [
"a"
]
}
What I want is:
some command {
"arr": [
"a", "b"
]
}
A:
#!/bin/bash
ARR=("a" "b")
collection_init_msg=$( jq -nc '{arr: $ARGS.positional}' --args "${ARR[@]}" )
echo "$collection_init_msg"
In answer to the supplementary question in the comment: one could do worse than:
jq -n --argjson a1 $(jq -nc '$ARGS.positional' --args "${A1[@]}") '
{$a1, a2: $ARGS.positional}' --args "${A2[@]}"
|
jq pass an array that should be converted into json array
|
I have script
#!/bin/bash
ARR=("a" "b")
collection_init_msg=$( jq -n --arg arr $ARR '{arr: [$arr]}')
echo some command "$collection_init_msg"
that should convert the ARR and print it as a JSON array.
Current result
some command {
"arr": [
"a"
]
}
What I want is:
some command {
"arr": [
"a", "b"
]
}
|
[
"#!/bin/bash\nARR=(\"a\" \"b\")\n\ncollection_init_msg=$( jq -nc '{arr: $ARGS.positional}' --args \"${ARR[@]}\" )\n\necho \"$collection_init_msg\" \n\n\nIn answer to the supplementary question in the comment: one could do worse than:\njq -n --argjson a1 $(jq -nc '$ARGS.positional' --args \"${A1[@]}\") '\n {$a1, a2: $ARGS.positional}' --args \"${A2[@]}\"\n\n"
] |
[
5
] |
[] |
[] |
[
"arrays",
"bash",
"jq",
"json",
"shell"
] |
stackoverflow_0074662395_arrays_bash_jq_json_shell.txt
|
Q:
How to decode a column using another column?
im new to sql and i have the following problem.
I have this kind of table with employee number, surname, job and a column named 'dir' that shows the employee number of the director of the employee in that row.
I was trying to do it using the decode function with some subqueries but failed :(.
Is there any way to do it with decode? I have not learned yet more advanced functions.
emp_no
Surname
Job
dir
1
a
director
2
b
analist
1
3
c
director
4
d
manager
1
5
e
analist
3
--------
--------
--------
--------
I need to write a query that will show in the first column, every employee's name and, in the second column, the name of that employee's director, or in case he has no director the legend "has no director".
Example:
Surname
director
a
has no director
b
a
c
has no director
d
a
e
c
Thanks in advance everyone!!
A:
select a.Surname,
case when a.dir is null then 'has no director'
else b.Surname end as director
from employee a
left join employee b on a.dir=b.emp_no
order by Surname;
You can see the example here ;
http://sqlfiddle.com/#!9/d6217d9/18
|
How to decode a column using another column?
|
im new to sql and i have the following problem.
I have this kind of table with employee number, surname, job and a column named 'dir' that shows the employee number of the director of the employee in that row.
I was trying to do it using the decode function with some subqueries but failed :(.
Is there any way to do it with decode? I have not learned yet more advanced functions.
emp_no
Surname
Job
dir
1
a
director
2
b
analist
1
3
c
director
4
d
manager
1
5
e
analist
3
--------
--------
--------
--------
I need to write a query that will show in the first column, every employee's name and, in the second column, the name of that employee's director, or in case he has no director the legend "has no director".
Example:
Surname
director
a
has no director
b
a
c
has no director
d
a
e
c
Thanks in advance everyone!!
|
[
"select a.Surname, \ncase when a.dir is null then 'has no director'\nelse b.Surname end as director\nfrom employee a \nleft join employee b on a.dir=b.emp_no\norder by Surname;\n\nYou can see the example here ;\nhttp://sqlfiddle.com/#!9/d6217d9/18\n"
] |
[
0
] |
[] |
[] |
[
"oracle",
"sql",
"sqlplus"
] |
stackoverflow_0074662392_oracle_sql_sqlplus.txt
|
Q:
Docker: Build Debian 11 image, with Python and Google Cloud SDK in it
I want ot build a Docker image with the following features:
Must have a Debian 11 base image (Mandatory)
On top of it, I also need installed:
Python 3.
spaCy package (There could be others of my choice).
Google Cloud SDK (I will need this to run commands using gcloud and gsutil).
Most likely, I will download some files stored in some Cloud Storage bucket.
My current Dockerfile looks as follows:
FROM gcr.io/cloud-marketplace/google/debian11:latest
RUN apt-get update -y
# --------- THIS STEP FAILS ---------
RUN apt-get install google-cloud-sdk
#------------------------------------
RUN apt-get install -y python3
RUN apt-get install -y python3-pip
RUN pip install spacy==3.2.1
CMD ["gsutil","--version"]
As far as I understand, that base image should have both Python and Google Cloud SDK already installed on top of it, but it does not, so I started adding what I needed on my own. The current error is:
=> ERROR [3/6] RUN apt-get install google-cloud-sdk
------
> [3/6] RUN apt-get install google-cloud-sdk:
#7 0.412 Reading package lists...
#7 0.828 Building dependency tree...
#7 0.941 Reading state information...
#7 1.040 E: Unable to locate package google-cloud-sdk
------
executor failed running [/bin/sh -c apt-get install google-cloud-sdk]: exit code: 100
If the line producing the error [3/6] gets commented, everything else works correctly.
QUESTIONS:
What am I doing wrong?
Is there a better way to do what I want? (Image size can have up to 10GB in size, so optimization might be optional for this case).
NOTES:
This section will include lengthy answers to questions raised in the comment sections. Will probably vary.
A:
You can install gcloud cli in your container with the following way :
FROM gcr.io/cloud-marketplace/google/debian11:latest
RUN apt-get update -y
ENV PATH=/google-cloud-sdk/bin:$PATH
WORKDIR /
RUN export CLOUD_SDK_VERSION="410.0.0" && \
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \
tar xzf google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \
rm google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \
ln -s /lib /lib64
RUN gcloud config set core/disable_usage_reporting true && \
gcloud config set component_manager/disable_update_check true && \
gcloud config set metrics/environment github_docker_images && \
gcloud -q components install beta kubectl
ENTRYPOINT [ "sh", "-c", "gcloud --version" ]
This part is not mandatory :
RUN gcloud config set core/disable_usage_reporting true && \
gcloud config set component_manager/disable_update_check true && \
gcloud config set metrics/environment github_docker_images && \
gcloud -q components install beta kubectl
|
Docker: Build Debian 11 image, with Python and Google Cloud SDK in it
|
I want ot build a Docker image with the following features:
Must have a Debian 11 base image (Mandatory)
On top of it, I also need installed:
Python 3.
spaCy package (There could be others of my choice).
Google Cloud SDK (I will need this to run commands using gcloud and gsutil).
Most likely, I will download some files stored in some Cloud Storage bucket.
My current Dockerfile looks as follows:
FROM gcr.io/cloud-marketplace/google/debian11:latest
RUN apt-get update -y
# --------- THIS STEP FAILS ---------
RUN apt-get install google-cloud-sdk
#------------------------------------
RUN apt-get install -y python3
RUN apt-get install -y python3-pip
RUN pip install spacy==3.2.1
CMD ["gsutil","--version"]
As far as I understand, that base image should have both Python and Google Cloud SDK already installed on top of it, but it does not, so I started adding what I needed on my own. The current error is:
=> ERROR [3/6] RUN apt-get install google-cloud-sdk
------
> [3/6] RUN apt-get install google-cloud-sdk:
#7 0.412 Reading package lists...
#7 0.828 Building dependency tree...
#7 0.941 Reading state information...
#7 1.040 E: Unable to locate package google-cloud-sdk
------
executor failed running [/bin/sh -c apt-get install google-cloud-sdk]: exit code: 100
If the line producing the error [3/6] gets commented, everything else works correctly.
QUESTIONS:
What am I doing wrong?
Is there a better way to do what I want? (Image size can have up to 10GB in size, so optimization might be optional for this case).
NOTES:
This section will include lengthy answers to questions raised in the comment sections. Will probably vary.
|
[
"You can install gcloud cli in your container with the following way :\nFROM gcr.io/cloud-marketplace/google/debian11:latest \n\nRUN apt-get update -y\n\nENV PATH=/google-cloud-sdk/bin:$PATH\n\nWORKDIR /\nRUN export CLOUD_SDK_VERSION=\"410.0.0\" && \\\n curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \\\n tar xzf google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \\\n rm google-cloud-sdk-${CLOUD_SDK_VERSION}-linux-x86_64.tar.gz && \\\n ln -s /lib /lib64\n\nRUN gcloud config set core/disable_usage_reporting true && \\\n gcloud config set component_manager/disable_update_check true && \\\n gcloud config set metrics/environment github_docker_images && \\\n gcloud -q components install beta kubectl\n\nENTRYPOINT [ \"sh\", \"-c\", \"gcloud --version\" ]\n\nThis part is not mandatory :\nRUN gcloud config set core/disable_usage_reporting true && \\\n gcloud config set component_manager/disable_update_check true && \\\n gcloud config set metrics/environment github_docker_images && \\\n gcloud -q components install beta kubectl\n\n"
] |
[
1
] |
[] |
[] |
[
"debian",
"docker",
"google_cloud_platform",
"google_cloud_sdk"
] |
stackoverflow_0074662355_debian_docker_google_cloud_platform_google_cloud_sdk.txt
|
Q:
python2 can't file a file in current folder
For the next file info:
[jzun@hscd8a25e93f9vm dates]$ pwd
/home/jzun/vivo_mod_samples/dates
[jzun@hscd8a25e93f9vm dates]$ ls
date_def.json dates_add.rdf dates.bak dates.rdf dates_sub.rdf dates.txt datetime_precision_enum.txt gen_date_rdf.py gen_date_rdf.py.bak gen_dates.py gen_dates.py.bak get.txt README.md run_pump_2_to_create_date_defs.sh sv.cfg
I have the next python2 function:
def read_csv(filename, skip=True, delimiter='|'):
"""
Read a CSV file, return dictionary object
:param filename: name of file to read
:param skip: should lines with invalid number of columns be skipped? False=Throw Exception
:param delimiter: The delimiter for CSV files
:return: Dictionary object
"""
cwd = os.getcwd()
print("read_csv>current dir = " + cwd)
# fp = open(filename, 'rU')
# print(fp)
# data = read_csv_fp(fp, skip, delimiter)
# fp.close()
with open(filename, 'rU') as fp:
data = read_csv_fp(fp, skip, delimiter)
fp.close()
return data
After running it with filename = dates.txt I get the next result:
read_csv>current dir = /home/jzun/vivo_mod_samples/dates
dates.txt file not found
I know similar questions have been posted but interestingly I can not find anything that could help me to solve this problem. Any ideas?
A:
Try passing the full path of the file dates.txt:
cwd = os.getcwd()
file_name = "dates.txt"
file_path = os.path.join(cwd, file_name)
# Double check that file exist
assert os.path.isfile(file_path) is True
with open(file_path, 'rU') as fp:
data = read_csv_fp(fp, skip, delimiter)
fp.close()
|
python2 can't file a file in current folder
|
For the next file info:
[jzun@hscd8a25e93f9vm dates]$ pwd
/home/jzun/vivo_mod_samples/dates
[jzun@hscd8a25e93f9vm dates]$ ls
date_def.json dates_add.rdf dates.bak dates.rdf dates_sub.rdf dates.txt datetime_precision_enum.txt gen_date_rdf.py gen_date_rdf.py.bak gen_dates.py gen_dates.py.bak get.txt README.md run_pump_2_to_create_date_defs.sh sv.cfg
I have the next python2 function:
def read_csv(filename, skip=True, delimiter='|'):
"""
Read a CSV file, return dictionary object
:param filename: name of file to read
:param skip: should lines with invalid number of columns be skipped? False=Throw Exception
:param delimiter: The delimiter for CSV files
:return: Dictionary object
"""
cwd = os.getcwd()
print("read_csv>current dir = " + cwd)
# fp = open(filename, 'rU')
# print(fp)
# data = read_csv_fp(fp, skip, delimiter)
# fp.close()
with open(filename, 'rU') as fp:
data = read_csv_fp(fp, skip, delimiter)
fp.close()
return data
After running it with filename = dates.txt I get the next result:
read_csv>current dir = /home/jzun/vivo_mod_samples/dates
dates.txt file not found
I know similar questions have been posted but interestingly I can not find anything that could help me to solve this problem. Any ideas?
|
[
"Try passing the full path of the file dates.txt:\ncwd = os.getcwd()\nfile_name = \"dates.txt\"\nfile_path = os.path.join(cwd, file_name)\n\n# Double check that file exist\nassert os.path.isfile(file_path) is True\n\nwith open(file_path, 'rU') as fp:\n data = read_csv_fp(fp, skip, delimiter)\n fp.close()\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_2.7"
] |
stackoverflow_0074660016_python_python_2.7.txt
|
Q:
Prisma Transactions Cross Modules
Problem
I was trying to implement a clean prisma transaction architecture with a DDD architecture.
My problem is that i want to be able to perform transactions cross different modules without need to pass the prisma transaction client to each repository
ie:
// repository layer
@injectable()
export class UserRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(user: IUser): Promise<User>{
return this.prisma.user.create({data: user});
}
}
@injectable()
export class OrderRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(order: IOrder): Promise<Order>{
return this.prisma.order.create({data: order});
}
}
// service layer
export class UserService{
constructor(@inject(UserRepository) private userRepo: UserRepository)
create(request: CreateUserRequest){
return this.userRepo.save(request);
}
}
export class OrderService{
constructor(@inject(OrderRepository) private orderRepo: OrderRepository)
create(request: CreateOrderRequest){
return this.orderRepo.save(request);
}
}
// controller layer
export UserController{
constructor(
@inject(UserService) private userService: UserService,
@inject(OrderService) private orderService: OrderService
){}
placeOrder(
userRequest: CreateUserRequest,
orderRequest: CreateOrderRequest
){
// perform transaction, if any fails go with rollback
// !THIS ACTUALLY DOESN'T WORK
prisma.$transaction([
await this.userService.create(userRequest),
await this.orderService.create(orderRequest)
])
}
}
I want to figure out a clean way to achieve this, has anyone faced a similar problem before?
Thank you all!
A:
Your UserRepository.save and OrderRepository.save, should return PrismaPromises instead of a Promise(https://www.prisma.io/docs/concepts/components/prisma-client/transactions#the-transaction-api)
Also, when you await the promise returned by UserRepository.save you are passing a User not a PrismaPromise<User> which the $transaction expects.
To fix it, fix the typing from the repositories methods as commented above and then you should be able to do a transaction by inverting the order on which you await:
await prisma.$transaction([
this.userService.create(userRequest),
this.orderService.create(orderRequest)
])
A:
You could use a library like typeorm for this, which includes a transaction decorator that can be used to wrap multiple queries in a single transaction.
Alternatively, you could use the native prisma transaction client in each of your repositories. This would involve passing the transaction client to each repository when it needs to be used.
For example:
// repository layer
@injectable()
export class UserRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(user: IUser, transactionClient: Prisma.TransactionClient): Promise<User>{
return this.prisma.user.create({data: user}, {transaction: transactionClient});
}
}
@injectable()
export class OrderRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(order: IOrder, transactionClient: Prisma.TransactionClient): Promise<Order>{
return this.prisma.order.create({data: order}, {transaction: transactionClient});
}
}
// service layer
export class UserService{
constructor(@inject(UserRepository) private userRepo: UserRepository)
create(request: CreateUserRequest, transactionClient: Prisma.TransactionClient){
return this.userRepo.save(request, transactionClient);
}
}
export class OrderService{
constructor(@inject(OrderRepository) private orderRepo: OrderRepository)
create(request: CreateOrderRequest, transactionClient: Prisma.TransactionClient){
return this.orderRepo.save(request, transactionClient);
}
}
// controller layer
export UserController{
constructor(
@inject(UserService) private userService: UserService,
@inject(OrderService) private orderService: OrderService
){}
placeOrder(
userRequest: CreateUserRequest,
orderRequest: CreateOrderRequest
){
// create the transaction client
const transactionClient = this.prisma.transaction();
// perform transaction, if any fails go with rollback
this.prisma.$transaction([
await this.userService.create(userRequest, transactionClient),
await this.orderService.create(orderRequest, transactionClient)
])
}
}
|
Prisma Transactions Cross Modules
|
Problem
I was trying to implement a clean prisma transaction architecture with a DDD architecture.
My problem is that i want to be able to perform transactions cross different modules without need to pass the prisma transaction client to each repository
ie:
// repository layer
@injectable()
export class UserRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(user: IUser): Promise<User>{
return this.prisma.user.create({data: user});
}
}
@injectable()
export class OrderRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(order: IOrder): Promise<Order>{
return this.prisma.order.create({data: order});
}
}
// service layer
export class UserService{
constructor(@inject(UserRepository) private userRepo: UserRepository)
create(request: CreateUserRequest){
return this.userRepo.save(request);
}
}
export class OrderService{
constructor(@inject(OrderRepository) private orderRepo: OrderRepository)
create(request: CreateOrderRequest){
return this.orderRepo.save(request);
}
}
// controller layer
export UserController{
constructor(
@inject(UserService) private userService: UserService,
@inject(OrderService) private orderService: OrderService
){}
placeOrder(
userRequest: CreateUserRequest,
orderRequest: CreateOrderRequest
){
// perform transaction, if any fails go with rollback
// !THIS ACTUALLY DOESN'T WORK
prisma.$transaction([
await this.userService.create(userRequest),
await this.orderService.create(orderRequest)
])
}
}
I want to figure out a clean way to achieve this, has anyone faced a similar problem before?
Thank you all!
|
[
"Your UserRepository.save and OrderRepository.save, should return PrismaPromises instead of a Promise(https://www.prisma.io/docs/concepts/components/prisma-client/transactions#the-transaction-api)\nAlso, when you await the promise returned by UserRepository.save you are passing a User not a PrismaPromise<User> which the $transaction expects.\nTo fix it, fix the typing from the repositories methods as commented above and then you should be able to do a transaction by inverting the order on which you await:\nawait prisma.$transaction([\n this.userService.create(userRequest),\n this.orderService.create(orderRequest)\n])\n\n",
"You could use a library like typeorm for this, which includes a transaction decorator that can be used to wrap multiple queries in a single transaction.\nAlternatively, you could use the native prisma transaction client in each of your repositories. This would involve passing the transaction client to each repository when it needs to be used.\nFor example:\n// repository layer\n@injectable()\nexport class UserRepository{\n constructor(@inject(PrismaClient) private prisma: PrismaClient)\n save(user: IUser, transactionClient: Prisma.TransactionClient): Promise<User>{\n return this.prisma.user.create({data: user}, {transaction: transactionClient});\n }\n}\n\n@injectable()\nexport class OrderRepository{\n constructor(@inject(PrismaClient) private prisma: PrismaClient)\n \n save(order: IOrder, transactionClient: Prisma.TransactionClient): Promise<Order>{\n return this.prisma.order.create({data: order}, {transaction: transactionClient});\n }\n}\n// service layer\nexport class UserService{\n constructor(@inject(UserRepository) private userRepo: UserRepository)\n\n create(request: CreateUserRequest, transactionClient: Prisma.TransactionClient){\n return this.userRepo.save(request, transactionClient);\n }\n}\n\nexport class OrderService{\n constructor(@inject(OrderRepository) private orderRepo: OrderRepository)\n \n create(request: CreateOrderRequest, transactionClient: Prisma.TransactionClient){\n return this.orderRepo.save(request, transactionClient);\n }\n}\n// controller layer\nexport UserController{\n constructor(\n @inject(UserService) private userService: UserService,\n @inject(OrderService) private orderService: OrderService\n ){}\n\n placeOrder(\n userRequest: CreateUserRequest,\n orderRequest: CreateOrderRequest\n ){\n // create the transaction client\n const transactionClient = this.prisma.transaction();\n // perform transaction, if any fails go with rollback\n this.prisma.$transaction([\n await this.userService.create(userRequest, transactionClient),\n await this.orderService.create(orderRequest, transactionClient)\n ])\n }\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"domain_driven_design",
"node.js",
"prisma",
"typescript"
] |
stackoverflow_0074516388_domain_driven_design_node.js_prisma_typescript.txt
|
Q:
DynamoDB JavaScript PutItemCommand is neither failing nor working
Please note: although this question mentions AWS SAM, it is 100% a DynamoDB JavaScript SDK question at heart and can be answered by anyone with experience writing JavaScript Lambdas (or any client-side apps) against DynamoDB using the AWS DynamoDB client/SDK.
So I used AWS SAM to provision a new DynamoDB table with the following attributes:
FeedbackDynamoDB:
Type: AWS::DynamoDB::Table
Properties:
TableName: commentary
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
StreamSpecification:
StreamViewType: NEW_IMAGE
This configuration successfully creates a DynamoDB table called commentary. However, when I view this table in the DynamoDB web console, I noticed a few things:
it has a partition key of id (type S)
it has no sort key
it has no (0) indexes
it has a read/write capacity mode of "5"
I'm not sure if this raises any red flags with anyone but I figured I would include those details, in case I've configured anything incorrectly.
Now then, I have some JavaScript that instantiates a DynamoDB client (using the JavaScript SDK) and attempts to add a record/item to this table:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const params = {
TableName: "commentary",
Item: {
"id": {
S: "123""
},
"content": {
S: "some content""
},
"commentaryType": {
S: "constructive-criticism"
}
},
};
console.log("about to try to insert commentary into dynamo...");
try {
const ddbClient = new DynamoDBClient({ region: "us-east-1" });
console.log("wait for it...")
const data = await ddbClient.send(new PutItemCommand(params));
console.log("sent...");
console.log("success", data);
} catch (err) {
console.log("hmmm something awry");
throw err;
}
When I execute this code, I see the following log statements:
about to try to insert commentary into dynamo...
wait for it...
...and nothing else. No errors, failure responses...nothing. Checking in DynamoDB, the table is still empty.
So I decide to remove the await and make the API look like:
const data = ddbClient.send(new PutItemCommand(params));
And then after re-executing, I check the logs and see:
about to try to insert commentary into dynamo...
wait for it...
sent...
success Promise { <pending> }
But still, checking DynamoDB, the table is empty.
Have I set the table up incorrectly? Am I using the PutItemCommand (or its parameters) incorrectly? Am I invoking the DynamoDB client incorrectly? Or something else? What do I need to change to get this app writing to my table?
A:
Try using a promise to see the outcome:
client.send(command).then(
(data) => {
// process data.
},
(error) => {
// error handling.
}
);
Everything seems alright with your table setup, I believe it's Lambda async issue with the JS sdk. I'm guessing Lambda is not waiting on your code and exiting early. Can you include your full lambda code.
|
DynamoDB JavaScript PutItemCommand is neither failing nor working
|
Please note: although this question mentions AWS SAM, it is 100% a DynamoDB JavaScript SDK question at heart and can be answered by anyone with experience writing JavaScript Lambdas (or any client-side apps) against DynamoDB using the AWS DynamoDB client/SDK.
So I used AWS SAM to provision a new DynamoDB table with the following attributes:
FeedbackDynamoDB:
Type: AWS::DynamoDB::Table
Properties:
TableName: commentary
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
StreamSpecification:
StreamViewType: NEW_IMAGE
This configuration successfully creates a DynamoDB table called commentary. However, when I view this table in the DynamoDB web console, I noticed a few things:
it has a partition key of id (type S)
it has no sort key
it has no (0) indexes
it has a read/write capacity mode of "5"
I'm not sure if this raises any red flags with anyone but I figured I would include those details, in case I've configured anything incorrectly.
Now then, I have some JavaScript that instantiates a DynamoDB client (using the JavaScript SDK) and attempts to add a record/item to this table:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const params = {
TableName: "commentary",
Item: {
"id": {
S: "123""
},
"content": {
S: "some content""
},
"commentaryType": {
S: "constructive-criticism"
}
},
};
console.log("about to try to insert commentary into dynamo...");
try {
const ddbClient = new DynamoDBClient({ region: "us-east-1" });
console.log("wait for it...")
const data = await ddbClient.send(new PutItemCommand(params));
console.log("sent...");
console.log("success", data);
} catch (err) {
console.log("hmmm something awry");
throw err;
}
When I execute this code, I see the following log statements:
about to try to insert commentary into dynamo...
wait for it...
...and nothing else. No errors, failure responses...nothing. Checking in DynamoDB, the table is still empty.
So I decide to remove the await and make the API look like:
const data = ddbClient.send(new PutItemCommand(params));
And then after re-executing, I check the logs and see:
about to try to insert commentary into dynamo...
wait for it...
sent...
success Promise { <pending> }
But still, checking DynamoDB, the table is empty.
Have I set the table up incorrectly? Am I using the PutItemCommand (or its parameters) incorrectly? Am I invoking the DynamoDB client incorrectly? Or something else? What do I need to change to get this app writing to my table?
|
[
"Try using a promise to see the outcome:\nclient.send(command).then(\n (data) => {\n // process data.\n },\n (error) => {\n // error handling.\n }\n);\n\nEverything seems alright with your table setup, I believe it's Lambda async issue with the JS sdk. I'm guessing Lambda is not waiting on your code and exiting early. Can you include your full lambda code.\n"
] |
[
0
] |
[] |
[] |
[
"amazon_dynamodb",
"amazon_web_services",
"aws_sdk_js"
] |
stackoverflow_0074661745_amazon_dynamodb_amazon_web_services_aws_sdk_js.txt
|
Q:
How to switch between 2 languages with a button and not a dropdown with WPML?
It's silly to have dropdown when you have only two languages. Makes sense if there are more. I want to have just a simple button that will switch to the other language and I can't find any guide on google.
A:
You need to create a custom language switcher.
The first step is to add the PHP code responsible for rendering the language switcher on your page. For that, you create a function that adds a div container with the language switcher inside it. We can use the wpml_add_language_selector action to render the language switcher.
In this example, we want the new language switcher to be displayed in the footer, so we use our new function with the WordPress’s own wp_footer hook.
The complete PHP code will look like this.
//WPML - Add a floating language switcher to the footer
add_action('wp_footer', 'wpml_floating_language_switcher');
function wpml_floating_language_switcher() {
echo '<div class="wpml-floating-language-switcher">';
//PHP action to display the language switcher (see https://wpml.org/documentation/getting-started-guide/language-setup/language-switcher-options/#using-php-actions)
do_action('wpml_add_language_selector');
echo '</div>';
}
You can copy and add it to your (child) theme’s functions.php file.
With the previous code in place, we already have a new language switcher added to the footer of our website. Now, it’s time to customize it so that it is floating in the bottom right corner of the website. You can do this using the position: fixed CSS attribute.
Use the following steps to add the CSS code:
Go to WPML → Languages.
Scroll down to Language switcher options and expand the Additional CSS section.
Alternatively, you can add this CSS code by going to Appearance → Customize and clicking Additional CSS.
The following example adds some extra customization like rounded borders and box-shadow. Of course, you can customize it as you want.
/*Removing some default CSS from our language switcher*/
.wpml-floating-language-switcher .wpml-ls-statics-shortcode_actions {
margin-bottom: 0;
}
.wpml-floating-language-switcher .wpml-ls-statics-shortcode_actions a {
background-color: transparent !important;
}
.wpml-floating-language-switcher .wpml-ls-legacy-list-horizontal a {
padding: 5px;
}
/*Customize this if you want*/
.wpml-floating-language-switcher {
position: fixed;
bottom: 10px;
right: 10px;
background: #f8f8f8; /*background color*/
border: 1px solid; /*border settings*/
border-color: #eee; /*color of the border*/
padding: 0px; /*padding of container*/
border-radius: 6px; /*rounded border*/
/*Box Shadow*/
-webkit-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);
-moz-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);
box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);
}
Finally, you need to adjust some settings so the language switcher displays only the flags.
Use the following steps:
List item
Go to WPML → Languages.
Scroll down to Custom language switchers and click Enable.
Click the Customize button.
For What to include in the language switcher, select Flag and uncheck the other options.
Click Save.
You can find the complete documentation at WPML webiste.
A:
I add the css here to include the | "Pipe" between two languages in the switcher
.wpml-ls-statics-shortcode_actions li:nth-of-type(1) .wpml-ls-link:after{
content:"\00a0 \00a0|" !important;
display:inline-block !important;
}
/*fix padding switcher WPML */
.wpml-ls-legacy-list-horizontal a{
padding-left:2px !important;
padding-right:2px !important;
}
|
How to switch between 2 languages with a button and not a dropdown with WPML?
|
It's silly to have dropdown when you have only two languages. Makes sense if there are more. I want to have just a simple button that will switch to the other language and I can't find any guide on google.
|
[
"You need to create a custom language switcher.\nThe first step is to add the PHP code responsible for rendering the language switcher on your page. For that, you create a function that adds a div container with the language switcher inside it. We can use the wpml_add_language_selector action to render the language switcher.\nIn this example, we want the new language switcher to be displayed in the footer, so we use our new function with the WordPress’s own wp_footer hook.\nThe complete PHP code will look like this.\n//WPML - Add a floating language switcher to the footer\n add_action('wp_footer', 'wpml_floating_language_switcher'); \n \n function wpml_floating_language_switcher() { \n echo '<div class=\"wpml-floating-language-switcher\">';\n //PHP action to display the language switcher (see https://wpml.org/documentation/getting-started-guide/language-setup/language-switcher-options/#using-php-actions)\n do_action('wpml_add_language_selector');\n echo '</div>'; \n}\n\nYou can copy and add it to your (child) theme’s functions.php file.\nWith the previous code in place, we already have a new language switcher added to the footer of our website. Now, it’s time to customize it so that it is floating in the bottom right corner of the website. You can do this using the position: fixed CSS attribute.\nUse the following steps to add the CSS code:\n\nGo to WPML → Languages.\nScroll down to Language switcher options and expand the Additional CSS section.\n\nAlternatively, you can add this CSS code by going to Appearance → Customize and clicking Additional CSS.\nThe following example adds some extra customization like rounded borders and box-shadow. Of course, you can customize it as you want.\n/*Removing some default CSS from our language switcher*/\n.wpml-floating-language-switcher .wpml-ls-statics-shortcode_actions {\n margin-bottom: 0;\n}\n \n.wpml-floating-language-switcher .wpml-ls-statics-shortcode_actions a {\n background-color: transparent !important;\n}\n \n.wpml-floating-language-switcher .wpml-ls-legacy-list-horizontal a {\n padding: 5px;\n}\n \n \n/*Customize this if you want*/\n.wpml-floating-language-switcher {\n position: fixed;\n bottom: 10px;\n right: 10px;\n background: #f8f8f8; /*background color*/\n border: 1px solid; /*border settings*/\n border-color: #eee; /*color of the border*/\n padding: 0px; /*padding of container*/\n border-radius: 6px; /*rounded border*/\n /*Box Shadow*/\n -webkit-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);\n -moz-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);\n box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.25);\n}\n\nFinally, you need to adjust some settings so the language switcher displays only the flags.\nUse the following steps:\n\nList item\nGo to WPML → Languages.\nScroll down to Custom language switchers and click Enable.\nClick the Customize button.\nFor What to include in the language switcher, select Flag and uncheck the other options.\nClick Save.\n\nYou can find the complete documentation at WPML webiste.\n",
"I add the css here to include the | \"Pipe\" between two languages in the switcher\n.wpml-ls-statics-shortcode_actions li:nth-of-type(1) .wpml-ls-link:after{\n content:\"\\00a0 \\00a0|\" !important;\n display:inline-block !important;\n}\n/*fix padding switcher WPML */\n.wpml-ls-legacy-list-horizontal a{\n padding-left:2px !important;\n padding-right:2px !important;\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"code_translation",
"plugins",
"translation",
"wordpress",
"wpml"
] |
stackoverflow_0073370989_code_translation_plugins_translation_wordpress_wpml.txt
|
Q:
Is there GTM Trigger based on HTML text on page
I created an element visibility trigger and attached it to my tag. The element visibility trigger was based on an id. It turns out that that id was not unique. Hence the tag connected to my trigger is being triggered for behaviors I don't want the tag triggered for. However there is a unique message that appears along with this id. Is there a way I can create a trigger that fires only when this message appears on the website? Thanks!
I researched to see if there are any additional GTM triggers based on not only an id but also actual text on the page.
A:
Well, you can use the element visibility trigger, but it's being frowned upon due to how heavy it is.
A better thing to do would be having an unrelated trigger, like a pageview, but then have a CJS value there as a condition. That CJS would do exactly that: check if the text is on the page and return the result of the check.
A:
I'm sorry one more question.
Are you using the term "event visibility trigger" and "element visibility trigger" interchangeably?
|
Is there GTM Trigger based on HTML text on page
|
I created an element visibility trigger and attached it to my tag. The element visibility trigger was based on an id. It turns out that that id was not unique. Hence the tag connected to my trigger is being triggered for behaviors I don't want the tag triggered for. However there is a unique message that appears along with this id. Is there a way I can create a trigger that fires only when this message appears on the website? Thanks!
I researched to see if there are any additional GTM triggers based on not only an id but also actual text on the page.
|
[
"Well, you can use the element visibility trigger, but it's being frowned upon due to how heavy it is.\nA better thing to do would be having an unrelated trigger, like a pageview, but then have a CJS value there as a condition. That CJS would do exactly that: check if the text is on the page and return the result of the check.\n",
"I'm sorry one more question.\nAre you using the term \"event visibility trigger\" and \"element visibility trigger\" interchangeably?\n"
] |
[
0,
0
] |
[] |
[] |
[
"google_tag_manager",
"javascript"
] |
stackoverflow_0074632544_google_tag_manager_javascript.txt
|
Q:
Is there something similar to Mercurial's Command Server in Git?
Mercurial's Command Server allows to issue commands to a Mercurial repository over a pipe through a special protocol... it is like a "webservice" of sorts.
https://www.mercurial-scm.org/wiki/CommandServer
Is there anything similar in Git in order to manipulate remote Git repositories to do things you need? (like switching to another branch or updating to another revision)
A:
Don't know exactly, what the mercurial command server does, but usually git utilizes ssh as its primary remote protocol.
ssh serverName "cd /path/to/repo; git pull"
ssh serverName "git --git-dir=/path/to/repo pull"
Sends a shell command to a remote ssh server serverName. As long as the user you log in with has the rights to do it, you can everything, what the remote git installation provides.
A:
When Git communicate with a remote host (over SSH / HTTP) it utilizes an internal protocol:
https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols
|
Is there something similar to Mercurial's Command Server in Git?
|
Mercurial's Command Server allows to issue commands to a Mercurial repository over a pipe through a special protocol... it is like a "webservice" of sorts.
https://www.mercurial-scm.org/wiki/CommandServer
Is there anything similar in Git in order to manipulate remote Git repositories to do things you need? (like switching to another branch or updating to another revision)
|
[
"Don't know exactly, what the mercurial command server does, but usually git utilizes ssh as its primary remote protocol.\nssh serverName \"cd /path/to/repo; git pull\"\nssh serverName \"git --git-dir=/path/to/repo pull\"\n\nSends a shell command to a remote ssh server serverName. As long as the user you log in with has the rights to do it, you can everything, what the remote git installation provides.\n",
"When Git communicate with a remote host (over SSH / HTTP) it utilizes an internal protocol:\nhttps://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols\n"
] |
[
3,
0
] |
[] |
[] |
[
"administration",
"git",
"version_control"
] |
stackoverflow_0014187904_administration_git_version_control.txt
|
Q:
Laravel 9 relations with subquery
I'm working on an educational game, this is basically the scheme:
Important: I need a question to be in multiple languages.
That is, a game will have many questions. And each question will have many languages.
Models:
Game, GameQuestion, QuestionGroup, Question, Languague
Relationships:
Game:
public function game_questions()
{
return $this->hasMany(GameQuestion::class);
}
GameQuestion:
public function question_groups()
{
return $this->belongsToMany(QuestionGroup::class, 'questions','question_group_id');
}
QuestionGroup:
public function questions()
{
return $this->hasMany(Question::class);
}
Question:
public function language()
{
return $this->belongsTo(Language::class);
}
Language:
public function questions()
{
return $this->hasMany(Question::class);
}
How can I retrieve with a search the collection of questions (many languages) added to the game?
$games = Game::where('user_id', $user_id)->orderBy('created_at', 'DESC')->with('game_question_question_group')->get();
I've already tried some consultations but I haven't had any luck. I appreciate the help.
A:
You need to use nested relationships:
$games = Game::where('user_id', $user_id)->with('game_questions.question_groups.questions')->orderBy('created_at', 'DESC')->get();
Read more about it here https://laravel.com/docs/9.x/eloquent-relationships#nested-eager-loading
But honestly, the database could be designed better
|
Laravel 9 relations with subquery
|
I'm working on an educational game, this is basically the scheme:
Important: I need a question to be in multiple languages.
That is, a game will have many questions. And each question will have many languages.
Models:
Game, GameQuestion, QuestionGroup, Question, Languague
Relationships:
Game:
public function game_questions()
{
return $this->hasMany(GameQuestion::class);
}
GameQuestion:
public function question_groups()
{
return $this->belongsToMany(QuestionGroup::class, 'questions','question_group_id');
}
QuestionGroup:
public function questions()
{
return $this->hasMany(Question::class);
}
Question:
public function language()
{
return $this->belongsTo(Language::class);
}
Language:
public function questions()
{
return $this->hasMany(Question::class);
}
How can I retrieve with a search the collection of questions (many languages) added to the game?
$games = Game::where('user_id', $user_id)->orderBy('created_at', 'DESC')->with('game_question_question_group')->get();
I've already tried some consultations but I haven't had any luck. I appreciate the help.
|
[
"You need to use nested relationships:\n$games = Game::where('user_id', $user_id)->with('game_questions.question_groups.questions')->orderBy('created_at', 'DESC')->get();\n\nRead more about it here https://laravel.com/docs/9.x/eloquent-relationships#nested-eager-loading\nBut honestly, the database could be designed better\n"
] |
[
0
] |
[] |
[] |
[
"laravel",
"laravel_9",
"relationship",
"subquery"
] |
stackoverflow_0074658244_laravel_laravel_9_relationship_subquery.txt
|
Q:
Matrix multiplication of a 2d numpy array to cpp using ctypes
What is a correct way to do the matrix multiplication using ctype ?
in my current implementation data going back and forth consuming lots of time, is there any way to do it optimally ? by passing array address and getting pointer in return instead of generating entire array using .contents method.
cpp_function.cpp
compile using g++ -shared -fPIC cpp_function.cpp -o cpp_function.so
#include <iostream>
extern "C" {
double* mult_matrix(double *a1, double *a2, size_t a1_h, size_t a1_w,
size_t a2_h, size_t a2_w, int size)
{
double* ret_arr = new double[size];
for(size_t i = 0; i < a1_h; i++){
for (size_t j = 0; j < a2_w; j++) {
double val = 0;
for (size_t k = 0; k < a2_h; k++){
val += a1[i * a1_h + k] * a2[k * a2_h +j] ;
}
ret_arr[i * a1_h +j ] = val;
// printf("%f ", ret_arr[i * a1_h +j ]);
}
// printf("\n");
}
return ret_arr;
}
}
Python file to call the so file
main.py
import ctypes
import numpy
from time import time
libmatmult = ctypes.CDLL("./cpp_function.so")
ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
libmatmult.mult_matrix.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
def mult_matrix_cpp(a,b):
shape = a.shape[0] * a.shape[1]
libmatmult.mult_matrix.restype = ctypes.POINTER(ctypes.c_double * shape )
ret_cpp = libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
out_list_c = [i for i in ret_cpp.contents] # <---- regenrating list which is time consuming
return out_list_c
size_a = (300,300)
size_b = size_a
a = numpy.random.uniform(low=1, high=255, size=size_a)
b = numpy.random.uniform(low=1, high=255, size=size_b)
t2 = time()
out_cpp = mult_matrix_cpp(a,b)
print("cpp time taken:{:.2f} ms".format((time() - t2) * 1000))
out_cpp = numpy.array(out_cpp).reshape(size_a[0], size_a[1])
t3 = time()
out_np = numpy.dot(a,b)
# print(out_np)
print("Numpy dot() time taken:{:.2f} ms".format((time() - t3) * 1000))
This solution works but time consuming is there any way to make it faster ?
A:
One reason for the time consumption is not using an ndpointer for the return value and copying it into a Python list. Instead use the following restype. You won't need the later reshape as well. But take the commenters' advice and don't reinvent the wheel.
def mult_matrix_cpp(a, b):
shape = a.shape[0] * a.shape[1]
libmatmult.mult_matrix.restype = np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, shape=a.shape, flags="C")
return libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
A:
One way to do this is to create a function that takes two two-dimensional arrays (representing matrices) as arguments, and returns a two-dimensional array containing the result of the matrix multiplication.
The code for this function could look like this:
#include <stdio.h>
// This function multiplies two matrices, and returns the result
// in a two-dimensional array
int** matrix_multiply(int** matrix1, int** matrix2, int rows1, int cols1, int rows2, int cols2) {
int** matrix_result = (int**)malloc(rows1 * sizeof(int*));
int i, j, k;
// Check if the matrices can be multiplied
if (cols1 != rows2) {
printf("Matrices cannot be multiplied!\n");
return NULL;
}
// Perform matrix multiplication
for (i = 0; i < rows1; i++) {
matrix_result[i] = (int*)malloc(cols2 * sizeof(int));
for (j = 0; j < cols2; j++) {
matrix_result[i][j] = 0;
for (k = 0; k < cols1; k++) {
matrix_result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return matrix_result;
}
int main(void) {
// Example matrices
int** matrix1 = (int**)malloc(2 * sizeof(int*));
matrix1[0] = (int*)malloc(2 * sizeof(int));
matrix1[1] = (int*)malloc(2 * sizeof(int));
matrix1[0][0] = 1; matrix1[0][1] = 2;
matrix1[1][0] = 3; matrix1[1][1] = 4;
int** matrix2 = (int**)malloc(2 * sizeof(int*));
matrix2[0] = (int*)malloc(2 * sizeof(int));
matrix2[1] = (int*)malloc(2 * sizeof(int));
matrix2[0][0] = 5; matrix2[0][1] = 6;
matrix2[1][0] = 7; matrix2[1][1] = 8;
// Do matrix multiplication
int** matrix_result = matrix_multiply(matrix1, matrix2, 2, 2, 2, 2);
// Print the result
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", matrix_result[i][j]);
}
printf("\n");
}
return 0;
}
|
Matrix multiplication of a 2d numpy array to cpp using ctypes
|
What is a correct way to do the matrix multiplication using ctype ?
in my current implementation data going back and forth consuming lots of time, is there any way to do it optimally ? by passing array address and getting pointer in return instead of generating entire array using .contents method.
cpp_function.cpp
compile using g++ -shared -fPIC cpp_function.cpp -o cpp_function.so
#include <iostream>
extern "C" {
double* mult_matrix(double *a1, double *a2, size_t a1_h, size_t a1_w,
size_t a2_h, size_t a2_w, int size)
{
double* ret_arr = new double[size];
for(size_t i = 0; i < a1_h; i++){
for (size_t j = 0; j < a2_w; j++) {
double val = 0;
for (size_t k = 0; k < a2_h; k++){
val += a1[i * a1_h + k] * a2[k * a2_h +j] ;
}
ret_arr[i * a1_h +j ] = val;
// printf("%f ", ret_arr[i * a1_h +j ]);
}
// printf("\n");
}
return ret_arr;
}
}
Python file to call the so file
main.py
import ctypes
import numpy
from time import time
libmatmult = ctypes.CDLL("./cpp_function.so")
ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
ndim=2,
flags="C")
libmatmult.mult_matrix.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
def mult_matrix_cpp(a,b):
shape = a.shape[0] * a.shape[1]
libmatmult.mult_matrix.restype = ctypes.POINTER(ctypes.c_double * shape )
ret_cpp = libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
out_list_c = [i for i in ret_cpp.contents] # <---- regenrating list which is time consuming
return out_list_c
size_a = (300,300)
size_b = size_a
a = numpy.random.uniform(low=1, high=255, size=size_a)
b = numpy.random.uniform(low=1, high=255, size=size_b)
t2 = time()
out_cpp = mult_matrix_cpp(a,b)
print("cpp time taken:{:.2f} ms".format((time() - t2) * 1000))
out_cpp = numpy.array(out_cpp).reshape(size_a[0], size_a[1])
t3 = time()
out_np = numpy.dot(a,b)
# print(out_np)
print("Numpy dot() time taken:{:.2f} ms".format((time() - t3) * 1000))
This solution works but time consuming is there any way to make it faster ?
|
[
"One reason for the time consumption is not using an ndpointer for the return value and copying it into a Python list. Instead use the following restype. You won't need the later reshape as well. But take the commenters' advice and don't reinvent the wheel.\ndef mult_matrix_cpp(a, b):\n shape = a.shape[0] * a.shape[1]\n libmatmult.mult_matrix.restype = np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, shape=a.shape, flags=\"C\")\n return libmatmult.mult_matrix(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])\n\n",
"One way to do this is to create a function that takes two two-dimensional arrays (representing matrices) as arguments, and returns a two-dimensional array containing the result of the matrix multiplication.\nThe code for this function could look like this:\n#include <stdio.h>\n\n// This function multiplies two matrices, and returns the result\n// in a two-dimensional array\nint** matrix_multiply(int** matrix1, int** matrix2, int rows1, int cols1, int rows2, int cols2) {\n int** matrix_result = (int**)malloc(rows1 * sizeof(int*));\n int i, j, k;\n\n // Check if the matrices can be multiplied\n if (cols1 != rows2) {\n printf(\"Matrices cannot be multiplied!\\n\");\n return NULL;\n }\n\n // Perform matrix multiplication\n for (i = 0; i < rows1; i++) {\n matrix_result[i] = (int*)malloc(cols2 * sizeof(int));\n for (j = 0; j < cols2; j++) {\n matrix_result[i][j] = 0;\n for (k = 0; k < cols1; k++) {\n matrix_result[i][j] += matrix1[i][k] * matrix2[k][j];\n }\n }\n }\n\n return matrix_result;\n}\n\nint main(void) {\n // Example matrices\n int** matrix1 = (int**)malloc(2 * sizeof(int*));\n matrix1[0] = (int*)malloc(2 * sizeof(int));\n matrix1[1] = (int*)malloc(2 * sizeof(int));\n matrix1[0][0] = 1; matrix1[0][1] = 2;\n matrix1[1][0] = 3; matrix1[1][1] = 4;\n\n int** matrix2 = (int**)malloc(2 * sizeof(int*));\n matrix2[0] = (int*)malloc(2 * sizeof(int));\n matrix2[1] = (int*)malloc(2 * sizeof(int));\n matrix2[0][0] = 5; matrix2[0][1] = 6;\n matrix2[1][0] = 7; matrix2[1][1] = 8;\n\n // Do matrix multiplication\n int** matrix_result = matrix_multiply(matrix1, matrix2, 2, 2, 2, 2);\n\n // Print the result\n int i, j;\n for (i = 0; i < 2; i++) {\n for (j = 0; j < 2; j++) {\n printf(\"%d \", matrix_result[i][j]);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"c++",
"ctypes",
"numpy",
"python"
] |
stackoverflow_0074612029_c++_ctypes_numpy_python.txt
|
Q:
how to update a variable in a text file
I have a program that opens an account and there are several lines but i want it to update this one line credits = 0 Whenever a purchase is made I want it to add one more to the amount this is what the file looks like
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
this bit of info is kept inside of a text file I don't care if you replace it (as long as it has 1 more) or whether you just update it. Please help me out :) sorry if this question is trival
A:
The below code snippet should give you an idea on how to go about. This code updates, the value of the counter variable present within a file counter_file.txt
import os
counter_file = open(r'./counter_file.txt', 'r+')
content_lines = []
for line in counter_file:
if 'counter=' in line:
line_components = line.split('=')
int_value = int(line_components[1]) + 1
line_components[1] = str(int_value)
updated_line= "=".join(line_components)
content_lines.append(updated_line)
else:
content_lines.append(line)
counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()
Hopefully, this sheds some light on how to go about with solving your problem
A:
You can create a general text file replacer based on a dictionary containing what to look for as keys and as corresponding values what to replace:
In the template text file put some flags where you want variables:
['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = <credit_var>
Then create a mapping dictionary:
map_dict = {'<namef>':'New name', '<credit_var>':1}
Then rewrite the text file doing the replacements:
newfile = open('new_file.txt', 'w')
for l in open('template.txt'):
for k,v in map_dict.iteritems():
l = l.replace(k,str(v))
newfile.write(l)
newfile.close()
A:
Rather than creating new files like new_file.txt or template.txt, you can use your existing file. Here I am using client_name and client_credit_score as place holders reflecting user data:
client_name="Joseph"
client_credit_score=1
map_dict = {'<namef>':f'{client_name}', '<credit_var>':f'{client_credit_score}'}
template = """['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = <credit_var>"""
with open('existing_file.txt', 'w') as f:
for k,v in map_dict.items():
template = template.replace(k,str(v))
f.write(template)
Here the existing_file.txt will have this code initially (like you question):
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
And thanks to the map_dict, all the keys will be updated with new values in your file. Here's what output will look like:
['Joseph', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 1
Note: Special thanks to @Saullo and @Tarun for the above answer.
|
how to update a variable in a text file
|
I have a program that opens an account and there are several lines but i want it to update this one line credits = 0 Whenever a purchase is made I want it to add one more to the amount this is what the file looks like
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
this bit of info is kept inside of a text file I don't care if you replace it (as long as it has 1 more) or whether you just update it. Please help me out :) sorry if this question is trival
|
[
"The below code snippet should give you an idea on how to go about. This code updates, the value of the counter variable present within a file counter_file.txt\nimport os\n\ncounter_file = open(r'./counter_file.txt', 'r+')\ncontent_lines = []\n\nfor line in counter_file:\n if 'counter=' in line:\n line_components = line.split('=')\n int_value = int(line_components[1]) + 1\n line_components[1] = str(int_value)\n updated_line= \"=\".join(line_components)\n content_lines.append(updated_line)\n else:\n content_lines.append(line)\n\ncounter_file.seek(0)\ncounter_file.truncate()\ncounter_file.writelines(content_lines)\ncounter_file.close()\n\nHopefully, this sheds some light on how to go about with solving your problem\n",
"You can create a general text file replacer based on a dictionary containing what to look for as keys and as corresponding values what to replace:\nIn the template text file put some flags where you want variables:\n['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']\n\ncredits = <credit_var>\n\nThen create a mapping dictionary:\nmap_dict = {'<namef>':'New name', '<credit_var>':1}\n\nThen rewrite the text file doing the replacements:\nnewfile = open('new_file.txt', 'w')\nfor l in open('template.txt'):\n for k,v in map_dict.iteritems():\n l = l.replace(k,str(v))\n newfile.write(l)\nnewfile.close()\n\n",
"Rather than creating new files like new_file.txt or template.txt, you can use your existing file. Here I am using client_name and client_credit_score as place holders reflecting user data:\nclient_name=\"Joseph\"\nclient_credit_score=1\n\nmap_dict = {'<namef>':f'{client_name}', '<credit_var>':f'{client_credit_score}'}\ntemplate = \"\"\"['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2'] \ncredits = <credit_var>\"\"\"\n\nwith open('existing_file.txt', 'w') as f:\n for k,v in map_dict.items():\n template = template.replace(k,str(v))\n f.write(template)\n\nHere the existing_file.txt will have this code initially (like you question):\n['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']\ncredits = 0\n\nAnd thanks to the map_dict, all the keys will be updated with new values in your file. Here's what output will look like:\n['Joseph', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']\ncredits = 1\n\nNote: Special thanks to @Saullo and @Tarun for the above answer.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"file",
"python",
"python_3.x",
"variables"
] |
stackoverflow_0018040596_file_python_python_3.x_variables.txt
|
Q:
Date and time in console log
Is their a way to mention the date and time in the console log of an asp.net core 2.0 project for production and development environment?
I have following in my startup:
services.AddLogging(builder =>
{
builder.AddConfiguration(Configuration.GetSection("Logging"+Environment.EnvironmentName))
.AddConsole()
.AddDebug();
});
Appsettings.json:
"LoggingDevelopment": {
"IncludeScopes": false,
"Console": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
},
"LoggingProduction": {
"IncludeScopes": false,
"Console": {
"LogLevel": {
"Default": "Error",
"System": "Error",
"Microsoft": "Error"
}
}
},
Current [development] log layout (without a date or time of the log line):
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action a.Controller (project) in 531.2457ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 532.5812ms 200 text/html; charset=utf-8
A date and time would be extremly handy in production mode for error lines.
A:
Default Console logger is pretty limited. Of course there is always the possibility to use lambda formatter like said in Github issue provided by serpent5. But it's accessible only if using raw ILogger.Log() method.
It's not available for ILogger extensions like LogInformation or LogError. This option is also not available if you don't control logging call. It's actually your case when logging is done by ASP.NET Core internal classes.
So you need some more flexible implementation of logger for .Net Core. I suggest using of Serilog. It's pretty simple but very flexible and powerful at the same time.
To integrate Serilog into ASP.Net Core application do the following:
Install following NuGet packages:
Serilog.AspNetCore
Serilog.Sinks.Console
Besides Console, Serilog supports many other targets like Rolling File, E-mail, SQL Server, etc. See this list of other Serilog targets.
Configure Serilog on application startup:
Here is a sample:
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")
.CreateLogger();
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog()
.Build();
}
Provided output template adds date and time to logged message:
A:
To expand on CodeFuller's response, here's how you can modify the Serilog Console output formatter purely from configuration:
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"System": "Information",
"Microsoft": "Information"
}
},
"WriteTo:Sublogger": {
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{TraceId}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
}
}
}
}
If you take this approach, remove the WriteTo.Console logger method from your startup configuration. This line:
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")
I've also modified the output format template slightly. Either template will work fine.
|
Date and time in console log
|
Is their a way to mention the date and time in the console log of an asp.net core 2.0 project for production and development environment?
I have following in my startup:
services.AddLogging(builder =>
{
builder.AddConfiguration(Configuration.GetSection("Logging"+Environment.EnvironmentName))
.AddConsole()
.AddDebug();
});
Appsettings.json:
"LoggingDevelopment": {
"IncludeScopes": false,
"Console": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
},
"LoggingProduction": {
"IncludeScopes": false,
"Console": {
"LogLevel": {
"Default": "Error",
"System": "Error",
"Microsoft": "Error"
}
}
},
Current [development] log layout (without a date or time of the log line):
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action a.Controller (project) in 531.2457ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 532.5812ms 200 text/html; charset=utf-8
A date and time would be extremly handy in production mode for error lines.
|
[
"Default Console logger is pretty limited. Of course there is always the possibility to use lambda formatter like said in Github issue provided by serpent5. But it's accessible only if using raw ILogger.Log() method.\nIt's not available for ILogger extensions like LogInformation or LogError. This option is also not available if you don't control logging call. It's actually your case when logging is done by ASP.NET Core internal classes.\nSo you need some more flexible implementation of logger for .Net Core. I suggest using of Serilog. It's pretty simple but very flexible and powerful at the same time.\nTo integrate Serilog into ASP.Net Core application do the following:\n\nInstall following NuGet packages:\nSerilog.AspNetCore\nSerilog.Sinks.Console\nBesides Console, Serilog supports many other targets like Rolling File, E-mail, SQL Server, etc. See this list of other Serilog targets.\nConfigure Serilog on application startup:\n\nHere is a sample:\npublic class Program\n{\n public static void Main(string[] args)\n {\n Log.Logger = new LoggerConfiguration()\n .MinimumLevel.Debug()\n .MinimumLevel.Override(\"Microsoft\", LogEventLevel.Information)\n .Enrich.FromLogContext()\n .WriteTo.Console(outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}\")\n .CreateLogger();\n\n BuildWebHost(args).Run();\n }\n\n public static IWebHost BuildWebHost(string[] args) =>\n WebHost.CreateDefaultBuilder(args)\n .UseStartup<Startup>()\n .UseSerilog()\n .Build();\n}\n\nProvided output template adds date and time to logged message:\n\n",
"To expand on CodeFuller's response, here's how you can modify the Serilog Console output formatter purely from configuration:\n{\n \"Serilog\": {\n \"MinimumLevel\": {\n \"Default\": \"Debug\",\n \"Override\": {\n \"System\": \"Information\",\n \"Microsoft\": \"Information\"\n }\n },\n \"WriteTo:Sublogger\": {\n \"Name\": \"Logger\",\n \"Args\": {\n \"configureLogger\": {\n \"WriteTo\": [\n {\n \"Name\": \"Console\",\n \"Args\": {\n \"outputTemplate\": \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{TraceId}] {Message:lj}{NewLine}{Exception}\"\n }\n }\n ]\n }\n }\n }\n }\n}\n\nIf you take this approach, remove the WriteTo.Console logger method from your startup configuration. This line:\n .WriteTo.Console(outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}\")\n\nI've also modified the output format template slightly. Either template will work fine.\n"
] |
[
5,
0
] |
[] |
[] |
[
"asp.net_core"
] |
stackoverflow_0047815138_asp.net_core.txt
|
Q:
Duplicate websocket subscription in Azure webapp
I have a node.js app running in Azure as a webApp. On startup it connects to an external service using a websocket subscription. Specifically I'm using the reconnecting-websockets NPM package to wrap it to handle disconnects.
The problem I am having is that because there are 2 instances of the app running on Azure (horizontal scaling for failover) I end up with two subscriptions at any one time.
Is there an obvious way to solve this problem?
For extra context, this is a problem for 2 reasons:
I pay for each message received and am over quota
When messages are received I process then and do database updates, these are also being duplicated.
A:
One possible solution to this problem would be to use a shared session state management solution, such as Azure Redis Cache, to store the websocket subscription information. This way, both instances of the app can access the same subscription information and only one subscription will be created.
Another solution would be to use Azure App Service's deployment slots feature, where one instance of the app is designated as the "primary" instance and handles the websocket subscription. The other instance acts as a standby in case the primary instance fails. This way, only one instance of the app is actively handling the websocket subscription at any given time.
Additionally, it may be helpful to implement some logic in the app to check if a websocket subscription already exists before creating a new one, to prevent duplicate subscriptions from being created.
|
Duplicate websocket subscription in Azure webapp
|
I have a node.js app running in Azure as a webApp. On startup it connects to an external service using a websocket subscription. Specifically I'm using the reconnecting-websockets NPM package to wrap it to handle disconnects.
The problem I am having is that because there are 2 instances of the app running on Azure (horizontal scaling for failover) I end up with two subscriptions at any one time.
Is there an obvious way to solve this problem?
For extra context, this is a problem for 2 reasons:
I pay for each message received and am over quota
When messages are received I process then and do database updates, these are also being duplicated.
|
[
"One possible solution to this problem would be to use a shared session state management solution, such as Azure Redis Cache, to store the websocket subscription information. This way, both instances of the app can access the same subscription information and only one subscription will be created.\nAnother solution would be to use Azure App Service's deployment slots feature, where one instance of the app is designated as the \"primary\" instance and handles the websocket subscription. The other instance acts as a standby in case the primary instance fails. This way, only one instance of the app is actively handling the websocket subscription at any given time.\nAdditionally, it may be helpful to implement some logic in the app to check if a websocket subscription already exists before creating a new one, to prevent duplicate subscriptions from being created.\n"
] |
[
0
] |
[] |
[] |
[
"azure",
"azure_web_app_service",
"javascript",
"node.js",
"websocket"
] |
stackoverflow_0074537579_azure_azure_web_app_service_javascript_node.js_websocket.txt
|
Q:
Comparing time.Time out of MySQL with Before seems not working
I'm trying to compare two time.Time dates in Go using the Before function.
The issue is that one of these dates comes from a MySQL datetime field.
When I Scan the result, it is saved as a UTC timezone, but I wrote in database in my local time (UTC +1). This is a problem when I compare the database date with a time.Now() that is in my local time.
I extracted the date with a scan into a time.Time variable with ?parseTime=true on the connection string.
Do you have any suggestion? I don't want to add 1 hour after reading the date from the DB because it can cause me problems with summer time (UTC +2).
I tried to extract the date from DB and convert with UTC function:
data, _ = time.Parse("2006-01-02 15:04:05", data.UTC().Format("2006-01-02 15:04:05"))
but without any success.
|
Comparing time.Time out of MySQL with Before seems not working
|
I'm trying to compare two time.Time dates in Go using the Before function.
The issue is that one of these dates comes from a MySQL datetime field.
When I Scan the result, it is saved as a UTC timezone, but I wrote in database in my local time (UTC +1). This is a problem when I compare the database date with a time.Now() that is in my local time.
I extracted the date with a scan into a time.Time variable with ?parseTime=true on the connection string.
Do you have any suggestion? I don't want to add 1 hour after reading the date from the DB because it can cause me problems with summer time (UTC +2).
I tried to extract the date from DB and convert with UTC function:
data, _ = time.Parse("2006-01-02 15:04:05", data.UTC().Format("2006-01-02 15:04:05"))
but without any success.
|
[] |
[] |
[
"to convert a mysql datetime value to a Go time.Time correctly I recommend this code:\ndatesplit := strings.Split(mysql_datetime, \" \")\nrfc3339_datetime = datesplit[0] + \"T\" + datesplit[1] + \"Z\"\ngodate, _ = time.Parse(time.RFC3339, datetime)\n\n"
] |
[
-1
] |
[
"datetime",
"go",
"time",
"timezone"
] |
stackoverflow_0074662036_datetime_go_time_timezone.txt
|
Q:
Reversing a txt File in python
Assume you are given a file called newText.txt which contains the lines:
line 1
line 2
line 3
Write a python program that reads the data from newText.txt and writes a new file called newerText.txt in the following format:
line 3
Python Inserted a new line
line 2
line 1
I can get it reversed but the line 2 and line 3 are in the same line.
I also need help appending the new line between line 2 and line 3.
Input
lines = []
with open('text.txt') as f:
lines = f.readlines()
with open('newtext.txt', 'w') as f:
for line in reversed(lines):
f.write(line)
Output
line3line2
line1
A:
If you look into what text.txt actually is, it's probably something like this:
line1\nline2\nline3
Notice how each line is divided by a new line character (\n). This means the last line doesn't have a new line at the end of it, so when you write it to newText.txt, it won't have a newline.
What you can do is strip away all possible new lines, then add one yourself:
with open('newtext.txt', 'w') as f:
for line in reversed(lines):
f.write(line.strip() + "\n")
|
Reversing a txt File in python
|
Assume you are given a file called newText.txt which contains the lines:
line 1
line 2
line 3
Write a python program that reads the data from newText.txt and writes a new file called newerText.txt in the following format:
line 3
Python Inserted a new line
line 2
line 1
I can get it reversed but the line 2 and line 3 are in the same line.
I also need help appending the new line between line 2 and line 3.
Input
lines = []
with open('text.txt') as f:
lines = f.readlines()
with open('newtext.txt', 'w') as f:
for line in reversed(lines):
f.write(line)
Output
line3line2
line1
|
[
"If you look into what text.txt actually is, it's probably something like this:\nline1\\nline2\\nline3\n\nNotice how each line is divided by a new line character (\\n). This means the last line doesn't have a new line at the end of it, so when you write it to newText.txt, it won't have a newline.\nWhat you can do is strip away all possible new lines, then add one yourself:\nwith open('newtext.txt', 'w') as f:\n for line in reversed(lines):\n f.write(line.strip() + \"\\n\")\n\n"
] |
[
1
] |
[] |
[] |
[
"append",
"python",
"reverse"
] |
stackoverflow_0074662524_append_python_reverse.txt
|
Q:
How to delegate O365 authentication to a SSO provider other than Azure AD?
Here is the use case:
User access O365 URL
User should be challenged for authentication by a SSO / authentication provider (e.g., Okta / miniOrange / AuthPoint etc.)
The SSO solution in turn authenticates against Azure AD (userid and Azure AD password)
What I tried and observed:
Created a custom federated domain in Azure AD
User now is redirected to the SSO provider
If user is allowed to authenticate against local credential of the SSO provider, user is able to access O365
What I need is to authenticate with Azure AD credentials (not using on-prem AD)
I tried with ADDS as well but the problem is the moment I set the federated domain as UPN of the user, AAD does not allow to manage the user anymore including password changes
Questions:
Other than using custom domain, is there any other way to use a non-Microsoft authentication provider?
If I use Azure AD authentication, what are the options for using a third-party MFA provider? (E.g., OATH token)
Is it even possible to use federated custom domain in Azure AD and then let the IdP authenticate against Azure AD (via APIs or by using AAD as IdP)?
A:
Answers:
Other than using custom domain, is there any other way to use a non-Microsoft authentication provider?
Yes, some providers, such as Google, do not require custom domain names added. For more infomation take a look at Identity Providers for External Identities.
If I use Azure AD authentication, what are the options for using a third-party MFA provider? (E.g., OATH token)
Yes, Azure AD supports OATH tokens, FIDO2 keys and more. For more information take a look to What authentication and verification methods are available in Azure Active Directory?
Is it even possible to use federated custom domain in Azure AD and then let the IdP authenticate against Azure AD (via APIs or by using AAD as IdP)?
That would defeat the purpose of federation.
|
How to delegate O365 authentication to a SSO provider other than Azure AD?
|
Here is the use case:
User access O365 URL
User should be challenged for authentication by a SSO / authentication provider (e.g., Okta / miniOrange / AuthPoint etc.)
The SSO solution in turn authenticates against Azure AD (userid and Azure AD password)
What I tried and observed:
Created a custom federated domain in Azure AD
User now is redirected to the SSO provider
If user is allowed to authenticate against local credential of the SSO provider, user is able to access O365
What I need is to authenticate with Azure AD credentials (not using on-prem AD)
I tried with ADDS as well but the problem is the moment I set the federated domain as UPN of the user, AAD does not allow to manage the user anymore including password changes
Questions:
Other than using custom domain, is there any other way to use a non-Microsoft authentication provider?
If I use Azure AD authentication, what are the options for using a third-party MFA provider? (E.g., OATH token)
Is it even possible to use federated custom domain in Azure AD and then let the IdP authenticate against Azure AD (via APIs or by using AAD as IdP)?
|
[
"Answers:\n\nOther than using custom domain, is there any other way to use a non-Microsoft authentication provider?\nYes, some providers, such as Google, do not require custom domain names added. For more infomation take a look at Identity Providers for External Identities.\n\nIf I use Azure AD authentication, what are the options for using a third-party MFA provider? (E.g., OATH token)\nYes, Azure AD supports OATH tokens, FIDO2 keys and more. For more information take a look to What authentication and verification methods are available in Azure Active Directory?\n\nIs it even possible to use federated custom domain in Azure AD and then let the IdP authenticate against Azure AD (via APIs or by using AAD as IdP)?\nThat would defeat the purpose of federation.\n\n\n"
] |
[
0
] |
[] |
[] |
[
"azure_active_directory"
] |
stackoverflow_0074463460_azure_active_directory.txt
|
Q:
Appending a list with a dictionary key that contains multiple values from a json response
I'm traversing a json response in which stats are grouped by games played. I want to gather all of the values from the set and assign a single dictionary key to them. Currently every value has its own key. Here is a sample of the json response:
{'data': [{'ast': 9,
'blk': 0,
'dreb': 4,
'fg3_pct': 0.0,
'fg3a': 2,
'fg3m': 0,
'fg_pct': 0.6,
'fga': 20,
'fgm': 12,
'ft_pct': 0.333,
'fta': 3,
'ftm': 1,
'game': {'date': '2003-10-29T00:00:00.000Z',
'home_team_id': 26,
'home_team_score': 106,
'id': 15946,
'period': 4,
'postseason': False,
'season': 2003,
'status': 'Final',
'time': ' ',
'visitor_team_id': 6,
'visitor_team_score': 92},
'id': 361330,
'min': '42:50',
'oreb': 2,
'pf': 3,
'player': {'first_name': 'LeBron',
'height_feet': 6,
'height_inches': 8,
'id': 237,
'last_name': 'James',
'position': 'F',
'team_id': 14,
'weight_pounds': 250},
'pts': 25,
'reb': 6,
'stl': 4,
'team': {'abbreviation': 'CLE',
'city': 'Cleveland',
'conference': 'East',
'division': 'Central',
'full_name': 'Cleveland Cavaliers',
'id': 6,
'name': 'Cavaliers'},
'turnover': 2},
{'ast': 8,
'blk': 0,
'dreb': 10,
'fg3_pct': 0.2,
'fg3a': 5,
'fg3m': 1,
'fg_pct': 0.471,
'fga': 17,
'fgm': 8,
'ft_pct': 0.571,
'fta': 7,
'ftm': 4,
'game': {'date': '2003-10-30T00:00:00.000Z',
'home_team_id': 24,
'home_team_score': 95,
'id': 16277,
'period': 4,
'postseason': False,
'season': 2003,
'status': 'Final',
'time': ' ',
'visitor_team_id': 6,
'visitor_team_score': 86},
'id': 361523,
'min': '40:21',
'oreb': 2,
'pf': 1,
'player': {'first_name': 'LeBron',
'height_feet': 6,
'height_inches': 8,
'id': 237,
'last_name': 'James',
'position': 'F',
'team_id': 14,
'weight_pounds': 250},
'pts': 21,
'reb': 12,
'stl': 1,
'team': {'abbreviation': 'CLE',
'city': 'Cleveland',
'conference': 'East',
'division': 'Central',
'full_name': 'Cleveland Cavaliers',
'id': 6,
'name': 'Cavaliers'},
'turnover': 7},
This is my code:
players_stats=[]
players_game_stats_url="https://balldontlie.io/api/v1/stats?season[]=2018&player_ids[]=237"
result=requests.get(players_game_stats_url).json()
for assists in result['data']:
players_stats.append({"Assists per game":assists['ast']})
What I would like to produce is something like this:
{Assists per game:9,8,6,7,3}
But what I'm getting is this:
[{'Assists per game': 9},
{'Assists per game': 8},
{'Assists per game': 6},
{'Assists per game': 7},
{'Assists per game': 3},
{'Assists per game': 9},
{'Assists per game': 4},
{'Assists per game': 7},
{'Assists per game': 3},
{'Assists per game': 8},
{'Assists per game': 8},
{'Assists per game': 8},
{'Assists per game': 2},
{'Assists per game': 4},
{'Assists per game': 9},
{'Assists per game': 7},
{'Assists per game': 7},
{'Assists per game': 5},
{'Assists per game': 8},
{'Assists per game': 5},
{'Assists per game': 3},
{'Assists per game': 9},
{'Assists per game': 4},
{'Assists per game': 6},
{'Assists per game': 3}]
A:
Based the comment from Kenny Ostrom
output = {"Assists per game": [game_info['ast'] for game_info in result['data']]}
which is going to result like you asked
{'Assists per game': [9, 8]}
|
Appending a list with a dictionary key that contains multiple values from a json response
|
I'm traversing a json response in which stats are grouped by games played. I want to gather all of the values from the set and assign a single dictionary key to them. Currently every value has its own key. Here is a sample of the json response:
{'data': [{'ast': 9,
'blk': 0,
'dreb': 4,
'fg3_pct': 0.0,
'fg3a': 2,
'fg3m': 0,
'fg_pct': 0.6,
'fga': 20,
'fgm': 12,
'ft_pct': 0.333,
'fta': 3,
'ftm': 1,
'game': {'date': '2003-10-29T00:00:00.000Z',
'home_team_id': 26,
'home_team_score': 106,
'id': 15946,
'period': 4,
'postseason': False,
'season': 2003,
'status': 'Final',
'time': ' ',
'visitor_team_id': 6,
'visitor_team_score': 92},
'id': 361330,
'min': '42:50',
'oreb': 2,
'pf': 3,
'player': {'first_name': 'LeBron',
'height_feet': 6,
'height_inches': 8,
'id': 237,
'last_name': 'James',
'position': 'F',
'team_id': 14,
'weight_pounds': 250},
'pts': 25,
'reb': 6,
'stl': 4,
'team': {'abbreviation': 'CLE',
'city': 'Cleveland',
'conference': 'East',
'division': 'Central',
'full_name': 'Cleveland Cavaliers',
'id': 6,
'name': 'Cavaliers'},
'turnover': 2},
{'ast': 8,
'blk': 0,
'dreb': 10,
'fg3_pct': 0.2,
'fg3a': 5,
'fg3m': 1,
'fg_pct': 0.471,
'fga': 17,
'fgm': 8,
'ft_pct': 0.571,
'fta': 7,
'ftm': 4,
'game': {'date': '2003-10-30T00:00:00.000Z',
'home_team_id': 24,
'home_team_score': 95,
'id': 16277,
'period': 4,
'postseason': False,
'season': 2003,
'status': 'Final',
'time': ' ',
'visitor_team_id': 6,
'visitor_team_score': 86},
'id': 361523,
'min': '40:21',
'oreb': 2,
'pf': 1,
'player': {'first_name': 'LeBron',
'height_feet': 6,
'height_inches': 8,
'id': 237,
'last_name': 'James',
'position': 'F',
'team_id': 14,
'weight_pounds': 250},
'pts': 21,
'reb': 12,
'stl': 1,
'team': {'abbreviation': 'CLE',
'city': 'Cleveland',
'conference': 'East',
'division': 'Central',
'full_name': 'Cleveland Cavaliers',
'id': 6,
'name': 'Cavaliers'},
'turnover': 7},
This is my code:
players_stats=[]
players_game_stats_url="https://balldontlie.io/api/v1/stats?season[]=2018&player_ids[]=237"
result=requests.get(players_game_stats_url).json()
for assists in result['data']:
players_stats.append({"Assists per game":assists['ast']})
What I would like to produce is something like this:
{Assists per game:9,8,6,7,3}
But what I'm getting is this:
[{'Assists per game': 9},
{'Assists per game': 8},
{'Assists per game': 6},
{'Assists per game': 7},
{'Assists per game': 3},
{'Assists per game': 9},
{'Assists per game': 4},
{'Assists per game': 7},
{'Assists per game': 3},
{'Assists per game': 8},
{'Assists per game': 8},
{'Assists per game': 8},
{'Assists per game': 2},
{'Assists per game': 4},
{'Assists per game': 9},
{'Assists per game': 7},
{'Assists per game': 7},
{'Assists per game': 5},
{'Assists per game': 8},
{'Assists per game': 5},
{'Assists per game': 3},
{'Assists per game': 9},
{'Assists per game': 4},
{'Assists per game': 6},
{'Assists per game': 3}]
|
[
"Based the comment from Kenny Ostrom\n output = {\"Assists per game\": [game_info['ast'] for game_info in result['data']]}\n\nwhich is going to result like you asked\n {'Assists per game': [9, 8]}\n\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"json",
"list",
"python",
"python_3.x"
] |
stackoverflow_0074661957_dictionary_json_list_python_python_3.x.txt
|
Q:
Why is my scanf not taking in my choice and going through the loop?
Whenever I input the number 1, it keeps going through the print_menu(); function.
If choice was == to 1 I was expecting that the while loop will continue and go through the if statement, but it does not. Insted it keeps printing me the menu. Infact if I put any number it prints me the menu.
while (run_game==TRUE) {
print_menu();
scanf("%d", &choice);
choice = choice1;
if (choice1 == 1) {
while (hands<10);
shuffle(card_deck);
deal(card_deck, face, suit);
print_hand(face, suit, p1_hand);
printf("You have these cards in your hand:\n");
p1_score = check_hand(p1_hand);
p2_score = check_hand(p2_hand);
printf("Player one has :%d points", p1_score);
printf("Redraw card?\n 1.Yes, 2. No");
scanf("%d", &ans);
if (ans == 1) {
while (ans > 3) {
print_hand(face, suit, p1_hand);
}
}
}
}
}
A:
Did you mean to scanf to choice1?
scanf("%d", &choice1);
If not, then the next line is overwriting choice and it's always going to be what choice1 was at the start.
|
Why is my scanf not taking in my choice and going through the loop?
|
Whenever I input the number 1, it keeps going through the print_menu(); function.
If choice was == to 1 I was expecting that the while loop will continue and go through the if statement, but it does not. Insted it keeps printing me the menu. Infact if I put any number it prints me the menu.
while (run_game==TRUE) {
print_menu();
scanf("%d", &choice);
choice = choice1;
if (choice1 == 1) {
while (hands<10);
shuffle(card_deck);
deal(card_deck, face, suit);
print_hand(face, suit, p1_hand);
printf("You have these cards in your hand:\n");
p1_score = check_hand(p1_hand);
p2_score = check_hand(p2_hand);
printf("Player one has :%d points", p1_score);
printf("Redraw card?\n 1.Yes, 2. No");
scanf("%d", &ans);
if (ans == 1) {
while (ans > 3) {
print_hand(face, suit, p1_hand);
}
}
}
}
}
|
[
"Did you mean to scanf to choice1?\n scanf(\"%d\", &choice1);\n\nIf not, then the next line is overwriting choice and it's always going to be what choice1 was at the start.\n"
] |
[
1
] |
[] |
[] |
[
"c",
"logic",
"scanf",
"while_loop"
] |
stackoverflow_0074662503_c_logic_scanf_while_loop.txt
|
Q:
Cn you please check my css code, what I want is, when I press submit button next page should open and all the signup form info should print
Can you please check my css code, what I want is, when I press submit button next page should open and all the signup form info should print info on the next page.
Website is making me write some more detail which is not needed
CSS
html, body {
min-height: 100%;
}
body, div, form, input, select, p, button, radio {
padding: 0;
margin: 0;
outline: none;
font-family: sans-serif;
font-size: 16px;
color: #eee;
}
body {
background-color: Grey;
background-size: cover;
}
@media print {
h1, h2 {page-break-before: always;}
}
{
text-transform: uppercase;
font-weight: 200;
}
@media print {
h2 {page-break-before: always;}
{
margin: 0 0 0 8px;
}
.main-block {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
padding: 100px;
background: rgba(0, 0, 0, 0.8);
padding: 20px;
padding: 25px 15px;
margin-bottom: 1.3rem;
}
.left-part, form {
padding: 20px;
padding: 25px 15px;
margin-bottom: 1.3rem;
}
.left-part {
text-align: center;
}
form {
background: rgba(0, 0, 0, 0.7);
border: 3px solid;
outline: 0;
}
.title {
display: flex;
align-items: center;
margin-bottom: 50px;
}
.info {
display: flex;
flex-direction: column;
}
radio {
font-family: sans-serif;
font-size: 16px;
}
input, select {
padding: 5px;
margin-bottom: 30px;
background: transparent;
border: none;
border-bottom: 1px solid #eee;
}
input::placeholder {
color: #eee;
}
option:focus {
border: none;
}
option {
background: black;
border: none;
}
.checkbox input {
margin: 0 10px 0 0;
vertical-align: middle;
}
.checkbox a {
color: #26a9e0;
}
.checkbox a:hover {
color: #85d6de;
}
.btn-item, button {
padding: 10px 5px;
margin-top: 20px;
border-radius: 5px;
border: none;
background: #26a9e0;
text-decoration: none;
font-size: 15px;
font-weight: 400;
color: #fff;
}
.btn-item {
display: inline-block;
margin: 20px 5px 0;
}
button {
padding: 0.6rem 1.2rem;
background: #554258;
border: 2px solid #554258;
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
button:hover, .btn-item:hover {
background: #a1636a;
}
.textbox {
margin: 20px 0px 0
}
p {
color: white;
font-size: 18px;
width: 100%;
}
footer {
background-color: #7C677F;
padding: 25px;
font-size: 1px;
width: 100%;
margin-top: 0;
margin-bottom: 12px;
font-weight: bold;
font-size: 16px;
}
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=email] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=zip] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=city] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=number] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=radio] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=checkbox] {
width: 8%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
table {
border-Style: solid;
I was expecting that through my code I will open signup form with all details in a separate page.
|
Cn you please check my css code, what I want is, when I press submit button next page should open and all the signup form info should print
|
Can you please check my css code, what I want is, when I press submit button next page should open and all the signup form info should print info on the next page.
Website is making me write some more detail which is not needed
CSS
html, body {
min-height: 100%;
}
body, div, form, input, select, p, button, radio {
padding: 0;
margin: 0;
outline: none;
font-family: sans-serif;
font-size: 16px;
color: #eee;
}
body {
background-color: Grey;
background-size: cover;
}
@media print {
h1, h2 {page-break-before: always;}
}
{
text-transform: uppercase;
font-weight: 200;
}
@media print {
h2 {page-break-before: always;}
{
margin: 0 0 0 8px;
}
.main-block {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
padding: 100px;
background: rgba(0, 0, 0, 0.8);
padding: 20px;
padding: 25px 15px;
margin-bottom: 1.3rem;
}
.left-part, form {
padding: 20px;
padding: 25px 15px;
margin-bottom: 1.3rem;
}
.left-part {
text-align: center;
}
form {
background: rgba(0, 0, 0, 0.7);
border: 3px solid;
outline: 0;
}
.title {
display: flex;
align-items: center;
margin-bottom: 50px;
}
.info {
display: flex;
flex-direction: column;
}
radio {
font-family: sans-serif;
font-size: 16px;
}
input, select {
padding: 5px;
margin-bottom: 30px;
background: transparent;
border: none;
border-bottom: 1px solid #eee;
}
input::placeholder {
color: #eee;
}
option:focus {
border: none;
}
option {
background: black;
border: none;
}
.checkbox input {
margin: 0 10px 0 0;
vertical-align: middle;
}
.checkbox a {
color: #26a9e0;
}
.checkbox a:hover {
color: #85d6de;
}
.btn-item, button {
padding: 10px 5px;
margin-top: 20px;
border-radius: 5px;
border: none;
background: #26a9e0;
text-decoration: none;
font-size: 15px;
font-weight: 400;
color: #fff;
}
.btn-item {
display: inline-block;
margin: 20px 5px 0;
}
button {
padding: 0.6rem 1.2rem;
background: #554258;
border: 2px solid #554258;
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
button:hover, .btn-item:hover {
background: #a1636a;
}
.textbox {
margin: 20px 0px 0
}
p {
color: white;
font-size: 18px;
width: 100%;
}
footer {
background-color: #7C677F;
padding: 25px;
font-size: 1px;
width: 100%;
margin-top: 0;
margin-bottom: 12px;
font-weight: bold;
font-size: 16px;
}
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=email] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=zip] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=city] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=number] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=radio] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=checkbox] {
width: 8%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
table {
border-Style: solid;
I was expecting that through my code I will open signup form with all details in a separate page.
|
[] |
[] |
[
"I guess you cant do that with just css and html.\nyou actually need cookies.\nfor that you need to use Node.js or ASP.NET\n"
] |
[
-1
] |
[
"css",
"html"
] |
stackoverflow_0074662417_css_html.txt
|
Q:
PageView.animateToPage not working for elasticInOut Animation
I've a PageView with 3 pages(initial page:0). What I'm intending to do is to create a 3 section page with a back button which only displays if not in the initial page.
The code used to navigate to the other pages from initial page. (Working without issues)
pageController.animateToPage(1,
duration: Duration(milliseconds: 500),
curve: Curves.easeIn);
}),
[easeIn animation, 500ms duration]
The Code used for the back button
pageController.animateToPage(pageController.initialPage,
duration: Duration(milliseconds: 500),
curve: Curves.elasticInOut
);
[elasticInOut animation, 500ms duration]
When trying to go back from page(2) to page(0) this won't work, however it works fine while going back from page(1) to page(0).
What Seems To Fix It?
Reducing duration to 250ms or less
Changing curve to easeIn
Changing animateToPage to jumpTopage
So is this a known limitation of Flutter or am I doing something wrong?
A:
I think this happens with any curve that initially produces a negative value (like Curves.elasticInOut). I can't pinpoint the exact line (I suspect it's in applyUserOffset from ScrollPositionWithSingleContext), but negative values seem to be treated as if the animation has already completed. It may occasionally work with smaller/faster animations that produce values that are "less negative" (or close enough to zero).
Curves.linear or Curves.ease* don't produce negative values, so they should work consistently.
A:
Setting the PageView scroll-behavior to Cupertino (which allows negative values) seems to fix the problem
PageView(
controller: controller,
scrollBehavior: CupertinoScrollBehavior(),
children: [
|
PageView.animateToPage not working for elasticInOut Animation
|
I've a PageView with 3 pages(initial page:0). What I'm intending to do is to create a 3 section page with a back button which only displays if not in the initial page.
The code used to navigate to the other pages from initial page. (Working without issues)
pageController.animateToPage(1,
duration: Duration(milliseconds: 500),
curve: Curves.easeIn);
}),
[easeIn animation, 500ms duration]
The Code used for the back button
pageController.animateToPage(pageController.initialPage,
duration: Duration(milliseconds: 500),
curve: Curves.elasticInOut
);
[elasticInOut animation, 500ms duration]
When trying to go back from page(2) to page(0) this won't work, however it works fine while going back from page(1) to page(0).
What Seems To Fix It?
Reducing duration to 250ms or less
Changing curve to easeIn
Changing animateToPage to jumpTopage
So is this a known limitation of Flutter or am I doing something wrong?
|
[
"I think this happens with any curve that initially produces a negative value (like Curves.elasticInOut). I can't pinpoint the exact line (I suspect it's in applyUserOffset from ScrollPositionWithSingleContext), but negative values seem to be treated as if the animation has already completed. It may occasionally work with smaller/faster animations that produce values that are \"less negative\" (or close enough to zero).\nCurves.linear or Curves.ease* don't produce negative values, so they should work consistently.\n",
"Setting the PageView scroll-behavior to Cupertino (which allows negative values) seems to fix the problem\nPageView(\n controller: controller,\n scrollBehavior: CupertinoScrollBehavior(),\n children: [\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"flutter",
"flutter_animation"
] |
stackoverflow_0064728128_flutter_flutter_animation.txt
|
Q:
How to make CMD stop opening as administrator
So I'm creating a batch project, everything is fine, but suddenly the cmd automatically opens as administrator.
I tried finding something in registry keys, looking almost an hour for an answer online, etc.
How can I disable cmd opening as administrator?
(It's almost 12pm in my country, sorry if i don't answer quickly)
A:
See if this has what you are looking for:
CMD as admin
My guess is you have one of the issues mentioned in this thread
Edit: (yes this is windows 7 but many of the same principals apply to win10/11)
A:
I restarted my PC, as for now the batch file is working once again, now at least I know what to do if that ever happens again.
|
How to make CMD stop opening as administrator
|
So I'm creating a batch project, everything is fine, but suddenly the cmd automatically opens as administrator.
I tried finding something in registry keys, looking almost an hour for an answer online, etc.
How can I disable cmd opening as administrator?
(It's almost 12pm in my country, sorry if i don't answer quickly)
|
[
"See if this has what you are looking for:\nCMD as admin\nMy guess is you have one of the issues mentioned in this thread\nEdit: (yes this is windows 7 but many of the same principals apply to win10/11)\n",
"I restarted my PC, as for now the batch file is working once again, now at least I know what to do if that ever happens again.\n"
] |
[
0,
0
] |
[] |
[] |
[
"cmd"
] |
stackoverflow_0074662327_cmd.txt
|
Q:
How can I add an extra label/slide button to a FlyoutItem in MAUI?
I encountered an UI issue when developing an app using MAUI flyoutItem. According to the official doc, it looks like I can only define the flyoutItem appearance by setting two columns(https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/flyout?view=net-maui-7.0): one bind to FlyoutIcon and the other bind to Title.
What if I want to add a third item such as a label for identity/status or a slide button to enable/disable? I expect sth look like this:
[column 0]FlyoutIcon [column 1]Label1 [column 2]Label2/Slide Button
Can you please also show me some sample code for the solution?
Best and Regards
I tried to modify the Grid to add a third column and addition Label but seems not working.
<Shell ...>
...
<Shell.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="0.2*,0.4*,0.4*">
<Image Source="{Binding FlyoutIcon}"
Margin="5"
HeightRequest="45" />
<Label Grid.Column="1"
Text="{Binding Title}"
FontAttributes="Italic"
VerticalTextAlignment="Center" />
<Label Grid.Column="2"
Text="{Binding Text}"
FontAttributes="Italic"
VerticalTextAlignment="End" />
</Grid>
</DataTemplate>
</Shell.ItemTemplate>
</Shell>
A:
Er, guys. Looks like using Menu Item instead of FlyoutItem will resolve the issue.
|
How can I add an extra label/slide button to a FlyoutItem in MAUI?
|
I encountered an UI issue when developing an app using MAUI flyoutItem. According to the official doc, it looks like I can only define the flyoutItem appearance by setting two columns(https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/flyout?view=net-maui-7.0): one bind to FlyoutIcon and the other bind to Title.
What if I want to add a third item such as a label for identity/status or a slide button to enable/disable? I expect sth look like this:
[column 0]FlyoutIcon [column 1]Label1 [column 2]Label2/Slide Button
Can you please also show me some sample code for the solution?
Best and Regards
I tried to modify the Grid to add a third column and addition Label but seems not working.
<Shell ...>
...
<Shell.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="0.2*,0.4*,0.4*">
<Image Source="{Binding FlyoutIcon}"
Margin="5"
HeightRequest="45" />
<Label Grid.Column="1"
Text="{Binding Title}"
FontAttributes="Italic"
VerticalTextAlignment="Center" />
<Label Grid.Column="2"
Text="{Binding Text}"
FontAttributes="Italic"
VerticalTextAlignment="End" />
</Grid>
</DataTemplate>
</Shell.ItemTemplate>
</Shell>
|
[
"Er, guys. Looks like using Menu Item instead of FlyoutItem will resolve the issue.\n"
] |
[
0
] |
[] |
[] |
[
"maui",
"maui_windows"
] |
stackoverflow_0074660765_maui_maui_windows.txt
|
Q:
Spring JPA @CreatedDate Entity column flushing out time LocalDateTime in wrong format
I have created an Entity column like below
@CreatedDate
@Column(name = "create_ts", nullable = false, updatable = false)
private LocalDateTime createdDate;
This is mapped to a Postgres table with column of type
timestamp(0) without time zone
Inserts are going in fine with the correct format in the table
2022-12-01 01:24:35
Upon doing a curl on the api,
curl -X GET "http://localhost:8080/api/v1/profile/111111"
the column data looks like below.
{"userId":111111,"createdDate":[2022,12,1,1,24,35],"lastModifiedDate":[2022,12,1,1,24,35]}
My application.yml below
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
show-sql=true:
Controller
@GetMapping(path = "/{dsid}", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<UserProfile> getUserProfile(@PathVariable Long dsid){
Optional<UserProfile> userProfile = userProfService.getUserProfile(dsid);
if (!userProfile.isPresent()) {
logger.error("User profile not set for user with id: " + dsid);
throw new ResourceNotFoundException("Profile", "id", dsid);
}
return new ResponseEntity<>(userProfService.getUserProfile(id).get(), HttpStatus.OK);
What am I doing wrong here?
A:
The solution was to annotate the Entity field createdDate with
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
Response after adding annotation.
{
"id": 123,
"userPreference": {
"theme": "dark",
"landing": "myprojects",
"projects": "112,333,222"
},
"createdDate": "2022-12-02 20:28:23",
"lastModifiedDate": "2022-12-02 20:28:23"
}
|
Spring JPA @CreatedDate Entity column flushing out time LocalDateTime in wrong format
|
I have created an Entity column like below
@CreatedDate
@Column(name = "create_ts", nullable = false, updatable = false)
private LocalDateTime createdDate;
This is mapped to a Postgres table with column of type
timestamp(0) without time zone
Inserts are going in fine with the correct format in the table
2022-12-01 01:24:35
Upon doing a curl on the api,
curl -X GET "http://localhost:8080/api/v1/profile/111111"
the column data looks like below.
{"userId":111111,"createdDate":[2022,12,1,1,24,35],"lastModifiedDate":[2022,12,1,1,24,35]}
My application.yml below
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
show-sql=true:
Controller
@GetMapping(path = "/{dsid}", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<UserProfile> getUserProfile(@PathVariable Long dsid){
Optional<UserProfile> userProfile = userProfService.getUserProfile(dsid);
if (!userProfile.isPresent()) {
logger.error("User profile not set for user with id: " + dsid);
throw new ResourceNotFoundException("Profile", "id", dsid);
}
return new ResponseEntity<>(userProfService.getUserProfile(id).get(), HttpStatus.OK);
What am I doing wrong here?
|
[
"The solution was to annotate the Entity field createdDate with\n@JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\")\n@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)\n\nResponse after adding annotation.\n{\n \"id\": 123,\n \"userPreference\": {\n \"theme\": \"dark\",\n \"landing\": \"myprojects\",\n \"projects\": \"112,333,222\"\n },\n \"createdDate\": \"2022-12-02 20:28:23\",\n \"lastModifiedDate\": \"2022-12-02 20:28:23\"\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"hibernate",
"java",
"postgresql",
"spring_boot",
"spring_data_jpa"
] |
stackoverflow_0074638090_hibernate_java_postgresql_spring_boot_spring_data_jpa.txt
|
Q:
Unable to create Global region using Spring Data Geode/Gemfire
From spring data geode/gemfire, can we create Regions on the cluster ? Currently it is creating local cache region but any configuration being done either in ClientCache mode or ServerCache mode, doesn't have any impact on the Cluster server.
But using gfsh commands if we create a REPLICATE Region then the connectivity works fine. Is that the only way to create a REPLICATE
region in Gemfire/Geode cluster ?
Next, there are many documentation which refers to Region with GLOBAL scope but again in gfsh there is no way to create a Region with Scope GLOBAL, nor I could locate any configuration via Spring data geode.
Do we have any additional information on this ?
Regards,
Malaya
Searched the Geode/Gemfire documentation regarding any commannds but couldn't find any.
Tried to adapt the spring data geode/gemfire but even there also there is no option of GLOBAL region creation.
A:
Spring Data for Apache Geode (SDG) does support pushing configuration metadata for Apache Geode Regions (and other Apache Geode objects, e.g. Indexes) to the cluster of servers using the SDG Cluster Configuration Push feature. However, this feature currently only pushes the Region "name" and DataPolicy type (Javadoc) to the servers from the client.
Additionally, "Cluster Configuration Push" only applies when your Spring [Boot] Data application is an Apache Geode ClientCache. If the application is a peer Cache, then this feature does not apply.
NOTE: Spring Boot for Apache Geode (SBDG) applies additional features on top of SDG's Cluster Configuration Push feature. See here. Again, this applies to clients only.
AFAIR, Scope.GLOBAL Regions only applies to REPLICATE Regions, first of all. That is, you cannot create a "GLOBAL" PARTITION Region. See Apache Geode docs for further details on Scope along with other Region distribution configuration attributes.
Assuming your Spring [Boot] Data for Apache Geode application were a peer Cache instance, then you can configure your REPLICATE Regions with a "GLOBAL" Scope as follows:
// Alternatively, you can use @CacheServerApplication
@PeerCacheApplication(name = "MySpringGeodeServer")
class MySpringDataGeodeApplication {
@Bean("MyRegion")
ReplicatedRegionFactoryBean myReplicateRegion(GemFireCache cache) {
ReplicatedRegionFactoryBean region = new ReplicatedRegionFactoryBean();
region.setCache(cache);
region.setScope(Scope.GLOBAL);
return region;
}
}
However, keep in mind this peer Cache, Spring-configured server application is NOT going to push the configuration to other servers in the cluster.
If you are using SDG Annotation-based configuration to (dynamically & conveniently) create Regions in your Spring peer Cache application, for example: using either @EnableEntityDefinedRegions or perhaps @EnableCachingDefinedRegions, then you will need to additionally rely on 1 or more RegionConfigurer bean definitions (see docs) to customize the configuration of individual Regions as the Annotation-based support does not enable fine-grained Region configuration customization of this nature (e.g. Scope on REPLICATE Regions).
This might look something like the following.
Given a persistent entity:
@Region("Customers")
class Customer {
// ...
}
Then:
@CacheServerApplication(name = "MySpringGeodeServer")
@EnableEntityDefinedRegions(
basePackageClasses = Customer.class,
serverRegionShortcut = RegionShortcut.REPLICATE
)
class MySpringDataGeodeApplication {
@Bean
RegionConfigurer customerRegionConfigurer() {
return new RegionConfigurer() {
@Override
public void configure(String beanName, PeerRegionFactoryBean<?, ?> region) {
if ("Customers".equals(beanName)) {
((ReplicatedRegionFactoryBean) region).setScope(Scope.GLOBAL);
}
}
}
}
}
NOTE: Alternatively, if you need such fine-grained control over Region (bean) configuration like this, then you should simply use the Java-based configuration rather than Annotations, anyway. Annotation-based configuration is primarily provided for convenience; it is not a 1-size fits all by any means.
Technically, you could also annotate your persistent entity classes (e.g. Customer) with 1 of the Region type-specific mapping annotations (Javadoc), rather than simply the generic @Region mapping annotation, as well, such as with @ReplicateRegion. This allows you to do things like:
@ReplicateRegion(name = "Customers", scope = Scope.GLOBAL)
class Customer {
// ...
}
Still, I generally prefer users to simply use the generic @Region mapping annotation, and again, if they need to do low-level configuration of Regions (like setting "Scope" on a REPLICATE Region) then simply use Java-based configuration as the opening example demonstrated.
Still, keep in mind, none of this is shared across the other servers inside the same cluster. Spring peer Cache applications do NOT push configuration metadata to other servers at all, and never will. This is sort of the point of using Apache Geode's Cluster Configuration Service anyhow.
NOTE: SDG peer Cache applications can be enabled (disabled by default) to inherit configuration from an existing cluster using Apache Geode's Cluster Configuration Service. For instance, see the useClusterConfiguration attribute (Javadoc) on the PeerCacheApplication annotation. There are strong reasons why SDG disabled this peer/server-side feature by default.
Upon reviewing this and this (not that Scope is something you can "alter" on a Region after the fact anyway), you are CORRECT, when using Gfsh, you cannot create a GLOBAL Scoped REPLICATE Region in the cluster, :(
In general, keep in mind that anything that is possible to do with Apache Geode's API, you can definitely do with Spring (Boot/Data) for Apache Geode and then some.
This is due in large part because SDG was built on Apache Geode's API and not some tool, like Gfsh.
|
Unable to create Global region using Spring Data Geode/Gemfire
|
From spring data geode/gemfire, can we create Regions on the cluster ? Currently it is creating local cache region but any configuration being done either in ClientCache mode or ServerCache mode, doesn't have any impact on the Cluster server.
But using gfsh commands if we create a REPLICATE Region then the connectivity works fine. Is that the only way to create a REPLICATE
region in Gemfire/Geode cluster ?
Next, there are many documentation which refers to Region with GLOBAL scope but again in gfsh there is no way to create a Region with Scope GLOBAL, nor I could locate any configuration via Spring data geode.
Do we have any additional information on this ?
Regards,
Malaya
Searched the Geode/Gemfire documentation regarding any commannds but couldn't find any.
Tried to adapt the spring data geode/gemfire but even there also there is no option of GLOBAL region creation.
|
[
"Spring Data for Apache Geode (SDG) does support pushing configuration metadata for Apache Geode Regions (and other Apache Geode objects, e.g. Indexes) to the cluster of servers using the SDG Cluster Configuration Push feature. However, this feature currently only pushes the Region \"name\" and DataPolicy type (Javadoc) to the servers from the client.\nAdditionally, \"Cluster Configuration Push\" only applies when your Spring [Boot] Data application is an Apache Geode ClientCache. If the application is a peer Cache, then this feature does not apply.\n\nNOTE: Spring Boot for Apache Geode (SBDG) applies additional features on top of SDG's Cluster Configuration Push feature. See here. Again, this applies to clients only.\n\nAFAIR, Scope.GLOBAL Regions only applies to REPLICATE Regions, first of all. That is, you cannot create a \"GLOBAL\" PARTITION Region. See Apache Geode docs for further details on Scope along with other Region distribution configuration attributes.\nAssuming your Spring [Boot] Data for Apache Geode application were a peer Cache instance, then you can configure your REPLICATE Regions with a \"GLOBAL\" Scope as follows:\n// Alternatively, you can use @CacheServerApplication\n@PeerCacheApplication(name = \"MySpringGeodeServer\")\nclass MySpringDataGeodeApplication {\n\n @Bean(\"MyRegion\")\n ReplicatedRegionFactoryBean myReplicateRegion(GemFireCache cache) {\n\n ReplicatedRegionFactoryBean region = new ReplicatedRegionFactoryBean();\n\n region.setCache(cache);\n region.setScope(Scope.GLOBAL);\n\n return region;\n }\n}\n\nHowever, keep in mind this peer Cache, Spring-configured server application is NOT going to push the configuration to other servers in the cluster.\nIf you are using SDG Annotation-based configuration to (dynamically & conveniently) create Regions in your Spring peer Cache application, for example: using either @EnableEntityDefinedRegions or perhaps @EnableCachingDefinedRegions, then you will need to additionally rely on 1 or more RegionConfigurer bean definitions (see docs) to customize the configuration of individual Regions as the Annotation-based support does not enable fine-grained Region configuration customization of this nature (e.g. Scope on REPLICATE Regions).\nThis might look something like the following.\nGiven a persistent entity:\n@Region(\"Customers\")\nclass Customer { \n // ...\n}\n\nThen:\n@CacheServerApplication(name = \"MySpringGeodeServer\")\n@EnableEntityDefinedRegions(\n basePackageClasses = Customer.class,\n serverRegionShortcut = RegionShortcut.REPLICATE\n)\nclass MySpringDataGeodeApplication {\n\n @Bean\n RegionConfigurer customerRegionConfigurer() {\n\n return new RegionConfigurer() {\n\n @Override\n public void configure(String beanName, PeerRegionFactoryBean<?, ?> region) {\n\n if (\"Customers\".equals(beanName)) {\n ((ReplicatedRegionFactoryBean) region).setScope(Scope.GLOBAL);\n }\n }\n\n }\n }\n}\n\n\nNOTE: Alternatively, if you need such fine-grained control over Region (bean) configuration like this, then you should simply use the Java-based configuration rather than Annotations, anyway. Annotation-based configuration is primarily provided for convenience; it is not a 1-size fits all by any means.\n\nTechnically, you could also annotate your persistent entity classes (e.g. Customer) with 1 of the Region type-specific mapping annotations (Javadoc), rather than simply the generic @Region mapping annotation, as well, such as with @ReplicateRegion. This allows you to do things like:\n@ReplicateRegion(name = \"Customers\", scope = Scope.GLOBAL)\nclass Customer {\n // ...\n}\n\nStill, I generally prefer users to simply use the generic @Region mapping annotation, and again, if they need to do low-level configuration of Regions (like setting \"Scope\" on a REPLICATE Region) then simply use Java-based configuration as the opening example demonstrated.\nStill, keep in mind, none of this is shared across the other servers inside the same cluster. Spring peer Cache applications do NOT push configuration metadata to other servers at all, and never will. This is sort of the point of using Apache Geode's Cluster Configuration Service anyhow.\n\nNOTE: SDG peer Cache applications can be enabled (disabled by default) to inherit configuration from an existing cluster using Apache Geode's Cluster Configuration Service. For instance, see the useClusterConfiguration attribute (Javadoc) on the PeerCacheApplication annotation. There are strong reasons why SDG disabled this peer/server-side feature by default.\n\nUpon reviewing this and this (not that Scope is something you can \"alter\" on a Region after the fact anyway), you are CORRECT, when using Gfsh, you cannot create a GLOBAL Scoped REPLICATE Region in the cluster, :(\nIn general, keep in mind that anything that is possible to do with Apache Geode's API, you can definitely do with Spring (Boot/Data) for Apache Geode and then some.\nThis is due in large part because SDG was built on Apache Geode's API and not some tool, like Gfsh.\n"
] |
[
0
] |
[] |
[] |
[
"geode",
"spring",
"spring_boot",
"spring_data_gemfire"
] |
stackoverflow_0074640036_geode_spring_spring_boot_spring_data_gemfire.txt
|
Q:
Inverse of a complicated matrix not working in Sympy/ Python
So I was trying to formulate some matrix out of another matrix's elements using sympy. But while the taking the inverse it didn't work I believe cause of the complicity of the matrix I am taking the inverse of.
x0, x1, x2, x3 = smp.symbols('x^0 x^1 x^2 x^3')
COORDS = [x0, x1, x2, x3]
N = len(COORDS)
g00 = smp.Function('g00')(x0, x1, x2, x3)
g01 = smp.Function('g01')(x0, x1, x2, x3)
g02 = smp.Function('g02')(x0, x1, x2, x3)
g03 = smp.Function('g03')(x0, x1, x2, x3)
g10 = smp.Function('g10')(x0, x1, x2, x3)
g11 = smp.Function('g11')(x0, x1, x2, x3)
g12 = smp.Function('g12')(x0, x1, x2, x3)
g13 = smp.Function('g13')(x0, x1, x2, x3)
g20 = smp.Function('g20')(x0, x1, x2, x3)
g21 = smp.Function('g21')(x0, x1, x2, x3)
g22 = smp.Function('g22')(x0, x1, x2, x3)
g23 = smp.Function('g23')(x0, x1, x2, x3)
g30 = smp.Function('g30')(x0, x1, x2, x3)
g31 = smp.Function('g31')(x0, x1, x2, x3)
g32 = smp.Function('g_32')(x0, x1, x2, x3)
g33 = smp.Function('g_33')(x0, x1, x2, x3)
g = smp.Matrix([[g00,g01,g02,g03],[g10,g11,g12,g13],[g20,g21,g22,g23],[g30,g31,g32,g33]])
and when I do g.inv() the kernel just doesn't finish. What should I do in order to take this matrix's inverse? Thank you so much in advance :)
A:
A fully symbolic matrix has a complicated expression for its inverse (shown below). Feel free to substitute whatever you like for the entries of the matrix but it's unlikely that you can do anything useful with such an expression.
Here is the inverse of a fully symbolic 4x4 matrix (computed in less than a second):
In [8]: from sympy import *
In [9]: from sympy.polys.matrices import DomainMatrix
In [10]: dm = DomainMatrix.from_Matrix(Matrix(symbols('x:16')).reshape(4, 4))
In [11]: dm.to_field().inv().to_Matrix()
Out[11]:
⎡
⎢─────────────────────────────────────────────────────────────────────────────
⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉
⎢
⎢
⎢─────────────────────────────────────────────────────────────────────────────
⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉
⎢
⎢
⎢─────────────────────────────────────────────────────────────────────────────
⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉
⎢
⎢
⎢─────────────────────────────────────────────────────────────────────────────
⎣-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉
-x₁₀⋅x₁
──────────────────────────────────────────────────────────────────────────────
- x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x
x₁₀⋅x₁₂
──────────────────────────────────────────────────────────────────────────────
- x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x
x₁₁⋅x₁
──────────────────────────────────────────────────────────────────────────────
- x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x
-x₁₀⋅x
──────────────────────────────────────────────────────────────────────────────
- x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x
₃⋅x₇ + x₁₀⋅x₁₅⋅x₅ + x₁₁⋅x₁₃⋅x₆ - x₁₁⋅x₁₄⋅x₅ + x₁₄⋅x₇⋅x₉ - x₁₅⋅x₆⋅x₉
──────────────────────────────────────────────────────────────────────────────
₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x
⋅x₇ - x₁₀⋅x₁₅⋅x₄ - x₁₁⋅x₁₂⋅x₆ + x₁₁⋅x₁₄⋅x₄ - x₁₄⋅x₇⋅x₈ + x₁₅⋅x₆⋅x₈
──────────────────────────────────────────────────────────────────────────────
₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x
₂⋅x₅ - x₁₁⋅x₁₃⋅x₄ - x₁₂⋅x₇⋅x₉ + x₁₃⋅x₇⋅x₈ + x₁₅⋅x₄⋅x₉ - x₁₅⋅x₅⋅x₈
──────────────────────────────────────────────────────────────────────────────
₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x
₁₂⋅x₅ + x₁₀⋅x₁₃⋅x₄ + x₁₂⋅x₆⋅x₉ - x₁₃⋅x₆⋅x₈ - x₁₄⋅x₄⋅x₉ + x₁₄⋅x₅⋅x₈
──────────────────────────────────────────────────────────────────────────────
₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x
──────────────────────────────────────────────────────────────────────────────
₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈
──────────────────────────────────────────────────────────────────────────────
₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈
──────────────────────────────────────────────────────────────────────────────
₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈
──────────────────────────────────────────────────────────────────────────────
₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈
─────────────────────────────────────────────────────────── ─────────────────
- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ +
─────────────────────────────────────────────────────────── ─────────────────
- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ +
─────────────────────────────────────────────────────────── ─────────────────
- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ +
─────────────────────────────────────────────────────────── ─────────────────
- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ +
──────────────────────────────────────────────────────────────────────────────
x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ +
──────────────────────────────────────────────────────────────────────────────
x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ +
──────────────────────────────────────────────────────────────────────────────
x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ +
──────────────────────────────────────────────────────────────────────────────
x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ +
-x₁⋅x₁₀⋅x₁₅ + x₁⋅x₁₁⋅x₁₄
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +
x₀⋅x₁₀⋅x₁₅ - x₀⋅x₁₁⋅x₁₄ -
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +
x₀⋅x₁₁⋅x₁₃ - x₀⋅x₁₅⋅x₉ -
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +
-x₀⋅x₁₀⋅x₁₃ + x₀⋅x₁₄⋅x₉
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +
+ x₁₀⋅x₁₃⋅x₃ - x₁₁⋅x₁₃⋅x₂ - x₁₄⋅x₃⋅x₉ + x₁₅⋅x₂⋅x₉
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄
x₁₀⋅x₁₂⋅x₃ + x₁₁⋅x₁₂⋅x₂ + x₁₄⋅x₃⋅x₈ - x₁₅⋅x₂⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄
x₁⋅x₁₁⋅x₁₂ + x₁⋅x₁₅⋅x₈ + x₁₂⋅x₃⋅x₉ - x₁₃⋅x₃⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄
+ x₁⋅x₁₀⋅x₁₂ - x₁⋅x₁₄⋅x₈ - x₁₂⋅x₂⋅x₉ + x₁₃⋅x₂⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄
──────────────────────────────────────────────────────────────────────────────
- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x
──────────────────────────────────────────────────────────────────────────────
- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x
──────────────────────────────────────────────────────────────────────────────
- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x
──────────────────────────────────────────────────────────────────────────────
- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x
───────────────────────────────────────── ───────────────────────────────────
₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀
───────────────────────────────────────── ───────────────────────────────────
₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀
───────────────────────────────────────── ───────────────────────────────────
₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀
───────────────────────────────────────── ───────────────────────────────────
₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀
──────────────────────────────────────────────────────────────────────────────
⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁
──────────────────────────────────────────────────────────────────────────────
⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁
──────────────────────────────────────────────────────────────────────────────
⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁
──────────────────────────────────────────────────────────────────────────────
⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁
-x₁⋅x₁₄⋅x₇ + x₁⋅x₁₅⋅x₆ + x₁₃⋅x₂⋅x₇ - x₁₃⋅
──────────────────────────────────────────────────────────────────────────────
⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁
x₀⋅x₁₄⋅x₇ - x₀⋅x₁₅⋅x₆ - x₁₂⋅x₂⋅x₇ + x₁₂⋅x
──────────────────────────────────────────────────────────────────────────────
⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁
-x₀⋅x₁₃⋅x₇ + x₀⋅x₁₅⋅x₅ + x₁⋅x₁₂⋅x₇ - x₁⋅x
──────────────────────────────────────────────────────────────────────────────
⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁
x₀⋅x₁₃⋅x₆ - x₀⋅x₁₄⋅x₅ - x₁⋅x₁₂⋅x₆ + x₁⋅x₁
──────────────────────────────────────────────────────────────────────────────
⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁
x₃⋅x₆ + x₁₄⋅x₃⋅x₅ - x₁₅⋅x₂⋅x₅
──────────────────────────────────────────────────────────────────────────────
₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x
₃⋅x₆ - x₁₄⋅x₃⋅x₄ + x₁₅⋅x₂⋅x₄
──────────────────────────────────────────────────────────────────────────────
₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x
₁₅⋅x₄ - x₁₂⋅x₃⋅x₅ + x₁₃⋅x₃⋅x₄
──────────────────────────────────────────────────────────────────────────────
₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x
₄⋅x₄ + x₁₂⋅x₂⋅x₅ - x₁₃⋅x₂⋅x₄
──────────────────────────────────────────────────────────────────────────────
₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x
──────────────────────────────────────────────────────────────────────────────
₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅
──────────────────────────────────────────────────────────────────────────────
₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅
──────────────────────────────────────────────────────────────────────────────
₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅
──────────────────────────────────────────────────────────────────────────────
₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅
─────────────────────── ─────────────────────────────────────────────────────
x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x
─────────────────────── ─────────────────────────────────────────────────────
x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x
─────────────────────── ─────────────────────────────────────────────────────
x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x
─────────────────────── ─────────────────────────────────────────────────────
x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x
x₁⋅x₁₀⋅x₇ - x₁⋅x₁₁⋅x₆ - x₁₀⋅x₃⋅x₅ + x₁₁⋅x₂⋅x₅ - x₂⋅x₇⋅x₉ +
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅
-x₀⋅x₁₀⋅x₇ + x₀⋅x₁₁⋅x₆ + x₁₀⋅x₃⋅x₄ - x₁₁⋅x₂⋅x₄ + x₂⋅x₇⋅x₈
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅
-x₀⋅x₁₁⋅x₅ + x₀⋅x₇⋅x₉ + x₁⋅x₁₁⋅x₄ - x₁⋅x₇⋅x₈ - x₃⋅x₄⋅x₉ +
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅
x₀⋅x₁₀⋅x₅ - x₀⋅x₆⋅x₉ - x₁⋅x₁₀⋅x₄ + x₁⋅x₆⋅x₈ + x₂⋅x₄⋅x₉ -
──────────────────────────────────────────────────────────────────────────────
₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅
x₃⋅x₆⋅x₉
──────────────────────────────────────────────────────────────────────────────
x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅
- x₃⋅x₆⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅
x₃⋅x₅⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅
x₂⋅x₅⋅x₈
──────────────────────────────────────────────────────────────────────────────
x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅
──────────────────────────────────────────────────────────────────────────────
x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅
──────────────────────────────────────────────────────────────────────────────
x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅
──────────────────────────────────────────────────────────────────────────────
x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅
──────────────────────────────────────────────────────────────────────────────
x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅
⎤
─────⎥
x₅⋅x₈⎥
⎥
⎥
─────⎥
x₅⋅x₈⎥
⎥
⎥
─────⎥
x₅⋅x₈⎥
⎥
⎥
─────⎥
x₅⋅x₈⎦
|
Inverse of a complicated matrix not working in Sympy/ Python
|
So I was trying to formulate some matrix out of another matrix's elements using sympy. But while the taking the inverse it didn't work I believe cause of the complicity of the matrix I am taking the inverse of.
x0, x1, x2, x3 = smp.symbols('x^0 x^1 x^2 x^3')
COORDS = [x0, x1, x2, x3]
N = len(COORDS)
g00 = smp.Function('g00')(x0, x1, x2, x3)
g01 = smp.Function('g01')(x0, x1, x2, x3)
g02 = smp.Function('g02')(x0, x1, x2, x3)
g03 = smp.Function('g03')(x0, x1, x2, x3)
g10 = smp.Function('g10')(x0, x1, x2, x3)
g11 = smp.Function('g11')(x0, x1, x2, x3)
g12 = smp.Function('g12')(x0, x1, x2, x3)
g13 = smp.Function('g13')(x0, x1, x2, x3)
g20 = smp.Function('g20')(x0, x1, x2, x3)
g21 = smp.Function('g21')(x0, x1, x2, x3)
g22 = smp.Function('g22')(x0, x1, x2, x3)
g23 = smp.Function('g23')(x0, x1, x2, x3)
g30 = smp.Function('g30')(x0, x1, x2, x3)
g31 = smp.Function('g31')(x0, x1, x2, x3)
g32 = smp.Function('g_32')(x0, x1, x2, x3)
g33 = smp.Function('g_33')(x0, x1, x2, x3)
g = smp.Matrix([[g00,g01,g02,g03],[g10,g11,g12,g13],[g20,g21,g22,g23],[g30,g31,g32,g33]])
and when I do g.inv() the kernel just doesn't finish. What should I do in order to take this matrix's inverse? Thank you so much in advance :)
|
[
"A fully symbolic matrix has a complicated expression for its inverse (shown below). Feel free to substitute whatever you like for the entries of the matrix but it's unlikely that you can do anything useful with such an expression.\nHere is the inverse of a fully symbolic 4x4 matrix (computed in less than a second):\nIn [8]: from sympy import *\n\nIn [9]: from sympy.polys.matrices import DomainMatrix\n\nIn [10]: dm = DomainMatrix.from_Matrix(Matrix(symbols('x:16')).reshape(4, 4))\n\nIn [11]: dm.to_field().inv().to_Matrix()\nOut[11]: \n⎡ \n⎢─────────────────────────────────────────────────────────────────────────────\n⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉\n⎢ \n⎢ \n⎢─────────────────────────────────────────────────────────────────────────────\n⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉\n⎢ \n⎢ \n⎢─────────────────────────────────────────────────────────────────────────────\n⎢-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉\n⎢ \n⎢ \n⎢─────────────────────────────────────────────────────────────────────────────\n⎣-x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉\n\n -x₁₀⋅x₁\n──────────────────────────────────────────────────────────────────────────────\n - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x\n \n x₁₀⋅x₁₂\n──────────────────────────────────────────────────────────────────────────────\n - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x\n \n x₁₁⋅x₁\n──────────────────────────────────────────────────────────────────────────────\n - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x\n \n -x₁₀⋅x\n──────────────────────────────────────────────────────────────────────────────\n - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x\n\n₃⋅x₇ + x₁₀⋅x₁₅⋅x₅ + x₁₁⋅x₁₃⋅x₆ - x₁₁⋅x₁₄⋅x₅ + x₁₄⋅x₇⋅x₉ - x₁₅⋅x₆⋅x₉ \n──────────────────────────────────────────────────────────────────────────────\n₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x\n \n⋅x₇ - x₁₀⋅x₁₅⋅x₄ - x₁₁⋅x₁₂⋅x₆ + x₁₁⋅x₁₄⋅x₄ - x₁₄⋅x₇⋅x₈ + x₁₅⋅x₆⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x\n \n₂⋅x₅ - x₁₁⋅x₁₃⋅x₄ - x₁₂⋅x₇⋅x₉ + x₁₃⋅x₇⋅x₈ + x₁₅⋅x₄⋅x₉ - x₁₅⋅x₅⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x\n \n₁₂⋅x₅ + x₁₀⋅x₁₃⋅x₄ + x₁₂⋅x₆⋅x₉ - x₁₃⋅x₆⋅x₈ - x₁₄⋅x₄⋅x₉ + x₁₄⋅x₅⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x\n\n \n──────────────────────────────────────────────────────────────────────────────\n₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ \n \n \n──────────────────────────────────────────────────────────────────────────────\n₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ \n \n \n──────────────────────────────────────────────────────────────────────────────\n₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ \n \n \n──────────────────────────────────────────────────────────────────────────────\n₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ \n\n \n─────────────────────────────────────────────────────────── ─────────────────\n- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + \n \n \n─────────────────────────────────────────────────────────── ─────────────────\n- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + \n \n \n─────────────────────────────────────────────────────────── ─────────────────\n- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + \n \n \n─────────────────────────────────────────────────────────── ─────────────────\n- x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + \n\n \n──────────────────────────────────────────────────────────────────────────────\nx₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + \n \n \n──────────────────────────────────────────────────────────────────────────────\nx₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + \n \n \n──────────────────────────────────────────────────────────────────────────────\nx₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + \n \n \n──────────────────────────────────────────────────────────────────────────────\nx₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + \n\n -x₁⋅x₁₀⋅x₁₅ + x₁⋅x₁₁⋅x₁₄ \n──────────────────────────────────────────────────────────────────────────────\nx₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +\n \n x₀⋅x₁₀⋅x₁₅ - x₀⋅x₁₁⋅x₁₄ -\n──────────────────────────────────────────────────────────────────────────────\nx₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +\n \n x₀⋅x₁₁⋅x₁₃ - x₀⋅x₁₅⋅x₉ -\n──────────────────────────────────────────────────────────────────────────────\nx₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +\n \n -x₀⋅x₁₀⋅x₁₃ + x₀⋅x₁₄⋅x₉ \n──────────────────────────────────────────────────────────────────────────────\nx₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ +\n\n+ x₁₀⋅x₁₃⋅x₃ - x₁₁⋅x₁₃⋅x₂ - x₁₄⋅x₃⋅x₉ + x₁₅⋅x₂⋅x₉ \n──────────────────────────────────────────────────────────────────────────────\n x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ \n \n x₁₀⋅x₁₂⋅x₃ + x₁₁⋅x₁₂⋅x₂ + x₁₄⋅x₃⋅x₈ - x₁₅⋅x₂⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ \n \n x₁⋅x₁₁⋅x₁₂ + x₁⋅x₁₅⋅x₈ + x₁₂⋅x₃⋅x₉ - x₁₃⋅x₃⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ \n \n+ x₁⋅x₁₀⋅x₁₂ - x₁⋅x₁₄⋅x₈ - x₁₂⋅x₂⋅x₉ + x₁₃⋅x₂⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ \n\n \n──────────────────────────────────────────────────────────────────────────────\n- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x\n \n \n──────────────────────────────────────────────────────────────────────────────\n- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x\n \n \n──────────────────────────────────────────────────────────────────────────────\n- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x\n \n \n──────────────────────────────────────────────────────────────────────────────\n- x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x\n\n \n───────────────────────────────────────── ───────────────────────────────────\n₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀\n \n \n───────────────────────────────────────── ───────────────────────────────────\n₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀\n \n \n───────────────────────────────────────── ───────────────────────────────────\n₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀\n \n \n───────────────────────────────────────── ───────────────────────────────────\n₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀\n\n \n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁\n \n \n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁\n \n \n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁\n \n \n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁\n\n -x₁⋅x₁₄⋅x₇ + x₁⋅x₁₅⋅x₆ + x₁₃⋅x₂⋅x₇ - x₁₃⋅\n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁\n \n x₀⋅x₁₄⋅x₇ - x₀⋅x₁₅⋅x₆ - x₁₂⋅x₂⋅x₇ + x₁₂⋅x\n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁\n \n -x₀⋅x₁₃⋅x₇ + x₀⋅x₁₅⋅x₅ + x₁⋅x₁₂⋅x₇ - x₁⋅x\n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁\n \n x₀⋅x₁₃⋅x₆ - x₀⋅x₁₄⋅x₅ - x₁⋅x₁₂⋅x₆ + x₁⋅x₁\n──────────────────────────────────────────────────────────────────────────────\n⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁\n\nx₃⋅x₆ + x₁₄⋅x₃⋅x₅ - x₁₅⋅x₂⋅x₅ \n──────────────────────────────────────────────────────────────────────────────\n₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x\n \n₃⋅x₆ - x₁₄⋅x₃⋅x₄ + x₁₅⋅x₂⋅x₄ \n──────────────────────────────────────────────────────────────────────────────\n₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x\n \n₁₅⋅x₄ - x₁₂⋅x₃⋅x₅ + x₁₃⋅x₃⋅x₄ \n──────────────────────────────────────────────────────────────────────────────\n₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x\n \n₄⋅x₄ + x₁₂⋅x₂⋅x₅ - x₁₃⋅x₂⋅x₄ \n──────────────────────────────────────────────────────────────────────────────\n₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅x₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x\n\n \n──────────────────────────────────────────────────────────────────────────────\n₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅x₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅\n\n \n─────────────────────── ─────────────────────────────────────────────────────\nx₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x\n \n \n─────────────────────── ─────────────────────────────────────────────────────\nx₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x\n \n \n─────────────────────── ─────────────────────────────────────────────────────\nx₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x\n \n \n─────────────────────── ─────────────────────────────────────────────────────\nx₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅x₅⋅x₈ -x₀⋅x₁₀⋅x₁₃⋅x₇ + x₀⋅x₁₀⋅x₁₅⋅x₅ + x₀⋅x₁₁⋅x₁₃⋅x₆ - x₀⋅x\n\n \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x\n \n \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₄⋅x₅ + x₀⋅x₁₄⋅x₇⋅x₉ - x₀⋅x₁₅⋅x₆⋅x₉ + x₁⋅x₁₀⋅x₁₂⋅x₇ - x₁⋅x₁₀⋅x₁₅⋅x₄ - x₁⋅x\n\n x₁⋅x₁₀⋅x₇ - x₁⋅x₁₁⋅x₆ - x₁₀⋅x₃⋅x₅ + x₁₁⋅x₂⋅x₅ - x₂⋅x₇⋅x₉ +\n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅\n \n -x₀⋅x₁₀⋅x₇ + x₀⋅x₁₁⋅x₆ + x₁₀⋅x₃⋅x₄ - x₁₁⋅x₂⋅x₄ + x₂⋅x₇⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅\n \n -x₀⋅x₁₁⋅x₅ + x₀⋅x₇⋅x₉ + x₁⋅x₁₁⋅x₄ - x₁⋅x₇⋅x₈ - x₃⋅x₄⋅x₉ +\n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅\n \n x₀⋅x₁₀⋅x₅ - x₀⋅x₆⋅x₉ - x₁⋅x₁₀⋅x₄ + x₁⋅x₆⋅x₈ + x₂⋅x₄⋅x₉ - \n──────────────────────────────────────────────────────────────────────────────\n₁₁⋅x₁₂⋅x₆ + x₁⋅x₁₁⋅x₁₄⋅x₄ - x₁⋅x₁₄⋅x₇⋅x₈ + x₁⋅x₁₅⋅x₆⋅x₈ - x₁₀⋅x₁₂⋅x₃⋅x₅ + x₁₀⋅\n\n x₃⋅x₆⋅x₉ \n──────────────────────────────────────────────────────────────────────────────\nx₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅\n \n- x₃⋅x₆⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\nx₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅\n \n x₃⋅x₅⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\nx₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅\n \nx₂⋅x₅⋅x₈ \n──────────────────────────────────────────────────────────────────────────────\nx₁₃⋅x₃⋅x₄ + x₁₁⋅x₁₂⋅x₂⋅x₅ - x₁₁⋅x₁₃⋅x₂⋅x₄ - x₁₂⋅x₂⋅x₇⋅x₉ + x₁₂⋅x₃⋅x₆⋅x₉ + x₁₃⋅\n\n \n──────────────────────────────────────────────────────────────────────────────\nx₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\nx₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\nx₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅\n \n \n──────────────────────────────────────────────────────────────────────────────\nx₂⋅x₇⋅x₈ - x₁₃⋅x₃⋅x₆⋅x₈ - x₁₄⋅x₃⋅x₄⋅x₉ + x₁₄⋅x₃⋅x₅⋅x₈ + x₁₅⋅x₂⋅x₄⋅x₉ - x₁₅⋅x₂⋅\n\n ⎤\n─────⎥\nx₅⋅x₈⎥\n ⎥\n ⎥\n─────⎥\nx₅⋅x₈⎥\n ⎥\n ⎥\n─────⎥\nx₅⋅x₈⎥\n ⎥\n ⎥\n─────⎥\nx₅⋅x₈⎦\n\n"
] |
[
2
] |
[] |
[] |
[
"matrix",
"python",
"sympy",
"tensor"
] |
stackoverflow_0074658912_matrix_python_sympy_tensor.txt
|
Q:
How to use requestGeometryUpdateWithPreferences in Objective C
I have an example in Swift language:
guard let windowScene = view.window?.windowScene else { return }
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { error in }
I can't write it in Objective C:
UIWindowScene *windowScene = self.view.window.windowScene;
[windowScene requestGeometryUpdateWithPreferences: UIInterfaceOrientationMaskPortrait errorHandler:nil];
Please tell me how to write correctly I will be grateful for any help.
A:
One way to write that Swift code in Objective-C would be:
UIWindowScene *windowScene = self.view.window.windowScene;
if (!windowScene) { return; }
UIWindowSceneGeometryPreferences *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
[windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {
// Handle error here
}];
|
How to use requestGeometryUpdateWithPreferences in Objective C
|
I have an example in Swift language:
guard let windowScene = view.window?.windowScene else { return }
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { error in }
I can't write it in Objective C:
UIWindowScene *windowScene = self.view.window.windowScene;
[windowScene requestGeometryUpdateWithPreferences: UIInterfaceOrientationMaskPortrait errorHandler:nil];
Please tell me how to write correctly I will be grateful for any help.
|
[
"One way to write that Swift code in Objective-C would be:\nUIWindowScene *windowScene = self.view.window.windowScene;\nif (!windowScene) { return; }\nUIWindowSceneGeometryPreferences *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];\n[windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {\n // Handle error here\n}];\n\n"
] |
[
0
] |
[] |
[] |
[
"objective_c",
"uiinterfaceorientation",
"uiwindowscene"
] |
stackoverflow_0074657620_objective_c_uiinterfaceorientation_uiwindowscene.txt
|
Q:
Flutter, Nesting scrollable (or list) views
Can anyone clarify for me what I have shown in the 'image' attached is achievable in flutter? if yes, how? explaining the image is a bit hard.
I am new to flutter and trying to nest some scrollable views inside each other.
at first I tried to achieve this by nesting simple scrollable row and columns inside each other but faced some errors and exceptions (unbound height and width).
I searched and found out it is better to use 'CustomScrollView' for nesting lists in each other. tried it but haven't achieved what I want yet.
Any help/hint on how to achieve this would be much appreciated.
Nested Scroll Views
A:
This is definitely possible, and you could use an approach like below, which is inspired by another question on stack overflow. I recommend reading that for better clarification -- here.
Edit: Wrapping the Row widget in a SingleChildScrollView would make the entire page scrollable.
body: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: X,
itemBuilder: (BuildContext context, int index) => ...
),
),
Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: Y,
itemBuilder: (BuildContext context, int index) => ...
),
),
],
);
If this doesn't help, I'd suggest finding flutter repositories of e.g. Netflix clones or other existing apps known to have scroll views inside a list view.
A:
@bragi, thanks for the answer,
I followed what you suggested and after some trial and error, I finally got it working.
But in terms of efficiency and how the application will respond/render I am not sure if this was the best way to do it:
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
// mainAxisSize: MainAxisSize.min,
children: [
makeColumn(),
makeColumn(),
makeColumn(),
makeColumn(),
makeColumn(),
],
),
),
Widget makeColumn() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Container(
width: 150,
height: 150,
color: Colors.green,
),
SizedBox(
width: 150,
height: 500,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
Container(), ....
For some reason, the Expanded widget did not work so I had to wrap my second column with SizedBox!
|
Flutter, Nesting scrollable (or list) views
|
Can anyone clarify for me what I have shown in the 'image' attached is achievable in flutter? if yes, how? explaining the image is a bit hard.
I am new to flutter and trying to nest some scrollable views inside each other.
at first I tried to achieve this by nesting simple scrollable row and columns inside each other but faced some errors and exceptions (unbound height and width).
I searched and found out it is better to use 'CustomScrollView' for nesting lists in each other. tried it but haven't achieved what I want yet.
Any help/hint on how to achieve this would be much appreciated.
Nested Scroll Views
|
[
"This is definitely possible, and you could use an approach like below, which is inspired by another question on stack overflow. I recommend reading that for better clarification -- here.\nEdit: Wrapping the Row widget in a SingleChildScrollView would make the entire page scrollable.\nbody: Row(\n mainAxisSize: MainAxisSize.min,\n children: <Widget>[\n Expanded(\n child: ListView.builder(\n scrollDirection: Axis.vertical,\n itemCount: X,\n itemBuilder: (BuildContext context, int index) => ...\n ),\n ),\n Expanded(\n child: ListView.builder(\n scrollDirection: Axis.vertical,\n itemCount: Y,\n itemBuilder: (BuildContext context, int index) => ...\n ),\n ),\n ],\n );\n\nIf this doesn't help, I'd suggest finding flutter repositories of e.g. Netflix clones or other existing apps known to have scroll views inside a list view.\n",
"@bragi, thanks for the answer,\nI followed what you suggested and after some trial and error, I finally got it working.\nBut in terms of efficiency and how the application will respond/render I am not sure if this was the best way to do it:\nSingleChildScrollView(\n scrollDirection: Axis.horizontal,\n child: Row(\n // mainAxisSize: MainAxisSize.min,\n children: [\n makeColumn(),\n makeColumn(),\n makeColumn(),\n makeColumn(),\n makeColumn(),\n ],\n ),\n ),\n\nWidget makeColumn() {\nreturn Padding(\npadding: const EdgeInsets.all(8.0),\nchild: Column(\n children: [\n Container(\n width: 150,\n height: 150,\n color: Colors.green,\n ),\n SizedBox(\n width: 150,\n height: 500,\n child: SingleChildScrollView(\n scrollDirection: Axis.vertical,\n child: Column(\n children: [\n Container(), ....\n\nFor some reason, the Expanded widget did not work so I had to wrap my second column with SizedBox!\n"
] |
[
0,
0
] |
[] |
[] |
[
"flutter",
"listview",
"scrollview"
] |
stackoverflow_0074649209_flutter_listview_scrollview.txt
|
Q:
How to Redirect automatically to a page/path on login - MSAL React SPA
I am working on a single page application (SPA) app that grants access to specific paths in the application, based on roles setup in Azure AD for the user logging in. As per this https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles
This is my 'authConfig.js' file - you can see the redirectUri
const clientId = window.REACT_APP_CLIENTID
export const msalConfig = {
auth: {
clientId: clientId,
authority: window.REACT_APP_AUTHORITY,
redirectUri: 'http://localhost:3000/todolist/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin
postLogoutRedirectUri: "/", // Indicates the page to navigate after logout.
navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
},
cache: {
cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
/**
* Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
*/
export const protectedResources = {
apiTodoList: {
todoListEndpoint: window.REACT_APP_APIENDPOINT+"/api/v2/support/list",
scopes: [window.REACT_APP_APIENDPOINT+"/access_as_user"],
},
}
/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
* For more information about OIDC scopes, visit:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
export const loginRequest = {
scopes: [...protectedResources.apiTodoList.scopes]
};
export const appRoles = {
TaskUser: "TaskUser",
TaskAdmin: "TaskAdmin",
TrialAdmin: "Trial.Admin",
GlobalAdmin: "Global.Admin"
}
Here is the App.jsx file (I believe there needs to be some change made here). You can see 'RouteGuard' that renders the Component {TodoList}, when the path 'todolist' is accessed.
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { MsalProvider } from "@azure/msal-react";
import { RouteGuard } from './components/RouteGuard';
import { PageLayout } from "./components/PageLayout";
import { TodoList } from "./pages/TodoList";
import { appRoles } from "./authConfig";
import "./styles/App.css";
const Pages = () => {
return (
<Switch>
<RouteGuard
exact
path='/todolist/'
roles={[appRoles.TaskUser, appRoles.TaskAdmin, appRoles.TrialAdmin, appRoles.GlobalAdmin]}
Component={TodoList}
/>
</Switch>
)
}
/**
* msal-react is built on the React context API and all parts of your app that require authentication must be
* wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication
* then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the
* PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
*/
const App = ({ instance }) => {
return (
<Router>
<MsalProvider instance={instance}>
<PageLayout>
<Pages instance={instance} />
</PageLayout>
</MsalProvider>
</Router>
);
}
export default App;
So as far as my understanding goes, the path 'todolist' is accessed with the listed role, and component is rendered
When logged in, The navigation bar at the top renders with login request, after authentication (). It has the button rendered, with a click function that 'href's to the path '/todolist'.
import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";
import { Nav, Navbar, Button, Dropdown, DropdownButton} from "react-bootstrap";
import React, { useState, useEffect } from "react";
import { loginRequest } from "../authConfig";
import { InteractionStatus, InteractionType } from "@azure/msal-browser";
import "../styles/App.css";
import logo from "../public/images/logo.jpg";
export const NavigationBar = (props) => {
const { instance } = useMsal();
const { inProgress } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
//The below function is needed incase you want to login using Popup and not redirect
const handleLogin = () => {
instance.loginPopup(loginRequest)
.catch((error) => console.log(error))
}
/**
* Most applications will need to conditionally render certain components based on whether a user is signed in or not.
* msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
* only render their children if a user is authenticated or unauthenticated, respectively.
*/
return (
<>
<Navbar className="color-custom" variant="dark">
<a className="navbar-brand" href="/"><img src={logo} className="navbarLogo" alt="TODDOLIST1"/></a>
<AuthenticatedTemplate>
<Nav.Link as={Button} id="signupbutton" variant="dark" className="signupNav" href="/todolist"><strong>List</strong></Nav.Link>
<Button variant="warning" className="ml-auto" drop="left" title="Sign Out" onClick={() => instance.logoutRedirect({ postLogoutRedirectUri: "/" })}><strong>Sign Out</strong></Button>
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<Button variant="dark" className="ml-auto" drop="left" title="Sign In" onClick={() => instance.loginRedirect(loginRequest)}>Sign In</Button>
</UnauthenticatedTemplate>
</Navbar>
</>
);
};
Here is the RouteGuard.jsx component that renders based on roles/authorization.
import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
export const RouteGuard = ({ Component, ...props }) => {
const { instance } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
const onLoad = async () => {
const currentAccount = instance.getActiveAccount();
if (currentAccount && currentAccount.idTokenClaims['roles']) {
let intersection = props.roles
.filter(role => currentAccount.idTokenClaims['roles'].includes(role));
if (intersection.length > 0) {
setIsAuthorized(true);
}
}
}
useEffect(() => {
onLoad();
}, [instance]);
return (
<>
{
isAuthorized
?
<Route {...props} render={routeProps => <Component {...routeProps} />} />
:
<div className="data-area-div">
<h3>You are unauthorized to view this content.</h3>
</div>
}
</>
);
};
I want the application to directly go to the '/todolist' and render the components within. My redirect uri, does not seem to work. When i login with the required role, it always renders 'You are unauthorized to view this content' as per the RouteGuard file. The URI is /signuplist/ but still the children props are not rendered. ONLY WHEN I CLICK the button 'Todolist' (as per NavigationBar.jsx), does it go and render the child props properly. Redirection does not work as expected. I want it to directly go to /todolist and render the page, child components
Any suggestions ?
A:
Can you try removing the async from onload method signature ?
A:
Did you registered 'http://localhost:3000/todolist/' as a valid redirect uri on Azure portal. You can have multiple redirect uri as per the role, but all the uri must be registred on Azure portal under you app.
https://learn.microsoft.com/en-ca/azure/active-directory/develop/quickstart-register-app#register-an-application
A redirect URI is the location where the Microsoft identity platform redirects a user's client and sends security tokens after authentication.Is
A:
In case my last comment worked out for you, let me make it into an official answer so it can be recorded.
Basically,
define: const { instance, accounts, inProgress } = useMsal();
Then try to redirect when inProgress !== 'login'.
|
How to Redirect automatically to a page/path on login - MSAL React SPA
|
I am working on a single page application (SPA) app that grants access to specific paths in the application, based on roles setup in Azure AD for the user logging in. As per this https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles
This is my 'authConfig.js' file - you can see the redirectUri
const clientId = window.REACT_APP_CLIENTID
export const msalConfig = {
auth: {
clientId: clientId,
authority: window.REACT_APP_AUTHORITY,
redirectUri: 'http://localhost:3000/todolist/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin
postLogoutRedirectUri: "/", // Indicates the page to navigate after logout.
navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
},
cache: {
cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
/**
* Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
*/
export const protectedResources = {
apiTodoList: {
todoListEndpoint: window.REACT_APP_APIENDPOINT+"/api/v2/support/list",
scopes: [window.REACT_APP_APIENDPOINT+"/access_as_user"],
},
}
/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
* For more information about OIDC scopes, visit:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
export const loginRequest = {
scopes: [...protectedResources.apiTodoList.scopes]
};
export const appRoles = {
TaskUser: "TaskUser",
TaskAdmin: "TaskAdmin",
TrialAdmin: "Trial.Admin",
GlobalAdmin: "Global.Admin"
}
Here is the App.jsx file (I believe there needs to be some change made here). You can see 'RouteGuard' that renders the Component {TodoList}, when the path 'todolist' is accessed.
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { MsalProvider } from "@azure/msal-react";
import { RouteGuard } from './components/RouteGuard';
import { PageLayout } from "./components/PageLayout";
import { TodoList } from "./pages/TodoList";
import { appRoles } from "./authConfig";
import "./styles/App.css";
const Pages = () => {
return (
<Switch>
<RouteGuard
exact
path='/todolist/'
roles={[appRoles.TaskUser, appRoles.TaskAdmin, appRoles.TrialAdmin, appRoles.GlobalAdmin]}
Component={TodoList}
/>
</Switch>
)
}
/**
* msal-react is built on the React context API and all parts of your app that require authentication must be
* wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication
* then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the
* PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
*/
const App = ({ instance }) => {
return (
<Router>
<MsalProvider instance={instance}>
<PageLayout>
<Pages instance={instance} />
</PageLayout>
</MsalProvider>
</Router>
);
}
export default App;
So as far as my understanding goes, the path 'todolist' is accessed with the listed role, and component is rendered
When logged in, The navigation bar at the top renders with login request, after authentication (). It has the button rendered, with a click function that 'href's to the path '/todolist'.
import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";
import { Nav, Navbar, Button, Dropdown, DropdownButton} from "react-bootstrap";
import React, { useState, useEffect } from "react";
import { loginRequest } from "../authConfig";
import { InteractionStatus, InteractionType } from "@azure/msal-browser";
import "../styles/App.css";
import logo from "../public/images/logo.jpg";
export const NavigationBar = (props) => {
const { instance } = useMsal();
const { inProgress } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
//The below function is needed incase you want to login using Popup and not redirect
const handleLogin = () => {
instance.loginPopup(loginRequest)
.catch((error) => console.log(error))
}
/**
* Most applications will need to conditionally render certain components based on whether a user is signed in or not.
* msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
* only render their children if a user is authenticated or unauthenticated, respectively.
*/
return (
<>
<Navbar className="color-custom" variant="dark">
<a className="navbar-brand" href="/"><img src={logo} className="navbarLogo" alt="TODDOLIST1"/></a>
<AuthenticatedTemplate>
<Nav.Link as={Button} id="signupbutton" variant="dark" className="signupNav" href="/todolist"><strong>List</strong></Nav.Link>
<Button variant="warning" className="ml-auto" drop="left" title="Sign Out" onClick={() => instance.logoutRedirect({ postLogoutRedirectUri: "/" })}><strong>Sign Out</strong></Button>
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<Button variant="dark" className="ml-auto" drop="left" title="Sign In" onClick={() => instance.loginRedirect(loginRequest)}>Sign In</Button>
</UnauthenticatedTemplate>
</Navbar>
</>
);
};
Here is the RouteGuard.jsx component that renders based on roles/authorization.
import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
export const RouteGuard = ({ Component, ...props }) => {
const { instance } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
const onLoad = async () => {
const currentAccount = instance.getActiveAccount();
if (currentAccount && currentAccount.idTokenClaims['roles']) {
let intersection = props.roles
.filter(role => currentAccount.idTokenClaims['roles'].includes(role));
if (intersection.length > 0) {
setIsAuthorized(true);
}
}
}
useEffect(() => {
onLoad();
}, [instance]);
return (
<>
{
isAuthorized
?
<Route {...props} render={routeProps => <Component {...routeProps} />} />
:
<div className="data-area-div">
<h3>You are unauthorized to view this content.</h3>
</div>
}
</>
);
};
I want the application to directly go to the '/todolist' and render the components within. My redirect uri, does not seem to work. When i login with the required role, it always renders 'You are unauthorized to view this content' as per the RouteGuard file. The URI is /signuplist/ but still the children props are not rendered. ONLY WHEN I CLICK the button 'Todolist' (as per NavigationBar.jsx), does it go and render the child props properly. Redirection does not work as expected. I want it to directly go to /todolist and render the page, child components
Any suggestions ?
|
[
"Can you try removing the async from onload method signature ?\n",
"Did you registered 'http://localhost:3000/todolist/' as a valid redirect uri on Azure portal. You can have multiple redirect uri as per the role, but all the uri must be registred on Azure portal under you app.\nhttps://learn.microsoft.com/en-ca/azure/active-directory/develop/quickstart-register-app#register-an-application\n\nA redirect URI is the location where the Microsoft identity platform redirects a user's client and sends security tokens after authentication.Is\n\n",
"In case my last comment worked out for you, let me make it into an official answer so it can be recorded.\nBasically,\ndefine: const { instance, accounts, inProgress } = useMsal();\nThen try to redirect when inProgress !== 'login'.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"azure_rbac",
"msal",
"msal_react",
"react_aad_msal",
"reactjs"
] |
stackoverflow_0074649973_azure_rbac_msal_msal_react_react_aad_msal_reactjs.txt
|
Q:
Unable to install agda via nix in macOS M1
Running
nix-shell -p agda
on macOS M1 (Monterey), compilation seems to run fine but linking fails with a segmentation error
clang-11: error: linker command failed with exit code 139 (use -v to see invocation)
`cc' failed in phase `Linker'. (Exit code: 139)
error: builder for '/nix/store/0zli7b0k7mdq3aj9yrfk546vr1a1mb34-Agda-2.6.2.2.drv' failed with exit code 1;
last 10 log lines:
> [399 of 401] Compiling Agda.Compiler.JS.Compiler ( src/full/Agda/Compiler/JS/Compiler.hs, dist/build/Agda/Compiler/JS/Compiler.o, dist/build/Agda/Compiler/JS/Compiler.dyn_o )
> [400 of 401] Compiling Agda.Compiler.Builtin ( src/full/Agda/Compiler/Builtin.hs, dist/build/Agda/Compiler/Builtin.o, dist/build/Agda/Compiler/Builtin.dyn_o )
> [401 of 401] Compiling Agda.Main ( src/full/Agda/Main.hs, dist/build/Agda/Main.o, dist/build/Agda/Main.dyn_o )
> Preprocessing executable 'agda' for Agda-2.6.2.2..
> Building executable 'agda' for Agda-2.6.2.2..
> [1 of 1] Compiling Main ( src/main/Main.hs, dist/build/agda/agda-tmp/Main.o )
> Linking dist/build/agda/agda ...
> /nix/store/l1vm9w0y2fdav63xk2nfrwgzrg30hm5x-clang-wrapper-11.1.0/bin/ld: line 256: 1241 Segmentation fault: 11 /nix/store/gwm9iadcyybh7gc4q6djvaz4fb40i90c-cctools-binutils-darwin-949.0.1/bin/ld ${extraBefore+"${extraBefore[@]}"} ${params+"${params[@]}"} ${extraAfter+"${extraAfter[@]}"}
> clang-11: error: linker command failed with exit code 139 (use -v to see invocation)
> `cc' failed in phase `Linker'. (Exit code: 139)
I did run into linking issues with other Haskell packages in recent versions of macOS, where ghc couldn't find libffi or zlib, and I had to set env variables, eg
export C_INCLUDE_PATH="`xcrun --show-sdk-path`/usr/include/ffi"¬
However, In the case of agda, from the error message it's not obvious to me what the issue is: is it caused by a C lib that the linker cannot locate, and if yes how can i discover which one? is it a problem with M1? is nix-shell -p agda suppose to work on M1?
A:
I've finally managed to find a github issue tracking the problem (it wasn't that easy to find): https://github.com/NixOS/nixpkgs/issues/149692#issuecomment-1177684790
According to the ticket, the only available workaround at the moment is to compile for x86_64 and use Rosetta
|
Unable to install agda via nix in macOS M1
|
Running
nix-shell -p agda
on macOS M1 (Monterey), compilation seems to run fine but linking fails with a segmentation error
clang-11: error: linker command failed with exit code 139 (use -v to see invocation)
`cc' failed in phase `Linker'. (Exit code: 139)
error: builder for '/nix/store/0zli7b0k7mdq3aj9yrfk546vr1a1mb34-Agda-2.6.2.2.drv' failed with exit code 1;
last 10 log lines:
> [399 of 401] Compiling Agda.Compiler.JS.Compiler ( src/full/Agda/Compiler/JS/Compiler.hs, dist/build/Agda/Compiler/JS/Compiler.o, dist/build/Agda/Compiler/JS/Compiler.dyn_o )
> [400 of 401] Compiling Agda.Compiler.Builtin ( src/full/Agda/Compiler/Builtin.hs, dist/build/Agda/Compiler/Builtin.o, dist/build/Agda/Compiler/Builtin.dyn_o )
> [401 of 401] Compiling Agda.Main ( src/full/Agda/Main.hs, dist/build/Agda/Main.o, dist/build/Agda/Main.dyn_o )
> Preprocessing executable 'agda' for Agda-2.6.2.2..
> Building executable 'agda' for Agda-2.6.2.2..
> [1 of 1] Compiling Main ( src/main/Main.hs, dist/build/agda/agda-tmp/Main.o )
> Linking dist/build/agda/agda ...
> /nix/store/l1vm9w0y2fdav63xk2nfrwgzrg30hm5x-clang-wrapper-11.1.0/bin/ld: line 256: 1241 Segmentation fault: 11 /nix/store/gwm9iadcyybh7gc4q6djvaz4fb40i90c-cctools-binutils-darwin-949.0.1/bin/ld ${extraBefore+"${extraBefore[@]}"} ${params+"${params[@]}"} ${extraAfter+"${extraAfter[@]}"}
> clang-11: error: linker command failed with exit code 139 (use -v to see invocation)
> `cc' failed in phase `Linker'. (Exit code: 139)
I did run into linking issues with other Haskell packages in recent versions of macOS, where ghc couldn't find libffi or zlib, and I had to set env variables, eg
export C_INCLUDE_PATH="`xcrun --show-sdk-path`/usr/include/ffi"¬
However, In the case of agda, from the error message it's not obvious to me what the issue is: is it caused by a C lib that the linker cannot locate, and if yes how can i discover which one? is it a problem with M1? is nix-shell -p agda suppose to work on M1?
|
[
"I've finally managed to find a github issue tracking the problem (it wasn't that easy to find): https://github.com/NixOS/nixpkgs/issues/149692#issuecomment-1177684790\nAccording to the ticket, the only available workaround at the moment is to compile for x86_64 and use Rosetta\n"
] |
[
0
] |
[] |
[] |
[
"agda",
"apple_m1",
"macos",
"nix",
"segmentation_fault"
] |
stackoverflow_0074621737_agda_apple_m1_macos_nix_segmentation_fault.txt
|
Q:
Amcharts5: legend errors in multiline chart
I am using amchart5 to render some multi line data and I have some issues with how the data is being rendered.
I cannot add currency symbols to the labels of the y-axis
I cant turn the labels of the x-axis so they are more vertical rather than horizontal
The preview will not show any lines
How can I resolve this?
See image:
Javascript
<script type="text/javascript">
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("fundChartLine");
root.numberFormatter.setAll({
numberFormat: "#,###.##00",
});
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root),
am5themes_Responsive.new(root),
Amdg.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
// Define data
var data = {{ line_chart_data| safe }}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
// Create Y-axis
let yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
// Create X-Axis
/*var xAxis = chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {}),
categoryField: "chart_dates"
})
);
xAxis.data.setAll(data);*/
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
minGridDistance: 30
})
})
);
xAxis.get("dateFormats")["day"] = "MM/dd";
xAxis.get("periodChangeDateFormats")["day"] = "MMMM";
xAxis.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/
function createSeries(name, field) {
var series = chart.series.push(
am5xy.LineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: field,
categoryXField: "chart_dated_dt",
stacked: false
//legendLabelText: "[{fill}]{category}[/]",
//legendValueYText: "[bold {fill}]ZAR{valueY}[/]"
})
);
series.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
series.fills.template.setAll({
fillOpacity: 0.5,
visible: false
});
series.data.setAll(data);
//series.labels.template.set("visible", false);
//series.ticks.template.set("visible", false);
console.log(series)
}
chart.topAxesContainer.children.push(am5.Label.new(root, {
text: "Performance",
fontSize: 30,
fontColor: '#e40505',
fontWeight: "500",
textAlign: "center",
x: am5.percent(50),
centerX: am5.percent(50),
paddingTop: 0,
paddingBottom: 20,
}));
createSeries("Average Contributions", "average_contrib");
createSeries("Average Contributions + Interest", "average_totals");
createSeries("Median Contributions", "median_contrib");
createSeries("Median Contributions + Interest", "median_totals");
createSeries("Your Contributions", "user_contrib");
createSeries("Your Contributions + Interest", "user_totals");
//var legend = chart.children.push(am5.Legend.new(root, {}));
//legend.data.setAll(chart.series.values);
var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
useDefaultMarker: true,
paddingTop: 10,
paddingBottom: 20,
layout: am5.GridLayout.new(root, {
maxColumns: 3,
fixedWidthGrid: true
})
}));
legend.data.setAll(chart.series.values);
// Add scrollbar
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
/*var scrollbarX = am5.Scrollbar.new(root, {
orientation: "horizontal"
});*/
var scrollbarX = am5xy.XYChartScrollbar.new(root, {
orientation: "horizontal",
height: 50
});
//chart.bottomAxesContainer.children.push(scrollbarX);
/*let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
}),
categoryField: "chart_dates"
})
);*/
let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
groupIntervals: [{ timeUnit: "year", count: 1 }],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
})
})
);
let sbyAxis = scrollbarX.chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
let sbseries = scrollbarX.chart.series.push(
am5xy.LineSeries.new(root, {
xAxis: sbxAxis,
yAxis: sbyAxis,
valueYField: "user_totals",
valueXField: "chart_dated_dt",
})
);
sbseries.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
sbseries.data.setAll(data);
chart.set("scrollbarX", scrollbarX);
console.log(sbseries.data.values[0]["user_totals"])
console.log(sbseries.data.values[0]["chart_dated_dt"])
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
root._logo.dispose();
chart.appear(1000, 100);
}); // end am5.ready()
I've looked at the docs and at some questions here and still stuck-
A:
For the currency I added the currency symbol within the number formatter:
root.numberFormatter.setAll({
numberFormat: "'ZAR '#,###.##00",
tooltipNumberFormat: "'ZAR '#,###.##00",
I didn't figure out how to handle the formatting of the legend but what I did instead was change the date data from a Category value with a string to a an actual which allowed me to change the axis into a date one. Amcharts naturally handles the formatting of this in such a way that my problem disappeared and it also fit my long terms data goals for the chart. The category was a story gap.
The preview had isues with my date compile. I noticed in the code when converting the date I was simply making the date object but not actually getting the time. By using the the get_time i was able to properly render the x-axis. This issue aslo affected number 2.
for (let i = 0; i < data.length; i++) {
data[i]["chart_dated_dt"] = new Date(data[i]["chart_dated_dt"]).getTime();
}
Full code:
<script type="text/javascript">
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("fundChartLine");
root.numberFormatter.setAll({
numberFormat: "'ZAR '#,###.##00",
tooltipNumberFormat: "'ZAR '#,###.##00",
});
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root),
am5themes_Responsive.new(root),
Amdg.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
// Define data
var data = {{ line_chart_data| safe }}
for (let i = 0; i < data.length; i++) {
data[i]["chart_dated_dt"] = new Date(data[i]["chart_dated_dt"]).getTime();
}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
// Create Y-axis
let yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
maxDeviation: 0.1,
renderer: am5xy.AxisRendererY.new(root, {})
})
);
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
maxDeviation: 0.1,
groupData: true,
groupIntervals: [
{ timeUnit: "month", count: 1 }
],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
}),
tooltip: am5.Tooltip.new(root, {})
})
);
xAxis.get("dateFormats")["day"] = "MM/dd";
xAxis.get("periodChangeDateFormats")["day"] = "MMMM";
xAxis.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/
function createSeries(name, field) {
var series = chart.series.push(
am5xy.LineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: field,
valueXField: "chart_dated_dt",
stacked: false,
tooltip: am5.Tooltip.new(root, {
pointerOrientation: "horizontal",
labelText: "{valueY}",
})
})
);
series.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
series.fills.template.setAll({
fillOpacity: 0.5,
visible: false
});
series.data.setAll(data);
}
chart.topAxesContainer.children.push(am5.Label.new(root, {
text: "Performance",
fontSize: 30,
fontColor: '#e40505',
fontWeight: "500",
textAlign: "center",
x: am5.percent(50),
centerX: am5.percent(50),
paddingTop: 0,
paddingBottom: 20,
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
createSeries("Average Contributions", "average_contrib");
createSeries("Average Contributions + Interest", "average_totals");
createSeries("Median Contributions", "median_contrib");
createSeries("Median Contributions + Interest", "median_totals");
createSeries("Your Contributions", "user_contrib");
createSeries("Your Contributions + Interest", "user_totals");
var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
useDefaultMarker: true,
paddingTop: 10,
paddingBottom: 20,
layout: am5.GridLayout.new(root, {
maxColumns: 3,
fixedWidthGrid: true
})
}));
legend.data.setAll(chart.series.values);
// Add scrollbar
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
var scrollbarX = am5xy.XYChartScrollbar.new(root, {
orientation: "horizontal",
height: 50
});
let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
groupIntervals: [
{ timeUnit: "month", count: 1 }
],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
})
})
);
let sbyAxis = scrollbarX.chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
let sbseries = scrollbarX.chart.series.push(
am5xy.LineSeries.new(root, {
xAxis: sbxAxis,
yAxis: sbyAxis,
valueYField: "user_totals",
valueXField: "chart_dated_dt",
})
);
sbseries.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
sbseries.data.setAll(data);
chart.set("scrollbarX", scrollbarX);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
sbseries.appear(1000, 100);
console.log(chart.series)
console
root._logo.dispose();
chart.appear(1000, 100);
}); // end am5.ready()
</script>
|
Amcharts5: legend errors in multiline chart
|
I am using amchart5 to render some multi line data and I have some issues with how the data is being rendered.
I cannot add currency symbols to the labels of the y-axis
I cant turn the labels of the x-axis so they are more vertical rather than horizontal
The preview will not show any lines
How can I resolve this?
See image:
Javascript
<script type="text/javascript">
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("fundChartLine");
root.numberFormatter.setAll({
numberFormat: "#,###.##00",
});
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root),
am5themes_Responsive.new(root),
Amdg.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
// Define data
var data = {{ line_chart_data| safe }}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
// Create Y-axis
let yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
// Create X-Axis
/*var xAxis = chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {}),
categoryField: "chart_dates"
})
);
xAxis.data.setAll(data);*/
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
minGridDistance: 30
})
})
);
xAxis.get("dateFormats")["day"] = "MM/dd";
xAxis.get("periodChangeDateFormats")["day"] = "MMMM";
xAxis.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/
function createSeries(name, field) {
var series = chart.series.push(
am5xy.LineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: field,
categoryXField: "chart_dated_dt",
stacked: false
//legendLabelText: "[{fill}]{category}[/]",
//legendValueYText: "[bold {fill}]ZAR{valueY}[/]"
})
);
series.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
series.fills.template.setAll({
fillOpacity: 0.5,
visible: false
});
series.data.setAll(data);
//series.labels.template.set("visible", false);
//series.ticks.template.set("visible", false);
console.log(series)
}
chart.topAxesContainer.children.push(am5.Label.new(root, {
text: "Performance",
fontSize: 30,
fontColor: '#e40505',
fontWeight: "500",
textAlign: "center",
x: am5.percent(50),
centerX: am5.percent(50),
paddingTop: 0,
paddingBottom: 20,
}));
createSeries("Average Contributions", "average_contrib");
createSeries("Average Contributions + Interest", "average_totals");
createSeries("Median Contributions", "median_contrib");
createSeries("Median Contributions + Interest", "median_totals");
createSeries("Your Contributions", "user_contrib");
createSeries("Your Contributions + Interest", "user_totals");
//var legend = chart.children.push(am5.Legend.new(root, {}));
//legend.data.setAll(chart.series.values);
var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
useDefaultMarker: true,
paddingTop: 10,
paddingBottom: 20,
layout: am5.GridLayout.new(root, {
maxColumns: 3,
fixedWidthGrid: true
})
}));
legend.data.setAll(chart.series.values);
// Add scrollbar
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
/*var scrollbarX = am5.Scrollbar.new(root, {
orientation: "horizontal"
});*/
var scrollbarX = am5xy.XYChartScrollbar.new(root, {
orientation: "horizontal",
height: 50
});
//chart.bottomAxesContainer.children.push(scrollbarX);
/*let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
}),
categoryField: "chart_dates"
})
);*/
let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
groupIntervals: [{ timeUnit: "year", count: 1 }],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
})
})
);
let sbyAxis = scrollbarX.chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
let sbseries = scrollbarX.chart.series.push(
am5xy.LineSeries.new(root, {
xAxis: sbxAxis,
yAxis: sbyAxis,
valueYField: "user_totals",
valueXField: "chart_dated_dt",
})
);
sbseries.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
sbseries.data.setAll(data);
chart.set("scrollbarX", scrollbarX);
console.log(sbseries.data.values[0]["user_totals"])
console.log(sbseries.data.values[0]["chart_dated_dt"])
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
root._logo.dispose();
chart.appear(1000, 100);
}); // end am5.ready()
I've looked at the docs and at some questions here and still stuck-
|
[
"\nFor the currency I added the currency symbol within the number formatter:\nroot.numberFormatter.setAll({\nnumberFormat: \"'ZAR '#,###.##00\",\ntooltipNumberFormat: \"'ZAR '#,###.##00\",\n\nI didn't figure out how to handle the formatting of the legend but what I did instead was change the date data from a Category value with a string to a an actual which allowed me to change the axis into a date one. Amcharts naturally handles the formatting of this in such a way that my problem disappeared and it also fit my long terms data goals for the chart. The category was a story gap.\n\nThe preview had isues with my date compile. I noticed in the code when converting the date I was simply making the date object but not actually getting the time. By using the the get_time i was able to properly render the x-axis. This issue aslo affected number 2.\nfor (let i = 0; i < data.length; i++) {\ndata[i][\"chart_dated_dt\"] = new Date(data[i][\"chart_dated_dt\"]).getTime();\n}\n\n\nFull code:\n<script type=\"text/javascript\">\n am5.ready(function() {\n\n // Create root element\n // https://www.amcharts.com/docs/v5/getting-started/#Root_element\n var root = am5.Root.new(\"fundChartLine\");\n \n root.numberFormatter.setAll({\n numberFormat: \"'ZAR '#,###.##00\",\n tooltipNumberFormat: \"'ZAR '#,###.##00\",\n });\n\n // Set themes\n // https://www.amcharts.com/docs/v5/concepts/themes/\n root.setThemes([\n am5themes_Animated.new(root),\n am5themes_Responsive.new(root),\n Amdg.new(root)\n ]);\n // Create chart\n // https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/\n var chart = root.container.children.push(am5xy.XYChart.new(root, {\n panX: true,\n panY: true,\n wheelX: \"panX\",\n wheelY: \"zoomX\",\n pinchZoomX:true\n }));\n // Add cursor\n // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/\n var cursor = chart.set(\"cursor\", am5xy.XYCursor.new(root, {\n behavior: \"none\"\n }));\n cursor.lineY.set(\"visible\", false);\n\n\n\n // Define data\n var data = {{ line_chart_data| safe }}\n \n for (let i = 0; i < data.length; i++) {\n data[i][\"chart_dated_dt\"] = new Date(data[i][\"chart_dated_dt\"]).getTime();\n }\n\n // Create axes\n // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/\n // Create Y-axis\n let yAxis = chart.yAxes.push(\n am5xy.ValueAxis.new(root, {\n maxDeviation: 0.1,\n renderer: am5xy.AxisRendererY.new(root, {})\n })\n );\n\n\n var xAxis = chart.xAxes.push(\n am5xy.DateAxis.new(root, {\n maxDeviation: 0.1,\n groupData: true,\n groupIntervals: [\n { timeUnit: \"month\", count: 1 }\n ],\n baseInterval: { timeUnit: \"day\", count: 1 },\n renderer: am5xy.AxisRendererX.new(root, {\n }),\n tooltip: am5.Tooltip.new(root, {})\n })\n );\n\n xAxis.get(\"dateFormats\")[\"day\"] = \"MM/dd\";\n xAxis.get(\"periodChangeDateFormats\")[\"day\"] = \"MMMM\";\n \n xAxis.data.setAll(data);\n // Add series\n // https://www.amcharts.com/docs/v5/charts/xy-chart/series/\n // https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/\n function createSeries(name, field) {\n var series = chart.series.push( \n am5xy.LineSeries.new(root, { \n name: name,\n xAxis: xAxis, \n yAxis: yAxis,\n valueYField: field, \n valueXField: \"chart_dated_dt\",\n stacked: false,\n tooltip: am5.Tooltip.new(root, {\n pointerOrientation: \"horizontal\",\n labelText: \"{valueY}\",\n })\n\n })\n );\n \n series.strokes.template.setAll({\n strokeWidth: 2,\n //strokeDasharray: [2,1]\n });\n series.fills.template.setAll({\n fillOpacity: 0.5,\n visible: false\n });\n series.data.setAll(data);\n\n }\n \n chart.topAxesContainer.children.push(am5.Label.new(root, {\n text: \"Performance\",\n fontSize: 30,\n fontColor: '#e40505',\n fontWeight: \"500\",\n textAlign: \"center\",\n x: am5.percent(50),\n centerX: am5.percent(50),\n paddingTop: 0,\n paddingBottom: 20,\n }));\n\n // Add cursor\n // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/\n var cursor = chart.set(\"cursor\", am5xy.XYCursor.new(root, {\n xAxis: xAxis\n }));\n cursor.lineY.set(\"visible\", false);\n\n\n createSeries(\"Average Contributions\", \"average_contrib\");\n createSeries(\"Average Contributions + Interest\", \"average_totals\");\n createSeries(\"Median Contributions\", \"median_contrib\");\n createSeries(\"Median Contributions + Interest\", \"median_totals\");\n createSeries(\"Your Contributions\", \"user_contrib\");\n createSeries(\"Your Contributions + Interest\", \"user_totals\");\n\n var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {\n centerX: am5.percent(50),\n x: am5.percent(50),\n useDefaultMarker: true,\n paddingTop: 10,\n paddingBottom: 20,\n layout: am5.GridLayout.new(root, {\n maxColumns: 3,\n fixedWidthGrid: true\n })\n }));\n legend.data.setAll(chart.series.values);\n\n // Add scrollbar\n // https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/\n\n var scrollbarX = am5xy.XYChartScrollbar.new(root, {\n orientation: \"horizontal\",\n height: 50\n });\n \n let sbxAxis = scrollbarX.chart.xAxes.push(\n am5xy.DateAxis.new(root, {\n groupData: true,\n groupIntervals: [\n { timeUnit: \"month\", count: 1 }\n ],\n baseInterval: { timeUnit: \"day\", count: 1 },\n renderer: am5xy.AxisRendererX.new(root, {\n opposite: false,\n strokeOpacity: 0\n })\n })\n );\n\n let sbyAxis = scrollbarX.chart.yAxes.push(\n am5xy.ValueAxis.new(root, {\n renderer: am5xy.AxisRendererY.new(root, {})\n })\n );\n\n let sbseries = scrollbarX.chart.series.push(\n am5xy.LineSeries.new(root, {\n xAxis: sbxAxis,\n yAxis: sbyAxis,\n valueYField: \"user_totals\", \n valueXField: \"chart_dated_dt\",\n })\n );\n sbseries.strokes.template.setAll({\n strokeWidth: 2,\n //strokeDasharray: [2,1]\n });\n sbseries.data.setAll(data);\n chart.set(\"scrollbarX\", scrollbarX);\n\n\n // Make stuff animate on load\n // https://www.amcharts.com/docs/v5/concepts/animations/\n \n sbseries.appear(1000, 100);\n console.log(chart.series)\n console\n root._logo.dispose();\n chart.appear(1000, 100);\n }); // end am5.ready()\n</script>\n\n"
] |
[
1
] |
[] |
[] |
[
"amcharts",
"amcharts5",
"javascript",
"visualization"
] |
stackoverflow_0074580792_amcharts_amcharts5_javascript_visualization.txt
|
Q:
Failure starting docker container. "failed to create shim task: OCI runtime create failed: runc create failed"
I am new to Ubuntu and new to Docker. I am running a command that was given to me in an explanation of how to start the project. I want to start my Docker containers and they fail with an error.
Some notes:
It is a new Ubuntu laptop.
I added Docker to have sudo privileges. groups yields docker among the list it responds with.
Here's the command I use to start it: docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
And it gives:
Step 11/12 : EXPOSE $PORT
---> Using cache
---> 7620427ebfe9
Step 12/12 : CMD ["ts-node", "./src/server.ts"]
---> Using cache
---> 00a32820e6e2
Successfully built 00a32820e6e2
Successfully tagged backend-marketplace_backend:latest
backend-marketplace_database_1 is up-to-date
Starting backend-marketplace_backend_1 ...
Starting backend-marketplace_backend_1 ... error
ERROR: for backend-marketplace_backend_1 Cannot start service backend: failed to create shim task:
OCI runtime create failed: runc create failed: unable to start container process: error during container init:
error mounting "/var/lib/docker/volumes/3ceff6572cda1981f7d29faf09f888cb9a8c0c5ac41b10bb323eb5d14e7e1d35/_data"
to rootfs at "/app/node_modules": mkdir /var/lib/docker/overlay2/c0a5b761bb9a94bb9a4dd3c21a862968dbbabe87698c0f744569ea56e323ea0e/merged/app/node_modules:
read-only file system: unknown
ERROR: for backend Cannot start service backend: failed to create shim task:
OCI runtime create failed: runc create failed: unable to start container process: error during container init:
error mounting "/var/lib/docker/volumes/3ceff6572cda1981f7d29faf09f888cb9a8c0c5ac41b10bb323eb5d14e7e1d35/_data" to rootfs at
"/app/node_modules": mkdir /var/lib/docker/overlay2/c0a5b761bb9a94bb9a4dd3c21a862968dbbabe87698c0f744569ea56e323ea0e/merged/app/node_modules:
read-only file system: unknown
ERROR: Encountered errors while bringing up the project.
I see docker-compose.yml and docker-compose.dev.yml mentioned so here they are:
docker-compse.yml:
version: "3"
services:
backend:
build: .
ports:
- "8000:8000"
env_file:
- ./.env
and docker-compose.dev.yml:
version: "3"
services:
backend:
build:
context: .
args:
NODE_ENV: development
volumes:
- ./:/app:ro
- /app/node_modules
links:
- database
env_file:
- ./.env
command: npm run dev
database:
image: "postgres:latest"
volumes:
- pgdata:/var/lib/postgresql/data
expose:
- "5432"
ports:
- "5432:5432"
env_file:
- ./.env.database
pgadmin:
image: dpage/pgadmin4:latest
ports:
- 5454:5454/tcp
environment:
- PGADMIN_DEFAULT_EMAIL=<redacted>
- PGADMIN_DEFAULT_PASSWORD=<redacted>
- PGADMIN_LISTEN_PORT=5454
depends_on:
- database
volumes:
pgdata:
I would love to say "I found a few threads and tried what they recommend" but to be honest I don't really understand them when I read them yet. The following threads might be related but they read like Latin to me.
"Error response from daemon: failed to create shim: OCI runtime create failed" error on Windows machine
Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver
Cannot start service app: OCI runtime create failed: container_linux.go:349
Like, my guess from reading the error message is that there's some sort of write permission I need to turn on, because the error message ends in "read-only file system: unknown". Sadly, that's all I can contribute.
A:
A coworker solved my issue.
FROM node:16-alpine
ENV NODE_ENV="development"
WORKDIR /app
COPY package.json .
COPY package-lock.json .
ARG NODE_ENV
RUN apk add g++ make py3-pip
RUN npm install
RUN chown -R node /app/node_modules
RUN npm install -g ts-node nodemon
COPY . ./
ENV PORT 8000
EXPOSE $PORT
CMD ["ts-node", "./src/server.ts"]
I added RUN chown -R node /app/node_modules and it worked. He said the issue was Linux specific.
A:
Quite elementary good sir (Sherlock)...
Linux is just picky when it comes to executing files as an executable (redundant I know).
So you create a text file (or binary file) with commands but you want to then run that file and have it perform some job within the container, yet you will need to let the environment know that it has permissions to do so.
chown or chmod would do the trick.
--chmod-- approch
RUN chmod +x ./src/server.ts
The level of permissions (+x for all) gives the executable the rights to do so within the container.
A:
In my case, docker compose had timed out, and had corrupted the containers. I just had to:
increase the compose timeout (COMPOSE_HTTP_TIMEOUT=480)
clean the containers (docker (image|container|network) prune
run compose again
|
Failure starting docker container. "failed to create shim task: OCI runtime create failed: runc create failed"
|
I am new to Ubuntu and new to Docker. I am running a command that was given to me in an explanation of how to start the project. I want to start my Docker containers and they fail with an error.
Some notes:
It is a new Ubuntu laptop.
I added Docker to have sudo privileges. groups yields docker among the list it responds with.
Here's the command I use to start it: docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
And it gives:
Step 11/12 : EXPOSE $PORT
---> Using cache
---> 7620427ebfe9
Step 12/12 : CMD ["ts-node", "./src/server.ts"]
---> Using cache
---> 00a32820e6e2
Successfully built 00a32820e6e2
Successfully tagged backend-marketplace_backend:latest
backend-marketplace_database_1 is up-to-date
Starting backend-marketplace_backend_1 ...
Starting backend-marketplace_backend_1 ... error
ERROR: for backend-marketplace_backend_1 Cannot start service backend: failed to create shim task:
OCI runtime create failed: runc create failed: unable to start container process: error during container init:
error mounting "/var/lib/docker/volumes/3ceff6572cda1981f7d29faf09f888cb9a8c0c5ac41b10bb323eb5d14e7e1d35/_data"
to rootfs at "/app/node_modules": mkdir /var/lib/docker/overlay2/c0a5b761bb9a94bb9a4dd3c21a862968dbbabe87698c0f744569ea56e323ea0e/merged/app/node_modules:
read-only file system: unknown
ERROR: for backend Cannot start service backend: failed to create shim task:
OCI runtime create failed: runc create failed: unable to start container process: error during container init:
error mounting "/var/lib/docker/volumes/3ceff6572cda1981f7d29faf09f888cb9a8c0c5ac41b10bb323eb5d14e7e1d35/_data" to rootfs at
"/app/node_modules": mkdir /var/lib/docker/overlay2/c0a5b761bb9a94bb9a4dd3c21a862968dbbabe87698c0f744569ea56e323ea0e/merged/app/node_modules:
read-only file system: unknown
ERROR: Encountered errors while bringing up the project.
I see docker-compose.yml and docker-compose.dev.yml mentioned so here they are:
docker-compse.yml:
version: "3"
services:
backend:
build: .
ports:
- "8000:8000"
env_file:
- ./.env
and docker-compose.dev.yml:
version: "3"
services:
backend:
build:
context: .
args:
NODE_ENV: development
volumes:
- ./:/app:ro
- /app/node_modules
links:
- database
env_file:
- ./.env
command: npm run dev
database:
image: "postgres:latest"
volumes:
- pgdata:/var/lib/postgresql/data
expose:
- "5432"
ports:
- "5432:5432"
env_file:
- ./.env.database
pgadmin:
image: dpage/pgadmin4:latest
ports:
- 5454:5454/tcp
environment:
- PGADMIN_DEFAULT_EMAIL=<redacted>
- PGADMIN_DEFAULT_PASSWORD=<redacted>
- PGADMIN_LISTEN_PORT=5454
depends_on:
- database
volumes:
pgdata:
I would love to say "I found a few threads and tried what they recommend" but to be honest I don't really understand them when I read them yet. The following threads might be related but they read like Latin to me.
"Error response from daemon: failed to create shim: OCI runtime create failed" error on Windows machine
Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver
Cannot start service app: OCI runtime create failed: container_linux.go:349
Like, my guess from reading the error message is that there's some sort of write permission I need to turn on, because the error message ends in "read-only file system: unknown". Sadly, that's all I can contribute.
|
[
"A coworker solved my issue.\nFROM node:16-alpine\nENV NODE_ENV=\"development\"\nWORKDIR /app\nCOPY package.json .\nCOPY package-lock.json .\nARG NODE_ENV\nRUN apk add g++ make py3-pip\nRUN npm install\nRUN chown -R node /app/node_modules\nRUN npm install -g ts-node nodemon\nCOPY . ./\nENV PORT 8000\nEXPOSE $PORT\nCMD [\"ts-node\", \"./src/server.ts\"]\n\n\nI added RUN chown -R node /app/node_modules and it worked. He said the issue was Linux specific.\n",
"Quite elementary good sir (Sherlock)...\nLinux is just picky when it comes to executing files as an executable (redundant I know).\nSo you create a text file (or binary file) with commands but you want to then run that file and have it perform some job within the container, yet you will need to let the environment know that it has permissions to do so.\nchown or chmod would do the trick.\n--chmod-- approch\nRUN chmod +x ./src/server.ts\nThe level of permissions (+x for all) gives the executable the rights to do so within the container.\n",
"In my case, docker compose had timed out, and had corrupted the containers. I just had to:\n\nincrease the compose timeout (COMPOSE_HTTP_TIMEOUT=480)\nclean the containers (docker (image|container|network) prune\nrun compose again\n\n"
] |
[
6,
1,
1
] |
[] |
[] |
[
"docker",
"docker_compose"
] |
stackoverflow_0072695311_docker_docker_compose.txt
|
Q:
AccessDeniedException when retrieving AWS Parameters from Lambda
I am attempting to access system parameters from a Lambda developed using C#
I have added the required lambda layer as per https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html#ps-integration-lambda-extensions-sample-commands
The lambda execution role has the following in the IAM definition (???????? replacing actual account id)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ssm:*"
],
"Resource": "arn:aws:ssm:*:???????????:parameter/*"
}
]
}
As per the AWS page reference above I made a HTTP GET request to http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1
This is failing with the following response
{
"Version": "1.1",
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"text/plain"
]
},
{
"Key": "Content-Length",
"Value": [
"31"
]
}
]
},
"StatusCode": 401,
"ReasonPhrase": "Unauthorized",
"Headers": [
{
"Key": "X-Amzn-Errortype",
"Value": [
"AccessDeniedException"
]
},
{
"Key": "Date",
"Value": [
"Thu, 01 Dec 2022 12:16:59 GMT"
]
}
],
"TrailingHeaders": [],
"RequestMessage": {
"Version": "1.1",
"VersionPolicy": 0,
"Content": null,
"Method": {
"Method": "GET"
},
"RequestUri": "http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1",
"Headers": [],
"Properties": {},
"Options": {}
},
"IsSuccessStatusCode": false
}
Any clues where I am going wrong?
A:
After a discussion on an AWS forum, it looks like the issue was that I was not setting a required header of the HTTP GET request.
For this to work, it needs the X-Aws-Parameters-Secrets-Token header set with the AWS_SESSION_TOKEN.
Once I did this it worked fine.
|
AccessDeniedException when retrieving AWS Parameters from Lambda
|
I am attempting to access system parameters from a Lambda developed using C#
I have added the required lambda layer as per https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html#ps-integration-lambda-extensions-sample-commands
The lambda execution role has the following in the IAM definition (???????? replacing actual account id)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ssm:*"
],
"Resource": "arn:aws:ssm:*:???????????:parameter/*"
}
]
}
As per the AWS page reference above I made a HTTP GET request to http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1
This is failing with the following response
{
"Version": "1.1",
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"text/plain"
]
},
{
"Key": "Content-Length",
"Value": [
"31"
]
}
]
},
"StatusCode": 401,
"ReasonPhrase": "Unauthorized",
"Headers": [
{
"Key": "X-Amzn-Errortype",
"Value": [
"AccessDeniedException"
]
},
{
"Key": "Date",
"Value": [
"Thu, 01 Dec 2022 12:16:59 GMT"
]
}
],
"TrailingHeaders": [],
"RequestMessage": {
"Version": "1.1",
"VersionPolicy": 0,
"Content": null,
"Method": {
"Method": "GET"
},
"RequestUri": "http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1",
"Headers": [],
"Properties": {},
"Options": {}
},
"IsSuccessStatusCode": false
}
Any clues where I am going wrong?
|
[
"After a discussion on an AWS forum, it looks like the issue was that I was not setting a required header of the HTTP GET request.\nFor this to work, it needs the X-Aws-Parameters-Secrets-Token header set with the AWS_SESSION_TOKEN.\nOnce I did this it worked fine.\n"
] |
[
0
] |
[] |
[] |
[
"amazon_iam",
"aws_lambda",
"aws_lambda_layers"
] |
stackoverflow_0074641769_amazon_iam_aws_lambda_aws_lambda_layers.txt
|
Q:
Kstream transformValues ambigious
I have problem with ambiguous methods in KStream.
Actually I don't understand what is wrong.
.toStream()
.transformValues(
ValueTransformerWithKeySupplier<String, CandleDto, CandleDto> {
SuppressTransformer<String, CandleDto, CandleDto>(
Duration.ofMinutes(5),
"supress-store",
Duration.ofSeconds(5))
},
"suppress-store"
)
This code result into this:
class SuppressTransformer<K, V, VR>(
private val windowSize: Duration,
private val storeName: String,
private val scheduleTime: Duration
) : ValueTransformerWithKey<K, V, VR> {
// Implementation
}
A:
Update: I just realize what is wrong (because i'm blind). Thanks @OneCricketeer, your answer forced me to look logs once more :-)
Error was caused because I use windowing before transformation.
And I had to map values before start transformation.
Now it is compilable:
.map { key, value -> KeyValue.pair(key.key(), Mapper.toCandle(value)) }
.transformValues(
ValueTransformerWithKeySupplier<String, Candle, Candle> {
SuppressTransformer<String, Candle,Candle>(
Duration.ofMinutes(5),
"suppress-store",
Duration.ofSeconds(5))
},
"suppress-store"
)
|
Kstream transformValues ambigious
|
I have problem with ambiguous methods in KStream.
Actually I don't understand what is wrong.
.toStream()
.transformValues(
ValueTransformerWithKeySupplier<String, CandleDto, CandleDto> {
SuppressTransformer<String, CandleDto, CandleDto>(
Duration.ofMinutes(5),
"supress-store",
Duration.ofSeconds(5))
},
"suppress-store"
)
This code result into this:
class SuppressTransformer<K, V, VR>(
private val windowSize: Duration,
private val storeName: String,
private val scheduleTime: Duration
) : ValueTransformerWithKey<K, V, VR> {
// Implementation
}
|
[
"Update: I just realize what is wrong (because i'm blind). Thanks @OneCricketeer, your answer forced me to look logs once more :-)\nError was caused because I use windowing before transformation.\nAnd I had to map values before start transformation.\nNow it is compilable:\n .map { key, value -> KeyValue.pair(key.key(), Mapper.toCandle(value)) }\n .transformValues(\n ValueTransformerWithKeySupplier<String, Candle, Candle> {\n SuppressTransformer<String, Candle,Candle>(\n Duration.ofMinutes(5),\n \"suppress-store\",\n Duration.ofSeconds(5))\n },\n \"suppress-store\"\n )\n\n"
] |
[
1
] |
[] |
[] |
[
"apache_kafka",
"apache_kafka_streams",
"kotlin"
] |
stackoverflow_0074662108_apache_kafka_apache_kafka_streams_kotlin.txt
|
Q:
browser does't receive the reponse that tokio TcpStream write
i tried use tokio(tokio={version="1", features=["full"]}) to implement a simple http server. The code is below. The weired thing is the server can receive the request from browser, but the brower can't receive the response from the server. Is there any bug in my code?
use tokio::{self, net};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
async fn process(mut stream: TcpStream) {
let mut buf = [0u8; 4096];
loop {
let n = stream.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
let s = String::from_utf8_lossy(&buf[0..n]).to_string();
print!("{}", s);
if s.ends_with("\r\n\r\n") {
println!("request received");
break;
}
}
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>
";
println!("response");
// browser doesn't receive the response that this line of code send.
stream.write(response_str.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
println!("response DONE");
}
#[tokio::main]
async fn main() {
let listener = net::TcpListener::bind("127.0.0.1:9998").await.unwrap();
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move{
process(stream).await;
});
}
}
A:
there need a extra line separator between status line and entity body. the browser can pase the response when the response_str like this
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>"
|
browser does't receive the reponse that tokio TcpStream write
|
i tried use tokio(tokio={version="1", features=["full"]}) to implement a simple http server. The code is below. The weired thing is the server can receive the request from browser, but the brower can't receive the response from the server. Is there any bug in my code?
use tokio::{self, net};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
async fn process(mut stream: TcpStream) {
let mut buf = [0u8; 4096];
loop {
let n = stream.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
let s = String::from_utf8_lossy(&buf[0..n]).to_string();
print!("{}", s);
if s.ends_with("\r\n\r\n") {
println!("request received");
break;
}
}
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>
";
println!("response");
// browser doesn't receive the response that this line of code send.
stream.write(response_str.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
println!("response DONE");
}
#[tokio::main]
async fn main() {
let listener = net::TcpListener::bind("127.0.0.1:9998").await.unwrap();
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move{
process(stream).await;
});
}
}
|
[
"there need a extra line separator between status line and entity body. the browser can pase the response when the response_str like this\nlet response_str = \"HTTP/1.1 200 OK\n\n<!DOCTYPE html>\n<html lang=\\\"en\\\">\n<head>\n<meta charset=\\\"udf-8\\\">\n<title>Hello!</title>\n</head>\n<body>\nHELLO\n</body>\n</html>\"\n\n"
] |
[
0
] |
[] |
[] |
[
"rust",
"rust_tokio"
] |
stackoverflow_0074662212_rust_rust_tokio.txt
|
Q:
Google Cloud DNS records do not propagate to any server
Hej!
I own a domain registered through GCP and it's connected with Cloud DNS in GCP, I would be very happy if you could help me setup my custom domain for my web page at buahaha.github.io.
I think I know how to do this, because I did it before with other domain(s), but this time something is not working as it should. I have set up even a TXT record, and it does not propagate through DNS servers, and the same goes for my CNAME record. I attach screenshots of my setup below.
It's strange to me as it is the basic setup for this kind of service, and I'm really confused...
Pozdrawiam,
Szymon
A:
The problem was that I had to explicitly choose Cloud DNS as my DNS provider. If you have set your DNS zone already, just choose it from the drop-down menu, otherwise create your own...
A:
In addition to @blacha answer, here are some links and guidance. Once you use Cloud Domain to register a domain, there is an option where you can use which DNS provider that you use for your domain. These are Cloud DNS, Google Domains and Custom Name servers.
If by chance you get confused which DNS server that you are using I suggest to DIG your domain to see which name server that you are using just to make sure you are using the correct DNS server.
Since this concern choses Cloud DNS here is the link that you can follow on how to create zone, configure A record connecting to the domains IP address and creating Cname record for the subdomain that you desire.
|
Google Cloud DNS records do not propagate to any server
|
Hej!
I own a domain registered through GCP and it's connected with Cloud DNS in GCP, I would be very happy if you could help me setup my custom domain for my web page at buahaha.github.io.
I think I know how to do this, because I did it before with other domain(s), but this time something is not working as it should. I have set up even a TXT record, and it does not propagate through DNS servers, and the same goes for my CNAME record. I attach screenshots of my setup below.
It's strange to me as it is the basic setup for this kind of service, and I'm really confused...
Pozdrawiam,
Szymon
|
[
"The problem was that I had to explicitly choose Cloud DNS as my DNS provider. If you have set your DNS zone already, just choose it from the drop-down menu, otherwise create your own...\n\n",
"In addition to @blacha answer, here are some links and guidance. Once you use Cloud Domain to register a domain, there is an option where you can use which DNS provider that you use for your domain. These are Cloud DNS, Google Domains and Custom Name servers.\nIf by chance you get confused which DNS server that you are using I suggest to DIG your domain to see which name server that you are using just to make sure you are using the correct DNS server.\nSince this concern choses Cloud DNS here is the link that you can follow on how to create zone, configure A record connecting to the domains IP address and creating Cname record for the subdomain that you desire.\n"
] |
[
0,
0
] |
[] |
[] |
[
"google_cloud_dns",
"google_cloud_platform"
] |
stackoverflow_0074646644_google_cloud_dns_google_cloud_platform.txt
|
Q:
M1 Mac: java.lang.ExceptionInInitializerError at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820)
I am trying to run an automation test by launching the Chrome browser using the chrome driver.
Setup:
Chip: Apple M1 Pro
OS: macOS Monterey
JDK: jdk-18.0.1.1.jdk
Maven: Apache Maven 3.8.5
IntelliJ IDEA 2022.1.1 (Community Edition)Build #IC-221.5591.52
When I run my code, I get the following errors:
Could you please suggest a solution? No idea something wrong with the setup, version, Pom or chromedriver path:
java.lang.ExceptionInInitializerError at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:574) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:530) at cucumber.runtime.xstream.LocalizedXStreams$LocalizedXStream.(LocalizedXStreams.java:50) at cucumber.runtime.xstream.LocalizedXStreams.newXStream(LocalizedXStreams.java:37) at cucumber.runtime.xstream.LocalizedXStreams.get(LocalizedXStreams.java:29) at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37) at cucumber.runtime.Runtime.runStep(Runtime.java:300) at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44) at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39) at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44) at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165) at cucumber.runtime.Runtime.run(Runtime.java:122) at cucumber.api.cli.Main.run(Main.java:36) at cucumber.api.cli.Main.main(Main.java:18) at ?.Given I launch a browser(/Users/ravithapa/IdeaProjects/letstry/src/test/resources/Features/Homepagelogo_Login.feature:5) Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Comparator java.util.TreeMap.comparator accessible: module java.base does not "opens java.util" to unnamed module @179d3b25 at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354) at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:180) at java.base/java.lang.reflect.Field.setAccessible(Field.java:174) at cucumber.deps.com.thoughtworks.xstream.core.util.Fields.locate(Fields.java:39) at cucumber.deps.com.thoughtworks.xstream.converters.collections.TreeMapConverter.(TreeMapConverter.java:50) at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:574) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:530) at cucumber.runtime.xstream.LocalizedXStreams$LocalizedXStream.(LocalizedXStreams.java:50) at cucumber.runtime.xstream.LocalizedXStreams.newXStream(LocalizedXStreams.java:37) at cucumber.runtime.xstream.LocalizedXStreams.get(LocalizedXStreams.java:29) at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37) at cucumber.runtime.Runtime.runStep(Runtime.java:300) at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44) at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39) at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44) at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165) at cucumber.runtime.Runtime.run(Runtime.java:122) at cucumber.api.cli.Main.run(Main.java:36) at cucumber.api.cli.Main.main(Main.java:18)
Pom file:
4.0.0
<groupId>org.example</groupId>
<artifactId>letstry</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>net.masterthought</groupId>
<artifactId>maven-cucumber-reporting</artifactId>
<version>2.8.0</version>
<executions>
<execution>
<id>execution</id>
<phase>test</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<projectName>e2e</projectName>
<outputDirectory>${project.build.directory}/cucumber-report-html</outputDirectory>
<cucumberOutput>${project.build.directory}/cucumber.json</cucumberOutput>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-htmlunit-driver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.48.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
</properties>
code:
public WebDriver driver;
@Given("^I launch a browser$")
public void i_launch_a_browser() throws Throwable {
public class Homepagelogo_Login {
public WebDriver driver;
@Given("^I launch a browser$")
public void i_launch_a_browser() throws Throwable {
System.setProperty("webdriver.chrome.driver", "/Users/me/Desktop/test/webdriver");
driver = new ChromeDriver();
}
A:
Add following to the VM options in the Run configuration of your IDE:
--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED
Reference from here: https://github.com/Riduidel/aadarchi/issues/90#issuecomment-1291640544
The above link also has sample code to use in pom.xml if you are running a mvn test instead.
|
M1 Mac: java.lang.ExceptionInInitializerError at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820)
|
I am trying to run an automation test by launching the Chrome browser using the chrome driver.
Setup:
Chip: Apple M1 Pro
OS: macOS Monterey
JDK: jdk-18.0.1.1.jdk
Maven: Apache Maven 3.8.5
IntelliJ IDEA 2022.1.1 (Community Edition)Build #IC-221.5591.52
When I run my code, I get the following errors:
Could you please suggest a solution? No idea something wrong with the setup, version, Pom or chromedriver path:
java.lang.ExceptionInInitializerError at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:574) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:530) at cucumber.runtime.xstream.LocalizedXStreams$LocalizedXStream.(LocalizedXStreams.java:50) at cucumber.runtime.xstream.LocalizedXStreams.newXStream(LocalizedXStreams.java:37) at cucumber.runtime.xstream.LocalizedXStreams.get(LocalizedXStreams.java:29) at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37) at cucumber.runtime.Runtime.runStep(Runtime.java:300) at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44) at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39) at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44) at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165) at cucumber.runtime.Runtime.run(Runtime.java:122) at cucumber.api.cli.Main.run(Main.java:36) at cucumber.api.cli.Main.main(Main.java:18) at ?.Given I launch a browser(/Users/ravithapa/IdeaProjects/letstry/src/test/resources/Features/Homepagelogo_Login.feature:5) Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Comparator java.util.TreeMap.comparator accessible: module java.base does not "opens java.util" to unnamed module @179d3b25 at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354) at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:180) at java.base/java.lang.reflect.Field.setAccessible(Field.java:174) at cucumber.deps.com.thoughtworks.xstream.core.util.Fields.locate(Fields.java:39) at cucumber.deps.com.thoughtworks.xstream.converters.collections.TreeMapConverter.(TreeMapConverter.java:50) at cucumber.deps.com.thoughtworks.xstream.XStream.setupConverters(XStream.java:820) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:574) at cucumber.deps.com.thoughtworks.xstream.XStream.(XStream.java:530) at cucumber.runtime.xstream.LocalizedXStreams$LocalizedXStream.(LocalizedXStreams.java:50) at cucumber.runtime.xstream.LocalizedXStreams.newXStream(LocalizedXStreams.java:37) at cucumber.runtime.xstream.LocalizedXStreams.get(LocalizedXStreams.java:29) at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37) at cucumber.runtime.Runtime.runStep(Runtime.java:300) at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44) at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39) at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44) at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165) at cucumber.runtime.Runtime.run(Runtime.java:122) at cucumber.api.cli.Main.run(Main.java:36) at cucumber.api.cli.Main.main(Main.java:18)
Pom file:
4.0.0
<groupId>org.example</groupId>
<artifactId>letstry</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>net.masterthought</groupId>
<artifactId>maven-cucumber-reporting</artifactId>
<version>2.8.0</version>
<executions>
<execution>
<id>execution</id>
<phase>test</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<projectName>e2e</projectName>
<outputDirectory>${project.build.directory}/cucumber-report-html</outputDirectory>
<cucumberOutput>${project.build.directory}/cucumber.json</cucumberOutput>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-htmlunit-driver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.48.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
</properties>
code:
public WebDriver driver;
@Given("^I launch a browser$")
public void i_launch_a_browser() throws Throwable {
public class Homepagelogo_Login {
public WebDriver driver;
@Given("^I launch a browser$")
public void i_launch_a_browser() throws Throwable {
System.setProperty("webdriver.chrome.driver", "/Users/me/Desktop/test/webdriver");
driver = new ChromeDriver();
}
|
[
"Add following to the VM options in the Run configuration of your IDE:\n--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED\n\nReference from here: https://github.com/Riduidel/aadarchi/issues/90#issuecomment-1291640544\nThe above link also has sample code to use in pom.xml if you are running a mvn test instead.\n"
] |
[
0
] |
[] |
[] |
[
"apple_m1",
"cucumber",
"cucumber_java",
"intellij_idea",
"selenium"
] |
stackoverflow_0072367715_apple_m1_cucumber_cucumber_java_intellij_idea_selenium.txt
|
Q:
python + psycopg2.errors.SyntaxError: syntax error at end of input
I'm getting this error message
cursor.execute(query, variables)
psycopg2.errors.SyntaxError: syntax error at end of input
My code
data = {
'country': data['country'][x],
'year': data['year'][x].astype(float),
'month': data['month'][x].astype(float)
}
db_connection.execute(
f"""
INSERT INTO my_table (country, year, month) VALUES (%(country)s, %(year)s, %(month)s) ON CONFLICT (country, year, month)
""",
data,
)
A:
You're missing a conflict_action in your sql statement. See https://www.postgresql.org/docs/current/sql-insert.html#:~:text=ON%20CONFLICT%20DO%20NOTHING%20simply,can%20perform%20unique%20index%20inference. for details.
EG You might want ON CONFLICT (country, year, month) DO NOTHING
|
python + psycopg2.errors.SyntaxError: syntax error at end of input
|
I'm getting this error message
cursor.execute(query, variables)
psycopg2.errors.SyntaxError: syntax error at end of input
My code
data = {
'country': data['country'][x],
'year': data['year'][x].astype(float),
'month': data['month'][x].astype(float)
}
db_connection.execute(
f"""
INSERT INTO my_table (country, year, month) VALUES (%(country)s, %(year)s, %(month)s) ON CONFLICT (country, year, month)
""",
data,
)
|
[
"You're missing a conflict_action in your sql statement. See https://www.postgresql.org/docs/current/sql-insert.html#:~:text=ON%20CONFLICT%20DO%20NOTHING%20simply,can%20perform%20unique%20index%20inference. for details.\nEG You might want ON CONFLICT (country, year, month) DO NOTHING\n"
] |
[
2
] |
[] |
[] |
[
"postgresql",
"python"
] |
stackoverflow_0074662600_postgresql_python.txt
|
Q:
how to convert Json field & relational fields into multiple rows?
I have a SQL table with a "regular fields" Fields & another field (extra_field) that holds a json value which holds different elements that belongs to unique combination of date, account_id, metric_name, value.
There is no closed list of keys and values. Both keys and values are dynamic
i want to convert the json field to rows as follows:
how should i do it?
A:
You can use the json_extract function in your SQL query to extract the keys and values from the extra_field column, which contains the JSON data. For example, the following query extracts the keys and values from the extra_field column and converts them into multiple rows:
SELECT
json_extract(extra_field, '$.date') AS date,
json_extract(extra_field, '$.account_id') AS account_id,
json_extract(extra_field, '$.metric_name') AS metric_name,
json_extract(extra_field, '$.value') AS value
FROM your_table;
This will produce a result set with one row for each key-value pair in the extra_field column.
---- Edit as per comment received ---
"but in each record i get different json with different # of properties and i need a general solution for all cases"
In that case, you can use the JSON_KEYS function in MySQL to extract the keys from the extra_field column, and then use those keys to extract the corresponding values using the JSON_EXTRACT function.
Here's an example query that shows how this could work:
SELECT
date,
JSON_KEYS(extra_field) AS keys,
JSON_EXTRACT(extra_field, CONCAT('$.', JSON_KEYS(extra_field))) AS values
FROM mytable;
This query will return a table with three columns: date, keys, and values. The keys column will contain a JSON array of all the keys in the extra_field column for each row, and the values column will contain a JSON array of the corresponding values for each key.
You can then use the JSON_UNQUOTE function to convert the JSON arrays in the keys and values columns to strings, which will make it easier to work with the data. Here's an example:
SELECT
date,
JSON_UNQUOTE(JSON_KEYS(extra_field)) AS keys,
JSON_UNQUOTE(JSON_EXTRACT(extra_field, CONCAT('$.', JSON_KEYS(extra_field)))) AS values
FROM mytable;
This will return a table with the same three columns as before, but the keys and values columns will now contain strings instead of JSON arrays.
I hope this helps! Let me know if you have any other questions.
|
how to convert Json field & relational fields into multiple rows?
|
I have a SQL table with a "regular fields" Fields & another field (extra_field) that holds a json value which holds different elements that belongs to unique combination of date, account_id, metric_name, value.
There is no closed list of keys and values. Both keys and values are dynamic
i want to convert the json field to rows as follows:
how should i do it?
|
[
"You can use the json_extract function in your SQL query to extract the keys and values from the extra_field column, which contains the JSON data. For example, the following query extracts the keys and values from the extra_field column and converts them into multiple rows:\nSELECT\n json_extract(extra_field, '$.date') AS date,\n json_extract(extra_field, '$.account_id') AS account_id,\n json_extract(extra_field, '$.metric_name') AS metric_name,\n json_extract(extra_field, '$.value') AS value\nFROM your_table;\n\nThis will produce a result set with one row for each key-value pair in the extra_field column.\n---- Edit as per comment received ---\n\"but in each record i get different json with different # of properties and i need a general solution for all cases\"\nIn that case, you can use the JSON_KEYS function in MySQL to extract the keys from the extra_field column, and then use those keys to extract the corresponding values using the JSON_EXTRACT function.\nHere's an example query that shows how this could work:\nSELECT\n date,\n JSON_KEYS(extra_field) AS keys,\n JSON_EXTRACT(extra_field, CONCAT('$.', JSON_KEYS(extra_field))) AS values\nFROM mytable;\n\nThis query will return a table with three columns: date, keys, and values. The keys column will contain a JSON array of all the keys in the extra_field column for each row, and the values column will contain a JSON array of the corresponding values for each key.\nYou can then use the JSON_UNQUOTE function to convert the JSON arrays in the keys and values columns to strings, which will make it easier to work with the data. Here's an example:\nSELECT\n date,\n JSON_UNQUOTE(JSON_KEYS(extra_field)) AS keys,\n JSON_UNQUOTE(JSON_EXTRACT(extra_field, CONCAT('$.', JSON_KEYS(extra_field)))) AS values\nFROM mytable;\n\nThis will return a table with the same three columns as before, but the keys and values columns will now contain strings instead of JSON arrays.\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
0
] |
[] |
[] |
[
"database",
"json",
"sql"
] |
stackoverflow_0074662510_database_json_sql.txt
|
Q:
SPFx web part similar to the Quick Links web part which check if the user have permission on the related links (internal and external links)
I am working on a project to build a portal inside SharePoint online. Now i got this requirement:-
To build a quick links web part in React SPFx (similar to the built-in modern Quick Links)
But this quick links can contain links to internal applications that can only be accessed using VPN.
So if the user access the SharePoint online home page without VPN >> the quick links should hide all the links which the user does not have access to.
Also if the user access the SharePoint using VPN and the user does not have permission to the internal system (the user will get http 401 or will be prompted with a dialog to enter username and password) to hide the links as well.
So in other words, the SPFx web part need to send a request to the link url, and if it get http code other than "2xx success" to hide the link.
Can anyone advice how to build such a web part please?
Now i tried to benefit from this SPFx web part @ https://github.com/clarktozer/spfx-quicklinks . where this is the QuickLinksWebPart.ts:-
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneDropdown,
PropertyPaneCheckbox} from '@microsoft/sp-webpart-base';
import * as strings from 'QuickLinksWebPartStrings';
import QuickLinks from './components/QuickLinks';
import { IQuickLinksProps } from './components/IQuickLinksProps';
import { PropertyPaneLinksList } from '../../controls/PropertyPaneLinksList/PropertyPaneLinksList';
import { PropertyFieldColorPicker, PropertyFieldColorPickerStyle } from '@pnp/spfx-property-controls/lib/PropertyFieldColorPicker';
import { Link } from '../../controls/PropertyPaneLinksList/components/ILinksListState';
export interface IQuickLinksWebPartProps {
title: string;
type: LinkType;
iconColor: string;
openInNewTab?: boolean;
fontColor: string;
initLinks: string[];
links: Link[];
}
export enum LinkType {
LINK = "Link",
FILE = "File"
}
export default class QuickLinksWebPart extends BaseClientSideWebPart<IQuickLinksWebPartProps> {
public render(): void {
const element: React.ReactElement<IQuickLinksProps> = React.createElement(
QuickLinks,
{
title: this.properties.title,
type: this.properties.type,
iconColor: this.properties.iconColor,
fontColor: this.properties.fontColor,
openInNewTab: this.properties.openInNewTab,
links: this.properties.links != null ? this.properties.links : [],
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
}
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneDropdown('type', {
label: strings.LinkType,
options: Object.keys(LinkType).map((e) => {
return {
key: LinkType[e], text: LinkType[e]
};
}),
selectedKey: 'link'
}),
PropertyPaneCheckbox('openInNewTab', {
text: strings.OpenInNewTab
})
]
},
{
groupName: strings.StylingGroup,
groupFields: [
PropertyFieldColorPicker('iconColor', {
label: strings.IconColor,
selectedColor: this.properties.iconColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'iconColor'
}),
PropertyFieldColorPicker('fontColor', {
label: strings.FontColor,
selectedColor: this.properties.fontColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'fontColor'
})
]
},
{
groupName: strings.LinksGroup,
groupFields: [
new PropertyPaneLinksList("links", {
key: "links",
links: this.properties.links
})
]
}
]
}
]
};
}
}
and this is the QuikcLinks.tsx :-
import * as React from 'react';
import styles from './QuickLinks.module.scss';
import { IQuickLinksProps } from './IQuickLinksProps';
import { autobind } from '@uifabric/utilities';
import { LinkType } from '../QuickLinksWebPart';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import Radium from 'radium';
import * as tinycolor from 'tinycolor2';
@Radium
export default class QuickLinks extends React.Component<IQuickLinksProps, {}> {
private inlineStyles: any;
constructor(props: IQuickLinksProps) {
super(props);
}
@autobind
private createLinkStyle(hoverColor) {
return {
color: this.props.fontColor,
':hover': {
color: tinycolor(hoverColor).darken(25).toString()
}
};
}
@autobind
public getIcon() {
let icon = "";
switch (this.props.type) {
case LinkType.FILE:
icon = "OpenFile";
break;
default:
icon = "Link";
}
return icon;
}
public render(): React.ReactElement<IQuickLinksProps> {
this.inlineStyles = {
link: this.createLinkStyle(this.props.fontColor)
};
return (
<div className={"ms-Grid " + styles.quickLinks}>
<div>
<div className="ms-Grid-row">
<div className="ms-Grid-col ms-sm12">
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty} />
{
this.props.links.map((e, i) => {
let linkProps = {
key: e.key,
href: e.value
};
if (this.props.openInNewTab) {
linkProps["target"] = "_blank";
}
return <div className={styles.linkRow} key={this.props.type + "-link-" + i}>
<i style={{ color: this.props.iconColor }} className={styles.quickLinkIcon + " ms-Icon ms-Icon--" + this.getIcon()} aria-hidden="true"></i>
<a className={styles.link} {...linkProps} style={this.inlineStyles.link}>{e.label}</a>
</div>;
})
}
</div>
</div>
</div>
</div>
);
}
}
So where i need to do the call to the URL and check the response so i can render the link or hide it accordingly??
Thanks
A:
To hide links that the user does not have access to, you can add a check in the web part's render method to determine whether to show or hide each link. You can use the fetch API to send a request to each link's URL, and check the response code to determine whether to show or hide the link. If the response code is anything other than a 2xx success code, you can hide the link.
Here is an example of how you might implement this:
import * as React from 'react';
import * as ReactDom from 'react-dom';
// Other imports here...
export default class QuickLinksWebPart extends BaseClientSideWebPart<IQuickLinksWebPartProps> {
public render(): void {
const links = this.properties.links.map(async (link: Link) => {
// Send a request to the link's URL
const response = await fetch(link.url);
// Check the response code
if (response.ok) {
// If the response code is a 2xx success code, return the link
return link;
} else {
// If the response code is not a 2xx success code, return null
return null;
}
});
const element: React.ReactElement<IQuickLinksProps> = React.createElement(
QuickLinks,
{
title: this.properties.title,
type: this.properties.type,
iconColor: this.properties.iconColor,
fontColor: this.properties.fontColor,
openInNewTab: this.properties.openInNewTab,
links: links, // Set the links to the updated list of links
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
}
}
);
ReactDom.render(element, this.domElement);
}
// Other methods here...
}
In the above example, the render method first sends a request to each link's URL and checks the response code. If the response code is a 2xx success code, the link is added to the list of links to be displayed. If the response code is not a 2xx success code, the link is not added to the list. The updated list of links is then passed to the QuickLinks component.
A:
You can do this in the componentDidMount() hook in the QuickLinks.tsx file. You can call the URL and check the response and set the state of the component accordingly. This will render the component based on the response you get.
|
SPFx web part similar to the Quick Links web part which check if the user have permission on the related links (internal and external links)
|
I am working on a project to build a portal inside SharePoint online. Now i got this requirement:-
To build a quick links web part in React SPFx (similar to the built-in modern Quick Links)
But this quick links can contain links to internal applications that can only be accessed using VPN.
So if the user access the SharePoint online home page without VPN >> the quick links should hide all the links which the user does not have access to.
Also if the user access the SharePoint using VPN and the user does not have permission to the internal system (the user will get http 401 or will be prompted with a dialog to enter username and password) to hide the links as well.
So in other words, the SPFx web part need to send a request to the link url, and if it get http code other than "2xx success" to hide the link.
Can anyone advice how to build such a web part please?
Now i tried to benefit from this SPFx web part @ https://github.com/clarktozer/spfx-quicklinks . where this is the QuickLinksWebPart.ts:-
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneDropdown,
PropertyPaneCheckbox} from '@microsoft/sp-webpart-base';
import * as strings from 'QuickLinksWebPartStrings';
import QuickLinks from './components/QuickLinks';
import { IQuickLinksProps } from './components/IQuickLinksProps';
import { PropertyPaneLinksList } from '../../controls/PropertyPaneLinksList/PropertyPaneLinksList';
import { PropertyFieldColorPicker, PropertyFieldColorPickerStyle } from '@pnp/spfx-property-controls/lib/PropertyFieldColorPicker';
import { Link } from '../../controls/PropertyPaneLinksList/components/ILinksListState';
export interface IQuickLinksWebPartProps {
title: string;
type: LinkType;
iconColor: string;
openInNewTab?: boolean;
fontColor: string;
initLinks: string[];
links: Link[];
}
export enum LinkType {
LINK = "Link",
FILE = "File"
}
export default class QuickLinksWebPart extends BaseClientSideWebPart<IQuickLinksWebPartProps> {
public render(): void {
const element: React.ReactElement<IQuickLinksProps> = React.createElement(
QuickLinks,
{
title: this.properties.title,
type: this.properties.type,
iconColor: this.properties.iconColor,
fontColor: this.properties.fontColor,
openInNewTab: this.properties.openInNewTab,
links: this.properties.links != null ? this.properties.links : [],
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
}
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneDropdown('type', {
label: strings.LinkType,
options: Object.keys(LinkType).map((e) => {
return {
key: LinkType[e], text: LinkType[e]
};
}),
selectedKey: 'link'
}),
PropertyPaneCheckbox('openInNewTab', {
text: strings.OpenInNewTab
})
]
},
{
groupName: strings.StylingGroup,
groupFields: [
PropertyFieldColorPicker('iconColor', {
label: strings.IconColor,
selectedColor: this.properties.iconColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'iconColor'
}),
PropertyFieldColorPicker('fontColor', {
label: strings.FontColor,
selectedColor: this.properties.fontColor,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Inline,
key: 'fontColor'
})
]
},
{
groupName: strings.LinksGroup,
groupFields: [
new PropertyPaneLinksList("links", {
key: "links",
links: this.properties.links
})
]
}
]
}
]
};
}
}
and this is the QuikcLinks.tsx :-
import * as React from 'react';
import styles from './QuickLinks.module.scss';
import { IQuickLinksProps } from './IQuickLinksProps';
import { autobind } from '@uifabric/utilities';
import { LinkType } from '../QuickLinksWebPart';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import Radium from 'radium';
import * as tinycolor from 'tinycolor2';
@Radium
export default class QuickLinks extends React.Component<IQuickLinksProps, {}> {
private inlineStyles: any;
constructor(props: IQuickLinksProps) {
super(props);
}
@autobind
private createLinkStyle(hoverColor) {
return {
color: this.props.fontColor,
':hover': {
color: tinycolor(hoverColor).darken(25).toString()
}
};
}
@autobind
public getIcon() {
let icon = "";
switch (this.props.type) {
case LinkType.FILE:
icon = "OpenFile";
break;
default:
icon = "Link";
}
return icon;
}
public render(): React.ReactElement<IQuickLinksProps> {
this.inlineStyles = {
link: this.createLinkStyle(this.props.fontColor)
};
return (
<div className={"ms-Grid " + styles.quickLinks}>
<div>
<div className="ms-Grid-row">
<div className="ms-Grid-col ms-sm12">
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty} />
{
this.props.links.map((e, i) => {
let linkProps = {
key: e.key,
href: e.value
};
if (this.props.openInNewTab) {
linkProps["target"] = "_blank";
}
return <div className={styles.linkRow} key={this.props.type + "-link-" + i}>
<i style={{ color: this.props.iconColor }} className={styles.quickLinkIcon + " ms-Icon ms-Icon--" + this.getIcon()} aria-hidden="true"></i>
<a className={styles.link} {...linkProps} style={this.inlineStyles.link}>{e.label}</a>
</div>;
})
}
</div>
</div>
</div>
</div>
);
}
}
So where i need to do the call to the URL and check the response so i can render the link or hide it accordingly??
Thanks
|
[
"To hide links that the user does not have access to, you can add a check in the web part's render method to determine whether to show or hide each link. You can use the fetch API to send a request to each link's URL, and check the response code to determine whether to show or hide the link. If the response code is anything other than a 2xx success code, you can hide the link.\nHere is an example of how you might implement this:\nimport * as React from 'react';\nimport * as ReactDom from 'react-dom';\n\n// Other imports here...\n\nexport default class QuickLinksWebPart extends BaseClientSideWebPart<IQuickLinksWebPartProps> {\n\n public render(): void {\n const links = this.properties.links.map(async (link: Link) => {\n // Send a request to the link's URL\n const response = await fetch(link.url);\n // Check the response code\n if (response.ok) {\n // If the response code is a 2xx success code, return the link\n return link;\n } else {\n // If the response code is not a 2xx success code, return null\n return null;\n }\n });\n\n const element: React.ReactElement<IQuickLinksProps> = React.createElement(\n QuickLinks,\n {\n title: this.properties.title,\n type: this.properties.type,\n iconColor: this.properties.iconColor,\n fontColor: this.properties.fontColor,\n openInNewTab: this.properties.openInNewTab,\n links: links, // Set the links to the updated list of links\n displayMode: this.displayMode,\n updateProperty: (value: string) => {\n this.properties.title = value;\n }\n }\n );\n\n ReactDom.render(element, this.domElement);\n }\n\n // Other methods here...\n\n}\n\nIn the above example, the render method first sends a request to each link's URL and checks the response code. If the response code is a 2xx success code, the link is added to the list of links to be displayed. If the response code is not a 2xx success code, the link is not added to the list. The updated list of links is then passed to the QuickLinks component.\n",
"You can do this in the componentDidMount() hook in the QuickLinks.tsx file. You can call the URL and check the response and set the state of the component accordingly. This will render the component based on the response you get.\n"
] |
[
0,
0
] |
[] |
[] |
[
"reactjs",
"sharepoint",
"spfx"
] |
stackoverflow_0074549568_reactjs_sharepoint_spfx.txt
|
Q:
How do I add images to a PyPI readme (that works on GitHub)?
In my readme on GitHub I have several images that are present there in my project's source tree which I reference successfully with directives like
.. image:: ./doc/source/_static/figs/moon_probe.png
I would also like to have these images appear when this same readme is generated in PyPi.
How do I (a) ensure that images are present on PyPi for the readme to access and (b) formulate the .. image:: directive to access them?
A:
PyPI will not read your package distributions for the image. You have to use the image's external link, for example:
.. image:: https://raw.githubusercontent.com/greyli/flask-share/master/images/demo.png
If you are using Markdown description, use this:

Be sure to replace the URL in the above examples with your image URL, here I use the image hosted by GitHub, the real demo is on PyPI.
P.S. To get the image's raw link on GitHub, right-click the image and choose Copy image address.
A:
Go to the image address in the Github repository. The path shown will be like this:
https://github.com/tensorbored/kds/blob/master/docs/_static/readme_lift.png
Change the blob term in the image address to raw
https://github.com/tensorbored/kds/raw/master/docs/_static/readme_lift.png
A:
If you have your images on Github, navigate to the image then right click on download button and copy link address:
Then you can add it in your README.md file:

It should be rendered properly both on Github and PyPi.
A:
Setting ?raw=True at the end of GitHub image link seems to work.
example:

I had found this somewhere on the internet previously, but couldn't find it now. I'll credit the original author when I find it again.
A:
The long_description_content_type should be text/x-rst if you use restructured text syntax (README.rst). Assuming that is what you are using based on ".. image::". If you save the image on GitHub and use that external link for the image then it works (typically something like raw.githubusercontent.com.... as described in one of the above answers).
It does work as shown in this pypi package:
https://pypi.org/project/gammath-spot/
|
How do I add images to a PyPI readme (that works on GitHub)?
|
In my readme on GitHub I have several images that are present there in my project's source tree which I reference successfully with directives like
.. image:: ./doc/source/_static/figs/moon_probe.png
I would also like to have these images appear when this same readme is generated in PyPi.
How do I (a) ensure that images are present on PyPi for the readme to access and (b) formulate the .. image:: directive to access them?
|
[
"PyPI will not read your package distributions for the image. You have to use the image's external link, for example:\n.. image:: https://raw.githubusercontent.com/greyli/flask-share/master/images/demo.png\n\nIf you are using Markdown description, use this:\n\n\nBe sure to replace the URL in the above examples with your image URL, here I use the image hosted by GitHub, the real demo is on PyPI.\nP.S. To get the image's raw link on GitHub, right-click the image and choose Copy image address.\n",
"Go to the image address in the Github repository. The path shown will be like this:\nhttps://github.com/tensorbored/kds/blob/master/docs/_static/readme_lift.png\n\nChange the blob term in the image address to raw\nhttps://github.com/tensorbored/kds/raw/master/docs/_static/readme_lift.png\n\n",
"If you have your images on Github, navigate to the image then right click on download button and copy link address:\n\nThen you can add it in your README.md file:\n\n\nIt should be rendered properly both on Github and PyPi.\n",
"Setting ?raw=True at the end of GitHub image link seems to work.\nexample:\n\n\nI had found this somewhere on the internet previously, but couldn't find it now. I'll credit the original author when I find it again.\n",
"The long_description_content_type should be text/x-rst if you use restructured text syntax (README.rst). Assuming that is what you are using based on \".. image::\". If you save the image on GitHub and use that external link for the image then it works (typically something like raw.githubusercontent.com.... as described in one of the above answers).\nIt does work as shown in this pypi package:\nhttps://pypi.org/project/gammath-spot/\n"
] |
[
34,
8,
3,
3,
0
] |
[] |
[] |
[
"github",
"pypi",
"python",
"readme",
"restructuredtext"
] |
stackoverflow_0041983209_github_pypi_python_readme_restructuredtext.txt
|
Q:
How can I tell Jest not to suppress console output on failure?
It seems that some combination of --silent=false or maybe --verbose=false is needed to get console.log output from Jest. But none of these options seems to help (in Jest 29.3) when my test fails (i.e., throws an error):
test('console output', () => {
console.log('this never prints')
throw new Error('but why?!?') // or 'expect(true).toBe(false)'
})
Why, oh why, Jest, do you do this? A failing test is exactly when I need console (i.e. debugging) output the most.
How can I see console.log output regardless of whether something in the test throws an error?
A:
// Jest configuration file (jest.config.js)
module.exports = {
errorOnDeprecated: true,
verbose: true,
forceExit: false,
};
The errorOnDeprecated option, when set to true, will cause Jest to throw an error whenever a deprecated feature is used. This will prevent Jest from suppressing the console output of the deprecated feature, and will allow you to see the full output of the test run.
Note: I am not too fond of Jest, and therefore cannot be responsible if anything on your system acts different than mine.
A:
By default, Jest suppresses the output of console.log statements when a test fails. This is to prevent the test output from being cluttered with extraneous information that may not be relevant to the failure.
To override this behavior and show the output of console.log statements when a test fails, you can use the --verbose or --silent command-line options when running Jest.
The --verbose option will show the output of all console.log statements, regardless of whether the test passes or fails. The --silent option will suppress all output from console.log statements, including when the test passes.
To use these options, you can run Jest with the --verbose or --silent flag, like this:
jest --verbose
jest --silent
For example, to see the output of console.log statements when a test fails, you could run Jest with the --verbose flag, like this:
jest --verbose test.js
Or, if you want to suppress all console.log output, you could run Jest with the --silent flag, like this:
jest --silent test.js
I hope this helps!
|
How can I tell Jest not to suppress console output on failure?
|
It seems that some combination of --silent=false or maybe --verbose=false is needed to get console.log output from Jest. But none of these options seems to help (in Jest 29.3) when my test fails (i.e., throws an error):
test('console output', () => {
console.log('this never prints')
throw new Error('but why?!?') // or 'expect(true).toBe(false)'
})
Why, oh why, Jest, do you do this? A failing test is exactly when I need console (i.e. debugging) output the most.
How can I see console.log output regardless of whether something in the test throws an error?
|
[
"// Jest configuration file (jest.config.js)\nmodule.exports = {\nerrorOnDeprecated: true,\nverbose: true,\nforceExit: false,\n};\n\nThe errorOnDeprecated option, when set to true, will cause Jest to throw an error whenever a deprecated feature is used. This will prevent Jest from suppressing the console output of the deprecated feature, and will allow you to see the full output of the test run.\nNote: I am not too fond of Jest, and therefore cannot be responsible if anything on your system acts different than mine.\n",
"By default, Jest suppresses the output of console.log statements when a test fails. This is to prevent the test output from being cluttered with extraneous information that may not be relevant to the failure.\nTo override this behavior and show the output of console.log statements when a test fails, you can use the --verbose or --silent command-line options when running Jest.\nThe --verbose option will show the output of all console.log statements, regardless of whether the test passes or fails. The --silent option will suppress all output from console.log statements, including when the test passes.\nTo use these options, you can run Jest with the --verbose or --silent flag, like this:\njest --verbose\n\njest --silent\n\nFor example, to see the output of console.log statements when a test fails, you could run Jest with the --verbose flag, like this:\njest --verbose test.js\n\nOr, if you want to suppress all console.log output, you could run Jest with the --silent flag, like this:\njest --silent test.js\n\nI hope this helps!\n"
] |
[
0,
0
] |
[] |
[] |
[
"javascript",
"jestjs",
"ts_jest"
] |
stackoverflow_0073750907_javascript_jestjs_ts_jest.txt
|
Q:
What does set(str.begin(), str.end()) mean?
I was going through this question on leetcode: https://leetcode.com/problems/determine-if-two-strings-are-close/solutions/935916/c-o-nlogn-sort-hash-table-easy-to-understand/
class Solution {
public:
bool closeStrings(string word1, string word2) {
if(word1.size()!=word2.size())
return false;
int n = word1.size();
vector<int>freq1(26,0);
vector<int>freq2(26,0);
for(int i= 0 ; i < n ; ++i){
freq1[word1[i]-'a']++;
freq2[word2[i]-'a']++;
}
sort(freq1.rbegin(),freq1.rend());
sort(freq2.rbegin(),freq2.rend());
**if(set(word1.begin(),word1.end())!=set(word2.begin(),word2.end()))**
return false;
for(int i= 0;i<26;++i){
if(freq1[i]!=freq2[i])
return false;
}
return true;
}
};
I am not understanding what does set(word1.begin(),word1.end()) mean over here, I tried to search on the internet for answer but I didn't got any satisfying answer, if someone can explain it would be very helpful. Thanks in advance!
A:
Strings can be thought of as containers for char. Thus it's possible to define iterators for them (that visit them in-order, char-by-char). word1.begin() and word1.end() are simply the iterators to the first character and to the end of string.
Other containers can usually be initialized using iterator pairs (begin, end), thus set(word1.begin(),word1.end()) means a std::set<char> of the characters of the string. Set in C++ means ordered collection of unique elements; their comparison returns true iff all elements are the same. Thus, in the if statement, you compare if both strings contain the same characters (but maybe multiple times and in different order).
A:
It creates a set of the characters in word1, which is just the unique characters and in a way that could be compared to another word without the number of occurrences or order mattering.
So, comparing sets made this way, "cat" and "taca" would have == sets. "cat" and "taco" would not. "cat" and "kat" would not, but "dog" and "good" would.
So, this code is saying that if the words do not share all of the same letters, then they would not be considered close.
A:
word1.begin() is the iterator that points to the first character in the string word1. word1.end() is the iterator that points to the position after the last character in the string word1. Together, they define the range of elements in the string word1 that will be added to a std::setobject.
set(word1.begin(),word1.end()) creates a temporary std::set object that contains all the characters in the string word1.
std::set is a container that stores unique elements in a specific order. In this case, the std::set object will have all of the unique characters in the string word1 in a specific order.
That std::set object is then compared to another temporary std::set object being created from the string word2, to see if the two sets of characters are equal. If they are not equal, it means that the two strings do not have the same set of unique characters and the function will return false.
|
What does set(str.begin(), str.end()) mean?
|
I was going through this question on leetcode: https://leetcode.com/problems/determine-if-two-strings-are-close/solutions/935916/c-o-nlogn-sort-hash-table-easy-to-understand/
class Solution {
public:
bool closeStrings(string word1, string word2) {
if(word1.size()!=word2.size())
return false;
int n = word1.size();
vector<int>freq1(26,0);
vector<int>freq2(26,0);
for(int i= 0 ; i < n ; ++i){
freq1[word1[i]-'a']++;
freq2[word2[i]-'a']++;
}
sort(freq1.rbegin(),freq1.rend());
sort(freq2.rbegin(),freq2.rend());
**if(set(word1.begin(),word1.end())!=set(word2.begin(),word2.end()))**
return false;
for(int i= 0;i<26;++i){
if(freq1[i]!=freq2[i])
return false;
}
return true;
}
};
I am not understanding what does set(word1.begin(),word1.end()) mean over here, I tried to search on the internet for answer but I didn't got any satisfying answer, if someone can explain it would be very helpful. Thanks in advance!
|
[
"Strings can be thought of as containers for char. Thus it's possible to define iterators for them (that visit them in-order, char-by-char). word1.begin() and word1.end() are simply the iterators to the first character and to the end of string.\nOther containers can usually be initialized using iterator pairs (begin, end), thus set(word1.begin(),word1.end()) means a std::set<char> of the characters of the string. Set in C++ means ordered collection of unique elements; their comparison returns true iff all elements are the same. Thus, in the if statement, you compare if both strings contain the same characters (but maybe multiple times and in different order).\n",
"It creates a set of the characters in word1, which is just the unique characters and in a way that could be compared to another word without the number of occurrences or order mattering.\nSo, comparing sets made this way, \"cat\" and \"taca\" would have == sets. \"cat\" and \"taco\" would not. \"cat\" and \"kat\" would not, but \"dog\" and \"good\" would.\nSo, this code is saying that if the words do not share all of the same letters, then they would not be considered close.\n",
"word1.begin() is the iterator that points to the first character in the string word1. word1.end() is the iterator that points to the position after the last character in the string word1. Together, they define the range of elements in the string word1 that will be added to a std::setobject.\nset(word1.begin(),word1.end()) creates a temporary std::set object that contains all the characters in the string word1.\nstd::set is a container that stores unique elements in a specific order. In this case, the std::set object will have all of the unique characters in the string word1 in a specific order.\nThat std::set object is then compared to another temporary std::set object being created from the string word2, to see if the two sets of characters are equal. If they are not equal, it means that the two strings do not have the same set of unique characters and the function will return false.\n"
] |
[
1,
1,
1
] |
[] |
[] |
[
"c++"
] |
stackoverflow_0074662545_c++.txt
|
Q:
How do I update an existing database in BigQuery with a Google Sheet?
I want to be able to upload new records into a BigQuery table from Google Sheets. I know how to attach them through Connected Sheets, and have the table mirror the Sheet, however I don't want it to mirror the sheet exactly, I want to be able to upload the sheet into the BigQuery table, and then clear the sheet without it deleting the table. Is there a way to do that through Connected Sheets, or do I need a script to do that.
Thanks.
Everything I find on the topic only shows how to make a table from scratch in BigQuery, and have it mirroring a Google Sheet. This doesn't fit my application because my sheet will get too big if I keep all the records around , too quickly. I want to be able upload the records on a sheet into a database, then clear the sheet without it affecting the database.
A:
If you want to keep everything in BigQuery, and you want to work with exactly one Sheet, I think a saved query using the BigQuery DML (data manipulation language) would be the way to go.
Let's imagine that you have a Google Sheet that you've added to BigQuery as an external table called my_gsheet in a dataset called external. For the sake of argument let's say it has three columns, id, name, and created_at.
We are going to use an insert select statement to append this to a table called all_records in a dataset called big_data, like this:
INSERT
big_data.all_records
(id, name, created_at)
SELECT
id, name, created_at
FROM
external.my_gsheet
Now you can save this query and run it whenever you want to bring the latest spreadsheet-based data into your warehouse table.
The table big_data.all_records should be created by you in advance; if it's going to be very large you should probably think about making it a partitioned table, and if it's going to be queried a lot you may want to cluster certain columns too.
You could even schedule the query to be run regularly, although beware: if you run the query above multiple times, duplicate rows will be created. If you have a unique identifier (e.g. the id column for my record), this can be avoided with a MERGE:
MERGE INTO
big_data.all_records AS target
USING
external.my_gsheet AS sheet
ON
target.id = sheet.id
WHEN
NOT MATCHED
THEN
INSERT (id, name, created_at)
VALUES(id, name, created_at)
This query, unlike the previous one, will only insert rows if they have an id that doesn't already exist in the table. If the id does exist, it will do nothing (you could add a WHEN MATCHED THEN UPDATE clause if you want the ability to overwrite instead).
|
How do I update an existing database in BigQuery with a Google Sheet?
|
I want to be able to upload new records into a BigQuery table from Google Sheets. I know how to attach them through Connected Sheets, and have the table mirror the Sheet, however I don't want it to mirror the sheet exactly, I want to be able to upload the sheet into the BigQuery table, and then clear the sheet without it deleting the table. Is there a way to do that through Connected Sheets, or do I need a script to do that.
Thanks.
Everything I find on the topic only shows how to make a table from scratch in BigQuery, and have it mirroring a Google Sheet. This doesn't fit my application because my sheet will get too big if I keep all the records around , too quickly. I want to be able upload the records on a sheet into a database, then clear the sheet without it affecting the database.
|
[
"If you want to keep everything in BigQuery, and you want to work with exactly one Sheet, I think a saved query using the BigQuery DML (data manipulation language) would be the way to go.\nLet's imagine that you have a Google Sheet that you've added to BigQuery as an external table called my_gsheet in a dataset called external. For the sake of argument let's say it has three columns, id, name, and created_at.\nWe are going to use an insert select statement to append this to a table called all_records in a dataset called big_data, like this:\n INSERT\n big_data.all_records\n (id, name, created_at)\n SELECT\n id, name, created_at\n FROM\n external.my_gsheet\n\nNow you can save this query and run it whenever you want to bring the latest spreadsheet-based data into your warehouse table.\nThe table big_data.all_records should be created by you in advance; if it's going to be very large you should probably think about making it a partitioned table, and if it's going to be queried a lot you may want to cluster certain columns too.\nYou could even schedule the query to be run regularly, although beware: if you run the query above multiple times, duplicate rows will be created. If you have a unique identifier (e.g. the id column for my record), this can be avoided with a MERGE:\n MERGE INTO\n big_data.all_records AS target\n USING\n external.my_gsheet AS sheet\n ON\n target.id = sheet.id\n WHEN\n NOT MATCHED\n THEN\n INSERT (id, name, created_at)\n VALUES(id, name, created_at)\n\nThis query, unlike the previous one, will only insert rows if they have an id that doesn't already exist in the table. If the id does exist, it will do nothing (you could add a WHEN MATCHED THEN UPDATE clause if you want the ability to overwrite instead).\n"
] |
[
0
] |
[] |
[] |
[
"google_apps_script",
"google_bigquery",
"google_sheets"
] |
stackoverflow_0074659345_google_apps_script_google_bigquery_google_sheets.txt
|
Q:
Why this simple for loop in batch doesn't work?
for /d %%d in (*) do (
set direc=%%d
if /i not "%%d"=="data" (
set subject=!direc!
REM INTRO INFORMATIONS
echo:
echo *****
echo Working With Subject: !subject!;
echo *****
echo:
echo ---- Running Step 1 ----
echo:
matlab -nodisplay -nosplash -nodesktop -r "addpath(genpath('%add1%'));addpath('%add2%');step1('%parentfolder%\!subject!\!subject!');exit;"
rem Wait matlab to finish process
:waitmatlab1
echo Waiting for Matlab to finish process...
timeout /t 10 /nobreak
rem /I not case sensitive
tasklist | find /I "matlab.exe"
if %ERRORLEVEL% NEQ 1 (goto :waitmatlab1)
echo:
echo *****
echo Subject !subject! Finished.
echo *****
echo:
)
)
My main directory has 3 folders but the following loop only run for the first (that has file inside for matlab) and command window pauses with "Subject 1 Finished" printed. I main to only jump to the next folder after executing the matlab task.
A:
for /d %%d in (*) do (
set direc=%%d
if /i not "%%d"=="data" (
set subject=!direc!
REM INTRO INFORMATIONS
echo:
echo *****
echo Working With Subject: !subject!;
echo *****
echo:
echo ---- Running Step 1 ----
echo:
matlab -nodisplay -nosplash -nodesktop -r "addpath(genpath('%add1%'));addpath('%add2%');step1('%parentfolder%\!subject!\!subject!');exit;"
rem Wait matlab to finish process
CALL :waitmatlab1
echo:
echo *****
echo Subject !subject! Finished.
echo *****
echo:
)
)
GOTO :EOF
:waitmatlab1
echo Waiting for Matlab to finish process...
timeout /t 10 /nobreak
rem /I not case sensitive
tasklist | find /I "matlab.exe"
if %ERRORLEVEL% NEQ 1 (goto waitmatlab1)
goto :eof
Should fix your problem.
Notes:
No labels are allowed within code blocks.
This includes ::-style comments which are "broken" (unreachable) labels
Any %var% within a loop will be replaced by the value of that variable when the loop is encountered %errorlevel% included. Use !errorlevel! if delayed expansion is invoked, or the if errorlevel n syntax.
So - CALL the internal subroutine which executes a normal loop (and since it is no longer in a code block (parenthesised sequence of lines) then %errorlevel% will act as expected.
Note that : is not required in a goto - with the sole exception of Goto :eof where :eof is defined as being end-of-file.
|
Why this simple for loop in batch doesn't work?
|
for /d %%d in (*) do (
set direc=%%d
if /i not "%%d"=="data" (
set subject=!direc!
REM INTRO INFORMATIONS
echo:
echo *****
echo Working With Subject: !subject!;
echo *****
echo:
echo ---- Running Step 1 ----
echo:
matlab -nodisplay -nosplash -nodesktop -r "addpath(genpath('%add1%'));addpath('%add2%');step1('%parentfolder%\!subject!\!subject!');exit;"
rem Wait matlab to finish process
:waitmatlab1
echo Waiting for Matlab to finish process...
timeout /t 10 /nobreak
rem /I not case sensitive
tasklist | find /I "matlab.exe"
if %ERRORLEVEL% NEQ 1 (goto :waitmatlab1)
echo:
echo *****
echo Subject !subject! Finished.
echo *****
echo:
)
)
My main directory has 3 folders but the following loop only run for the first (that has file inside for matlab) and command window pauses with "Subject 1 Finished" printed. I main to only jump to the next folder after executing the matlab task.
|
[
"for /d %%d in (*) do (\n set direc=%%d\n if /i not \"%%d\"==\"data\" (\n set subject=!direc!\n REM INTRO INFORMATIONS\n echo:\n echo *****\n echo Working With Subject: !subject!; \n echo *****\n echo:\n\n echo ---- Running Step 1 ----\n echo:\n matlab -nodisplay -nosplash -nodesktop -r \"addpath(genpath('%add1%'));addpath('%add2%');step1('%parentfolder%\\!subject!\\!subject!');exit;\"\n rem Wait matlab to finish process\n CALL :waitmatlab1\n echo:\n echo *****\n echo Subject !subject! Finished.\n echo *****\n echo:\n )\n)\nGOTO :EOF\n\n:waitmatlab1\necho Waiting for Matlab to finish process...\ntimeout /t 10 /nobreak\nrem /I not case sensitive\ntasklist | find /I \"matlab.exe\"\nif %ERRORLEVEL% NEQ 1 (goto waitmatlab1)\ngoto :eof\n\nShould fix your problem.\nNotes: \nNo labels are allowed within code blocks.\n\nThis includes ::-style comments which are \"broken\" (unreachable) labels\n\nAny %var% within a loop will be replaced by the value of that variable when the loop is encountered %errorlevel% included. Use !errorlevel! if delayed expansion is invoked, or the if errorlevel n syntax.\nSo - CALL the internal subroutine which executes a normal loop (and since it is no longer in a code block (parenthesised sequence of lines) then %errorlevel% will act as expected.\nNote that : is not required in a goto - with the sole exception of Goto :eof where :eof is defined as being end-of-file.\n"
] |
[
0
] |
[] |
[] |
[
"batch_file",
"cmd",
"for_loop",
"windows"
] |
stackoverflow_0074661954_batch_file_cmd_for_loop_windows.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.