Posts

Showing posts from September, 2020

Quarkus native image crashes

I have successfully built a native image with Quarkus/Graal and I can run it in the terminal (no container yet). However, it crashes with "Segmentation fault (core dumped)" message. How can I get more information about the error? Are there flags to pass to the native executable or while building the image? I am using GraalVM Version 20.2.0 (Java Version 11.0.8) Any help is much appreciated. Thanks. from Recent Questions - Stack Overflow https://ift.tt/36hsMWB https://ift.tt/eA8V8J

Python- Trying to find a date in a list

I have a file txt file taht contains all the dates in a year in the mm/dd/yy format. 01/01/20 01/02/20 01/03/20 01/04/20 01/05/20 01/06/20 And I have a today's date from Python code: current_time = datetime.datetime.now() date = current_time.strftime("%m/%d/%Y") When I try to find the list element == date i don't get a match. The code is: for i in range(0,366): if(date==calendarData[i]): break else: print(i,end=" ") print("date", date, end=" ") print(calendarData[i], end="") i=i+1 From the console 269 date 09/29/2020 0 9 / 2 6 / 2 0 270 date 09/29/2020 0 9 / 2 7 / 2 0 271 date 09/29/2020 0 9 / 2 8 / 2 0 272 date 09/29/2020 0 9 / 2 9 / 2 0 273 date 09/29/2020 0 9 / 3 0 / 2 0 274 date 09/29/2020 1 0 / 0 1 / 2 0 from Recent Questions - Stack Overflow https://ift.tt/2GfyIo9 https://ift.tt/eA8V8J

I have been trying to convert following code to Python but I couldn't figure out the way to do it. How can I slice a boolean list in Python?

I couldn't find how to create boolean list with same length of the input. I kept getting error at the line: checks[j] = true when I try to convert it to Python. I guess slicing a boolean list is not allowed in Python. int result = 0; Boolean lightsOn = true; Boolean[] checks = new Boolean[input.Length]; for (int i = 0; i < input.Length; i++) { int j = input[i] - 1; checks[j] = true; for (; 0 <= j; j--) { if (!checks[j]) # also this part { lightsOn = false; break; } } if (lightsOn) { result++; } lightsOn = true; } return result; from Recent Questions - Stack Overflow https://ift.tt/3lbmg8j https://ift.tt/eA8V8J

Why/When does calling a context cancel function from another goroutine cause a deadlock?

I'm having difficulties getting behind the concept of context cancel functions and at which point calling the cancel func causes a deadlock. I have a main method that declares a context and I am passing its cancel function to two goroutines ctx := context.Background() ctx, cancel := context.WithCancel(ctx) go runService(ctx, wg, cancel, apiChan) go api.Run(cancel, wg, apiChan, aviorDb) I use this context in a service function (infinite loop that stops once the context is cancelled). I am controlling this by calling the cancel function from another goroutine. runService is a long running operation and looks similar to this: func runService(ctx context.Context, wg *sync.WaitGroup, cancel context.CancelFunc, apiChan chan string) { MainLoop: for { // this is the long running operation worker.ProcessJob(dataStore, client, job, resumeChan) select { case <-ctx.Done(): _ = glg.Info("service stop signal received") ...

Python adding a list to a slice of another list

I have this code that's not working: self.lib_tree.item(song)['values'][select_values] = adj_list self.lib_tree.item(album)['values'][select_values] += adj_list self.lib_tree.item(artist)['values'][select_values] += adj_list The full code is this: def toggle_select(self, song, album, artist): # 'values' 0=Access, 1=Size, 2=Selected Size, 3=StatTime, 4=StatSize, # 5=Count, 6=Seconds, 7=SelSize, 8=SelCount, 9=SelSeconds # Set slice to StatSize, Count, Seconds total_values = slice(4, 7) # start at index, stop before index select_values = slice(7, 10) # start at index, stop before index tags = self.lib_tree.item(song)['tags'] if "songsel" in tags: # We will toggle off and subtract from selected parent totals tags.remove("songsel") self.lib_tree.item(song, tags=(tags)) # Get StatSize, Count and Seconds adj_list = [element * -...

Xamarin Visual Studio ios simulator not working

Image
We recently acquired mobile solution that contains an ios and android project. Android project runs fine. When i run the ios project i get error stating My environment is a windows laptop and a macbook pro running visual studio from windows. I can pair to mac just fine I am using automatic provisioning which appears to be correct since my team shows up in the team dropdown. I feel like i did the provisioning correct because team would not show up in dropdown if not. I have latest xcode installed on mac I verified simulator runs fine on mac by starting through xcode In the videos i watched as soon as mac was paired then more options appeared besides just simulator. (ipad, tvos, etc) One question is when i registered my device i used the UUID from the macbook and not UUID of simulator. Could not get straight answer for this. To be clear i am just trying to run the simulator and not a remote device. Honestly i just want to be able to test the ios application. It should not be ...

Java shift right outputting negative value

i'm really confused with, well it's best if I show my code first so here's what I got. void dumpInt(int x) throws IOException { if ( true ) { //8388638 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); writer.writeByte(x&0xff); writer.writeByte((x>>8)&0xff); writer.writeByte((x >> 16) & 0xfff); writer.writeByte((x>>24)&0xff); outputStream.write(x & 0xff); outputStream.write((x >> 8) & 0xff); outputStream.write((x >> 16) & 0xff); outputStream.write((x >> 24) & 0xff); System.out.println((x >> 16) & 0xff); if(x == 8388638){ String xz = ""; byte[]array = outputStream.toByteArray(); System.out.println(array[2]+" | " + (char)array[2]); } } else { writer.writeInt(x); } } this works fine but when I do dumpInt(8...

Swift -How to get the center frame of a button's titleLabel and not the button itself

Image
I have a custom segmented control with 4 segments with a button in each segment. I had to make a change to the button's contentEdgeInsets: // eg of the second button customSegmentedControl.secondButton?.contentEdgeInsets = UIEdgeInsets(top: 0, left: -35, bottom: 0, right: 0) The slider originally slid to each segment using button.frame.midX . After changing the contentEdgeInsets when the slider slides to a segment it looks as if it's in the wrong position because the title is no longer in the center of the button. I tried to change the slider to slide to the center of the button's button.titleLabel: button.titleLabel!.frame.midX but a weird bug occurs where the slider slides incorrectly. for button in buttons { UIView.animate(withDuration: 0.2, animations: { self.slider.frame.origin.x = button.titleLabel!.frame.midX // button.frame.midX was what was originally used // if it's the selected button break ... }) } How can I get t...

I am using phonenumbers in python to figure out the carrier of a number. I keep getting blank output

I am using phonenumbers in Python to figure out the carrier of a number. I keep getting blank output. Here is my code: import phonenumbers import phonenumbers.carrier num_object = None while num_object is None: try: num = input("phone number: ") num_object = phonenumbers.parse("+1 {}".format(num), region="US") except Exception as error: print("ERROR: {}".format(error)) carrier = phonenumbers.carrier.name_for_number(num_object, "en") print(carrier) from Recent Questions - Stack Overflow https://ift.tt/30l1rPv https://ift.tt/eA8V8J

Insert .csv file to SQL Server using OpenRowSet

I have a .csv file, called File1 that I would like insert into my already existing table, called Table1 within SQL Server. The .csv file has the following structure and values: ID Location Name Date 2 New York Sally 20191010 3 California Ben 20191110 My table within SQL server has the same structure: ID Location Name Date 1 Houston Kelly 20200810 I wish for output to look like the value below, I wish for the date to be in order as well. ID Location Name Date 1 Houston Kelly 20200810 2 New York Sally 20191010 3 California Ben 20191110 I am doing this: INSERT INTO dbo.Table1(Microsoft.ACE.OLEDB12.0; Database = 'Data', 'SELECT * FROM OpenRowSet' Dir = C:\downloads, 'SELECT * FROM File1.csv') I am still researching to see what it is I am doing wrong with the above command. Any suggestion is apprec...

How do I check if all the elements of a nested list tree are identical?

I am trying to create a function allsametree(tree) that takes a list, tree , as an input and returns TRUE or FALSE if all the elements of the list are numerically identical. So far, I have the following function: def allsametree(tree): if not type(tree) == list: return tree if type(tree) is list: final_lst = [] for item in tree: final_lst.append(allsametree(item)) return final_lst[1:] == final_lst[:-1] While for the most part, this function works, it runs into an issue when evaluating allsametree([1, [[[[[2]]]]]]) Any tips, or alternative ways you would approach this problem? from Recent Questions - Stack Overflow https://ift.tt/3cJPHLG https://ift.tt/eA8V8J

How to do a query using pyhton list (must have all OR must have at least one element) on a many to many structure with SQLAlchemy?

I'll create an not specific structure so the problem became more easy to understand. Considering a DB structure that store books information: from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow db = SQLAlchemy() #Base class to create some good pratices fields class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) class Book(Base): name = db.Column(db.String(255), nullable=False) pages = db.Column(db.Integer, nullable=True) tags = db.relationship('BooksTags', back_populates="book") class BooksTags(db.Model): __tablename__ = 'book_tag' tag_id = db.Column(db.Integer, db.ForeignKey('book.id'), primary_key=Tru...

jQuery UI menu inside cell is not displaying while jQuery DatePicker & Autocomplete is displaying in ag-Grid

I am trying to show a jQuery UI dropdown menu( https://jqueryui.com/menu/ ) . I am able to integrate jQuery UI for autocomplete and Datepicker . I am trying to implement the jQuery menu on "Age" columnDef. Plunker Link:- https://plnkr.co/edit/7SPkMmx2kfqiSZEq this.columnDefs = [ { headerName: "Athlete", field: "athlete", editable:true, cellEditor: "dropdownUI" }, { headerName: "Date", field: "date", editable: true, cellEditor: "datePicker" }, { headerName: "Age", field: "age", editable:true, cellEditor: "dropdownUIOnKeyPress" }, { headerName: "Country", field: "country" }, { headerName:...

Generate the same object file with a native compiler and a cross compiler

I'm trying to use a cross compiler running on Ubuntu to compile some Raspberry Pi code. I have already tested the executable and it works fine, but comparing that executable to the one generated by the native compiler (gcc on Raspberry Pi) I see there are some differences between the binary files. Setup The native compiler is gcc (Raspbian 8.3.0-6+rpi1) 8.3.0 running on Raspbian GNU/Linux 10 (buster). The cross compiler is arm-linux-gnueabihf-gcc-8 (Ubuntu/Linaro 8.4.0-1ubuntu1~18.04) 8.4.0 running on Ubuntu 18.04.4 (Bionic Beaver). I tried to make sure that the cross compiler is using the same compilation flags as the one on the Pi uses by default: marm to generate code that runs in ARM state (instead of Thumb) march=armv6 mfpu=vfp O0 and I turned off the optimizations to make sure nothing "funny" is going on What I have tried I wrote the most bare-bones C code I could think of: int main() {} And then compiled it into assembly using Unified Assembly Lang...

C#: keep the timer running even after the end of the method

Any idea how can I keep the timer running even after the method ends public static void Method(){ Timer Timer = new Timer(state: null, dueTime: 0, period: 60000, callback: (o) => { Console.WriteLine("Thank you <3"); }); } The code above displays something like this: 1. Thank you <3 I want to achieve something like this: 1. Thank you <3 (after 0 min) 2. Thank you <3 (after 1 min) 3. Thank you <3 (after 2 min) 4. ... I tried GC.KeepAlive(Timer); but doesn't seem to work. I know this is related to the garbage collector, and I can work around this and create Timer as a global variable, but are there any better suggestions? from Recent Questions - Stack Overflow https://ift.tt/3kXZvnZ https://ift.tt/eA8V8J

Update on duplicate using javascript

I got two object arrays to compare and return a result which contains two arrays one for insert and one for update. aObj --> parent object. (primary/unique key is empid) bObj --> children object.(primary/unique key is empid) let a = [ { empid: "emp001", name: "test1", status: "emp" }, { empid: "emp002", name: "test2", status: "ex-emp" }, { empid: "emp003", name: "test3", status: "emp" } ]; let b = [ { empid: "emp001", name: "test1_updated", status: "emp" }, { empid: "emp002", name: "test2", status: "emp" } ]; //insert array // console.log(_.differenceBy(a, b, 'empid')); //update array let updateArr = [], insertArr = []; for (let i = 0; i < a.length; i++) { let aObj = a[i]; for (let j = 0; j < b.length; j++) { let bObj = b[j]; if (aObj.empid === bObj.empid) { if (aObj.status !== b...

How to logout after X minutes of inactivity on button click?

I am working on a simple project where I have a login system with multiple users where each user will login and save form entries in a file. I am trying to build session timeout so that after 2 minutes of inactivity it can log me out. I have login.php page where I provide my user and password. If login is successful then it redirects me to index.php page where I have form with two textbox and a button. On index.php page I have Save Data button which if I click it calls save.php then it save form entries by overwriting in file. I also have logout link on my index.php page which if I click then it will log me out and redirect to login.php page. All above things works fine. Now I am trying to build this session timeout so that it can log me out after x minutes of inactivity and redirect me to login.php page. Here is my index.php file: <?php declare(strict_types = 1); // Start session. session_start(); // Include helper functions. require_once 'helpers.php'...

How to add data from multiple files to a single plot figure?

Image
Thank you in advance for your help! (Code Below) ( Link to 1st piece of data ) ( Link to data I want to add ) I am trying to import data from a second CSV (above) and add a second line to this plot based on that CSVs data. What is the best approach to doing this? (Images below) The squiggly lines on the plot represent the range of data. import pandas as pd import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') raw_data = pd.read_csv('all-deep-soil-temperatures.csv', index_col=1, parse_dates=True) df_all_stations = raw_data.copy() selected_soil_station = 'Minot' df_selected_station = df_all_stations[df_all_stations['Station'] == selected_soil_station] df_selected_station.fillna(method = 'ffill', inplace=True); df_selected_station_D=df_selected_station.resample(rule='D').mean() df_selected_station_D['Day'] = df_selected_station_D.index.dayofyear mean=df_selected_station_D.groupby(by...

Entity Framework Core and transaction usage

I am using Entity Framework Core 3.1.8 with SQL Server 2016. Consider following example (simplified for clarity): Database table is defined as follows: CREATE TABLE [dbo].[Product] ( [Id] INT IDENTITY(1,1) NOT NULL , [ProductName] NVARCHAR(500) NOT NULL, CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED (Id ASC) WITH (FILLFACTOR=80), CONSTRAINT [UQ_ProductName] UNIQUE NONCLUSTERED (ProductName ASC) WITH (FILLFACTOR=80) ) And following C# program: using System; using System.Linq; using System.Reflection; namespace CcTest { class Program { static int Main(string[] args) { Product product = null; string newProductName = "Basketball"; using (CcTestContext context = new CcTestContext()) using (var transaction = context.Database.BeginTransaction()) { try { product = context.Product.Where(p => p.ProductName == newProductNam...

How can I get to the last level of a json nest and format the output dynamically?

I have this json: [ { "name": "MARVEL", "superheroes": "yes" }, { "name": "Big Bang Theroy", "superheroes": "NO", "children": [ { "name": "Sheldon", "superheroes": "NO" } ] }, { "name": "dragon ball", "superheroes": "YES", "children": [ { "name": "goku", "superheroes": "yes", "children": [ { "name": "gohan", "superheroes": "YES" } ] } ] } ] I know how to loop and go through it but I need an output like this: [ { "name": "MARVEL", "answer": [ { "there_are_superheroes": "YES" ...

Pod update integration only?

When you're updating cocoapods, you can update a single pod or all pods, either pod update or pod update <podname> . In both cases, it updates the configuration of the project, xcconfig files, and other things that impact all pods. If you specify a pod, it then updates that one pod. If you don't specify a pod, it updates all the pods. Is there a way to update just this other stuff without updating any pods so I can commit that separately to git? My workaround so far has been to find a pod that hasn't been updated and pod update that pod. I get all the new project settings, new configuration, etc. with no actual pod changes. But that relies on finding (and having) a pod that hasn't changed. from Recent Questions - Stack Overflow https://ift.tt/3inxWmB https://ift.tt/eA8V8J

XML parsing to transform json using dataweave 2

I am trying to parse an XML recursively to create JSON array using dataweave 2 but I am not able to do so. My Input XML is given below - <?xml version="1.0" encoding="utf-16"?> <MessageParts xmlns="http://schemas.microsoft.com/dynamics/2011/01/documents/Message"> <BillsOfMaterials xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/BillsOfMaterials"> <SenderId>121</SenderId> <BOMVersion class="entity"> <BOMId>BOM0012605</BOMId> <ItemId>9650084</ItemId> <ItemIdCommercial></ItemIdCommercial> <Name>SmartRip for Folding Carton</Name> <RecId>5637161103</RecId> <BOMTable class="entity"> <BOMId>BOM0012605</BOMId> <Name>SmartRip for Folding Carton</Name> <RecId>5637160354</RecId> <BOM class="entity...

DDD validation on full object graph

@Value @Builder public class Parent { @NotNull private String firstName; private Child child; @Builder public class Child { @NotNull private String firstName; here is my challenge, we are doing DDD and we do the validation of objects within constructor or via a build method (builder pattern). What's I would like to achieve is to be able to construct the full object tree in a way that I can collect all validation errors. As you can see with the following code, I will with this only collect the errors of the child missing the missing firstname of the parent. Note that these objects are created manually, otherwise, I would just add @Valid's and such, but I don't think this can work when you do build objects manually. FYI : I use the spring boot stack. Parent.builder() .firstName(null) .child(Child.builder() .firstName(null) .build()) .build(); from Rec...

Count subarrays having sum modulo K same as the length of the subarray

Given an integer K and an array arr[] consisting of N positive integers, the task is to find the number of subarrays whose sum modulo K is equal to the size of the subarray. Examples: Input: arr[] = {1, 4, 3, 2}, K = 3 Output: 4 Explanation: 1 % 3 = 1 (1 + 4) % 3 = 2 4 % 3 = 1 (3 + 2) % 3 = 2 Therefore, subarrays {1}, {1, 4}, {4}, {3, 2} satisfy the required conditions. Input: arr[] = {2, 3, 5, 3, 1, 5}, K = 4 Output: 5 Explanation: The subarrays (5), (1), (5), (1, 5), (3, 5, 3) satisfy the required condition. Naive Approach: The simplest approach is to find the prefix sum of the given array, then generate all the subarrays of the prefix sum array and count those subarrays having sum modulo K equal to the length of that subarray. Print the final count of subarrays obtained. Below is the implementation of the above approach: // C++ program of the above approach     #include <bits/stdc++.h>  using namespace std;     // Function that counts the suba...

Find a number K having sum of numbers obtained by repeated removal of last digit of K is N

Given an integer N, the task is to find an integer K such that the sum of the numbers formed by repeated removal of last digit of K is equal to N. Examples: Input: N = 136 Output: 123 Explanation: Click to enlarge The numbers formed by repeatedly removing the last digit of 123 are {123, 12, 1}. Therefore, the sum of these numbers = 123 + 12 + 1 = 136( = N). Input: N = 107 Output: 98 Explanation: The numbers formed by repeatedly removing the last digit of 98 are {98, 9}. Therefore, the sum of these numbers = 98 + 7 = 107( = N). Approach: The approach is based on the following observations: Consider K = 123. The possible numbers formed from 123 are 1, 12, and 123. Now, 123 can be expressed as 100 + 20 + 3. If all the other numbers are expressed similarly, then the idea is to know the position and frequency of each digit in all the numbers combined, to get the total sum as N. Digit Frequency of each digit Sum units tens hundreds 1 1 1 1 1*1 + 1*10 + 1*100 = 111 2 1 1 ...

Find all array elements occurring more than ⌊N/3⌋ times

Given an array arr[] consisting of N integers, the task is to find all the array elements having frequency more than ⌊N/3⌋ in the given array. Examples: Input: arr[] = {5, 3, 5} Output: 5 Explanation: The frequency of 5 is 2, which is more than N/3( = 3/3 = 1). Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5} Output: 4 7 Explanation: The frequency of 7 and 4 in the array is 3, which is more than N/3( = 8/3 = 2). Approach: To solve the problem, the idea is to use Divide and Conquer technique. Follow the steps below to solve the problem: Initialize a function majorityElement() that will return the count of majority element in the array from any index left to right. Divide the given array arr[] into two halves and repeatedly pass it to the function majorityElement(). Initialize low and high as 0 and (N – 1) respectively. Compute the majority element using the following steps: If low = high: Return arr[low] as the majority element. Find the middle index,say mid(= (low + high)/2). Recursively call f...

Sum of array elements after reversing each element

Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element. Examples: Input: arr[] = {7, 234, 58100} Output: 18939 Explanation: Modified array after reversing each array elements = {7, 432, 18500}. Therefore, the sum of the modified array = 7 + 432 + 18500 = 18939. Input: arr[] = {0, 100, 220} Output: 320 Explanation: Modified array after reversing each array elements = {0, 100, 220}. Therefore, the sum of the modified array = 0 + 100 + 220 = 320. Approach: The idea is to reverse each number of the given array as per the given conditions and find sum of all array elements formed after reversing. Below steps to solve the problem: Initialize a variable, say sum, to store the required sum. Initialize variable count as 0 and f as false to store count of ending 0s of arr[i] and flag to avoid all non-ending 0. Initialize rev as 0 to store reversal of each array element. Traverse the given array and f...

Minimize steps defined by a string required to reach the destination from a given source

Given a string str and four integers X1, Y1, X2 and Y2, where (X1, Y1) denotes the source coordinates and (X2, Y2) denotes the coordinates of the destination. Given a string str, the task is to find the minimum number of steps of the following four types required to reach destination from the source: If str[i] = ‘E’: Convert (X1, Y1) to (X1 + 1, Y1). If str[i] = ‘W’: Convert (X1, Y1) to (X1 – 1, Y1). If str[i] = ‘N’: Convert (X1, Y1) to (X1, Y1 + 1). If str[i] = ‘S’: Convert (X1, Ysub>1) to (X1, Y1 – 1). If the destination cannot be reached, print -1. Note: It is not necessary to use str[i] always and can be skipped. But skipped characters will add to the steps used. Examples Input: str = “SESNW”, x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output: 4 Explanation: To move from (0, 0) to (1, 1), it requires one ‘E’ and one ‘N’. Therefore, the path defined by the substring “SESN” ensures that the destination is reached {(0, 0) -> skip S -> E(1, 0) -> skip S -> (1, 1)}. Therefore, the mi...

Smallest number exceeding N whose Kth bit is set

Given two integers N and K, the task is to find the smallest number greater than N whose Kth bit in its binary representation is set. Examples: Input: N = 15, K = 2 Output: 20 Explanation: The binary representation of (20)10 is (10100)2. The 2nd bit(0-based indexing) from left is set in (20)10. Therefore, 20 is the smallest number greater than 15 having 2nd bit set. Input: N = 16, K = 3 Output: 24 Naive Approach: The simplest approach is to traverse all numbers starting from N + 1 and for each number, check if its Kth bit is set or not. If the such a number is found, then print that number. Below is the implementation of the above approach: // C++ program for the above approach     #include "bits/stdc++.h"  using namespace std;     // Function to find the number greater  // than n whose Kth bit is set  int find_next(int n, int k)  {      // Iterate from N + 1      int M = n + 1;       ...