w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Can I set a timeout and number of retries on a specific pipeline request?
With the configuration file I use Spray 1.2.0 in an Akka system. Inside my actor, I import the existing Akka system so I can use the default Akka configuration file. implicit val system = context.system import context.dispatcher val pipeline: HttpRequest => Future[HttpResponse] = sendReceive Now you can change the configuration in application.conf. spray.can.host-connector { max-connections = 10 max-retries = 3 max-redirects = 0 pipelining = off idle-timeout = 30 s client = ${spray.can.client} } In code It is possible to change the settings in code using the HostConnectorSetup, but you have to define all parameters. (Based on the spray usage example.) val pipeline: Future[SendReceive] = for ( Http.HostConnectorInfo(connector, _) <- IO(Http) ? Htt

Categories : Scala

How do I expose the immutable messages of an Akka Actor to non-actor world?
You might want to look at Agents or the Futures and Agents chapter in general for this.

Categories : Java

Facebook Application - How do i count the number of friends a sender invites?
I don't know if i got your question right, but this is actually against the Facebook policy. Per section V.1. You must not incentivize users to grant additional permissions or use Application Integration Points. And per the documentation about Application Integration Points By "Application Integration Point" we mean Application Info Section, Application tab, Feed, requests (including invites), Publisher, inbox attachments, Chat, Bookmarks, or any other feature of a user profile or Facebook communication channel in which or through which an application can provide, display, or deliver content directed at, on behalf of, or by permission of a user.

Categories : PHP

What is sender.selected = !sender.isSelected actually doing to cause my button to toggle?
You can certainly use: if (sender.isSelected) sender.selected = false; else sender.selected = true; It's just that it's shorter to write sender.selected = !sender.isSelected, and it makes it clearer to the compiler what you want to have happen. And the compiler MAY generate more complex code for the longer form, which is of no benefit. It's probably worth getting used to "short form" of writing this sort of thing if you intend on using C or C++, because this sort of "trick" is quite commonly used.

Categories : Objective C

Is there a way to get a line number (and column number) of the input file where java.util.Scanner failed?
A Scanner does not track line numbers or character numbers. You could try to implement this using a custom FilterReader that counts lines and characters, but I think that won't be accurate in all cases. It will tell you how far you how far the scanner got through the stream, but it cannot take account of the fact that the scanner can read ahead a number of characters in a hasNext method and then wind back and read the input using a different next method. For example: if (sc.hasNext("[A-Z ]+")) { sc.nextInteger(); If the nextInteger() method call fails, the "current position" as reported by the FilterReader could be many characters past the stream position where the bad integer is detected. In the worst case, this winding back can take you back past line boundaries ... depending o

Categories : Java

MySQL .What approach should be used ,normalisation or decreasing the number of tables
Why would anyone think that databases designed to support tens or hundreds of gigabytes of data would perform better on zillions of small tables rather than one large table? There is only one instance that I can readily think of where splitting customer data among different tables (and ultimately databases) is desirable. That is when it is an explicit requirement of the problem at hand. For instance, a law firm might have to store client data in different places because that is legally necessary. The investment side of a bank might have to store data in a different place from the rest of the bank, to prevent access. What are downsides of having lots of tables? Here are some that I can think of: It is not free to find the right table for a given customer. It may take essentially no

Categories : Mysql

actor replying to non-actor
This should work just fine. When you use ask, a lightweight actor (I believe represented by a PromiseActorRef) is created to represent the sender so that a response can be sent back that will complete the Future that is created via ask. A little example to show this in action. First the test actor: class TestActor extends UntypedActor{ public TestActor(){ } public void onReceive(Object msg){ getContext().sender().tell("bar", getContext().self()); } } Then the non-actor code that will call it import java.util.concurrent.TimeUnit; import scala.concurrent.Await; import scala.concurrent.Future; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.pattern.Patterns; import akka.util.Timeout; public class AskTest { public static

Categories : Java

What is the standard approach to naming variables for a list of things that might change in order/number?
Define a class called Question @interface Question : NSObject @property (readonly, copy) NSString* question; @property (readonly, copy) NSString* answer; -(id) initWithQuestion: (NSString*) question answer: (NSString*) answer; @end I'll leave the implementation to you :) Store them in an array NSArray* questions = @[ [[Question alloc] initWithQuestion: @"What is the airspeed velocity of an unladen swallow?" answer: @"what do you mean? African or European?"], [[Question alloc] initWithQuestion: @"What is the largest fish in the sea" answer: @"Blue whale, no really, it is a fish as are all mammals"]];

Categories : Objective C

Encapsulating retries into `with` block
As decorators are just functions themselves, you could do the following: with transaction(_perform_in_transaction, retries=3) as _perf: _perf() For the details, you'd need to implement transaction() as a factory method that returns an object with __callable__() set to call the original method and repeat it up to retries number of times on failure; __enter__() and __exit__() would be defined as normal for database transaction context managers. You could alternatively set up transaction() such that it itself executes the passed method up to retries number of times, which would probably require about the same amount of work as implementing the context manager but would mean actual usage would be reduced to just transaction(_perform_in_transaction, retries=3) (which is, in fact, equiva

Categories : Python

Reload time & retries in selenium for a url
You could use browser.implicitly_wait(60) WebDriver.implicitly_wait

Categories : Python

Retries before lock and Locking scenarios in ConcurrentHashMap
I have read iteration doesn't hold lock,so what does above statement means? One can argue that the size method can go ahead and never hold a lock. But this implementation will get the size of the ConcurrentHashMap twice, if the size of first does not equal second it will retry. If the same is true it will lock all segments and get the size a last time. Do operations like get can also hold lock? Please provide scenario also. Technically yes it can but probably will never happen. In the event a JVM publishes one of the CHM's entry entry value after the entry is made available the CHM will do the read under segment lock (again this probably will never happen). Java 8 is releasing a new implementation of CHM so this is probably going to be outdated soon. Will the upda

Categories : Java

Google App Engine cron job sometimes fails due to too many retries
It fails because the retryCount continues to increment every time the cron task is executed. There is no control over retries for a Google App Engine cron task. In the example above, once 10 cron jobs have been performed, the servlet will reach the "Too many retries" point. Simply remove the retryCount testing and enqueue a real GAE task in the cron job if retry control is necessary.

Categories : Java

Store and forward HTTP requests with retries?
There are couple of possibilities. One option is to use Common Address Redundancy Protocol or carp. Brief description from the man page follows. "carp allows multiple hosts on the same local network to share a set of IP addresses. Its primary purpose is to ensure that these addresses are always available, but in some configurations carp can also provide load balancing functionality." It should be possible be configure IP balancing such that when a primary or master http service fails, the secondary or backup http service becomes the master. carp is host oriented as opposed to application service. So when the http service goes down, it should also take down the network interface for carp to do its thing. This means you would need more than one IP address in order to log into the mach

Categories : Http

Are recursive retries in user applications dangerous?
you should limit the number of consecutive attempts at entering a password anyway as a precaution against brute-force attacks. considering the code in isolation, an additional parameter to OnChangePassword reflecting the recursion depth would probably suffice, throwing an error message if it exceeds some limit. i wouldn't regard a stack overflow as a primary concern. realistically that would occur only if the code was exposed to some brute force attempt of cracking the password. having said this, an attack vector could be to deliberately strip the system of resources such as available stack space (eg. by an equivalent of dos attacks), then trying to provoke a stack overflow by requesting another processing task on top - a task that might be your password checker (the scenario feels rathe

Categories : C++

Retries on plink batch file error
find returns 1 when it does not find the search string, so you need something like this instead: @echo off :repeat plink 192.168.x.x ... | find "ERROR" >nul if %errorlevel% equ 0 goto repeat or shorter: @echo off :repeat plink 192.168.x.x ... | find "ERROR" >nul && goto repeat

Categories : Batch File

Azure Table Storage: track retries
You can use the Enterprise Library Transient Fault Handling Application Block as explained in Rob's answer: var retryPol = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy); retryPol.Retrying += (obj, eventArgs) => { var msg = String.Format("Retrying, CurrentRetryCount = {0} , Delay = {1}, Exception = {2}", eventArgs.CurrentRetryCount, eventArgs.Delay, eventArgs.LastException.Message); System.Diagnostics.Debug.WriteLine(msg); }; var options = new TableRequestOptions { RetryPolicy = new RetryPolicies.NoRetry() }; CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("people"); CustomerEntity customer1 = new CustomerEntity("Harp", "Walter"); TableOperation insertOperation = TableOpera

Categories : Azure

Python: requests.exceptions.ConnectionError. Max retries exceeded with url
Looking at stack trace you've provided your error is caused by httplib.BadStatusLine exception, which, according to docs, is: Raised if a server responds with a HTTP status code that we don’t understand. In other words something that is returned (if returned at all) by proxy server cannot be parsed by httplib that does actual request. From my experience with (writing) http proxies I can say that some implementations may not follow specs too strictly (rfc specs on http aren't easy reading actually) or use hacks to fix old browsers that have flaws in their implementation. So, answering this: Could it be a bad proxy? ... I'd say - that this is possible. The only real way to be sure is to see what is returned by proxy server. Try to debug it with debugger or grab packet sniffe

Categories : Python

Failed to read auto-increment value from storage engine, Error Number: 1467
One possible explanation for this behavior is that the autoincrement value has reached the maximum value for the datatype, and its not possible for the database engine to increment it by one. I suggest you check the current value. One relatively easy way to do that is to run a SHOW CREATE TABLE mytable;, the table definition will show the current value. (You can also query the information_schema.tables view, to get the same information.)

Categories : Mysql

Returning Value from Actor
The action of sending a message (actor ! foo) returns Unit because there is nothing to return, you fire and forget (asynchronous). If you want/expect some sort of response back, use ask or ? instead - this will return to you a Future[Any] that you can use. On a related note, it looks like you're using Scala Actors, I suggest you look at Akka (http://akka.io/) if you want to look into actors - as of Scala 2.10.0 Scala Actors are deprecated and replaced by Akka.

Categories : Scala

The Actor DSL example from Akka doc
Short answer (only for REPL without :paste mode): val a = ... implicit val i = inbox() You should pass self, not null as second parameter (sender) of tell method. Method ! takes this parameter implicitly and invokes tell. There are 2 implicit ActorRef in scope of sender ! "hi": i and self (field of Act) - compiler can't figure out which one you need. You should remove implicit val i from scope of sender ! "hi". Correct solution - move actor creation to method and all other code - to other method. In REPL you could create a before i. Quick dirty solution - hide i like this: val a = { val i = 0 actor(new Act { ... }

Categories : Scala

LibGDX Actor Grouping
I was just over thinking this. Basically all I had to do was create a Character class that extends Group, then inside that, just create a Head object which extends Image and a Body object that extends Image. From there, I just animated those in the Character.act method. My Screen then just adds Character to the stage.

Categories : Java

Asking a wildcarded actor selection
If you want to get all responses to the mailbox of actor self, you could use ! method with explicit sender argument like this: context.actorSelection("/actors*").!(Message)(self) In Actor self is implicit so compiler will use it as sender implicitly. You could just send message: context.actorSelection("/actors*") ! Message If you want to do something special with all responses you could create additional actor and specify it as sender in ! method, but you'll have to stop this additional actor manually.

Categories : Scala

Click through an Actor in libGDX
Use an InputMultiplexer. The InputMultiplexer class allows you to share user input among multiple input processors. Create your own class extending InputProcessor, and put that in InputMultiplexer with your Stage. That way you can respond to user input in a custom way, and still be able to use your stage. InputMultiplexer multiplexer = new InputMultiplexer(); Array<InputProcessor> processors = new Array<InputProcessor>(); MyInputProcessor myInputProcessor = new MyInputProcessor(); processors.add(myInputProcessor); processors.add(stage); this.multiplex.setProcessors(processors); //... //and in your show method in your Screen class Gdx.input.setInputProcessor(this.multiplex); Also, be sure to return null from Actor.hit. This should cau

Categories : Java

Actor addresses and tests
There is nothing wrong with injecting the address via the constructor. Let it me know if you need any details, because at the moment I don't know how to make this more clear, since you basically answered your own question. And btw, I don't know, which Akka version you are using, but actorFor has been recently deprecated in favor of ActorSelection, and there are good reasons for this.

Categories : Scala

Akka Actor Priorities
It seems the different actors in your system need to live in different dispatchers. Create a new dispatcher for the CPU-intensive actors and leave the web service actors in the default dispatcher (or maybe move those to another dispatcher as well, if you see fit) You may want to tweak the newly created dispatcher - for example, if you say your ingest actors perform computationally intensive jobs you should reduce the degree of parallelism of the dispatcher to something closer to 1.0 Separating your actor system into different dispatchers prevents problems similar to the one you have - if some actors start to hog the underlying threads they end up saturating the dispatcher that runs them. By having the web actors in another dispatcher you limit the impact that the CPU-intensive actors hav

Categories : Multithreading

How to create minimal Akka actor?
Here is a little benchmark that shows how to create actors in a hierarchy. I also get about 20 seconds for ~1000000 actors, but this is on a pretty slow notebook CPU and no tweaking of JVM options like useNUMA that you have in your benchmark. I tried to run your benchmark from github, and it wouldn't even start on my machine since it requires more than the 4GB of memory I have. So it seems that your notebook is way more powerful than mine. Here is what I get when I create actors in a two level hierarchy (1000 groups of 1000 workers each) Created 1001001 actors 20.752500989 s 48235.198279503136 actors per second Here is what I get when I create 1000000 actors directly below the root actor: Created 1000001 actors 56.118988558 s 17819.29834616461 actors per second So clearly there is

Categories : Scala

Akka and concurrent Actor execution
I think what you want is to filter the future if the response is true. Because of the way the for expression works it will short circuit and won't bother waiting for the rest of the futures to complete in order to assemble the the response. It will still return a failed future with a MatchError exception (per [1]) which you need to handle using an onFailure handler so val aggResult = for { f3 <- futureF3 if (f3.response) f2 <- futureF2 if (f2.response) f1 <- futureF1 if (f1.response) } yield f1.reponse && f2.reponse && f3.reponse aggResult.onFailure { case MatchError => sender ! false } [1] : https://groups.google.com/forum/#!msg/akka-user/oCBpAMRekks/X4y0QV-oOPYJ

Categories : Scala

Sidekiq current Celluloid Actor
Guess you should define a separate class including Celluloid, here's an example based on one of those from Sidekiq repo class MyWebSocketWhatever include Celluloid def initialize(url) @ws_client = Celluloid::WebSocket::Client.new url, Celluloid::Actor.current end def send_message(msg) @ws_client.text msg end def on_message(msg) $redis.lpush 'sinkiq-example-messages', "RESPONSE: #{msg}" end end class SinatraWorker include Sidekiq::Worker def perform(msg='lulz you forgot a msg!') $redis.lpush 'sinkiq-example-messages', "SENT: #{msg}" MyWebSocketWhatever.new('ws://echo.websocket.org').send_message msg end end Works like a charm, just finished playing with it. Get the full updated example, install required gems, then start both Sinatra and Si

Categories : Ruby

How to start a Scala akka actor
If you want to use your main class do the following: import akka.actor.{ActorSystem, Props} object Driver extends App { val system = ActorSystem("System") val hw = system.actorOf(Props[HelloWorld], name = "hw") } Which will create a new actor system and then create the HelloWorld actor using that actor system. You can also follow the akka instructions: set Akka.Main as the main class and give the program "com.example.HelloWorld" as argument.

Categories : Scala

Haskell - Actor based mutability
Here is a quick and dirty example using stm and pipes-network. This will set up a simple server that allows clients to connect and increment or decrement a counter. It will display a very simple status bar showing the current tallies of all connected clients and will remove client tallies from the bar when they disconnect. First I will begin with the server, and I've generously commented the code to explain how it works: import Control.Concurrent.STM (STM, atomically) import Control.Concurrent.STM.TVar import qualified Data.HashMap.Strict as H import Data.Foldable (forM_) import Control.Concurrent (forkIO, threadDelay) import Control.Monad (unless) import Control.Monad.Trans.State.Strict import qualified Data.ByteString.Char8 as B import Control.Proxy import Control.Proxy.TCP import S

Categories : Multithreading

Actor based classes with or without interfaces
Common practice is to use an algebraic data type in such cases: you could create a sealed base type for all messages like this: sealed trait MyActorMessages object Foo extends MyActorMessages object Bar extends MyActorMessages But this kind of contract is not enforced by compiler. You could use use Typed Channels to enforce this contract: class MyActor extends Actor with Channels[TNil, (MyActorMessages, MyActorReply) :+: TNil] { channel[MyActorMessages] { (req, snd) ⇒ req match { case Foo ⇒ ... case Bar ⇒ ... // You'll get a warning if you forget about `Bar` } } } Compiler will force you (with warning) to process all possible message types (in this case all subtypes of MyActorMessages), and senders will be forced to send only valid messages using <-!

Categories : Scala

How can I get Fibonacci(n) in an efficient way with Scala Actor?
For not large size of n, the serial code will always be faster (Much much faster in cases of tail recursion). This is because calling a new function will be faster than starting a new actor. Plus there will contention among threads and context switches. In the below code, I start a new actor for every n > 2. There can be many optimized ways, but I simply using the recurrence T(n) = T(n-1) + T(n-2) to serial one. import akka.actor.Actor import akka.actor.Props import akka.actor.ActorSystem import akka.event.Logging import akka.actor.ActorRef import akka.routing.RoundRobinRouter object Fib extends App { trait Fib case class N(val n: Int) extends Fib case class Ans(n: Int) class FibN(listen: ActorRef) extends Actor { var numOfResults = 0; var ans = 0; val log = Logging(context.system

Categories : Scala

How to adjust actor z index based on x?
Have an array of initial positions of all your cards. Whenever drag happens, re-shuffle your array based from the drag method you already have. Draw the cards using the positions stored in your array from 0 to length - 1 where first card's position is at index 0 and the last one is at length of array minus 1. Or - use Group. Add group in draw order. You can swap actors in a group. Swap the cards based from drag events.

Categories : Java

Improve this actor calling futures
It is minor, but why don't you store filters as sequence? filters.foreach(f ! Cancel(w)) is nicer than filter1 ! Cancel(w) filter2 ! Cancel(w) filter3 ! Cancel(w) Same for other cases: class Worker(filter1: ActorRef, filter2: ActorRef, filter3: ActorRef) extends Actor with ActorLogging { private val filters = Seq(filter1, filter2, filter3) implicit val timeout = Timeout(30.seconds) def receive = { case w:Work => val start = System.currentTimeMillis(); val futures = filters.map { f => (f ? w).mapTo[Response] } val aggResult = Future.find(futures) { res => !res.reponse } Await.result(aggResult, timeout.duration) match { case None => Nqueen.fact(10500000L) log.info(s"[${w.message}] Procesado men

Categories : Scala

Libgdx Scene2d - Set actor ( TextField ) padding?
Use the Table class to lay out scene2d UIs. To set up the Table: stage = new Stage(); Table table = new Table(); table.setFillParent(true); stage.addActor(table); table.add(textFieldUsername).padBottom(20f); //also use padTop, padLeft, and padRight table.row(); In the main loop, call: stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); For more information on tables, see: http://code.google.com/p/table-layout/

Categories : Android

Scala/ AKKA actor migration between machines
Depending on the use case, akka-cluster with cluster sharding may be a fit. Module is capable of reallocating shards to other cluster nodes.

Categories : Scala

How should an akka actor be created that might throw an exception?
You can catch the exception in the constructor of MyActor and notify other actors (e.g. the parent) about this exception. Try this: class MyActor(val parent: ActorRef) extends Actor { try{ throw new RuntimeException("failed construct") } catch { case e: Throwable => parent ! e throw e } def receive: Actor.Receive = {case _ => } } class ParentActor extends Actor { val child = context.actorOf(Props(classOf[MyActor], self), "child") override def receive = { case e: Throwable => println(e) } }

Categories : Scala

Possible to integrate existing Java class with Actor?
If there's a way to "actorfy" any interface, I'd love to know about it. =) The simplest thing to do, in my opinion, is just create a value that behaves as an actor to which you can send messages, and pull the stream handling implementation into that. So, with the important bits cut out, that would look something like the following... import akka.actor.ActorDSL._ class HelloWorld extends HttpServlet { val streamHandler = actor(new Act { become { case req: HttpServletRequest => val upload = new ServletFileUpload() // ... } }) override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = { if (ServletFileUpload.isMultipartContent(req)) { streamHandler ! req resp.getWriter().print(" File uploads success! ") // This is optim

Categories : Scala

Stop actor message processing on timeout
The short answer is that you can't. Once it starts processing it, sending Kill or Poison Pill or stopping it will only prevent it from processing future messages. The long answer is that maybe you can hack around this if the actor happened to be in a loop of some sort and was checking some mutable (and potentially globally available) signal for stopping looping, but there are so many red flags with that approach that you should forget I even mentioned it. And if the long call happened to be a blocking io call to something like a DB, forget about it; you're stuck until that call completes (or times out if you are lucky). The actor itself is not aware that someone called it via ask and there is a Future upstream that might time out. It has no concept of this and thus can not react accor

Categories : Java

Akka ActorRef being created with null actor
Try notifying other actor(s) of your actor's existence in its preStart method, by sending a message to them, instead of relying on the ActorRef created when you create the actor. This should sort out any concurrency bugs that might be preventing your application from working. If that doesn't fix it, enable full logging so you can see if the messages are being sent and received correctly.

Categories : Scala



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.