nearZeroVar in caret returns vary when using foreach - r-caret

I've noticed that setting foreach=TRUE in nearZeroVar returns a different vector of integers (always seems to be 1) than foreach=FALSE. The metrics returned by saveMetrics=TRUE do not differ. Any suggestions on what I might be missing?
frame = data.frame(seq(1:100),seq(1:100),c(rep(0,99),1))
frame = cbind(frame,frame)
names(frame) = c("a","b","c","d","e","f")
nearZeroVar(frame,allowParallel=TRUE,foreach=TRUE,saveMetrics=TRUE)
freqRatio percentUnique zeroVar nzv
a 1 100 FALSE FALSE
b 1 100 FALSE FALSE
c 99 2 FALSE TRUE
d 1 100 FALSE FALSE
e 1 100 FALSE FALSE
f 99 2 FALSE TRUE
nearZeroVar(frame,allowParallel=TRUE,foreach=FALSE,saveMetrics=TRUE)
freqRatio percentUnique zeroVar nzv
a 1 100 FALSE FALSE
b 1 100 FALSE FALSE
c 99 2 FALSE TRUE
d 1 100 FALSE FALSE
e 1 100 FALSE FALSE
f 99 2 FALSE TRUE
nearZeroVar(frame,allowParallel=TRUE,foreach=TRUE)
[1] 1 1
nearZeroVar(frame,allowParallel=TRUE,foreach=FALSE)
[1] 3 6

Related

clang-format 15 - force function parameters into new line

I can't force clang-format into spliting function parameters into separate lines:
Current:
virtual void OnSlotSelected(class UArcAbilitySystemComponentBase* InArcASC, class UArcQuickBarComponent* QuickBar, const struct FArcSlotData* InSlot) const {};
Expected:
virtual void OnSlotSelected(class UArcAbilitySystemComponentBase* InArcASC
, class UArcQuickBarComponent* QuickBar
, const struct FArcSlotData* InSlot) const {};
I don't mind where exactly it is aligned (so long as it is consistent).
This my current config:
Language: Cpp
BasedOnStyle: LLVM
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeComma
AccessModifierOffset: -4
AlignAfterOpenBracket: BlockIndent
PointerAlignment: Left
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
BinPackArguments: false
BinPackParameters: false
#ExperimentalAutoDetectBinPacking: true
#PenaltyBreakBeforeFirstCallParameter: 1
#PenaltyBreakOpenParenthesis: 1
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignOperands: true
AlignTrailingComments: false
AlwaysBreakTemplateDeclarations: Yes
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBraces: Custom
ColumnLimit: 0
IncludeCategories:
- Regex: '^<.*'
Priority: 1
- Regex: '^".*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseBlocks: true
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: true
MacroBlockBegin: ''
MacroBlockEnd: ''
NamespaceIndentation: All
SpacesInAngles: false
TabWidth: 4
UseTab: Always
Remove ColumnLimit, your 0 means unlimited line width (LLVM breaks at 80 characters) so nothing will trigger line break

Tell clang-format to not add newline after control statement

When I have this minimal program
int main(void) {
for (;;) ;
if (0) return 1;
}
clang-format is adding a new line before the statements:
int main(void)
{
for (;;)
;
if (0)
return 1;
}
How can I tell it to leave control statements without {, as they are. To make an example, when I have
int main(void)
{
for (;;) ;
if (0)
return 1;
}
running clang-format on it should do nothing. I cannot find a configuration option for it. My .clang-format file is:
# SPDX-License-Identifier: GPL-2.0
#
# clang-format configuration file. Intended for clang-format >= 4.
#
# For more information, see:
#
# Documentation/process/clang-format.rst
# https://clang.llvm.org/docs/ClangFormat.html
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
---
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
#AfterExternBlock: false # Unknown to clang-format-5.0
BeforeCatch: false
BeforeElse: false
IndentBraces: false
#SplitEmptyFunction: true # Unknown to clang-format-4.0
#SplitEmptyRecord: true # Unknown to clang-format-4.0
#SplitEmptyNamespace: true # Unknown to clang-format-4.0
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
#CompactNamespaces: false # Unknown to clang-format-4.0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
#FixNamespaceComments: false # Unknown to clang-format-4.0
#IncludeBlocks: Preserve # Unknown to clang-format-5.0
IncludeCategories:
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
#IndentPPDirectives: None # Unknown to clang-format-5.0
IndentWidth: 8
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
# Taken from git's rules
#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
#SortUsingDeclarations: false # Unknown to clang-format-4.0
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp03
TabWidth: 8
UseTab: Always
...
Look inside the documentation for OnASingleLine:
https://clang.llvm.org/docs/ClangFormatStyleOptions.html
You will find:
AllowShortBlocksOnASingleLine: [Never | Empty | Always]
AllowShortIfStatementsOnASingleLine: [Never | WithoutElse | OnlyFirstIf | AllIfsAndElse]
And many more for Switch statements, lambdas...

Using loop to solve if number < than 200 previous numbers, return 1

I'm writing a small program in lua and I was hoping to get some pointers on what would be the most correct way to approach this. Basically, if my number is bigger than the last 200 numbers, return 1, else return 0.
I figure the best way would be a loop?
Let's say x is the position of my number in a table, and then I want to check that it's bigger than the previous 200 numbers and return 1 at the end if it is and 0 if it's not.
while (x > x-a)
do
isbigger = 1;
a = a+1;
return isbigger;
end
I'm not sure if that's correct syntax wise, it also would technically return 1 everytime it goes through the loop and I just want it at the end if true that my number is bigger than the 200 previous one. Also, how do get out of the loop if its false (I'd guess with a break)?
Thanks for any help and have a nice day!
If you are looping over an array of values, you should use a for loop. you also do not want to return isbigger from inside the loop as it will prematurely end the loop
local last = 10
local myNumber = 123
local numbers = {}
--Setup our example numbers table
math.randomseed(os.clock())
for i = 1, 40 do
numbers[i] = math.random(1,200)
end
--Run comparison on our the last x values
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
isBigger= isBigger and myNumber > numbers[i]
end
print("isBigger is: " .. isBigger)
return isBigger and 1 or 0
Example Output
123 181 false
123 6 true
123 77 true
123 78 true
123 145 false
123 130 false
123 104 true
123 114 true
123 6 true
123 4 true
123 15 true
isBigger is: false
The for loop above is better for understanding what is happening, but this one is better for use as it will exit once it has found an result that shows myNumber is not bigger.
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
if not (myNumber > numbers[i]) then
isBigger = false
break
end
end

What controls break before member function of an object in clang format?

This is the part of of C++ code I want to format with clang-format tool (version 7.0.0).
template <typename Fn>
void AsyncAPI::init_write(std::string const& data, Fn&& callback)
{
errorcode injected(injected_);
injected_ = 0;
if (!injected) { data_ = data; }
std::thread([injected, callback = std::forward<Fn>(callback)]() mutable {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
callback(injected);
})
.detach();
}
The detach() member function of this_thread is somehow moved to a new line. How can I move it one line up, so it looks like
std::thread([]() {
/*
*/
}).detach();
I've quite content with current settings, so I hope the change is not too drastic. I tried predefined format styles provided by clang-format (Google, LLVM), none of them was able to move detach up.
My clang-format config file is,
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: false
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeComma
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
BeforeCatch: true
BeforeElse: false
SplitEmptyFunction: true
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeBlocks: Regroup
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
...
This seems to be something that broke in clang-format version 5.0.0, and was fixed for version 10.0.0 (verified using the configurator). So, your best bet is to move to clang-format version 10.0.0 or later.

How to tell clang-format do not make short lambda expression on a single line?

#include <iostream>
int main()
{
auto func = []() {
std::cout << "hello, world" << std::endl;
};
func();
}
I would like to keep my short lambda expression in this way. But clang-format always make it on a single line.
auto func = []() { std::cout << "hello, world" << std::endl; };
I have read the documentation but I can't find the correct settings. Here is my configureļ¼š
BasedOnStyle: LLVM
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
BeforeCatch: true
BeforeElse: true
IndentBraces: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
My clang-format version is 7.0.0. If the lambda expression have more than two lines, it works well. But when it only one line. clang-format always make it in one line. Sometimes a short function which body only one line, clang-format also make it in one line.
I don't know when this option was added, at least since version 10.0 there is AllowShortLambdasOnASingleLine. See official docs.
In your case you need option's value to be Inline, or Empty, or None.

Resources