Using the variable on range scope `x` in function literal (scopelint) - unit-testing

func TestGetUID(t *testing.T) {
namespace := "lkfm"
expecteduid := "fake_uid"
var tests = []struct {
description string
expected string
namespace string
objs []runtime.Object
}{
{"PositiveScenario", expecteduid, namespace, []runtime.Object{simpleNamespace(namespace)}},
}
for _, x := range tests {
t.Run(x.description, func(t *testing.T) {
client := fake.NewSimpleClientset(x.objs...)
actual := getUID(client, x.namespace)
assert.Equal(t, x.expected, actual)
})
}
}
Lint give me some problem on :
client := fake.NewSimpleClientset(x.objs...)
actual := getUID(client, x.namespace)
assert.Equal(t, x.expected, actual)
and it reports this error : "Using the variable on range scope x in function literal (scopelint)"

x is the loop variable which is reused in each iteration. And you create a function literal which you pass to t.Run(). The compiler does not know (does not have guarantee) whether the created and passed function literal is not called after t.Run() returns, in which case the function literal would refer to the loop variable which will be overwritten with the value of the next iteration. This is rarely–if ever–the intention. It's often the source of nasty bugs, even data race if the function literal is executed concurrently in another gorotuine.
So go vet warns about such uses.
Often the solution is to pass the value of the loop variable to the function literal as an argument, or create a copy of the loop variable and refer to the copy. Since the signature of your function literal is fixed (you can't change it), create a copy of the variable, e.g.:
x2 := x
And refer to x2 inside the function literal. This will make go vet happy.
Also, since the intention of making a copy is clear, you may use the same name, e.g. x := x, which copy will shadow the loop variable. After the above short variable declaration, the identifier x will refer to the local copy (and not the loop variable). In general this may cause confusion, but here the intention is clear and acceptable.

Related

The meaning of "static char __ = []() -> char" [duplicate]

This question already has answers here:
What is a lambda expression in C++11?
(10 answers)
Closed 2 years ago.
I saw the code from several solutions from LeetCode's problems.
static char __ = []() -> char {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return '\0'; }();
I understood that the following lines are for fast I/O.
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
However, I have no idea about
static char __ = []() -> char {
// fast IO
return '\0'; }();
Can someone explain what is meaning of the code?
[]() -> char { ... } is a lambda taking no inputs and returning a char.
The () following the lambda is calling it, like any other function call.
The char value that the lambda is returning is being assigned to a static variable named __.
Since the variable is static, it will be initialized only once, so the lambda will be called only once.
See this answer to Is there a better way in c++ for one time execution of a set of code instead of using a static variable check
This code: []() -> char { return '\0'; }()
is an expression which calls an unnamed lambda function. In fact it contains some redundant elements and could have been written []{ return '\0'; }(). Since empty argument list in lambdas can be omitted, and the return type can be deduced from the expression in the return statement.
The code is very similar to:
char qux() { return '\0'; }
char __ = qux();
except that there is no need for the identifier qux and therefore reduced chance of collision with some other identifier the program uses.
Naming the variable __ causes undefined behaviour since names containing double-underscore are reserved to the implementation, it'd be better for this code to use some valid identifier and that can perhaps be hidden via an unnamed namespace if there is a collision.
The purpose of this code is to execute the function body before main() runs. It would be cleaner to have this code occur on the first line of main(), but perhaps the author was concerned that there might be some other code which also runs before main() and relies on these statements having executed.
However, this method does not really resolve the problem as if said other statements are in a different translation unit, there is no guarantee of __'s initialization occurring before the other unit's static initialization. See static initialization order fiasco.
It's a C++ lambda, kind of an inline function (ref: https://en.cppreference.com/w/cpp/language/lambda)
It has no capture [] and no input argument () and returns char (-> char).
After define the lambda, then the code calls the lambda function. That is the last (); part. Otherwise it just defines the lambda, but not use it.

Test that an expression fails type checking

I'm writing a library in TypeScript, and I want to check that my type definitions are correct. Often, I want to check that a variable has a certain static type. I usually do it like this:
let expectedToBeString : string = Api.callFunction("param1", 2, []);
But sometimes, a type might be widened to any without me knowing about it, so the above expression would still compile. So I'd want to make sure it's not any by writing an expression that will intentionally fail type checking.
Sometimes I also want to check that my set of overloads works for legal types, but not for illegal ones, but the only way to make sure of that is to raise a compilation error.
How can I verify that a compilation error is being raised when it should be?
Interesting issue. When conditional types are released in TypeScript v2.8, coming out supposedly sometime this month (March 2018), or available now at typescript#next, you will be able to do something like this:
type ReplaceAny<T, R> = 0 extends (1 & T) ? R : T
The ReplaceAny<T, R> type will be T unless T is any, in which case it will be R. No normal type T should satisfy 0 extends (1 & T), since 1 & T should be at least as narrow as 1, and 0 is not a subtype of 1. But the any type in TypeScript breaks the rules: it's considered to be both a supertype of and a subtype of every other type (more or less). Which means that 1 & any becomes any, and 0 extends any is true. So 0 extends (1 & T) behaves like an any detector.
Now we can make a convenience function like this:
const replaceAny = <R>() => <T>(x: T): ReplaceAny<T,R> => x as any;
If you call replaceAny<{}>(), it produces a function which will take any input and return a value of type {} if that input is of type any.
So let's examine some scenarios:
declare const Api: {
callFunctionS(...args: any[]): string,
callFunctionN(...args: any[]): number,
callFunctionA(...args: any[]): any,
}
let expectedToBeString: string;
expectedToBeString =
replaceAny<{}>()(Api.callFunctionS("param1", 2, []));
// okay
expectedToBeString =
replaceAny<{}>()(Api.callFunctionN("param1", 2, []));
// error, number not assignable to string
expectedToBeString =
replaceAny<{}>()(Api.callFunctionA("param1", 2, []));
// error, {} not assignable to string
The first two behave as you expect, where expectedToBeString is happy with callFunctionS() but angry about callFunctionN(). The new behavior is that it is also angry about callFunctionA(), since replaceAny<{}>() causes the return value to be of type {} instead of any, and {} is not assignable to string.
Hope that helps; good luck!

How to keep the value of a string?

Hey guys I have a question about variables and If statements.
The reason I am asking is I am assigning tokens in a vector of strings to variables but if my vector only has 3 elements and I try to assign a variable to myVector(5) I get an error.
This is my solution to that problem
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
But that wont change the string outside the if statement? My code works fine if I have exactly 5 elements and no error check but if I'm passing in standard input I wont really know how many elements there are all I will know is that there are a max of 50 elements.
I dont need to ouput any elements just run this code on each one
if(countSubstring(element5,"a") > 0)
{
a = a + 1
}
then I would output a.
how do I make element5 keep its new string?
Problem
Your code here redefines your variable element5:
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
Here you first declare element5 after the first line, and then you re-declare it at the third line in your if statement. That essentially "recreates" the variable element5 for that scope {}. And then of course is poped right after the scope. So you won't see a change in element5 if you try to print it out of the scope.
Solution
Easy, just don't re-declare your variable, and you're all set! Like so:
std::string element5;
if(myVector.size () >= 4)
(
element5 = myVector.at(4)
}
Why is this happening?
Like I said, down in the assembly level the variable gets pushed, and then suddenly when it comes down to another level and the same variable gets re-declared, the global variable gets forgotten about. And as soon as the scope ends:
{
//This is a scope
}
the re-declared variable gets poped off the stack, and we have our original element5 back! This will leave element5 in the same position since you didn't actually change it ;).
Undefined Behaviors(UB)
Don't reference to an out-of-scope object; don't do it!
C++: Reference to "out of scope" object
References
What happens when C++ reference leaves it's scope?
What happens in C++ when I pass an object by reference and it goes out of scope?
Glossary
scope: The "container" a program is currently executing under; for example, let's take this:
int main() {
//1st scope
if (true) {
//2nd scope
{
//third scope
}
}
}
Undefined Behavior(UB):
When in an undefined/unknown state at any time given during the compilation. Compiler does whatever it decides to do, making it a very dangerous Behavior especially if you are writing a big project! Here is a good question/answer to this topic:
https://softwareengineering.stackexchange.com/questions/99692/philosophy-behind-undefined-behavior
You are redefining the string inside the if statement, you shouldn't do that because you want to use the string that has been declared before.
So just replace std::string element5 = myVector.at(4) with element5 = myVector.at(4)

Object.Error: Access Violation when printing result of std.algorithm.cartesianProduct

I'm using DMD 2.062 for x86.
module test;
private enum test1
{
one,
two,
three,
}
private enum test2
{
one,
two,
three,
}
auto ct = cartesianProduct([EnumMembers!test1], [EnumMembers!test2]);
unittest
{
import std.stdio;
foreach (n, m; ct)
{
writeln(n, " ", m);
}
}
This program prints out:
one one
two one
three one
Then an access violation error is thrown. Am I using cartesianProduct incorrectly, or is this a bug in the function?
Tiny bit of both, probably. The issue here is that ct is attempted to be evaluated at compile-time and produces result range that is used in run-time. I guess either CTFE or cartesianProduct does not expect such scenario and something bad happens that involves using invalid memory. I think it should have either work, or be a compile-time error, but that won't help you and belongs to bug tracker.
What does matter here, though is that everything will work if you move ct initialization to unit-test body or static this() module constructor. What you seem to miss is that D does not support initialization of global variables at program start-up. Value assigned to global is always evaluated at compile-time, which often "just works", often results in compile-time error (if initialization is not CTFE-able) and in this case results in weird behavior :)
What you may want is this code:
auto Test1Members = [ EnumMembers!test1 ];
auto Test2Members = [ EnumMembers!test2 ];
alias CT = typeof(cartesianProduct(Test1Members, Test2Members));
CT ct;
static this()
{
ct = cartesianProduct(Test1Members, Test2Members);
}
In general, interconnection between compile-time data and run-time data for complex types as arrays or associative arrays is very tricky with current D front-end implementation and requires lot of attention.

Is this code valid C++?

Is the following code valid C++?
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
Note : The code compiles on my g++ compiler.
As-is? No. If it were in the body of a function? Yes.
The first line declares an integer constant named var with a value of 10.
The braces begins a new block. Within that block, a new variable is declared, named var, which is an array of int with a size equal to the value of the integer constant previously declared as var (10).
The key is that var refers to the first variable until after the second variable named var is fully declared. Between the semicolon following the second declaration and the closing brace, var refers to the second variable. (If there was an initializer for the second variable, var would begin to refer to the second variable immediately before the initializer.)
Yes the code is valid C++. Non-local var is visible up to the point of declaration of local var.
So int var[var] defines a local array of 10 integers.
Yes the code is valid C++
It is a concept of SCOPE : Hiding Names
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
I think this link clears your doubt
IN C++:
http://msdn.microsoft.com/en-US/library/9a9h7328%28v=VS.80%29.aspx
In C :
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fzexscope_c.htm
If u want deep knowledge On this : Go for this link,here the information is about Lexical versus dynamic scoping
http://en.wikipedia.org/wiki/Scope_%28programming%29
but in your code : "Scope ::" of visibility of var .Here It differs like local and non-local variable.
Inside braces { x=1; } local variable . where as here {y=1;{x=1;}} ,here it differs.
helpful links
http://msdn.microsoft.com/en-us/library/b7kfh662%28VS.80%29.aspx
http://www.awitness.org/delphi_pascal_tutorial/c++_delphi/c++_scope_variables.html