Bogus | simple fake data generator for C # , F # , and VB.NET | Mock library

 by   bchavez C# Version: v34.0.2 License: Non-SPDX

kandi X-RAY | Bogus Summary

Bogus is a C# library typically used in Financial Services, Banks, Payments, Testing, Mock applications. Bogus has no bugs, it has no vulnerabilities and it has medium support. However Bogus has a Non-SPDX License. You can download it from GitHub.
[Chat] . Bogus for .NET: C#, F#, and VB.NET.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        Bogus has a medium active ecosystem.
                        summary
                        It has 7009 star(s) with 412 fork(s). There are 125 watchers for this library.
                        summary
                        It had no major release in the last 12 months.
                        summary
                        There are 32 open issues and 260 have been closed. On average issues are closed in 7 days. There are 12 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of Bogus is v34.0.2
                        Bogus Support
                          Best in #Mock
                            Average in #Mock
                            Bogus Support
                              Best in #Mock
                                Average in #Mock

                                  kandi-Quality Quality

                                    summary
                                    Bogus has 0 bugs and 0 code smells.
                                    Bogus Quality
                                      Best in #Mock
                                        Average in #Mock
                                        Bogus Quality
                                          Best in #Mock
                                            Average in #Mock

                                              kandi-Security Security

                                                summary
                                                Bogus has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                Bogus code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                Bogus Security
                                                  Best in #Mock
                                                    Average in #Mock
                                                    Bogus Security
                                                      Best in #Mock
                                                        Average in #Mock

                                                          kandi-License License

                                                            summary
                                                            Bogus has a Non-SPDX License.
                                                            summary
                                                            Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
                                                            Bogus License
                                                              Best in #Mock
                                                                Average in #Mock
                                                                Bogus License
                                                                  Best in #Mock
                                                                    Average in #Mock

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        Bogus releases are available to install and integrate.
                                                                        summary
                                                                        Installation instructions are not available. Examples and code snippets are available.
                                                                        Bogus Reuse
                                                                          Best in #Mock
                                                                            Average in #Mock
                                                                            Bogus Reuse
                                                                              Best in #Mock
                                                                                Average in #Mock
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
                                                                                  Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  Bogus Key Features

                                                                                  :card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.

                                                                                  Bogus Examples and Code Snippets

                                                                                  No Code Snippets are available at this moment for Bogus.
                                                                                  Community Discussions

                                                                                  Trending Discussions on Bogus

                                                                                  Getting authorization for Zoho APIs
                                                                                  chevron right
                                                                                  Git pull from two different branches in two different repositories into one local branch
                                                                                  chevron right
                                                                                  C# Regex whitespace between capturing groups
                                                                                  chevron right
                                                                                  Wrong result of multiplication: Undefined behavior or compiler bug?
                                                                                  chevron right
                                                                                  Generate Random Age Height Weight using Bogus
                                                                                  chevron right
                                                                                  Deallocating arrays defined from c_f_pointer
                                                                                  chevron right
                                                                                  Ternary operator not using the useState correctly
                                                                                  chevron right
                                                                                  Why is clangd not seeing my custom library location
                                                                                  chevron right
                                                                                  plotshape - text colour displayed incorrectly with user defined input variables
                                                                                  chevron right
                                                                                  How to deal with SQL Aggregate Functions when Grouping deeply hiearched data
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  Getting authorization for Zoho APIs
                                                                                  Asked 2022-Mar-24 at 02:32

                                                                                  I am trying to follow Zoho's guide for getting authorized via OAuth. Unfortunately, the guide seems a little outdated as the API Console doesnt look like the screen shots provided in the guide.

                                                                                  This is what I am trying to accomplish

                                                                                  I'm developing a windows client application. So naturally i chose the Non-Browser Application for my zoho client (in the API Console). Using this client type there is no "Authorized Redirect URIs".

                                                                                  So how am i supposed to get authorized to start using the Zoho APIs?

                                                                                  Currently, i've tried various client types w/ various redirect uris (bogus). I am getting an http code response of 500.

                                                                                  I am basically calling an HttpClient GetAsync(requestUrl ) where requestUrl is defined below:

                                                                                  var scopeValue = $"{scope}&client_id={clientId}&client_secret={secret}&response_type=code&access_type=offline";
                                                                                  var requestUrl = $"https://accounts.zoho.com/oauth/v2/auth?scope={scopeValue}";
                                                                                  

                                                                                  Question

                                                                                  • Why am i getting a 500 error when i invoke this GET request to get authorized?
                                                                                  • Am I choosing/configuring the wrong zoho client type?
                                                                                  • Is there a difference between a Zoho Account Id and User Id (this MIGHT be one of my problems)?

                                                                                  Just for FYI, here is the Zoho API Console with the various client types to choose from:

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-24 at 02:32

                                                                                  Try going to a different requestUrl. I believe you should be going here. You should also be using a POST request. I chose the Non-Browser Application for my zoho client (in the API Console). And I am able to get a response.

                                                                                  https://accounts.zoho.com/oauth/v3/device/code?client_id=xxxx&scope=ZohoProjects.tasklists.READ&grant_type=device_request
                                                                                  

                                                                                  I wrote this in VBA only for trouble shooting this question.

                                                                                      Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
                                                                                      Url = "https://accounts.zoho.com/oauth/v3/device/code?" & _
                                                                                          "client_id=xxx&" & _
                                                                                          "scope=ZohoProjects.tasklists.READ&" & _
                                                                                          "grant_type=device_request"
                                                                                      objHTTP.Open "POST", Url, False
                                                                                      objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
                                                                                      objHTTP.Send ("")
                                                                                  
                                                                                      replyTXT = objHTTP.responseText
                                                                                      Debug.Print (replyTXT)
                                                                                  

                                                                                  I believe this link has some helpful information. https://www.zoho.com/accounts/protocol/oauth/devices/initiation-request.html

                                                                                  Source https://stackoverflow.com/questions/71595390

                                                                                  QUESTION

                                                                                  Git pull from two different branches in two different repositories into one local branch
                                                                                  Asked 2022-Mar-04 at 00:19

                                                                                  I cloned a Git repo locally--call it A. This repo A has a branch named aaa. I created a new local branch--bbb. I then created a new GitHub repo (empty)--call it B--and pushed bbb to B. Next, I changed the origin of my local repository to point to B. I also then added a remote named "upstream" to my local repository that points to back to the original source, A. I set the "push" url of this upstream remote to be something bogus ("no-pushing") since I never want to accidentally push from my local repo back to A. I only want to pull from A into my local repo.

                                                                                  During a transition period, some developers will be committing changes to A/aaa. Others are committing changes to B/bbb.

                                                                                  I want to be able to pull changes from A/aaa into my local bbb branch and then push those to B/bbb so that the code on B will have all of the changes from the team committing to A as well as all of the change from the team committing to B. I also want to pull changes from B/bbb into my local bbb branch. Essentially, I want to use my local repo as a bridge between the two temporarily until we stop using A at some future point.

                                                                                  What git commands can I run to accomplish this? (and what are each of the commands doing so I am not just blinding copying commands)

                                                                                  So far nothing I have tried has worked, and I think I must be missing some key element in my understanding.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-23 at 09:06

                                                                                  I want to be able to pull changes from A/aaa into my local bbb branch and then push those to B/bbb so that the code on B will have all of the changes from the team committing to A as well as all of the change from the team committing to B

                                                                                  You can make sure:

                                                                                  cd /path/to/local
                                                                                  git switch bbb
                                                                                  git branch -u A/aaa bbb
                                                                                  git push -u B bbb
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71229444

                                                                                  QUESTION

                                                                                  C# Regex whitespace between capturing groups
                                                                                  Asked 2022-Feb-20 at 12:44

                                                                                  So basically, my input string is some kind of text containing keywords that I want to match, provided that:

                                                                                  1. each keyword may have whitespace/non-word chars pre/appended, or none (|\s\W)
                                                                                  2. there must be exactly one non-word/whtiespace char seperating multiple keywords, or keyword is at begining/end of line
                                                                                  3. Keyword simply ocurring as a substring does not count, e.g. bar does not match foobarbaz

                                                                                  E.g.:

                                                                                  input:    "#foo barbazboo tree car"
                                                                                  keywords: {"foo", "bar", "baz", "boo", "tree", "car"}
                                                                                  

                                                                                  I am dynamically generating a Regex in C# using a enumerable of keywords and a string-builder

                                                                                  StringBuilder sb = new();
                                                                                  foreach (var kwd in keywords)
                                                                                  {
                                                                                     sb.Append($"((|[\\s\\W]){kwd}([\\s\\W]|))|");
                                                                                  }
                                                                                  sb.Remove(sb.Length - 1, 1); // last '|'
                                                                                  _regex = new Regex(sb.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                                                                                  

                                                                                  Testing this pattern on regexr.com, given input matches all keywords. However, I do not want {bar, baz, boo} included, since there is no whitespace between each keyword. Ideally, I'd want my regex to only match {foo, tree, car}.

                                                                                  Modifying my pattern like (( |[\s\W])kwd([\s\W]| )) causes {bar, baz, boo} not to be included, but produces bogus on {tree, car}, since for that case there must be at least two spaces between keywords.

                                                                                  How do I specify "there may be only one whitespace seperating two keywords", or, to put it differently, "half a whitespace is ok", preserving the ability to create the regex dynamically?

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-20 at 12:44

                                                                                  In your case, you need to build the

                                                                                  var pattern = $@"\b(?:{string.Join("|", keywords.OrderByDescending(x => x.Length).Select(Regex.Escape))})\b";
                                                                                  _regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                                                                                  

                                                                                  Here, you are getting the longer keywords before shorter ones, so, if you have foo, bar and foo bar, the pattern will look like \b(?:foo\ bar|foo|bar)\b and will match foo bar, and not foo and bar once there is such a match.

                                                                                  In case your keywords can look like keywords: {"$foo", "^bar^", "[baz]", "(boo)", "tree+", "+car"}, i.e. they can have special chars at the start/end of the keyword, you can use

                                                                                  _regex = new Regex($@"(?!\B\w)(?:{string.Join("|", keywords.Select(Regex.Escape))})(?

                                                                                  The $@"(?!\B\w)(?:{string.Join("|", keywords.OrderByDescending(x => x.Length).Select(Regex.Escape))})(? is an interpolated verbatim string literal that contains

                                                                                  • (?!\B\w) - left-hand adaptive dynamic word boundary
                                                                                  • (?: - start of a non-capturing group:
                                                                                    • {string.Join("|", keywords.OrderByDescending(x => x.Length).Select(Regex.Escape))} - sorts the keywords by lenght in descending order, escapes them and joins with |
                                                                                  • ) - end of the group
                                                                                  • (? - right-hand adaptive dynamic word boundary.

                                                                                  Source https://stackoverflow.com/questions/71194117

                                                                                  QUESTION

                                                                                  Wrong result of multiplication: Undefined behavior or compiler bug?
                                                                                  Asked 2022-Feb-18 at 23:52
                                                                                  Background

                                                                                  While debugging a problem in a numerical library, I was able to pinpoint the first place where the numbers started to become incorrect. However, the C++ code itself seemed correct. So I looked at the assembly produced by Visual Studio's C++ compiler and started suspecting a compiler bug.

                                                                                  Code

                                                                                  I was able to reproduce the behavior in a strongly simplified, isolated version of the code:

                                                                                  sourceB.cpp:

                                                                                  double alwaysOneB(double a[3]) {
                                                                                      return 1.0;
                                                                                  }
                                                                                  

                                                                                  main.cpp:

                                                                                  #include 
                                                                                  
                                                                                  __declspec(noinline)
                                                                                  bool alwaysTrue() {
                                                                                      return true;
                                                                                  }
                                                                                  
                                                                                  __declspec(noinline)
                                                                                  double alwaysOneA(const double a[3]) {
                                                                                      return 1.0;
                                                                                  }
                                                                                  
                                                                                  double alwaysOneB(double a[3]); // implemented in sourceB.cpp
                                                                                  
                                                                                  int main() {
                                                                                      double* result = new double[2];
                                                                                  
                                                                                      if (alwaysTrue()) {
                                                                                          double v[3];
                                                                                          v[0] = 0.0;
                                                                                          v[1] = 0.0;
                                                                                          v[2] = 0.0;
                                                                                  
                                                                                          alwaysOneB(v);
                                                                                  
                                                                                          double d = alwaysOneA(v); // d = 1
                                                                                  
                                                                                          std::cout << "d = " << d << std::endl; // output: "d = 1" (as expected)
                                                                                  
                                                                                          result[0] = d * v[2];
                                                                                          result[1] = d * d; // should be: 1 * 1 => 1 
                                                                                      }
                                                                                      if (alwaysTrue()) {
                                                                                          std::cout << "result[1] = " << result[1] << std::endl; // output: "result[1] = 2.23943e-47" (expected: 1)
                                                                                      }
                                                                                  
                                                                                      delete[] result;
                                                                                      return 0;
                                                                                  }
                                                                                  

                                                                                  The code contains some bogus calls to other functions that are (unfortunately) necessary to reproduce the problem. However, the expected behavior should still be pretty clear. A value of 1.0 is assigned to the variable d, which is then multiplied by itself. That result should again be 1.0, which is written to an array and printed to the console. So the desired output is:

                                                                                  d = 1
                                                                                  result[1] = 1
                                                                                  

                                                                                  However, the obtained output is:

                                                                                  d = 1
                                                                                  result[1] = 3.77013e+214
                                                                                  
                                                                                  Test Environment

                                                                                  The code was tested with the C++ compiler that comes with Visual Studio Community 2019 (latest update, VS 16.11.9, VC++ 00435-60000-00000-AA327). The problem only occurs with optimizations activated (/O2). Compiling with /Od produces a binary that prints the correct output.

                                                                                  In the reduced example (not for the original problem when compiling the full library) I also had to deactivate "Full Program Optimization", otherwise the compiler gets rid of my bogus function calls.

                                                                                  This reduced example only reproduces the problem when compiled for x86 (other examples reproduce the problem for x64).

                                                                                  The full compilation command line is as follows: /permissive- /ifcOutput "Release\" /GS /analyze- /W3 /Gy /Zc:wchar_t /Zi /Gm- /O2 /sdl /Fd"Release\vc142.pdb" /Zc:inline /fp:precise /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /FC /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\DecimateBug2.pch" /diagnostics:column

                                                                                  Full Visual Studio solution to download: https://drive.google.com/file/d/1EyoX0uXEkvfJ_Fh649k9XjJQPdDUMik7/view?usp=sharing

                                                                                  Both the GNU compiler and Clang produce binaries that print the desired result.

                                                                                  Question

                                                                                  Is there any undefined behavior in this code that I am unable to see and that justifies an incorrect result? Or should I report this as a compiler bug?

                                                                                  Assembly produced by the compiler

                                                                                  For the two multiplication lines

                                                                                          result[0] = d * v[2];
                                                                                          result[1] = d * d;
                                                                                  

                                                                                  the compiler produces the following assembly code:

                                                                                  00CF1432  movsd       xmm1,mmword ptr [esp+18h]   // Load d into first part of xmm1
                                                                                  00CF1438  unpcklpd    xmm1,xmm1                   // Load d into second part of xmm1
                                                                                  00CF143C  movups      xmm0,xmmword ptr [esp+30h]  // Load second operands into xmm0
                                                                                  00CF1441  mulpd       xmm0,xmm1                   // 2 multiplications at one
                                                                                  00CF1445  movups      xmmword ptr [esi],xmm0      // store result
                                                                                  

                                                                                  Apparently it tries to perform the two multiplications at once using mulpd. In the first two lines it successfully loads the d operand into both parts of the xmm1 register (as first operands). But when it tries to load both second operands (v[2] and d), it simply loads 128 bits from the v[2] address (esp+30h). That's fine for the second operand of the first multiplication (v[2]), but not for the second multiplication (with d). Apparently the code supposes that d is located immediately after v in memory. However, it isn't. The variable d is never actually stored in memory, it seems to exist only in registers.

                                                                                  This makes me strongly suspect a compiler bug. However, I wanted to confirm that I am not missing any undefined behavior that justifies the incorrect assembly.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-18 at 23:52

                                                                                  Even though nobody posted an answer, from the comment section I could conclude that:

                                                                                  • Nobody found any undefined behavior in the bug repro code.
                                                                                  • At least some of you were able to reproduce the undesired behavior.

                                                                                  So I filed a bug report against Visual Studio 2019.

                                                                                  The Microsoft team confirmed the problem.

                                                                                  However, unfortunately it seems like Visual Studio 2019 will not receive a bug fix because Visual Studio 2022 seemingly does not have the bug. Apparently, the most recent version not having that particular bug is good enough for Microsoft's quality standards.

                                                                                  I find this disappointing because I think that the correctness of a compiler is essential and Visual Studio 2022 has just been released with new features and therefore probably contains new bugs. So there is no real "stable version" (one is cutting edge, the other one doesn't get bug fixes). But I guess we have to live with that or choose a different, more stable compiler.

                                                                                  Source https://stackoverflow.com/questions/70823697

                                                                                  QUESTION

                                                                                  Generate Random Age Height Weight using Bogus
                                                                                  Asked 2022-Feb-04 at 12:22

                                                                                  using Bogus we can generate fake and random data easily: https://github.com/bchavez/Bogus Now I need to generate some Person's. They have age, weight, height, so here is my code:

                                                                                  internal class Person
                                                                                  {
                                                                                      public int Age { get; set; }
                                                                                      public int Height { get; set; }
                                                                                      public int Weight { get; set; }
                                                                                  
                                                                                      public static Faker FakeData { get; } =
                                                                                          new Faker()
                                                                                              .RuleFor(p => p.Age, f => f.Random.Number(8, 90))
                                                                                              .RuleFor(p => p.Height, f => f.Random.Number(70, 200))
                                                                                              .RuleFor(p => p.Weight, f => f.Random.Number(15, 200));
                                                                                  }
                                                                                  

                                                                                  It will generate fake and random data very well. But there is a problem. I need to make it conditional. For example it will generate a person with age 9 and the height of 180 !!! Or a Person with the height of 70 and the weight of 190. I need to avoid such generationgs.

                                                                                  Any fix way?

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-04 at 12:22

                                                                                  To make the limits of the height dependent on the age and the limits of the weight dependent on the height (so, another function for that), you need to refer to the current Person instance - see the (f, x) => { return ...} parts below.

                                                                                  After reading Generating Test Data with Bogus, I came up with this:

                                                                                  using Bogus;
                                                                                  
                                                                                  namespace SO70976495
                                                                                  {
                                                                                      public class Person
                                                                                      {
                                                                                          public int Age { get; set; }
                                                                                          public int Height { get; set; }
                                                                                          public int Weight { get; set; }
                                                                                  
                                                                                          //TODO: Put the rand declaration somewhere more sensible.
                                                                                          private static Random rand = new Random();
                                                                                  
                                                                                          public static Faker FakeData
                                                                                          {
                                                                                              get
                                                                                              {
                                                                                                  return new Faker()
                                                                                                        .RuleFor(p => p.Age, f => f.Random.Number(8, 90))
                                                                                                        .RuleFor(p => p.Height, (f, x) =>
                                                                                                        {
                                                                                                            return RandHeightForAge(x.Age);
                                                                                                        })
                                                                                                        .RuleFor(p => p.Weight, (f, x) =>
                                                                                                        {
                                                                                                            return RandWeightForHeight(x.Height);
                                                                                                        });
                                                                                              }
                                                                                          }
                                                                                  
                                                                                          private static int RandHeightForAge(int age)
                                                                                          {
                                                                                              //TODO: Make a realistic distribution
                                                                                              return rand.Next(70, (int)(70 + age / 90.0 * 130));
                                                                                          }
                                                                                  
                                                                                          private static int RandWeightForHeight(int height)
                                                                                          {
                                                                                              //TODO: Make a realistic distribution
                                                                                              return 10 * rand.Next((int)Math.Sqrt(height - 15), (int)Math.Sqrt(height + 20));
                                                                                          }
                                                                                  
                                                                                          public override string ToString()
                                                                                          {
                                                                                              return $"Person: {Age} yrs, {Height} cm, {Weight} kg";
                                                                                          }
                                                                                  
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Anything silly in the above code is my fault.

                                                                                  Source https://stackoverflow.com/questions/70976495

                                                                                  QUESTION

                                                                                  Deallocating arrays defined from c_f_pointer
                                                                                  Asked 2022-Feb-03 at 15:42

                                                                                  The following code compiles in both GNU gfortran and Intel ifort. But only the gfortran compiled version will run successfully.

                                                                                      program fort_tst
                                                                                          use iso_c_binding
                                                                                  
                                                                                          INTEGER, POINTER :: a(:) 
                                                                                          TYPE(C_PTR) :: ptr 
                                                                                  
                                                                                          INTEGER, POINTER :: b(:) 
                                                                                  
                                                                                          ALLOCATE(a(5)) 
                                                                                  
                                                                                          ptr = c_loc(a) 
                                                                                  
                                                                                          CALL c_f_pointer(ptr,b,[5]) 
                                                                                  
                                                                                          DEALLOCATE(b) 
                                                                                      end program fort_tst
                                                                                  

                                                                                  The error in the Intel compiled code is :

                                                                                  forrtl: severe (173): A pointer passed to DEALLOCATE points to an object that cannot be deallocated
                                                                                  Image              PC                Routine            Line        Source             
                                                                                  fort_tst           000000000040C5A1  Unknown               Unknown  Unknown
                                                                                  fort_tst           0000000000403A17  Unknown               Unknown  Unknown
                                                                                  fort_tst           0000000000403812  Unknown               Unknown  Unknown
                                                                                  libc-2.17.so       00002AAAAB20F555  __libc_start_main     Unknown  Unknown
                                                                                  fort_tst           0000000000403729  Unknown               Unknown  Unknown
                                                                                  

                                                                                  The gfortran code runs to completion. A quick valgrind check does not find any leaks.

                                                                                  Can someone confirm whether the code above is valid/legal code?

                                                                                  I am running

                                                                                      ifort (IFORT) 2021.2.0 20210228
                                                                                  

                                                                                  and

                                                                                      GNU Fortran (GCC) 9.2.0
                                                                                      Copyright (C) 2019 Free Software Foundation, Inc.
                                                                                  

                                                                                  UPDATE :

                                                                                  What is interesting is that gfortran does the right thing, (i.e. deallocates only allocated memory), even when the user tries to confound it with improper index remapping, or a bogus shape argument. So the internal array descriptor is being properly copied over with gfortran's c_f_pointer.

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-31 at 17:50

                                                                                  The error is issued, because the compiler claims that the pointer that is being allocated was not allocated by an allocate statement.

                                                                                  The rules are (F2018):

                                                                                  9.7.3.3 Deallocation of pointer targets

                                                                                  1 If a pointer appears in a DEALLOCATE statement, its association status shall be defined. Deallocating a pointer that is disassociated or whose target was not created by an ALLOCATE statement causes an error condition in the DEALLOCATE statement. If a pointer is associated with an allocatable entity, the pointer shall not be deallocated. A pointer shall not be deallocated if its target or any subobject thereof is argument associated with a dummy argument or construct associated with an associate name.

                                                                                  Your pointer b was associated using the c_f_pointer subroutine. The error condition mentioned is the

                                                                                  forrtl: severe (173): A pointer passed to DEALLOCATE points to an object that cannot be deallocated
                                                                                  

                                                                                  Now we have to be careful, the exact wording is

                                                                                  or whose target was not created by an ALLOCATE statement

                                                                                  The target arguably was created by an allocatable statement. And then went through this indirect chain of association. I am not such an expert language lawyer to be sure whether this makes the target to be applicable or not, when it passed through c_loc() and c_f_pointer().

                                                                                  Gfortran does not issue this error condition and then it works fine because at the end of the day, under the hood, what matters is that the address passed to the system free() function was allocated by the matching system malloc() function.

                                                                                  I think we can conclude that one of the compilers is wrong here, because the mention of the error condition is clear in the standard and either it should be issued or it should not. A third option, that gfortran just leaves it too work, should not happen. Either it is allowed, or an error condition shall be issued.

                                                                                  Re UPDATE: What gfortran does is really sending the address to free(). As long as the pointer is contiguous and starts at the first element, it will work in practice. The size is not necessary and is not passed to free(). The system allocator malloc()/free() stores the size of each allocated system in its own database.

                                                                                  There are even worse abuse cases that can happen and will work just by chance due to this, even if completely illegal in Fortran.

                                                                                  See this:

                                                                                  use iso_c_binding
                                                                                  
                                                                                  character, allocatable, target :: a
                                                                                  type(c_ptr) :: p
                                                                                  real, pointer :: b(:)
                                                                                  
                                                                                  allocate(a)
                                                                                  
                                                                                  p = c_loc(a)
                                                                                  
                                                                                  call c_f_pointer(p, b, [1000])
                                                                                  
                                                                                  deallocate(b)
                                                                                  
                                                                                  end
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70922893

                                                                                  QUESTION

                                                                                  Ternary operator not using the useState correctly
                                                                                  Asked 2022-Jan-08 at 01:55

                                                                                  I'm trying to update the header component based on the state and the response I get from my API server but for some reason, my updated state is having some type of errors that I cannot understand.

                                                                                  When my API server responds back if the username and password are correct, I get the console.log(response.data) on my browser with the properties(username, password, token). I can login and the token gets saved in the local session... GREAT!! However, when I try to login with a blank username/password or any incorrect data, my state evaluates to true and therefore the HeaderLoggedIn component activates (not following the ternary operator ruleset) / my server responds with console.log('Incorrect username / password.'); but still the HeaderLoggedIn activates.

                                                                                  My useState(), initially is set to a Boolean(sessionStorage.getItem('movieappToken'). so if there's no token saved, its false and therefore it should be useState(false) - render the HeaderLoggedOut component.

                                                                                  What am I doing wrong? Thank you

                                                                                  main Header.js component:

                                                                                  import React, { useState, useEffect } from 'react';
                                                                                  import { Link } from 'react-router-dom';
                                                                                  import HeaderLoggedOut from './HeaderLoggedOut';
                                                                                  import HeaderLoggedIn from './HeaderLoggedIn';
                                                                                  
                                                                                  function Header() {
                                                                                      const [loggedIn, setLoggedIn] = useState(
                                                                                          Boolean(sessionStorage.getItem('movieappToken'))
                                                                                      );
                                                                                  
                                                                                      return (
                                                                                          
                                                                                              
                                                                                                  
                                                                                                      
                                                                                                          ComplexApp
                                                                                                      
                                                                                                  
                                                                                  
                                                                                  
                                                                                                     **//here's the problem**
                                                                                                  {loggedIn ? (
                                                                                                      
                                                                                                  ) : (
                                                                                                      
                                                                                                  )}
                                                                                              
                                                                                          
                                                                                      );
                                                                                  }
                                                                                  
                                                                                  export default Header;
                                                                                  

                                                                                  HeaderLoggedIn.js Component:

                                                                                  import React, { useEffect } from 'react';
                                                                                  
                                                                                  function HeaderLoggedIn(props) {
                                                                                      function handleLogout() {
                                                                                          props.setLoggedIn(false);
                                                                                          sessionStorage.removeItem('movieappToken');
                                                                                          sessionStorage.removeItem('movieappUsername');
                                                                                      }
                                                                                  
                                                                                      return (
                                                                                          
                                                                                              
                                                                                                  
                                                                                              
                                                                                              
                                                                                                  
                                                                                                   
                                                                                              
                                                                                              
                                                                                                  
                                                                                              
                                                                                              
                                                                                                  Create Post
                                                                                              
                                                                                              
                                                                                                  Sign Out
                                                                                              
                                                                                          
                                                                                      );
                                                                                  }
                                                                                  
                                                                                  export default HeaderLoggedIn;
                                                                                  

                                                                                  and HeaderLoggedOut.js Component - the one which gets data from the API server

                                                                                  import React, { useEffect, useState } from 'react';
                                                                                  import Axios from 'axios';
                                                                                  
                                                                                  function HeaderLoggedOut(props) {
                                                                                      const [username, setUsername] = useState();
                                                                                      const [password, setPassword] = useState();
                                                                                  
                                                                                      async function handleSubmit(e) {
                                                                                          e.preventDefault();
                                                                                          try {
                                                                                              const response = await Axios.post('http://localhost:4000/login', {
                                                                                                  username,
                                                                                                  password,
                                                                                              });
                                                                                              if (response.data) {
                                                                                                  console.log(response.data);
                                                                                                  sessionStorage.setItem('movieappToken', response.data.token);
                                                                                                  sessionStorage.setItem('movieappUsername', response.data.username);
                                                                                                  props.setLoggedIn(true);
                                                                                              } else {
                                                                                               
                                                                                                  console.log('Incorrect username / password.');
                                                                                              }
                                                                                          } catch (e) {
                                                                                              console.log('There was a problem.');
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      return (
                                                                                          
                                                                                              
                                                                                                  
                                                                                                       setUsername(e.target.value)}
                                                                                                          name="username"
                                                                                                          className="form-control form-control-sm input-dark"
                                                                                                          type="text"
                                                                                                          placeholder="Username"
                                                                                                          autoComplete="off"
                                                                                                      />
                                                                                                  
                                                                                                  
                                                                                                       setPassword(e.target.value)}
                                                                                                          name="password"
                                                                                                          className="form-control form-control-sm input-dark"
                                                                                                          type="password"
                                                                                                          placeholder="Password"
                                                                                                      />
                                                                                                  
                                                                                                  
                                                                                                      Sign In
                                                                                                  
                                                                                              
                                                                                          
                                                                                      );
                                                                                  }
                                                                                  
                                                                                  export default HeaderLoggedOut;
                                                                                  

                                                                                  API Server userController.js

                                                                                  const User = require('../models/User');
                                                                                  
                                                                                  //
                                                                                  exports.login = function (req, res) {
                                                                                      let user = new User(req.body);
                                                                                      user
                                                                                          .login()
                                                                                          .then(function (result) {
                                                                                              
                                                                                              res.send(result);
                                                                                          })
                                                                                          .catch(function (error) {
                                                                                              res.send(error);
                                                                                          });
                                                                                  };
                                                                                  

                                                                                  API Server User.js

                                                                                  const usersCollection = require('../db').collection('users');
                                                                                  const bcrypt = require('bcryptjs');
                                                                                  const validator = require('validator');
                                                                                  
                                                                                  let User = function (data) {
                                                                                      this.data = data;
                                                                                      this.errors = [];
                                                                                  };
                                                                                  
                                                                                  User.prototype.cleanUp = function () {
                                                                                      if (typeof this.data.username != 'string') {
                                                                                          this.data.username = '';
                                                                                      }
                                                                                      if (typeof this.data.email != 'string') {
                                                                                          this.data.email = '';
                                                                                      }
                                                                                      if (typeof this.data.password != 'string') {
                                                                                          this.data.password = '';
                                                                                      }
                                                                                  
                                                                                      // get rid of any bogus properties
                                                                                      this.data = {
                                                                                          username: this.data.username.trim().toLowerCase(),
                                                                                          email: this.data.email.trim().toLowerCase(),
                                                                                          password: this.data.password,
                                                                                          token: `58158188ji4j1ij42jio4j1ji41oji14i${this.data.username}`,
                                                                                      };
                                                                                  };
                                                                                  
                                                                                  User.prototype.validate = function () {
                                                                                      if (this.data.username == '') {
                                                                                          this.errors.push('You must provide a username');
                                                                                      }
                                                                                      if (
                                                                                          this.data.username != '' &&
                                                                                          !validator.isAlphanumeric(this.data.username)
                                                                                      ) {
                                                                                          this.errors.push('Username can only contain letters and numbers');
                                                                                      }
                                                                                      if (!validator.isEmail(this.data.email)) {
                                                                                          this.errors.push('You must provide a valid email address');
                                                                                      }
                                                                                      if (this.data.password == '') {
                                                                                          this.errors.push('You must provide a password');
                                                                                      }
                                                                                      if (this.data.password.length > 0 && this.data.password.length < 7) {
                                                                                          this.errors.push('Password must be at atleast 7 characters');
                                                                                      }
                                                                                      if (this.data.password.length > 25) {
                                                                                          this.errors.push('Password cannot exceed 25 characters');
                                                                                      }
                                                                                      if (this.data.username.length > 0 && this.data.username.length < 3) {
                                                                                          this.errors.push('Username must be at atleast 3 characters');
                                                                                      }
                                                                                      if (this.data.username.length > 15) {
                                                                                          this.errors.push('Username cannot exceed 15 characters');
                                                                                      }
                                                                                  };
                                                                                  
                                                                                  User.prototype.register = function () {
                                                                                      // Step #1: Validate user data
                                                                                      this.cleanUp();
                                                                                      this.validate();
                                                                                  
                                                                                      // Step #2: Only if there are no validation errors
                                                                                      // then save the user data into a database
                                                                                      if (!this.errors.length) {
                                                                                          // hash user password
                                                                                          let salt = bcrypt.genSaltSync(10);
                                                                                          this.data.password = bcrypt.hashSync(this.data.password, salt);
                                                                                          usersCollection.insertOne(this.data);
                                                                                      }
                                                                                  };
                                                                                  
                                                                                  User.prototype.login = function () {
                                                                                      return new Promise((resolve, reject) => {
                                                                                          this.cleanUp();
                                                                                          usersCollection
                                                                                              .findOne({ username: this.data.username })
                                                                                              .then((attemptedUser) => {
                                                                                                  if (
                                                                                                      attemptedUser &&
                                                                                                      bcrypt.compareSync(this.data.password, attemptedUser.password)
                                                                                                  ) {
                                                                                                      resolve(this.data);
                                                                                                  } else {
                                                                                                      reject('invalid username/password');
                                                                                                  }
                                                                                              })
                                                                                              .catch(function () {
                                                                                                  reject('Please try again later!');
                                                                                              });
                                                                                      });
                                                                                  };
                                                                                  
                                                                                  module.exports = User;
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-07 at 23:16

                                                                                  You are not setting loggedIn when getting the "incorrect username/password" response so loggedIn remains whatever it was initially. You can set it to false

                                                                                  if (response.data) {
                                                                                    console.log(response.data);
                                                                                    sessionStorage.setItem('movieappToken', response.data.token);
                                                                                    sessionStorage.setItem('movieappUsername', response.data.username);
                                                                                    props.setLoggedIn(true);
                                                                                  } else {
                                                                                    props.setLoggedIn(false);
                                                                                    console.log('Incorrect username / password.');
                                                                                  } catch (e) {
                                                                                    props.setLoggedIn(false);
                                                                                    console.log('There was a problem.');
                                                                                  }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70628150

                                                                                  QUESTION

                                                                                  Why is clangd not seeing my custom library location
                                                                                  Asked 2021-Nov-28 at 01:10
                                                                                  Problem Statement:

                                                                                  I have a library installed in a custom location, and compilation and linkage works properly, but clangd is reporting various errors related to the custom lib.

                                                                                  My Makefile has the following flags:

                                                                                  CFLAGS += -I/usr/local/share/mylib                             
                                                                                  LDFLAGS += -lmylib -L/usr/local/lib/
                                                                                  ...
                                                                                  
                                                                                  

                                                                                  However, clangd doesn't know how to find the header file and therefore my editor is showing errors like the following where it is unhelpful:

                                                                                  #include     'mylibheader.h' file not found
                                                                                  
                                                                                  mylib_type1_t foo                     unknown type name 'mylib_type1_t'
                                                                                  
                                                                                  ...
                                                                                  
                                                                                  

                                                                                  searching the internet for the errors and keywords clangd, clangd config, clangd .clang-format failed to produce anything useful on SO or elsewhere (hence this question).

                                                                                  The question is:

                                                                                  How do I tell clangd where my non-standard headers are so that it won't show bogus "file not found" warnings?

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-28 at 01:10
                                                                                  tl;dr:

                                                                                  add compile flags to compile_flags.txt (small project) or for a more complicated project generate compile_commands.json. See instructions here.

                                                                                  Example: my compile_flags.txt contains:

                                                                                  -I/usr/local/share/mylib
                                                                                  -lmylib
                                                                                  -L/usr/local/lib/
                                                                                  
                                                                                  How Did I Troubleshoot?

                                                                                  man 1 clangd gives a useful hint for inspecting output

                                                                                         --check[=]                 - Parse one file in isolation instead of acting as a language server. Useful to investigate/reproduce crashes or configu‐
                                                                                                ration problems. With --check=, attempts to parse a particular file.
                                                                                  

                                                                                  Some output of clangd --check=src/main.c:

                                                                                  E[13:12:40.787] [pp_file_not_found] Line 10: 'mylibheader.h' file not found
                                                                                  
                                                                                  E[13:12:40.820] [unknown_typename] Line 187: unknown type name 'mylib_type1_t'
                                                                                  E[13:12:40.820] [unknown_typename] Line 202: unknown type name 'mylib_type1_t'
                                                                                  E[13:12:40.820] [undeclared_var_use] Line 820: use of undeclared identifier 'mylib_type2_t'
                                                                                  ...
                                                                                  
                                                                                  

                                                                                  Adding pp_file_not_found to my search terms led me to this very helpful issue*, which has a comment that says:

                                                                                  Looks like you don't have a compile_flags.txt or compilation_database.json set up. That file tells clangd where to find include files, you can check project setup guide for details.

                                                                                  • Note that I am not using coc-neovim, but rather using Neovim's builtin lsp server, so this question doesn't directly relate but happens to have my solution.

                                                                                  Source https://stackoverflow.com/questions/70138829

                                                                                  QUESTION

                                                                                  plotshape - text colour displayed incorrectly with user defined input variables
                                                                                  Asked 2021-Nov-20 at 06:01

                                                                                  There seems to be a bug in the compiler of Pine Script, in this below example the use of a variable called transp sets a user definable input value for the transparency of a given colour.

                                                                                  Yet when using plotshape and bgcolor it has inconsistent results. bgcolour works as expected, plotshape however behaves very oddly. It sets the colour correctly for the plotted shape using style=shape.cross, but it fails to understand the colour instruction for the text = ‘hi’ or text = ‘lo’. In this case it uses the default colour of blue.

                                                                                  If you change transp to a set integer like transp = 80, it then works correctly and displays both the shape and text in the given colour. This is incredibly bogus, if it merely didn’t accept variables assigned to user inputs for transparency then it would affect both shape and text. You could also just enter the color.new expression straight into plotshape, and this works in the same way, use a variable for transparency that has a user input associated to it and it will not work correctly, use a hardcoded integer assignment and it works fine.

                                                                                  //@version=5
                                                                                  
                                                                                  indicator(title='RSI and test colour variable', shorttitle='Colour test', overlay=false)
                                                                                  
                                                                                  transp = input.int(60, minval=0, maxval=100, title='Transparency:')
                                                                                  
                                                                                  blue  = color.new(color.blue, 0)
                                                                                  green = color.new(color.green, transp)
                                                                                  red   = color.new(color.red, transp)
                                                                                  white = color.new(color.white, 0)
                                                                                  
                                                                                  lower = 30
                                                                                  higher = 60
                                                                                  Len = input(title='RSI Length:', defval=10)
                                                                                  Src = input(title='RSI Source:', defval=close)
                                                                                  rsi = ta.rsi(Src, Len)
                                                                                  plot(rsi, color=white)
                                                                                  
                                                                                  plot(lower, color=blue)
                                                                                  plot(higher, color=blue)
                                                                                  
                                                                                  plotshape (rsi > higher, location=location.top, color=green, style=shape.cross, text='Hi', size=size.tiny)
                                                                                  bgcolor (rsi > higher  ? green : na)
                                                                                   
                                                                                  plotshape (rsi < lower, location=location.top, color=red, style=shape.cross, text='Lo', size=size.tiny)
                                                                                  bgcolor (rsi < lower  ? red : na)
                                                                                  
                                                                                  

                                                                                  I have looked over this and tried every conceivable permutation to the code to get around this, and it always responds in the same incoherent manner. It took sometime to actually realise what the issue was, this is clearly a bug, not overly fatal, but it’s not an ideal presentation, and I can’t move on with this bug looking at me, still bugging me. ;o\

                                                                                  Any work-arounds?

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-20 at 06:01

                                                                                  Although it might not be the reason, it does not necessarily need to be a user defined input. The value needs to be known at compile time.

                                                                                  If you try transp=close > 2 ? 40 : 80, you will get the same behavior.

                                                                                  Some more info.

                                                                                  As a workaround, use the textcolor parameter.

                                                                                  plotshape (rsi > higher, location=location.top, color=green, textcolor=green, style=shape.cross, text='Hi', size=size.tiny)
                                                                                  plotshape (rsi < lower, location=location.top, color=red, textcolor=red, style=shape.cross, text='Lo', size=size.tiny)
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70040732

                                                                                  QUESTION

                                                                                  How to deal with SQL Aggregate Functions when Grouping deeply hiearched data
                                                                                  Asked 2021-Nov-16 at 19:56

                                                                                  Given the following scenario:

                                                                                  I have a Database with 5 tables:

                                                                                  1. currency (iso_number, iso_code),
                                                                                  2. product (id, name, current_price),
                                                                                  3. sale (id, time_of_sale, currency_items_sold_in),
                                                                                  4. sale_lines (id, sale_id, product_id, price_paid, quantity),
                                                                                  5. cash_transactions (id, sale_id, received_currency_id, converted_currency_id, received_amount, converted_amount)

                                                                                  The setup allows to store what kind of currency was originally given by the customer, and what currency it was exchanged to internally and the original amount and the exchanged(converted) amount.

                                                                                  I want to be able to find all sales that match certain criteria (time period, seller, store) etc. ((left out for simplicity)).

                                                                                  For all those sales i will join related data which is sale_lines and cash_transactions. Now the currency on sale_lines always matches the currency on the related sale. However for cash_transactions the received_amount/received_currency can differ from the currency on the sale. Allthough converted_currency/converted_amount is stored on the cash_transaction line it should follow the sale.

                                                                                  The problem arises when i try to perform SUM of certain fields, when you start joining One-To-Many relationships and then perform aggregate functions like SUM even though you specify the correct GROUP BY's behind the scene the SQL Server still SUMs the duplicated lines that would have been required to display the data had we not used a GROUP BY.

                                                                                  The problem is also described here: https://wikido.isoftdata.com/index.php/The_GROUPing_pitfall

                                                                                  Following the solution from the article above i should in my case LEFT JOIN the aggregate results of each sale onto the outer query.

                                                                                  But what can i do when the sale_lines currency match the sale, but cash_transactions currency can differ from the sale.?

                                                                                  I've tried creating the following SQL Fiddle which inserts some test data and highlights the problems: http://sqlfiddle.com/#!17/54a7b/15

                                                                                  In the fiddle i have created 2 Sales, where the items are sold in DKK(208) and 752(SEK). On the first sale there are 2 sale lines, and 2 cash transactions the first transaction is directly DKK => DKK, and the second transaction is SEK => DKK.

                                                                                  On the second sale there are also 2 sale lines, and 2 cash transactions the first transaction is NOK => DKK, and the second transaction is directly DKK => DKK.

                                                                                  In the last query of the fiddle it can be observed that the total_received_amount is bogus as it is a mix of DKK,SEK and NOK does not provide much value.

                                                                                  I want suggestions on how to fetch the data properly, i do not care if i have to perform additional "logic" on the server-side (PHP) in order to de-duplicate some of the data as long as the sums are correct.

                                                                                  Any suggestions are much appreciated.

                                                                                  DDL FROM FIDDLE

                                                                                  CREATE TABLE currency (
                                                                                    iso_number CHARACTER VARYING(3) PRIMARY KEY,
                                                                                    iso_code CHARACTER VARYING(3)
                                                                                  );
                                                                                  
                                                                                  INSERT INTO currency(iso_number, iso_code) VALUES ('208','DKK'), ('752','SEK'), ('572','NOK');
                                                                                  
                                                                                  CREATE TABLE product (
                                                                                    id SERIAL PRIMARY KEY,
                                                                                    name CHARACTER VARYING(12),
                                                                                    current_price INTEGER
                                                                                  );
                                                                                  
                                                                                  INSERT INTO product(id,name,current_price) VALUES (1,'icecream',200), (2,'sunglasses',300);
                                                                                  
                                                                                  CREATE TABLE sale (
                                                                                    id SERIAL PRIMARY KEY,
                                                                                    time_of_sale TIMESTAMP,
                                                                                    currency_items_sold_in CHARACTER VARYING(3)
                                                                                  );
                                                                                  
                                                                                  INSERT INTO sale(id, time_of_sale, currency_items_sold_in) 
                                                                                  VALUES 
                                                                                  (1, CURRENT_TIMESTAMP, '208'),
                                                                                  (2, CURRENT_TIMESTAMP, '752')
                                                                                  ;
                                                                                  
                                                                                  CREATE TABLE sale_lines (
                                                                                    id SERIAL PRIMARY KEY,
                                                                                    sale_id INTEGER,
                                                                                    product_id INTEGER,
                                                                                    price_paid INTEGER,
                                                                                    quantity FLOAT
                                                                                  );
                                                                                  
                                                                                  INSERT INTO sale_lines(id, sale_id, product_id, price_paid, quantity)
                                                                                  VALUES 
                                                                                  (1, 1, 1, 200, 1.0),
                                                                                  (2, 1, 2, 300, 1.0),
                                                                                  
                                                                                  (3, 2, 1, 100, 1.0),
                                                                                  (4, 2, 1, 100, 1.0)
                                                                                  ;
                                                                                          
                                                                                  
                                                                                  
                                                                                  CREATE TABLE cash_transactions (
                                                                                    id SERIAL PRIMARY KEY,
                                                                                    sale_id INTEGER,
                                                                                    received_currency_id CHARACTER VARYING(3),
                                                                                    converted_currency_id CHARACTER VARYING(3),
                                                                                    received_amount INTEGER,
                                                                                    converted_amount INTEGER
                                                                                  );
                                                                                  
                                                                                  
                                                                                  INSERT INTO cash_transactions(id, sale_id, received_currency_id, converted_currency_id, received_amount, converted_amount)
                                                                                  VALUES
                                                                                  (1, 1, '208', '208', 200, 200),
                                                                                  (2, 1, '752', '208', 400, 300),
                                                                                  
                                                                                  (3, 2, '572', '208', 150, 100),
                                                                                  (4, 2, '208', '208', 100, 100)
                                                                                  ;
                                                                                  

                                                                                  QUERIES FROM FIDDLE

                                                                                  --SELECT * FROM currency;
                                                                                  --SELECT * FROM product;
                                                                                  --SELECT * FROM sale;
                                                                                  --SELECT * FROM sale_lines;
                                                                                  --SELECT * FROM cash_transactions;
                                                                                  
                                                                                  
                                                                                  --- Showing the sales with duplicated lines to 
                                                                                  --- fit joined data for OneToMany SaleLines, and OneToMany cash transactions.
                                                                                  SELECT *
                                                                                  FROM sale s
                                                                                  LEFT JOIN sale_lines sl ON sl.sale_id = s.id
                                                                                  LEFT JOIN cash_transactions ct ON ct.sale_id = s.id;
                                                                                  
                                                                                  
                                                                                  
                                                                                  --- Grouping the data by important identifier "currency_items_sold_in".
                                                                                  --- The SUM of sl.price_paid is wrong as it SUMS the duplicated lines as well.
                                                                                  SELECT 
                                                                                    s.currency_items_sold_in, 
                                                                                    SUM(sl.price_paid) as "price_paid"
                                                                                  FROM sale s
                                                                                  LEFT JOIN sale_lines sl ON sl.sale_id = s.id
                                                                                  LEFT JOIN cash_transactions ct ON ct.sale_id = s.id
                                                                                  GROUP BY s.currency_items_sold_in;
                                                                                  
                                                                                  --- To solve this the SUM can be joined via the "Monkey-Poop" method.
                                                                                  --- Here the problem arises, the SUMS for cash_transaction.received_amount and cash_transaction.converted_amount cannot be relied upon
                                                                                  --- As those fields themselves rely on cash_transaction.received_currency_id and cash_transaction.converted_currency_id
                                                                                  SELECT 
                                                                                    s.currency_items_sold_in, 
                                                                                    SUM(sale_line_aggregates.price_paid) as "total_price_paid",
                                                                                    SUM(cash_transaction_aggregates.converted_amount) as "total_converted_amount",
                                                                                    SUM(cash_transaction_aggregates.received_amount) as "total_received_amount"
                                                                                  FROM sale s
                                                                                  LEFT JOIN (
                                                                                    SELECT 
                                                                                      sale_id,
                                                                                      SUM(price_paid) AS price_paid
                                                                                    FROM sale_lines
                                                                                    GROUP BY sale_id
                                                                                  ) AS sale_line_aggregates ON sale_line_aggregates.sale_id = s.id
                                                                                  
                                                                                  LEFT JOIN (
                                                                                    SELECT
                                                                                      sale_id,
                                                                                      SUM(converted_amount) as converted_amount,
                                                                                      SUM(received_amount) as received_amount
                                                                                    FROM cash_transactions
                                                                                    GROUP BY sale_id
                                                                                  ) AS cash_transaction_aggregates ON cash_transaction_aggregates.sale_id = s.id
                                                                                  GROUP BY s.currency_items_sold_in;
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-16 at 19:56

                                                                                  You could calculate for every amount grouped per currency in the subqueries. Then join them on the currency.

                                                                                  And with a CTE you can make sure each subquery is using the same sales.

                                                                                  WITH CTE_SALE AS (
                                                                                    SELECT
                                                                                     id as sale_id, 
                                                                                     currency_items_sold_in AS iso_number
                                                                                    FROM sale
                                                                                  )
                                                                                  SELECT curr.iso_code AS currency
                                                                                  , COALESCE(line.price_paid, 0)  as total_price_paid
                                                                                  , COALESCE(received.amount, 0)  as total_received_amount
                                                                                  , COALESCE(converted.amount, 0) as total_converted_amount
                                                                                  FROM currency AS curr
                                                                                  LEFT JOIN (
                                                                                    SELECT s.iso_number
                                                                                    , SUM(sl.price_paid) AS price_paid
                                                                                    FROM sale_lines sl
                                                                                    JOIN CTE_SALE s ON s.sale_id = sl.sale_id
                                                                                    GROUP BY s.iso_number
                                                                                  ) AS line 
                                                                                    ON line.iso_number = curr.iso_number
                                                                                  LEFT JOIN (
                                                                                    SELECT tr.received_currency_id as iso_number
                                                                                    , SUM(tr.received_amount) AS amount
                                                                                    FROM cash_transactions tr
                                                                                    JOIN CTE_SALE s ON s.sale_id = tr.sale_id
                                                                                    GROUP BY tr.received_currency_id
                                                                                  ) AS received
                                                                                    ON received.iso_number = curr.iso_number
                                                                                  LEFT JOIN (
                                                                                    SELECT tr.converted_currency_id as iso_number
                                                                                    , SUM(tr.converted_amount) AS amount
                                                                                    FROM cash_transactions AS tr
                                                                                    JOIN CTE_SALE s ON s.sale_id = tr.sale_id
                                                                                    GROUP BY tr.converted_currency_id
                                                                                  ) AS converted
                                                                                    ON converted.iso_number = curr.iso_number;
                                                                                  
                                                                                  currency | total_price_paid | total_received_amount | total_converted_amount
                                                                                  :------- | ---------------: | --------------------: | ---------------------:
                                                                                  DKK      |              500 |                   300 |                    700
                                                                                  SEK      |              200 |                   400 |                      0
                                                                                  NOK      |                0 |                   150 |                      0
                                                                                  

                                                                                  db<>fiddle here

                                                                                  Source https://stackoverflow.com/questions/69991331

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install Bogus

                                                                                  You can download it from GitHub.

                                                                                  Support

                                                                                  For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit

                                                                                  Share this Page

                                                                                  share link

                                                                                  Consider Popular Mock Libraries

                                                                                  faker.js

                                                                                  by Marak

                                                                                  Faker

                                                                                  by fzaninotto

                                                                                  Mock

                                                                                  by nuysoft

                                                                                  faker

                                                                                  by joke2k

                                                                                  nock

                                                                                  by nock

                                                                                  Try Top Libraries by bchavez

                                                                                  RethinkDb.Driver

                                                                                  by bchavezC#

                                                                                  BugTrap

                                                                                  by bchavezC++

                                                                                  Coinbase

                                                                                  by bchavezC#

                                                                                  Coinbase.Pro

                                                                                  by bchavezC#

                                                                                  Coinbase.Commerce

                                                                                  by bchavezC#

                                                                                  Compare Mock Libraries with Highest Support

                                                                                  faker

                                                                                  by joke2k

                                                                                  Faker

                                                                                  by fzaninotto

                                                                                  wiremock

                                                                                  by tomakehurst

                                                                                  faker

                                                                                  by faker-ruby

                                                                                  powermock

                                                                                  by powermock

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit