MQL4 Error: " '}' - not all control paths return a value" - mql4

Been doing this code in "Include" file. But I am encountering the error "not all control paths return a value. What should I do?
double CalculateTakeProfit (double entryPrice, int takeProfitPips, double GetPipValue)
{
if (bIsBuyPosition == True)
{
double result = 0;
entryPrice = Ask;
result = (entryPrice + takeProfitPips * GetPipValue());
return result;
}
else if (bIsBuyPosition == False)
{
double result = 0;
entryPrice = Bid;
result = (entryPrice - takeProfitPips * GetPipValue());
return result;
}
}

Your if... else is wrong and you are also not using the variables passed to the function. You are instead referencing another function or overwriting them. Mixing variable types in a calculation can also lead to undesirable results (takeProfitPips should be of type double). You can also cut a few lines of your code down as follows
double CalculateTakeProfit(double entryPrice, double takeProfitPips, double GetPipValue)
{
if(bIsBuyPosition) return(entryPrice+takeProfitPips*GetPipValue);
else return(entryPrice-takeProfitPips*GetPipValue);
}

Related

The operator '[]=' isn't defined for the type 'String'

I'm getting an error in this code:
void main() {
List<String> wave(String str) {
List<String> results = [];
String newStr;
int i = 0;
for (String ltr in str.split('')) {
newStr = str;
if (ltr != ' ') {
newStr[i] = ltr.toUpperCase();
results.add(newStr);
}
i++;
}
return results;
}
print(wave(' gap '));
}
the error is at the line:
newStr[i] = ltr.toUpperCase;
Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!
In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.
To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:
if (ltr != ' ' && i < newStr.length) {
newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
results.add(newStr);
}
To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.
try to replace
newStr[i] = ltr.toUpperCase();
to
newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);
So the result will be [ Gap , gAp , gaP ]
Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

How to create a function WordSplit(strArr) read the array of strings stored in strArr using dart

I have a simple exercise in Coderbyte, it just want to have a function that's WordSplit(strArr) read the array of strings stored in strArr, For example I have two elements like ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]
I just want to to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input.
For example: the first element can be split into two words: hello and cat because both of those words are in the dictionary.
So the program should return the two words that exist in the dictionary separated by a comma, as this result hello,cat .
I've made a recursive solution below. It checks if the string to be split starts with any word in the dictionary. If it exists, the function is called again using a substring with that first word removed.
This function only works up to the first word that isn't in the dictionary since you did not specify the expected behavior when the inputted word is not made up of words in the dictionary. You could make it throw an exception perhaps, but please specify your expectation.
void main() {
print(wordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
//hello,cat
}
String wordSplit(List<String> arg) {
String wordToSplit = arg[0];
String dict = arg[1];
List<String> parsedDict = arg[1].split(',');
for(String word in parsedDict) {
if(wordToSplit.startsWith(word)) {
//If the substring would be empty, don't do more recursion
if(word.length == wordToSplit.length) {
return word;
}
return word + ',' + wordSplit([wordToSplit.substring(word.length), dict]);
}
}
return wordToSplit;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> converToWords(string dict) {
vector<string> res;
string s = "";
int n = dict.length();
for(int i=0; i<n; i++) {
if(dict[i] == ',') {
res.push_back(s);
s = "";
}
else s += dict[i];
}
res.push_back(s);
s = "";
return res;
}
string solve(string str[]) {
string result = "";
string word = str[0], dict = str[1];
int n = word.length();
vector<string> vs = converToWords(dict);
unordered_set<string> ust;
for(auto it: vs) ust.insert(it);
// for(auto i=ust.begin(); i!=ust.end(); i++){
// cout<<*i<<endl;
// }
string s = "";
for(int i=0; i<n; i++) {
s += word[i];
// cout<<s<<endl;
string temp = word.substr(i+1, n-(i+1));
// cout<<temp<<endl;
if(ust.find(s) != ust.end() && ust.find(temp) != ust.end()) {
cout<<s<<endl;
cout<<temp<<endl;
result += s+","+temp;
break;
}
temp = "";
}
return result;
}
int main() {
string arr[2];
cin>>arr[0]>>arr[1];
cout << solve(arr);
return 0;
}

What is the best way to trim a trailing character in Dart?

In Dart the trim(), trimLeft() and trimRight() string methods do not take a parameter to specify unwanted non-whitespace characters.
What is the best way to trim a specific character from the ends of a string in Dart?
I am using this for now, but it feels hard to remember and not very generic:
final trailing = RegExp(r"/+$");
final trimmed = "test///".replaceAll(trailing, "");
assert(trimmed == "test");
There is no specific functionality to trim non-whitespace from the end of a string.
Your RegExp based approach is reasonable, but can be dangerous when the character you want to remove is meaningful in a RegExp.
I'd just make my own function:
String removeTrailing(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = from.length;
while (from.startsWith(pattern, i - pattern.length)) i -= pattern.length;
return from.substring(0, i);
}
Then you can use it as:
final trimmed = removeTrailing("/", "test///")
assert(trimmed == "test");
The corresponding trimLeading function would be:
String trimLeading(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = 0;
while (from.startsWith(pattern, i)) i += pattern.length;
return from.substring(i);
}
Since the existing answer by lrn has a lot of problems - including infinite loop scenarios - I thought I'd post my version.
String trimLeft(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.startsWith(pattern) ){
from = from.substring(pattern.length);
}
return from;
}
String trimRight(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.endsWith(pattern) ){
from = from.substring(0, from.length-pattern.length);
}
return from;
}
String trim(String from, String pattern){
return trimLeft(trimRight(from, pattern), pattern);
}
To trim all trailing/right characters by specified characters, use the method:
class StringUtil {
static String trimLastCharacters(String srcStr, String pattern) {
if (srcStr.length > 0) {
if (srcStr.endsWith(pattern)) {
final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
return trimLastCharacters(v, pattern);
}
return srcStr;
}
return srcStr;
}
}
For example, you want to remove all 0 behind the decimals
$23.67890000
then, invoke the method
StringUtil.trimLastCharacters("$23.67890000", "0")
finally, got the output:
$23.6789

How to remove trailing zeros using Dart

I would like the optimal solution for removing trailing zeros using Dart. If I have a double that is 12.0 it should output 12. If I have a double that is 12.5 it should output 12.5
I made regular expression pattern for that feature.
double num = 12.50; // 12.5
double num2 = 12.0; // 12
double num3 = 1000; // 1000
RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
String s = num.toString().replaceAll(regex, '');
UPDATE
A better approach, just use this method:
String removeDecimalZeroFormat(double n) {
return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
}
OLD
This meets the requirements:
double x = 12.0;
double y = 12.5;
print(x.toString().replaceAll(RegExp(r'.0'), ''));
print(y.toString().replaceAll(RegExp(r'.0'), ''));
X Output: 12
Y Output: 12.5
Use NumberFormat:
String formatQuantity(double v) {
if (v == null) return '';
NumberFormat formatter = NumberFormat();
formatter.minimumFractionDigits = 0;
formatter.maximumFractionDigits = 2;
return formatter.format(v);
}
If what you want is to convert a double without decimals to an int but keep it as a double if it has decimals, I use this method:
num doubleWithoutDecimalToInt(double val) {
return val % 1 == 0 ? val.toInt() : val;
}
Lots of the answers don't work for numbers with many decimal points and are centered around monetary values.
To remove all trailing zeros regardless of length:
removeTrailingZeros(String n) {
return n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "");
}
Input: 12.00100003000
Output: 12.00100003
If you only want to remove trailing 0's that come after a decimal point, use this instead:
removeTrailingZerosAndNumberfy(String n) {
if(n.contains('.')){
return double.parse(
n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "") //remove all trailing 0's and extra decimals at end if any
);
}
else{
return double.parse(
n
);
}
}
I found another solution, to use num instead of double. In my case I'm parsing String to num:
void main() {
print(num.parse('50.05').toString()); //prints 50.05
print(num.parse('50.0').toString()); //prints 50
}
Here is what I've come up with:
extension DoubleExtensions on double {
String toStringWithoutTrailingZeros() {
if (this == null) return null;
return truncateToDouble() == this ? toInt().toString() : toString();
}
}
void main() {
group('DoubleExtensions', () {
test("toStringWithoutTrailingZeros's result matches the expected value for a given double",
() async {
// Arrange
final _initialAndExpectedValueMap = <double, String>{
0: '0',
35: '35',
-45: '-45',
100.0: '100',
0.19: '0.19',
18.8: '18.8',
0.20: '0.2',
123.32432400: '123.324324',
-23.400: '-23.4',
null: null
};
_initialAndExpectedValueMap.forEach((key, value) {
final initialValue = key;
final expectedValue = value;
// Act
final actualValue = initialValue.toStringWithoutTrailingZeros();
// Assert
expect(actualValue, expectedValue);
});
});
});
}
String removeTrailingZero(String string) {
if (!string.contains('.')) {
return string;
}
string = string.replaceAll(RegExp(r'0*$'), '');
if (string.endsWith('.')) {
string = string.substring(0, string.length - 1);
}
return string;
}
======= testcase below =======
000 -> 000
1230 -> 1230
123.00 -> 123
123.001 -> 123.001
123.00100 -> 123.001
abc000 -> abc000
abc000.0000 -> abc000
abc000.001 -> abc000.001
Here is a very simple way. Using if else I will check if the number equals its integer or it is a fraction and take action accordingly
num x = 24/2; // returns 12.0
num y = 25/2; // returns 12.5
if (x == x.truncate()) {
// it is true in this case so i will do something like
x = x.toInt();
}
To improve on What #John's answer: here is a shorter version.
String formatNumber(double n) {
return n.toStringAsFixed(0) //removes all trailing numbers after the decimal.
}
This function removes all trailing commas. It also makes it possible to specify a maximum number of digits after the comma.
extension ToString on double {
String toStringWithMaxPrecision({int? maxDigits}) {
if (round() == this) {
return round().toString();
} else {
if (maxDigits== null) {
return toString().replaceAll(RegExp(r'([.]*0)(?!.*\d)'), "");
} else {
return toStringAsFixed(maxDigits)
.replaceAll(RegExp(r'([.]*0)(?!.*\d)'), "");
}
}
}
}
//output without maxDigits:
// 1.0 -> 1
// 1.0000 -> 1
// 0.99990 -> 0.9999
// 0.103 -> 0.103
//
////output with maxDigits of 2:
// 1.0 -> 1
// 1.0000 -> 1
// 0.99990 -> 0.99
// 0.103 -> 0.1
user3044484's version with Dart extension:
extension StringRegEx on String {
String removeTrailingZero() {
if (!this.contains('.')) {
return this;
}
String trimmed = this.replaceAll(RegExp(r'0*$'), '');
if (!trimmed.endsWith('.')) {
return trimmed;
}
return trimmed.substring(0, this.length - 1);
}
}
// The syntax is same as toStringAsFixed but this one removes trailing zeros
// 1st toStringAsFixed() is executed to limit the digits to your liking
// 2nd toString() is executed to remove trailing zeros
extension Ex on double {
String toStringAsFixedNoZero(int n) =>
double.parse(this.toStringAsFixed(n)).toString();
}
// It works in all scenarios. Usage
void main() {
double length1 = 25.001;
double length2 = 25.5487000;
double length3 = 25.10000;
double length4 = 25.0000;
double length5 = 0.9;
print('\nlength1= ' + length1.toStringAsFixedNoZero(3));
print('\nlength2= ' + length2.toStringAsFixedNoZero(3));
print('\nlenght3= ' + length3.toStringAsFixedNoZero(3));
print('\nlenght4= ' + length4.toStringAsFixedNoZero(3));
print('\nlenght5= ' + length5.toStringAsFixedNoZero(0));
}
// output:
// length1= 25.001
// length2= 25.549
// lenght3= 25.1
// lenght4= 25
// lenght5= 1
you can do a simple extension on the double class
and add a function which in my case i called it neglectFractionZero()
in this extension function on double(which returns a string) i
split the converted number to string and i check if the split part of the string is "0" , if so i return the first part only of the split and i neglect this zero
you can modify it according to your needs
extension DoubleExtension on double {
String neglectFractionZero() {
return toString().split(".").last == "0"? toString().split(".").first:toString();
}
}
I've came up with improved version of #John.
static String getDisplayPrice(double price) {
price = price.abs();
final str = price.toStringAsFixed(price.truncateToDouble() == price ? 0 : 2);
if (str == '0') return '0';
if (str.endsWith('.0')) return str.substring(0, str.length - 2);
if (str.endsWith('0')) return str.substring(0, str.length -1);
return str;
}
// 10 -> 10
// 10.0 -> 10
// 10.50 -> 10.5
// 10.05 -> 10.05
// 10.000000000005 -> 10
void main() {
double x1 = 12.0;
double x2 = 12.5;
String s1 = x1.toString().trim();
String s2 = x2.toString().trim();
print('s1 is $s1 and s2 is $s2');
}
try trim method https://api.dartlang.org/stable/2.2.0/dart-core/String/trim.html

Access in array in specific indices

I am trying to access an array in a function, as far as I understand there is no Arraylists in Swift, so I am trying to use regular list:
func findNearsetPoints(pointsArray: [Point] , myPoint: Point )-> Array <Point>{
var twoPoint = [Point]()
var minDist1:Double = DBL_MAX;
var minDist2:Double = DBL_MAX;
var distance:Double = 0
for element in pointsArray{
distance = getDistanceBetweenTwoPoints(pointsArray[element], Point); //error 0
if (distance < minDist1) {
minDist1 = distance;
twoPoint[1] = twoPoint[0];
twoPoint[0] = pointsArray[element]; // error 1
}
else if (distance < minDist2) {
minDist2 = distance;
twoPoint[1] = pointsArray[element]; //error 1
}
}
return twoPoint;
}
func getDistanceBetweenTwoPoints(point1:Point , point2:Point )->Double{
return 5; //TODO
}
error 0:
/Users/user/Desktop/proj/ViewController.swift:145:38: Cannot subscript a value of type '[ViewController.Point]' with an index of type 'ViewController.Point'
error 1:
/Users/user/Desktop/proj/ViewController.swift:149:38: Cannot subscript a value of type '[ViewController.Point]' with an index of type 'ViewController.Point'
What is wrong with the code?
thanks!
your element is already a Point and not an index.
for element in pointsArray{
distance = getDistanceBetweenTwoPoints(point1: element, point2: myPoint) // fix here
if (distance < minDist1) {
minDist1 = distance;
twoPoint[1] = twoPoint[0];
twoPoint[0] = element; // fix here
}
else if (distance < minDist2) {
minDist2 = distance;
twoPoint[1] = element; // fix here
}
}
PS:
take a loook also to this question "Sort array by calculated distance in Swift" for better calculation of distance. just sort the array by distance and then take the first from the array after it is sorted. thats more easy to do
You declared getDistanceBetweenTwoPoints as taking named parameters.
With the current declaration, you need to call it using this syntax:
getDistanceBetweenTwoPoints(point1: aPoint, point2: anotherPoint)
If you want to call it without labels on the parameters then you should redefine it like this:
func getDistanceBetweenTwoPoints(
_ point1:Point ,
_ point2:Point )->Double{
return 5; //TODO
}

Resources