w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Scala parameters pattern (Spray routing example)
Why don't you look into source? As for me, it could be implemented as follows method path takes arbitrary type parameter, some pattern-object of that type and a function from that type: def path[T](pattern:Pattern[T])(function:Function[T, `some other type like unit or any`]) the pattern is constructed with two tricks. The String is either "pimped" to have method / or has an implicit convertion to Pattern[Nothing] the Pattern[T] has method / that constructs another pattern with some new type. The method takes single argument (some ancestor of Segment). I guess — Pattern[T2]: trait Pattern[T] { /// def `/`[T2](otherPattern:Pattern[T2]):Pattern[(T,T2)] } So the first argument of path allows to determine the constructed type of pattern as being the pair. Thus we get prop

Categories : Scala

execute DefferedObjs asynchronously
If you are looking to run a piece of code after they all complete then: $.when.apply(null, array).then(function() { console.log("all deferreds in array are complete!"); }); If you are looking to control the order the deferreds run, you will have to be sure the deferreds haven't already started. Before you put them in the array, I would suggest wrapping them in an ongoing deferred. var last = array[0]; function tackOnFunction(fn) { array.push(last = last.then(fn)); }

Categories : Jquery

Execute the query on getValueAt and return the results asynchronously
I am implementing a swing jtable with a huge number of data, i want the data to be loaded at the moment of getValueAt in the data model and print "Loading" in the cell and return the data later, I dont wanna to execute the query in the UI Thread. Any ideas to de that? Thanks use Workers Thread Runnable#Thread, output to XxxTableModel must be wrapped into invokeLater SwingWorker, output from methods publish(synchronous), process(synchronous), done(asynchronous) is done on EDT

Categories : Java

Execute a server side program asynchronously with an asp.net mvc4 app
Asp.Net MVC has the concept of an Async Controller that is suited to perform long-running tasks. It will help you by not locking a thread while you wait for out program to execute. But to do what you are after I think you need to create you own Http Handler (probaby by implementing the IHttpHandler interface) that wraps the process and returns the results incrementally. This will not be trivial to do, but it should be possible. A third viable alternative might be to use SignalR. That would be a fun project, but would still require much work I think.

Categories : Asp Net

How to execute multiple DB calls asynchronously using Simple.Data
Use async/await but don't return a Task from each routine. The effect is that they run concurrently all awaiting on their own io and then complete on the UI thread. private void Initialize() { LoadTechnologies(); LoadInstallationTypes(); LoadProvinces(); LoadYears(); } // Note that LoadTechnologies will return as soon as it is // called. The part after the await will be scheduled on // the UI thread after the task completes with the data private async Task LoadTechnologies() { ddlTechnologies.Datasource = await Task.Run(()=>GizRepository.GetTechnologies()); ddlTechnologies.DataValueField = "Name"; ddlTechnologies.DataTextField = "Name"; ddlTechnologies.Items.Insert(0, n

Categories : Asp Net

Can I manually apply Grails routing logic to a String containing a URL?
Check whether the mapping is present from the list of mappings available in UrlMappings using grailsApplication which can be injected easily in artefacts like controller/service. def allMappings = grailsApplication.allClasses .find{it.name == "UrlMappings"}.mappings.urlMappings assert '/path/one' == allMappings.find{it.toString() == "/path/one"}?.toString() assert !allMappings.find{it.toString() == "/path/fake"}?.toString()

Categories : Grails

Bamboo : How to execute some logic if job is cancelled or fails
From reading what you had written, I think that using an event listener is definitely the correct way to approach your problem. Below I have provided an image of my own creation that seems to describe what you have constructed and that shows where it might be best to place the event listener. Essentially, the client of yours will issue a cancel notification to the server via its network controller mechanism. The server will then receive that cancelation notification via its network controller which is already connected to the client via some network protocol (I am assuming TCP). When that cancellation notification from the client network controller reaches the network controller of the server, the event listener in the network controller of the server will then signal the server build man

Categories : Java

Getting familiar with MVC - how do I work with session logic, additional classes and background logic
Why not use one of the many existing MVC frameworks available for PHP? There are a lot out there (CakePHP, CodeIgniter, Yii etc etc). If you really want to re-invent the wheel, go ahead! However the existing frameworks represent the culmination of a lot of development by smart people, so you are getting a great head start by adopting one. Furthermore, they are well documented and have good tutorials which will answer the questions you are asking and also many you haven't asked yet.

Categories : PHP

Logic rules want pop up if Enable conditional logic?
Create toggleLogic() javascript function and put your popup box code and check your logic to display content. Like this. function toggleLogic(someid) { // your logic code ... }

Categories : Wordpress

ruby on rails routing error routing to the wrong page
-updating per comment- Tweetsblog2::Application.routes.draw do resources :coordinates get "tweets/show" => "tweets#show" get "tweets/index" => "tweets#index" Removing the resources :tweets should fix your issue and allow you to use just call the 2 options. The initial resources :tweets tells rails that you wanted resourceful routes (index shows all of the resource, show a specify one, etc..). So just building out the 2 non-resourceful routes as above sounds like what you want. The way I normally do something like this is to just include the search form in in the index page and if there are no search params then show all tweets.)

Categories : Ruby On Rails

PHP MVC Routing -> How do I convert uri array elements to a string useful for routing?
The issue you are having is due to the way in which you are trying to assign the properties of Request to Router. $router = new Router(array($request)); Here you have given the Router its argument as an array with one element. The Request instance. You are not casting to an array. I'm not sure if that was the intent. Because of this you are not able to access the properties of Request in array notation (such as $request['controller]). As is, the Router would need to be modified so Router::__construct() correctly assigns the parameters. e.g. public function __construct($array) { $request = $array[0]; $this->controller = $request->getController(); // No longer using array notation $this->method = $request->getMethod(); // such as $request['method']

Categories : PHP

Use Angular routing alongside roundtrip routing
I think I may have found a solution. I'm doing a similar thing, a multi-page angular site that uses angular for some of it's pages. Here's what I'm doing var app = angular.module('appname', ['ui.bootstrap', 'ui.autocomplete']) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); }]) .run(function($rootScope, $location) { var redirected = false; $rootScope.$on('$locationChangeStart', function(event, nextLocation, currentLocation) { if(!redirected && $location.path() !== '/current-url') { redirected = true; event.preventDefault(); window.location = $location.path(); } }); }); So what I have to work o

Categories : Angularjs

MV4 Routing Dynamic Routing from MySQL Database
Put below code in you RouteConfig.cs before the default route expression. foreach (var item in _context.products) { routes.MapRoute( item.Url, "products/" + item.Url, new { controller = "products", action = "index", @id = item.ProductId } ); } In above _context.products is used to retrieve the products from the DB. You can modify this according your models.

Categories : C#

How can I deconstruct a Spray API HTTPResponse?
The main issue I see with your code is that you are expecting mapTo to automatically unmarshall the http response body into your case class structure. The mapTo method belongs to the Future class and has no idea about json unmarshalling. You use mapTo within an Akka request (which ? is doing under the hood) to basically "cast" a Future[Any] (which is the default response type from ?) into the type that will actually be returned. This has nothing to do with json unmarshalling. I believe in order to achieve what you want, you should create a pipeline for spray that will both send the request and unmarshall the response. The documentation showing examples of that are here. I think for your example, it would look something like this (code may not be 100% right, just trying to show genera

Categories : Scala

Mapping Spray Parameters
I am new to Scala/Akka etc and spent a bit of time stuck on a parameter mapping problem earlier this week. I will share what I have which is working and perhaps it can guide you down the correct path. By no-way is this telling you why Scala is choking on that symbol, but hopefully is helpful in some way. My GET directive looks like this: get { parameters('filter, 'sort ?, 'skip ?, 'take ?).as(Search) { model => complete { (account ? UserSearchReq(model)).mapTo[SearchResult[User]] } } } ~ And my search model looks like this: case class Search(filter: String, sort: Option[String], skip: Option[Int], take: Option[Int]) As you can see, the filter is required, but the remaining parameters are optional. I have not specified the type, but everything works just fine. Best of luck.

Categories : Scala

How to deploy my spray API into production?
You should build a jar with the plugin sbt-assembly addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.0") Then you can run the jar in production with java -jar If you give version number to your project, this is a rather classic process. Hope it helps.

Categories : Scala

How to handle business logic errors and application exceptions from business logic layer in MVC ASP.NET
I think it is a good idea to look at this sample. When ever an error occurs in Business logic layer you can return false or say -1 for a method of Business class, then show proper error message to user, and in catch part of the business method you can use one of popular error logging libs like Log4NET or elmah. Edited: To redirect user when error occurs you can specify the error controller in custom error section of web config

Categories : Asp Net Mvc

Spray Client Post Multipart
@grandes Thanks for responding. I used the newman rest client library (https://github.com/stackmob/newman) to send http requests, but had to create the MultipartFormData manually and it worked. This will be fixed in newman in the near future. Here's the link that I used to manually build the multipart form data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Categories : Scala

spray-json and list marshalling
You also need to import the format you defined on the route scope: import JollyJsonProtocol._ get { complete { List(new ElementResponse(...), new ElementResponse(...)) } }

Categories : Scala

Sending post with json using spray?
Sorry, but you question is a bit cumbersome, for me at least. If you want to make a POST request in Spray with some Json as HttpEntity, then you should try to do it with Spray-Clients pipelining, it's drop dead simple. You need to create a simple pipe: val pipe: HttpRequest => Future[HttpResponse] = sendReceive and then build a request: import spray.json.SprayJsonSupport._ pipe(Post("/api/1.0/users/ping", """{ "key"="whatever" }""".asJson)) This will return you a Future with HttpResponse, if you want some specific result, let's say, for example, some confirmation code, then add unmarshall step to your pipe: val pipe: HttpRequest => Future[ConfCode] = sendReceive ~> unmarshal[ConfCode]

Categories : Scala

Sending a post request in spray
Here is an example. There is going to be a small amount of akka code but as I mentioned in my comment, it's necessary for spray: import spray.httpx.RequestBuilding._ import spray.http._ import HttpMethods._ import HttpHeaders._ import MediaTypes._ import spray.json._ import DefaultJsonProtocol._ import spray.httpx.SprayJsonSupport._ import akka.actor.ActorSystem import spray.io.IOExtension import akka.actor.Props import spray.can.client.HttpClient import spray.client.HttpConduit import scala.concurrent.Future import scala.util.Failure import scala.util.Success case class MyObj(str:String, i:Int) object SprayExample { implicit val myObjFormat = jsonFormat2(MyObj) def main(args: Array[String]) { import concurrent.ExecutionContext.Implicits._ val obj = MyObj("hello", 1)

Categories : Json

Spray HttpClient Synchronous/Blocking Call
Doesn't the spray HTTP Client just return a scala Future? If so, then you should be able to just do: import scala.concurrent._ import duration._ val fut = ... //call spray here val result = Await.result(fut, 5 seconds) This will block on the future for up to 5 seconds waiting for it to be completed. If it times out, an exception will be thrown instead of getting a result.

Categories : Scala

Spray io - unable to resolve an error about dependencies in sbt
There is no version 1.0 of spray yet, according to the docs (and browsing the repo): see spray - Current Versions. The latest seems to be either 1.0-M7 for scala 2.9.2 or 1.1-M7 for scala 2.10.0-RC5.

Categories : Scala

How do I turn all rejections into custom json in spray?
If you just want to turn all of the rejections into your custom json format, you can create a rejection handler. For example, I'll put this in my ServiceActor and do the following: class ApiServiceActor extends Actor with HttpServiceActor with ApiServices { def jsonify(response: HttpResponse): HttpResponse = { response.withEntity(HttpBody(ContentType.`application/json`, JSONObject(Map( "details" -> response.entity.asString.toJson, "errorType" -> ApiErrorType.Unknown.toJson )).toString())) } implicit val apiRejectionHandler = RejectionHandler { case rejections => mapHttpResponse(jsonify) { RejectionHandler.Default(rejections) } } def receive = runRoute { yourRoute ~ yourOtherRoute ~ someOtherRoute } }

Categories : Json

python 2D matrix simple logic works but matrix print logic doesnt show correct matrix
You can use zip here: >>> lis = [['a','b','c'],['d','e','f']] >>> [ x[::-1] for x in zip(*lis) ] [('d', 'a'), ('e', 'b'), ('f', 'c')] #or >>> [ list(reversed(x)) for x in zip(*lis)] [['d', 'a'], ['e', 'b'], ['f', 'c']]

Categories : Python

How do I make sure the path in a Scala Spray URI does not have a trailing slash?
There are two directives in Spray-Routing toolkit in FileAndResourceDirectives module: stripLeadingSlash and withTrailingSlash, both returns boolean. Example from my project: lazy val staticPath = staticPrefixes & cache(simpleRouteCache) & encodeResponse(Gzip) & extract(ctx => !withTrailingSlash(ctx.request.uri.path))

Categories : Scala

sbt publish spray example apps to local maven repository
In the build publishing is purposely disabled for examples in this line (same file): lazy val exampleSettings = basicSettings ++ noPublishing Try removing ++ noPublishing.

Categories : Scala

spray.io http server inside Play2 application context
I can say that Spray actually is the fastest JVM-based toolkit for web-based development, you can check out the latest benchmarks on the official blog. As for the question. If you want to write your own implementation for a little HTTP server then you should check spray-can http based api, spray-io is just a layer between Akka IO and Java NIO. I'm not very good at Play, but as a way i would sugest to create a multi-build sbt config or separate project with Spray http server and connect them through REST api. Architecture would be pretty simple cause it's based on Akka actors in the simplest case would look like a bunch of cases in the receive method: def receive = { case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => sender ! HttpResponse(entity = "PONG") } On the Play side

Categories : Scala

Spray client marshalling of custom case class to JSON
Ok, I figured this out. I needed to add this import to support json marshalling: import spray.httpx.SprayJsonSupport._ After that marshalling function would be: implicit def StartObjMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = PrettyPrinter) = Marshaller.delegate[T, String](ContentTypes.`application/json`) { value ⇒ val json = writer.write(value) printer(json) }

Categories : Json

Why won't shell_exec execute files but does execute simple commands?
You want to use system in the second case, and not shell_exec. system executes an external program and displays the output. shell_exec executes a command via shell and returns the complete output as a string. and for good measure: exec simply executes an external program. Furthermore you want to make sure your external program is executable and (though you have stated it, I'll restate this) has execute permissions for the user which is running the web server. You also want to make sure the directory your external program is running in has the ability to write to its directory or /tmp or whatever output directory you have set. Finally you should always use absolute paths for executing things like this in cron or php or whatever... so don't use ./c-compiled-file argv1 argv2 argv3, but

Categories : PHP

DNS lookup asynchronously
Should be something like this CFHostSetClient(host, callbackFunction, hostContext); CFHostScheduleWithRunLoop(host, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); CFHostStartInfoResolution(host, kCFHostNames, 0); And callbackFunction void callbackFunction(CFHostRef theHost, CFHostInfoType typeInfo, const CFStreamError *error, void *info) { // Do something } You don't need to start a new thread, system will do it for you.

Categories : IOS

How to Run a whole QApplication Asynchronously?
Design pattern is totally wrong, QApplication as well as QCoreApplication are not supposed to be multiplied inside one application. What you should do for example is make your own class like: class LibraryCore: public QObject { } and substitute QApplication to this class inside your future library sources. Then you should implement needed methods in LibraryCore (ones which are used inside application) making them work properly..

Categories : C++

Using fread() asynchronously
The only way to improve this, is to return the html early and then use javascript to perform an AJAX request for another page which does the fread().. You could display a progress bar until the operation has finished. Btw, for sockets there is socket_read()

Categories : PHP

Loading UserControl asynchronously
Simply saying user control is extremely hard to render on a different thread. First, you need to be aware that the animation of progress bar also occupies UI thread that means if your time consuming job is on UI thread, even your progress bar is showing, it does not get animated. Therefore putting a progress bar on loading user control does not work as what you expected. Second, you put two UI operations in a event handler, WPF can only handle these UI operations after it finishes the current operation. Since you call loading user control using Dispatcher.Invoke with default priority at Normal,9 (I think), and direct call UI is at around Input,5, you see progress bar shows after user control is loaded. Finally you need a clear separation of sync job and async job. In your case, all UI

Categories : Wpf

What does asynchronously recursive mean in nodejs
It means that, despite the fact that you have multiple events triggering "simultaneously" each method maintains it's own state, and it's own error handling steps separately for each request and for each step. Consider this example in which we need disk information to initialize a database query. Each successive step is an asynchronous operation, that calls a callback. function dataBaseQuerys(someQuerys) { function queryDatabase(someQuery) { if(someQuery === undefined) return; fs.readFile('someFile', function (err, data) { 'use strict'; var myQuery = someQuery + data; query(myQuery, function (err, qData) { doSomethingWithTheQuery(qData); queryDatabase(someQuerys.pop());//Recursion(behaves iterativ

Categories : Node Js

File.getdirectorylisting asynchronously
You're using getDirectoryListing() instead of using the async version of the function called getDirectoryListingAsync(). The sample on Adobe's website shows how to use it. import flash.filesystem.File; import flash.events.FileListEvent; var directory:File = File.userDirectory; directory.addEventListener(FileListEvent.DIRECTORY_LISTING, directoryListingHandler); directory.getDirectoryListingAsync(); function directoryListingHandler(event:FileListEvent):void { var list:Array = event.files; for (var i:uint = 0; i < list.length; i++) { trace(list[i].nativePath); } } Do note that even this will not let you show a progress bar because you'll get the entire response in one callback. You can use a spinner instead, which indicates that the application is waiting for a re

Categories : Actionscript

Reading three files asynchronously in c#
Make writefile a single instance and apply aync lock when writing contents. public static void myCallback(IAsyncResult iar) { AsyncResult ar = (AsyncResult)iar; ReadFile readf = (ReadFile)ar.AsyncDelegate; string line = readf.EndInvoke(iar); lock(obj) { writefile.writeLine(line); successCount++; } } private static object obj = new object(); private static int successCount = 0; static void Main(string[] args) { readFileAsync(filereader1); readFileAsync(filereader2); readFileAsync(filereader3); while(Console.ReadKey()) { if(successCount == 3) { filereader1.Dispose(); filereader2.Dispose(); filereader3.Dispose(); writefile.Dispose(); break; } } }

Categories : C#

How to send email asynchronously but as soon as possible?
When you put an e-mail into the database, you also send a notification to your e-mail sending job to wake it up and send the new e-mail. Rather than waiting for the sending job to check, it is actively notified and deals with the new e-mail immediately.

Categories : Email

Sending mails asynchronously
I read that client.Send uses asynchronous calling Assuming client is actually an SmtpClient, then Send does not use asynchronous calling. SmtpClient has a specific method for sending emails asynchronously and it's called SendAsync - if you want to send an email in the background, use this instead of Send.

Categories : Asp Net

Running ssh sudo asynchronously
Use expect to control your ssh. It could be used to give automated response to the remote shell. Most processes when ran asynchronously suspends itself or becomes suspended when it tries to read input from terminal since another foreground process (the main shell) is using it. There's a post about ssh and expect lately here: http://superuser.com/questions/509545/how-to-run-a-local-script-in-remote-server-using-expect-and-bash-script Also try to disown your process after placing it on the background with disown to keep it from job control. e.g. whole_command & disown Changing its input to /dev/null might also help but it could hang forever if it really needs input from user. whole_command <&- < /dev/null & disown

Categories : Bash



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