When you write koka.pas = null, there is no koka whose pas you can set. You must initialize that somehow.
python,algorithm,queue,josephus
Maybe you have some indentation problem, the output for the script below is 3 - as you suggested. class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def hotPotato(namelist, num): simqueue = Queue() for...
If I got You right, you're asking why would someone start serial task on a concurrent queue. You would need that kind of behaviour in case, if most tasks with some resource can be performed concurrently (aka, simultaneously), but some tasks are, by nature, unsafe to be performed concurrently with...
python,multithreading,csv,queue
You could use concurrent.futures.ThreadPoolExecutor or a multiprocessing.pool.ThreadPool for this. It's hard to tell you exactly how to implement it without knowing what MiThread is doing, but the basic idea is something like this (using multiprocessing.pool.ThreadPool): def run_mi_thread(i, CliLine, ip): # Do whatever MiThread.run does. oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") routers...
python,class,stack,queue,reverse
This will work. Your queue is composed of a list, so you can use slice syntax on the list to get a reversed version of the queue. class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def __str__(self): '''Allow print to be called on the queue object itself'''...
It depends how your search (or which search algorithm) is implemented. Stack or Queue may also helpful for some searching application like - BFS, DFS. But in normal case when you are using linear search you can consider about array or ArrayList.
java,collections,queue,priority-queue,comparable
A bit further down in the documentation it says: The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. Since AbstractCollection's toString (which PriorityQueue inherits) returns a string in the iteration order, you get no particular order from it....
You can use Queue::connection to swith to another connection. Queue::connection('new-connection')->push('[email protected]', [], 'queue-name'); ...
Yes you can. In fact there are a number of package which do exactly this ... including Celery and RQ for Python and resque for Ruby and ports of resque to Java (Jesque and Javascript (Coffee-resque). There's also RestMQ which is implemented in Python, but designed for use with any...
java,multithreading,queue,threadpool
Oh, you're concerned about returning a result. Per your comment: I updated with code. When I do this it goes way too fast. even though I put thread to sleep for 3.5 secs. I dont think it actually sleeps. So I thought I should add queue to prevent loss of...
queue,distributed,distributed-computing,distributed-system
You can think of the backend of a queue as a replicated database. (I am assuming the queues you are talking about consider themselves as durable: when they accept a message, they guarantee at least once delivery.) As a replicated database, the message queue backend uses a replication protocol to...
Use a topic exchange and have each consumer create it's own unique persistent queue and bind it to the exchange with a topic to which you want to subscribe. Publishing a message on the exchange will deliver that message to each queue bound to that exchange/topic. If one of your...
python,cassandra,queue,multiprocessing
I don't have a cassandra machine, but I guess, It'll work once you move the connection part to the prcoess-function hi(). Like: def hi(): cluster = Cluster(['127.0.0.1']) metadata = cluster.metadata session = cluster.connect("sujata") global queue while True: y=queue.get() if y=="exit": os._exit(0) else: print y session.execute(y) Don't know why it's behaving...
Make sure, you don't have any QUEUE_DRIVER value other than beanstalkd set in the .env file. The env() method: 'default' => env('QUEUE_DRIVER', 'beanstalkd'), will first search for that key in the current eviroment loaded variables, and if there are no matches, it will fallback to the beanstalkd value passed as...
java,queue,message-queue,priority-queue
see https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html I would advise using wrapper for your requests that has priority value specifically for this queue. For instance, you can use Long as that value, where you calculate value = timestamp % N * priorityLevel N is dependent on how long it takes you to process your events...
If you want to be able to use front() to modify the first element, it needs to return a reference to it, not a copy: Type & front(); ^ You'll also need to remove the spurious ; after if(!isEmptyQueue()), and perhaps do something like throw an exception if it is...
Use this: qstat -u user_name[@host][,user_name[@host],...] You could list a single user Edit: In that case I don't know. You could still use some shell tricks to count the number of lines with specific pattern (eg user_name) but that would be indirect. For example: qstat | grep user_name | wc -l...
The template argument need to be a full and complete type. And a templated class like std::bitset is not a complete type without its size. So you need to do e.g. std::queue<bitset<8>> buttonQueue; In other words, you need to provide the bitset size as well....
When you do queue and deque you should manipulate a variable inside the class. So in the beginning it will be equal to 0. After each queue or dequeue accordingly you will ++ or -- it. Then this is the variable you use in toString to define end boundary for...
ruby-on-rails,queue,task,jobs,sidekiq
You cannot do that. pidfile is designed to be a command line arg only.
algorithm,data-structures,queue,circular-buffer
In a standard queue, implemented using array, when we delete any element only front is increment by 1, but that position is not used later. So when we perform many add and delete operations, memory wastage increases. But in Circular Queue , if we delete any element that position is...
c#,.net,queue,async-await,.net-4.5
There are many possible designs for this. But I always prefer TPL Dataflow. You can use an ActionBlock and post async delegates into it to be processed sequentially: ActionBlock<Func<Task>> _block = new ActionBlock<Func<Task>>(action => action()); block.Post(async () => { await Task.Delay(1000); MessageBox.Show("bar"); }); Another possible solution would be to asynchronously...
If the internal arrays are meant to be variable length or the length won't be known until run-time you could use std::queue<std::vector<Hooks>> Hooks_queue; If the size is fixed and known at compile time, you could use std::queue<std::array<Hooks, N>> Hooks_queue; Where N is the size of each array...
python,class,linked-list,queue
The problem you are actually encountering is that you are not calling the method, but just referring to the boolean value of the method object itself, which is always true. It should be: if self.isEmpty(): ...
node.js,mongodb,architecture,cron,queue
You would use setTimeout() for that and save the timer ID that it returns because you can then use that timer ID to cancel the timer. To schedule the timer: var timer = setTimeout(myFunc, 60 * 60 * 1000); Then, sometime later before the timer fires, you can cancel the...
c#,azure,queue,azure-servicebus-queues,brokeredmessage
This is only a partial-answer or work-around; the following code reliably gets all elements, but doesn't use the "ReceiveBatch"; note, as far as I can discern, Peek(i) operates on a one-based index. Also: depending on which server one is running on, if you are charged by the message pull, this...
Here q is an instance of class queue. Also q is not callable.And items is the instance variable.So you have to use for n in q.items: print "This time, it's: "+ str(n) ...
data-structures,queue,priority-queue,binary-search
Your loop, the binary search, only finds the index at which the new item should be inserted to maintain sorted order. Actually inserting it there is the hard part. Simply put, this takes linear time and there's nothing we can do about that. A sorted array is very fast for...
To create a std::vector that has a random quantity of Passenger<NODETYPE> do the following: First, you would generate a random number. Next, use a loop to the limit of the random number. srand(time(0); // Seed the random number generator. const unsigned int quantity = rand() % 16 + 1; std::vector<Passenger<NODETYPE>...
laravel,laravel-4,queue,beanstalk
Try using the inbuilt Queue service and use the following Queue::later(Carbon::now()->addMinutes(1), $task); Relevant docs...
priorityQueue.put(child.getH+count, count, child) The above line calls put with the arguments: item=child.getH+count, block=count, and timeout=child. As a result, only child.getH+count is be considered as the 'item' that get will retrieve. Try putting all three objects into a tuple: priorityQueue.put((child.getH+count, count, child)) This way, item will be the tuple (child.getH+count, count,...
If you implement enqueue by adding node at the list head, you have to dequeue by removing the tail. If you implement enqueue in the other way, dequeue would be easier. Since this is homework, I'd like to only give hint.
question: how to select patient via social security number? IF the social security number is a field in the struct being used to make nodes in the linked list. The simply start at the head pointer of the linked list, stepping one by one through the linked list. at each...
Step 1 You have to have PHP installed and be able to run in from the command prompt. Test that by typing: php -v If you get a version number and some other details proceed with Step 2, otherwise follow this tutorial on sitepoint at least until point 4. The...
If you implement a queue using an array the queue's max size will be the size of the array, but you can't tell if the queue is empty or full just using the size of the array cause is static, you need to keep a counter that increases or decreases...
@RyanP really deserves credit for this answer. After looking at his suggestion, when I fixed the code to... while (bmess [i] != '/O'){ palinS.push(bmess [i]); palinQ.front(bmess [i]); i++; } That solved my problem of the never-ending Stack & Queue 'list' creation. Thanks for all the comments!...
python,multithreading,queue,producer-consumer
I'd call that a self-latching queue. For your primary requirement, combine the queue with a condition variable check that gracefully latches (shuts down) the queue when all producers have vacated: class SelfLatchingQueue(LatchingQueue): ... def __init__(self, num_producers): ... def close(self): '''Called by a producer to indicate that it is done producing'''...
.net,linq,queue,ienumerable,peek
If the collection implements IList<T>, then the indexer property is used in both First() and Last() (which is usually O(1), though it's not required to be). Otherwise, a call to First() will only take the first element (and exit immediately, if the enumerator supports deferred execution), but a call to...
Beanstalkd can be started with the -b (binary log) option, and beanstalkd will write all jobs to a binlog. If the power goes out, you can restart beanstalkd with the same option and it will recover the contents of the log.
You should not cast to the raw type: Iterator<MotionEvent> it = queue.iterator(); ...
Q: I haven't been able to think of a way to keep the stack the way it is A: A: That's because reading from a "classic" stack is destructive. "Reading" an element == removing that element from the stack. TWO SOLUTIONS: 1) Modify your stack implementation so that you can...
This case is always solved in lock-free lists by keeping a dummy node in the list. The head always points to the dummy node which is the first node in the list. When the queue becomes empty, both head and tail point to a dummy node. You can look at...
c++,swift,queue,port,grand-central-dispatch
The second argument of dispatch_queue_create() has the type dispatch_queue_attr_t, which is declared as typealias dispatch_queue_attr_t = NSObject You have to pass DISPATCH_QUEUE_SERIAL or nil for a serial queue (or DISPATCH_QUEUE_CONCURRENT for a concurrent queue): var thisQueue = dispatch_queue_create("com.myApp.mHitsUpdateQueue", DISPATCH_QUEUE_SERIAL) In C(++), 0 can be passed instead of a NULL pointer....
azure,queue,servicebus,azureservicebus
Properties is a simple key-value pair collection. In most cases you can use it to send information if you can map them as key-value pair of course. Body is the payload of the message that can be empty if you send your information content using only Properties (as above). If...
Thank you Snild Dolkow. Your suggestions are valuable. In doing further research I did find a mechanism that seems intended for my particular situation. A collections.deque([iterable[, maxlen]]) would be thread-safe, discards old data when accepting new data, and according to the documentation: They are also useful for tracking transactions and...
java,pointers,queue,circular-buffer
You can read more about Full/Empty Buffer Distinction on Wikipedia http://en.wikipedia.org/wiki/Circular_buffer#Full_.2F_Empty_Buffer_Distinction There are multiple workarounds described. I would point out the one you mentioned and maybe the easiest one to understand. Always keep one slot open The buffer will never be full to the last item, but there will be...
You can first optimize it in two ways: 1) You do not require integer linkedlist. Instead use a simple for loop. 2) Once you are using for loop, you can first remove all the even numbers as they are obviously divisible by 2. And then just traverse through the odd...
linux,linux-kernel,kernel,queue,spinlock
Spinlocks are primarily for use in (or to interoperate with) contexts that cannot block / reschedule. They should only be used where the likelihood of actually waiting for them is relatively low and the lock will not be held long. For example, assume an interrupt handler (and/or other contexts as...
ConcurrentQueue is a thread safe implementation that does exactly what you need. It will also definitely be faster that your own code. Use this link to see the source code of the ConcurrentQueue implementation.
c++,multithreading,thread-safety,queue
You already said it. Lock the write and read access to every queue with a mutex. Queue 1 and 2 gets a mutex. It would be easy if you write your own push and pop function for the queues. Inside this function you could use std queues or else.
c++,data-structures,linked-list,queue
void enQueue(int x){ Node* temp = NULL; //Node* temp = new Node; temp->data = x; //BOOM temp->next = NULL; if(front == NULL && rear == NULL){ front = rear = NULL; //What? return; } rear->next = temp; rear = temp; } You are assigning to an invalid address. This will...
python,queue,task,celery,worker
After considering several options I chose to use app.control.inspect. It's not a really beautiful solution, but it works: # fetch all scheduled tasks scheduled_tasks = inspect().scheduled() # iterate the scheduled task values, see http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#dump-of-scheduled-eta-tasks for task_values in iter(scheduled_tasks.values()): # task_values is a list of dicts for task in task_values: if...
python,url,redis,queue,web-crawler
A few suggestions: Look into using Redis' (2.8.9+) HyperLogLog data structure - you can use PFADD and PFCOUNT to get a reasonable answer whether a URL was counted before. Don't keep each URL in its own url_ key - consolidate into a single or bucket Hashs as explained in "Memory...
You need memory for your queue. At the moment, you have an uninitialised pointer that points to a random location in memory. Dereferencing that pointer is undefined behaviour and will very likely give you a seg fault. You have to decide how you want to store your queue. You can...
python,memory,queue,multiprocessing
I used a global counter that I passed to each processor as opposed to a large queue of numbers.
javascript,jquery,ajax,queue,promise
You need to append the article to a certain position, based on for example the i variable you have. Or you could wait for all of the requests and then append them in order. Something like this: mod.getArticles = function( ){ var load = function( id ) { return $.ajax({...
php,laravel,queue,facebook-sdk-4.0
Really simple solve, my first attempt at this must have thrown errors for other reasons. Just make the request with those parameters appended. $request = new FacebookRequest( $session, 'GET', $endpoint, $parameters ); ...
The current() function will give you the 'current' array-value. If you're not sure if your code has begun to iterate over the array, you can use reset() instead - but this will reset the iterator, which is a side-effect - which will also give you the first item. Like this:...
php,laravel,queue,daemon,artisan
We've implemented something like this in our application - but it was not something that was built-in to Laravel itself. You would have to edit this file, by adding another condition to the if-block so that it would call the stop function. You can do this by either setting a...
Try something like: map1.put(login, new ArrayBlockingQueue<Map<Integer, MyObject>>(500, true)); ^^^^^^^ ^(missing closing bracket) See that you are missing the Integer type in map. If you wish to add value to Queue then you could do something like: Map<Integer, MyObject> myMap = ...; myMap.put(1, new MyObject...); map1.get(login).add(myMap);//or can use offer ...
I think this is your problem: th_list.push_back(std::thread(&App::th_getInfo, *this, *it, readFile(holder["cmdFile"]))); std::thread takes arguments by value; so the *this creates a copy of your App object, with a separate Holder. You can get reference semantics, as you and God intended, by wrapping like so: th_list.push_back(std::thread(&App::th_getInfo, std::ref(*this), *it, readFile(holder["cmdFile"]))); See here for...
Have you considered managing a NSOperationQueue? This tutorial might be helpful. In his example, he pauses the downloads as they scroll off the page, but I believe you could adjust the queuePriority property of the NSOperation objects instead.
algorithm,data-structures,stack,queue
A doubly linked list, has all the computational complexity attributes you desire, but poor cache locality. A ring buffer (array) that allows for appending and removing at head and tail has the same complexity characteristics. It uses a dynamic array and requires reallocation, once the number of elements grows beyond...
Before reusing a class, you need to ask yourself, is Inventoty a queue or does inventory has a queue? One this is understood, you will know if Inventory needs to extend Queue, or has a field whom type is Queue. Some questions you need to ask yourself for answering the...
If I understand the problem correctly, the simplest solution that comes into my mind is adding a middle layer between task senders (putting into queue) and workers (taking from queue). This, probably routine, would be responsible for storing current tasks (by ID) and broadcasting the results to every matching tasks....
algorithm,data-structures,queue,deque
There are two common ways to implement a deque: Doubly linked list: You implement a doubly linked list, and maintain pointers to the front and the end of the list. It is easy to both insert and remove the start/end of the linked list in O(1) time. A circular dynamic...
amazon-web-services,amazon-ec2,queue,message-queue
You are describing a very common batch-oriented design pattern: Work is placed in a queue One or more "worker" instances pull work from the queue The number of worker instances scales based upon the size of the queue and urgency of the work Using spot pricing to minimise costs The...
Try changing struct NODE *next; to struct Node *next; in definiton of your structure EDIT: Looking more on the code, I think you have some problems at the pointer assignments. For example, I think that Link current = *Queue; will assign only data of Queue, not address, therefore you cannot...
Lots of problems: You have a double-linked Node but never update its prev member in the add/remove methods. You are keeping track of both the Queue head/tail but don't properly update them when you add/remove nodes. Both your forward and reverse loops in printQueue() are wrong and result in an...
python,queue,multiprocessing,python-multiprocessing
It sounds like your issues started when you tried to share a multiprocessing.Queue() by passing it as an argument. You can get around this by creating a managed queue instead: import multiprocessing manager = mutiprocessing.Manager() passable_queue = manager.Queue() When you use a manager to create it, you are storing and...
c++,compiler-errors,queue,undeclared-identifier
Why do you need constant method delcarations? I would get rid of const() completely on all of your methods. A couple of other things that are likely problematic: get_totalWait() has a void return type, you probably want either int or double for that. It's hard to know what else might...
algorithm,queue,constants,analysis
Personally, I don't like interview questions with arbitrary restrictions like this, unless it actually reflects the conditions you have to work with at the company. I don't think it actually finds qualified candidates or rather, I don't think it accurately eliminates unqualified ones. When I did technical interviews for my...
I would have expected the consumer not to consume/print anything becauses the messages he is interested at are blocked by the messages 0,1,2 that are not being pulled by any consumer This assumption is incorrect. When you use a selector in JMS, the messages that do not satisfy the...
I see the following problems in your code: Problem 1 In insert(), you haven't allocated memory for the info of the newly allocated Node before setting values on it. You are also not setting the next of the newly constructed node in insert. rear->next remains uninitialized. If you access that...
join() will block until task_done() has been called as many times as items have been enqueued. You don't call task_done(), thus join() blocks. In the code you provide, the right place to call this is at the very end of your doWork loop: def doWork(): while True: task = start_q.get(False)...
laravel,command,queue,laravel-5
I could not find any way to do this, so I came up workaround (tested on laravel sync driver). First, you have to create/adjust base command: namespace App\Commands; use Illuminate\Foundation\Bus\DispatchesCommands; abstract class Command { use DispatchesCommands; /** * @var Command[] */ protected $commands = []; /** * @param Command|Command[] $command...
I believe you are overcomplicating things. What you want is to start at f (e.g. i = f), and then move up by one, but since we can wrap-around, we should move up by (i + 1) % capacity. We keep on doing this until we reach the end (e.g....
There are a few problems with your implementation: A. After you resize the array, you set: back = backing.length - 1; that should be: back = backing.length; Let's take the example of an queue with capacity 1: create queue initial capacity 1: size = 0, front = 0, back =...
Yes, back < front and size < capacity is valid state in a circular buffer/queue. Note that size is generally implicit and calculated as (back-front)%capacity. The Wikipedia article on circular buffers has a great description of how circular buffers function: http://en.wikipedia.org/wiki/Circular_buffer
You want to think circularly here in terms of relative, circular ranges instead of absolute, linear ones. So you don't want to get too hung up on the absolute indices/addresses of FRONT and REAR. They're relative to each other, and you can use modulo arithmetic to start getting back to...
Well, depending on the actual Queue implementation, you may be able to use an Iterator. For example, for PriorityQueue<E> : * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link * #iterator()}...
java,multithreading,concurrency,queue
You are using the same byte array (fileInBytes) to read from the stream: byte[] fileInBytes = new byte[1500]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName)); while((bytesRead = in.read(fileInBytes)) != -1) { Sender.enqueue(new Packet(seq, fileInBytes); seq++; } I guess that the constructor of Packet does not copy the byte array: class Packet...
laravel,command,queue,scheduled-tasks,laravel-5
You can just supply them in the command() function. The string given is literally just run through artisan as you would normally run a command in the terminal yourself. $schedule->command('users:daysInactiveInvitation --days=30')->daily(); See https://github.com/laravel/framework/blob/5.0/src/Illuminate/Console/Scheduling/Schedule.php#L36...
Setting up queues requires, as the very first step, to choose what driver you'll be using. Because it's the quickest to get running, I'll explain how to begin with the database driver, as it doesn't require any other services to be installed on the server (as it's the case for...
authentication,queue,token,android-volley,priority
Posting an answer now that I found a half-decent way to handle token refreshing on retry. When I create my general (most common) API call with Volley, I save a reference to the call in case it fails, and pass it to my retry policy. public GeneralAPICall(int method, String url,...
From your question, it seems all you need to do is this: if (condition) landing.push(Plane(/*argumnts, if any */)); I'm assuming that your container creates copies. Example: #include <queue> class Plane { public: Plane() {} }; std::queue<Plane> landing; int main() { landing.push(Plane()); } Live Example: http://ideone.com/TyTtlc...
I ended up using regular arrays and copy methods on those arrays to implement the desired functionality
It looks like the length getter is only pointing to an internal counter. This is done because counting the elements everytime might take very long for long lists. The internal counter is only updated if you use the methods that directly operate on the list instead of using the prepend...
Because the 11th offset is zero and the conditional break triggers before the loop reaches the end of your data structure? Either that or // do something with currOffset involves popping more things from the queue....
bash,shell,parallel-processing,queue
Use GNU Parallel to make a job queue like this: # Clear out file containing job queue > jobqueue # Start GNU Parallel processing jobs from queue # -k means "keep" output in order # -j 4 means run 4 jobs at a time tail -f jobqueue | parallel -k...
javascript,node.js,redis,queue
RSMQ itself does not implement any kind of worker, and ist stripped down to the core functionalities of a queue (which in my opinion is the correct approach). While you could implement everything yourself of course, I'd recommend using the additional module rsmq-worker (http://smrchy.github.io/rsmq/rsmq-worker/) which provides the basic worker skeleton...
C++ is a strongly typed language. In the line names.push(a[1]); you are trying to push a struct (from your process a[x]; array) into a queue<string>. Your struct is not a string, so the compiler will emit an error. You at least need a queue<process>. Other issues: variable length arrays are...
Sounds like you need an Azure Service Bus Topic for the first part (two queues, each with competing consumers). This will allow for the topic/subscription model you have described. To automatically trigger another service after these have completed is not possible using a queue. This will require some sort of...
The problem is probably not in the code actually, at a glance it behaves normally. You declare Queue q; as a local variable in your main. This means that when the main finishes it's execution, q goes out of scope, and the destructor is called. Hope this sheds some light...
email,laravel,dns,queue,mailgun
Switching the configuration details of the Laravel Mailer at runtime is not that hard, however I don't know of any way it can be done using the Mail::queue facade. It can be done by using a combination of Queue::push and Mail::send (which is what Mail::queue does anyway). The problem with...
You have to do two things, Get faster bandwidth Change block size from 4096 to something like 8192 or any number which can be hold in memory easily. ...