QuestionId
stringlengths
8
8
AnswerId
stringlengths
8
8
QuestionBody
stringlengths
91
22.3k
QuestionTitle
stringlengths
17
149
AnswerBody
stringlengths
48
20.9k
76383987
76384806
I am following this tutorial on creating notifications However, I cannot seem to do the following: NotificationManager notificationManager = getSystemService(NotificationManager.class); Because my Android studio reports the error: Required Type: Context Provided: Class <android.app.NotificationManager> reason: Class<N...
Notification Manager getSystemService() call not working
I found this was my solution: NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
76382344
76382710
In modern Fortran, we can call a subroutine from C by using C binding. E.g. The Fortran subroutine will look like this subroutine my_routine(...) bind (C, name="my_routine") However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution. What would be the best alterna...
Can an f77 subroutine be called from C?
However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution. It depends. Modern Fortran is largely backwards compatible with Fortran 77. Your F77 subroutine will not come with a bind attribute, but if you're willing to add one and compile it with a modern Fortra...
76382433
76382759
I apologize from the start as I am not allowed to share the workbook I am working on (it has confidential information from work) but I will do my best to explain what is happening and what my issue is. I have two sheets, "Tracker" and "Reviewers". In the tracker names are recorded in column L and their submission is re...
How can I make an adaptive list to check against another adaptive list?
=LET(d,DROP(FILTER(A:B,A:A<>""),1), n,INDEX(d,,1), s,INDEX(d,,2), u,UNIQUE(n), m,MMULT(--(TOROW(n)=u),--(s="")), HSTACK(u,m)) Change the filter range (and maybe the lines to drop) and the index numbers to your situation. I think this would work in your case: =LET(d,DROP(FILTER(Tracker!$L$4:$M$4999...
76382452
76382772
Is it technically impossible to show the data outside of the list? I searched through the internet but I couldn't get any answers at all smh -_- I wanted to display the value of data rows of the list besides of the section ListViewBuilder. Output: [ ListView Builder Screen ] Name: You, Age: 20 Name: Him, Age: 20 A...
How to show the data of the list outside of the area of ListView Builder in Flutter?
So... if it's the same list, just add this : Instead : Container( child: Text("Display the data here, How?") ) Do : SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: userList ...
76380806
76381408
I'm attempting to call a callable cloud function (which is already deployed) from a client app and getting this error on the GCP logs: { httpRequest: {9} insertId: "647865c20002422d2d32b259" labels: {1} logName: "projects/faker-app-flutter-firebase-dev/logs/run.googleapis.com%2Frequests" receiveTimestamp: "2023-06-01T0...
Firebase Cloud Functions V2: The request was not authorized to invoke this service
Open https://console.cloud.google.com/iam-admin/<project_name>, find the service account you are using in your firebase project and add the Rol "Cloud Functions Invoker". Is like Admin, Editor or Viewer roles are about manipulating the function on GCP (don't allow you to use it) and Invoker allows that account to invo...
76384708
76384807
I'm using NiFi 1.21.0 and nifi-marklogic-nar-1.9.1.6. I have been using PutMarkLogic 1.9.1.6 processor to ingest documents to MarkLogic-db for more than 2 years. Recently witnessed that the processor doesn't support adding document-quality (PFB the processor image). So I have created a new issue against marklogic/nifi...
How to set document quality while ingesting document into MarkLogic through PutMarkLogic NiFi processor?
This enhancement was fixed as part of https://github.com/marklogic/nifi/pull/121. Therefore use nifi-marklogic-nar-1.15.3.1 or later version to set document-quality. I'm currently using PutMarkLogic 1.16.3.2 and I can now see a provision to add Quality.
76381224
76381430
I have used the below code to Loop through selection on outlook and convert into Hyperlinks and change Text To Display Link. it works but it adds the the ascending number incrementally to all cells like this picture: My need is to add the ascending number per each row like this picture: In advance, great thanks for a...
Loop through rows of a table on outlook and change (Text To Display) to an ascending number per each row
Try looping through rows first (the following is not tested): Sub Hyperlink_Outlook() Dim wDoc As Word.Document, rngSel As Word.Selection, cel As Cell, i As Long Dim r As Variant Set wDoc = Application.ActiveInspector.WordEditor Set rngSel = wDoc.Windows(1).Selection If Not rngSel Is Nothing And rngS...
76382642
76382822
I have df which has 5 columns. A column named date which has minute-wise data of a few days but the data start at 9:15 and ends at 15:29. And then there are four other columns which are named first, max, min, and last which have numerical numbers in them. I wrote a code that uses x mins as a variable. It resamples the ...
Resampling Rows minute wise not working in for Even Minutes in Python DataFrame
Use: resampled_df = df.resample(x_minutes, origin = 'start').agg({ 'first': 'first', 'max': 'max', 'min': 'min', 'last': 'last' })
76384685
76384818
If i have a toggle, which updates its state from external async load but also by user intput, how can i differentiate those two? eg. to perform a special action on user action Group { Toggle(isOn: $on) { EmptyView() } } .onChange(of: on) { newValue in was "on" changed by ...
SwiftUI Toggle how to distinguish changing value by UI action vs changing programatically
If you want a side effect for use the user actions, you can use a custom wrapper Binding: struct ContentView: View { @State private var on: Bool = false var userManagedOn: Binding<Bool> { .init { return on } set: { newValue in print("Side effect") on = ne...
76380987
76381434
<input type="checkbox" id="darkmode-toggle" class="peer invisible h-0 w-0" /> <label for="darkmode-toggle" class="btn-toggle group"> <svg class="icon absolute"> <use href="../../assets/icons/spirit.svg#sun" /> </svg> <svg class="icon absolute group-[peer-checked]:fill-secondary-dark-300"> <...
How can I change the color of an icon when a checkbox is checked using Tailwind?
You could consider using group-[.peer:checked+&]:: tailwind.config = { theme: { extend: { colors: { 'secondary-dark-300': 'red', }, }, }, }; <script src="https://cdn.tailwindcss.com"></script> <input type="checkbox" id="darkmode-toggle" class="peer invisible h-0 w-0" /> <label for="da...
76380618
76381442
In onblur I need to call alert(), but this doesn't work in Chrome and Firefox. Sess https://jsfiddle.net/mimomade/5sur482w/1/ In Firefox :focus-visible stays after leaving the 2nd and 4th input field and is not removed. In Chrome I can't leave the 2nd input field. Although the 1st doesn't has any problem.
Javascript - alert problem with onblur and focus-visible Firefox/Chrome
At the very bottom is the code with both bugs fixed. You're initial JavaScript looks like this: // Has different bugs in Firefox and Chrome. function blurring(el) { console.log(el.id + ' pre alert'); alert('blurring ' + el.id); console.log(el.id + ' post alert'); } In Firefox, your apparent bug actually masks a...
76382726
76382845
I'm pretty new to TypeScript, as well as using the T3 stack (React Query / Tanstack Query). I'm trying to type companyId as string, so that I don't have to type companyId as string every time I use it later on it in the code, but I can't figure out how to best to that or what the best practice is with this stack... I'...
How to type NextJS router.query.id as string?
You can use optional chaining and nullish coalescing in combination with the query params' toString() method, heres an example based on your code snippet: const CompanyPage: NextPage = () => { const router = useRouter(); // this result will be of type string const companyId = useMemo(() => { return router.qu...
76384713
76384822
I was trying to use a state variables value inside another state variable, but when the other sub state variable was updated outside, its updated value didn't get reflected in parent state variable, why did this happened? can I not use state variable inside another state variable or is there any specific way to use it?...
Tried to use state variable inside another state variable, but it didn't work as expected it to, Why ? (in ReactJS using function component)
Could you add how you update your state(s)? But in general, states are not bound or connected to each other. If you change one state, it won't update any other state. const [rooms, setRooms] = useState([ { roomNo: 1, noOfPersons: noOfPersonsForRoom[0], ageOfPerson1: ageOfPerson1ForRoom[0], ...
76382432
76382854
I am trying to write code in R for a dataset to check if DAYS column have consecutive numbers and print out the missing DAYS number, in such a way that, if the count of missing consecutive numbers between two rows of the DAYS column equals to that count+1 in the corresponding last row of the PERIOD column, exclude it f...
What is the best way to check for consecutive missing values in a data column in R and exclude them based on a related column value?
I've managed to do this using tidyverse tools: Set up example data I've tweaked your data slightly to show that the solution can handle longer runs of missing days. library(vroom) library(dplyr) library(tidyr) test <- vroom( I( "days period 161 1 162 1 163 1 166 3 167 1 168 1 169 1 170 1 172 1 "), col_types = c(...
76380830
76381444
I have an entity Person @Entity @Data public class Person { @Temporal(TemporalType.DATE) private Calendar dob; } And some dao classes @Data public class PersonResponse { @JsonFormat(pattern = "yyyy-MM-dd") private Calendar dob; } @Data public class PersonRequest{ @DateTimeFormat(pattern = "yyyy-MM-dd") ...
Spring Boot Wrong date returned
If Applicable try to switch from class Calendar to LocalDate. LocalDate does not take time zone into consideration. This should resolve your issue (and simplify your code). Also, for formatting the LocalDate with Json see the answer to this question: Spring Data JPA - ZonedDateTime format for json serialization
76384705
76384834
I am trying to monkey patch a missing import. The old_invoke() still does not get the import. In case it is relevant, MyClass is a gdb.Command. (gdb) pi >>> import mymodule >>> old_invoke = mymodule.MyClass.invoke >>> def new_invoke(self, *k, **kw): ... print("New invoke") ... import getopt ... old_invoke(self, *...
Python: Fix missing import with a monkey patch
old_invoke is trying to reference mymodule's getopt, which doesn't exist. You need: >>> import mymodule >>> old_invoke = mymodule.MyClass.invoke >>> def new_invoke(self, *k, **kw): ... print("New invoke") ... import getopt ... ... # here ... mymodule.getopt = getopt ... ... old_invoke(self, *k, **kw) .....
76382691
76382862
I am trying to create an image of Windows with additional things. My question is whether it is possible to include a specific volume when creating the container. For example, I would like to do: docker run --name container -v shared:c:\shared -it mcr.microsoft.com/windows/servercore:20H2-amd64 powershell There I am acc...
Adding a volume in dockerfile
Using VOLUME in dockerfile does not mount the volume during build, this only specifies a target where a directory can be mounted during container runtime (anonymous volume). Because image build and container run can happen on different machines, so having VOLUME source defined in dockerfile (buid time) does not make se...
76381353
76381491
I want to implement brush cursor like in most image editors when cursor is a circle that change its size according to brush size. I've read the docs and found only setShape method, but no setSize. Is it possible in Qt to change cursor size?
How to change cursor size in PyQt5?
pixmap = QPixmap("image.png") # Replace with the path to your custom cursor image, brush in your case pixmap = pixmap.scaled(30, 30) # Set the desired size cursor = QCursor(pixmap) self.setCursor(cursor) you can change the size and the "form" of your cursor in PyQt5 by creating a pixmap and then assigning in to your...
76384330
76384840
Encoding honestly continues to confuse me, so hopefully this isn't a totally daft question. I have a python script that calls metaflac to compare the flac fingerprints in a file to the flac fingerprints of a file. Recently I came across files with » (https://bytetool.web.app/en/ascii/code/0xbb/) in the file name. This ...
subprocess.run command with non-utf-8 characters (UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb)
I believe coding of "latin1" or "cp1252" will do decode that successfully. Also, it is easier to deal with strings than with bytes, so here is my suggestion: import pathlib import subprocess directory = pathlib.Path("/tmp") with open(directory / "data.ffp", "r", encoding="latin1") as stream: for line in stream: ...
76382379
76382881
There are several StackOverflow posts about situation where t.test() in R produce an error saying "data are essentially constant", this is due to that there is not enough difference between the groups (there is no variation) to run the t.test(). (Correct me if there is something else) I'm in this situation, and I would...
Optimize data for t.test to avoid "data are essentially constant" error
Finding the sd of Mean for each Date-Species combination and then filtering out any Dates where any sd is 0 will do the trick. You could even just pipe the filtered data to compare_means(): library(dplyr) library(ggpubr) data <- data.frame(Date = c("2021.08","2021.08","2021.09","2021.09","2021.09","2021.10","2021.10",...
76384487
76384848
Here is my simple code: package org.example; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.ty...
Trying to run simple code that writes a dataframe as a csv file using spark and Java. java.lang.NoClassDefFoundError: org/apache/spark/sql/Dataset
Avoid using compileOnly directive for dependencies which implementation will be needed during runtime as stated on Gradle's Java library plugin user guide https://docs.gradle.org/current/userguide/java_library_plugin.html and blog https://blog.gradle.org/introducing-compile-only-dependencies
76380747
76381513
I have two items positioned vertically, and I'd like the narrower one is as wide as the wider one. My code looks like <div class="flex flex-col items-end"> <div>This should take all the space</div> <div class="flex flex-row gap-x-4"> <div> this is the first element</div> <div> this is the second element</di...
Give same width to items vertically positioned
You could shrink-wrap the container and then right align it: <script src="https://cdn.tailwindcss.com"></script> <div class="flex flex-col w-max ml-auto"> <div>This should take all the space</div> <div class="flex flex-row gap-x-4"> <div> this is the first element</div> <div> this is the second element</...
76382807
76382905
I'm trying to send messages to my users from my server using Pusher Channels. My api receives a list of users and the message needs to be sent to all the users in the list. I can't group these users into a single channel and an individual channel has to be used for each user. This makes my api slow as the list of users...
Is there a better way to publish messages using Pusher Channels' batch event?
If you are sending the same event to multiple channels then you can use the standard trigger endpoint but specify a list of the channels that you are broadcasting to. For example: using PusherServer; var options = new PusherOptions(); options.Cluster = "APP_CLUSTER"; var pusher = new Pusher("APP_ID", "APP_KEY", "APP_S...
76384790
76384880
I'm currently trying to webscrape websites for tables using pandas and I get this error for one of the links. Here's a snippet of what causes the crash: import pandas as pd website_df = pd.read_html("https://ballotpedia.org/Roger_Wicker") print(website_df) Below is the error I get, does anyone know how to fix this? Tr...
Pandas Webscraping Errors
Set header=0. You're going to get a lot of dataframes, but you can parse them to get what you need. website_df = pd.read_html("https://ballotpedia.org/Roger_Wicker", header=0)
76381459
76381521
I am using fluentbit as a pod deployment where I am creating many fluentbit pods which are attached to azure blob containers. Since multiple pods exist I tried adding tolerations as I did on daemonset deployment but it did not work and failed. Also every time I delete and start the pods reinvests all the the again. Ple...
Adding tolerations to fluentbit pod and making it persistent
The tolerations attribute needs to be set on the pod, but you are attempting to set it on a container (that's why you see the error "unknown field "tolerations" in io.k8s.api.core.v1.Container"). You would need to write: apiVersion: v1 kind: Pod metadata: name: deployment spec: volumes: - name: config_map_name ...
76382480
76382917
I am trying to create a playbook where I want to perform a simple debug task after cpu load is below 2.0. I have this so far in cpu-load.yml: --- - name: Check CPU load and wait hosts: localhost gather_facts: yes tasks: - name: Check cpu load shell: uptime | awk -F 'load average:' '{print $2}' | awk ...
Ansible - starting a task after cpu load is below 2.0
You need to put an until loop around your "check cpu load" task: - hosts: localhost gather_facts: false tasks: - name: Check cpu load shell: uptime | awk -F 'load average:' '{print $2}' | awk -F ', ' '{print $1}' register: cpu_load until: cpu_load.stdout|float < 2.0 retries: 300 de...
76382514
76382923
How to load a separate JS file in Shopware 6 using webpack? What? I'm trying to load a separate javascript file next to the all.js file by using WebPack. Why? The all.js file can get really big and you're loading unnecessary javascript on a page. So by using code splitting (which should be possible since WebPack is imp...
How can I use Webpack to load a separate JS file in Shopware 6 and improve web performance?
This will not work since all pre-compiled assets of plugins are collected in the ThemeCompiler and concatenated into one single script. This is done in PHP since node is not a requirement for production environments. You could try to add separate scripts as additional custom assets, but you would still have to extend ...
76384679
76384898
Context: I have a datacube with 3 variables (3D arrays, dims:time,y,x). The datacube is too big to fit in memory so I chunk it with xarray/dask. I want to apply a function to every cell in x,y of every variable in my datacube. Problem: My method takes a long time to load only one cell (1 minute) and I have to do that 1...
Chunked xarray: load only 1 cell in memory efficiently
I find that explicitly iterating over the xarray is faster than isel(), by about 10%. Example: for var_name, var_data in xrds.data_vars.items(): # if variable is 3D if var_data.shape == (xrds.dims['time'], xrds.dims['y'], xrds.dims['x']): # Iterate through every cell of the variable al...
76381460
76381528
I have the data below: time=c(200,218,237,237,237,237,237,246,246,246,257,257,257,272,272,272,294,294,294) location=c("A","A","D","C","A","B","B","D","C","B","D","C","B","D","C","B","D","C","B") value=c(0,774,0,0,2178,0,2178,0,1494,2644,1326,1504,4188,3558,1385,5013,12860,829,3483) dataA=data.frame(time,location,value)...
How to change colors when using scale_fill_discrete in R?
I think you need scale_fill_discrete(type = c(...)). library(ggplot2) ggplot(data=dataA, aes(x=time, y=value))+ geom_area(aes(group=location, fill=location), position="stack", linetype=1, size=0.5 ,colour="black") + scale_fill_discrete(breaks=c("A","B","C","D"), labels=c("Main_town","B","C","D"), ...
76381485
76381539
I have the following code: var expressions = new List<IQueryable<Container>>(); var containers1 = containers .Where(x => EF.Functions.Like(x.ContainerReference1, $"%{message.SearchValue}%") || EF.Functions.Like(x.ContainerReference2, $"%{message.SearchValue}%")) .OrderBy(x => x.ContainerReference1...
C# IQueryable .Union reset sorting
Union operator does not preserve the order of the elements. You need to dynamically construct the sorting logic based on the presence of data var expressions = new List<IQueryable<Container>>(); var sortingExpressions = new List<Func<IQueryable<Container>, IOrderedQueryable<Container>>>(); var containers1 = containers...
76381526
76381562
I have a .json file but I got the tokenId numbering wrong. I need to increase all values of "tokenId" by 1 number [ { "Background": "Red", "Body": "Tunn", "Hat": "Bambu", "Outfit": "Pirate", "Expression": "Sad", "Accessory": "Rifle", "tokenId": 0 }, { ...
How can I use Python to increment 'tokenId' values in a .json file?
To increase the values of the "tokenId" field in your JSON file by 1, you can modify your code as follows: import json with open('traits.json') as f: data = json.load(f) for item in data: item['tokenId'] += 1 with open('new_data.json', 'w') as f: json.dump(data, f) In your original code, you were trying...
76382811
76382942
I have created an index file so that the information entered here is added to the created element this is for a review section the index.html file is here, and includes the CSS and js let name = document.querySelector('.name').value; let message = document.querySelector('.message').value; let btn = docume...
Update input values into elements only JS
Your name variable should be a pointer to the element, not the value. Also, you should clear the input after adding. const name = document.querySelector('.name'), message = document.querySelector('.message'), btn = document.getElementById('button'), div = document.querySelector('.items'); const handleAdd = (...
76381469
76381565
I have the following xml: <?xml version="1.0" encoding="utf-8"?> <wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.opengis.net/wfs/2.0 http://www.wfs.nrw.de/aaa-suite/schema/ogc/wfs/2.0/wfs.xsd" timeStamp="2023-06-...
How to extract data from xml in NodeJS?
You need to set ignoreAttributes option to false import { XMLParser } from "fast-xml-parser"; const XMLdata = `<?xml version="1.0" encoding="utf-8"?> <wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.opengis.net/wfs/2...
76384843
76384912
I use Retrofit and Coroutines to fetch a list of languages from an API. My ViewModel loads the list of languages whenever it is created. I want to load this list into a spinner, but whenever I update the spinner data, the data in the ViewModel hasn't completely loaded. Here my viewmodel class to load data from an api c...
How can I update my UI after a coroutine is completed in Kotlin for Android?
In Your case update your viewmodel as below- class TranslateViewModel : ViewModel() { private val _langList = MutableLiveData<List<String>>() val langList: LiveData<List<String>> get() = _langList init { viewModelScope.launch { if (langList.isSuccessful && langList.body() != null) {...
76382497
76382988
I'm working on a block based programming language based of of Google's Blockly. I need to make a block that loops the contents forever, for making games. I tried a while (true) loop but it froze. Is there any way to make a forever loop that won't freeze and will let other scripts run? Thanks!
How to make a forever loop in JS not freeze
check setTimeout() : https://developer.mozilla.org/en-US/docs/Web/API/setTimeout Something like that to loop indefinitely without blocking the main thread (you should probably design a way to break the loop at some point) : function doSomeStuff() { // do some stuff… setTimeout(() => { doSomeStuff(); }, 1000);...
76384804
76384938
[Why am i getting "formula parse error" when I try to classify the ages (column H) into groups using the following formula? And is there a better way? Thanks for your assistance: =IF (H19<20, “0-19”, IF ((H19>=20 AND H19<40), “20-39”, IF ((H19>=40 AND H19<60), “40-59”, IF ((H19>=60 AND H19<70), “60-69”, IF (H19>=70, ">...
What is the correct syntax to classify ages into groups using IF statements in Google Sheets?
The portions that you have formatted as (H19>=20 AND H19<40) should be changed to AND(H19>=20, H19<40). Your final formula should then be: =IF(H19<20, “0-19”, IF(AND(H19>=20, H19<40), “20-39”, IF(AND(H19>=40, H19<60), “40-59”, IF(AND(H19>=60, H19<70), “60-69”, IF(H19>=70, ">= 70", “WRONG”))))) Alternatively: =...
76381508
76381592
So what I have is two Pandas dataframes in Python with a large number of xyz-coordinates. One of them will be used to mask/remove some coordinates in the other one, but the problem is that the coordinates are very slightly different so that I cannot simply remove duplicates. As an example, let's say they look like this...
Masking a pandas column based on another column with slightly different values
You can use numpy broadcasting to consider the individual distances between the coordinates: # convert DataFrames to numpy arrays a1 = df1.to_numpy() a2 = df2.to_numpy() # define a distance below which the coordinates are considered equal thresh = 500 # compute the distances, identify matches on all coordinates match...
76382887
76382994
I have the following little program in Python from pathlib import Path filename = Path("file.txt") content = "line1\nline2\nline3\n" with filename.open("w+", encoding="utf-8") as file: file.write(content) After running it I get the following file (as expected) line1 line2 line3 However, depending on where the pro...
How to fix the line ending style (either CRLF or LF) in Python when written a text file?
It is possible to explicitly specify the string used for newlines using the newline parameter. It works the same with open() and pathlib.Path.open(). The snippet below will always use Linux line endings \n: from pathlib import Path filename = Path("file.txt") content = "line1\nline2\nline3\n" with filename.open("w+", e...
76382888
76383031
I have many JSON files with the following structure: { "requestId": "test", "executionDate": "2023-05-10", "executionTime": "12:02:22", "request": { "fields": [{ "geometry": { "type": "Point", "coordinates": [-90, 41] }, "colour": "blue", "bean": "blaCk", "bir...
Partially flatten nested JSON and pivot longer
I would suggest simply extracting what you need. It seems very specific for it to be solved using specific parsing. Therefore I would start by creating two dataframes: df_prediction = pd.DataFrame(example['response']['results'][0]['predictions']) df_data = pd.DataFrame({x:y for x,y in example.items() if type(y)==str},i...
76383903
76384969
This question is connected to [-> here]. I would like to reorganize the following nested dict please: a = { (0.0, 0.0): {'a': [25, 29, nan]}, (0.0, 2.0): {'a': [25, 29, nan], 'b': [25, 35, 31.0]}, (0.0, 4.0): {'b': [25, 35, 31.0]}, (2.0, 0.0): {'a': [25, 29, nan], 'c': [25, 26, 29.0]}, (2.0, 1.5): {'a': [25, 29, n...
Reorganize nested `dict`
You can use: out = {} for k1, d in a.items(): for k2 in d: out.setdefault(k2, {})[k1] = list(d.values()) Output: {'a': {(0.0, 0.0): [[25, 29, nan]], (0.0, 2.0): [[25, 29, nan], [[25, 35, 31.0]]], (2.0, 0.0): [[25, 29, nan], [[25, 26, 29.0]]], (2.0, 1.5): [[25, 29, nan], [[25, 26, 29.0...
76381414
76381603
How can I make the bellow regex exclude matches that span across lines? import re reg = re.compile(r'\b(apple)(?:\W+\w+){0,4}?\W+(tree|plant|garden)') reg.findall('my\napple tree in the garden') reg.findall('apple\ntree in the garden') The first one should match, the second one should not. (Now both matches...)
How to exclude linebreaks from a regex match in python?
Your \W matches newlines. To exclude them replace \W with [^\w\n]: import re reg = re.compile(r'\b(apple)(?:[^\n\w]+\w+){0,4}?[^\n\w]+(tree|plant|garden)') print(reg.findall('my\napple tree in the garden')) # [('apple', 'tree')] print(reg.findall('apple\ntree in the garden')) # []
76381292
76381604
I'm creating a nestjs API so I'm using classes to declare my entities for example export class Customer { id: number; name: string; } So now I'm working in my Customer Controller and I would like to type an get query param as customer.id because I'm thinking if some day the customer id data type changes to string auto...
How to declare a constant datatype using a class property datatype in typescript?
You can use TypeScript lookup types: getCustomerById(@Params('id') id: Customer['id']) {}
76384902
76384970
I have two data frames t1 and t2. I want a seaborn plot where it plots side by side for every variable using the for loop. I was able to achieve this but I fail when I try to set the customized x labels. How do I incorporate set_xlabel in to the for loop? data1 = { 'var1': [1, 2, 3, 4], 'var2': [20, 21, 19, 18]...
Different X Labels for Different Variables
Use zip: for col, new_label in zip(t1.columns, xlabels_list):
76382981
76383058
I am trying to add the corresponding value from df to df1 for each time the name and week match in df1 df Name Week Value 0 Frank Week 3 8.0 1 Bob Week 3 8.0 2 Bob Week 4 8.0 3 Elizabeth Week 3 4.0 4 ...
Add pre-defined value to DataFrame on each instance of matching index
Use a merge + assign: out = (df1 .merge(df, how='left') .assign(Total=lambda d: d['Total'].add(d.pop('Value'), fill_value=0)) ) Output: Name Week Total 0 Frank Week 1 16.0 1 Frank Week 1 3.0 2 Frank Week 3 36.0 3 Frank Week 3 9.0 4 Frank Week 4 3.0 ... 5 Daniel Week 2 50.0 ...
76384338
76384983
I am processing sales data, sub-setting across a combination of two distinct dimensions. The first is a category as indicated by each of these three indicators ['RA','DS','TP']. There are more indicators in the data; however, those are the only ones of interest, and the others not mentioned but in the data can be ignor...
Looping through combinations of subsets of data for processing
IIUC, you can use : def crossubsets(df): labels = ["RA", "DS", "TP"] time_intervals = [7, 30, 60, 90, 120, None] group_dfs = df.loc[ df["Association Label"].isin(labels) ].groupby("Association Label") data = [] for l, g in group_dfs: for ti in time_intervals: s = ( ...
76381561
76381629
I'm using the Boston Housing data set from the MASS package, and working with splines from the gam package in R. However, an error is returned with this code: library(gam) library(MASS) library(tidyverse) Boston.gam <- gam(medv ~ s(crim) + s(zn) + s(indus) + s(nox) + s(rm) + s(age) + s(dis) + s(rad) + s(tax) + s(ptrat...
How to find columns with three or fewer distinct values
Would this work? You can use dplyr::n_distinct() to perform the unique check. # Number of unique values n_unique_vals <- map_dbl(Boston, n_distinct) # Names of columns with >= 4 unique vals keep <- names(n_unique_vals)[n_unique_vals >= 4] # Model data gam_data <- Boston %>% dplyr::select(all_of(keep))
76381619
76381632
I have a layout like this: <com.google.android.material.textfield.TextInputLayout android:id="@+id/user_description_input_layout" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="16dp" android:layout_marginTop="16dp" and...
Android - How to make the height of a TextInputEditText to be exactly of 2 lines?
Try this, in your TextInputEditText android:minLines="2" android:gravity="top"
76384389
76384989
I have a PostMapping whith form where user can create a meeting and invite employees. My problem is that the employees are not saved to the database. Here is my MeetingDTO: @Data @Builder public class MeetingDto { private Long id; @NotEmpty(message = "Content could not be empty") private String contentOfMee...
Spring boot + JPA problem with post mapping form where is select multiple
While reviewing your code, I noticed a potential issue with how the relationships are handled in JPA/Hibernate. When you're dealing with related entities, in this case Meeting and Employee, it's crucial to manage both sides of the relationship correctly. In your code, you're assigning employees to a meeting using meeti...
76382806
76383084
I a df like this my_df <- data.frame( b1 = c(2, 6, 3, 6, 4, 2, 1, 9, NA), b2 = c(100, 4, 106, 102, 6, 6, 1, 1, 7), b3 = c(75, 79, 8, 0, 2, 3, 9, 5, 80), b4 = c(NA, 6, NA, 10, 12, 8, 3, 6, 2), b5 = c(2, 12, 1, 7, 8, 5, 5, 6, NA), b6 = c(9, 2, 4, 6, 7, 6, 6, 7, 9), b7 = c(1, 3, 7, 7, 4, 2, ...
How to group variables that falls within a range of numbers
You can use between from dplyr: my_df %>% mutate(NEW = case_when( b9 <= 2 ~ "Yellow", between(b9, 4, 7) ~ "white", b9 >= 9 ~ "green" )) Output: b1 b2 b3 b4 b5 b6 b7 b8 b9 NEW 1 2 100 75 NA 2 9 1 NA 4 white 2 6 4 79 6 12 2 3 8 5 white 3 3 106 8 NA 1 4 7 4 7 white 4 6 102 0...
76381410
76381690
I have a df where the first little bit looks like: >dput(df_long_binned_sound2[1:48,]) structure(list(id = c(20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230420, 20230424, 20230424, 20230424, 20230424, 20230424...
saving ccf() looped output in r
You need to inspect the ccf object with View() or checking it's help page: Value An object of class "acf", which is a list with the following elements: lag A three dimensional array containing the lags at which the acf is estimated. acf An array with the same dimensions as lag containing the estimated acf. Thus, yo...
76382508
76383091
I have a executable used to generate a "cache" file. In CMake, I have something like this: add_executable(Generator ...) add_custom_target(OUTPUT cache DEPENDS Generator OtherDep1 OtherDep2 COMMAND Generator --input OtherDep1 OtherDep2 --output cache) However, because it takes about 10 minutes and I do not car...
How to make a CMake custom command depends on a target being built but without rerunning on relink?
I do not want cache to be re-computed whenever Generator is re-linked for whatever reason. Then you need to define target-level dependencies instead of file-level ones. Target-level dependencies are defined with add_dependencies command: add_executable(Generator ...) # Custom command for **file-level** dependencies....
76384961
76385001
I'm trying to setup a sftp server with Apache MINA sshd. But I'm getting subsystem request failed on channel 0 while trying to connect to the server. sftp -P 22 john@localhost ...
Unable to connect to Apache MINA sshd server
I think the error is caused by the server not allowing SFTP. If you check the SFTP docs for NIMA, you can see that you can enable the SFTP subsystem like this: SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder() //... .build(); sshd.setSubsystemFactories(Collections.singletonList(factory)); For f...
76382989
76383095
I have 3 functions, how can I plot them using differents intervals ? This is my code: import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5,5,100) y = 2*x+1 k = 3*x+2 i = 2*x+2 plt.plot(x, y, '-r', label='y=2x+1') plt.plot(x, k, '-r', label='k =3x+2') plt.plot(x, i, '-r', label='i =2x+2') plt.title('3 f...
Functions intervals
Is it this that you want? In [33]: import matplotlib.pyplot as plt ...: import numpy as np ...: ...: xs = [np.linspace(0,4), np.linspace(-3, 5), np.linspace(4, 10)] ...: fs = [np.cos, np.sin, lambda x:np.sin(x)-2*np.cos(x)] ...: for x, f in zip(xs, fs): ...: plt.plot(x, f(x), label=f.__nam...
76381322
76381691
I am trying to find all records between two dates, but can't figure out the proper query. The mapping looks like this GET my-books-index-1/_mapping { "my-books-index-1": { "mappings": { "properties": { "book": { "properties": { "bookInfo": { "properties": { ...
Elasticsearch query for deeply nested field
You can use range query inside of nested path. PUT test_my-books-index-1 { "mappings": { "properties": { "book": { "properties": { "bookInfo": { "properties": { "publisherInfo": { "type": "nested", "properties": { ...
76380576
76381711
This is my attempt at the problem asked in this thread. When I try to run it with input egg_weights = (1,5,10,25) and n = 99, it seems to run into an infinite loop. The code seems to give the correct answer for smaller n, albeit very slowly. What went wrong here? def dp_make_weight(egg_weights, target_weight, memo = {}...
0/1 Knapsack Problem with Dynamic Programming
If you are planning to call dp_make_weight for different egg weight lists, then the default memo argument should be handled as follows. Also, read my comments in the code: def dp_make_weight(egg_weights, target_weight, memo=None): if memo is None: memo = {} infinity = float('inf') if target_weight...
76381523
76381725
I would like get accumulating weighted-average prices by sym from a table, meaning taking account of not just the previous record but all previous records. Input q)show t:([]sym:`a`a`a`b`b;size:(2;6;2;7;5);price:(2;10;3;4;9)) sym size price -------------- a 2 2 a 6 10 a 2 3 b 7 4 b 5 9 Desired...
How can I get accumulating weighted-average prices in KDB+ by symbol from a table, taking into account all previous records?
update avgPrice:(sums price*size)%sums size by sym from t sym size price avgPrice ----------------------- a 2 2 2 a 6 10 8 a 2 3 7 b 7 4 4 b 5 9 6.083333
76384914
76385010
I have a TableData class: public class TableData { public string ID, WrestlerID; public string Name; } And some data that I then put on a list: List<TableData> _tableData = new List<TableData>(); TableData tableData = new TableData { ID = "0", WrestlerID = "000", Name = "test1" }; _tableData.Add(ta...
Items are showing blank in DataGrid
Your TableData class needs to have properties instead of fields to be able use bindings. It should also implement the INotifyPropertyChanged interface to use observable properties, so that changes to those properties get reflected in the UI. Change your class as follows: public class TableData : INotifyPropertyChanged ...
76382920
76383096
How to make it like that so odd indexes will be doing (-) and even indexes will do (+) The max iteration is 6. iteration 1 +10, iteration 2 -20, iteration 3 +30, iteration 4 -40, iteration 5 + 50, iteration 6 -60 AA = np.array([[9.27914]+10, [9.33246]-20, [9.26303]+30, [9.30597...
How to doing dynamic calculation in python
You were very close. Just had to make 3 small changes. I added a +1 inside the parenthesis, added *10 for each of the array operations and change iter += 10 to array += 1 max_iter = 6 iter = 0 for i in range(len(AA)): if i % 2 == 0: AA[i][0] = AA[i][0] + (iter % max_iter+1)*10 else: AA[i][0] = A...
76384866
76385024
I am trying to set this input control using $input_group.find('input'); but it is not getting set. Is this the correct way to use find and then set the value of the input control or is there anyway to do this? var $container = $('#gridrow-field-container'); var template = $('#gridrow-template-in...
Set value of input control from input_group
I added Bootstrap 5 dependencies and fixed the template. You can clone the contents of the template with: const $inputGroup = $template.contents().clone(); const $container = $('#gridrow-field-container'); const $template = $('#gridrow-template-input-group'); const RemoveRow = (span) => { $(span).closest('.row')....
76384474
76385026
I have been trying to add multiple entries on the search bar of the renderdt table function on shiny. for example on the following code, instead of having a new search bar, i want to modify the one which is inbuilt in renderDT and allow it to take multiple entries, comma separated; for example setosa,virginica should b...
How can I modify the inbuilt search bar of RenderDT in R Shiny to allow multiple entries separated by commas?
You can use this code: library(shiny) library(DT) callback <- function(sep) { sprintf(' $("div.search").append($("#mySearch")); $("#mySearch").on("keyup redraw", function(){ var splits = $("#mySearch").val().split("%s").filter(function(x){return x !=="";}) var searchString = "(" + splits.join("|") + ")"; table...
76383038
76383142
I'm trying to write a test involving the filesystem. I chose to use pyfakefs and pytest for writing these tests. When I was trying to write and then read from the fake filesystem, I couldn't seem to get any tests to work. So, I wrote a simple test to ensure that pyfakefs was reading the right value: def test_filesystem...
Pytestfs write then read doesn't return expected value
def test_filesystem(fs): with open("fooey.txt", "w") as my_file: my_file.write("Hello") with open("fooey.txt", "r") as my_file: read = my_file.read() assert os.path.exists("hoklh\\fooey.txt") assert "Hello" in read This should do it!
76381054
76381777
I want to place a numpy array in a cell of a pandas dataframe. For specific reasons, before assigning the array to the cell, I add another column in the same dataframe, whose values are set to NaN. Can someone help me understand what adding the column with the nans does to my data frame, why breaks the code, and how I ...
Adding numpy array to Pandas dataframe cell results in ValueError
If you only need to set a single cell, use at: df.at[4, 'a'] = np.array([5, 6, 7, 8])
76381509
76381781
I have a script which outputs an excel file '.xlsx' containing various data. It generates a file with the date in the name in one folder, and then generates a copy, using shutil.copy(), in a separate folder. I then rename the file using os.rename(), however instead of overwriting the file already there, it produces the...
How can I overwrite a file in a different folder using shutil.copy() and os.rename() in Python?
To avoid the "FileExistsError" when renaming the file, you can check if the destination file already exists before renaming it. import os import shutil from datetime import date # Select file you want to copy & where to copy it to src_file = vb.output_path destination = vb.path_reports_cashflowcopy # Copy the file sh...
76385031
76385105
I have an ngFor loop set up like this: <div *ngFor="let record of this.RecordsProcessed; let i = index"> <div class="row my-16" data-test='test'_{{i}}> <div class="col-4">Id:</div> <div class="col-8">{{record?.Id}}</div> </div> </div> I want to put the index from ngFor on the data-text tag withi...
How to make the index from ngFor part of an html tag value
Try like this: <div *ngFor="let record of this.RecordsProcessed; let i = index"> <div class="row my-16" [attr.data-test]="'test_' + i"> <div class="col-4">Id:</div> <div class="col-8">{{record?.Id}}</div> </div> </div> [] brackets let angular know that everything inside of "" is typescript code.
76385070
76385109
I am trying to decipher this code (MurmurHash) and came across the following lines: switch (remainder) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); // When is this executed? k1 = (((k1 & 0xfff...
JavaScript - Code after case in switch statements
The code is part of case 1. Personally I'd re-arrange the whitespace to be more clear: switch (remainder) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) *...
76382771
76383156
I have a data set: df<- structure(list(Depth = c(6.83999999999997, 8.56, 4.64999999999998, 8.83999999999997, 6.56, 8.64999999999998, 12.21, 11.82, 5.41000000000003, 11.63, 9.41000000000003, 11.26, 8.95999999999998, 10.81, 10.68, 12.74, 14.06, 8.16000000000003, 12.31, 10.76, 10.74, 1, 9.38, 5, 4, 12, 6.7099999999...
Getting the correct order of factors for parametric terms in gratia::draw(parametric_effects())
As a workaround or fix for your issue you could set the order using the limits argument of scale_x_discrete: library(mgcv) #> Loading required package: nlme #> This is mgcv 1.8-42. For overview type 'help("mgcv-package")'. library(gratia) library(ggplot2) packageVersion("gratia") #> [1] '0.8.1.34' gam <- gam(Depth ~ ...
76383137
76383166
I want to create simple react component with form inside, every time that user click Submit button, data should be send to the server. For testing purposes I created component with two buttons, one stand alone and one inside form. return ( <> <button onClick={submit}>Working example</button> <form style={ce...
Why I can't send data using submit button inside Form
Add the attribute method="post" to the element.
76384759
76385111
I am translating Rust code into C#. Rust has some type called Box<> which is said to be C++'s equivalent of smart pointers. What should be the C# equivalent of Rust's Box<> type?
What should be the C# equivalent of Rust's Box<> type?
The short answer is that there isn't an exactly-equivalent type. Box is used to put a value on the heap. There are several reasons why you would want to do that, but that's all it does. In C#, reference types always point to a heap allocation. "Boxing" is therefore pointless on reference types, as they are already ef...
76383032
76383179
This is a secondary question as I thought my previously answered question was resolved. Here is my use case: Customer (office) buys physical products. We collect the information on the mobile app and then the server creates a Stripe Customer and a PaymentIntent. This succeeds, as evidenced by Stripe portal When the ...
Stripe Customer paymentMethod applied to its subscribers
In order to create Subscriptions with customer's attached payment method, you need to set it as default payment method for the customer. Specifically on customer.invoice_settings.default_payment_method parameter Once you do that, the subscription should charge the default payment method on creation. For your second que...
76381709
76381792
How to convert a jupyter notebook to a python script with cell delimiters (#%%)? I've already checked nbconvert , but it doesn't seem to have the one. Also, the same question found, the answer doesn't satisfy the need because actual raw source codes of jupyter notebook isn't structured as such. (It'd be better to be ab...
How to convert a jupyter notebook to a python script with cell delimiters (#%%)?
That looks similar to the percent delimiter that Jupytext handles, see the top few commands here also. The specific commands I'm referencing: jupytext --to py:percent notebook.ipynb # convert notebook.ipynb to a .py file in the double percent format jupytext --to py:percent --opt comment_magics=false notebook.i...
76385046
76385123
Python - How to make current script iterate through list of words instead of one string/word only? I am very new to python, and have put together a script parsing different scripts i've looked at. The goal is to return all possible variants of a list of keywords, replacing the characters by leet code (e.g.: 'L33T' or '...
How do I use itertools in Python to generate all possible variants of a list of keywords with leet code?
Loop over the list of words, calling leet() on each word. words = ['hola', 'some', 'other', 'word'] with open ('leet_latinalphabet.csv', mode ='w') as csvfile: fieldnames = ['word', 'leet variants'] writer = csv.DictWriter(csvfile,fieldnames=fieldnames) writer.writeheader() for word in words: r...
76382337
76383224
I am using Google code scanner Android MLKit for Barcode scanning. I am using below dependencies. I want the use bundled model so that initialisation time is not taken when app is launched. Is there a way can I use bundled version of model : Please find below dependencies I used for this : implementation 'com.google....
ml-kit - barcode-scanning android - Google code scanner
What about this: dependencies { // ... // Use this dependency to bundle the model with your app implementation 'com.google.mlkit:barcode-scanning:17.1.0' } Found at: https://developers.google.com/ml-kit/vision/barcode-scanning/android
76381596
76381793
I have rest controller with token creation call. Here inside ObjectNode I get big json data. The database column is varchar2(4000) nad I want limit this ObjectNode size to 4000 adding validation at controller level. Not sure how to do this? data class TokenRequest( @NotEmpty(message = "id is mandatory") open va...
Spring Rest Validation ObjectNode data size limit
It sounds like you're trying to cap the size of the JSON data contained in the 'token' field of your request. You want it to be no more than 4000 characters, right? There's actually a way to handle this in Kotlin by creating your own validation annotation. Here's how: First, you need to create the annotation itself: @T...
76384241
76385126
Have following YAML image: repository: "test.com/test" pullPolicy: IfNotPresent tag: "abc" JAVA code to modify the YAKL file public class SnakeYaml1 { public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub InputStream inputStream = n...
Not able to format YAML using SnakeYaml keeping original way
Well, you mentioned it is SnakeYaml lib, so I wonder have you ever looked through its documentation ? Your code works as it should. try: DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options);
76378684
76383239
I'm new to Harbor registry. I was asked to propose an architecture for harbor in my company. I proposed at first to use an architecture based on proxy cache. But the CISO refused to use proxy cache for the entreprise without saying why. I proposed anoter architecture based on replication. We validate some base images t...
Harbor registry proxy cache vs replication
At this stage one can only speculate, about the unprofessional behavior of not explaining the reasons and also for not asking. Regarding Harbor proxy and replication, the main difference between both option is the difference of threat surface and its control. Proxy Passive, forwards requests upstream if not found loca...
76383101
76383250
I have data that looks like this: dataframe_1: week SITE LAL SITE LAL 0 1 BARTON CHAPEL 1.1 PENASCAL I 1 1 2 BARTON CHAPEL 1.1 PENASCAL I 1 2 3 BARTON CHAPEL 1.1 PENASCAL I 1 And, i need the final dataframe to look like this: dataframe_2: week ...
Reshaping a Dataframe with repeating column names
Not a very generalizable solution, but will work on your example: df.groupby('week').apply( lambda _df : pd.concat((_df.iloc[:,1:3], _df.iloc[:,3:5]))).reset_index('week') it groups by week and then reshapes with column selection + concatenation. Removing a superfluous index column in the end.
76381742
76381799
I created a popup that appears when I click a button, but to make it disappear I have to click again. Is there a way to set a timer and make it disappear? Function: // When the user clicks on div, open the popup function myFunction() { var popup = document.getElementById("myPopup"); popup.classList.toggle("show"); ...
How to set a timeout for a popup and close if user clicks elsewhere?
To do this you need to: Define a function, hide() that hides the popup. Add an mousedown event listener to the whole document that invokes hide Within hide, ensure that the click event's target is not contained in the popup. Set up the timeout to call hide Important: Have hide clear the created timeout and remove t...
76382658
76383281
i am making a three-d array the problem i am facing is i want to create multiple 3-d array however with varying size of row and column so the first matrix size could be 0-2-2 while next matrix could be say 1-1-3 so on.. kindly do not suggest making a large matrix that could have value of all the row and columns. i pers...
3-d array with different size of row and column
Since each matrix may be a different size, you should manage each matrix separately and record its dimensions separately. The code below shows how to use a structure type to do that. Common C implementations support variable length arrays, so you use this to make addressing the matrix elements simpler. The program belo...
76385092
76385129
<class 'pandas.core.frame.DataFrame'> RangeIndex: 400 entries, 0 to 399 Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 CompPrice 400 non-null int64 1 Income 400 non-null int64 2 Advertising 400 non-null int64 3 Popul...
Index of .iloc API in Pandas
What you are observing is the standard functionality of pandas. If you look in the documentation, you can find the definition. This is intended and logical, as Python lists function the same way. As per the docs: .iloc is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a bo...
76380777
76381845
We are middle of upgrading ruby versions v2.7.3 -> v3.1.3 One of our test cases are failing related to valid ipv6 address string, check the following # ruby 2.7.3 IPAddr.new('fe80::85e:7530:69ec:9074%en0').ipv6? => IPAddr::InvalidAddressError (invalid address: fe80::85e:7530:69ec:9074%en0) # ruby 3.1.3 IPAddr.new('fe...
Ruby IPAddr class accepting wrong IPv6 address string
Is it really a bug or am I missing something? This used to be an issue in the ipaddr default gem up to version 1.2.2 which was fixed in version 1.2.3 in order to be fully compliant with RFC 4007 and RFC 6874. Version 1.2.3 of the ipaddr default gem was shipped as part of Ruby 3.1.0. So, you are correct. This is a bug...
76383210
76383298
When using pandas.date_range with start date, frequency, and periods the date range rounds up when using the start date as the last day of a month. It seems like a silent edge case bug. If it's not a bug, any idea why it does that? For example import pandas as pd start_date = pd.Timestamp(2023, 5, 31) date_range = pd....
Why does pandas `date_range` rounds up to the next month?
pd.date_range is to generate a range of date between start and end. 2023-05-01 is less than start date 2023-05-31, it will never reach it. To do what you want, you can replace the day of pd.Timestamp by 1. start_date = pd.Timestamp(2023, 5, 31) date_range = pd.date_range(start=start_date.replace(day=1), freq="MS", peri...
76383232
76383300
I am using the following code to persist utms across my website. However i notice that its adding a question mark to links even without the UTM parameters. Can someone help me figure out what in this code needs to change. It should only be trying to add UTM parameters to the links if there is one present in the URL. <...
What is the bug in my Persistent UTM Code?
In decorateUrl you are adding the ? if there is not one urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&'; I would suggest you may only want to do this if collectedQueryParams contains any elements function decorateUrl(urlToDecorate) { var collectedQueryParams = [];...
76385033
76385142
I have some Gujarati string but its in ISCII encoding, so python throughing error (SyntaxError: invalid decimal literal). string = TFH[TZDF\ I]GF.8[0 G[Xg; line 1 string = TFH[TZDF\ I]GF.8[0 G[Xg; ^ SyntaxError: unexpected character after line continuation character I was tried byte encoding...
How can I convert ISCII encoding to unicode for Gujarati language in Python 3?
If you just want to write the string literal, for me, just writing print("તાજેતરમાં યુનાઇટેડ નેશન્સ") worked. Or you could write: characters = [2724, 2750, 2716, 2759, 2724, 2736, 2734, 2750, 2690, 32, 2735, 2753, 2728, 2750, 2695, 2719, 2759, 2721, 32, 2728, 2759, 2742, 2728, 2765, 2744] string = str() for c in charac...
76381570
76381846
I have vcf file like this: ##bcftools_annotateVersion=1.3.1+htslib-1.3.1 ##bcftools_annotateCommand=annotate #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT HG005 chr1 817186 rs3094315 G A 50 PASS platforms=2;platformnames=Illumina,CG;datasets=3;datasetnames=HiSeq250x250,CGnormal,HiSeqMatePair;ca...
Extracting vcf columns substring with awk
You can try this awk: awk 'BEGIN{OFS="\t"} /^##/{next} /^#/{print $3,$8; next} { split($8,a,";") for(i=1;i<=length(a);i++) if (a[i]~/^AN=/) {sub(/^AN=/,"",a[i]); break} printf "%s%s%s\n", $3, OFS, a[i] } ' file With the example, prints: ID INFO rs3094315 2 rs3131972 2
76384930
76385186
I'm using the following code to create a video player for detected reference images in AR session. Currently I display a placeholder video and after 1 second switch to real video that I want played. However, I would like to show the placeholder video until the real video is ready to be played. I tried experimenting wit...
Load AVAsset video in the background and replace playing placeholder video once it's playable in Swift and RealityKit
The key to resolving this issue is making sure the AVPlayer's item is actually ready to play before switching the video. You can use the Key-Value Observing (KVO) on the AVPlayerItem's status property to get notified when it's ready to play. Here is the updated createVideoNode(_:) function: func createVideoNode(_ targe...
76383308
76383309
Openai provides an api which allows you to implement AI services such as ChaGPT or DAL-E. For Ruby on Rails application, and there are couple of gems available, obe of them being ruby-openai. It works very well, but the only problem is that it doesn't come with the stream conversation feature, meaning that you can only...
ruby-openai api gem in Ruby on Rails: how to implement a streaming conversation?
Basically you need to implement the whole behaviour yourself. Here are all the implementation step, including the implementation of the dal-e ai with a response with several pictures rather then just one. You can also find my whole repository HERE and clone the app!!! IMPLEMENTING A STREAM CONVERSATION FEATURE Basic im...
76381726
76381855
I want to write integration tests with shared context (shared state) for all testcases. From docs: When using a class fixture, xUnit.net will ensure that the fixture instance will be created before any of the tests have run, and once all the tests have finished, it will clean up the fixture object by calling Dispose, ...
xUnit IClassFixture reinitialized for every testcase
This is working correctly, but you have implemented it wrong. xUnit runtime will create a new instance of UnitTest1 for every test execution, but it should only create a single instance of WebApplicationFactory<Program> for the lifetime of the current test batch execution context for this test class. Your _val variabl...
76381615
76381868
I am trying to build a date range bar graph usins ggplot2 (R) in the spirit of: I have followed a thread but I am completely unable to reproduce the results with dates. If I understood it correctly, for each "id", the bar length is determined by the smallest and largest "value" in the database. Here is a minimally wor...
ggplot2: Date range bar graph
A quick and dirty approach using geom_segment. ggplot2::ggplot(DF, ggplot2::aes(x = CreationTime, xend = LastActivity, y = Name, yend = Name, colour = Status)) + ggplot2::geom_segment(linewidth = 15) + ggplot2::coord_cartesian(xlim = c(min(DFGather$Value),max(DFGather$Value))) + ggplot2::scale_x_datetime(date_br...
76382858
76383322
I am trying to cast multiple date formats from string type field using Pyspark. When I am using below date format it is working fine. def custom_to_date(col): formats = ("MM/dd/yyyy", "yyyy-MM-dd", "dd/MM/yyyy", "MM/yy","dd/M/yyyy") return coalesce(*[to_date(col, f) for f in formats]) from pyspark.sql.func...
Spark is unable to handle a particular date format
Adding an answer since the comments and others answer doesn't cover the behaviour. The solution is not to add new formats. Since the formats itself can be better defined. with spark 3.0 M supports 01, 1. January, Jan. So you don't need MM spark reference - https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.h...
76384850
76385187
My line renderer is drawing behind objects. I want it to draw on top of other game objects except for the ball. How can I do this? See the following image to reference the problem (the line renderer draws below the goal, and I want it to draw itself on top. I searched for the issue but haven't found a single answer fo...
How to draw LineRenderer above other objects?
To render a material "above" some other materials, you must set your LineRenderer or TrailRenderer's material Rendering mode to Transparent. Also, set the Rendering Mode of materials of objects you wish to draw LineRenderer on top to Transparent. Now go back to the LineRenderer's material and in Advanced Options set it...
76381796
76381874
I got some problems with duplicate rows which I don't wanna get. Hi! I got two tables - tab1, tab2 and I want to join tab2 to tab1 like: SELECT t1.column_A1, t2.column_B2 FROM tab1 t1 JOIN tab2 t2 ON t1.column_A1=t2.column_A2 tab1 | Column A1 | Column B1 | Column C1 | | -------- | -------- | -------- | | Z1 ...
How to get not duplicate rows in join?
One option is to "sort" rows per each column_a1 by value stored in column_b2 and return rows that rank as the highest. Sample data: SQL> WITH 2 tab1 (column_a1, column_b1, column_c1) 3 AS 4 (SELECT 'Z1', 'cell 2', 'cell 3' FROM DUAL 5 UNION ALL 6 SELECT 'Z2', 'cell 5', 'cell 6' ...
76378880
76378926
Trying to modify my axios wrapper and can't figure out why I'm getting this typescript error... type Headers = { Accept: string; 'Content-Type': string; Authorization?: string; } export interface AxiosOptions { params?: any; data?: any; headers: Headers; } const axiosOptions: AxiosOptions = { headers: {...
Pick error "Type 'Pick' cannot be used as an index type."
This doesn't really meet the usage pattern of Pick. You just need keyof Headers for your case: type Headers = { Accept: string; 'Content-Type': string; Authorization?: string; } export interface AxiosOptions { params?: any; data?: any; headers: Headers; } const axiosOptions: AxiosOptions = { headers: { ...
76378929
76378999
What happens for an initial count of zero for an x86 rep prefix? Intel's manual says explicitly it’s a while count != 0 loop with the test at the top, which is the sane expected behaviour. But most of the many vague reports I’ve seen elsewhere suggest that there’s no initial test for zero so it would be like a countdow...
x86 rep prefix with a count of zero: what happens?
Nothing happens with RCX=0; rep prefixes do check for zero first like the pseudocode says. (Unlike the loop instruction which is exactly like the bottom of a do{}while(--ecx), or a dec rcx/jnz but without affecting FLAGS.) I think I've heard of this rarely being used as an idiom for a conditional load or store with re...
76383242
76383335
Trying to match a dictionary item with a string value from another column. sample data: df = A B 0 'a' {'a': '2', 'b': '5'} 1 'c' {'a': '2', 'b': '16', 'c': '32'} 2 'a' {'a': '6', 'd': '23'} 3 'd' {'b': '4', 'd': '76'} I'm trying to get the following out: Df = A B ...
Dictionary Comprehension within pandas dataframe column
You can use a list comprehension with zip: df['B'] = [{x: d[x]} for x, d in zip(df['A'], df['B'])] Output: A B 0 a {'a': '2'} 1 c {'c': '32'} 2 a {'a': '6'} 3 d {'d': '76'}
76384672
76385193
I have a yaml file which is similar to the following (FYI: ssm_secrets can be an empty array): rabbitmq: repo_name: bitnami namespace: rabbitmq target_revision: 11.1.1 path: rabbitmq values_file: charts/rabbitmq/values.yaml ssm_secrets: [] app_name_1: repo_name: repo_name_1 namespace: namespace_1 targ...
Terraform for_each over yaml file contents which is an object
Assumptions Based on what you shared, i make the following assumptions: the service is not actually important for you as you want to create external secrets by ssm_secrets.*.name using the given key and ssm_path attributes. each name is globally unique for all services and never reused. terraform hacks Based on the a...
76380957
76381877
How can I assert that the jest mocked module method was called? E.g. in my .spec.js I have the following jest mocked module: jest.mock('../../../../services/logs.service.js', () => ({ log: jest.fn() })); Now I would like to assert the log method. I.e. something like this: //the log was called twice with the text "...
How can I assert that the jest mocked module method was called?
You can do the following: JavaScript import { log } from '../../../../services/logs.service.js'; jest.mock('../../../../services/logs.service.js', () => ({ log: jest.fn() })); expect(log).toHaveBeenCalledWith(2, "foo"); // JavaScript TypeScript import { log } from '../../../../services/logs.service.js'; jest.mo...
76382640
76383361
I have a mobile app developed in ionic capacitor. The backend to the app is a .net core web api deployed on amazon elastic beanstalk. I am getting CORS error** No 'Access-Control-Allow-Origin' header is present on the requested resource** when trying to access the back end using the app. I have attempted to allow the A...
Ionic app error: No 'Access-Control-Allow-Origin' header is present on the requested resource
Log in to the AWS Management Console and navigate to the Elastic Beanstalk service. Select your application and environment where the .NET Core Web API is deployed. In the navigation pane, click on "Configuration." Under the "Software" section, click on "Edit" for the "Environment properties." Add a new property with ...
76384683
76385208
I would like to draw random numbers from a modified exponential distribution: p(x) = C * a * Exp[-(a*x)^b] with C=1/Gamma[1 + 1/b] for normalization. How can I do this in julia? Unfortunately I have only little experience with Julia and no experiences with creating custom random numbers. I would be very grateful for an...
Draw random numbers from a custom probability density function in Julia
If I'm not mistaken, that is a p-Generalized Gaussian distribution, which has a rather efficient implementation in Distributions.jl: using Distributions mu = 0 # your location parameter alpha = 1/a # your scale parameter beta = b # your shape parameter p = PGeneralizedGaussian(mu, alpha, beta) Using the Dis...
76385164
76385211
For my main project, I'm trying to find a way to hide a column in JS. The following function : function hide() { const table = document.getElementById('test'); const cols = table.getElementsByTagName('col'); cols[1].style.visibility = "collapse"; } works great, but the borders don't move. Here's the proble...
Border doesn't adapt after collapsing a column
To address this issue, you can use the border-spacing property instead of border-collapse. Modify your CSS as follows: <style> table { border-spacing: 0; } th, td { border: 1px solid; padding: 5px; } </style>
76381785
76381889
first I saw similar questions but nothing helped me. I'm trying to sort list of tuples, and convert the data types inside the tuple, convert it according to a list of tuples I get. for example, if I have a list of tuple, every tuple is built like (ID,Grade,Height) A = [(123,23,67),(234,67,45)] and I have a list of ty...
TypeError: data type '>' not understood using dtype from numpy
I think you maybe overlooked the documentation you are referring. You used dt = np.dtype(('>14')) which is >14 (fourteen)... But in fact the documentation clearly mentions dt = np.dtype('>i4') which is i4 not 1 (one) Also based on the docs > or < specifies upper/lower bound for each dtype, for example >i would be big...