text string | meta dict |
|---|---|
Q: Download issues when trying to use My.Computer.Network.DownloadFile in VB.NET I have a lot of issues with My.Computer.Network.DownloadFile command. I want my application to download a file from internet. First, I tried to upload the file to dropbox and I copied the link. My application should download that file, but it gave an error like this: The request was aborted: Could not create SSL/TLS secure channel. How do I bypass this error? After this, I tried to copy a link from an antivirus website and coded my program to download that file. It worked. Why this command works on a random link but not in dropbox files?
Also, I tried to upload that file to Google Drive. It didn't give me any error; the file was downloaded but it was 0 KB! It just downloaded a blank file. I tried another online file upload web site, but my application gave me an error like this: The request was aborted: Could not create SSL/TLS secure channel. How do I fix these issues? I am using Microsoft Visual Studio 2010 Professional.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: New to C programming, need guidance I have an assignment where I must calculate the load on a cantilever beam at 1 ft increments until it reaches 2% of the beam length. My calculations work, and the first portion of the for loop seems to do what it is designed to do. I just can't figure out how to increment the distance to the load from the fixed point end of the cantilever beam. I tried to use a while loop, and then a couple of if statements. I just don't understand enough at this point to make it work.
Here is the text of the assignment:
"Write a C program to read the information for each beam from the beam.txt data file (one point at a time) and print a report, both to the screen and to an output file (deflection.txt) that places the applied load at 1-foot intervals starting at one foot from the fixed end (i.e., at 1 foot) and moving down the length of the beam. Once this is working, modify the program so that the deflections for each beam are printed only as long as they are less than 2% of the beam length. When the beam deflection is greater than or equal to 2%, the program should stop computing values for that beam and go on to the next. If the deflection distance of 2% is never reached, the program should print an appropriate message."
Here is what the output should look like:
BEAM DEFLECTION
BEAM NO. X Total length = xx.xx ft
2% of length = xx.xx ft
DISTANCE FROM FIXED END DEFLECTION
1.00 xxx.xx
2.00 xxx.xx
. .
. .
. .
BEAM NO. X Total length = xx.xx ft
2% of length = xx.xx ft
DISTANCE FROM FIXED END DEFLECTION
1.00 xxx.xx
2.00 xxx.xx
. .
. .
. .
Deflection of 2% of length not reached
My output either has nothing below each beam section, or the incrementation is off, like under beam 1 it is 1.00 2.00, under beam 2 it is 2.00 3.00, and so on.
This is my unsuccessful code:
/* Preprocessor directives */
#include <stdio.h>
#include <math.h>
#define infile "C:\\Users\\tommc\\OneDrive\\Documents\\ENGR 200\\beam.txt"
#define outfile "C:\\Users\\tommc\\OneDrive\\Documents\\ENGR 200\\deflection.txt"
/* Main function */
int main(void)
{
/* Declare variables */
double load, load_len=1, elast, inert, beam_len, beam_base, deflection, perc_len;
int i, ndata;
FILE *beam=NULL, *deflect=NULL;
/* open files */
beam=fopen(infile, "r");
deflect=fopen(outfile, "w");
/* Print headings */
printf("********************************************");
printf("\n BEAM DEFLECTION");
fprintf(deflect,"********************************************");
fprintf(deflect,"\n BEAM DEFLECTION");
/* Verify input file */
if(beam==NULL)
{
printf("\n\n\n\n ERROR OPENING INPUT FILE.");
printf("\n\n PROGRAM TERMINATED.\n\n\n");
return 1;
}
/* Read control number */
fscanf(beam, "%i", &ndata);
/* Compute beam deflection and print results */
for(i=1; i<=ndata; i++)
{
/* read in data */
fscanf(beam, "%lf %lf %lf %lf", &beam_len, &beam_base, &elast, &load);
inert=(beam_base*pow(beam_len,3.0))/12.0;
deflection=(load*pow(load_len,2.0))/(2.0*elast*inert)*(beam_len-(load_len/3.0));
perc_len=(0.02*beam_len);
printf("\nBEAM NO %d Total length = %5.2lf ft", i, beam_len);
printf("\n 2%% of length = %5.2lf ft", perc_len);
printf("\n DISTANCE FROM FIXED END DEFLECTION ");
printf("\n %4.2lf %6.2lf", load_len, deflection);
fprintf(deflect, "\nBEAM NO %d Total length = %5.2lf ft", i, beam_len);
fprintf(deflect, "\n 2%% of length = %5.2lf ft", beam_len*0.02);
fprintf(deflect, "\n DISTANCE FROM FIXED END DEFLECTION ");
load_len++;
if(deflection < perc_len)
{
printf("\n %4.2lf %6.2lf", load_len, deflection);
}
if(deflection>=perc_len)
{
printf("\nDeflection of 2%% of length not reached");
}
}
printf("\n********************************************\n\n\n");
fprintf(deflect,"\n********************************************\n\n\n");
/* Close the files */
fclose(beam);
fclose(deflect);
/* Exit the program */
return 0;
}
/******************************************************************************/
A:
DISTANCE FROM FIXED END DEFLECTION 1.00 xxx.xx 2.00 xxx.xx . . . . . . Deflection of 2% of length not reached
Your problem is that you need to have a nested loop over load_len for each beam, and you are not doing that.
Your code should look like this:
for (beam_no = 0; beam_no < ndata; beam_no++) { /* 1 */
/* read the data for this beam */
for (load_len = 0; load_len < beam_len; load_len++) {
/* print deflections here */
}
}
1 Note that in C you should always start your loops from 0 and continue until < ndata -- that's idiomatic. Having loops which start at 1 and continue until <= ndata will bite you sooner or later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get angles for clock hands I know that I can use getHours() and getMinutes() and getSecond() in JavaScript and show the exact time of my computer, but how should I sync that with the shape of the clock?
const activeb = document.querySelector(".run")
const mysec = document.querySelector(".second")
const mymin = document.querySelector(".min")
const myhour = document.querySelector(".hour")
function first() {
mysec.style.transformOrigin = "0% 100%"
mysec.style.transform += "rotate(6deg)"
}
function second() {
mymin.style.transformOrigin = "0% 100%"
mymin.style.transform += "rotate(6deg)"
}
function third() {
myhour.style.transformOrigin = "0% 100%"
myhour.style.transform += "rotate(6deg)"
}
<div>
<div class="shapeofclock">
<span class="nom12">12</span>
<span class="nom1">1</span>
<span class="nom2">2</span>
<span class="nom3">3</span>
<span class="nom4">4</span>
<span class="nom5">5</span>
<span class="nom6">6</span>
<span class="nom7">11</span>
<span class="nom8">10</span>
<span class="nom9">9</span>
<span class="nom10">8</span>
<span class="nom11">7</span>
<span class="second"></span>
<span class="min"></span>
<span class="hour"></span>
<span class="circle"></span>
</div>
<div class="textofclock"></div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alignment Of Cells ar not the same I have this code in FormLoad event -
DataGridView1.Columns("Note").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
I want this column only with alignment MiddleLeft....
As you can see, only the first row is OK. What should I do ?
A: *
*Make sure the DataGridView.RowTemplate.DefaultCellStyle.Alignment property is set to the default value NotSet. The same for the DataGridView.RowsDefaultCellStyle.Alignment property.
*Set the DataGridView.DefaultCellStyle.Alignment property to MiddleCenter value to have the cell contents aligned at the middle center except,
*By code or grid designer, set the Note column .DefaultCellStyle.Alignment property to MiddleLeft.
In other words, in the Form's ctor or Load event and before populating the grid:
DataGridView1.RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.NotSet
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.NotSet
DataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
DataGridView1.Columns("Note").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Further Reading
Cell Styles in the Windows Forms DataGridView Control
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove endarrow on mxgraph? I want to remove andarrow on edge and join the line
I want to remove endarrow on edge on mxgraph.
How can I do as below?
orijinal is here
I want to like this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: PHPickerViewController: hide "Select items" section Is it possible to hide "Select items" section at the bottom? It looks like it's useless in most of user scenarios.
Any tricks like method swizzling?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to create a solid background color? How to create this kind of background color?
website portfolio from Brittany Chiang
website portfolio from Jonathan
User-friendly, solid and professional? When I choose any color for my background, looks like old sites like at the beginning of the 2000s.
A:
I just ran this through imagecolorpicker.com and you can get all the colours you need from the site.
A: You should learn some color theory to find good colors. Color theory may also help in finding a palette based on the context it will be used in.
There exist several online tools to generate color palettes mathematically. Canva's color wheel page explains some combinations along with some other interesting aspects about color composition, characteristics and more.
Instead of finding or generating your own, you may want to look for precomposed color palettes.
You may also want to learn about how colors and brand identity correlate.
However, creating a solid background color is a simple matter of using a single color. No gradients, no patterns, just a single solid color:
From vocabulary.com:
solid-colored
adjective, having the same color all over
synonyms:
plain, unpatterned
lacking patterns especially in color
To use a solid background on an element, use the background-color property:
#example {background-color: crimson}
/*Set size to make background visible*/
#example {
width: 200px;
height: 200px;
}
<div id="example"></div>
As you can see, I used a keyword for a named color. Multiple named colors exist in CSS, and any other color value needs to be specified in another way, e.g. functional notation like rgb() or hsl().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to post/save models without including navigation properties I am trying to post a model to an API controller action to save a new "PotluckItem", which has a parent of "Potluck" and a child of "Item". The relevant portions of the relevant entity models are below:
public class Potluck
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<PotluckItem> PotluckItems { get; set; }
}
public class PotluckItem
{
[Key]
public int Id { get; set; }
public int ItemId { get; set; }
public int PotluckId { get; set; }
public int? GuestId { get; set; }
[ForeignKey("ItemId")]
public virtual Item Item { get; set; }
[ForeignKey("PotluckId")]
public virtual Potluck Potluck { get; set; }
[ForeignKey("GuestId")]
public virtual Guest? Guest { get; set; }
}
public class Item
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
When I post a model I create on the front end, I'm getting errors that the "Item" and "Potluck" fields are required. Here is the model I'm posting
{
"Id": 0,
"PotluckId": 3,
"ItemId": 5,
}
Here is the controller action I am posting to:
[HttpPost("items/new")]
public IActionResult NewItem([FromBody] PotluckItem item)
{
return Ok();
}
And the error message I'm getting without hitting the breakpoint in the controller.
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-c972d27ce1fc352982df872f82d264a6-6f4f462c229e7bbf-00",
"errors": {
"Item": [
"The Item field is required."
],
"Potluck": [
"The Potluck field is required."
]
}
}
My question is what is the best practice for handling situations like this? Would it be best to create separate models specifically for posting/updating that do not have the navigation properties? Or am I configuring the entity models incorrectly?
In theory I'd want to do something like adding the new PotluckItem to the context and saving changes. Would it be better to get the full parent entity and add the item to the collection and then save the whole thing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: pandas exception keeps throwing errors when using googletrans for translating text using data frame I am doing a googletrans excercise for scraping website and need to translate english language courses title to be in Hindi. Somehow my pandas library keeps throwing an exception and dont know how fix this issue been long week trying to find best possible solutions still no luck.Yet the worse part i am using python 3 version on my OS and what could be the reason for this infrastructure...? On my pycharm IDE i selected virtualenvironment even anaconda still results are still the same. Could be a corrupted packages...? How do resolve such problem...?
Traceback (most recent call last): File "C:\Users\Zux\PycharmProjects\ClassCentral\main.py", line 35, in <module> df['Title (hin)'] = df['Title (eng)'].apply(lambda x: translator.translate(x, dest='hi').text) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Zux\PycharmProjects\ClassCentral\ClassCentral\Lib\site-packages\pandas\core\series.py", line 4771, in apply return SeriesApply(self, func, convert_dtype, args, kwargs).apply() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Zux\PycharmProjects\ClassCentral\ClassCentral\Lib\site-packages\pandas\core\apply.py", line 1123, in apply
`from googletrans import Translator
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import pandas as pd
import urllib.request as urllib2
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument("window-size=1920,1080")
driver = webdriver.Chrome(options=chrome_options)
url = "https://www.classcentral.com/collection/top-free-online-courses"
driver.get(url)
translator = Translator()
try:
while True:
# wait until button is clickable
WebDriverWait(driver, 1).until(
expected_conditions.element_to_be_clickable((By.XPATH, "//button[@data-name='LOAD_MORE']"))
).click()
time.sleep(0.5)
except Exception as e:
pass
all_courses = driver.find_element(by=By.CLASS_NAME, value='catalog-grid__results')
courses = all_courses.find_elements(by=By.CSS_SELECTOR, value='[class="color-charcoal course-name"]')
df = pd.DataFrame([[course.text, course.get_attribute('href')] for course in courses],
columns=['Title (eng)', 'Link'])
df['Title (hin)'] = df['Title (eng)'].apply(lambda x: translator.translate(x, dest='hi').text)
print(df)
`
`from googletrans import Translator
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import pandas as pd
import urllib.request as urllib2
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument("window-size=1920,1080")
driver = webdriver.Chrome(options=chrome_options)
url = "https://www.classcentral.com/collection/top-free-online-courses"
driver.get(url)
translator = Translator()
try:
while True:
# wait until button is clickable
WebDriverWait(driver, 1).until(
expected_conditions.element_to_be_clickable((By.XPATH, "//button[@data-name='LOAD_MORE']"))
).click()
time.sleep(0.5)
except Exception as e:
pass
all_courses = driver.find_element(by=By.CLASS_NAME, value='catalog-grid__results')
courses = all_courses.find_elements(by=By.CSS_SELECTOR, value='[class="color-charcoal course-name"]')
df = pd.DataFrame([[course.text, course.get_attribute('href')] for course in courses],
columns=['Title (eng)', 'Link'])
df['Title (hin)'] = df['Title (eng)'].apply(lambda x: translator.translate(x, dest='hi').text)
print(df)
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: passing object to Route in react i try to pass object in rount in react
i have this code which rount to new componenet , i like to pass the all user details to this
componenet .
//this is the route , how can i pass the "elm" object to TodoComponent
<Route path="/todo/:id" element={
<AuthenticatedRoute>
<TodoComponent/>
</AuthenticatedRoute>
function updateTodo(id) {
navigate(`/todo/${id}`)
}
<tbody>
{
todos.map(elm =>(
<tr key={elm.id}>
<td>{elm.id}</td>
<td>{elm.describtion}</td>
<td>{elm.done.toString()}</td>
<td>{elm.targetDate.toString()}</td>
<td><button className="btn btn-warning" onClick={()=>deleteTodo(elm.id)}>Delete</button></td>
<td><button className="btn btn-success" onClick={()=>updateTodo(elm.id)}>Update</button></td>
</tr>
))
}
</tbody>
This is the TodoComponent how can i catch the "elm" object from the component above
function TodoComponent() {
return (
<div className="continer">
<h1>Enter Todo Details</h1>
<div>
</div>
</div>
)
}
export default TodoComponent;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Building a parser in Racket I am new to Racket and I am trying to parse a grammar using the Beautiful Racket library. I have defined the grammar in a separate file and it seems to be completely fine. My tokenization is also working, I've printed the output to confirm everything is getting tokenized. I'm creating a parser that uses the 'parse-to-datum' procedure in Beautiful Racket. However, I am encountering an error with my parser. As the parser encounters an ID such as 'A', it produces an error message:
Encountered unexpected token of type 'ID (value "A") while parsing 'unknown [line=1, column=#f, offset=9]
Here is my input:
10 read A
20 read B
30 gosub 400
40 if C = 400 then write C
50 if C = 0 then goto 1000
400 C = A + B : return
$$
Here is my Grammar defined in Racket:
#lang brag
program : linelist DOLLAR DOLLAR
linelist : line linelist | "epsilon"
line : idx stmt linetail* EOL
idx : digit | nonzero_digit digit*
linetail : COLON stmt | "epsilon"
stmt : id ASSIGN-OP expr DELIMIT
| IF expr THEN stmt
| READ id DELIMIT
| WRITE expr DELIMIT
| GOTO idx
| GOSUB idx
| RETURN
expr : id etail | num etail | LPAREN expr RPAREN
etail : ADD-OP expr | SUB-OP expr | EQ-OP expr | "epsilon"
id : LETTER+
num : numsign digit digit*
numsign : ADD-OP | SUB-OP | "epsilon"
nonzero_digit : DIGIT - "0"
digit : "0" | nonzero_digit
Here is my parsing function:
#lang br
(require "grammar.rkt" "tokenizer.rkt" brag/support)
(define (parse file-name)
(define file-content (port->string (open-input-file file-name) #:close? #t))
(with-handlers ([exn:fail? (lambda (exn)
(displayln (exn-message exn)))])
(let ((tokens (apply-tokenizer-maker make-tokenizer file-content)))
(for-each (lambda (token)
(displayln token))
tokens)
(parse-to-datum tokens)
(displayln "Accept"))))
(parse "file03.txt")
I've tried adjusting the way I define an ID in my grammar, but that did not help as I believe it is a parser issue. It parses the "10" and "read" just fine in the first line, but cannot parse A. I want it to parse A accordingly to the grammar rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Memory Leak After Upgrading Ads Library For Android I have upgraded the ads library to the following today:
implementation 'com.google.android.gms:play-services-ads:21.5.0'
I'm using banners and Interstitial Ads.
Now, I'm getting the following memory leak as detected by Leak Canary.
I'm destroying the activity along with all related ads objects, such as setting them to null, listeners to null, setFullScreenContentCallback(null), etc.
┬───
│ GC Root: Input or output parameters in native code
│
├─ android.os.MessageQueue instance
│ Leaking: NO (MessageQueue#mQuitting is false)
│ HandlerThread: "ExoPlayerImplInternal:Handler"
│ ↓ MessageQueue[0]
│ ~~~
├─ android.os.Message instance
│ Leaking: UNKNOWN
│ Retaining 2.5 MB in 605 objects
│ Message.what = 2
│ Message.when = 507477121 (661 ms after heap dump)
│ Message.obj = null
│ Message.callback = null
│ Message.target = instance @348531240 of android.os.Handler
│ ↓ Message.target
│ ~~~~~~
├─ android.os.Handler instance
│ Leaking: UNKNOWN
│ Retaining 2.5 MB in 604 objects
│ ↓ Handler.mCallback
│ ~~~~~~~~~
├─ com.google.android.gms.internal.ads.zzatb instance
│ Leaking: UNKNOWN
│ Retaining 2.5 MB in 603 objects
│ ↓ zzatb.zzm
│ ~~~
├─ com.google.android.gms.internal.ads.zzaup instance
│ Leaking: UNKNOWN
│ Retaining 22.1 kB in 81 objects
│ ↓ zzaup.zzb
│ ~~~
├─ com.google.android.gms.internal.ads.zzatz instance
│ Leaking: UNKNOWN
│ Retaining 16 B in 1 objects
│ ↓ zzatz.zzb
│ ~~~
├─ com.google.android.gms.internal.ads.zzclf instance
│ Leaking: UNKNOWN
│ Retaining 346 B in 10 objects
│ zzd instance of com.google.android.gms.internal.ads.zzcpc, wrapping
│ androidx.multidex.MultiDexApplication
│ ↓ zzclf.zzd
│ ~~~
├─ com.google.android.gms.internal.ads.zzcpc instance
│ Leaking: UNKNOWN
│ Retaining 24 B in 1 objects
│ zza instance of com.xxxxx.xxxxx.CreateCardsActivity with
│ mDestroyed = true
│ zzb instance of androidx.multidex.MultiDexApplication
│ zzc instance of com.xxxxx.xxxxx.CreateCardsActivity with
│ mDestroyed = true
│ mBase instance of androidx.multidex.MultiDexApplication
│ zzcpc wraps an Application context
│ ↓ zzcpc.zza
│ ~~~
╰→ com.xxxx.xxxxxx.CreateCardsActivity instance
Leaking: YES (ObjectWatcher was watching this because
xxxx.xxxxx.CreateCardsActivity received Activity#onDestroy() callback and
Activity#mDestroyed is true)
Retaining 8.4 kB in 204 objects
key = 433e4c0b-dd8e-4321-a496-8a5a5542d28e
watchDurationMillis = 428997
retainedDurationMillis = 423991
mApplication instance of androidx.multidex.MultiDexApplication
mBase instance of androidx.appcompat.view.ContextThemeWrapper
METADATA
Build.VERSION.SDK_INT: 28
Build.MANUFACTURER: BLU
LeakCanary version: 2.10
App process name: com.xxx.xxxx
Class count: 20438
Instance count: 386631
Primitive array count: 252937
Object array count: 46275
Thread count: 148
Heap total bytes: 39734117
Bitmap count: 52
Bitmap total bytes: 29096284
Large bitmap count: 0
Large bitmap total bytes: 0
Db 1: open /com.google.android.
datatransport.events
Db 2: closed google_app_measurement_local.db
Db 3: open androidx.work.workdb
Stats: LruCache[maxSize=3000,hits=182820,misses=342787,hitRate=34%]
RandomAccess[bytes=16217423,reads=342787,travel=94405937828,range=40656354,size=
56429010]
Analysis duration: 149315 ms
Any ideas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: passing format string to scanf as an command line argument vs hardcoding it I have following code:
#include <stdio.h>
int main()
{
int i;
char c;
char *format_string = "%d\n";
scanf(format_string, &i);
printf("read: %d\n", i);
printf("Let's check what is in the input buffer:\n");
while (scanf("%c", &c) == 1)
{
printf("read from input buf: %d\n", c);
}
}
If I run the code following way:
echo "5" | ./specific.out
The output is following:
read: 5
Let's check what is in the input buffer:
Here I have more general version of above code, where I pass format string from command line:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
exit(EXIT_SUCCESS);
}
int i;
char c;
char *format_string = argv[1];
scanf(format_string, &i);
printf("read: %d\n", i);
printf("Let's check what is in the input buffer:\n");
while (scanf("%c", &c) == 1)
{
printf("read from input buf: %d\n", c);
}
}
If I run the code following way:
echo "5" | ./general.out '%d\n'
The output is following:
read: 5
Let's check what is in the input buffer:
read from input buf: 10
Why do I get different outputs?
A: When you specify '%d\n' on the command line, you're not sending a % followed by d followed by a newline. You sending % followed by d followed by \ followed by n.
Because of this, the newline generated by the echo command doesn't match anything in the format string (specifically a newline doesn't match \), so it gets left in the input buffer.
To get the same result, your command line would have to look like this:
echo "5" | ./x1 '%d
'
On a side note, it's a bad idea for a format string to be under the control of a user, as that can lead to a format string vulnerability. Format strings are best left as string literals.
As an added bonus, if you use a string literal as a format string then your compile will also be able to generate warnings if the format string doesn't match the parameters passed to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Custom JsonConverter attribute for single field not working for .NET 6.0 I had the following converter to serialize the date with a custom format and it was working for .NET Core 3.1:
public class CustomDateConverter : IsoDateTimeConverter {
public CustomDateConverter() {
base.DateTimeFormat = "dd.MM.yyyy";
}
}
public class Test {
[JsonConverter(typeof(CustomDateConverter))]
public DateTime? CustomFormattedDate { get; set; }
}
However, after I migrated to .NET 6.0 the converter no longer gets called. The only way I found was to add the converter to the global list of converters at configuration time, but then it will be used for every DateTime field in my project, which is not what I want. Btw, my configuration looks like this:
builder.Services.AddControllersWithViews()
.AddNewtonsoftJson(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
// options.SerializerSettings.Converters.Add(new CustomDateConverter());
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clarification on the ephemeral port range in NNG At https://nng.nanomsg.org/man/tip/nng_sockaddr_zt.5.html, the explanation of the sa_port argument reads:
This field holds the port number used by the zt transport to distinguish different sockets. This value in native byte order. A zero value here indicates that a port number should be chosen randomly from the ephemeral ports. Only the lower 24 bits of the port number are used.
What exactly are the specific lower and upper bounds for the port range, both here and all other places NNG/nanomsg chooses an ephemeral port? I have heard ephemeral ports defined different ways depending on who I ask. Apparently RFC 6056 says 1024 and above, other times it's about 36000 and above, and this Wikipedia page says 49152 and above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to connect to same instance of chromium using Playwright Dotnet from different processes I use Playwright DotNet in order to enable SEO for my SPA react application. I have several websites on the same server and I would like all of them to maintain connection (being attached) to the same browser instance in the machine. In case the instance crashes or closes for whatever reason I would like one of the sites to re-launch the browser, while the others will re-connect to the new browser instance.
I haven't found a way to connect to an existing browser instance yet. I need the websocket endpoint, but how would my application now which one is, when the browser is launched from another application?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to set val auto with same val other input <input id ="game" val="<?php include "is_game"?>
<input id ="name_game" val="">
string is_game = beyonce, rakgnarok, valkryie'
<?php include "is_game"?> its a refresh changes
if id (#game).val = "valkryie" {
id(#name_game).val = "VALK"
}
if id (#game).val = "rakgnarok" {
id(#name_game).val = "RAGNA"
}
if id (#game).val = "beyonce" {
id(#name_game).val = "BYN"
}
Help me to make perfect code from above logic because I can't solve it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: React app with Vite working locally but not after build I'm working on a React-Typescript-Vite project that I want to deploy to Firebase hosting. The app is running fine locally (with npm run dev), but I'm having issues with prod. My app basically has a name of a store as the first url subdirectory then another subdirectory /entry for the homepage. So for example - http://localhost:5173/gucci/entry. The interesting thing is that on prod if I only navigate to https://myprojectname.firebaseapp.com/gucci(the url hosting my app) I do see the background picture, but if I try https://myprojectname.firebaseapp.com/gucci/entry then I get an empty page.
I've tried using the sources and network tabs in chrome dev tools to help me debug, this is what I see in the prod site in the sources tab in the 'entry' document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="./vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<script type="module" crossorigin src="./assets/index-f625c516.js"></script>
<link rel="stylesheet" href="./assets/index-31f53eb0.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
and this what I see in the same document in my local environment:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="/@vite/client"></script>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx?t=1677961443563"></script>
</body>
</html>
So it seems the issue is with the script tags in prod, but I'm not sure how to handle it.
This is my firebase.json
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
and this is my vite.config
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})
I'm using react-router-dom for routing. I'd appreciate anyone's help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to move the first letters in a word forward by a certain amount, Java I'm new to coding, and need some help completing an assignment. It specifies that we need to take strings from a file, and shift the letters forward a certain amount. This is the part I'm struggling with:
If a word has n letters, where n is an odd number, move the first (n+1)/2 letters to the end of the word. For example: ‘kitchen’ becomes ‘henkitc’.
If a word has n letters, where n is an even number, move the first n/2 letters to the end of the word. For example, ‘before’ becomes ‘orebef’.
Input files will look like this:
Before
Kitchen
Outputs like this:
Before OREBEF
Kitchen HENKITC
Apologies if this is a stupid question.
Here's what I have so far:
public static void main(String[] args) throws IOException {
Scanner input;
FileInputStream inputFile = null;
FileOutputStream outputFile = null;
PrintWriter outPrint = null;
inputFile = new FileInputStream("input2.in");
outputFile = new FileOutputStream("results.out.txt");
outPrint = new PrintWriter(outputFile);
input = new Scanner(inputFile);
while (input.hasNext()) {
String lineReader = null;
lineReader = input.nextLine();
if (lineReader.length() % 2 == 0) {
String evenWord = lineReader;
String flippedEvenWord = null;
System.out.print(evenWord);
System.out.print(" ");
System.out.println(evenWord.toUpperCase());
outPrint.print(evenWord);
outPrint.print(" ");
outPrint.println(evenWord.toUpperCase());
}
else if (lineReader.length() % 2 != 0){
String oddWord = lineReader;
System.out.print(oddWord);
outPrint.print(oddWord);
outPrint.print(" ");
System.out.print(" ");
String flippedOddWord = oddWord;
System.out.println(flippedOddWord.toUpperCase());
outPrint.println(oddWord.toUpperCase());
}
else {
break;
}
}
inputFile.close();
outPrint.close();
input.close();
}
}
A: You are on the right track! Here's how you can modify your code to shift the letters forward as specified in the assignment:
public static void main(String[] args) throws IOException {
Scanner input;
FileInputStream inputFile = null;
FileOutputStream outputFile = null;
PrintWriter outPrint = null;
inputFile = new FileInputStream("input2.in");
outputFile = new FileOutputStream("results.out.txt");
outPrint = new PrintWriter(outputFile);
input = new Scanner(inputFile);
while (input.hasNext()) {
String lineReader = null;
lineReader = input.nextLine();
if (lineReader.length() % 2 == 0) {
// even length word
String evenWord = lineReader;
String shiftedWord = evenWord.substring(evenWord.length()/2) + evenWord.substring(0, evenWord.length()/2);
System.out.print(evenWord + " ");
System.out.print(shiftedWord.toUpperCase());
System.out.println();
outPrint.print(evenWord + " ");
outPrint.println(shiftedWord.toUpperCase());
}
else if (lineReader.length() % 2 != 0){
// odd length word
String oddWord = lineReader;
String shiftedWord = oddWord.substring((oddWord.length()+1)/2) + oddWord.substring(0, (oddWord.length()+1)/2);
System.out.print(oddWord + " ");
System.out.println(shiftedWord.toUpperCase());
outPrint.print(oddWord + " ");
outPrint.println(shiftedWord.toUpperCase());
}
}
inputFile.close();
outPrint.close();
input.close();
}
In the code above, for even length words, we split the word at the middle, swap the two halves and concatenate them back together. For odd length words, we add 1 to the length of the word, split it at the middle, swap the two halves and concatenate them back together.
Note that I have also modified the print statements to match the output format specified in the assignment.
A: An alternative way to calculate this (w/out the extra code) is to use the the fact that an int is always a whole number.
So, by adding one and dividing by two will get you the length of the string to move.
(7+1)/2 = 4 stays 4 when stored as an int.
(6+1)/2 = 3.5 becomes 3 when stored as an int.
while (input.hasNext()) {
//Remove the "= null" part. It's redundant
String line = input.nextLine();
int charactersToMove = (line.length() + 1) / 2;
String shiftedWord = line.substring(charactersToMove)
+ line.substring(0, charactersToMove);
System.out.println(line + " " + shiftedWord.toUpperCase());
outPrint.println(evenWord + " " + shiftedWord.toUpperCase());
}
You could also use % to calculate the offset on a single line, too:
int charactersToMove = (line.length()/2) + (line.length() % 2);
or
int charactersToMove = ((line.length() + (line.length() % 2)) / 2);
In this case (line.length() % 2) is always 1 for odd numbers and 0 for even numbers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: fastify connect stylesheet ejs How can I include static files in FASTIFY?
For example, in express I do this:
app.use(express.static(path.join(__dirname, "/static")));
fastify:
fastify.register(require("@fastify/view"), {
engine: {
ejs: require("ejs"),
},
root: path.join(__dirname, "pages"),
});
I don't think that's in fastify. What do you recommend?
Maybe someone has faced this task, there is nothing in the documentation
declare namespace fastifyView {
export interface FastifyViewOptions {
engine: {
ejs?: any;
eta?: any;
nunjucks?: any;
pug?: any;
handlebars?: any;
mustache?: any;
'art-template'?: any;
twig?: any;
liquid?: any;
dot?: any;
};
templates?: string | string[];
includeViewExtension?: boolean;
options?: object;
charset?: string;
maxCache?: number;
production?: boolean;
defaultContext?: object;
layout?: string;
root?: string;
viewExt?: string;
propertyName?: string;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: html anchor tag is downloading pdf file as .html instead of .pdf Hello I'm trying to do a button in my portfolio website where the user can download my resume in pdf format when they click it but for some reason the file is being downloaded in html format instead of pdf.
This is the code that I have
<a href="../assets/resume.pdf" download="firstname_lastname_cv">
<button onclick='window.open("resume.pdf")'> Download CV </button>
</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: in radio form using css input[type="radio"] checked not working I created a mood barometer with a radio form and want to keep only img as a selector. When I hover and press the image I want to keep it bigger when selected. With hover it works but when pressed doesn't keep its size.
I've tried with input[type="radio"]:checked and focus, but it doesn't work.
Any ideas? I cant change the HTML code because its a WordPress plugin (Forminator), I can only change the CSS.
.forminator-radio .forminator-radio-bullet {
position: absolute !important;
opacity: 0 !important;
width: 0 !important;
height: 0 !important;
}
.forminator-radio .forminator-radio-label img.emoji {
height: 40px !important;
width: 40px !important;
padding: 0 5px;
}
.forminator-radio .forminator-radio-label img.emoji:hover,
.forminator-radio-label:focus {
height: 60px !important;
width: 60px !important;
}
<div role="radiogroup" class="forminator-field" aria-labelledby="forminator-poll-68326--title">
<label for="68326-0-answer-1" class="forminator-radio">
<input id="68326-0-answer-1" type="radio" data-required="" name="68326" value="answer-1">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f641.svg">
</span>
</label>
<label for="68326-0-answer-2" class="forminator-radio">
<input id="68326-0-answer-2" type="radio" data-required="" name="68326" value="answer-2">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f610.svg">
</span>
</label>
<label for="68326-0-answer-3" class="forminator-radio">
<input id="68326-0-answer-3" type="radio" data-required="" name="68326" value="answer-3">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f642.svg">
</span>
</label>
</div>
A: To do what you require you can use an additional rule which sets the emoji size when the input is checked:
.forminator-radio input:checked ~ .forminator-radio-label img.emoji
This selector targets any checked radio input, then retrieves the label sibling and finally it's child img.
Here's a working example:
.forminator-radio .forminator-radio-bullet {
position: absolute !important;
opacity: 0 !important;
width: 0 !important;
height: 0 !important;
}
.forminator-radio .forminator-radio-label img.emoji {
height: 40px !important;
width: 40px !important;
padding: 0 5px;
}
.forminator-radio .forminator-radio-label img.emoji:hover,
.forminator-radio input:checked ~ .forminator-radio-label img.emoji,
.forminator-radio-label:focus {
height: 60px !important;
width: 60px !important;
}
<div role="radiogroup" class="forminator-field" aria-labelledby="forminator-poll-68326--title">
<label for="68326-0-answer-1" class="forminator-radio">
<input id="68326-0-answer-1" type="radio" data-required="" name="68326" value="answer-1">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f641.svg">
</span>
</label>
<label for="68326-0-answer-2" class="forminator-radio">
<input id="68326-0-answer-2" type="radio" data-required="" name="68326" value="answer-2">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f610.svg">
</span>
</label>
<label for="68326-0-answer-3" class="forminator-radio">
<input id="68326-0-answer-3" type="radio" data-required="" name="68326" value="answer-3">
<span class="forminator-radio-bullet" aria-hidden="true"></span>
<span class="forminator-radio-label">
<img draggable="false" role="img" class="emoji" alt="" src="https://s.w.org/images/core/emoji/14.0.0/svg/1f642.svg">
</span>
</label>
</div>
One thing to note here is that I would strongly suggest you stop using !important everywhere. Use selector specificity to override, not flags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Graph API - Get count for Mailfolder Sent Items I was able to get the count number of emails from Inbox with this request https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=ReceivedDateTime ge 2017-04-01 and receivedDateTime lt 2017-05-01 & count=true, but i also want to get the same result from the Sent folder but the filter "ReceivedDateTime" only exists for inbox and i couldn't seem to find something of equal for https://graph.microsoft.com/v1.0/me/mailFolders/SentItems/messages?$filter= XXXXX & count=true, is there way to accomplish the same way with Inbox? or i have to apply a workaround for this? Would be gratefull if anyone could help me.
Thank you for your attention.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a tree where each node lists its ancestors instead of its descendants. Will the node with the most ancestors always be the lowest node? I have a problem where I need to confirm that a node is at the lowest level of a tree. Each node in the tree lists its ancestors. Rather than doing a BFS, it seems to me that a shortcut would just be to pick the node with the most ancestors, as that will always be the node at the lowest level. Am I wrong about that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VSCode (Code Helper) JS CPU usage spikes whenever I make any edit in editor (M2 MacBook Air 16GB, VSCode 1.76.0, macOS 13.2.1)
I'm working in a NextJS project in VSCode, and have been experiencing annoying and disruptive issues all of the time, when the JS/TS Language Features extension is enabled.
With this issue, whenever I make an edit in a JS file, Code Helper's CPU usage spikes, to perhaps 70-100% and with it CPU temperatures. Even actions as simple as literally typing a comma cause my temps to rise from their stable 30-35C to over 50C. This subsequently causes battery drain, simply from typing characters, nothing complex, which is very disruptive.
So far I have tried disabling the JS/TS Language Features extension (which stops the CPU spikes, but essentially turns VSCode into a colourful TextEdit), as well as setting TS disable auto type acquisition to true, to no luck. My jsconfig.json and tsconfig.json are not present, as per default.
Any ideas on why this could be happening?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I replace funtion each() for PHP 8.1? PART 1
I have the next mistake on the line 3:
WARNING | Function each() is deprecated since PHP 7.2; Use a foreach loop instead
I tried to replace this line with:
foreach ( $this->init_activity as $activity ) {
and the mistake disappeared.
protected function callActivities() {
do_action( 'vc_mapper_call_activities_before' );
while ( $activity = each( $this->init_activity ) ) {
list( $object, $method, $params ) = $activity[1];
if ( 'mapper' === $object ) {
switch ( $method ) {
case 'map':
WPBMap::map( $params['tag'], $params['attributes'] );
break;
case 'drop_param':
WPBMap::dropParam( $params['name'], $params['attribute_name'] );
break;
case 'add_param':
WPBMap::addParam( $params['name'], $params['attribute'] );
break;
case 'mutate_param':
WPBMap::mutateParam( $params['name'], $params['attribute'] );
break;
case 'drop_all_shortcodes':
WPBMap::dropAllShortcodes();
break;
case 'drop_shortcode':
WPBMap::dropShortcode( $params['name'] );
break;
case 'modify':
WPBMap::modify( $params['name'], $params['setting_name'], $params['value'] );
break;
}
}
}
}
PART 2
I have the same mistake on the line 4:
WARNING | Function each() is deprecated since PHP 7.2; Use a foreach loop instead
So i tried to do the same and replaced with:
foreach ( $this->element_activities[ $tag ] as $activity ) {
but in this case it appeared:
Warning: Undefined array key 0 on the next line (list( $method, $params ) = $activity[1];)
Warning: Undefined array key 1 on the next line (list( $method, $params ) = $activity[1];)
and i don´t know how i can fix.
public function callElementActivities( $tag ) {
do_action( 'vc_mapper_call_activities_before' );
if ( isset( $this->element_activities[ $tag ] ) ) {
while ( $activity = each( $this->element_activities[ $tag ] ) ) {
list( $method, $params ) = $activity[1];
switch ( $method ) {
case 'drop_param':
WPBMap::dropParam( $params['name'], $params['attribute_name'] );
break;
case 'add_param':
WPBMap::addParam( $params['name'], $params['attribute'] );
break;
case 'mutate_param':
WPBMap::mutateParam( $params['name'], $params['attribute'] );
break;
case 'drop_shortcode':
WPBMap::dropShortcode( $params['name'] );
break;
case 'modify':
WPBMap::modify( $params['name'], $params['setting_name'], $params['value'] );
break;
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I programatically select a tree item in a VS Code tree view given its label? I followed the example provided here to create a basic VS Code tree view.
I am now looking for how to to select (or unselect) an item in a tree view given its label.
I searched a lot but couldn't find any (simple) example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DAX: Average of same months across multiple years I am attempting to create something similar to a rolling average in power BI, however this calculation averages for a rolling period (say 5 years) using only a single month at a time.
I have sum total figures for 12 months for each year for 5 years in a table with the dates.
Any ideas on how to create a summary measure or table that will calculate this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: the bar chart of power bi doesn't apear the data I have created a column to estimate a rate by country but the diagramm appears only three countries with same rate which obviously is mistaken . Which is the mistake?
enter image description here
enter image description here
A: I'm guessing you have a divide by zero case that causes an "infinite" value to be calculated for France, Germany and Mexico.
However, you do not provide meaningful sample data or other relevant data such as what formula you have used in your calculated column rate (which is apparently giving you bad values).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an easy way to comment out / silence a code cell in Python/Colab? enter image description here
I am wondering if there is an easier way to do exactly this. I often have code that is theoretically useful for later if I run into a problem, but currently do not want it to run. Is there something I can type at the top of the cell like skip to get it to ignore the cell completely?
A: you could copy paste the code where it would be useful but i think that it would be better if you made it a function you could call it at will and the code will not run until called on.
def yourfunctionnamehere():
yourcode
this is how you create a function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL hackerrank weird output I have a problem with making multiple queries on hackerrank using mysql as when i provide it with the following queries:
SELECT CONCAT(Name,'(',LEFT(OCCUPATION,1),')')
FROM OCCUPATIONS
ORDER BY Name;
SELECT CONCAT('There are a total of ',COUNT(Occupation),' ',LOWER(Occupation),'s.')
FROM OCCUPATIONS
GROUP BY Occupation
ORDER BY COUNT(Occupation), Occupation;
this is the output:
Aamina(D)
Ashley(P)
Belvet(P)
Britney(P)
Christeen(S)
Eve(A)
Jane(S)
Jennifer(A)
Jenny(S)
Julia(D)
Ketty(A)
Kristeen(S)
Maria(P)
Meera(P)
Naomi(P)
Priya(D)
Priyanka(P)
Samantha(A)
CONCAT('There are a total of ',COUNT(Occupation),' ',LOWER(Occupation),'s.')
There are a total of 3 doctors.
There are a total of 4 actors.
There are a total of 4 singers.
There are a total of 7 professors.
and i dont know why this line appears:
CONCAT('There are a total of ',COUNT(Occupation),' ',LOWER(Occupation),'s.')
in the output, this happens no matter how simple the query is;
I tried doing just
SELECT Name from OCCUPATIONS;
and still in the output i have whats between select and occupations so in this case Name, the same happen if i include more queries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is Gatsby not loading '' component? Trying to map an array of objects as component, inside component but the console.log within never logs as well as the JSX? I am new to Gatsby and trying to understand it better, code I have is below. It is no longer producing any errors on load; previous errors was mostly a ".map is not a function" for it did not produce the array of objs before calling. However, again, there is no errors on loading, just no rendering of the component.
Any help or suggestions is greatly appreciated, thank you.
const IndexPage = () => {
var bookObjHolderArray = [];
// * Initialize book collection
const [books, setBooks] = useState(() => {
GetInfo().then((querySnapshot) =>{
querySnapshot.forEach((doc) => {
let bookObjHolderTemp = {
title: doc.data().title,
author: doc.data().author,
yearPublished: doc.data().yearPublished,
pageCount: doc.data().pageCount,
genre: doc.data().genre,
id: Math.random() * 1000
};
bookObjHolderArray.push(bookObjHolderTemp);
});
});
return bookObjHolderArray;
});
return(<>
<div className="header">
<span>Let's find a new book to read</span>
<Modal/>
</div>
<span className="section btn-container">
<button className="submit-btn" type='submit' onClick={inputHandler}>Let's read!</button>
<button className="clear-btn" type="submit">Clear Filters</button>
</span>
<BookContainer books={books}/>
</>);
}
export default IndexPage;
const BookContainer = ({books}) => {
console.log(books);
return(<>
<div id="display" className="section">
<input id='search-input' className="search-input"
type="search" placeholder="Search book by title..."></input>
<div className="section book-collection">
{books.map((book) => {
console.log(book);
<Book key={books.id} title={book.title} author={books.author} yearPublished={books.yearPublished} pageCount={books.pageCount} genre={books.genre}/>
})}
</div>
</div>
</>);
}
export default BookContainer;
import React from "react";
import cover from "../images/fairyTale.jpg";
import "../styles/book.scss";
const Book = (props) => {
console.log(props.title);
return(<div className="book-container">
<img src={cover} className="book-cover" alt="Cover"/>
<span className="book-title">{props.title}</span>
<div className="book-filter-container">
<span className="book-filter">{props.genre}</span>
<span className="book-filter">{props.yearPublished}</span>
<span className="book-filter">{props.pageCount} p.</span>
</div>
</div>);
}
export default Book;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python program for download google map / earth pictures Is there any python command (or python library command) for download a google maps or google earth pictures of specific :
+ location (lat. & long.)
+ Heading (bearing or azimuth)
+ Height (altitude)
For example something like this :
Googlemap.get(lat,long,heading,alt)
Any suggestions?
A: I would recommend you to look into Google's APIs for Earth and Maps.
Start here: https://developers.google.com/maps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Can't bind Blob to type 'Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer' I am a beginner on Azure, and I am developing a function application that allows me to store photos. I am using Linux and VS Code, and below is my code:
The code for my function application :
public static class PhotosStorage
{
[FunctionName("PhotosStorage")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [Blob("photos", FileAccess.ReadWrite,Connection = Literals.StoreConnectionString)] CloudBlobContainer blobContainer, ILogger log)
{
var body = await new StreamReader(req.Body).ReadToEndAsync();
var request = JsonConvert.DeserializeObject<PhotoUploadModel>(body);
var newId = Guid.NewGuid();
var blobName = $"{newId}.jpeg";
await blobContainer.CreateIfNotExistsAsync();
var blockBlobContainer = blobContainer.GetBlockBlobReference(blobName);
var photosBytes = Convert.FromBase64String(request.Photo);
await blockBlobContainer.UploadFromByteArrayAsync(photosBytes, 0, photosBytes.Length);
log?.LogInformation($"Successfully uploaded {newId}.jpeg file.");
return new OkObjectResult(newId);
}
}
My local.settings.json File
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"StoreConnectionString": "UseDevelopmentStorage=true"
}
}
Furthermore, here are the packages that I had imported :
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Blob;
I use a Docker container for Azure Storage Explorer. When I run my function func start, I get this error:
Can someone help me? Thank you in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the clicked image only when images are rendering inside a map function {compArr.map((comp, compIndex) => {
const compId = comp-${compIndex};
const levelOneId = levelOne-${compIndex} - ${comp} ;
const levelTwoId = levelTwo-${compIndex} - ${comp} ;
const levelThreeId = levelThree-${compIndex} - ${comp} ;
const levelOneName = ${comp} ;
const levelTwoName = ${comp} ;
const levelThreeName = ${comp} ;
return (
<div key={compIndex} className='comp-cont-externally'>
<p className='competency-text'>{comp}</p>
<div className="react-step">
<form >
<label>
<input
type='radio'
value='1'
name='item'
id={levelOneName}
checked={!checked}
onClick={(e) => ChangeIcon(e, compIndex, levelOneName)}
style={{ 'display': 'none' }}
/>
<img src= {InitialLevelOne} style= {{'height':'7vh'}}/>
</label>
<label>
<input
type='radio'
name='item'
value='2'
id={levelTwoName}
onClick={(e) => ChangeIcon(e, compIndex, levelTwoName)}
style={{ 'display': 'none' }}
/>
<img src= {InitialLevelTwo} style= {{'height':'7vh'}}/>
</label>
<label>
<input
type='radio'
name='item'
value='3'
id={levelThreeName}
onClick={(e) => ChangeIcon(e, compIndex, levelThreeName)}
style={{ 'display': 'none' }}
/>
<img src= {InitialLevelThree} style= {{'height':'7vh'}}/>
</label>
</form>
</div>
</div>
);
})}
I have tried few solution but it is changing the clicked images in all the tiles
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: translateX element when another element is on hover I'm trying to make a swiper slider using CSS and this what I got so far
HTML
<section id="lakeSlider" class="carousel vcenter-item py-5">
<div>
<div class="carousel__container">
<div class="carousel-item carousel-index1">
<div class="card">
<img class="carousel-item__img img-fluid"
src="./assets/images/cards/oserenfloatingcardimageindex2.png" alt="" />
<div class="card-body pb-0">
<h5 class="text-center card-title">Mila Hubert</h5>
<p class="card-text text-center">Sales Manager</p>
</div>
</div>
</div>
<div class="carousel-item carousel-index2">
<div class="card">
<img class="carousel-item__img img-fluid"
src="./assets/images/cards/oserenfloatingcardimageindex2.png" alt="" />
<div class="card-body pb-0">
<h5 class="text-center card-title">Boris Komnenov</h5>
<p class="card-text text-center">Marketing Manager</p>
</div>
</div>
</div>
<div class="carousel-item carousel-index3">
<div class="card">
<img class="carousel-item__img img-fluid"
src="./assets/images/cards/oserenfloatingcardimage.png" alt="" />
<div class="card-body pb-0">
<h5 class="text-center card-title">Joshua Rubens</h5>
<p class="card-text text-center">CEO</p>
<div class="cardbodydownarrow text-center m-0 p-0"><img
src="./assets/images/icon/oserendownarrowpix.png" alt="">
</div>
</div>
</div>
</div>
<div class="carousel-item carousel-index4">
<div class="card">
<img class="carousel-item__img img-fluid"
src="./assets/images/cards/oserenfloatingcardimageindex2.png" alt="" />
<div class="card-body pb-0">
<h5 class="text-center card-title">Anna Jimenez</h5>
<p class="card-text text-center">Product Designer</p>
</div>
</div>
</div>
<div class="carousel-item carousel-index5">
<div class="card">
<img class="carousel-item__img img-fluid"
src="./assets/images/cards/oserenfloatingcardimageindex2.png" alt="" />
<div class="card-body pb-0">
<h5 class="text-center card-title">Ben Hubert</h5>
<p class="card-text text-center">Programmer</p>
</div>
</div>
</div>
</div>
</div>
</section>
CSS
/* lakeSlider */
#lakeSlider .carousel {
width: 100%;
padding: 30px;
padding-top: 80px;
position: relative;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
#lakeSlider .carousel__container {
margin: 70px 0px;
padding-bottom: 10px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
#lakeSlider .categories__title {
color: rgb(77, 55, 102);
font-size: 28px;
position: absolute;
padding-left: 30px;
}
#lakeSlider .carousel-item {
width: 280px;
margin: 50px 5px;
overflow: hidden;
display: inline-block;
cursor: pointer;
-webkit-transition: 1000ms all;
transition: 1000ms all;
}
#lakeSlider .carousel-index1, #lakeSlider .carousel-index2 {
-webkit-transform-origin: center left;
transform-origin: center left;
}
#lakeSlider .carousel-index4, #lakeSlider .carousel-index5 {
-webkit-transform-origin: center right;
transform-origin: center right;
}
#lakeSlider .carousel-index3 {
-webkit-transform-origin: center center;
transform-origin: center center;
}
@media (min-width:960px) {
#lakeSlider .carousel-item:hover~.carousel-item {
-webkit-transform: translate3d(100px, 0, 0);
transform: translate3d(100px, 0, 0);
}
#lakeSlider .carousel__container:hover .carousel-item {
opacity: 0.3;
}
}
@media (min-width:960px) {
#lakeSlider .carousel__container:hover .carousel-item:hover {
-webkit-transform: scale(1.3);
transform: scale(1.3);
opacity: 1;
}
}
@media (max-width:960px) {
#lakeSlider .carousel__container:hover .carousel-item:hover {
opacity: 1;
}
}
#lakeSlider .card-body {
background-color: #2699FB;
color: white;
}
#lakeSlider .card-body h5 {
font-family: 'Poppins', sans-serif;
font-weight: 400;
}
#lakeSlider .card-body p {
font-family: 'Poppins', sans-serif;
font-size: 14px;
font-weight: 100;
}
enter image description here
this what is happening now:
When I hover on any card from them all elements on the right of the one I hovered is moving to the right 100px.
this what I need to happen :
*
*when hovering on any of the first two elements(1st,2nd) from the left, all right elements move to the right 100px.
*when hovering on the middle one (3rd), the first two elements move to the left 100px and the last two elements move to the right 100px.
*when hovering on the any of the last two elements (4th,5th), all left elements move to the left 100px.
Thank you for your patience and your help.
I tried to change this line
@media (min-width:960px) {
#lakeSlider .carousel-item:hover~.carousel-item {
-webkit-transform: translate3d(100px, 0, 0);
transform: translate3d(100px, 0, 0);
}
to be
#lakeSlider .carousel-index4:hover~.carousel-index1 {
-webkit-transform: translate3d(100px, 0, 0);
transform: translate3d(100px, 0, 0);
}
and custom all carousel-index for each one but it didn't do anything
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular - PageSizeOnChange not working in ngx-pagination In Angular-14, I am implementing ngx-pagination with server side pagination in ASP.NET Core-6 Web API. I have this code:
JSON Response:
{
"data": {
"pageItems": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"userId": "string",
"systemIpAddress": "string",
"auditType": "string",
"actionPerformed": "string",
"actionPerformedTime": "2022-10-28T05:54:12.830Z"
}
],
"currentPage": 1,
"pageSize": 10,
"numberOfPages": 3,
"totalRecord": 33
},
"successful": true,
"message": "string",
"statusCode": 0
}
service:
getAllAuditsPagination(pageNumber?: number,pageSize?: number): Observable<IAuditList[]> {
return this.http.get<IAuditList[]>(this.baseUrl + '/users/all-audits?pagenumber='+ pageNumber+'&pageSize='+pageSize);
}
component.ts:
allAuditList: any[] = [];
dataBk: IPageItem[] = this.allAuditList;
pageSize: number = 10;
currentPage: number = 1;
numberOfPages!: number;
totalRecords: number = 0;
pageSizes = [10, 20, 50, 100];
handlePageChange(event: number): void {
this.currentPage = event;
this.loadAllAudits();
}
handlePageSizeChange(event: any): void {
this.pageSize = event.target.value;
this.currentPage = 1;
this.loadAllAudits();
}
loadAllAudits() {
this.auditService.getAllAuditsPagination(this.currentPage, this.pageSize).subscribe({
next: (res: any) => {
this.allAuditList = res.data.pageItems;
this.totalRecords = res.data.totalRecord;
this.currentPage = res.data.currentPage;
this.pageSize = res.data.pageSize;
this.dataBk = res.data.pageItems;
this.isLoading = false;
}
})
}
component.html:
<tr
*ngFor="
let row of allAuditList
| paginate
: {
itemsPerPage: pageSize,
currentPage: currentPage,
totalItems: totalRecords
}
| orderBy : order : reverse : caseInsensitive;
let i = index
"
>
<div class="row">
<div class="col-md-6">
<pagination-controls
previousLabel="Prev"
nextLabel="Next"
[responsive]="true"
(pageChange)="handlePageChange($event)"
>
</pagination-controls>
</div>
<div class="col-md-4">
Items Per Page:
<select (change)="handlePageSizeChange($event)">
<option *ngFor="let size of pageSizes" [ngValue]="size">
{{ size }}
</option>
</select>
</div>
</div>
Pagination is working fine. But where I have issue is the handlePageSizeChange, I mean dropdown paging
Then dropdown has 10,20,50,100. For example when I selected 50 from the from the dropdown OnChange, the pagesize and the pagination (1,2...6) remain the same.
How do I correct this?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to define an auto height into a var I'm trying to put my footer under the section div, the section's height is auto so i can't define a top.
I'm trying to define the height using this script:
function footer()
{
var h = parseFloat(document.getElementById("sect").style.height);
document.getElementById("foot").style.top = h + "px";
}
It doesn't work because it doesn't read the height as the number but as the string 'auto'.
Is possible to do it? There is a better way to do it?
A: If I understood your question correctly as you want to find the height of your element in javascript then here are your options:
const elm = document.getElementById("sect");
// Returns an object with left, x, top, y, right, bottom, width, height properties of the element.
// width and height includes the border and padding. Others are relative to the top/left of the viewport
elm.getBoundingClientRect();
// Viewable width/height of the element including padding, but NOT border, scrollbar or margin (excludes overflow)
elm.clientWidth;
elm.clientHeight;
// Viewable width/height of the element including padding, border, scrollbar, but NOT margin (excludes overflow)
elm.offsetWidth;
elm.offsetHeight;
// Entire width/height of the element including padding, but NOT border, scrollbar or margin (includes overflow)
elm.scrollWidth;
elm.scrollHeight;
so your function may looks like:
function footer()
{
var h = parseFloat(document.getElementById("sect").offsetHeight);
document.getElementById("foot").style.top = h + "px";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Where clause performance constant vs variable I have a table function as show below. When I call the function with a literal it completes in 3 seconds on my dataset. So the following completes in 3 seconds:
Select *
from getActiveConcessionsForShipment(12)
If I use a variable, on the other hand, the function completes in 11:32! So the following completes in 11:32s
Declare @shipmentID int = 12
Select *
from getActiveConcessionsForShipment((@shipmentID))
Same function. How can I improve it using a variable? Here is the function:
Alter Function getActiveConcessionsForShipment(@shipmentID int)
returns Table
With Encryption
As
return
(
-- Item Concessions
Select 0 OrderNo, ConcessionID, ic.TariffNo, ic.DepartmentID, d.DepartmentName, [Level], i.ItemID, ExpiryDate, GeneralRate Rate, GeneralRateNumeric ConcessionRate, Cast(1 as Bit) Concession
from Shipment s
join Manifest m
on (m.ManifestID = s.ManifestID)
join ShipmentInvoice si
on (si.ShipmentID = s.ShipmentID)
join ShipmentInvoiceDetail sid
on (sid.ShipmentInvoiceID = si.ShipmentInvoiceID)
join StockInvoice sti
on (sti.StockInvoiceID = si.StockInvoiceID)
join StockInvoiceDetail stid
on (stid.StockInvoiceDetailID = sid.StockInvoiceDetailID)
join ItemSupplier isup
on (isup.SupplierID = sti.SupplierID and isup.SupplierItemNo = stid.SupplierItemNo)
join Item i
on (i.ItemID = isup.ItemID)
join Tariff t
on (t.TariffID = i.TariffID)
join Department d
on (d.DepartmentID = sti.DepartmentID)
join ItemConcession ic
on (ic.ItemID = i.ItemID and ic.TariffNo = t.TariffNo)
Where s.ShipmentID = @shipmentID and ExpiryDate > m.ArrivalDate and 'Paid|Concession|Mixed' like '%' + s.EntryType + '%'
UNION
-- Tariff Concessions minus duty paid items
Select 1, ConcessionID, tc.TariffNo, tc.DepartmentID, d.DepartmentName, [Level], i.ItemID, ExpiryDate, GeneralRate Rate, GeneralRateNumeric ConcessionRate, 1 Concession
from Shipment s
join Manifest m
on (m.ManifestID = s.ManifestID)
join ShipmentInvoice si
on (si.ShipmentID = s.ShipmentID)
join ShipmentInvoiceDetail sid
on (sid.ShipmentInvoiceID = si.ShipmentInvoiceID)
join StockInvoice sti
on (sti.StockInvoiceID = si.StockInvoiceID)
join StockInvoiceDetail stid
on (stid.StockInvoiceDetailID = sid.StockInvoiceDetailID)
join ItemSupplier isup
on (isup.SupplierID = sti.SupplierID and isup.SupplierItemNo = stid.SupplierItemNo)
join Item i
on (i.ItemID = isup.ItemID)
join Tariff t
on (t.TariffID = i.TariffID)
join Department d
on (d.DepartmentID = sti.DepartmentID)
join TariffConcession tc
on (tc.DepartmentID = d.DepartmentID and tc.TariffID = i.TariffID)
outer apply
(
Select StockInvoiceDetailID
from FreezoneDutyPaidItem
Where StockInvoiceDetailID = sid.StockInvoiceDetailID
) dpi
Where s.ShipmentID = @shipmentID and ExpiryDate > m.ArrivalDate and 'Paid|Concession|Mixed' like '%' + s.EntryType + '%' and dpi.StockInvoiceDetailID is null
UNION
-- Department Concessions minus duty paid items
Select 2 [Order], ConcessionID, dc.TariffNo, dc.DepartmentID, d.DepartmentName, [Level], i.itemID, ExpiryDate, GeneralRate Rate, GeneralRateNumeric ConcessionRate, 1 Concession
from Shipment s
join Manifest m
on (m.ManifestID = s.ManifestID)
join ShipmentInvoice si
on (si.ShipmentID = s.ShipmentID)
join ShipmentInvoiceDetail sid
on (sid.ShipmentInvoiceID = si.ShipmentInvoiceID)
join StockInvoice sti
on (sti.StockInvoiceID = si.StockInvoiceID)
join StockInvoiceDetail stid
on (stid.StockInvoiceDetailID = sid.StockInvoiceDetailID)
join ItemSupplier isup
on (isup.SupplierID = sti.SupplierID and isup.SupplierItemNo = stid.SupplierItemNo)
join Item i
on (i.ItemID = isup.ItemID)
join Tariff t
on (t.TariffID = i.TariffID)
join Department d
on (d.DepartmentID = sti.DepartmentID)
join DepartmentConcession dc
on (dc.DepartmentID = d.DepartmentID)
outer apply
(
Select StockInvoiceDetailID
from FreezoneDutyPaidItem
Where StockInvoiceDetailID = sid.StockInvoiceDetailID
) dpi
Where s.ShipmentID = @shipmentID and ExpiryDate > m.ArrivalDate and 'Paid|Concession|Mixed' like '%' + s.EntryType + '%' and dpi.StockInvoiceDetailID is null
UNION
-- Bonded in PaidZone
Select 3 [Order], ConcessionID, dc.TariffNo, dc.DepartmentID, d.DepartmentName, [Level], i.itemID, ExpiryDate, 'Free' Rate, 0 ConcessionRate, 1 Concession
from Shipment s
join Manifest m
on (m.ManifestID = s.ManifestID)
join ShipmentInvoice si
on (si.ShipmentID = s.ShipmentID)
join ShipmentInvoiceDetail sid
on (sid.ShipmentInvoiceID = si.ShipmentInvoiceID)
join StockInvoice sti
on (sti.StockInvoiceID = si.StockInvoiceID)
join StockInvoiceDetail stid
on (stid.StockInvoiceDetailID = sid.StockInvoiceDetailID)
join ItemSupplier isup
on (isup.SupplierID = sti.SupplierID and isup.SupplierItemNo = stid.SupplierItemNo)
join Item i
on (i.ItemID = isup.ItemID)
join Tariff t
on (t.TariffID = i.TariffID)
join Department d
on (d.DepartmentID = sti.DepartmentID)
join DepartmentConcession dc
on (dc.DepartmentID = d.DepartmentID)
Where s.ShipmentID = @shipmentID and dc.TariffNo = 'Bonded' and s.EntryType = dc.EntryType
UNION
-- Freezone Items
Select 3 [Order], -1 ConcessionID, 'Freezone' TariffNo, d.DepartmentID, DepartmentName, 'Department' [Level], i.ItemID, null ExpiryDate, 'Freezone' Rate, 0 ConcessionRate, 1 Concession
from Shipment s
join Manifest m
on (m.ManifestID = s.ManifestID)
join ShipmentInvoice si
on (si.ShipmentID = s.ShipmentID)
join ShipmentInvoiceDetail sid
on (sid.ShipmentInvoiceID = si.ShipmentInvoiceID)
join StockInvoice sti
on (sti.StockInvoiceID = si.StockInvoiceID)
join StockInvoiceDetail stid
on (stid.StockInvoiceDetailID = sid.StockInvoiceDetailID)
join ItemSupplier isup
on (isup.SupplierID = sti.SupplierID and isup.SupplierItemNo = stid.SupplierItemNo)
join Item i
on (i.ItemID = isup.ItemID)
join Tariff t
on (t.TariffID = i.TariffID)
join Department d
on (d.DepartmentID = sti.DepartmentID)
outer apply
(
Select StockInvoiceDetailID
from FreezoneDutyPaidItem
Where StockInvoiceDetailID = sid.StockInvoiceDetailID
) dpi
Where s.ShipmentID = @ShipmentID and EntryType = 'Freezone' and dpi.StockInvoiceDetailID is null
)
go
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't disable discord buttons after they are used I'm trying to have discord disable buttons once they are used twice but when I try to disable the buttons i get a type error in the console saying TypeError: Cannot read properties of undefined (reading 'setDisabled'). I've been trying to fix it for 2 hours I did try to do research about it in the discord.js docs and here but I wasn't really able to find a solution so any help would be great!
collector.on('end', async () => {
const shuffledQueue = [...queue].sort(() => Math.random() - 0.5);
const captains = [shuffledQueue[0], shuffledQueue[1]];
const players = shuffledQueue.slice(2);
const shuffledCaptains = captains.sort(() => Math.random() - 0.5);
// console.log(captains)
const halfIndex = players.length / 2;
const team1 = [shuffledCaptains[0], ...players.splice(0, halfIndex)];
const team2 = [shuffledCaptains[1], ...players.splice(0, halfIndex)];
const team1Usernames = team1.map(user => `@${user.username}`);
const team2Usernames = team2.map(user => `@${user.username}`);
const mapPool = [
'Bind',
'Haven',
'Split',
'Ascent',
'Icebox',
'Breeze',
'Fracture',
'Pearl',
'Lotus'
];
const MAX_MAPS_TO_BAN = 2;
let mapBanCount = 0;
const mapBanButtons = [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ban_1')
.setLabel('Ban Bind')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
new ButtonBuilder()
.setCustomId('ban_2')
.setLabel('Ban Split')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
new ButtonBuilder()
.setCustomId('ban_3')
.setLabel('Ban Haven')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
),
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ban_4')
.setLabel('Ban Ascent')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
new ButtonBuilder()
.setCustomId('ban_5')
.setLabel('Ban Icebox')
.setStyle(ButtonStyle.Danger)
.setDisabled(false)
),
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ban_6')
.setLabel('Ban Breeze')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
new ButtonBuilder()
.setCustomId('ban_7')
.setLabel('Ban Fracture')
.setStyle(ButtonStyle.Danger)
.setDisabled(false),
new ButtonBuilder()
.setCustomId('ban_8')
.setLabel('Ban Pearl')
.setStyle(ButtonStyle.Danger)
.setDisabled(false)
),
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ban_9')
.setLabel('Ban Lotus')
.setStyle(ButtonStyle.Danger)
.setDisabled(false)
)
];
const banEmbed = new EmbedBuilder()
.setTitle('Map Ban')
.setDescription('Team Captains: Please ban one map each. The remaining map will be played.')
.addFields(
{ name: '\u200B', value: '\u200B' },
{ name: 'Banned Maps', value: 'None', inline: true },
{ name: 'Maps to Play', value: 'None', inline: true }
)
.setFooter({ text: `Captain: ${interaction.user.tag}`});
const banMessage = await interaction.channel.send({
embeds: [banEmbed],
components: mapBanButtons,
});
let numButtonUses = 0;
const banButtonCollector = banMessage.createMessageComponentCollector({
time: 60000,
});
banButtonCollector.on('collect', async (interaction) => {
if (numButtonUses < 2) {
numButtonUses++;
} else {
const disabledButton = interaction.component.setDisabled(true);
interaction.update({
embeds: [banEmbed],
components: mapBanButtons.map((row) =>
row.addComponents(disabledButton)
),
});
}
});
banButtonCollector.on('end', async () => {
});
It's just suppose to disable the mapBanButtons once the number of uses has reached 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ vs Python | Read Memory Have working code in C++ and would like to get equivalent results with Python.
The idea is to retrieve data from memory using a specific process and a pointer. The result should look like this as it works in C++:
Here is the C++ code:
hProcess = SOME_HANDLER
addr = SOME_POINTER
SIZE_T bytesRead = 0;
SIZE_T sizeBuff = 0x4000;
BYTE buff[sizeBuff];
ReadProcessMemory(hProcess, addr, buff, sizeBuff, &bytesRead);
In Python I have tried this:
read_buffer = (ctypes.c_char * 0x4000)()
lp_buffer = ctypes.byref(read_buffer)
n_size = ctypes.sizeof(read_buffer)
lp_number_of_bytes_read = ctypes.c_ulong(0)
ctypes.windll.kernel32.ReadProcessMemory(self.handle, ctypes.c_void_p(lp_base_address), lp_buffer, n_size, lp_number_of_bytes_read)
result = read_buffer.value
Which gave me this result:
`b'hA\xdf\x01<B\xdf\x01\xb9\t\xba\t'`
I don't know what this means or if it contains anything useful.
A: result is a value of type bytes, which represents a series of integer values between 0 and 255, inclusive.
When you display the each byte is show in one of two forms:
*
*If the byte corresponds to a printable ASCII character, it is shown as that character.
*Otherwise, it is shown as a hexadecimal integer prefixed with \x.
Iterating over a bytes value yields a sequence of int objects:
>>> list(result)
[104, 65, 223, 1, 60, 66, 223, 1, 185, 9, 186, 9]
(Note that ord('h') == 104, ord('A') == 65, \xdf == 223, etc.)
As mentioned in the comments, the struct package can be used to extract "usable" objects from a raw bytes value. For example, one could treat these 12 bytes as 3 unsigned 4-byte words in big-endian byte order:
>>> import struct
>>> struct.unpack(">III", result)
(1749147393, 1011015425, 3104422409)
or 6 unsigned 2-byte words in little-endian byte order:
>>> struct.unpack("<HHHHHH", result)
(16744, 479, 16956, 479, 2489, 2490)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: bokeh.plotting.gmap.image - what should I put as first argument of this method? I want to draw my own image instead of the circle on the map. Method circle works perfectly, however I have problem with method image. I do not know what should I put as first argument. According (https://docs.bokeh.org/en/2.3.3/docs/reference/models/glyphs/image.html) documentation it should be an array od scalars. As a result I want to put there icons (as png or I can convert them to some point/lines array).
Current result:
Wanted result:
p = gmap(api_key, gmap_options, title='Pays de Gex',
width=bokeh_width, height=bokeh_height,
tools=[hover, 'reset', 'wheel_zoom', 'pan'])
p.circle('lon',
'lat',
size=10, alpha=1,
color=mapper,
source=source)
p.image(?,
'lon',
'lat',
source=source)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this a gdb bug? I was playing around with a simple program (see below) and I came across behavior that did not seem correct. I ran the program with gdb as shown below, and it does not seem to read the passed arguments to func correctly, for instance it says b=21845, and even says . Is there an explanation for this?
I am running this on a MacBook Pro, 2.3 GHz 8-Core Intel Core i9, MACOS 13.1 (22C65). I compiled the program with: g++ -std=c++2a test.cpp -g -lpthread -lstdc++fs -o test
I got the DBG debugger from https://marketplace.visualstudio.com/items?itemName=coolchyni.beyond-debug, with https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools. I am using visual studio code.
Code: test.cpp
#include <iostream>
void func(int b, int &c)
{
std::cout << b <<" and " << c<< std::endl;
}
int main()
{
int num2 = 4;
int &num3 = num2;
func(num2, num3);
return 0;
}
GDB Run
Starting program: /home/es927/exper/test
Breakpoint 1, main () at test.cpp:10
10 int num2 = 4;
(gdb) s
11 int &num3 = num2;
(gdb) s
12 func(num2, num3);
(gdb) s
func (b=21845, c=<error reading variable>) at test.cpp:4
4 {
(gdb) s
5 std::cout << b << " and " << c << std::endl;
(gdb) s
4 and 4
6 }
(gdb) s
main () at test.cpp:14
14 return 0;
(gdb) s
15 }
(gdb) c
Continuing.
[Inferior 1 (process 1235898) exited normally]
I was expecting the values of the passed arguments when stepping after code line 12.
A: This is fully expected behavior. This kind of parameter behaviour is described in the gdb manual - 10.3 Program Variables (emphasis mine):
Warning: Occasionally, a local variable may appear to have the wrong value at certain points in a function—just after entry to a new scope, and just before exit.
Thus, the easiest solution is to just step once more into the actual function block scope and use info local. The manual also goes on to talk about methods for trying to mitigate this wrong value behavior. Unfortunately, I was not able to reproduce the weird values you were having (in WSL with gcc-11.3.0 and gdb-13.1) so I was unable to verify these methods.
All things considered, I would not worry about this kind of debugger behavior too much. For example, these uninitialized parameter values are every day for the Visual Studio's debugger, even to the point of making it hard to debug single line functions.
Edit: Based on the comments and more findings, here are some other things you can try:
*
*As @jwdonahue pointed out that, you might have an issue with an old gdb version (eg. gdb --version). You can try updating gdb with the package manager or just build a newer gdb from source and replace the system gdb with that.
*Try to use gdb specific debugging information with -ggdb. There is also a -g3 option, but that changes very little compared to the default level 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework Core 7 - composite key mapping problem I am struggling to create the necessary attributes and code to allow me to retrieve all information from 3 tables I have.
The tables are:
Recipe table:
Column
Type
RecipeId
int (Key)
Title
varchar
Ingredients table:
Column
Type
IngredientId
int (Key)
Description
varchar
Ingredients_Mapping table:
Column
Type
RecipeId
int (Key)
IngredientId
int (Key)
Quantity
int (Key)
Hopefully the above makes sense. Each recipe may contain many ingredients. When I've pulled back details before it has been a simple one and I've added a .Include(x => x.Whatever) to extract the data from the joining table.
Here's the code:
public class Recipe
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[NotMapped]
public Ingredient[] Ingredients { get; set; }
}
public class Ingredient
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Title { get; set; }
}
public class IngredientMapping
{
[Key]
[Required]
public int RecipeId { get; set; }
[Key]
[Required]
public int IngredientId { get; set; }
[Required]
public int Quantity { get; set; }
}
public async Task<List<Recipe>> GetAllRecipesAsync()
{
return await _MyDbContext.Recipes
.Include(x => x.???)
.OrderBy(b => b.Title).ToListAsync();
}
Could somebody please advise how I can do this please?
A: There are two main ways to configure the many-to-many relationship in EF Core - either by setting two entities up and having EF Core to generate the join table without explicitly exposing it:
public class Recipe
{
// ...
public List<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
// ...
public List<Recipe> Recipes { get; set; }
}
Or setting up the join table explicitly, which should be the case taking in account the need to store the additional information in it (Quantity):
public class Recipe
{
// ...
public List<RecipeIngredient> RecipeIngredient { get; set; }
}
public class Ingredient
{
// ...
public List<RecipeIngredient> RecipeIngredients { get; set; }
}
// for 7th version, otherwise use
// modelBuilder.Entity<RecipeIngredient>().HasKey(e => new {e.RecipeId,e.IngredientId })
[PrimaryKey(nameof(RecipeId), nameof(IngredientId))]
public class RecipeIngredient
{
public int RecipeId { get; set; }
public Recipe Recipe { get; set; }
public int IngredientId { get; set; }
public Ingredient Ingredient { get; set; }
[Required]
public int Quantity { get; set; }
}
This should already be fully defined relationship but if needed you can apply the configuration via model builder (also see options to set up composite key).
A: Store Guru's answer is fine, but if you have problem with two primary keys.
use this config
public class Recipe
{
[Key]
public int Id { get; set; }
[Required]
public required string Title { get; set; }
public virtual List<IngredientMapping> IngredientMappings { get; set; }
}
public class Ingredient
{
[Key]
public int Id { get; set; }
[Required]
public required string Title { get; set; }
public List<IngredientMapping> ingredientMappings { get; set; }
}
public class IngredientMapping
{
[Key]
public int Id { get; set; }
[Required]
public int RecipeId { get; set; }
[Required]
public int IngredientId { get; set; }
[Required]
public int Quantity { get; set; }
public virtual required Recipe Recipe { get; set; }
public virtual required Ingredient Ingredient { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When does the getTransportDetails operation return the CarrierName? Amazon SP-API, FulfillmentInbound The Amazon MWS API used to return a carrier name after some time, during the cost estimation process. With the Amazon Selling Partner API, I've waited for over 2 hours, and although the report says that the cost has been estimated, I still don't have a carrier name.
When does the carrier name get assigned?
Here is the reference:
https://developer-docs.amazon.com/sp-api/docs/fulfillment-inbound-api-v0-reference#gettransportdetails
I used the SP API to mimic an already existing shipment that had been entered manually, and I need to make sure that all the data is available before continuing.
We specified PartneredLtlData in the transport contents, which got accepted. The transport cost also got estimated.
Should I just stop waiting after a while? I saw the carrier name show up in the Seller Central console on a previous rendition of the same test, quickly after requesting the estimate. Should I call a different operation?
Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: nextauth.js credentials provider: unable to return user or error message I am using next-auth.js version 4.19.2 with the "credentials" (db) provider and some custom sign-in, signout pages. I seem unable to return what it expects from the authorize() handler. I would like to return the authenticated user or an error message. I tried 'return user' and 'return null' as well as resolving and rejecting a Promise 'return Promise.resolve(user)' and 'return Promise.reject(null)'... neither worked. Can someone spot the issue below? Thank you!
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import User from "../../../../models/User";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
CredentialsProvider({
name: "Credentials",
async authorize(credentials, req) {
const { username, password } = credentials;
const user = await User.findOne({ email: username }).exec();
if (user) {
console.log("user", user);
await user.comparePassword(password, function (err, isMatch) {
console.log("comparePassword err, isMatch", err, isMatch);
if (err) throw err;
if (isMatch) {
console.log("IS MATCH!");
return Promise.resolve(user);
}
});
} else {
return Promise.reject(null);
}
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
error: "/auth/error", // Error code passed in query string as ?error=
verifyRequest: "/auth/verify-request", // (used for check email message)
newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest)
},
};
export default NextAuth(authOptions);
Using it like this:
<button
type="submit"
className="btn btn-primary w-100 mt-4"
onClick={() =>
signIn("credentials", {
redirect: false,
username: state.username,
password: state.password,
callbackUrl: "/",
}).then(({ ok, error }) => {
if (ok) {
alert("OK");
} else {
console.log(error);
alert("NOT OK");
}
})
}
>
Sign in
</button>
What am I doing wrong here?
A: You have to return an object not a promise :
let returnedValue;
if (user) {
await user.comparePassword(password, function (err, isMatch) {
if (err) returnedValue = null; // throwing an error here will prevent the function from returning
if (isMatch) returnedValue = user;
});
} else {
returnedValue = null;
}
return returnedValue;
Also here you are only returning the user you are not storing it in your session to do that you should use callbacks :
callbacks: {
async jwt({ user, token }) {
if (user) {
token.user = user;
}
return token;
},
async session({ session, token }) {
session.user = token.user;
return session;
},
},
A: This my current next-auth with credentials and it working fine
import NextAuth from 'next-auth'
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials"
import dbConnect from '../../../lib/dbConnect';
import User from '../../../models/User';
import { compare, hash } from 'bcryptjs';
import crypto from 'crypto';
import sendVerificationEmail from '../../../middleware/emailService';
let AuthUser;
export const authOptions = {
providers: [
// OAuth authentication providers...
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
}
}),
CredentialsProvider({
name: 'Credentials',
async authorize(credentials, req) {
await dbConnect()
//check user existance
const result = await User.findOne({email: credentials.email}).select('+password')
if(!result){
throw new Error('No user Found With Email Please Sign Up!')
}
if(result.verified){
//compare password
const checkPassword = await compare(credentials.password, result.password)
if(!checkPassword || result.email !== credentials.email){
throw new Error("Email or Password dosen't match")
}
AuthUser = result
return result
}else{
sendVerificationEmail(result.email, result.verificationToken)
throw new Error("Please Confirm Your Email!")
}
}
})
],
callbacks:{
signIn: async ({ user, account, profile }) => {
await dbConnect()
if (account.provider === "google") {
const existingUser = await User.findOne({ email: user.email });
if (existingUser) {
AuthUser = existingUser
return existingUser;
}
const randomPassword = crypto.randomBytes(8).toString('hex');
const hashedPassword = await hash(randomPassword, 12);
const newUser = await User.create({
name: user.name,
email:user.email,
password:hashedPassword,
provider:true,
providerName:"google"
});
AuthUser = newUser
return newUser;
}else{
return true
}
},
session: async ({session}) => {
if(AuthUser){
// Add custom data to the session object
session.userData = {
isAdmin: AuthUser.isAdmin,
id: AuthUser._id,
};
}
return session;
},
},
secret: process.env.NEXT_AUTH_SECRET,
database: process.env.DB_URL
}
export default NextAuth(authOptions)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Displaying array data in table with react Hello I am trying to display some data in a table using React.JS and Im having trouble understanding how to get it all to work. I can get the data to display using just a p tag but thats not what I want. I'm not sure where to go here since I am still reactjs is still new to me I have looked through numerous tutorials and have tried a few different things to see if something would display but nothing has happened.
import logo from './logo.svg';
import './App.css';
import React, {useMemo, useEffect, useState} from "react";
import Table from 'react';
function App() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// const columns = useMemo(() => [
// {
// Header: "Population Density",
// accessor: "DENSITY_2021",
// },
// {
// Header: "Population",
// accessor: "POP_2021",
// },
// {
// Header: "State",
// accessor: "NAME",
// },
// ])
useEffect(() => {
fetch("https://api.census.gov/data/2021/pep/population?get=DENSITY_2021,POP_2021,NAME,STATE&for=state:*")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return(
<table>
<thead>
<tr>
<th>Population Density</th>
<th>Population</th>
<th>State</th>
</tr>
</thead>
<tbody>
console.log(items)
</tbody>
</table>
);}```
I have tried displaying to get the data to display by using
{items.map(item => {
return (
<tr key={item.DENSITY_2021}>
<td>{ item.POP_2021}</td>
<td>{ item.NAME }</td>
</tr>
);
})}```
in the table body
A: you imported the wrong component
Change import Table from 'react'; to import {Table} from 'react-bootstrap';
make sure you have installed the react-bootstrap
to install a react-bootstrap with bootstrap or you can follow this https://react-bootstrap.github.io/getting-started/introduction
npm install react-bootstrap bootstrap --save
or
yarn install react-bootstrap bootstrap --save
here is the updated version.
<table>
<head>
<tr>
<th>Density</th>
<th>Population</th>
<th>State</th>
</tr>
</thead>
<tbody>
{items.map(item => {
<tr key={item.STATE}>
<td>{item.DENSITY_2021}</td>
<td>{item.POP_2021}</td>
<td>{item.NAME}</td>
</tr>
})}
</tbody>
</table>
or you can use
<tbody>
{items.map(item => (
<tr key={item.STATE}>
<td>{item.DENSITY_2021}</td>
<td>{item.POP_2021}</td>
<td>{item.NAME}</td>
</tr>
))}
</tbody>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VS2022 Temp Folders from %LOCALAPPDATA%\Temp: Is it safe to delete them? I am new (I'd say) to Visual Studio. I installed it about ~a month ago. Although, while using Visual Studio, I see a huge problem. As I open %TEMP% folder (user temp directory), I see a ton of folders with absolutely random names. Some of them are empty, some consist of a 0-byte JSON file with random name also. Just look at this mess. I am absolutely sorry if you cannot read this language, but it's not important, the only important thing is to look at folder names. These are all generated by Visual Studio!
Now, I know these do not occupy disk space at all. But I absolutely don't like looking at this mess.
I can use Disk Cleanup tool. However, there are 2 things to mention:
*
*Disk Cleanup only deletes 0-byte JSON files, not the directories.
*There are some huge directories also created by Visual Studio, which Disk Cleanup actually would delete. But I think it is unsafe to delete them.
For example, take a look at this directory that's in the TEMP directory as well, also with a completely random name. This one has a size of 1.7GB.
Basically, I think deleting this folder would cause problems with Visual Studio. It is also one of the folders Disk Cleanup can delete.
So my question is: Can I delete folders created by Visual Studio (2022) in %TEMP% with names like these described:
*
*VS
*VSTempFiles
*VSTelem
*VSTelem.Out
*VSFeedbackIntelliCodeLogs
*VSFeedbackPerfWatsonData
*WPF (Assuming this one is created by Visual Studio, even though I wasn't developing any WPF-based applications)
*MSBuildTempUSERNAME
*NuGetScratch
*The 1.7GB directory with a random name described above with an image
*Tons of 0-byte directories with random names
Not important: I know that I may be asking too much here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Express POST endpoint waiting for another one to respond I have the following code:
app.post(dispatchOrderPath, async (deliveryRequest: any, deliveryRes: any) => {
try{
const order: Order = deliveryRequest.body;
console.log(order);
await initConnection(order);
const internalEndpoint = '/internalService/' + order.token;
let acceptOrderPromise: Promise<boolean> = new Promise((resolve, reject) => {
app.post(internalEndpoint, (req:any, res:any) => {
res.status(200).send("OK");
resolve(req.body.accept);
})
})
const acceptOrder = await acceptOrderPromise;
let responseObject : object = {};
let status : number;
if (acceptOrder) {
responseObject = {
remoteOrderId: order.token
}
status = 200;
} else {
responseObject = {
reason: "blabla",
message: "blblaba"
}
status = 400;
}
deliveryRes.status(status).json(responseObject);
}catch(err){
throw err;
}
})
It works correctly the first time: a request arrieves to the first post endpoint and waits for internalendpoint to recieve a request in order to finish the request. But when a second one arrieves, it just freezes and dont respond anymore. I dont know if this is a correct way of managing this behaviour of making a post endpoint wait for another one to end a request.
I've tried to implement promises in order to await for the internalendpoint to
recieve a request and resolve, it works fine for the first cycle of request-response. The second one just freezes.
EDIT:
CHATGPT is amazing and it helped me find the way. For anyone wondering how i managed to fixed, here's the working code:
let acceptOrderPromiseResolver: (value: boolean | PromiseLike<boolean>) => void;
app.post(dispatchOrderPath, async (deliveryRequest: any, deliveryRes: any) => {
try {
const order: Order = deliveryRequest.body;
console.log(order);
await initConnection(order);
const internalEndpoint = '/internalService/' + order.token;
let acceptOrderPromise: Promise<boolean> = new Promise((resolve, reject) => {
acceptOrderPromiseResolver = resolve;
})
const acceptOrder = await acceptOrderPromise;
let responseObject: object = {};
let status: number;
if (acceptOrder) {
responseObject = {
remoteOrderId: order.token
}
status = 200;
} else {
responseObject = {
reason: "blabla",
message: "blblaba"
}
status = 400;
}
deliveryRes.status(status).json(responseObject);
} catch (err) {
throw err;
}
})
app.post('/internalService/:token', (req:any, res:any) => {
res.status(200).send("OK");
acceptOrderPromiseResolver(req.body.accept);
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding Shadow to Curved AppBar I have a curved AppBar using the following code.
I want to add a shadow right beneath the curve.
Any help would be much appreciated!
image of curved AppBar
Code:
appBar: PreferredSize(
preferredSize: const Size.fromHeight(85.0),
child: AppBar(
title: const Text("Services"),
flexibleSpace: ClipPath(
clipper: Customshape(),
child: Container(
height: 250,
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.1, 0.55],
colors: <Color>[Color(0xff21CDAF), Color(0xff1093BC)],
),
),
),
),
),
),
class Customshape extends CustomClipper<Path> {
@override
Path getClip(Size size) {
double height = size.height;
double width = size.width;
var path = Path();
path.lineTo(0, height - 50);
path.quadraticBezierTo(width / 2, height, width, height - 50);
path.lineTo(width, 0);
path.close();
return path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return true;
}
}
I tried wrapping the container with a material widget and adding a box shadow to box decoration but neither worked.
A: to achieve the shadow you can use
*
*elevation
*shadowColor
you can also modify the toolbarHeight and toolbarOpacity to achieve the shadow effect
if you need further assistance i will be happy to help more!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the detailed page by slug and not id in Django Rest Framework class based views I am building an API using Django Rest Framework. I have the /api/localities endpoint where all of the objects on my database are displayed.
Now I want to create the endpoint for a single page of a particular locality, and I want to make it by slug and not id for example /api/localities/munich.
I am using Class based views and right now I can get the single page by id, for example /api/localities/2, but I want to change that to the slug.
How can I do this?
Here is my code:
models.py
class Localities(models.Model):
id_from_api = models.IntegerField()
city = models.CharField(max_length=255, null=True, blank=True)
slug = models.CharField(max_length=255, null=True, blank=True)
postal_code = models.CharField(max_length=20, null=True, blank=True)
country_code = models.CharField(max_length=10, null=True, blank=True)
lat = models.CharField(max_length=255, null=True, blank=True)
lng = models.CharField(max_length=255, null=True, blank=True)
google_places_id = models.CharField(max_length=255, null=True, blank=True)
search_description = models.CharField(max_length=500, null=True, blank=True)
seo_title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.city
serializers.py
from rest_framework import serializers
from .models import Localities
class LocalitiesSerializers(serializers.ModelSerializer):
class Meta:
model = Localities
fields = (
"id",
"id_from_api",
"city",
"slug",
"postal_code",
"country_code",
"lat",
"lng",
"google_places_id",
"search_description",
"seo_title",
)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from wagtail.core.models import Page
from .models import LocalityPage, Localities
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import generics
import json
import requests
from .models import Localities
from .serializers import LocalitiesSerializers
class LocalitiesAll(generics.ListCreateAPIView):
queryset = Localities.objects.all()
serializer_class = LocalitiesSerializers
class LocalitiesDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Localities.objects.all()
serializer_class = LocalitiesSerializers
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('reload', views.convert_json), # app homepage
path("localities/", views.LocalitiesAll.as_view()),
path("localities/<int:pk>/", views.LocalitiesDetail.as_view()),
]
A: If you want to use slug instead of id then first you need to update your URLs from int:pk to str:slug:
path("localities/<str:slug>/", views.LocalitiesDetail.as_view())
Now update your views.py file class to:
class LocalitiesDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Localities.objects.all()
serializer_class = LocalitiesSerializers
lookup_field = 'slug'
This will help you to reach the goal that you wanted to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django: NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent I am trying to integrate stripe into my django application, i have followed the documentation and some articles, but when i hit the checkout button i get this error that says NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent, what could be the issue here because everything seems to be working fine, this is the github repo.
views.py
@csrf_exempt
def create_checkout_session(request, id):
request_data = json.loads(request.body)
product = get_object_or_404(Product, pk=id)
stripe.api_key = settings.STRIPE_SECRET_KEY
checkout_session = stripe.checkout.Session.create(
# Customer Email is optional,
# It is not safe to accept email directly from the client side
customer_email = request_data['email'],
payment_method_types=['card'],
line_items=[
{
'price_data': {
'currency': 'inr',
'product_data': {
'name': product.name,
},
'unit_amount': int(product.price * 100),
},
'quantity': 1,
}
],
mode='payment',
success_url=request.build_absolute_uri(
reverse('success')
) + "?session_id={CHECKOUT_SESSION_ID}",
cancel_url=request.build_absolute_uri(reverse('failed')),
)
# OrderDetail.objects.create(
# customer_email=email,
# product=product, ......
# )
order = OrderDetail()
order.customer_email = request_data['email']
order.product = product
order.stripe_payment_intent = checkout_session['payment_intent']
order.amount = int(product.price * 100)
order.save()
# return JsonResponse({'data': checkout_session})
return JsonResponse({'sessionId': checkout_session.id})
models.py
class OrderDetail(models.Model):
id = models.BigAutoField(
primary_key=True
)
# You can change as a Foreign Key to the user model
customer_email = models.EmailField(
verbose_name='Customer Email'
)
product = models.ForeignKey(
to=Product,
verbose_name='Product',
on_delete=models.PROTECT
)
amount = models.IntegerField(
verbose_name='Amount'
)
stripe_payment_intent = models.CharField(
max_length=200,
null=True, blank=True
)
if i add null=True, blank=True to stripe_payment_intent field, it loads up the checkout page, but then no payment intent get saved in the field and i cannot return the Order Detail since, because i need to filter the order detail by the payment intent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django installed_apps is not working for me I have problem with this code. I cant do python manage.py runserver
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why SHAP values are the same every time, if kernel SHAP is based on random sample? I am learning SHAP, and have this quick question. If kernel SHAP values are estimated by randomly sampling feature values, why every time I received exactly the same SHAP values for the same model?
Any comments are very well appreciated. Thank you in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python use instance of class in a function in another file I have three files, app.py, server.py and tools.py
the files are quite big in total, so i'll just show excerpts
server.py is basically just flask
app.py looks about like this
from server import Server
from tools import Tools
if __name__ == "__main__":
web = Server(Server.defaultMainPage)
tool = Tools()
# logic
tools.py looks like this
class Tools()
def __init__(self):
# logic
def tools_func(self, args):
# logic
server.py looks like this
from flask import Flask
from tools import Tools
class Server:
# A lot of flask stuff, plus one function:
def do_smth(self, args):
# logic
# here I want to call the tool.tools_func() function
The problem is that I create an instance of Tools in app.py. In do_smth() in server.py I want to call the tools_func() from the instance of the class I created in app.py, so tool.tools_func(). How do I that?
A: You can do the follwing:
*
*Create a new method in app.py
*Import this method into server.py
*Call this method from do_smth
A: Pass the tool instance as argument to do_smth function in Server.py and call tools_func like this.
def server(self, tool):
tool.tools_func()
And in app.py you can do the following
Server.do_smth(tool)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Aligning CSS background-image with offsetted image center axis I'd like to align image files (as .png) with an offsetted image center axis using CSS's background-*-properties.
Imagine having the following document:
<div class="my-icon" data-category="1">abc</div>
<div class="my-icon" data-category="2">def</div>
<div class="my-icon" data-category="1">ghi</div>
with the following style sheet:
.my-icon {
background-position: center left;
background-repeat: no-repeat;
background-size: contain;
padding-left: 25px;
height: 30px;
display: flex;
}
.my-icon[data-category="1"] {
background-image: url('...../icon-1.png');
}
.my-icon[data-category="2"] {
background-image: url('...../icon-2.png');
}
I can align the icon as follows:
background-position: center center;
background-position: center left;
However, what I want is the following:
I'd like the image's center axis to be aligned with an axis offsetted by x pixels from the left-hand side of the div.
How is this feat achievable using pure CSS? (Without JS/JQuery?)
A: I would post a reply, as this is not actually an answer, but I don't have enough rep...
If you have the possibility of editing the HTML, I would suggest doing something like this:
<div class="wrapper">
<div class="my-icon" data-category="1" style="width: 50%;"></div> <!--image-->
<div style="width: 50%:">abc</div>
</div>
use classes instead of inline css ofcourse.
Otherwise here is an example of setting offset with percentages and statements (left, right). So something along the lines of background-position: 50% center;
A: Your HTML and CSS seems incomplete. I assume your icons are wrapped in a parent element, so I wrapped your icons in a .my-element div.
Using background-image to position elements and their backgrounds relative to a parent is very tricky. I would suggest using CSS Grid to position icons. Here's an example using display: grid
.my-element {
position: relative;
display: grid;
grid-template-columns: 1fr 1fr;
width: 200px;
height: 80px;
border: 3px solid black;
text-align: right;
padding: 0px 20px 0px 0px;
font-size: 38px;
}
.my-icon {
color: white;
font-size: 18px;
}
.my-icon[data-category="1"] {
grid-area: 1/1;
background-image: url(https://picsum.photos/450/332);
border: 2px solid green;
margin: 10px;
}
.my-icon[data-category="2"] {
grid-area: 1/1;
background-image: url(https://picsum.photos/40/40);
height: 40px;
width: 40px;
border: 2px solid red;
margin: auto;
}
<div class="my-element">
abc
<div class="my-icon" data-category="1">def</div>
<div class="my-icon" data-category="2">ghi</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fody: Copy an attribute from one property to another I iterate through all classes, then all properties, then their attributes. When I see an attribute MetaAttribute(typeof(SomethingElse)) I find a property named Target on that class and copy all of its properties across to the current property on the class in the module being worked on by the weaver...
For example
public class Person
{
[Meta(typeof(PersonTitleMeta))] // <- Identifies the source
public string Title { get; set; } // <- The target property
}
public class PersonTitleMeta
{
[Required, MinimumLength(2), MaximumLength(16)] // These get applied to Person.Title
public object Target { get; set; }
}
This works fine when the PersonTitleMeta is in the same assembly as Person
foreach (var currentSourceAttribute in sourceAttributes)
property.CustomAttributes.Add(currentSourceAttribute);
But when they are in different assemblies it does not work
System.ComponentModel.DataAnnotations.RequiredAttribute::.ctor()' is declared in another module and needs to be imported
Could someone please tell me how to copy the attribute across from a different assembly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: no response from the websocket in CMD I am trying to set up the web socket on my local WAMP server, I have followed several docs, and I am at this point. I first installed composer to then install Ratchet for the PHP, then I created 2 PHP documents:
server.php :
<?php
require 'Chat.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/www/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
Chat.php :
<?php
namespace MyApp;
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
echo "Nouvelle connexion : ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
echo "Connexion fermée : ({$conn->resourceId})\n";
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo "Erreur : ({$conn->resourceId}) : {$e->getMessage()}\n";
$conn->close();
}
}
Finally, I opened my CMD and run: php server.php
Here is the response from CMD that I got:
None, that's the problem, normally I would have received this:
Starting WebSocket server on: 0.0.0.0:8080
It is as if the program was running in a loop, like a while loop. How to solve the problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Collide function only works on first two rectangles Pygame I have generated some rectangles using a while loop in pygame and the collision with the player and the rectangle only works on the first two rectangles. The rest don't work.
CircleR = 15
player = pygame.draw.circle(screen, yellow,(x,y),CircleR)
#While loop is to generate blue rectangles
i = 1
while i < 225:
bluerect = pygame.draw.rect(screen, blue,(50,i, 10, 10))
i+=15
i = 15
collide = pygame.Rect.colliderect(player , bluerect)
if collide:
screen.fill(black)
CircleR += 1
# it refreshes the window
pygame.display.update()
pygame.quit()
I want to generate some rectangles in a line going down my screen, I have changed the y axis to "i" which will make the rectangles be generated in a line going down. What the problem is, is that when I collide my circle "player" with the rectangles, nothing happens apart from when I collide it with the first 2 rectangles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: no routes matched location using react router v6 Okay so I'm trying to build an app which consists of 2 pages, home page and a designer page. The app takes a user input value which would be a certain (url) and on clicking the navigate button in the home page, it should redirects the user from the home page to the designer page and pass this url to the designer component. The designer component should use this url to pass it to a custom hook for fetching data using my own API and then render the data in a drop-down-list. I already tested the endpoints and it works fine but the problem is that each time i try to enter the url and hit navigate it gives me an error saying that No routes matched location ./designer/"url" but if I tried to enter it in the browser itself it redirects me to the designer page and renders it fine, so I don't know what is the problem actually.
**App.jsx **
import React from "react"
import AppRouter from './Components/AppRouter'
function App() {
return (
<div>
<AppRouter />
</div>
);
};
export default App;
**AppRouter.jsx **
import React, { Component } from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./Home";
import TemplateSelector from "./TemplateSelector";
class AppRouter extends Component {
render() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="designer/:url" element={<TemplateSelector />} />
</Routes>
</BrowserRouter>
);
}
}
export default AppRouter;
**Home.jsx **
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { Form } from "react-bootstrap";
function Home() {
const [url, setURL] = useState('');
return (
<div className="py-5 container">
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1" value = {url}
onChange={(e) => setURL(e.target.value)}>
<Form.Label>URL</Form.Label>
<Form.Control type="text" placeholder="example.com" />
</Form.Group>
</Form>
<Link className="btn btn-primary btn-sm" to={`designer/${url}`}>
navigate
</Link>
</div>
);
}
export default Home;
**TemplateSelector.jsx **
import React, { useState } from "react";
import { useParams } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
import getTemplates from "../Hooks/getTemplates";
import Designer from "./Designer";
function TemplateSelector() {
const [showDesigner, setShowDesigner] = useState(false)
const onClick = () => setShowDesigner(true)
const {url} = useParams();
const data = getTemplates(url); // this line is for calling the custom hook
const templates = data.Templates; // this is the response properties
const parameters = data.Parameters; // this is the response properties
return(
<div className = "py-1 container">
<h1>Designer</h1>
<Form className="py-1 container">
<option>Select a Template</option>
<Form.Select className="form-select" aria-label="Default select example" onChange={() => onClick()}>
{templates.map((t) => (
<option key={t.Id}>{t.TemplateName}</option>
))}
</Form.Select>
</Form>
<div>
{ showDesigner ? <Designer designerURL={url} name="user" parameters={parameters} /> : null }
</div>
</div>
);
};
export default TemplateSelector;
**Designer.jsx **
import React from "react";
function Designer(props) {
return(
<div className="Generator">
<br/>
Hi This is a test for {props.name} to see the {props.designerURL} and the {parameters}.
</div>
);
};
export default Designer;`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why do i get redirected to "#blocked" in expressjs? I am trying to make a food page and I replaced the values and form actions(they get replaced with "foodidcomeshere0,1,2,3") but when I clicked the buttons(form's submit button) I get redirected to "#blocked".Why do I get redirected to "#blocked" and how can I solve it?
(I checked the form's actions with Inspect in google chrome and they are replaced correctly.)
var food_id;
var food_photo;
var food_count_2 = food_count * 4;
var food_snippet_replaced;
var food_snippet = "<div id='food-div-stack-div'><div id='food-div'><div id='food-div-photo-main-div'><div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere0' alt=''></div></div><div id='food-div-header-div'><h1 id='food-div-header'>Foodnamecomeshere0</h1></div><div id='food-div-desc-div'><p id='food-div-desc'>Foodinfocomesherea0</p></div><form action='/foodidcomeshere0' method='post'><div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div><div id='food-div-price-div'><p id='food-div-price'>0ab$</p></div></form></div><div style='width: 2vw;'></div><div id='food-div'><div id='food-div-photo-main-div'><div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere1'></div></div><div id='food-div-header-div'><h1 id='food-div-header'>Foodnamecomeshere1</h1></div><div id='food-div-desc-div'><p id='food-div-desc'>Foodinfocomesherea1</p></div><form action='/foodidcomeshere1' method='post'><div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div><div id='food-div-price-div'><p id='food-div-price'>1ab$</p></div></form></div><div style='width: 2vw;'></div><div id='food-div'><div id='food-div-photo-main-div'><div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere2' alt=''></div></div><div id='food-div-header-div'><h1 id='food-div-header'>Foodnamecomeshere2</h1></div><div id='food-div-desc-div'><p id='food-div-desc'>Foodinfocomesherea2</p></div><form action='/foodidcomeshere2' method='post'><div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div><div id='food-div-price-div'><p id='food-div-price'>2ab$</p></div></form></div><div style='width: 2vw;'></div><div id='food-div'><div id='food-div-photo-main-div'><div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere3' alt=''></div></div><div id='food-div-header-div'><h1 id='food-div-header'>Foodnamecomeshere3</h1></div><div id='food-div-desc-div'><p id='food-div-desc'>Foodinfocomesherea3</p></div><form action='/foodidcomeshere3' method='post'><div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div><div id='food-div-price-div'><p id='food-div-price'>3ab$</p></div></form></div><div style='width: 2vw;'></div></div>";
var top_value = 0;
for (var i = 0; i < food_count / 4; i++) {
var a = i * 4;
var food_snippet_2 = food_snippet.replace("Foodnamecomeshere0", JSON.stringify(food_name_result[a]).slice(14, -2));
var food_snippet_3 = food_snippet_2.replace("Foodnamecomeshere1", JSON.stringify(food_name_result[a + 1]).slice(14, -2));
var food_snippet_4 = food_snippet_3.replace("Foodnamecomeshere2", JSON.stringify(food_name_result[a + 2]).slice(14, -2));
var food_snippet_5 = food_snippet_4.replace("Foodnamecomeshere3", JSON.stringify(food_name_result[a + 3]).slice(14, -2));
var food_snippet_6 = food_snippet_5.replace("Foodinfocomesherea0", JSON.stringify(food_info_result[a]).slice(14, -2));
var food_snippet_7 = food_snippet_6.replace("Foodinfocomesherea1", JSON.stringify(food_info_result[a + 1]).slice(14, -2));
var food_snippet_8 = food_snippet_7.replace("Foodinfocomesherea2", JSON.stringify(food_info_result[a + 2]).slice(14, -2));
var food_snippet_9 = food_snippet_8.replace("Foodinfocomesherea3", JSON.stringify(food_info_result[a + 3]).slice(14, -2));
var food_snippet_10 = food_snippet_9.replace("0ab$", JSON.stringify(food_price_result[a]).slice(14, -1) + "$");
var food_snippet_11 = food_snippet_10.replace("1ab$", JSON.stringify(food_price_result[a + 1]).slice(14, -1) + "$");
var food_snippet_12 = food_snippet_11.replace("2ab$", JSON.stringify(food_price_result[a + 2]).slice(14, -1) + "$");
var food_snippet_13 = food_snippet_12.replace("3ab$", JSON.stringify(food_price_result[a + 3]).slice(14, -1) + "$");
var food_snippet_14 = food_snippet_13.replace("photocomeshere", JSON.stringify(food_photo_result[a]).slice(15, -1));
//!Food ID replacer
//TODO:Code the Photo displayer after making the admin panel
var b = a + 1;
var c = a + 2;
var d = a + 3;
var a_string = a.toString();
var b_string = b.toString();
var c_string = c.toString();
var d_string = d.toString();
var food_route = "/%7B%22Food_ID%22:%22yemek" + a_string + "%22%7D";
var food_route_2 = "/%7B%22Food_ID%22:%22yemek" + b_string + "%22%7D";
var food_route_3 = "/%7B%22Food_ID%22:%22yemek" + c_string + "%22%7D";
var food_route_4 = "/%7B%22Food_ID%22:%22yemek" + d_string + "%22%7D";
var food_snippet_15 = food_snippet_14.replace("foodidcomeshere0", food_route);
var food_snippet_16 = food_snippet_15.replace("foodidcomeshere1", food_route_2);
var food_snippet_16 = food_snippet_15.replace("foodidcomeshere2", food_route_3);
var food_snippet_17 = food_snippet_16.replace("foodidcomeshere3", food_route_4);
var food_snippet_19 = food_snippet_19 + food_snippet_17;
}
food_snippet_replaced = data.replace(food_snippet, food_snippet_19);
res.write(food_snippet_replaced);
res.end();
app.post(food_route, function(req, res) {
console.log("cihantoker");
});
#food-div-stack-div {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
padding-top: 5%;
}
#food-div-photo {
width: 100%;
}
#food-div {
border: 2px solid gray;
width: 18vw;
display: flex;
flex-direction: column;
}
#food-div-photo-main-div {
width: 100%;
padding-top: 3%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#s-div {
width: 3vw;
}
#food-div-photo-div {
width: 17vw;
height: 12vw;
border: 2px solid red;
}
#food-div-header-div {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
#food-div-header {
font-family: sans-serif;
font-size: 1.6vw;
color: gray;
}
#food-div-desc-div {
width: 100%;
text-align: center;
flex-grow: 11;
}
#food-div-desc {
font-family: sans-serif;
color: gray;
font-size: 1vw;
line-height: 2vw;
}
#food-div-add-to-the-basket-button-div {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#add-to-the-basket-button {
width: 50%;
height: 1.6vw;
background-color: #C94277;
border: 2px solid #C94277;
color: white;
font-family: sans-serif;
font-size: 0.8vw;
border-radius: 10px;
}
@keyframes food_div_button_animation {
from {
background-color: #C94277;
color: white;
}
to {
background-color: white;
color: #C94277;
}
}
#add-to-the-basket-button:hover {
animation-name: food_div_button_animation;
animation-duration: 1s;
color: #C94277;
background-color: white;
}
#food-div-price-div {
width: 100%;
padding-top: 3%;
display: flex;
justify-content: center;
align-items: center;
}
#food-div-price {
font-family: sans-serif;
font-size: 1vw;
color: gray;
}
<div id='food-div-stack-div'>
<div id='food-div'>
<div id='food-div-photo-main-div'>
<div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere0' alt=''></div>
</div>
<div id='food-div-header-div'>
<h1 id='food-div-header'>Foodnamecomeshere0</h1>
</div>
<div id='food-div-desc-div'>
<p id='food-div-desc'>Foodinfocomesherea0</p>
</div>
<form action='/foodidcomeshere0' method='post'>
<div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div>
<div id='food-div-price-div'>
<p id='food-div-price'>0ab$</p>
</div>
</form>
</div>
<div style='width: 2vw;'></div>
<div id='food-div'>
<div id='food-div-photo-main-div'>
<div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere1'></div>
</div>
<div id='food-div-header-div'>
<h1 id='food-div-header'>Foodnamecomeshere1</h1>
</div>
<div id='food-div-desc-div'>
<p id='food-div-desc'>Foodinfocomesherea1</p>
</div>
<form action='/foodidcomeshere1' method='post'>
<div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div>
<div id='food-div-price-div'>
<p id='food-div-price'>1ab$</p>
</div>
</form>
</div>
<div style='width: 2vw;'></div>
<div id='food-div'>
<div id='food-div-photo-main-div'>
<div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere2' alt=''></div>
</div>
<div id='food-div-header-div'>
<h1 id='food-div-header'>Foodnamecomeshere2</h1>
</div>
<div id='food-div-desc-div'>
<p id='food-div-desc'>Foodinfocomesherea2</p>
</div>
<form action='/foodidcomeshere2' method='post'>
<div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div>
<div id='food-div-price-div'>
<p id='food-div-price'>2ab$</p>
</div>
</form>
</div>
<div style='width: 2vw;'></div>
<div id='food-div'>
<div id='food-div-photo-main-div'>
<div id='food-div-photo-div'><img id='food-div-photo' src='/Order-Food/Food-Photos/photocomeshere3' alt=''></div>
</div>
<div id='food-div-header-div'>
<h1 id='food-div-header'>Foodnamecomeshere3</h1>
</div>
<div id='food-div-desc-div'>
<p id='food-div-desc'>Foodinfocomesherea3</p>
</div>
<form action='/foodidcomeshere3' method='post'>
<div id='food-div-add-to-the-basket-button-div'><button type='submit' id='add-to-the-basket-button'>Add To The Basket</button></div>
<div id='food-div-price-div'>
<p id='food-div-price'>3ab$</p>
</div>
</form>
</div>
<div style='width: 2vw;'></div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Joining 2 data frames with all the same columns In pandas/jupyter notebook with python:
I have a dataframe (df1) with information about the amount of crime per year where each row is a summation of the total amount of crime in that country-year unit. However, df1 does not have rows which contain "0 crime" for the years with 0 crime, and I want to add them.
I thought the easiest way to do this would be to create a blank df, (df2), with the same columns, but with all the country-years in them. Then I could add df1 data through join/merge, and change all the NaN values to 0 in df2 for years with no crime.
df1 looks like this (in excel):
df2 looks like this:
So basically I want to put df1 into the format of df2 so that I have data with all the years with 0 crime as well. I'm new to coding and not really sure how to approach this because I'm not understanding the documentation for .join and .merge. There are 18 countries and years are 2000-2020. Let me know if you have any thoughts!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tailwind CSS Flex causing icons to shrink Writing the Sidebar UI to align with the main logo - the icons have shrunk too much when each element has flex
Tried double checking code and taking on and off flex, checked for typos
UI now
Code below
const Icon = ({ styles, name, imgUrl, isActive, disabled, handleClick }) => (
<div className={`w=[48px] rounded-[10px] ${isActive && isActive === name && 'bg-[#2c2f32]'} flex justify-center items-center ${!disabled && 'cursor-pointer'} ${styles}` } onClick={handleClick}>
{!isActive ? (
<img src={imgUrl} alt="fund-logo"
className='w-1/2 h-1/2' />
) : (
<img src={imgUrl} alt="fund-logo"
className={`w-1/2 h-1/2 ${isActive !== name && 'grayscale'}`} />
)
}
</div>
)
const Sidebar = () => {
const navigate = useNavigate();
const [ isActive, setIsActive] = useState('dashboard');
return (
<div className='flex justify-between items-center flex-col sticky top-5 h-[93vh]'>
<Link to="/">
<Icon styles="w-[52px] h-[52px] bg-[#2c2f32]" imgUrl={logo} />
</Link>
<div className='flex-1 flex flex-col justify-between items-center bg-[#1c1c24] rounded-[20px] w-[76px] py-4 mt-12'>
<div className='flex flex-col justify-center items-center gap-3'>
{navlinks.map((link) => (
<Icon
key={link.name}
{...link}
isActive={isActive}
handleClick={() => {
if(!link.disabled) {
setIsActive(link.name);
navigate(link.link);
}
}} />
)
)}
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mapping of theoretical consistency models to C++ memory ordering models Wikipedia page for Consistency models list four consistency models for shared memory architecture as which require specific explicit synchronization by the programmers (in order from strongest to weakest):
*
*Weak ordering:
Classifies memory operations into two categories: 'data operations' and 'synchronization operations'. Synchronization operations signal the processor to make sure it has completed and seen all previous operations done by all processors.
*Release Consistency:
Distinguishes the entrance synchronization operation from the exit synchronization operation. During the entry to a critical section, termed as 'acquire', all operations with respect to the local memory variables need to be completed. During the exit, termed as 'release', all changes made by the local processor should be propagated to all other processors.
*Entry Consistency:
Every shared variable is assigned a synchronization variable specific to it. When the 'acquire' is to variable x, all operations related to x need to be completed with respect to that processor. When the 'release' is to variable x, all changes related to x should be propagated.
*Local Consistency:
Each process performs its own operations in the order defined by its program. There is no constraint on the ordering in which the write operations of other processes appear to be performed.
Many of these look similar to C++ memory order models. Can someone give a correct mapping of these concepts to C++ memory order models.
A: I'm not sure whether C++ memory order models are derived from these. But they do map to these consistency models pretty well.
*
*Weak Ordering:
Using C++ sequentially-consistent fences do correspond to 'synchronization operations' in weak ordering.
*Release Consistency:
This has two kinds (also mentioned in the Wikipedia page linked in question)
RCsc: Usage of C++ sequentially-consistent operations do map to 'acquire' and 'release' operations in release consistency (with sequential consistency between synchronization operations).
RCpc: Usage of C++ release-acquire operations do map to 'acquire' and 'release' operations in release consistency (with processor consistency between synchronization operations).
*Entry Consistency:
The nearest you can get to these in C++ is by using C++ release-consume operations. But in case, release operation does synchronize entire memory instead of only dependent operations. Perhaps, due to its complexity, C++ didn't bother to add a produce operation. Also note that, even though consume operation is there, in most implementations it is implemented as acquire. I also have heard that use of it is discouraged as of now.
Also, by symmetry, Entry consistency may also have two types - ECsc and ECpc - though it is not mentioned in the Wikipedia. In that case, release-consume model is near to ECpc I think.
*Local consistency:
This is the default model of single threaded C++ program. If you are using multiple threads with shared data, then have to use relaxed atomics.
I don't know where to fit release-acquire and release-consume fences. They seem to be stronger than release consistency models, but are definitely weaker than weak ordering.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: issues when connecting embedded device to the internet through local network and Virtual Box This is my setup.
connection illustration
I am connecting a Debian 11 on a Beagle Bone Black to Ubuntu22.04 on VirtualBox through ethernet cable. They form a local network with a static IP address configured and they can ping each other. Debian IP is 192.168.2.32 and Ubuntu IP is 192.168.2.5.
I want to have the Debian access to internet. The Virtual Box is running on a Windows which has access to internet through WiFi. They are in the subnet of 192.168.1.xxx. The Windows IP is 192.168.1.40 and the router IP is 192.168.1.1.
The network setting on Virtual Box is Bridge.
Tried to add gateway address to Ubuntu. The command line "route add ..." says "SIOCADDRT: network is unreachable".
Through Ubuntu GUI, the gateway address 192.168.1.1 is added and checked with "ip r" that it is actually added.
But pinging google.ca shows nothing, just stays there. And pinging 192.168.1.51 (another computer connected to the internet through the same router), shows "Destination Host Unreachable".
In Windows, ipconfig shows:
Virtualbox Host-Only network IP 192.168.56.1, no gateway.
Ethernet IP 169.254.132.184, no gateway.
WiFi IP 192.168.1.40, gateway 192.168.1.1
Is it because it doesn't work through Virtual Box or something wrong with the gateway configuration on both Ubuntu and Windows and setting with Virtual Box?
Thanks!
Crane
update:
I tried to bypass the virtualBox and connect Debian directly to Windows. Set static IP address of 192.168.2.10 for Windows ethernet and gateway of 192.168.1.1, but it isn’t allowed (not the same network segment). Instead, using networking settings to config static IP address of 192.168.2.10 and gateway 192.168.1.1 works (just warn "not the same network segment). Then Windows can ping 192.168.2.32 (Debian) and google.ca (internet). And Debian can ping the Windows (192.168.2.10) , but can’t ping google.ca (temporary failure in name resolution). It can't ping 8.8.8.8 as well (Network is unreachable).
What's something still missing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do i insert a Point / MultiPolygon in postgres ( using postgis ) with Spring data JPA? I created a map using leaflet and i'm trying to send point / multipolygon drawns to my postgres database using spring data JPA. The server initially receives a string geoJSON ( converted to org.locationtech.jts.geom.MultiPolygon and org.locationtech.jts.geom.Point by the follow deserialize methods ).
Obs: I took care that the geojson string is always valid
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.locationtech.jts.geom.MultiPolygon;
import java.io.IOException;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.geojson.GeoJsonReader;
public class MultiPolygonDeserializer extends JsonDeserializer<MultiPolygon> {
@Override
public MultiPolygon deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String geoJson = parser.getValueAsString();
GeoJsonReader reader = new GeoJsonReader();
try {
return (MultiPolygon) reader.read(geoJson);
} catch (ParseException e) {
throw new IOException(e);
}
}
}
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.locationtech.jts.geom.Point;
import java.io.IOException;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.geojson.GeoJsonReader;
public class PointDeserializer extends JsonDeserializer<Point> {
@Override
public Point deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String geoJson = parser.getValueAsString();
GeoJsonReader reader = new GeoJsonReader();
try {
return (Point) reader.read(geoJson);
} catch (ParseException e) {
throw new IOException(e);
}
}
}
They apparently work fine, returning, for example:
MULTIPOLYGON (((-42.538033 -19.461896, -42.542667 -19.489894, -42.487564 -19.478404, -42.538033 -19.461896)))
and
POINT (-42.5270802 -19.4777807)
And this is my model:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.pedro.geoPartners.util.MultiPolygonDeserializer;
import com.pedro.geoPartners.util.PointDeserializer;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.util.UUID;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
/**
*
* @author pedro
*/
@Entity
public class Partner {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private String tradingName;
private String ownerName;
private String document;
@Column(columnDefinition = "geometry(Point,4326)")
@JsonDeserialize(using = PointDeserializer.class)
private Point address;
@Column(columnDefinition = "geometry(MultiPolygon,4326)")
@JsonDeserialize(using = MultiPolygonDeserializer.class)
private MultiPolygon coverageArea;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTradingName() {
return tradingName;
}
public void setTradingName(String tradingName) {
this.tradingName = tradingName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public Point getAddress() {
return address;
}
public void setAddress(Point address) {
this.address = address;
}
public MultiPolygon getCoverageArea() {
return coverageArea;
}
public void setCoverageArea(MultiPolygon coverageArea) {
this.coverageArea = coverageArea;
}
However, when i try to save a Partner in db, i receive:
2023-03-04T17:51:39.152-03:00 WARN 116266 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: XX000
2023-03-04T17:51:39.152-03:00 ERROR 116266 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: Invalid endian flag value encountered.
2023-03-04T17:51:39.152-03:00 INFO 116266 --- [nio-8080-exec-1] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2023-03-04T17:51:39.157-03:00 ERROR 116266 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.orm.jpa.JpaSystemException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: Invalid endian flag value encountered.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676) ~[postgresql-42.5.4.jar:42.5.4]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366) ~[postgresql-42.5.4.jar:42.5.4]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356) ~[postgresql-42.5.4.jar:42.5.4]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496) ~[postgresql-42.5.4.jar:42.5.4]...
*
*I tried numerous implementantios of "JPA Attribute Converters" and always same error. Moreover, i read somewhere ( not sure ) that MultiPolygon and Point locationtech can be directly inserted in @Column(columnDefinition = "geometry(MultiPolygon,4326)") and @Column(columnDefinition = "geometry(Point,4326)").
*Also read about hibernate @Type... but apparently doens't works ( deprecated?) in hibernate spatial version 5.4.32
*Only for have sure, i tried to set coverageArea and address null before try to save in db, and it saves correctly.
My application properties:
spring.jpa.database=POSTGRESQL
spring.datasource.url=jdbc:postgresql://localhost:5432/GeoPartners?useTimeZone=true&serverTimezone=UTC&autoReconnect=true&useSSL=false
spring.datasource.username=postgres
spring.datasource.password=:)
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.sql.init.mode=ALWAYS
spring.jpa.defer-datasource-initialization=true
hibernate.dialect=org.hibernate.spatial.dialect.postgis.PostgisDialect
My pom.xml:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.pedro</groupId>
<artifactId>geoPartners</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>geoPartners</name>
<description>update of "JavaWebProject", implementing new features and Front-end</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.4.32.Final</version>
</dependency>
<dependency>
<groupId>org.locationtech.jts.io</groupId>
<artifactId>jts-io-common</artifactId>
<version>1.19.0</version>
</dependency>
<dependency>
<groupId>org.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>osgeo-alt</id>
<url>https://repo.osgeo.org/repository/release/</url>
</repository>
<repository>
<id>geomajas</id>
<name>Geomajas Maven Repository</name>
<url>http://maven.geomajas.org/(http://maven.geomajas.org/)</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Its my first question here, sorry if i made a mistake or forget something. Thank You
Tried to save a "Partner" ( model ) in a postgres db with JpaRepository "save". Expected to save all attributes but always receive same error (org.postgresql.util.PSQLException: ERROR: Invalid endian flag value encountered.) when i try to save a MultiPolygon or/and Point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TypeScript issue with framer-motion 9+ and When building a Next app using framer-motion 9.1.7 and 10.0, I get the following error:
./node_modules/framer-motion/dist/index.d.ts:1212:28
Type error: ';' expected.
1210 | declare type HydratedFeatureDefinition = {
1211 | isEnabled: (props: MotionProps) => boolean;
> 1212 | Feature: typeof Feature<unknown>;
| ^
1213 | ProjectionNode?: any;
1214 | MeasureLayout?: typeof MeasureLayout;
1215 | };
A: The problem in my case was solved by bumping TypeScript from 4.3.x to 4.9.5. Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python client receiving data from NI DataSocketServer URL I'm searching for a possibility to receive data (strings or numbers) from specific DataSocketServer URL with a simple python client.Connecting to DSS is possible with python socket library.
Example:
LabView program writes data to DataSocketServer URL dstp://localhost/wave. Python client receives data from this specific URL.
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3015)
client.connect(server_address)
#method to receive data from specific dstp URL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I split vuejs library from the main app bundle? How do I split vuejs library from my main vue component when I bundle the file with webpack?
I want something like this in the end:
Build
- Pages
---- PageContact
------ bundle.js (this file would have only my main component and other components, so no vue library here)
---- PageAccount
------ bundle.js (this file would have only my main component and other components, so no vue library here)
---- Vendors
------ vue.bundle.js (this file would have all the vue dependencies that my app needs to work)
------ otherlibraries.bundle.js
Webpack config
const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = {
mode: "development",
resolve: {
// Add `.ts` as a resolvable extension.
extensions: [".ts", ".js"],
},
optimization: {
// splitChunks: {
// cacheGroups: {
// vendors: {
// filename: "vendor.js",
// test: /[\\/]node_modules[\\/](vue|vuejs|@vue)[\\/]/,
// reuseExistingChunk: true,
// chunks: "all",
// },
// },
// },
},
module: {
rules: [
{
test: /\.vue$/,
include: path.resolve(__dirname, "src"),
loader: "vue-loader",
},
{
test: /\.ts$/,
loader: "ts-loader",
include: path.resolve(__dirname, "src"),
options: {
transpileOnly: true,
happyPackMode: true,
appendTsSuffixTo: [/\.vue$/],
},
},
],
},
entry: {
"page-account": {
import: "./src/pages/page-account/main.ts",
chunkLoading: false,
dependOn: "vendors",
},
"page-contact": {
import: "./src/pages/page-contact/main.ts",
chunkLoading: false,
dependOn: "vendors",
},
vendors: ["vue"],
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
inject: true,
chunks: ["vendors", "page-account"],
template: "src/pages/page-account/index.html",
filename: "pages/page-account/index.html",
}),
new HtmlWebpackPlugin({
inject: true,
chunks: ["vendors", "page-contact"],
template: "src/pages/page-contact/index.html",
filename: "pages/page-contact/index.html",
}),
//new BundleAnalyzerPlugin(),
],
output: {
filename: "pages/[name]/bundle.js",
path: path.resolve(__dirname, "build"),
clean: true,
},
devServer: {
hot: true,
compress: true,
port: 9000,
},
};
This is what I am getting with the bundle analyzer.
As you can see I have this compiler-core.esm-bundler.js
enter image description here
Any thoughts?
Thank you in advanced.
*
*I tried to use splitChunks, but that didn't work, the app could not load.
*The current configuration that I have, does put vue outside, but we still have the vue.compiler into the component.
*I tried the same idea with a react project, and that works very nicely, I have react and react dom into vendors library and my library only have my components code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to place tick label above grid line in matplotlib I wanted to place my tick labels just on top of the grid lines of my graph like it shows in the image below.
I tried setting the direction to 'in' and the pad to -22 in tick_params but I don't know how to move the labels slightly up to achieve what I want.
My code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# My lists
dates = []
ratings = []
fig = plt.figure()
ax = fig.add_subplot()
fig.set_facecolor('#2f3136')
ax.set_facecolor('#2f3136')
ax.spines['bottom'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.tick_params(axis='x', colors='grey')
ax.tick_params(axis='y', colors='grey',direction='in',pad=-22)
ax.yaxis.tick_right()
ax.spines[['left','top']].set_visible(False)
ax.grid(axis='y')
fig.set_figwidth(10)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_major_locator(mdates.MonthLocator())
plt.plot(dates, ratings)
And this is what I am getting
A: Set the yticklabels vertical and horizontal alignments and it should look as expected.
ax.set_yticklabels(ax.get_yticklabels(), ha="right", va="bottom")
ax.tick_params(axis='y', colors='grey', direction='in', pad=-5)
Note that the tick_params(pad) value has been reduced since the text is already right aligned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: [Nothing works!!! Support for the experimental syntax 'jsx' isn't currently enabled [URGENT] Help please, I just can't get by this error and nothing on stackoverflow seems to work. I've added @babel/preset-env, @babel/preset-react to both my .babelrc and babel.config.json files, used babel-runtime, I can't even recall all the configurations I've tested. I have used babel, webpack, rollup. Still the same error:
Support for the experimental syntax 'jsx' isn't currently enabled. Image of error
Someone please just help me with it and create a pull request.
Github: https://github.com/benhexie/angel-form
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How useCallback in React optimizes performance? The React docs claims that "useCallback is a React Hook that lets you cache a function definition between re-renders."
How is it possible to cache function definitions? This example is taken from React docs:
import { useCallback } from 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productid, referrer]);
How is it possible to prevent the callback passed to useCAllback from being created? As far as I know, the JS runtime will create a new instance of the callback each time the ProductPage function is called (I have tested this behavior in JavaScript code).
What is useCallback optimizing? I also assumed that React calls the ProductPage function on every render.
I have searched Stackoverflow and google. I expect an explanation on why using useCallback is beneficiary.
A: Let's re-order the questions a little:
How is it possible to prevent the callback passed to useCallback from being created?
It is not possible. The function ProductPage is called every time the component is instantiated, which creates a new instance of the (orderDetails) => { ... } callback.
But – when we use useCallback, React uses the previous value unless any of the deps has changed, essentially throwing away the new instance.
How is it possible to cache function definitions?
It's caching the value of the function itself. A standard dynamic cache would require an extra unique key to store/retrieve the cached value; since React's rules of hooks ensure that each instance of a hook within a component instance has a fixed position, there is no explicit cache key required.
What is useCallback optimizing?
useCallback stabilises the callback value – essentially, the function doesn't change unless it needs to change because one of the dependencies has changed.
On its own, this doesn't optimise anything – there is, of course, a cost associated with tracking the cached value and its dependencies. If, however, the callback is passed to other components or hooks, then it may cause re-rendering or other work. A self-contained if slightly contrived example:
function useNotifier(instances, value) {
// Notify all instances when value changes
const notifyAll = useCallback((value) => {
instances.forEach(instance => instance.notify(value));
}, [instances]);
useEffect(() => {
notifyAll(value);
}, [notifyAll, value]);
}
If we don't stabilise notifyAll using useCallback, then the value of the callback changes every time the hook is rendered, even if the instances and value have stayed the same.
The useCallback docs do go into better explanations of the situations in which stabilising a function using useCallback (and similarly useMemo) can reduce the amount of work done in re-renders, in particular a couple of deep dives towards the bottom.
A:
How is it possible to prevent the callback passed to useCallback from being created?
It's not possible, you're right on that. But that's not what useCallback is aiming at.
The optimisation that useCallback enables is when using handleSubmit (i.e. the return value of useCallback) as a dependency of other hooks, e.g. useMemo or useEffect. But on its own, it's pretty useless.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How does this implementation of negative log-likelihood quantify uncertainty? What is this function doing and how does it quantify uncertainty? I find negative log-likelihood quite difficult to understand in general.
def nll_gaussian(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
scaled: bool = True,
) -> float:
"""Negative log likelihood for a gaussian.
The negative log likelihood for held out data (y_true) given predictive
uncertainty with mean (y_pred) and standard-deviation (y_std).
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of the predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
scaled: Whether to scale the negative log likelihood by size of held out set.
Returns:
The negative log likelihood for the heldout set.
"""
# Check that input arrays are flat
assert_is_flat_same_shape(y_pred, y_std, y_true)
# Set residuals
residuals = y_pred - y_true
# Compute nll
nll_list = stats.norm.logpdf(residuals, scale=y_std)
nll = -1 * np.sum(nll_list)
# Potentially scale so that sum becomes mean
if scaled:
nll = nll / len(nll_list)
return nll
What is the logpdf doing? What does the function tell us?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get also 0 from the string (Regular expression) how to get also 0 from this string, this is how I try,/thanks
[^\s\/][\w\s]+[^\s\/]
....text..text./..text.text.text...../.0....... (dots = spaces)
https://regex101.com/r/FeXsEH/1
i need array, without '/' and ' all spaces':
text text
text text text
0
A: This was quite a hard and interesting one:
(?!\s)[\w\s]*(?<!\s)
Explanation:
*
*(?!\s) If it doesn't have space in front, continue with the step below
*[\w\s]* match as many alphanumeric characters and spaces.
*(?<!\s) and match nothing if it doesn't have space before, meaning it has a alphanumeric character, therefore ending the match right there and not capture any extra spaces.
A: We can also describe the expetected extraction as:
start with word characters with one single padding space, keep repeated pattern and then the last word without padding space.
The above can translated into the following regex:
(\w+\s)*\w+
Output in regex101 link:
text text
text text text
0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you close/stop tab in vimscript? I use a command in a function like the one below:
execute "normal! i\begin\r\<tab>somethinghere\r\\end"
and I am expecting this result:
\begin
somethinghere
\end
But instead I get:
\begin
somethinghere
\end
How do I "stop" the tab?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows command prompt in Python I have the following code which captures traffic packets, write them into a traffic.pcap file, then convert the pcap to text file using the tshark. If I enter the full path and name of the files in the last line, the code works perfectly, however it is always overwriting the files, so I added the lines to add time to each file so I can save all, the sniff and write commands work as expected, they create a new name each time I run it and save the file with the new name, however, when the code reaches the last line, it does not recognize the name of the file (source and destination) to read and convert, any help would be appreciated.
from scapy.all import *
import time
import os
# Create a new unique name
if os.path.exists('D:/folder/traffic.pcap'):
file_name = ('D:/folder/traffic_{}.pcap'.format(int(time.time())))
# Create a destination file
txt_file = file_name + '.txt'
# Sniff traffic and write to a file *.pcap
x = sniff(count=10)
wrpcap(file_name,x)
# Convert pcap file to txt file usign tshark command
#os.system('cmd /c "tshark -i - < "D:/folder/traffic.pcap" > "D:/folder/traffic.txt""')# working line
os.system('cmd /c "tshark -i - < %file_name% > %txt_file%"')#not working line
The output is generated by the last line is The system cannot find the file specified.
A: %file_name% is a cmd variable.
You need to use the python variable.
You can access the python variable via
f'cmd /c "tshark -i - < {file_name} > {txt_file}"'
(An f string f"string", works like .format.)
The system call does not run in python. It forks (well creates) a new process. After creation, the processes do not communicate. Not even pipes. You can use the process module to create processes with some interprocess communication, however they won't have access to each other's variables.
The replacement line is: os.system(f'cmd /c "tshark -i - < {file_name} > {txt_file}"')
You may also wish to consider bash as your shell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Snake Game in C Graphics isn't working as it should I'm building the classic snake game using c graphics.
There is no errors in my code, however, the game isn't working as it should.
here are the problems I found:
*
*The game doesn't end until the snake touch halfway threw the border, and sometimes it doesn't even touch it, it just be near to it.
*When the snake eat the food, only the part that it touched disappear.
*The food sometimes appear on the border so the snake can't reach it.
here is the source code:
#include <graphics.h>
#include <time.h>
// This function draw the borders of the game feild.
void borders(int value) {
bar(0, 0, 720, value);
bar(0, 0, value, 720);
bar(720-value, 0, 720, 720);
bar(0, 720-value, 720, 720);
}
// This function is to draw the snake and the food
void draw(int x, int y) {
bar(x-10, y-10, x+10, y+10);
}
// This function returns a random number between 20 and 720
int random() {
srand(time(NULL));
return rand()%661+30;
}
int main() {
int gd, gm, value=20, i=0, snakeX[100], snakeY[100], snakeLength=5, foodX=1, foodY=1, direction=0;
detectgraph(&gd, &gm);
initgraph(&gd, &gm, NULL);
initwindow(720, 720);
setactivepage(0);
setfillstyle(1,1);
borders(value);
snakeX[i] = snakeY[i] = 360; //Put the snake in the center
setfillstyle(1,14);
draw(snakeX[i], snakeY[i]); //Draw the snake
for(i=1; i<snakeLength; i++) {
snakeX[i]=snakeX[0]-(i*value);
snakeY[i]=snakeY[0];
draw(snakeX[i], snakeY[i]);
}
setfillstyle(1,5);
while(getpixel(foodX, foodY)!=0) {
foodX=random();
foodY=random();
}
draw(foodX, foodY); //Draw the food with random coordinations
delay(1000);
while(1) {
setfillstyle(1,0);
draw(snakeX[snakeLength-1], snakeY[snakeLength-1]); //Let the the sanke fade as it moves
for(i=snakeLength-1; i>0; i--) {
snakeX[i]=snakeX[i-1];
snakeY[i]=snakeY[i-1];
}
if(direction==0) //Right
snakeX[0]+=value;
else if(direction==90) //Up
snakeY[0]-=value;
else if(direction==180) //Left
snakeX[0]-=value;
else if(direction==270) //Down
snakeY[0]+=value;
if((getpixel(snakeX[0],snakeY[0])==1)||(getpixel(snakeX[0],snakeY[0])==15)) //If the snake hits the border or itself
break;
if((GetAsyncKeyState(VK_RIGHT)) && (direction!=180))
direction=0;
else if((GetAsyncKeyState(VK_UP)) && (direction!=270))
direction=90;
else if((GetAsyncKeyState(VK_LEFT)) && (direction!=0))
direction=180;
else if((GetAsyncKeyState(VK_DOWN)) && (direction!=90))
direction=270;
if(getpixel(snakeX[0], snakeY[0])==5) { //If the snake hits the food
foodX=1; foodY=1;
setfillstyle(1,5);
while(getpixel(foodX, foodY)!=0) {
foodX=random();
foodY=random();
}
draw(foodX, foodY); //Put food in a new place
snakeLength++;
}
setfillstyle(1,14);
for(i=0; i<snakeLength; i++) //Make the snake taller
draw(snakeX[i], snakeY[i]);
delay(100);
}
while(!GetAsyncKeyState(VK_RETURN));
closegraph();
getch();
return 0;
}
I inspired my code from this correct one I found on the internet:
https://www.mediafire.com/file/fvn30jrh6ateb2v/Snake.c/file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
} |
Q: Stuck in a redirection loop I got a web hosting service which got a text file name Redirect.txt, what Im trying to do is do a check every 5 seconds using intrevals, so basically every 5 seconds im sending a fetch request to a text file and if the content is not equal to # ill redirect the user to the content of the file. Im also doing another check so the user wouldnt get redirected infinitely, im just using a var named usedLink, if the text file content is not equal to usedLink it will redirect the user.
Here is my code:
var usedLink;
setInterval(read_redirect(), 5000);
function read_redirect(){
var url = `${SERVER_HOST}/Redirect.txt`;
fetch(url, {
mode: "no-cors"
})
.then(response => response.text())
.then(data => {
const textData = data;
console.log(textData + ": used");
if (textData != "#" && textData != usedLink) {
usedLink = textData;
console.log(usedLink + " : USED LINK")
location.href = textData;
}
})
.catch(error => console.error(error));
}
I tried adding a small delay before the redirection so the response to the fetch request could reach the server, but the user is still being redirected non stop.
However this is my output:
https://youtube.com/: used
https://youtube.com/ : USED LINK
: used
: USED LINK
: used
: USED LINK ... and so on
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pydub can't find file Am using OpenAI's API to do a transcription of a very long video (2 hrs long), as suggested by the documentation, am trying to split it in shorter sections using the Pydub library.
I do not know why I keep getting the "FileNotFoundError", I've tried from hardcoding the path to the audio file on my desktop, to currently opening a TKinter window to choose it from there.
The above methods were implemented on a different part of the project and I cannot tell why with this library it doesn't work.
I've also tried pre-opening it with the "read binary" flag but no luck.
Any help appreciated
import os
from pathlib import Path
from pydub import AudioSegment
import tkinter
from tkinter import filedialog
tkinter.Tk().withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
audio_file = open(file_path,"rb")
audioFull = AudioSegment.from_file(audio_file)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Kubernetes - connect to Azure SQL using Active Directory ID We have an AKS POD (.NET 6 application) which can successfully connect to an Azure SQL database with SQL Server auth - user and password.
However, when used with an Active Directory ID, it throws a remotecertificatename mismatch error. This AKS cluster has istio configured. If used with a cluster which doesn't have Istio enabled, I can connect using Active Directory ID and password.
I tried adding service entries with *.database.windows.net, destination rule with tls disabled, none of these work. I validated certificate against digicert utility page, and certificatename matches. So, not sure where the mismatch issue is coming from.
Any suggestions are much appreciated.
The SSL connection could not be established, see inner exception.
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.CompleteHandshake(SslAuthenticationOptions sslAuthenticationOptions)
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I run into a discord.gateway warning "Shard ID None heartbeat blocked for more than x seconds." my simple bot checks of it got a .json file from an API, if it did, then the bot outputs some info and then deletes that .json file. But if it did not, then it checks again until there is a .json file in that directory.
Bot actually works fine, but I get a warning Discord.gateway warning "Shard ID None heartbeat blocked for more than x seconds."
Can it crush my bot? Because the bot is supposed to be constantly running.
import discord
from discord.ext import commands
import os
import json
import time
from config import TOKEN
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.AutoShardedBot(shard_count=2, command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
@bot.command()
async def example(ctx):
while True:
try:
f = open("result.json", "r")
result = json.load(f)
await ctx.send(f"some message, {result['name']}")
os.remove("/home/user/Projects/project_folder/result.json")
except FileNotFoundError:
continue
if __name__ == "__main__":
bot.run(TOKEN)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QtAndroid: Grant Usb Permission in Android with Qt6 in android programming you need to get usb permission before working with connected device to client device.
i am trying to connect a hack-rf to android device and use it... but first of all i need to get usb permission and detect that hackrf.
setup:
1- qt6.3.0
2- ndk 21.3.6528147
3- ui with QML
this is my c++ code to get permission of storage:
bool checkAppPermissions(QString permission)
{
auto result = QtAndroidPrivate::checkPermission(permission).result();
if (result == QtAndroidPrivate::Denied) {
auto result2 = QtAndroidPrivate::requestPermission(permission).result();
qDebug() << permission << result2;
if (result2 == QtAndroidPrivate::Denied)
return false;
else {
return true;
}
}
else {
return true;
}
}
and it's usage:
checkAppPermissions("android.permission.WRITE_EXTERNAL_STORAGE")
but i cannot get usb permisson this way.. its not working.
in AndroidManifest.xml i put these:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.usb.host"/>
also i think the permission that i had to get is "com.android.example.USB_PERMISSION" but i dont know how should i Grant or request for that.
this kotlin code works fine... it detects device and gets the permission but i don't know how it is working! or how can i implement it in Qt with cpp.
i also see this answer but i dont know how he uses C++ native side code or MyActivity.java
could you help me to detect device and grant it's permission at run time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails Git post-receive hooks doesn't start Puma I have two almost identical post-hooks script that behaves differently. This is the one that doesn't work, Rails 7 API-only, Debian 11:
#!/bin/bash
GIT_DIR=/home/deploy/api.mydomain.com
WORK_TREE=/home/deploy/apps/api.mydomain.com
. ~/.profile
while read oldrev newrev ref
do
if [[ $ref =~ .*/main$ ]];
then
echo " Main ref received. Deploying main branch to production..."
mkdir -p $WORK_TREE
git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f main
mkdir -p $WORK_TREE/shared/pids $WORK_TREE/shared/sockets $WORK_TREE/shared/log
# start deploy tasks
cd $WORK_TREE
bundle install
rake db:migrate
echo " Killing existing process.."
kill $(lsof -t -i:3002)
echo " Starting puma..."
bundle exec puma -C config/puma.rb -e production > /dev/null 2>&1 &
echo " Puma is running"
#echo "Restarting sidekiq..."
#sudo systemctl restart sidekiq.service
#echo "Sidekiq is running"
# end deploy tasks
echo "✅ Git hooks deploy complete"
else
echo "Ref $ref successfully received. Doing nothing: only the main branch may be deployed on this server."
fi
done
It doesn't work because I end up always need to run bundle exec puma -C config/puma.rb -e production > /dev/null 2>&1 & manually from the WORK_TREE.
However, this is the one that works, Rails 6, Debian 11:
#!/bin/bash
GIT_DIR=/home/deploy/myproject-production
WORK_TREE=/home/deploy/apps/myproject-web
. ~/.profile
while read oldrev newrev ref
do
if [[ $ref =~ .*/main$ ]];
then
echo "Main ref received. Deploying main branch to production..."
mkdir -p $WORK_TREE
git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f main
mkdir -p $WORK_TREE/shared/pids $WORK_TREE/shared/sockets $WORK_TREE/shared/log
# start deploy tasks
cd $WORK_TREE
echo "--> Selecting Node version in the .nvmrc"
. $HOME/.nvm/nvm.sh
nvm use
yarn install
bundle install
rake db:migrate
bin/rails webpacker:clobber
bin/rails assets:precompile
echo "Killing existing process.."
kill $(lsof -t -i:3000)
echo "Starting puma..."
bundle exec puma -C config/puma.rb -e production > /dev/null 2>&1 &
echo "Puma is running"
echo "Generating sitemap..."
rake sitemap:refresh
echo "Sitemap done"
echo "Restarting sidekiq..."
sudo systemctl restart sidekiq.service
echo "Sidekiq is running"
# end deploy tasks
echo "Git hooks deploy complete"
else
echo "Ref $ref successfully received. Doing nothing: only the main branch may be deployed on this server."
fi
done
It kills the running puma correctly, then restart the puma from the WORK_TREE.
I'm aware it might be environment issue in which they run, but it should work the same. I notice one storage behaviour though, whenever I ssh to the first box, it loads the ˜/.profile directly, judging by the colorful $user in the console, but the second box it's not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: google cloud. upsert large csv file by chunks start to take a lot longer than expected I have a large csv files of prices that I want to upsert to a postgres table. I am reading it with pandas by chunks then uploading it into a temp table, then copy the temp table into the prices table and finally dropping the temp table. Locally this is really fast. each chunk takes 18s, and the file of 18M rows takes 14 minutes. In the google cloud run however, the first 3 chunks take 17s, the 4th one take 42s, the 5th takes 102s and after that the chunks take btween 100 and 120s (sometimes more).
my cloud run has 2 CPUs, Concurrency 200, 1GB of RAM with CPU is only allocated during request processing. My SQL isntance has 1CPU and 628 MB of Memory.
Here is the upsert code:
import time
import pandas as pd
from sqlalchemy.pool import NullPool
from aldjemy.core import get_engine
import uuid
from typing import List
import pandas as pd
import sqlalchemy as sa
engine = get_engine(connect_args={'connect_timeout': 3600, 'pool_size': NullPool})
i = 0
with pd.read_csv("prices.csv", chunksize=350000) as reader:
for prices in reader:
time.sleep(0.01)
i=i+1
print("chunk number %s" %str(i))
t = time.time()
try:
_ = df_upsert(data_frame=prices, engine=engine, table_name=ModelPrice._meta.db_table, match_columns=['id', 'date'])
except Exception as e:
raise Exception(f"{self.__class__.__name__}: {str(e)}")
elapsed = time.time() - t
print('price data upserted. TOTAL elapsed = %d' %elapsed)
and df_upsert:
def df_upsert(data_frame: pd.DataFrame, table_name: str, engine: sa.engine.Engine, match_columns: List[str]=None):
"""
Perform an "upsert" on a PostgreSQL table from a DataFrame.
Constructs an INSERT … ON CONFLICT statement, uploads the DataFrame to a
temporary table, and then executes the INSERT.
Parameters
----------
data_frame : pandas.DataFrame
The DataFrame to be upserted.
table_name : str
The name of the target table. Note that this string value is injected
directly into the SQL statements, so proper quoting is required for
table names that contain spaces, etc. A schema can be specified as
well, e.g., 'my_schema."my table"'.
engine : sa.engine.Engine
The SQLAlchemy Engine to use.
match_columns : list of str, optional
A list of the column name(s) on which to match. If omitted, the
primary key columns of the target table will be used. Note that these
names *are* automatically quoted in the INSERT statement, so do not
quote them in this list, e.g., ["my column"], not ['"my column"'].
"""
df_columns = list(data_frame.columns)
if not match_columns:
insp = sa.inspect(engine)
match_columns = insp.get_pk_constraint(table_name)[
"constrained_columns"
]
temp_table_name = f"temp_{uuid.uuid4().hex[:6]}"
columns_to_update = [col for col in df_columns if col not in match_columns]
insert_col_list = ", ".join([f'"{col_name}"' for col_name in df_columns])
stmt = f"INSERT INTO {table_name} ({insert_col_list})\n"
stmt += f"SELECT {insert_col_list} FROM {temp_table_name}\n"
match_col_list = ", ".join([f'"{col}"' for col in match_columns])
stmt += f"ON CONFLICT ({match_col_list}) DO UPDATE SET\n"
stmt += ", ".join(
[f'"{col}" = EXCLUDED."{col}"' for col in columns_to_update]
)
with engine.begin() as conn:
t = time.time()
conn.exec_driver_sql(
f"CREATE TEMPORARY TABLE {temp_table_name} AS SELECT * FROM {table_name} WHERE false"
)
elapsed = time.time() - t
print('TEMPORARY TABLE created. elapsed = %d' %elapsed)
t = time.time()
data_frame.to_sql(temp_table_name, conn, if_exists="append", index=False)
elapsed = time.time() - t
print('dataframe written to TEMPORARY TABLE. elapsed = %d' %elapsed)
t = time.time()
conn.exec_driver_sql(stmt)
elapsed = time.time() - t
print('TEMPORARY TABLE copied into price table. elapsed = %d' %elapsed)
t = time.time()
engine.execute(f'DROP TABLE "{temp_table_name}"')
elapsed = time.time() - t
print('TEMPORARY TABLE dropped. elapsed = %d' %elapsed)
I have tried:
*
*Reducing the chunk size (to 100k). Smaller chunks is worse actually. Relatively each chunk becomes slower.
*Deleting the prices table and rebuilding the index and doing an upsert with on empty table.
*Increase RAM and CPU on cloud run
*Use CPU always allocated on cloud run
None of them worked.
A little more details on the timing breakdown:
first 3 chunks:
Temp Table creation: 0s
Copy to Temp table: 9s
Copy from Temp table to prices table: 7-9s
Drop Temp table: 0s
Afterwards:
Temp Table creation: 0s
Copy to Temp table: 48s
Copy from Temp table to prices table: 74s
Drop Temp table: 0s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fixing the seed in QuantLib UniformRandomGenerator() I am simulating paths of the Hull-White One Factor process using the following code and I am wondering how I can fix the seed of the UniformRandomGenerator(). I have tried writing UniformRandomGenerator(seed=0), but it keeps returning variable paths.
import QuantLib as ql
import matplotlib.pyplot as plt
import numpy as np
sigma = 0.1
a = 0.1
timestep = 3
length = 1 # in years
forward_rate = 0.05
day_count = ql.Actual365Fixed()
todays_date = ql.Date(15, 1, 2015)
ql.Settings.instance().evaluationDate = todays_date
spot_curve = ql.FlatForward(todays_date, ql.QuoteHandle(ql.SimpleQuote(forward_rate)), day_count)
spot_curve_handle = ql.YieldTermStructureHandle(spot_curve)
hw_process = ql.HullWhiteProcess(spot_curve_handle, a, sigma)
rng = ql.GaussianRandomSequenceGenerator(ql.UniformRandomSequenceGenerator(timestep, ql.UniformRandomGenerator(seed=0)))
seq = ql.GaussianPathGenerator(hw_process, length, timestep, rng, False)
def generate_paths(num_paths, timestep):
arr = np.zeros((num_paths, timestep+1))
for i in range(num_paths):
sample_path = seq.next()
path = sample_path.value()
time = [path.time(j) for j in range(len(path))]
value = [path[j] for j in range(len(path))]
arr[i, :] = np.array(value)
return np.array(time), arr
num_paths = 1
time, path = generate_paths(num_paths, timestep)
for i in range(path.shape[1]):
print(path[0][i])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove enclosing square brackets in an awk string How can I remove enclosing square brackets in an awk string?
For instance, I would have a variable dgt with value [[:digit:]] and want to remove the outer enclosing square brackets.
Currently my solution is very naive.
retval = substr(dgt, 2, length(dgt)-2)
A: Using gsub where ^ is the beginning of the string and $ the end.
% awk 'BEGIN{str = "[[:digit:]]"; gsub(/^\[|\]$/, "", str); print str}'
[:digit:]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gtk3 Invalid cast from 'GtkHeaderBar' to 'GtkMenuShell' I recently upgraded from debian 11 bullseye to debian 12 bookworm and noticed that
gtk was upgraded from 3.24.24-4 to 3.24.36-4
and
glib was upgraded from 2.66.8-1 to 2.74.5-1.
I have a Gtk3 application which was working fine on debian 11, but now throws several Glib-GObject warnings.
The application uses client side decorations with GtkHeaderBar and a small menu on each window's headerbar.
The warning is:
Glib-GObject-WARNING **: 16:15:37.638: invalid cast from 'GtkHeaderBar' to 'GtkMenuShell'
Does anyone know if there is an easy solution to this or would it be better to remove client side decorations?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using sharp with formidable I try to use sharp with formidable in order to resize my image and change the format but it does not work as expected.
The ceeated file is not with the correct format and the correct extension.
My code :
form.on('fileBegin', function(name, file) {
if (file.name !== '') {
var ext = file.name.match(/\.(jpg|jpeg|JPG|png|webp|pdf|ico|ttf|otf)$/i)[0],
newFileName = crypto.createHmac('sha1', 'test')
.update(file.name)
.digest('hex') + new Date()
.getTime();
file.path = './public/uploads/' + newFileName + ext;
}
});
form.on('file', async function(name, file) {
if (file.name !== '') {
var fileBuffer = fs.readFileSync(file.path),
sharpImage = sharp(fileBuffer);
sharpImage.resize({500, 500}).toFormat(sharp.format.webp);
}
});
With this code, I got this file :
*
*0e3deab581ff7c29f146bef8ac679fa7c603dad71677965394628.jpg (same height, width and extension as the original file)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In VS Code, is there a way to auto create JS/CSS files and/or directories when adding HTML link/script tags if the files don't exist yet? I understand the standard workflow is to create your directories and files first, but sometimes I want to add additional styling/scripting files without switching to the sidebar or terminal. So trying to see a way to auto create the JS/CSS files and directories when adding the HTML <link> & <script> tags, if the files and/or directories don't exist yet.
For example, adding <script type="text/javascript" src="my-script-file.js"></script> tag to your dir/index.html file, would create dir/my-script-file.js. I know if the files already exist, either intellisense or an extension can suggest the path to link to, but I’m trying to add the tag first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Docker desktop container config Using Docker Desktop(dd) with Redis it gives the port 32768:6379 making it impossible to access from local command prompt. How can I configure Docker Desktop to effectively run docker run -d -p 6379 :6379 redis --port 6379 thereby expecting to access the container from localhost? Do I need to run dockerd and load run the command manually? Or how best to run docker and access the redis in the docker container from command prompt and development tools?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cloud shell refers to an incorrect organization ID I am able to create a new project with the same user account, but I cannot seem to do this from cloud shell.
I get the following error:
failed: 7: Permission 'resourcemanager.projects.create' denied on parent resource 'organizations/{someId}'.
The problem is I have no idea what this someId is. It definitely does not refer the the orgID my project (from which I am running this) is a child of.
I tried to see if it's something in my environment variables, but don't see anything. Is this a known bug?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to render a response from Onsnapshot in React I am trying to render the answer I receive from an Onsnapshot in Firebase. The problem is that I do not know how to assign the value I receive to a variable, since it is what I need to be able to render it in React.
const unsub = onSnapshot(doc(db, "incrementCounter", "counter"), (doc) => {
console.log(doc.data().contador);
});
The answer is a number of a counter.
This is my problem practically.
How to get data from firestore DB in outside of onSnapshot
The result looks good in the console, but I have read that being an asynchronous response, the result cannot be assigned to a variable.
But I don't know how to solve it, it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Site wont render as soon as button is added around I am trying to make a dynamic and good looking picture gallery but i am having a problem. Since i want the images to be clickable (so i can expand them) i need to wrap a button around the images. For some reason this is crashing react. I tried around 5 different ways of implementing the button. Sadly none worked
My Code currently looks like this:
import { useState, useEffect } from 'react';
import "./styles/gallery.css"
import Masonry, {ResponsiveMasonry} from 'react-responsive-masonry';
function Gallery() {
const [pictures, setPictures] = useState([]);
const [popup, togglepopup] = useState(false);
useEffect(() => {
const importPictures = async () => {
const context = require.context('../pictures/gallery', false, /\.(png|jpe?g|svg)$/);
const files = context.keys();
const pictures = await Promise.all(files.map(async (file) => {
const image = await import(`../pictures/gallery/${file.slice(2)}`);
return {
src: image.default,
alt: file.slice(2, -4),
};
}));
setPictures(pictures);
};
importPictures();
}, []);
return (
<div className="galleryElements">
<ResponsiveMasonry columnsCountBreakPoints={{300: 1, 750: 2, 900: 3, 1400: 4, 1900: 5, 2100: 6}}>
<Masonry gutter='1rem'>
{pictures.map((picture) => (
<button className='elementButton' type="button" onClick={togglepopup(!popup)}>
<img className="element" src={picture.src} alt={picture.alt} key={picture.alt} />
</button>
))}
</Masonry>
</ResponsiveMasonry>
</div>
);
}
export default Gallery;
If i remove the button everything works and is rendered correctly. If it is in there only the background color is rendered. Nothing else. No Navbar, no Footer etc.
If you know any other way of making the popout feature possible i would be glad to hear it.
A: You can use onClick in your <img/> you don't really need <button> to do that :
<img
className="element"
src={picture.src}
alt={picture.alt}
key={picture.alt}
onClick={() => {
togglepopup(!popup)
}}
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a simple image editor to add and manipulate emoticons in WPF I've been searching the net for a solution in WPF, but can't find anything. I am almost sure that there is a ready-made library that meets my requirements. I want to add a very simple image editor to my application, that allows me to overlay emoticons and other image icons on an image at runtime. Similar to how this works on Instagram for example. I have a background image and want to overlay emoticons on top of it and manipulate them in size and rotation angle. Does anyone know something suitable? I am grateful for any help. My own attempts to build something have been only moderately successful so far.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Render innerHTML inside .html() Trying to Sanitize a text HTML and render it inside another html , this is what I tried,
$(document).ready(function(){
$("button").click(function(){
$("p").html(sanitizeHTML("Hello <b>world!</b>"));
});
});
function sanitizeHTML(str){
var temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
}
Getting output as
Hello <b>world!</b>
Need proper HTML as
Hello world!
Here is a working sample to try out,
https://jsfiddle.net/mb9ksq3z/
Please note this is not another remove HTML from text question , the whole point is to sanitise the HTML for open vulnerabilities for 'Fortify Code Scans' and directly putting string inside .html() is direct vulnerability.
A: change your function to:
function sanitizeHTML(str)
{
let tmp = document.createElement("div");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: STRING_SPLIT -Query is adding more lines rather then allocating serial number in sequence I am trying to split Serial No of a order item table , which has string separated values. I am able to separate the value but serial no allocation is not happening correctly, Its just showing additional rows.
Table has data like
OrderID OrderItemID Item Price SerialNo
100 101 P1 200.50 OW52288-OW52289-OW52290-OW52291-OW52292-OW52293
100 102 P1 200.50 NULL
100 103 P1 100.50 NULL
100 104 P1 300.40 NULL
100 105 P1 600.30 NULL
100 106 P1 300.50 NULL
100 107 P1 500.70 NULL
100 108 P1 200.60 NULL
100 109 P1 800.60 NULL
Result coming
OrderID OrderItemID Item Price value
100 101 P1 200.50 OW52288
100 101 P1 200.50 OW52289
100 101 P1 200.50 OW52290
100 101 P1 200.50 OW52291
100 101 P1 200.50 OW52292
100 101 P1 200.50 OW52293
Required result
OrderID OrderItemID Item Price SerialNo
100 101 P1 200.5 OW52288
100 102 P1 200.5 OW52289
100 103 P1 100.5 OW52290
100 104 P1 300.4 OW52291
100 105 P1 600.3 OW52292
100 106 P1 300.5 OW52293
100 107 P1 500.7 NULL
100 108 P1 200.6 NULL
100 109 P1 800.6 NULL
--Can please help me
Table & query I am writing
CREATE TABLE dbo.TestOrderItemSerial(
[OrderID] [int] NOT NULL,
[OrderItemID] [int] NOT NULL,
[Item] [nvarchar](50) NULL,
[Price] [money] NOT NULL,
[SerialNo] [nvarchar](100) )
Insert into dbo.TestOrderItemSerial values
(100,101,'P1',200.50,'OW52288-OW52289-OW52290-OW52291-OW52292-OW52293')
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price)values
(100,102,'P1',200.50)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,103,'P1',100.50)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,104,'P1',300.40)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,105,'P1',600.30)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,106,'P1',300.50)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,107,'P1',500.70)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,108,'P1',200.60)
Insert into dbo.TestOrderItemSerial (OrderID,OrderItemID,Item,Price) values
(100,109,'P1',800.60)
select OrderID,OrderItemID,Item,Price,value
FROM dbo.TestOrderItemSerial with (nolock)
CROSS APPLY String_Split(REPLACE(REPLACE((
CASE WHEN CHARINDEX('-',SerialNo) = 3 THEN REPLACE (SerialNo,'-','')
WHEN CHARINDEX(' ',SerialNo) = 3 THEN REPLACE (SerialNo,' ','')
WHEN CHARINDEX(' ',SerialNo) = 6 THEN REPLACE (SerialNo,' ','-')
ELSE SerialNo END)
,',','-'),'/','-'),'-')
Data can be like this also
A: Probably a few ways you can approach this, none particularly pretty as dealing with delimited strings just isn't nice.
You need to split the string into ordered rows that can join to your existing table.
If you were using SQL Server 2022 (16) then string_split would be fine, however for SQL Server 2019 it is not always guaranteed rows will be returned in order, so other methods like using a json array can be used.
Try the following which splits the string(s) and assigns a sequential number on which to join:
with s as (
select t.OrderId, j.SerialNo,
Row_Number() over(partition by Orderid order by t.OrderItemID, j.Seq) seq
from TestOrderItemSerial t
cross apply (
select j.[value] SerialNo, 1 + Convert(tinyint, j.[key]) Seq
from OpenJson(Concat('["',replace(Serialno, '-', '","'),'"]')) j
)j
where t.SerialNo is not null
), t as (
select *, Row_Number() over(partition by OrderId order by OrderItemId)Seq
from TestOrderItemSerial t
)
select t.OrderId, t.OrderItemId, t.Item, t.Price, s.Serialno
from t
Left join s on s.OrderId = t.OrderId and s.Seq = t.Seq
order by OrderId, t.Seq;
Here is a demo fiddle
A: I like using a function for this kind of thing when I can't fix the data (which is the right thing to do). Assuming SQL Server 2016 or better (always good to tell us via a tag on the question, like sql-server-2019):
CREATE OR ALTER FUNCTION dbo.SplitOrdered_JSON
(
@List varchar(max),
@Delimiter varchar(10)
)
RETURNS table WITH SCHEMABINDING
AS
RETURN
(
SELECT seq = [key] + 1, value
FROM OPENJSON(N'["' + REPLACE(STRING_ESCAPE(@List, 'JSON'),
@Delimiter, '","') + '"]') AS x
);
Now the query is:
WITH sn AS
(
SELECT t.OrderID, j.seq, j.value
FROM
(
SELECT t.OrderID, sn = STRING_AGG(t.SerialNo, '-')
WITHIN GROUP (ORDER BY t.OrderItemID)
FROM dbo.TestOrderItemSerial AS t
WHERE t.SerialNo > '' GROUP BY t.OrderID
) AS t CROSS APPLY dbo.SplitOrdered_JSON(t.sn, '-') AS j
),
Orders AS
(
SELECT OrderID, OrderItemID, Item, Price,
rn = ROW_NUMBER() OVER (PARTITION BY OrderID ORDER BY OrderItemID)
FROM dbo.TestOrderItemSerial
)
SELECT o.OrderID, o.OrderItemID, o.Item, o.Price, sn.value
FROM Orders AS o
LEFT OUTER JOIN sn
ON o.OrderID = sn.OrderID
AND o.rn = sn.seq
ORDER BY o.OrderID, o.OrderItemID;
*
*Example db<>fiddle demonstrating both cases in the question
With the new information, sure, we can handle any number of delimiters. Slash, space, dash, pencil... you name it. We can just use TRANSLATE() to convert them all to dashes first:
WITH sn AS
(
SELECT t.OrderID, j.seq, j.value
FROM
(
SELECT t.OrderID, sn = STRING_AGG(
TRANSLATE(t.SerialNo, N'/ ✎',N'---'), N'-')
------^^^^^^^^^--------------- only change
WITHIN GROUP (ORDER BY t.OrderItemID)
FROM dbo.TestOrderItemSerial AS t
WHERE t.SerialNo > '' GROUP BY t.OrderID
)
AS t CROSS APPLY dbo.SplitOrdered_JSON(t.sn, '-') AS j
),
...
*
*Updated db<>fiddle example
But please, please, please consider storing your data properly in the first place. Seems whoever designed this system forgot about the R in RDBMS - if these serial numbers are independent pieces of data, they should always be stored separately and never shmeared together like goop.
And please state all of your requirements up front. When you post half of the info, people who are volunteering their valuable time might only help you solve half of the problem, but they waste potentially all of their time. See chameleon questions and How do I ask a good database question?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Converting JSON to Pandas Dataframe Text Issue I am trying to load information from a HTTP request and store it as a JSON file:
here is how I am loading the data:
try:
response = requests.get(url)
except requests.exceptions.ConnectionError as e:
print("ConnectionError:", e)
try:
data = json.loads(response.text)
except JSONDecodeError:
if "Bad Gateway" in response.text:
print("Bad Gateway, sleeping.")
else:
print("JSONDecodeError, data not loaded")
if data and data["response"]["status"] == 200:
for m in data["messages"]:
record = {}
record["id"] = m["id"]
record["text"] = m["body"]
tweets.append(record)
tweets is a list of dictionaries containing all the information I got from the HTTP request.
I then save the list of dictionaries as a JSON file like this:
fileName = "stuff/{}/{}.json".format(symbol, Id)
with open(fileName, "w",encoding="utf-8") as f:
json.dump(tweets, f,ensure_ascii=False)
I try to load the JSON as a dataframe like this:
with open('thefile.json', 'r', encoding='utf-8') as f:
data = json.load(f)
df = pd.read_json(json.dumps(data), orient='records')
The text in my JSON file looks like this:
"i felt awful to not cash out the 145 puts on Thursday open"
When I check my dataframe ( df.head() ) the text looks like this:
"ℎℎ145ℎ"
I am using jupyter notebook to view the data
I tried converting the dataframe to a Numpy array ( a = df["text"].values ) and when I printed out the text it looked fine.
Can some explain why is this? Is there a problem with my data or does df.head() just print out some data in a weird style?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: data not refatching after invalidate query in react0query i using react-query for fetching some data in my admin panel website. after mutation i am in onSuccess function invalidate query. this invalidate working currect bot cuery does not clear in ReactQueryDevtools and not refatching updated data.
this is my code
[enter image description here](https://i.stack.imgur.com/mB9K2.png)[enter image description here](https://i.stack.imgur.com/h5hED.png)
i using refresh token in interceptor axios, firstly i thinking this is a problm but my new request for reftching does not send
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add a detected object in cost map that generated from move_base package How can I add a detected object in cost map that generated from move_base package.
Car is detecting traffic light and road line in simulation but how can add this property in coast map because the car has to go from one point to another by following the traffic rules and it uses sensors such as lidar imu camera gps.
I thought of adding the detected objects to the map. Generating map and giving koordinate data from code isn't hard but i can't find adding detected object in cost map and navigating car.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get NGINX to redirect rather than append a redirected address? I'm trying to get webmail.example.com to redirect to www.example.com/mail
This is the conf file setting I have:
http {
include /etc/nginx/conf-enabled/*.conf;
include /etc/nginx/sites-enabled/*.conf;
server {
listen 80;
listen 443 ssl;
server_name webmail.example.com;
return 301 https://www.example.com/mail$request_uri;
}
}
What the browser kicks back when I try to go to webmail.example.com is:
webmail.example.com/://www.example.com/mail/://www.example.com/mail/. . .
and then throws a 414 error because the url is too long. What am I missing here?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75638836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |