2020-09-30

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")
            break MainLoop
        default:
        }
        select {
        case <-resumeChan:
            continue
        default:
        }
        waitCtx, cancel := context.WithTimeout(context.Background(), time.Duration(sleepTime)*time.Minute)
        globalstate.WaitCtxCancel = cancel
        <-waitCtx.Done()

    }
    _ = dataStore.SignOutClient(client)
    apiChan <- "stop"
    wg.Done()
    cancel()
}

api has a global variable for the context cancel function:

var appCancel context.CancelFunc

It is set in the beginning by the api.Run method like so:

func Run(cancel context.CancelFunc, wg *sync.WaitGroup, stopChan chan string, db *db.DataStore) {
    ...
    appCancel = cancel
    ...
}

api has a stop function which calls the cancel function:

func requestStop(w http.ResponseWriter, r *http.Request) {
    _ = glg.Info("endpoint hit: shut down service")
    if globalstate.WaitCtxCancel != nil {
        globalstate.WaitCtxCancel()
    }
    state := globalstate.Instance()
    state.ShutdownPending = true

    appCancel()
    encoder := json.NewEncoder(w)
    encoder.SetIndent("", " ")
    _ = encoder.Encode("stop signal received")
}

When the requestStop function is called and thus the context is cancelled, the long running operation (worker.ProcessJob) immediately halts and the entire program deadlocks. Before its next line of code is executed, the code jumps to gopark with reason waitReasonSemAcquire.

The context cancel function is only called in these two locations. So it seems like the other goroutine (runService) can't get a lock for some reason.

My understanding up to now was that the cancel function can be passed around to different goroutines and there are no synchronization issues attached when calling it.

For example, the WaitCtxCancel function never causes a deadlock when I call it.

I could

  • replace the context with a 1-buffered channel and send a message to break out of the loop
  • use my global state struct and a boolean

to determine whether should run.

However, I want to understand what's happening here and why. Also, is there any solution or approach I could use using contexts? It seemed like the "correct" thing to use for use cases like mine.



from Recent Questions - Stack Overflow https://ift.tt/3jj0uim
https://ift.tt/eA8V8J

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 * -1 for element in \
                    self.lib_tree.item(song)['values'][total_values]]
    else:    
        tags.append("songsel")
        self.lib_tree.item(song, tags=(tags))
        # Get StatSize, Count and Seconds
        adj_list = self.lib_tree.item(song)['values'][total_values]  # 1 past

    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
    if self.debug_toggle < 10:
        self.debug_toggle += 1
        print('artist,album,song:',self.lib_tree.item(artist, 'text'), \
                                   self.lib_tree.item(album, 'text'), \
                                   self.lib_tree.item(song, 'text'))
        print('adj_list:',adj_list)

The adj_list has the correct values showing up in debug.

How do I add a list of values to the slice of a list?



from Recent Questions - Stack Overflow https://ift.tt/2Ge686R
https://ift.tt/eA8V8J

Xamarin Visual Studio ios simulator not working

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 enter image description here

My environment is a windows laptop and a macbook pro running visual studio from windows.

  1. I can pair to mac just fine
  2. I am using automatic provisioning which appears to be correct since my team shows up in the team dropdown.
  3. I feel like i did the provisioning correct because team would not show up in dropdown if not.
  4. I have latest xcode installed on mac
  5. 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 this many steps to just run a test. Is there a more simple way to test or am i on the right track?



from Recent Questions - Stack Overflow https://ift.tt/33g76rS
https://ift.tt/3kXZvV1

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(8388638), I get some weird occurrences. writer.writeByte((x >> 16) & 0xfff) writes -128 to the writer Im clueless as why that is.

The same thing happens for outputStream.write((x >> 16) & 0xff); but when I run System.out.println((x >> 16) & 0xff); it outputs 128(positive)

Does anybody know why this is and how I can correct it? (Sorry i'm somewhat experienced in java but im not the best by any means so if this is a really simple fix my bad)



from Recent Questions - Stack Overflow https://ift.tt/2S7DruM
https://ift.tt/eA8V8J

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

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 the slider to slide to the center of the button's titleLabel? For example I want it to slide to the middle of the word Pencil which is the title of the button with its contentEdgeInsets changed and not the button itself.

enter image description here

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/2HIcPi5
https://ift.tt/33eO5X6

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 appreciated



from Recent Questions - Stack Overflow https://ift.tt/2ShhE3H
https://ift.tt/eA8V8J

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=True)
    book_id = db.Column(db.Integer, db.ForeignKey('tag.id'), primary_key=True)
    book = db.relationship('Book', back_populates='tags')
    tag = db.relationship('Tag', back_populates='books')

class Tags(Base):
    name = db.Column(db.String(255), nullable=False)
    books = db.relationship('BooksTags', back_populates="tag")

With this code I have a "Many to Many" structure, and the works pretty well for me, but I'm stuck when I try to create queries based on tag, per example:

  • How do I query this structure to get all book that has all tags present in a list of tags and a minimum number of pages?
  • What if the need to have at least one tag present on the list?

I've been trying to use some aggregation functions like array_agg and group_concat, but I always returns different errors message, I'm not sure how to do it.

On pure SQL I'd query something like this:

SELECT 
  group_concat(tag.name) AS tags, 
  book.name as book_name
FROM 
  book 
  INNER JOIN book_tag ON book.id = book_tag.book_id 
  INNER JOIN tag ON tag.id = book_tag.tag_id 
GROUP BY 
  book.id

But IDK how to filter this query.

Ok after reading and asking some friends helps I've managed to do it with SQL:

In the case of "at least one" tag:

SELECT 
  group_concat(tag.name) AS tags, 
  book.name as book_name
FROM 
  book 
  INNER JOIN book_tag ON book.id = book_tag.book_id 
  INNER JOIN tag ON tag.id = book_tag.tag_id AND tag.name in (<insert tag list>)
GROUP BY 
  book.id

In the case of "must have all" tags:

SELECT 
  group_concat(tag.name) AS tags, 
  book.name as book_name
FROM 
  book 
  INNER JOIN book_tag ON book.id = book_tag.book_id 
  INNER JOIN tag ON tag.id = book_tag.tag_id AND tag.name in (<insert tag list>)
GROUP BY 
  book.id
WHERE
  COUNT(tag.name) > <sizeof tag array>

But I still don't know how to do it with SQLAlchemy.



from Recent Questions - Stack Overflow https://ift.tt/3cI6xdx
https://ift.tt/eA8V8J

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: "Year",
            field: "year"
          },
          {
            headerName: "Sport",
            field: "sport",
            cellEditor: "agRichSelectCellEditor",
            cellEditorParams: {
              values: this.sports
            },
            editable:true
          }
        ];
    
    function getdropdownUIOnKeyPress() {
  function DropdownuiOnKeyPress() {}
  DropdownuiOnKeyPress.prototype.init = function(params) {
    
    this.eInput = document.createElement("input"); //<====
    this.eInput.value = params.value;
  var listMenu = [
      "ActionScript",
      "AppleScript",
      "Asp"
    ];
    // *************************************************************
   // adding dropdown menu on enter of char
  //  https://jqueryui.com/menu/
    var z = document.createElement('div'); // is a node
    var html = "";
    for(var j = 0; j < listMenu.length; j++){
        html +="<img src='https://'>";
        html +="<ul>";
        html +="<li>"+listMenu[j]+"</li>";
        html +="<ul>";
    }
    z.innerHTML = html;
    $("body").appendChild(z);
     // show above div when some character is input 

    $(this.eInput).menu();  
  };
  DropdownuiOnKeyPress.prototype.getGui = function() {
    return this.eInput;
  };
  DropdownuiOnKeyPress.prototype.afterGuiAttached = function() {
    this.eInput.focus();
    this.eInput.select();
  };
  DropdownuiOnKeyPress.prototype.getValue = function() {
    return this.eInput.value;
  };
  DropdownuiOnKeyPress.prototype.destroy = function() {};
  DropdownuiOnKeyPress.prototype.isPopup = function() {
    return false;
  };
  return DropdownuiOnKeyPress;
}

function getdropdownUI() {
  function Dropdownui() {}
  Dropdownui.prototype.init = function(params) {
    this.eInput = document.createElement("input");
    this.eInput.value = params.value;
        var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    // adding of autocomplete- similarly trying to add dropdown above
    $(this.eInput).autocomplete({
      source: availableTags
    });

  };
  Dropdownui.prototype.getGui = function() {
    return this.eInput;
  };
  Dropdownui.prototype.afterGuiAttached = function() {
    this.eInput.focus();
    this.eInput.select();
  };
  Dropdownui.prototype.getValue = function() {
    return this.eInput.value;
  };
  Dropdownui.prototype.destroy = function() {};
  Dropdownui.prototype.isPopup = function() {
    return false;
  };
  return Dropdownui;
}

function getDatePicker() {
  function Datepicker() {}
  Datepicker.prototype.init = function(params) {
    this.eInput = document.createElement("input");
    this.eInput.value = params.value;
    $(this.eInput).datepicker({ dateFormat: "dd/mm/yy" });
  };
  Datepicker.prototype.getGui = function() {
    return this.eInput;
  };
  Datepicker.prototype.afterGuiAttached = function() {
    this.eInput.focus();
    this.eInput.select();
  };
  Datepicker.prototype.getValue = function() {
    return this.eInput.value;
  };
  Datepicker.prototype.destroy = function() {};
  Datepicker.prototype.isPopup = function() {
    return false;
  };
  return Datepicker;
}


from Recent Questions - Stack Overflow https://ift.tt/347EMY4
https://ift.tt/eA8V8J

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 Language syntax. Both compilers generated the exact same assembly (except for the .ident line, but that one doesn't matter):

    .arch armv6
    .eabi_attribute 28, 1
    .eabi_attribute 20, 1
    .eabi_attribute 21, 1
    .eabi_attribute 23, 3
    .eabi_attribute 24, 1
    .eabi_attribute 25, 1
    .eabi_attribute 26, 2
    .eabi_attribute 30, 6
    .eabi_attribute 34, 1
    .eabi_attribute 18, 4
    .file   "main.c"
    .text
    .align  2
    .global main
    .arch armv6
    .syntax unified
    .arm
    .fpu vfp
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    @ link register save eliminated.
    str fp, [sp, #-4]!
    add fp, sp, #0
    mov r3, #0
    mov r0, r3
    add sp, fp, #0
    @ sp needed
    ldr fp, [sp], #4
    bx  lr
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 8.4.0-1ubuntu1~18.04) 8.4.0"
    .section    .note.GNU-stack,"",%progbits

I then tried something else: I just built the object file before linking it to any shared libraries, but even then there will be differences between the native and cross compiled files. Therefore, it's not an issue of the installed libraries being different between Raspbian and Ubuntu.

Problem

If I compile this assembly code using the native compiler and the cross compiler, I will get different executables even though they function the same way.

Question

Even though it's not a big deal since both executables work as expected (they do nothing and return 0) I would like to know:

  • Why does this happen?
  • Is it a matter of using slightly different versions of gcc (8.3.0 vs 8.4.0)?
  • Or are these differences inherent to the operating system that runs the compiler?
  • And is it possible to use a cross compiler to build the exact same executable as a native compiler would? Even when the code is very big and complex?


from Recent Questions - Stack Overflow https://ift.tt/349bZSZ
https://ift.tt/eA8V8J

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 !== bObj.status || aObj.name !== bObj.name) {
        updateArr.push(aObj);
      }
    } else {
      insertArr.push(aObj);
    }
  }
}
console.log("--update--");
console.log(updateArr);
console.log("--insert--");
console.log(insertArr);

Code Links - https://codesandbox.io/s/fervent-kare-ixht9?fontsize=14&hidenavigation=1&theme=dark



from Recent Questions - Stack Overflow https://ift.tt/3jggeCF
https://ift.tt/eA8V8J

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';

// 2 mins in seconds
$inactive = 120; 

if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        redirect('logout.php');
        return;
    }
}

$_SESSION['timeout'] = time();

// Redirect user to login page if not authenticated.
if (! check_auth()) {
    redirect('login.php');
    return;
}

?>
<!doctype html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <div>
        <h1>Website Title</h1> <a href="logout.php">Logout</a> </div>
    <div>
        <p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
    </div>
    <form method="post">
        <input type="text" name="field1" />
        <input type="text" name="field2" />
        <input type="submit" name="submit" value="Save Data"> </form>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
    $(function() {
        $('form').submit(function(e) {
            e.preventDefault();
            $.post({
                url: 'save.php',
                data: $(this).serialize(),
            }).done(response => {
                response = JSON.parse(response);
                if(response.message) {
                    alert(response.message);
                }
            });
        });
    });
    </script>
</body>
</html>

Here is my save.php file:

<?php
declare(strict_types=1);
// Start session.
session_start();
// Include helper functions.
require_once 'helpers.php';

// 2 mins in seconds
$inactive = 120; 

if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        redirect('logout.php');
        return;
    }
}

$_SESSION['timeout'] = time();

// Redirect user to login page if not authenticated.
if (! check_auth()) {
    redirect('login.php');
    return;
}

// save form entries in a file

Here is my helpers.php file:

<?php
declare(strict_types=1);

if (! function_exists('check_auth')) {
    function check_auth(): bool
    {
        return isset($_SESSION['user_id']);
    }
}

if (! function_exists('logout'))
{
    function logout()
    {
        if (isset($_SESSION['user_id'])) {
            $trace = json_decode(file_get_contents('current_user.txt'));

            if ((int) $trace->user_id === $_SESSION['user_id']) {
                $content = isset($trace->revoked_user_id)
                ? json_encode(['user_id' => $trace->revoked_user_id, 'created_at' => (new DateTime('now'))->format('Y-m-d H:i:s')])
                : '';
                file_put_contents('current_user.txt', $content);
            }

            unset($_SESSION['user_id']);
            unset($_SESSION['timeout']);
        }
    }
}

if (! function_exists('redirect')) {
    function redirect(string $url, int $status_code = 303): void
    {
        header('Location: ' . $url, true, $status_code);
        die();
    }
}

Here is my logout.php file:

<?php
declare(strict_types=1);

// Start session.
session_start();

// Include helper functions.
require_once 'helpers.php';

logout();

redirect('login.php');

Problem Statement

I am redirecting to logout.php file once it is idle for 2 minutes in index.php and save.php. Here is what I am noticing -

  • If I am on index.php page and after 2 minutes of inactivity, if I refresh my browser then it logs me out fine without any issues and redirects me to login.php page.
  • Now let's say If I am on index.php page again and after 2 minutes of inactivity if I click on Save Data button then it gives me error on my console but techincally it should have logged me out and redirected me to login.php page.

Below is the ajax call I have in my index.php page -

<script>
$(function() {
    $('form').submit(function(e) {
        e.preventDefault();
        $.post({
            url: 'save.php',
            data: $(this).serialize(),
        }).done(response => {
            response = JSON.parse(response);
            if(response.message) {
                alert(response.message);
            }
        });
    });
});
</script>

I get a json parsing error for my point 2 whenever I click Save Data button after 2 minutes of inactivity. And value of response variable is full login.php in html. I am not sure why it is happening. Do we need to check for session validation in jquery itself before it calls save.php?



from Recent Questions - Stack Overflow https://ift.tt/3kVkVCj
https://ift.tt/eA8V8J

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

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='Day').mean()
mean['Day']=mean.index

maxx=df_selected_station_D.groupby(by='Day').max()
minn=df_selected_station_D.groupby(by='Day').min()
mean['maxx20']=maxx['20 cm']
mean['minn20']=minn['20 cm']

plt.style.use('ggplot')
bx = mean.plot(x='Day', y='20 cm',color='black')
plt.fill_between(mean['Day'],mean['minn20'],mean['maxx20'],color='blue',alpha = 0.2);
bx.set_xlabel("Day of the year")
bx.set_ylabel("Temperature in Celsius")
bx.set_title("Soil Temp, Air Temp, and Snow Depth for " + str(selected_soil_station))

What I have:

enter image description here

What I want to have:

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/36hXZc9
https://ift.tt/3cISGE7

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 == newProductName).SingleOrDefault();
                    if (product is null)
                    {
                        product = new Product { ProductName = newProductName };
                        context.Product.Add(product);
                        context.SaveChanges();
                        transaction.Commit();
                    }
                }
                catch(Exception ex)
                {
                    transaction.Rollback();
                }

            }

            if (product is null)
                return -1;
            else
                return product.Id;
        }
    }
}

Everything works as expected during testing - new product is inserted into the table if it didn't already exist. So I never expect [UQ_ProductName] constraint to be hit because everything is done as a single transaction.

However, in reality this code is a part of the business logic connected to Web API. What happened was that 10 instances of this code using the same new product name got executed almost simultaneously (execution time was the same within one hundredth of a second, we save it in the log table). One of them succeeded (new product name got inserted into the table) but the rest of them failed with following exception:

Violation of UNIQUE KEY constraint 'UQ_ProductName'. Cannot insert duplicate key in object 'dbo.Product'. The duplicate key value is (Basketball). The statement has been terminated.

Why did this happen? Isn't this exactly what my use of transaction was supposed to prevent? That is I think checking whether row with such value already exists and inserting if it doesn't should have been an atomic operation. After the first API call was executed and row was inserted the rest of API calls should have detected value already exists and not tried to insert a duplicate.

Can someone explain if there is an error in my implementation? Clearly it is not working the way I expect.



from Recent Questions - Stack Overflow https://ift.tt/3ijq6ds
https://ift.tt/eA8V8J

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"
      }
    ]
  },
  {
    "name": "Big Bang Theroy",
    "answer": [
      {
        "there_are_superheroes": "NO",
        "new_leaft": [
          {
            "name": "sheldon",
            "there_are_superheroes": "NO"
          }
        ]
      }
    ]
  },
  {
    "name": "dragon ball",
    "answer": [
      {
        "there_are_superheroes": "YES",
        "new_leaft": [
          {
            "name": "goku",
            "answer": [
              {
                "there_are_superheroes": "YES",
                "new_leaft": [
                  {
                    "name": "gohan",
                    "answer": [
                      {
                        "there_are_superheroes": "YES"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

I tried something like this:

format(d) {
if (d.children) {
  d.children.forEach((d) => {
    format;
  });
}
}
format(data);

I don't know how to get the structure I want. I have tried to do it with foreach, but at one point I don't know how to dynamically access until the last children, this is an example but I can have n levels where there can be elements with more children. In my real project I am getting a structure from a web service, I need to structure it like this.

Basically this is something like a tree, so I want to put the first level of children inside an attribute called tree

the attribute called superheroes I want it to be shown inside an array called answer and inside of it, there_are_superheroes it will have its value.

 "name": "MARVEL",
 "answer": [
        {
          "there_are_superheroes": "YES",  --> `there_are_superheroes` was `superheroes`,
          "new_leaft": [
                    {
 .
 .

and new_leaft is the equivalent of children

As I said, I know how to go through objects and arrays but in this case, I don't know how to go to the last children nested of each object.



from Recent Questions - Stack Overflow https://ift.tt/30inMNL
https://ift.tt/eA8V8J

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">
          <BOMId>BOM0012605</BOMId>
          <BOMQty>1.0000</BOMQty>
          <BOMType>Item</BOMType>
          <ItemId>9650092</ItemId>
          <RecId>5637307757</RecId>
          <UnitId>PCS</UnitId>
          <InventDimBOM class="entity">
            <RecId>5637213290</RecId>
          </InventDimBOM>
          <BOMTable>
            <BOMId>BOM0012613</BOMId>
            <Name>FlexRip Classic Intel kernel and tools</Name>
            <RecId>5637161355</RecId>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9650079</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM0012613</BOMId>
              <RecId>5637307799</RecId>
            </BOM>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9644919T</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM0012613</BOMId>
              <RecId>5637307800</RecId>
            </BOM>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9644920</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM0012613</BOMId>
              <RecId>5637307801</RecId>
            </BOM>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9700720Z</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM0012613</BOMId>
              <RecId>5637307802</RecId>
              <BOMTable>
                <BOMId>BOM012173</BOMId>
                <Name></Name>
                <RecId>5637157832</RecId>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>9700595</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM012173</BOMId>
                  <RecId>5637333626</RecId>
                </BOM>
              </BOMTable>
              <BOMTable>
                <BOMId>BOM012173</BOMId>
                <Name></Name>
                <RecId>5637157832</RecId>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>9700595</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM012173</BOMId>
                  <RecId>5637333626</RecId>
                </BOM>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>9608224Z</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM012173</BOMId>
                  <RecId>5637333627</RecId>
                </BOM>       
              </BOMTable>
            </BOM>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9683336L</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM0012613</BOMId>
              <RecId>5637307803</RecId>
              <BOMTable>
                <BOMId>BOM0012781</BOMId>
                <Name>Esko Suite 12.1 A5 Software box</Name>
                <RecId>5637165603</RecId>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>G211249</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM0012781</BOMId>
                  <RecId>5637309242</RecId>
                </BOM>
              </BOMTable>
              <BOMTable>
                <BOMId>BOM0012781</BOMId>
                <Name>Esko Suite 12.1 A5 Software box</Name>
                <RecId>5637165603</RecId>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>G211249</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM0012781</BOMId>
                  <RecId>5637309242</RecId>
                </BOM>
                <BOM>
                  <BOMType>Item</BOMType>
                  <ItemId>G25583961_24</ItemId>
                  <BOMQty>1.00</BOMQty>
                  <UnitId>PCS</UnitId>
                  <BOMId>BOM0012781</BOMId>
                  <RecId>5637309243</RecId>
                </BOM>
              </BOMTable>
            </BOM>
          </BOMTable>
        </BOM>
        <BOM class="entity">
          <BOMId>BOM0012605</BOMId>
          <BOMQty>1.0000</BOMQty>
          <BOMType>Item</BOMType>
          <ItemId>9608221Z</ItemId>
          <RecId>5637307758</RecId>
          <UnitId>PCS</UnitId>
          <InventDimBOM class="entity">
            <RecId>5637213290</RecId>
          </InventDimBOM>
        </BOM>
        <BOM class="entity">
          <BOMId>BOM0012605</BOMId>
          <BOMQty>1.0000</BOMQty>
          <BOMType>Item</BOMType>
          <ItemId>9700624Y</ItemId>
          <RecId>5637307759</RecId>
          <UnitId>PCS</UnitId>
          <InventDimBOM class="entity">
            <RecId>5637213291</RecId>
          </InventDimBOM>
          <BOMTable>
            <BOMId>BOM012172</BOMId>
            <Name></Name>
            <RecId>5637157831</RecId>
            <BOM>
              <BOMType>Item</BOMType>
              <ItemId>9644921</ItemId>
              <BOMQty>1.00</BOMQty>
              <UnitId>PCS</UnitId>
              <BOMId>BOM012172</BOMId>
              <RecId>5637333624</RecId>
            </BOM>
          </BOMTable>
        </BOM>
        <BOM class="entity">
          <BOMId>BOM0012605</BOMId>
          <BOMQty>1.0000</BOMQty>
          <BOMType>Item</BOMType>
          <ItemId>9700815</ItemId>
          <RecId>5637307760</RecId>
          <UnitId>PCS</UnitId>
          <InventDimBOM class="entity">
            <RecId>5637213290</RecId>
          </InventDimBOM>
        </BOM>
      </BOMTable>
      <InventDim class="entity">
        <RecId>5637199988</RecId>
      </InventDim>
    </BOMVersion>
  </BillsOfMaterials>
</MessageParts>

I want to create JSON array of all the BOMs (a flat structure with no hierarchy) with parentId as RecId of parent BOM as shown below -

Output -

[
    {
        "id": "5637307757",
        "productId": "9650092",                                                                                                                                 
        "parentId": null
    },
    {
        "id": "5637307799",
        "productId": "9650079",
        "parentId": "5637307757"
    },
    {
        "id": "5637307800",
        "productId": "9644919T",
        "parentId": "5637307757"
    },
    {
        "id": "5637307801",
        "productId": "96AR060W",
        "parentId": "5637307757"
    },
    
    {
        "id": "5637307802",
        "productId": "9700720Z",
        "parentId": "5637307757"
    },
    {
        "id": "5637333626",
        "productId": "9700595",
        "parentId": "5637307802"
    },  
    
    {
        "id": "5637333626",
        "productId": "9700595",
        "parentId": "5637307802"
    },
    {
        "id": "5637333627",
        "productId": "9608224Z",
        "parentId": "5637307802"
    },  
    {
        "id": "5637307803",
        "productId": "9683336L",
        "parentId": "5637307757"
    },
    {
        "id": "5637309242",
        "productId": "G211249",
        "parentId": "5637307803"
    },
    {
        "id": "5637309242",
        "productId": "G211249",
        "parentId": "5637307803"
    },
    {
        "id": "5637309243",
        "productId": "G25583961_24",
        "parentId": "5637307803"
    }
]

Mapping Rules -

  1. id : BOM -> RecId
  2. productId : BOM -> ItemId
  3. parentId : the RecId of the parent BOM

The difference with the suggested answer is that I need to set parentid with the immediate recid of the BOM and not of the BOM table.



from Recent Questions - Stack Overflow https://ift.tt/2EKjIhD
https://ift.tt/eA8V8J

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 Recent Questions - Stack Overflow https://ift.tt/3cBGo04
https://ift.tt/eA8V8J

2020-09-29

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 subarrays 
// having sum modulo k equal to the 
// length of subarray 
  
long long int countSubarrays( 
    int a[], int n, int k) 
  
    // Stores the count 
    // of subarrays 
    int ans = 0; 
  
    // Stores prefix sum 
    // of the array 
    vector<int> pref; 
    pref.push_back(0); 
  
    // Calculate prefix sum array 
    for (int i = 0; i < n; i++) 
        pref.push_back((a[i] 
                        + pref[i]) 
                       % k); 
  
    // Generate all the subarrays 
    for (int i = 1; i <= n; i++) { 
        for (int j = i; j <= n; j++) { 
  
            // Check if this subarray is 
            // a valid subarray or not 
            if ((pref[j] - pref[i - 1] + k) % k 
                == j - i + 1) { 
                ans++; 
            } 
        } 
    } 
  
    // Total count of subarrays 
    cout << ans << ' '; 
  
// Driver Code 
int main() 
    // Given arr[] 
    int arr[] = { 2, 3, 5, 3, 1, 5 }; 
  
    // Size of the array 
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Given K 
    int K = 4; 
  
    // Function Call 
    countSubarrays(arr, N, K); 
  
    return 0; 
Output:
5
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The idea is to generate the prefix sum of the given array and then the problem reduces to the count of subarray such that (pref[j] – pref[i]) % K equal to (j – i), where j > i and (j − i) ≤ K. Below are the steps:

Create an auxiliary array pref[] that stores the prefix sum of the given array.
To count the subarray satisfying the above equation, the equation can be written as:
(pref[j] − j) % k = (pref[i] − i) % k, where j > i and (j − i) ≤ K

Traverse the prefix array pref[] and for each index j store the count (pref[j] – j) % K in a Map M.
For each element pref[i] in the above steps update the count as M[(pref[i] – i % K + K) % K] and increment the frequency of (pref[i] – i % K + K) % K in the Map M.
Print the value of the count of subarray after the above steps.
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 subarrays 
// s.t. sum of elements in the subarray 
// modulo k is equal to size of subarray 
long long int countSubarrays( 
    int a[], int n, int k) 
    // Stores the count of (pref[i] - i) % k 
    unordered_map<int, int> cnt; 
  
    // Stores the count of subarray 
    long long int ans = 0; 
  
    // Stores prefix sum of the array 
    vector<int> pref; 
    pref.push_back(0); 
  
    // Find prefix sum array 
    for (int i = 0; i < n; i++) 
        pref.push_back((a[i] 
                        + pref[i]) 
                       % k); 
  
    // Base Condition 
    cnt[0] = 1; 
  
    for (int i = 1; i <= n; i++) { 
  
        // Remove the index at present 
        // after K indices from the 
        // current index 
        int remIdx = i - k; 
  
        if (remIdx >= 0) { 
            cnt[(pref[remIdx] 
                 - remIdx % k + k) 
                % k]--; 
        } 
  
        // Update the answer for subarrays 
        // ending at the i-th index 
        ans += cnt[(pref[i] 
                    - i % k + k) 
                   % k]; 
  
        // Add the calculated value of 
        // current index to count 
        cnt[(pref[i] - i % k + k) % k]++; 
    } 
  
    // Print the count of subarrays 
    cout << ans << ' '; 
  
// Driver Code 
int main() 
    // Given arr[] 
    int arr[] = { 2, 3, 5, 3, 1, 5 }; 
  
    // Size of the array 
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Given K 
    int K = 4; 
  
    // Function Call 
    countSubarrays(arr, N, K); 
  
    return 0; 
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(N)

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 2*1 + 2*10 = 22
3 1 3*1 = 3
Now, for the given number N of length L. Divide the number with L number of 1s to get the highest place digit.
Calculate the remainder which will be our newly formed N.
Again divide the newly formed N with (L – 1) number of 1s to get 2nd highest place digit and continue till the L becomes 0.
Follow the steps below to solve the problem:

Let L be the count of digits in the given number N.
Initialize a string str as L numbers of 1s in it.
Initialize a variable ans as zero that will store the resultant number K.
Iterate until the string str is not empty and follow the steps below:
Convert the string str to number using the function stoi() and store it in M.
Divide N by M and update ans as:
ans = ans*10 + (N/M)

Update N to N % M.
Remove the last character from the string str.
After the above steps, print the value stored in the ans which is the required value of K.
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 value of K 
int findK(int N, int l) 
    // Stores l number of 1s 
    string ones = ""; 
  
    while (l--) { 
  
        // Storing 1's 
        ones = ones + '1'; 
    } 
  
    // Stores the value of K 
    int ans = 0; 
  
    // Iterate until ones is empty 
    while (ones != "") { 
  
        // Convert ones to number 
        int m = stoi(ones); 
  
        // Update the ans 
        ans = (ans * 10) + (N / m); 
  
        // Update N to N%m 
        N = N % m; 
  
        // Removing last digit from ones 
        ones.pop_back(); 
    } 
  
    // Return the value of K 
    return ans; 
  
// Driver Code 
int main() 
    // Given number N 
    int N = 136; 
  
    // Number of digits in N 
    int L = to_string(N).length(); 
  
    // Funtion Call 
    cout << findK(N, L); 
  
    return 0; 
Output:
123
Time Complexity: O(log10N)
Auxiliary Space: O(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 for both the left and right subarrays as majorityElement(arr, low, mid) and majorityElement(arr, mid + 1, high).
After completing the above steps, merge both the subarrays and return the majority element.
Whenever the required majority element is found, append it to the resultant list.
Print all the majority elements stored in the list.
Below is the implementation of the above approach:

# Python program for the above approach 
  
class Solution: 
  
    # Function to find all elements that 
    # occurs >= N/3 times in the array 
    def majorityElement(self, a): 
  
        # If array is empty return 
        # empty list 
        if not a: 
            return [] 
  
        # Function to find the majority 
        # element by Divide and Conquer 
        def divideAndConquer(lo, hi): 
            if lo == hi: 
                return [a[lo]] 
              
            # Find mid 
            mid = lo + (hi - lo)//2
  
            # Call to the left half 
            left = divideAndConquer(lo, mid) 
  
            # Call to the right half 
            right = divideAndConquer(mid + 1, hi) 
              
            # Stores the result 
            result = [] 
            for numbers in left: 
                if numbers not in right: 
                    result.append(numbers) 
  
            result.extend(right) 
  
            # Stores all majority elements 
            ans = [] 
  
            for number in result: 
                count = 0
                  
                # Count of elements that 
                # occurs most 
                for index in range(lo, hi + 1): 
                    if a[index] == number: 
                        count += 1
                          
                # If the number is a 
                # majority element 
                if count > (hi - lo + 1)//3: 
                    ans.append(number) 
              
            # Return the list of element 
            return ans 
          
        # Function Call 
        print(divideAndConquer(0, len(a) - 1)) 
  
  
# Driver Code 
if __name__ == "__main__": 
  
    # Given array a[] 
    a = [7, 7, 7, 3, 4, 4, 4, 6] 
    object = Solution() 
  
    # Function Call 
    object.majorityElement(a) 
Output:
[7, 4]
Time Complexity: O(N*log N)
Auxiliary Space: O(log N)

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 for each array element do the following operation:
Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.
Reset f with true that means all ending 0 digits have been considered.
Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and  arr[i] = arr[i]/10.
After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number.
For each reverse number in the above step, add that value to the resultant sum.
Below is the implementation of the above approach:

// Java program for the above approach 
  
import java.util.*; 
  
class GFG { 
  
    // Function to find the sum of elements 
    // after reversing each element in arr[] 
    static void totalSum(int[] arr) 
    { 
        // Stores the final sum 
        int sum = 0; 
  
        // Traverse the given array 
        for (int i = 0; 
             i < arr.length; i++) { 
  
            // Stores count of ending 0s 
            int count = 0; 
  
            int rev = 0, num = arr[i]; 
  
            // Flag to avoid count of 0s 
            // that doesn't ends with 0s 
            boolean f = false; 
  
            while (num > 0) { 
  
                // Count of ending 0s 
                while (num > 0 && !f 
                       && num % 10 == 0) { 
                    count++; 
                    num = num / 10; 
                } 
  
                // Update flag with true 
                f = true; 
  
                // Reversing the num 
                if (num > 0) { 
                    rev = rev * 10
                          + num % 10; 
  
                    num = num / 10; 
                } 
            } 
  
            // Add all ending 0s to 
            // end of rev 
            if (count > 0) 
                rev = rev 
                      * (int)Math.pow(10, 
                                      count); 
  
            // Update sum 
            sum = sum + rev; 
        } 
  
        // Print total sum 
        System.out.print(sum); 
    } 
  
    // Driver Code 
    public static void
        main(String[] args) 
    { 
        // Given arr[] 
        int[] arr = { 7, 234, 58100 }; 
  
        // Function Call 
        totalSum(arr); 
    } 
Output:
18939

Time Complexity: O(N*log10M), where N denotes the length of the array and M denotes maximum array element.
Auxiliary Space: O(1)

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 minimum length of the string traversed is 4.


Input: str = “NNNNNNNN”, x1 = 1, y1 = 1, x2 = 1, y2 = 2
Output: 1
Explanation:
From current position (1, 1) it can move to co-ordinate (1, 2) using first ‘N’ direction.
Therefore, the minimum length of the string traverse is 1.

Approach: The idea is to iterate through the string and perform the moves until the destination is reached. Below are the steps:

Initialize four variable pos1, pos2, pos3 and pos4 to store the positions of E, W, N, S respectively.
Now, check if (x1, y1) is equal to (x2, y2) then the current position is already the destination so print 0.
Otherwise, iterate over the string and check the following four conditions:
If x2 > x1 then iterate until a ‘E’ comes and update that index in pos1.
If x2 < x1 then iterate until a ‘W’ comes and update that index in pos2.
If y2 > y1 then iterate until a ‘N’ comes and update that index in pos3.
If y2 < y1 then iterate until a ‘S’ comes and update that index in pos4.
After performing above operations check if x1 != x2 and y1 != y2 then print “-1” that means it is impossible to reach the destination.
Otherwise, find the max of pos1, pos2, pos3 and pos4 and print it.
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 minimum length 
// of string required to reach from 
// source to destination 
void minimum_length(int x1, int y1, 
                    int x2, int y2, 
                    string str) 
    // Size of the string 
    int n = str.size(); 
  
    // Stores the index of the four 
    // directions E, W, N, S 
    int pos1, pos2, pos3, pos4; 
    pos1 = -1; 
    pos2 = -1; 
    pos3 = -1; 
    pos4 = -1; 
  
    // If destination reached 
    if (x1 == x2 && y1 == y2) { 
        cout << 0 << endl; 
    } 
  
    // Iterate over the string 
    else { 
        for (int i = 0; i < n; i++) { 
  
            // Move east 
            if (x2 > x1) { 
  
                // Change x1 according 
                // to direction E 
                if (str[i] == 'E') { 
                    x1 = x1 + 1; 
                    if (x1 == x2) { 
                        pos1 = i; 
                    } 
                } 
            } 
  
            // Move west 
            if (x2 < x1) { 
  
                // Change x1 according 
                // to direction W 
                if (str[i] == 'W') { 
                    x1 = x1 - 1; 
                    if (x1 == x2) { 
                        pos2 = i; 
                    } 
                } 
            } 
  
            // Move north 
            if (y2 > y1) { 
  
                // Change y1 according 
                // to direction N 
                if (str[i] == 'N') { 
                    y1 = y1 + 1; 
                    if (y1 == y2) { 
                        pos3 = i; 
                    } 
                } 
            } 
  
            // Move south 
            if (y2 < y1) { 
  
                // Change y1 according 
                // to direction S 
                if (str[i] == 'S') { 
                    y1 = y1 - 1; 
                    if (y1 == y2) { 
                        pos4 = i; 
                    } 
                } 
            } 
        } 
  
        int z; 
        // Store the max of all positions 
        z = max(max(max(pos1, pos2), 
                    pos3), 
                pos4); 
  
        // Print the minimum length of 
        // string required 
        if (x1 == x2 && y1 == y2) { 
            cout << z + 1 << endl; 
        } 
  
        // Otherwise, it is impossible 
        else { 
            cout << "-1" << endl; 
        } 
    } 
  
// Driver Code 
int main() 
    // Given string 
    string str = "SESNW"; 
  
    // Given source and destination 
    int x1 = 0, x2 = 1, y1 = 0, y2 = 1; 
  
    // Function Call 
    minimum_length(x1, y1, x2, y2, str); 
    return 0; 
Output:
4

Time Complexity: O(N)
Auxiliary Space: O(1)

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; 
  
    while (1) { 
  
        // Check if Kth bit is 
        // set or not 
        if (M & (1ll << k)) 
            break; 
  
        // Increment M for next number 
        M++; 
    } 
  
    // Return the minimum value 
    return M; 
  
// Driver Code 
int main() 
    // Given N and K 
    int N = 15, K = 2; 
  
    // Function Call 
    cout << find_next(N, K); 
  
    return 0; 
Output:
20
Time Complexity: O(2K)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, there exists two possibilities:

Kth bit is not set: Observe that bits having positions greater than K will not be affected. Therefore, make the Kth bit set and make all bits on its left 0.
Kth bit is set: Find the first least significant unset bit and set it. After that, unset all the bits that are on its right.
Follow the steps below to solve the problem:

Check if the Kth bit of N is set. If found to be true, then find the lowest unset bit and set it and change all the bits to its right to 0.
Otherwise, set the Kth bit and update all the bits positioned lower than K to 0.
Print the answer after completing the above steps.
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) 
    // Stores the resultant number 
    int ans = 0; 
  
    // If Kth bit is not set 
    if ((n & (1ll << k)) == 0) { 
        int cur = 0; 
  
        // cur will be the sum of all 
        // powers of 2 < k 
        for (int i = 0; i < k; i++) { 
  
            // If the current bit is set 
            if (n & (1ll << i)) 
                cur += 1ll << i; 
        } 
  
        // Add Kth power of 2 to n and 
        // subtract the all powers of 2 
        // less than K that are set 
        ans = n - cur + (1ll << k); 
    } 
  
    // If the kth bit is set 
    else { 
        int first_unset_bit = -1, cur = 0; 
  
        for (int i = 0; i < 64; i++) { 
  
            // First unset bit position 
            if ((n & (1ll << i)) == 0) { 
                first_unset_bit = i; 
                break; 
            } 
  
            // sum of bits that are set 
            else
                cur += (1ll << i); 
        } 
  
        // Add Kth power of 2 to n and 
        // subtract the all powers of 2 
        // less than K that are set 
        ans = n - cur 
              + (1ll << first_unset_bit); 
  
        // If Kth bit became unset 
        // then set it again 
        if ((ans & (1ll << k)) == 0) 
            ans += (1ll << k); 
    } 
  
    // Return the resultant number 
    return ans; 
  
// Driver Code 
int main() 
    int N = 15, K = 2; 
  
    // Print ans 
    cout << find_next(N, K); 
  
    return 0; 
Output:
20
Time Complexity: O(K)
Auxiliary Space: O(1)