Breeze: global overload fail function - breeze

Is there a way to global overload fail function?
For instance:
var query = breeze.EntityQuery
.from('Client');
manager.executeQuery(query)
//fail(myFunction)
// I don't want call 'fail' everytime.
;
Write now error is logging to the console. I would like to inject my implementation.

Pass your query thru another function before executing it
function executeQuery(q, manager) {
return manager.executeQuery(q).fail(globalFailureHandler);
}
function globalFailureHandler(e) {
// custom code here
}
Then execute all of your queries like this
var query = breeze.EntityQuery
.from('Client');
executeQuery(query, manager).then(...);

Related

Destructuring Syntax for Tuples?

So, I'm wondering whether there is any support for destructuring syntax in Dafny. Something along the following lines:
function method f(x:int) : (int,int) { (x,x+1) }
method test() {
var y:int;
var z:int;
(y,z) := f(1);
}
In fact, I want to go further than this as I want to destructure within a function.
According to the reference manual, you cannot do it for assignment statements, but only for variable declaration statements, like this:
function method f(x:int) : (int,int) { (x,x+1) }
method test() {
var (y,z) := f(1);
}
If you want to annotate the types, you can do it like this:
var (y:int, z:int) := f(1);
You can also use a let expression to do this inside a function, like this:
function method f(x:int) : (int,int) { (x,x+1) }
function g() {
var (y,z) := f(1);
y+z
}

forEach vs for in: Different Behavior When Calling a Method

I noticed that forEach and for in to produce different behavior. I have a list of RegExp and want to run hasMatch on each one. When iterating through the list using forEach, hasMatch never returns true. However, if I use for in, hasMatch returns true.
Sample code:
class Foo {
final str = "Hello";
final regexes = [new RegExp(r"(\w+)")];
String a() {
regexes.forEach((RegExp reg) {
if (reg.hasMatch(str)) {
return 'match';
}
});
return 'no match';
}
String b() {
for (RegExp reg in regexes) {
if (reg.hasMatch(str)) {
return 'match';
}
}
return 'no match';
}
}
void main() {
Foo foo = new Foo();
print(foo.a()); // prints "no match"
print(foo.b()); // prints "match"
}
(DartPad with the above sample code)
The only difference between the methods a and b is that a uses forEach and b uses for in, yet they produce different results. Why is this?
Although there is a prefer_foreach lint, that recommendation is specifically for cases where you can use it with a tear-off (a reference to an existing function). Effective Dart recommends against using Iterable.forEach with anything else, and there is a corresponding avoid_function_literals_in_foreach_calls lint to enforce it.
Except for those simple cases where the callback is a tear-off, Iterable.forEach is not any simpler than using a basic and more general for loop. There are more pitfalls using Iterable.forEach, and this is one of them.
Iterable.forEach is a function that takes a callback as an argument. Iterable.forEach is not a control structure, and the callback is an ordinary function. You therefore cannot use break to stop iterating early or use continue to skip to the next iteration.
A return statement in the callback returns from the callback, and the return value is ignored. The caller of Iterable.forEach will never receive the returned value and will never have an opportunity to propagate it. For example, in:
bool f(List<int> list) {
for (var i in list) {
if (i == 42) {
return true;
}
}
return false;
}
the return true statement returns from the function f and stops iteration. In contrast, with forEach:
bool g(List<int> list) {
list.forEach((i) {
if (i == 42) {
return true;
}
});
return false;
}
the return true statement returns from only the callback. The function g will not return until it completes all iterations and reaches the return false statement at the end. This perhaps is clearer as:
bool callback(int i) {
if (i == 42) {
return true;
}
}
bool g(List<int> list) {
list.forEach(callback);
return false;
}
which makes it more obvious that:
There is no way for callback to cause g to return true.
callback does not return a value along all paths.
(That's the problem you encountered.)
Iterable.forEach must not be used with asynchronous callbacks. Because any value returned by the callback is ignored, asynchronous callbacks can never be waited upon.
I should also point out that if you enable Dart's new null-safety features, which enable stricter type-checking, your forEach code will generate an error because it returns a value in a callback that is expected to have a void return value.
A notable case where Iterable.forEach can be simpler than a regular for loop is if the object you're iterating over might be null:
List<int>? nullableList;
nullableList?.forEach((e) => ...);
whereas a regular for loop would require an additional if check or doing:
List<int>? nullableList;
for (var e in nullableList ?? []) {
...
}
(In JavaScript, for-in has unintuitive pitfalls, so Array.forEach often is recommended instead. Perhaps that's why a lot of people seem to be conditioned to use a .forEach method over a built-in language construct. However, Dart does not share those pitfalls with JavaScript.)
👋 jamesdin! Everything you have shared about the limitations of forEach is correct however there's one part where you are wrong. In the code snippet showing the example of how you the return value from forEach is ignored, you have return true; inside the callback function for forEach which is not allowed as the callback has a return type of void and returning any other value from the callback is not allowed.
Although you have mentioned that returning a value from within the callback will result in an error, I'm just pointing at the code snippet.
Here's the signature for forEach
Also, some more pitfalls of forEach are:
One can't use break or continue statements.
One can't get access to the index of the item as opposed to using the regular for loop

Why am I returning an Async<unit> instead of an Async<Result>?

Problem:
I am struggling to figure out how to model a function that returns an Async Result type.
Example:
type Get<'requestor,'item,'error> = 'requestor -> Async<Result<'item list,'error>>
NOTE:
I didn't run into this issue until I had to write C# code that relies on an F# function type. Hence, my C# code is performing IO and as a result wants to use a Task type.
Failed Attempt:
I want to write idiomatic F# code and do not want to sprinkle C# Task types all over my F# signatures.
For example, I don't want to do this:
type Get<'requestor,'item,'error> = 'requestor -> Task<Result<'item list,'error>>
My challenge is that I haven't figured out a way to return:
Async<Result<'item list,'error>>
Here's an example of my failure:
let someLongRunningOperation = async { Ok [1] } // Returns Async<unit> instead of AsyncResult
Conclusion:
In conclusion, how can I return an Async Result type referencing the following failed example:
let someLongRunningOperation = async { Ok [1] }
Inside a computation expression, you need to use the return keyword to wrap values in that CE's types. So this:
let someLongRunningOperation = async { Ok [1] }
should be corrected to this:
let someLongRunningOperation = async { return Ok [1] }
And then you'll be returning an Async<Result>.

Testing HTTP parameter without sending or receiving HTTP requests

I am testing a function using PHPUnit, the function checks if there are any GET POST parameters set.
If Set it returns it otherwise returns null. I have no idea how can i test it as i am not setting any http request. The function is as follows,
public static function getURIParameter($param, $defaultValue=null) {
if(isset($_REQUEST[$param]) && is_array($_REQUEST[$param]))
return $_REQUEST[$param];
else
return isset($_REQUEST[$param]) ? trim($_REQUEST[$param]) : $defaultValue;
}
And this is my test function, with some psuedo kind of code.
public function testGetURIParameter()
{
$_POST['parameter'] = true; // is something like that possible?
$this->assertSame('POST', Core::getURIParameter('parameter'));
}
Can anyone tell me how can i test this function?
First, you should devide you code into logic and transport layer. Then use Dependency Injection pattern to inject transport into logic:
<?php
interface TransportInterface {
public function request($url, $params, $method);
}
class Logic {
public function __construct(TransportInterface $transport) {
$this->transport = $transport;
}
}
You should create 2 implementations of TransportInterface - real one (cUrl) and stub one (with empty method) to use it in test env.
In tests you create mock object for StubTransport, provide expectations and inject it into Logic class.

How to do chained callbacks in F#?

In C# I am using the asynchronous versions of TcpListener/TcpClient, and I am chaining these via the callback method so that another Accept/Read is posted when the callback completes. Here is an example (untested):
public void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
PostAccept(listener);
}
private void PostAccept(TcpListener listener)
{
listener.BeginAcceptTcpClient(AcceptCallback, listener);
}
private void AcceptCallback(IAsyncResult ar)
{
var listener = ar.AsyncState as TcpListener;
if (listener == null)
{
return;
}
// get the TcpClient and begin a read chain in a similar manner
PostAccept(listener);
}
My question is how do I model something similar in F#? Would I use the async keyword? Is the code after BeginAcceptTcpClient, BeginRead, etc.. essentially the code that would be executed in the callback function? For example, is this correct?
let accept(listener:TcpListener) = async {
let! client = listener.AsyncAcceptTcpClient()
// do something with the TcpClient such as beginning a Read chain
accept(listener)
return()
}
The above code doesn't work because accept isn't defined, and marking it recursive technically isn't true as it isn't a recursive method?
#kvb's answer is correct and idiomatic.
Just wanted to also point out you can use (gasp) a loop:
let accept(t:TcpListener) =
let completed = ref false
async {
while not(!completed) do
let! client = t.AsyncAcceptTcpClient()
if client <> null then
Blah(client)
else
completed := true
}
(that was typing code into my browser, hopefully it compiles). Which is nice, since you certainly can't use a loop in the C# code (that has to span multiple methods with the begin/end callbacks).
I'm not sure what you mean by "it isn't a recusive method"; if you refer to a function from within its own definition, then it is a recursive function. I don't have much experience with the Sockets classes, but perhaps something along these lines is what you're looking for?
let rec accept(t : TcpListener) =
async {
let! client = t.AsyncAcceptTcpClient()
// do some stuff with client here
do! accept(t)
}

Resources