In python 3.7, how do I check that x=typing.List[str] is "of" typing.List? - typing

I'm storing type information in a variable x:
x = typing.List[str]
Later, this x is passed together with x_value and I want to switch logic depending on whether x is of typing.List. I'm aware that typing shouldn't be used together with isinstance and issubclass hence I am saying is of. Is there any standard, future proof (and Python 3.6 proof) way of doing this issubtype?
import sys
from typing import List
def issubtype(sub_type, parent_type):
if sys.version_info >= (3, 7):
if not hasattr(sub_type, '__origin__') or not hasattr(parent_type, '__origin__'):
return False
if sub_type.__origin__ != parent_type.__origin__:
return False
if isinstance(parent_type.__args__[0], type):
return sub_type.__args__ == parent_type.__args__
return True
else:
if not hasattr(sub_type, '__extra__') or not hasattr(parent_type, '__extra__'):
return False
if sub_type.__extra__ != parent_type.__extra__:
return False
if not parent_type.__args__ or parent_type.__args__ == sub_type.__args__:
return True
return False
assert issubtype(List[str], List[str])
assert issubtype(List[str], List)
assert issubtype(List[int], List[int])
assert not issubtype(List[int], List[str])
When trying to implement this I realise that any good solution would have to recursively check args (which my attempt doesn't do, but for me just knowing if a thing is a list is enough).

Related

Scala: Compare Arrays ignoring order

I was wondering if there's any method within Arrays that checks for equality ignoring order. By far, I did find this one:
test("test ignoring order"){
assert(Array(1,2,4,5).sameElements(Array(1,4,2,5)))
}
But it fails as the order is not the same:
org.scalatest.exceptions.TestFailedException: scala.Predef.intArrayOps(scala.Array.apply(1, 2, 4, 5)).sameElements[Int](scala.Predef.wrapIntArray(scala.Array.apply(1, 4, 2, 5))) was false
Is there any method to do this, inside or outside Arrays?
EDIT: I don't need to sort the arrays, I just want to compare them ignoring order.
A simple recursion will do it.
def isSame[T](arrA:Array[T], arrB:Array[T]) :Boolean =
arrA.length == arrB.length &&
(arrA.isEmpty || isSame(arrA.filterNot(_ == arrA.head)
,arrB.filterNot(_ == arrA.head)))
But #Tim's question is valid: What's your objection to the obvious and simple sorted solution?
Following will sort both the arrays and then equates them :
test("test ignoring order"){
assert(Array(1,2,4,5).sorted sameElements Array(1,4,2,5).sorted)
}
NOTEs:
You can use == instead of sameElements if you are working with some other collections apart from Array.
array1.toSet == array2.toSet won't work if one of the array has duplicates while other doesn't.
Is this working as expected ??
import scala.annotation.tailrec
def equalsIgnoringOrder(first:Array[Int], second:Array[Int]) : Boolean = {
def removeAtIndex(i:Int, array: Array[Int]) : Array[Int] = {
val buffer = array.toBuffer
buffer.remove(i)
buffer.toArray
}
#tailrec
def firstEqualSecondRec(i:Int, other:Array[Int]) : Boolean = {
if(other.isEmpty) true
else {
val el = first(i)
val index = other.indexOf(el)
if(index == -1) false
else firstEqualSecondRec(i+1, removeAtIndex(index, other))
}
}
if (first.length != second.length) false
else {
val startingIndex = 0
firstEqualSecondRec(startingIndex, second)
}
}
It's an older thread, but I just had the same question.
The proposed answers include sorting (which only works for comparable objects) or approaches with O(n^2) runtime behavior (and/or non-trivial recursion).
Another (simple yet understandable and powerful) approach would be to use Scala's diff function:
def hasSameElementsUnordered[T](arrA: Array[T], arrB: Array[T]): Boolean = {
(arrA.length == arrB.length) && (arrA diff arrB).isEmpty
}
BTW this works on any collection and element types, not only arrays and comparables.
Internally diff() builds an occurrence count hash map, so runtime behavior will be much better for larger collections.

check if sub returned undef

Contrived example:
use strict;
use warnings;
my $myval = 'a';
my #result = my_sub($myval);
if (#result) {
print "DEFINED\n";
}
my ($res1, $res2, $res3) = #result;
print "res1=$res1, res2=$res2, res3=$res3\n";
sub my_sub {
my $myval = shift;
if ($myval eq 'a') {
return undef;
}
return ("a","b","c");
}
How do I check if sub returned undef?
or
How do I check if sub did not return undef?
return undef in list context returns list of one element, which is undef.
#result = my_sub($myval);
if (#result == 1 && !defined($result[0])) {
warn "my_sub() returned undef";
} else {
print "my_sub() returned data\n";
}
That said, a list with one undef element is almost never what you want. See How do I return nothing from a subroutine? You will generally just want to return with no arguments. In scalar context, that returns undef and in list context it returns an empty list.
sub my_other_sub {
my $myval = shift;
if ($myval eq 'a') {
return;
}
return ("a","b","c");
}
...
#result = my_other_sub($arg1);
$result = my_other_sub($arg2);
if (#result == 0) { # or: if (!#result) ... or: unless (#result) ...
warn "my_other_sub(arg1) did not return any data";
} else {
print "my_other_sub(arg1) returned data\n";
}
if (!defined($result)) {
warn "my_other_sub(arg2) did not return any data";
} else {
print "my_other_sub(arg2) returned data\n";
}
I would recommend, as others have, to use return, or the more explicit return (). This returns an empty list. However, since the example is contrived, we can't be sure that an empty list isn't an otherwise valid return. If it is a valid return, or it might reasonably be so one day, then you have other options which, IMO, are less ideal but can be more flexible.
An obvious one is to use die, as zdim suggested, but that can be relatively heavy-handed. It may actually be really what you want - if this situation really isn't supposed to happen, die is perfect as it might cause your program to abort if you don't wrap the failure in an eval.
Another alternative is to have your sub return an array ref instead of a list. And then you can return undef directly, your caller would be able to check that easily enough: my $result = my_sub(...);. Other uses of that array would just need to go through a dereference, e.g., my ($res1, $res2, $res3) = #$result;. This is probably my preference when a simple return () cannot suffice. Bonus points in that only the reference is passed back, not the whole list. Consider doing this even when an empty list isn't valid but the list can be very large.
Other options also abound, although those are probably the simplest. You could, for example, return a hash (or array) with one entry indicating success/failure and another with the array. You could return success/failure as the first element (your contrived example would return (1, "a", "b", "c") and you'd shift that first element off to see if it was successful or not). You could embed your return in an object that encapsulated all that. Of these, only the object one would I give serious consideration to, but it would greatly depend on the rest of the architecture, and would be very rare.
A subroutine returns a list of scalars in list context which you use, then assigned to variables. So if you return an undef from it the $res variables are going to be undef -- first assigned undef and others unassigned (while the array #result will have one element, an undef)
perl -Mstrict -wE'
my $val = shift;
sub t { return undef if shift eq "bad"; return qw(a b) };
my ($v1, $v2) = t($val);
if (not defined $v1 and not defined $v2) { say "undef" }
else { say "$v1, $v2" }
' bad
The first shift takes the value off of #ARGV, so vary input of "bad" to see other cases. This can be written in more compact and clearer ways if we knew how it's used.
I appreciate that this is a test example, but it is still too convoluted, allowing for tricky edge cases; for example, your first case won't work since #result is not "false" (empty list), what the code tests for, as it does have one element, which is undef.
For such "special" returns either use return with no arguments or throw a die, in situations you consider exceptional. For context-aware returns see wantarray.

What are the sign extension rules for calling Windows API functions (stdcall)? This is needed to call WInAPI from Go, which is strict about int types

Oops, there was one thing I forgot when I made this answer, and it's something that I'm both not quite sure on myself and that I can't seem to find information for on MSDN and Google and the Stack Overflow search.
There are a number of places in the Windows API where you use a negative number, or a number too large to fit in a signed integer; for instance, CW_USEDEFAULT, INVALID_HANDLE_VALUE, GWLP_USERDATA, and so on. In the world of C, everything is all fine and dandy: the language's integer promotion rules come to the rescue.
But in Go, I have to pass all my arguments to functions as uintptr (which is equivalent to C's uintptr_t). The return value from the function is also returned this way, and then I will need to compare. Go doesn't allow integer promotion, and it doesn't allow you to convert a signed constant expression into an unsigned one at compile-time.
Right now, I have a bit of a jerry-rig set up for handling these constants in my UI library. (Here's an example of what this solution looks like in action.) However, I'm not quite satisfied with this solution; it feels to me like it's assuming things about the ABI, and I want to be absolutely sure of what I'm doing.
So my question is: how are signed values handled when passing them to Windows API functions and how are they handled when returning?
All my constants are autogenerated (example output). The autogenerator uses a C ffi, which I'd rather not use for the main project since I can call the DLLs directly (this also makes cross-compilation easier at least for the rest of the year). If I could somehow leverage that, for instance by making everything into a C-side variable of the form
uintptr_t x_CONST_NAME = (uintptr_t) (CONST_NAME);
that would be helpful. But I can't do that without this answer.
Thanks!
Update
Someone on IRC put it differently (reformatted to avoid horizontal scrolling):
[19:13] <FraGag> basically, you're asking whether an int with a value of -1
will be returned as 0x00000000FFFFFFFF or as 0xFFFFFFFFFFFFFFFF
if an int is 4 bytes and an uintptr is 8 bytes
Basically this, but specifically for Windows API interop, for parameters passed in, and regardless of uintptr size.
#twotwotwo's comments to my question pointed me in the right direction. If Stack Overflow allowed marking comments as answers and having multiple answers marked, I'd do that.
tl;dr version: what I have now is correct after all.
I wrote a program (below) that simply dumped all the constants from package syscall and looked for constants that were negative, but not == -1 (as that would just be ^0). The standard file handles (STD_ERROR_HANDLE, STD_INPUT_HANDLE, and STD_OUTPUT_HANDLE) are (-12, -10, and -11, respectively). The code in package syscall passes these constants as the sole argument of getStdHandle(h int), which produces the required file handle for package os. getStdHandle() passes this int to an autogenerated function GetStdHandle(stdhandle int) that wraps a call to the GetStdHandle() system call. GetStdHandle() takes the int and merely converts it to uintptr for passing into syscall.Syscall(). Though no explanation is given in the autogenerator's source (mksyscall_windows.go), if this didn't work, neither would fmt.Println() =P
All of the above is identical on both windows/386 and windows/amd64; the only thing in a processor-specific file is GetStdHandle(), but the relevant code is identical.
My negConst() function is already doing the same thing, just more directly. As such, I can safely assume that it is correct.
Thanks!
// 4 june 2014
// based on code from 24 may 2014
package main
import (
"fmt"
"os"
"strings"
"go/token"
"go/ast"
"go/parser"
"code.google.com/p/go.tools/go/types"
_ "code.google.com/p/go.tools/go/gcimporter"
)
var arch string
func getPackage(path string) (typespkg *types.Package, pkginfo types.Info) {
var pkg *ast.Package
fileset := token.NewFileSet() // parser.ParseDir() actually writes to this; not sure why it doesn't return one instead
filter := func(i os.FileInfo) bool {
if strings.Contains(i.Name(), "_windows") &&
strings.Contains(i.Name(), "_" + arch) &&
strings.HasSuffix(i.Name(), ".go") {
return true
}
if i.Name() == "race.go" || // skip these
i.Name() == "flock.go" {
return false
}
return strings.HasSuffix(i.Name(), "_windows.go") ||
(!strings.Contains(i.Name(), "_"))
}
pkgs, err := parser.ParseDir(fileset, path, filter, parser.AllErrors)
if err != nil {
panic(err)
}
for k, _ := range pkgs { // get the sole key
if pkgs[k].Name == "syscall" {
pkg = pkgs[k]
break
}
}
if pkg == nil {
panic("package syscall not found")
}
// we can't pass pkg.Files directly to types.Check() because the former is a map and the latter is a slice
ff := make([]*ast.File, 0, len(pkg.Files))
for _, v := range pkg.Files {
ff = append(ff, v)
}
// if we don't make() each map, package types won't fill the structure
pkginfo.Defs = make(map[*ast.Ident]types.Object)
pkginfo.Scopes = make(map[ast.Node]*types.Scope)
typespkg, err = new(types.Config).Check(path, fileset, ff, &pkginfo)
if err != nil {
panic(err)
}
return typespkg, pkginfo
}
func main() {
pkgpath := "/home/pietro/go/src/pkg/syscall"
arch = os.Args[1]
pkg, _ := getPackage(pkgpath)
scope := pkg.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if obj == nil {
panic(fmt.Errorf("nil object %q from scope %v", name, scope))
}
if !obj.Exported() { // exported names only
continue
}
if _, ok := obj.(*types.Const); ok {
fmt.Printf("egrep -rh '#define[ ]+%s' ~/winshare/Include/ 2>/dev/null\n", obj.Name())
}
// otherwise skip
}
}

Backbone.js: Best way to handle multiple nullable filter parameters

have the following function on my collection:
getFiltered: function (status, city) {
return this.filter(function (trainer) {
return ((status === null) ? trainer : trainer.get("TrainerStatusName") === status) &&
((city === null) ? trainer : trainer.get('City') === city);
});
}
What is is best way to deal with nullable params passed in i.e. if city it null then ignore filter/fetch all and if status is null then ignore filter/fetch all
The code above works, but curious about alternatives
Ok, first off, I'm a little confused by your question; the title says its about handling "nullable" parameters, but your code looks like it is dealing with "special case" parameters (specifically "all") ... except for the case of trainer being null, but I don't think that is even possible when iterating through a Backbone collection.
* * Edit * *
OP updated the question, so the above is no longer relevant. I've also updated my answer accordingly.
In any case, there's nothing at all wrong or unusual about your code; ternary operators are a standard way of handling one-off special cases. If you're looking for alternative ideas though, here's one that uses an extra function to DRY out (eliminate the duplication of) your code:
function matchesOrAll(expected, actual) {
return expected === null || expected === actual;
}
getFiltered: function (status, city) {
return this.filter(function (trainer) {
return matchesOrAll(status, trainer.get("TrainerStatusName") &&
matchesOrAll(city, trainer.get("City"));
}
* * Edit * *
Now that we're talking about null and not "all", it's worth pointing out that there is a better pattern for simpler cases of nulls/undefined. If you were just filtering cities, for instance, the code could just be:
getFiltered: function (expectedCity) {
return this.filter(function (currentCity) {
return expectedCity === (currentCity || expectedCity);
}
In other words, you could take advantage of Javascript's "truthiness", and the fact that disjunctive (ie. ||) booleans expressions return the first truthy value. This eliminates the need for a ternary, and many libraries use this pattern to fill in un-provided arguments; for instance, here's a line from jQuery that sets the "target" argument to a new object if none is provided:
target = arguments[1] || {};
Unfortunately though, when you're dealing with properties/attributes of things (eg. trainer.get('foo')) instead of just objects directly (eg. trainer), there's no good shortcut you can use (other than making a function).

A better way to properly implement string 'in' array

suppose you have an array with a number of strings in ActionScript3 and you want to test if a test string is "in" that array. "in" only works against the index with Arrays in AS3 (which is totally retardo if you ask me), though it does work with ojects, but we're not talking about objects.
Can someone improve (reduce) on this code I'm using now? I'm hoping to avoid defining a utility function - I'd like a nice elegant one-liner.
myArray.filter(function(item:*, i:int, a:Array) { return (item == testString); }).length
Since 0 == false we can use it in a test. Do note that testString's scope is defined in the containing function, encapsulated by the closure.
if (allowedProfiles.filter(function(item:*, i:int, a:Array) { return (item == name); }).length){ // yay! }
Use the Array.indexOf() method to see that the index of the string in the array is not -1 (not found):
var myArray:Array = ["hello", "world"];
trace(myArray.indexOf("hello")); // == 0;
trace(myArray.indexOf("goodbye")); // == -1
Why not just use indexOf()?
if(myArray.indexOf("testString") != -1) { // it's in there

Resources