Amazon web services – How to create an AWS auto-scale policy to match the size of a SQS queue?

I build a rendering farm with the help of SQS and self-scale groups.

I think my use case is one of the few where I actually wish my group's capacity to match the size of the queue, within the limit of one limit .

How to write an automatic scaling strategy that keeps the group's capacity at the size of the queue?

Recursion – What is an example of a recursive (simple) queue algorithm that does not use a helper function?

Here's an example facing you: write a function that takes two arguments a and b and returns the sum of the integers from 0 to amore b.

Here's another example: Write a function that returns the last element of a list or a special value if the list is empty.

let rec last l =
  match l with
  | () -> None
  | (x) -> Some x
  | h::t -> last t

Here is another example, in imperative language: apply a function to all elements of a list, in order, without returning a value.

let rec iter f l =
  match l with
  | () -> ()
  | h::t -> f h; iter f t

So, you can see that the recursive queue does not to have take an extra argument. However, taking an additional argument is a common pattern, and there is a deep reason for that.

A common reason for writing a recursive function is to traverse a recursive data structure. For example, the list data structure is defined recursively: a list is either the empty list ("nil") or a pair ("against") consisting of an element ("head") and a list ("tail"). In Ocaml syntax:

type list_of_foo = Foo_nil | Foo_cons foo * list_of_foo;; (* Foo_cons (head, tail) *)

To act on a list, you must specify what to do on the empty list and what to do on a non-empty list. To browse the entire list with a function, you make a recursive call to process the queue in the case of a non-empty list. A generic list path is called a fold. Writing a recursive function is a way of writing a crease; another way is to call a generic fold function and tell him what to do with nil and what to do with a counter (depending on the head and the result of the treatment of the tail of the list).

This is generalized to all recursive data structures. A peculiarity of the lists is that there is never more than one sub-list, so the call to process the queue can be a tail call. Contrast with a binary tree, for example:

type btree = Leaf of int | Node of btree * btree

To treat a btreewhen you reach a Nodeyou must treat both the first subtree (left child) and the second subtree (right child). They can not be both queue calls. But with lists, the recursive call can be a final call.

Integers do not look much like a data structure. But in reality, the recursion on an integer is usually based on the structure of integers. For example, when you recurse by enumerating integers from 0 to n or n to 0 (or 1 to n, etc.), you use the structure provided by Peano's axioms: an integer is either 0, or the successor of an integer.

So you have a recursive function that takes a data structure as an argument. It makes a recursive call based on a substructure of the original data. What is he returning? If the recursive call is a final call, what it returns should be the value returned in case the function does not make a recursive call. This is often the case "initial", for example 0 for a recurring function on an integer or the empty list for a recurring function on a list. What can you return in the case of departure? If you return a constant, it is not very interesting. If you want to return something that depends on the information collected from the data structure, you must pass this information through the final calls. And that's where the extra argument comes from. A tail-recursive function requires an additional argument (in addition to the data structure on which it is recursive) to collect data read from the data structure.

In the case of departure, you often want to return a constant. Therefore, you write a pair of functions: a recursive function with two arguments (the structure of data to browse and the accumulator), which returns the accumulator when it reaches the end of the data; and an auxiliary function just to give an initial value to the accumulator. This corresponds to the initial value argument for fold functions.

c # – Queue Management Project – Recommendations

I would like to develop a patient queue management system with online booking.

In this case, there are options for generating queue tokens for different departments. For example, department A will have chips of A1, A2, A3, and so on. And department B will have chips of B1, B2, B3, etc.

When calling a token if the patient is not available, this token must be added after the next 3 tokens.

Other than that, there is an online module where a patient can book a specific time slot. Online tokens must be inserted between normal tokens at a specified time.

Given all these requirements, anyone can suggest a better solution. Will the C # queue be a better solution? or any other ideas / suggestions?

Thank you

performance – LeetCode: Reconstruction of the queue by C # height

https://leetcode.com/problems/queue-reconstruction-by-height/

Suppose you have a random list of people in a queue. Each
nobody is described by a pair of integers $ (h, k) $, or $ h $ is the
height of the person and $ k $ is the number of people in front of this
who has a height greater than or equal to $ h $. Write a
algorithm to rebuild the queue.

Note: The number of people is less than 1,100.

Example

Input:
((7,0), (4,4), (7,1), (5,0), (6,1), (5,2))

Output:
((5,0), (7,0), (5,2), (6,1), (4,4), (7,1))

Please consider for performance

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace SortingQuestions
{
    /// 
    /// https://leetcode.com/problems/queue-reconstruction-by-height/
    /// 
    (TestClass)
    public class ReconstructQueueTest
    {
        (TestMethod)
        public void ReconstructQueueExampleTest()
        {
            int()() people = new int(6)();
            people(0) = new() { 7, 0 };
            people(1) = new() { 4, 4 };
            people(2) = new() { 7, 1 };
            people(3) = new() { 5, 0 };
            people(4) = new() { 6, 1 };
            people(5) = new() { 5, 2 };

            int()() expected = new int(6)();
            expected(0) = new() { 5, 0 };
            expected(1) = new() { 7, 0 };
            expected(2) = new() { 5, 2 };
            expected(3) = new() { 6, 1 };
            expected(4) = new() { 4, 4 };
            expected(5) = new() { 7, 1 };
            int()() res = ReconstructQueueClass.ReconstructQueue(people);
            for (var index = 0; index < res.Length; index++)
            {
                CollectionAssert.AreEqual(expected(index), res(index));
            }
        }
    }

    public class ReconstructQueueClass
    {
        public static int()() ReconstructQueue(int()() people)
        {
            int()() res = new int(people.Length)();
            Array.Sort(people, new PairComparer());

            List list = new List();

            for (int i = 0; i < people.Length; i++)
            {
                list.Add(i); //a list of indices 0,1,2,3,4...
                res(i) = new int(2);
            }

            for (int i = 0; i < people.Length; i++)
            {
                int index = list(people(i)(1)); //the index in the result is the number of people before you
                res(index)(0) = people(i)(0);
                res(index)(1) = people(i)(1);
                list.RemoveAt(people(i)(1)); // we remove the index from the list so we keep only the un used ones
            }
            return res;
        }
    }

    /// 
    /// sort the people, have min height first
    /// for the same height for example 5,0 and 5,2
    /// 5,2 is before 5,0
    /// 
    public class PairComparer : IComparer
    {
        public int Compare(int() x, int() y)
        {
            if (x(0) != y(0))
            {
                return x(0) - y(0);// we want min value first
            }
            return y(1) - x(1);
        }
    }
}

javascript – unable to read ytdl data queue

I'm trying to add a music feature to my bot (discord.js) and I have a problem. When I start with Visual Studio, everything works fine, but when I download my bot on GitHub and launch it via Heroku, the problem is this:

When I type s! Play (name or URL)

Everything works, bot joins the channel, etc., but he does not play music! And that's a problem for a music bot!

I leave my code for the command set here:

const Discord = require('discord.js');
const ytdl = require('ytdl-core');

async function play(client, message, ops, data) {

    client.channels.get(data.queue(0).announceChannel).send(`Joue : ${data.queue(0).songTitle} | Requete par : ${data.queue(0).requester}`)

    console.log(data.queue(0).url)
    data.dispatcher = await data.connection.playStream(ytdl(data.queue(0).url, {filter: 'audioonly'}));
    data.dispatcher.guildID = data.guildID;
    data.dispatcher.once('end', function() {
        end(client, ops, this);
    });
}

function end(client, ops, dispatcher) {

    let fetched = ops.active.get(dispatcher.guildID);

    fetched.queue.shift();

    if (fetched.queue.length > 0) {

        ops.active.set(dispatcher.guildID, fetched);

        play(client, ops, fetched);

    } else {
        ops.active.delete(dispatcher.guildID);

        let vc = client.guilds.get(dispatcher.guildID).client.voiceChannel;
        if(vc) { vc.leave()}
    }
}

module.exports.run = async (client, message, args, ops) => {

    if(!args(0)) {
        message.channel.send(`Veuillez renseigner un URL !`)
    } else {

        if (!message.member.voiceChannel) { return message.channel.send(`Veuillez vous connecter à un salon vocal !`)}

        else {

            let validate = await ytdl.validateURL(args(0));

            if(!validate) { 

                let commandFile = require(`./search.js`);
                commandFile.run(client, message, args, ops);

            }

            if(validate) {
                if(!message.guild.member(client.user).voiceChannel) { message.channel.send(`Le bot a bien rejoint le vocal !`)}
                let info = await ytdl.getInfo(args(0));

                let data = ops.active.get(message.guild.id) || {};

                if (!data.connection) { data.connection = await message.member.voiceChannel.join() };
                if (!data.queue) { data.queue = ()};
                data.guildID = message.guild.id; 

                data.queue.push({
                    songTitle: info.title,
                    requester: message.author.username,
                    url: args(0),
                    announceChannel: message.channel.id
                });

                if (!data.dispatcher) { 
                    play(client, ops, data) 
                } else {
                    message.channel.send(`Ajouté a la queue : ${info.title} | Requete par : ${message.author.username}`);
                }

                ops.active.set(message.guild.id, data);

            }

        }
    }
}

module.exports.help = {
    name:'play'
}```

//as well as the file for the command search because he's required for the play command but I don't think the error come from here, because this functionnality is working, except that it's not playing music as I said.

```const search = require('yt-search');
const Discord = require('discord.js');

module.exports.run = (client, message, args, ops) => {

    search(args.join(' '), function(err, res) {

        if(err) {return message.channel.send(`Une erreur est survenue.`)};

        let videos = res.videos.slice(0, 10);
        let resp = '';
        for (var i in videos) {
            resp += `**(${parseInt(i)+1}):** `${videos(i).title}`n`;
        };

        resp += `n**Choisissez un nombre entre** `1 et ${videos.length}``;

        message.channel.send(resp);

        const filter = m => !isNaN(m.content) && m.content < videos.length+1 && m.content > 0;

        const collector = message.channel.createMessageCollector(filter);

        collector.videos = videos;
        collector.once('collect', function(m) {

            let commandFile = require(`./play_music.js`);
            commandFile.run(client, message, (this.videos(parseInt(m.content)-1).url), ops);

        });

    });

};

module.exports.help = {
    name:'search'
};```

//And this is the error it returns to me :

```2019-09-19T18:52:45.913870+00:00 app(worker.1): (node:4) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'queue' of undefined
2019-09-19T18:52:45.913885+00:00 app(worker.1):     at play (/app/Commandes/play_music.js:6:30)
2019-09-19T18:52:45.913887+00:00 app(worker.1):     at Object.module.exports.run (/app/Commandes/play_music.js:73:21)
2019-09-19T18:52:45.913891+00:00 app(worker.1):     at process._tickCallback (internal/process/next_tick.js:68:7)
2019-09-19T18:52:45.913937+00:00 app(worker.1): (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...```

//Thanks for your consideration ! ;) (French, sorry for bad english)

Error printing when I try to access the print queue: "Windows can not access the device, path or file specified …"

Complete error message:

Windows can not access the specified device, path, or file. You may not have the appropriate permissions to access the item.

Why would my printer give me this error all at once? I can not print anything either – the queue is blocked or something like that!

cron – Kubernetes CronJob, do not queue for missed jobs

I have read these documents many times but I still do not understand what startingDeadlineSeconds Is.

I'm trying to understand if it's possible to avoid reprogramming a job if a work in progress is being run (with CronJob) and just leave following planned work picking up where he had stopped.

I have extremely erratic working times (problem to be solved separately). It can take 1 hour or up to 24 hours. So, sometimes, if a job takes a whole day, but I have scheduled it to run every 12 hours, I get a queue of another job that starts immediately when the last is displayed. Completed.

I really would just like to do it never put a job in queue and create only new jobs on the following expected time.

Is it possible with Kubernetes CronJob?

c # – Custom queue class with O (1) Enqueue and O (n) Dequeue

I'm implementing a queue class in C # using a Node / LinkedList class that I've also implemented, and I'm wondering if there is a way to implement it. queuing and waiting queue queuing methods, both in terms of algorithmic efficiency of $ O (1) $.

in the Queue class, I have a tail and head field, and I managed to implement the queuing method $ O (1) $but the queue is $ O (n) $.

Here is the code of the queue output method:

public T Dequeue()
{
    if (IsEmpty())
        throw new InvalidOperationException("The queue is empty");

    T data = head.Data;

    if (tail == null)
    {
        head = null;
        return data;
    }

    Node temp = tail;

    while (temp.Next != head)
        temp = temp.Next;

    temp.Next = null;
    head = temp;

    if (tail == head)
        tail = null;

    return data;
}

trees – Maximum space consumption of stack and queue for DFS and BFS

I'm trying to determine the maximum memory consumption of the data structure (pending nodes) (stack / queue) for both trips: BFS and DFS (in pre-order).

Since moving BFS and DFS have node discovery control (no loops), we can analyze the problem by thinking in terms of trees instead of graphs, your starting node being taken as root, as habit.

I began by assuming that the resulting displacement is a complete tree (all leaves have the same depth), with a height $ h $, $ n $ nodes, and thus all nodes having a degree $ d $ (except the leaves).

Of course, since the tree is complete, $ n $ can be calculated from $ h $ and $ d $:

$$ n = frac {1 – d ^ {h + 1}} {1 – d} $$

Under this assumption, the worst case scenario for DFS is when you are in the deepest non-leaf node of the first branch of the tree: every time you eject a node, you insert all of its children, for each level, you have $ D – $ 1 knots waiting in the stack except in the last non-leaf element where all his children are inserted.

If you, instead of being in the first limb, were in another, you would have a limb with less than $ d – $ 1 children waiting in the stack and so you have fewer nodes in the stack.

The maximum memory consumption of DFS for a complete graph with homogeneus degree is therefore ($ ms $ represent maximum space):

$$ ms = h * (d – 1) + 1 $$

This last + 1 represents the extra child for the last non-leaf node. For example, for a tree with $ d = $ 4 and $ h = $ 20 nodes, a DFS stack would require at most:

$$ ms_ {DFS} = 20 * 3 + 1 = 81 nodes $$

Given the fact that this graph would have $ n = 1.4660155e ^ {12} $ nodes, this is an amount more than eligible. This is the adventure of logarithmic spatial complexity ($ h = lfloor log_d ((d-1) n) rfloor $).

However, for BFS, which has exponential space complexity, the worst case is when all the leaves are waiting for discovery, while all other nodes have been discovered, so your queue contains all leaves. discovered but nothing else):

$$ ms_ {BFS} = d h nodes $$

which, in our example, is equal to 1.0995116e ^ {12} $.

My problem now is to loosen the restriction of the graph to be complete, so $ d $ is no longer a homogeneous degree, but a medium degree (which may now contain decimals), and the tree may exhibit an imbalance, even in the form of a list. As a result, the number of nodes is free, so it is not related to d and h like before.

Yes $ d $ is a medium degree and $ n $ whatever the number of nodes, I have tried to somehow model an upper limit of space consumption by first modeling a complete tree with a homogeneous $ lfloor d rfloor $ degree and then adding the kids to the last sheet until that $ d $ (I guess the resulting number of nodes must be equal to $ n $but I'm not sure either; I even tried to calculate, given some $ d $ and $ n $, a lower and upper limit for the height of the tree).

Since $ d $ is an average, if a node has more than $ d $ kids is because another node has less of $ d $ children and the idea was to find the worst case scenario for DFS and BFS by removing the children from one node and moving the cut branch as a child from another node or, in general, looking for the upper bound as close as possible to memory consumption, but I could not find a way.

The fact is, if you apply this pitch increase repeatedly by moving the sibling branches to the deepest levels, you will probably get many parent or sister paths, consisting of only lists, that would be quickly removed from the stack. of the queue, and so there must be a state of the tree where you can not make the consumption of space worse than that. I suppose, however, that the "worst tree" can be different from DFS and BFS.

Is it possible to perform this calculation of the upper limit (or even the exact amount)? Or is the worst case the one that is balanced?

java – Priority queue for minimum heap

General summary

Make all instance fields that are never reassigned final.

 private final PriorityNode() items;
 private final Set itemSet;

Make the constants static and read-only, and use underscores for readability.

 private static readonly int INITIAL_CAPACITY = 4;
 private int capacity = INITIAL_CAPACITY;

Do not introduce new useless lines. For example, between the class definition and the instance variables. Zero or a new line would suffice.

public class ArrayHeapMinPQ {


   private PriorityNode() items;
public class ArrayHeapMinPQ {
   private PriorityNode() items;

Do not write comments that state the obvious. This pollutes the source code. Write comments for when they would really make sense.

   // Declaring a construtor to intialize items as an array of PriorityNodes
   public ArrayHeapMinPQ() {

Like the public comments of the API (it's a good thing):

   /*
    * Adds an item with the given priority value. Throws an
    * IllegalArgumentException if item is already present
    */
   @Override
   public void add(T item, double priority) {

Perform argument checks before changing the state of the instance. (And delete those comments that have no added value)

public void add(T item, double priority) {
       ensureCapacity();

       // To ensure that duplicate keys are not being used in the queue
       if (itemSet.contains(item)) {
           throw new IllegalArgumentException();
       }
public void add(T item, double priority) {
       if (itemSet.contains(item)) {
           throw new IllegalArgumentException();
       }
       ensureCapacity();

It is customary in Java to provide not just add, but also offer methods. add throws an exception, while offer returns a boolean. To support multiple entry points, you must place the actual data insertion in a private method.

private void insert(T item, double priority) {
    ensureCapacity();
    items(size + 1) = new PriorityNode(item, priority);
    size++;
    itemSet.add(item);
    upwardHeapify(items(size));
}

And then refactor add:

   /*
    * Adds an item with the given priority value. Throws an
    * IllegalArgumentException if item is already present
    */
   @Override
   public void add(T item, double priority) {
       if (itemSet.contains(item)) {
           throw new IllegalArgumentException();
       }
       insert(item, priority);
   }

And present offer:

   /*
    * Adds an item with the given priority value. Returns
    * False if item is already present
    */
   public boolean offer(T item, double priority) {
       if (itemSet.contains(item)) {
           return false;
       }
       insert(item, priority);
       return true;
   }