问:
multiplication of random numbers different from zero
I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

using namespace std;

int main()
{
    cout << "draws 10 numbers:" << endl;
    Sleep(1000);
    cout << endl;

    srand(time(0));
    int sum=0;
    int product=1;

    for(int i=0, value=0; i<10; i++, sum+=value, product*=value)
    {
        value = rand()%10+0;
        Sleep(1000);
        cout << value << endl;
    }

    Sleep(1000);
    cout << "the sum is " << sum <<endl;
    cout << "the product is " << product <<endl;
    return 0;
  }
```

答:
To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.

int sum = 0;
int value = 1;

for(int i = 0; i < 10; i++)
{
  int value = rand() % 10;
  sum += value;
  product *= value;
  std::cout << value << std::::endl;
}
```

<p>Next, we only want to do the multiplication <code>if</code> the <code>value</code> is not equal <code>0</code>.</p>

<pre class="lang-cpp prettyprint-override"><code>int sum = 0;
int value = 1;

for(int i = 0; i < 10; i++)
{
  int value = rand() % 10;
  sum += value;

  if(value != 0)
  {
    product *= value;
  }

  std::cout << value << std::::endl;
}
</code>```

So the whole program looks like this.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
  std::cout << "draws 10 numbers:" << std::endl;

  srand(time(0));
  int sum = 0;
  int product = 1;
  int multiplied = 0;

  for(int i = 0; i < 10; i++)
  {
    int value = rand() % 10;
    sum += value;

    if(value != 0)
    {
      product *= value;
      multiplied += 1;
    }

    std::cout << value << " ";
  }

  std::cout << std::endl;
  std::cout << "the sum is " << sum << std::endl;
  std::cout << "the product is " << product << std::endl;
  std::cout << "numbers multiplied is " << multiplied << std::endl;
  return EXIT_SUCCESS;
}
```

Body:
To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.

int sum = 0;
int value = 1;

for(int i = 0; i < 10; i++)
{
  int value = rand() % 10;
  sum += value;
  product *= value;
  std::cout << value << std::::endl;
}

Next, we only want to do the multiplication if the value is not equal 0.

int sum = 0;
int value = 1;

for(int i = 0; i < 10; i++)
{
  int value = rand() % 10;
  sum += value;

  if(value != 0)
  {
    product *= value;
  }

  std::cout << value << std::::endl;
}

So the whole program looks like this.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
  std::cout << "draws 10 numbers:" << std::endl;

  srand(time(0));
  int sum = 0;
  int product = 1;
  int multiplied = 0;

  for(int i = 0; i < 10; i++)
  {
    int value = rand() % 10;
    sum += value;

    if(value != 0)
    {
      product *= value;
      multiplied += 1;
    }

    std::cout << value << " ";
  }

  std::cout << std::endl;
  std::cout << "the sum is " << sum << std::endl;
  std::cout << "the product is " << product << std::endl;
  std::cout << "numbers multiplied is " << multiplied << std::endl;
  return EXIT_SUCCESS;
}


来源: stackexchange

问:
In numbers with range of values, how to move the decimal point left until a single digit integer remains in Python
I'd like to take a number like: 12345678 and turn it into 1.2345678, leaving only a single digit integer and whatever decimal.

Multiplying 12345678 by 0.0000001 works for the above example, but not if the number is 1234. The numbers change so a static multiplier will not work.

Is there a method available that would help? Bonus if it can be done within a pandas dataframe.

答:
You can use np.log10 and astype(int) to find the correct power:

```<code>df['number'] /= 10**(np.log10(df['number']).astype(int))
</code>```

Output:

```<code>     number
0  1.234568
1  1.234000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use np.log10 and astype(int) to find the correct power:

df['number'] /= 10**(np.log10(df['number']).astype(int))

Output:

     number
0  1.234568
1  1.234000


问:
Bash: Copy all files with same extension in root/current folder, except those whose filename contains certain string
I have built script for copying multiple folders and files matching file types in one cp command line only like below:

```<code>today=$(date +"%d-%m-%Y");
cp -r ./{dir1,dir2,dir3,..,fi.le1.ext1,*.ext2,*.ext3} "../Target_$today/Subdir_$today/"
</code>```

Now I want to copy all files of ".ext3" but leave out files that contain "lock" or "-lock" in their name. Because those files are auto-generated and so not required to backup those(eg. package-lock.json).

How can I do that without adding any find statement in between, but only using wildcard and negation operators ?

答:
Using extended glob:</p>

```<code>shopt -s extglob nullglob

cp -r ./{dir1,dir2,dir3,..,fi.le1.ext1,!(*lock).ext2,*.ext3} "../Target_$today/Subdir_$today/"
</code>```

Body:
I have built script for copying multiple folders and files matching file types in one cp command line only like below:

today=$(date +"%d-%m-%Y");
cp -r ./{dir1,dir2,dir3,..,fi.le1.ext1,*.ext2,*.ext3} "../Target_$today/Subdir_$today/"

Now I want to copy all files of ".ext3" but leave out files that contain "lock" or "-lock" in their name. Because those files are auto-generated and so not required to backup those(eg. package-lock.json).

How can I do that without adding any find statement in between, but only using wildcard and negation operators ?

Body:
Using extended glob:

shopt -s extglob nullglob

cp -r ./{dir1,dir2,dir3,..,fi.le1.ext1,!(*lock).ext2,*.ext3} "../Target_$today/Subdir_$today/"


问:
To Inline an External Function Written in Assembly
I have a separate function written in assembly and want to call it in my C/C++ code.  Is it possible to tell my compiler (MS Visual C++ 2010) to inline that module written in assembly into my C/C++ function?

Note, I am not talking about using inline assembly code (__asm {}) in my C/C++ function.  All assembly codes are written in separate independent modules.

答:
Is it possible to tell my compiler … to inline that module written in assembly into my C/C++ function?

No. The compiler doesn’t even see the assembly code – it’s in a different compilation unit. You can ask your linker to inline the function though. In order to do that, you need to enable link-time optimizations.

There may be a separate option for the linker that tells it to perform inlining but usually this should be done automatically where it makes sense.

ContentLicense: CC BY-SA 3.0


问:
Multiples POST calls in pipe not being executed
I am new to angular and really do know what the issue is but I have a method with a pipe like this, so far just one config is needed and this work ok

```<code>.pipe(
     .
     .
    //addConfigToUser is a POST call
    flatMap(() => this.service.addConfigToUser(config))
     .
     .
)
</code>```

But now I need to modify the method in order to execute the same post request for each entry in the config, but for some reasons that is not the case

```<code>.pipe(
    .
    .
    flatMap(() => configElemnt.map(
      //addConfigToUser is a POST call
      config => this.service.addConfigToUser(configElemnt)
    .
    .
    ))
</code>```

A workaround would be accessing to the index and in that way the job is done, like this:

```<code>pipe(
    .
    .
    //addConfigToUser is a POST call
    flatMap(() => this.service.addConfigToUser(config[0])),
    flatMap(() => this.service.addConfigToUser(config[1]))
    .
    .
)
</code>```

Is not throwing any error, but neither do the POST request

答:
I think you can use forkJoin for this:

.pipe(
  flatMap(
    () => forkJoin(
      ...configElemnt.map(cfg => this.service.addConfigToUser(cfg))
    )
  ),
)
```

Notice that forkJoin will emit an array of resulted values if all the provided observables emit at least once and complete.

Body:
I am new to angular and really do know what the issue is but I have a method with a pipe like this, so far just one config is needed and this work ok

.pipe(
     .
     .
    //addConfigToUser is a POST call
    flatMap(() => this.service.addConfigToUser(config))
     .
     .
)

But now I need to modify the method in order to execute the same post request for each entry in the config, but for some reasons that is not the case

.pipe(
    .
    .
    flatMap(() => configElemnt.map(
      //addConfigToUser is a POST call
      config => this.service.addConfigToUser(configElemnt)
    .
    .
    ))

A workaround would be accessing to the index and in that way the job is done, like this:

pipe(
    .
    .
    //addConfigToUser is a POST call
    flatMap(() => this.service.addConfigToUser(config[0])),
    flatMap(() => this.service.addConfigToUser(config[1]))
    .
    .
)

Is not throwing any error, but neither do the POST request

Body:
I think you can use forkJoin for this:

.pipe(
  flatMap(
    () => forkJoin(
      ...configElemnt.map(cfg => this.service.addConfigToUser(cfg))
    )
  ),
)

Notice that forkJoin will emit an array of resulted values if all the provided observables emit at least once and complete.


问:
Vanilla JS - How To Stop Sub-Element's OnClick Method From Calling Parent Elements OnClick Method
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

```<code><script>
function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  alert("deleteImage");
}
</script>

<style>
body {
  background: black;
}
</style>

<div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option" onclick="chooseImage()">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="">
        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div>
</code>```

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?

答:
This is due to event bubbling.  Use event.stopPropagation() to stop the global event object from bubbling at that moment.  I would also recommend using js to add your event listener so you can grab the event object as an argument rather than having to access it globally.

function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  event.stopPropagation()
  alert("deleteImage");
}
```

Body:
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

        <input type="radio" id="img-1" name="images" checked="">

        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?


问:
how to debug macro?
having this code:

```<code>#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv) {

    if (argc!=2){
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(-1);
    }

    int fd;
    fd=open(argv[1], O_RDONLY);

    if(fd<0){
        perror("open");
        fprintf(stderr,"errno = %s\n",strerror(errno));
        exit(-1);
    }

    for(char c;check(read(fd,&c,1))>0;) //macro "check(x)" HERE
        fputc(c,stdout);

    return 0;
}
</code>```

It compiles without an error, but I can see the macro does not output error messeges (__FILE__, neither __LINE__), as define it the macro. How to fix that? (And for general, how to debug macro, how at least output some error for it)?

$cc -pedantic a.c

```<code>a.c: In function ‘main’:
a.c:10:2: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
  ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
             ^~~~~
a.c:9:18: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
 #define check(x) ({int _val = (x); (_val ==-1? \
                  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
</code>```

not single mention about for loop (only its location, because the macro is in there, but that is not error) statment. Only about macro. So please focus on macro problem and not about the for loop.

EDIT1:
the macro actually comes from this guy:
youtube tutorial (at the end of the video), well he uses clang, so I do not know what clang uses as a preprocessor (and therefor it works for him).

EDIT2 (output from a.i - preprocessed output):

```<code># 304 "/usr/include/fcntl.h" 3 4

# 8 "a.c" 2

# 14 "a.c"
int main (int argc, char **argv) {
</code>```

I have deleted all the noise. But you can see between #include <fcntl.h> and int main, there is nothing. But there should be the #define check(x).... So it does not tell me WHY is it missing.

答:
You can't debug a macro in the sense that a high level debugger will step through the macro code. What you can do is temporarily expand the macro in the source code and use a debugger to see what is going wrong.

One idea is to use a code formatter, like clang-format to beautify the macro so that you can understand it better an use the debugger. Applying this idea, transform the macro into a function and let the formatter do its job:

```<code>$ clang-format -i macro.c
</code>```

results in:

```<code>void check1(x) {
  ({
    int _val = (x);
    (_val == -1 ? ({
      fprintf(stderr,
              "Error (" __FILE__ ":%d) -- "
              "%s\n",
              __LINE__, strerror(errno));
      exit(-1);
      -1;
    })
                : _val);
  })
}
</code>```

The code you originally posted actually compiles and executes properly here. I made a version with a few cuts to be able to test the macro:

```<code>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv)
{
    check(-1);
    return 0;
}
</code>```

results in:

```<code>$ gcc a.c && ./a.out
Error (a.c:13) -- Success
</code>```

Title: how to debug macro?

Body:
having this code:

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv) {

    if (argc!=2){
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(-1);
    }

    int fd;
    fd=open(argv[1], O_RDONLY);

    if(fd<0){
        perror("open");
        fprintf(stderr,"errno = %s\n",strerror(errno));
        exit(-1);
    }

    for(char c;check(read(fd,&c,1))>0;) //macro "check(x)" HERE
        fputc(c,stdout);

    return 0;
}

It compiles without an error, but I can see the macro does not output error messeges (__FILE__, neither __LINE__), as define it the macro. How to fix that? (And for general, how to debug macro, how at least output some error for it)?

$cc -pedantic a.c

a.c: In function ‘main’:
a.c:10:2: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
  ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
             ^~~~~
a.c:9:18: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
 #define check(x) ({int _val = (x); (_val ==-1? \
                  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)

not single mention about for loop (only its location, because the macro is in there, but that is not error) statment. Only about macro. So please focus on macro problem and not about the for loop.

EDIT1:
the macro actually comes from this guy:
youtube tutorial (at the end of the video), well he uses clang, so I do not know what clang uses as a preprocessor (and therefor it works for him).

EDIT2 (output from a.i - preprocessed output):

# 304 "/usr/include/fcntl.h" 3 4

# 8 "a.c" 2

# 14 "a.c"
int main (int argc, char **argv) {

I have deleted all the noise. But you can see between #include <fcntl.h> and int main, there is nothing. But there should be the #define check(x).... So it does not tell me WHY is it missing.

Body:
You can't debug a macro in the sense that a high level debugger will step through the macro code. What you can do is temporarily expand the macro in the source code and use a debugger to see what is going wrong.

One idea is to use a code formatter, like clang-format to beautify the macro so that you can understand it better an use the debugger. Applying this idea, transform the macro into a function and let the formatter do its job:

$ clang-format -i macro.c

results in:

void check1(x) {
  ({
    int _val = (x);
    (_val == -1 ? ({
      fprintf(stderr,
              "Error (" __FILE__ ":%d) -- "
              "%s\n",
              __LINE__, strerror(errno));
      exit(-1);
      -1;
    })
                : _val);
  })
}

The code you originally posted actually compiles and executes properly here. I made a version with a few cuts to be able to test the macro:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv)
{
    check(-1);
    return 0;
}

results in:

$ gcc a.c && ./a.out
Error (a.c:13) -- Success


问:
TradingView Forward testing strategy error - filling multiple orders per bar rather than one
When I backtest my strategy it will only execute one order at the close of the bar, but when I let the strategy run in real-time it will execute multiple orders (sometimes 3,4,5 orders per bar). How do I stop this from happening so it only places ONE order per bar when forward testing?</p>

答: Do not use calc_on_every_tick = true in your strategy() call, and set Pyramiding to 1 in the strategy's "Properties".


问:
Using EnumMemberAttribute and doing automatic string conversions
I have the following code

```<code>[DataContract]
public enum StatusType
{
    [EnumMember(Value = "A")]
    All,
    [EnumMember(Value = "I")]
    InProcess,
    [EnumMember(Value = "C")]
    Complete,
}
</code>```

I'd like to do the following:

```<code> var s = "C";
 StatusType status = SerializerHelper.ToEnum<StatusType>(s);   //status is now StatusType.Complete
 string newString = SerializerHelper.ToEnumString<StatusType>(status);   //newString is now "C"
</code>```

I've done the second part using DataContractSerializer (see code below), but it seems like a lot of work.

Am I missing something obvious? Ideas? Thanks.

```<code>    public static string ToEnumString<T>(T type)
    {
        string s;
        using (var ms = new MemoryStream())
        {
            var ser = new DataContractSerializer(typeof(T));
            ser.WriteObject(ms, type);
            ms.Position = 0;
            var sr = new StreamReader(ms);
            s = sr.ReadToEnd();
        }
        using (var xml = new XmlTextReader(s, XmlNodeType.Element, null))
        {
            xml.MoveToContent();
            xml.Read();
            return xml.Value;
        }
    }
</code>```

答:
Using extensions and C# 7.3 constraints</p>

```<code>    public static class EnumMemberExtensions
    {
        public static string ToEnumString<T>(this T type)
            where T : Enum
        {
            var enumType = typeof(T);
            var name = Enum.GetName(enumType, type);
            var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
            return enumMemberAttribute.Value;
        }

        public static T ToEnum<T>(this string str)
            where T : Enum
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default;
        }
    }
</code>```

Body:
I have the following code

[DataContract]
public enum StatusType
{
    [EnumMember(Value = "A")]
    All,
    [EnumMember(Value = "I")]
    InProcess,
    [EnumMember(Value = "C")]
    Complete,
}

I'd like to do the following:

 var s = "C";
 StatusType status = SerializerHelper.ToEnum<StatusType>(s);   //status is now StatusType.Complete
 string newString = SerializerHelper.ToEnumString<StatusType>(status);   //newString is now "C"

I've done the second part using DataContractSerializer (see code below), but it seems like a lot of work.

Am I missing something obvious? Ideas? Thanks.

    public static string ToEnumString<T>(T type)
    {
        string s;
        using (var ms = new MemoryStream())
        {
            var ser = new DataContractSerializer(typeof(T));
            ser.WriteObject(ms, type);
            ms.Position = 0;
            var sr = new StreamReader(ms);
            s = sr.ReadToEnd();
        }
        using (var xml = new XmlTextReader(s, XmlNodeType.Element, null))
        {
            xml.MoveToContent();
            xml.Read();
            return xml.Value;
        }
    }

Body:
Using extensions and C# 7.3 constraints

    public static class EnumMemberExtensions
    {
        public static string ToEnumString<T>(this T type)
            where T : Enum
        {
            var enumType = typeof(T);
            var name = Enum.GetName(enumType, type);
            var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
            return enumMemberAttribute.Value;
        }

        public static T ToEnum<T>(this string str)
            where T : Enum
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default;
        }
    }


问:
Can I use ApolloClient to subscribe with Appsync graphql?
I am reading Appsync articles about how to use subscription and come up with this link: https://docs.aws.amazon.com/appsync/latest/devguide/real-time-data.html.  It says The AWS AppSync client SDK automatically handles subscription connection management.

My question is whether I can use graphql libraries other than AppSync client SDK? If I can, how are the subscription connections handled? Is there any problem to use other clients?

答:
If you use the REALTIME endpoint on your API (recommended), depending on your platform then you can use either the AppSync SDK or the Amplify client, it will work out of the box. https://aws.amazon.com/blogs/mobile/appsync-realtime/

Technically, you are free to use any client that supports websockets but you will need to implement the handshake & subscription flow. (it's very close to the Apollo flow with minor changes to improve security)

We created a client for Python that showcases it is possible if you want to use a different client or language when using AppSync https://aws.amazon.com/blogs/mobile/appsync-websockets-python/.


问:
How do i return column that contains images
I'm trying to build a widget that returns column of widgets, my code is like this

```<code>    import 'package:flutter/material.dart';

class ProductList extends StatelessWidget {

  String productImage;
  String productName;
  double productPrice;

  ProductList({this.productImage, this.productPrice, this.productName});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image(image: Image.asset(productImage)),
          Text(productName),
          Text(productPrice.toString())

        ],
      ),
    );
  }
}
</code>```

Im getting error on line 16 which is  Image(image: Image.asset(productImage)),

the error message is The argument type 'Image' can't be assigned to the parameter type 'ImageProvider<dynamic>'.
How do i fix this

答:
That's happens because u trying put a Image inside other Image. This is my suggestion:

class ProductList extends StatelessWidget {

  String productImage;
  String productName;
  double productPrice;

  ProductList({this.productImage, this.productPrice, this.productName});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image.asset(productImage),
          Text(productName),
          Text(productPrice.toString())
        ],
      ),
    );
  }
}
```

Body:
I'm trying to build a widget that returns column of widgets, my code is like this

    import 'package:flutter/material.dart';

class ProductList extends StatelessWidget {

  String productImage;
  String productName;
  double productPrice;

  ProductList({this.productImage, this.productPrice, this.productName});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image(image: Image.asset(productImage)),
          Text(productName),
          Text(productPrice.toString())

        ],
      ),
    );
  }
}

Im getting error on line 16 which is  Image(image: Image.asset(productImage)),

the error message is The argument type 'Image' can't be assigned to the parameter type 'ImageProvider<dynamic>'.
How do i fix this


问:
PHPUnit assertDataHas() on array
I'm working on a Laravel applications and testing whether my POST request has actually added the record to the database using

```<code>$this->assertDatabaseHas('profiles', [
  'physical_address'          => [
   'city'          => $physical_address['city'],
   'line_1'        => $physical_address['line_1'],
   'line_2'        => $physical_address['line_2'],
   'country'       => $physical_address['country'],
   'province'      => $physical_address['province'],
   'postal_code'   => $physical_address['postal_code'],
  ],
]);
</code>```

I'm making a POST request to the endpoint and passing in.

```<code>$physical_address = [
    'line_1'            => $this->faker->secondaryAddress,
    'line_2'            => $this->faker->streetAddress,
    'city'              => $this->faker->city,
    'province'          => $this->faker->state,
    'postal_code'       => $this->faker->postcode,
    'country'           => $this->faker->country,
];
</code>```

The physical_address column is a JSON column and is added to the $casts array on the model.

The test, however keeps failing with the error message:

```<code>1) Tests\Feature\ProfileTest::testCreateProfile
Failed asserting that a row in the table [profiles] matches the attributes {
    "physical_address": {
        "city": "Nicoview",
        "line_1": "Apt. 664",
        "line_2": "136 Mueller Mountain Suite 956",
        "country": "Malta",
        "province": "Arkansas",
        "postal_code": "19176-5371"
    }
}.
</code>```

When I dump the record that was added to the database, the column structure looks as follows:

```<code>"physical_address" => array:6 [
    "city" => "Nicoview"
    "line_1" => "Apt. 664"
    "line_2" => "136 Mueller Mountain Suite 956"
    "country" => "Malta"
    "province" => "Arkansas"
    "postal_code" => "19176-5371"
  ]
</code>```

I've made sure the keys are in the right order but I don't know what I should try anymore or if I'm missing something obvious.

答:
AssertDatabaseHas() underlying is just where queries, it will end up trying to parse your assertation as it was another nested array, most likely into city = Nicoview and line_1 = Apt. 664 ....

In Laravel Queries you can access JSON columns with -> as the accessor separator. So physical_address->city will represent the city representation. So i believe you will achieve the results you want by doing this.

```<code>$this->assertDatabaseHas('profiles', [
    'physical_address->city' => $physical_address['city'],
    'physical_address->line_1' => $physical_address['line_1'],
    'physical_address->line_2' => $physical_address['line_2'],
    'physical_address->country' => $physical_address['country'],
    'physical_address->province' => $physical_address['province'],
    'physical_address->postal_code' => $physical_address['postal_code'],
]);
</code>```

Title: PHPUnit assertDataHas() on array

Body:
I'm working on a Laravel applications and testing whether my POST request has actually added the record to the database using

$this->assertDatabaseHas('profiles', [
  'physical_address'          => [
   'city'          => $physical_address['city'],
   'line_1'        => $physical_address['line_1'],
   'line_2'        => $physical_address['line_2'],
   'country'       => $physical_address['country'],
   'province'      => $physical_address['province'],
   'postal_code'   => $physical_address['postal_code'],
  ],
]);

I'm making a POST request to the endpoint and passing in.

$physical_address = [
    'line_1'            => $this->faker->secondaryAddress,
    'line_2'            => $this->faker->streetAddress,
    'city'              => $this->faker->city,
    'province'          => $this->faker->state,
    'postal_code'       => $this->faker->postcode,
    'country'           => $this->faker->country,
];

The physical_address column is a JSON column and is added to the $casts array on the model.

The test, however keeps failing with the error message:

1) Tests\Feature\ProfileTest::testCreateProfile
Failed asserting that a row in the table [profiles] matches the attributes {
    "physical_address": {
        "city": "Nicoview",
        "line_1": "Apt. 664",
        "line_2": "136 Mueller Mountain Suite 956",
        "country": "Malta",
        "province": "Arkansas",
        "postal_code": "19176-5371"
    }
}.

When I dump the record that was added to the database, the column structure looks as follows:

"physical_address" => array:6 [
    "city" => "Nicoview"
    "line_1" => "Apt. 664"
    "line_2" => "136 Mueller Mountain Suite 956"
    "country" => "Malta"
    "province" => "Arkansas"
    "postal_code" => "19176-5371"
  ]

I've made sure the keys are in the right order but I don't know what I should try anymore or if I'm missing something obvious.

Body:
AssertDatabaseHas() underlying is just where queries, it will end up trying to parse your assertation as it was another nested array, most likely into city = Nicoview and line_1 = Apt. 664 ....

In Laravel Queries you can access JSON columns with -> as the accessor separator. So physical_address->city will represent the city representation. So i believe you will achieve the results you want by doing this.

$this->assertDatabaseHas('profiles', [
    'physical_address->city' => $physical_address['city'],
    'physical_address->line_1' => $physical_address['line_1'],
    'physical_address->line_2' => $physical_address['line_2'],
    'physical_address->country' => $physical_address['country'],
    'physical_address->province' => $physical_address['province'],
    'physical_address->postal_code' => $physical_address['postal_code'],
]);


问:
What am I able to (not) include in a .cpp file?
This question is pretty weird.
Say I have a file, called idiot.cpp, and it begins with:

```<code>#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#include "idiot.h"
</code>```

and I have a header file, idiot.h. First of all, in idiot.h, do I also have to insert

```<code>#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
</code>```

or do I not?
Second, if I have another source file, say, "bonito.cpp," that uses idiot.h, should I just #include "idiot.h", or should I paste in the code snippet again?
If not, is there any way to shorten this so I don't end up including around 20 headers per file? (hypothetically)
Sorry if this is a pretty dumb question, but I don't use many headers too often.

答:
idiot.cpp does not need to include anything included indirectly by idiot.h to be able to compile.

The more interesting case: bonito.cpp #includes idiot.h and idiot.h includes x.h.  If idiot.h only uses the content of x.h for private or anonymous namespace code - and bonito.cpp wants to use something from x.h too, then bonito.cpp should include x.h directly (redundantly).

The justification is simple: idiot.h can't remove something from the public/protected interface without risking breaking client code, so if that happens then the clients have to expect to deal with it - possibly including an extra header too.  BUT, the maintainer of idiot.h and idiot.cpp should be free to change private or anonymous namespace content within idiot.h without risking breaking client code, including which headers are included to support that private code.

So, the inclusion is redundant at the time it's done, but that's done in the expectation that it might stop being redundant as idiot.h evolves.

This best-practice model is not automatically enforced - you have to understand the way this should work and actively code to that model.

Example

If idiot.h contains...

```<code>#include <string>
#include <vector>
...
class X {
    void add(const std::string&);
  private:
    std::vector<std::string> v_;
};
</code>```

...then bonito.cpp can reasonably use std::string without including <string>, but should include <vector> itself if it needs std::vector<>.

Body:
This question is pretty weird.
Say I have a file, called idiot.cpp, and it begins with:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#include "idiot.h"

and I have a header file, idiot.h. First of all, in idiot.h, do I also have to insert

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>

or do I not?
Second, if I have another source file, say, "bonito.cpp," that uses idiot.h, should I just #include "idiot.h", or should I paste in the code snippet again?
If not, is there any way to shorten this so I don't end up including around 20 headers per file? (hypothetically)
Sorry if this is a pretty dumb question, but I don't use many headers too often.

Body:
idiot.cpp does not need to include anything included indirectly by idiot.h to be able to compile.

The more interesting case: bonito.cpp #includes idiot.h and idiot.h includes x.h.  If idiot.h only uses the content of x.h for private or anonymous namespace code - and bonito.cpp wants to use something from x.h too, then bonito.cpp should include x.h directly (redundantly).

The justification is simple: idiot.h can't remove something from the public/protected interface without risking breaking client code, so if that happens then the clients have to expect to deal with it - possibly including an extra header too.  BUT, the maintainer of idiot.h and idiot.cpp should be free to change private or anonymous namespace content within idiot.h without risking breaking client code, including which headers are included to support that private code.

So, the inclusion is redundant at the time it's done, but that's done in the expectation that it might stop being redundant as idiot.h evolves.

This best-practice model is not automatically enforced - you have to understand the way this should work and actively code to that model.

Example

If idiot.h contains...

#include <string>
#include <vector>
...
class X {
    void add(const std::string&);
  private:
    std::vector<std::string> v_;
};

...then bonito.cpp can reasonably use std::string without including <string>, but should include <vector> itself if it needs std::vector<>.


问:
Mobile application with sql databases
I am currently working on a mobile application, I have linked the application to the sql type database by Azure SQL Database Now I am in the trial phase and the program is working fine but I have not done REST services, I linked the application directly to the database through the connection strings
  Note that the application serves a specific category of users, do you recommend this work, or do REST and API services.
Please Help</p>

答: The REST model was created for this. If you want to make your application available to the public, anyone can try to decompile your application, and if they can, they will have access to your database if you are using a connection string. With access to the database, they can delete records and tables, for example, tasks that your API will not allow.</p>

Title: Mobile application with sql databases


问:
Can std::string::resize() throw when shrinking?
Consider the following function:

void shrink_string(std::string& str) {
  if (str.size() >= 2) {
    str.resize(str.size() - 2);
  }
}
```

I wonder if this function can be declared noexcept (assuming C++11 standard)? I understand that the documentation does not declare .resize() as noexcept, but that's mostly because this method can be used both for growing and shrinking a string.

Obviously, shrinking can be trivially implemented by leaving the string's capacity constant and simply reducing the internal length; at the same time resize() may decide to reallocate anyways, in order to free up some memory -- but would it fall back to the trivial resizing if reallocation throws an error?

答:
From the docs:

In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call.

Therefore, resizing the vector to something smaller will not alter the memory (use shrink_to_fit instead to (suggest a) reduce capacity to the size). That's because there is no standard way in the OS to resize the memory and force the pointers to be the same.

HeapReAlloc() for example, in Windows, may or may not return the same pointer but you can't force it to return the same.

Body:
Consider the following function:

void shrink_string(std::string& str) {
  if (str.size() >= 2) {
    str.resize(str.size() - 2);
  }
}

I wonder if this function can be declared noexcept (assuming C++11 standard)? I understand that the documentation does not declare .resize() as noexcept, but that's mostly because this method can be used both for growing and shrinking a string.

Obviously, shrinking can be trivially implemented by leaving the string's capacity constant and simply reducing the internal length; at the same time resize() may decide to reallocate anyways, in order to free up some memory -- but would it fall back to the trivial resizing if reallocation throws an error?


问:
What is the syntax meaning of RAISERROR()
I just created a Instead After Trigger whose syntax is given below:

```<code>Create trigger tgrInsteadTrigger on copytableto
Instead of Insert as
    Declare @store_name varchar(30);
    declare @sales int;
    declare @date datetime;

    select @store_name = i.store_name from inserted i
    select @sales = i.sales from inserted i
    select @date = i.Date from inserted i
begin
    if (@sales > 1000)
        begin
        RAISERROR('Cannot Insert where salary > 1000',16,1); ROLLBACK;
        end
    else
        begin
        insert into copytablefrom(store_name, sales, date) values (@store_name, @sales, @date);
        Print 'Instead After Trigger Executed';
        end
End
</code>```

In the above syntax I have used RAISERROR('Cannot Insert where salary > 1000',16,1)

But when I write RAISERROR('Cannot Insert where salary > 1000') it gives the error "Incorrect syntax near ')'" on the same line.

Can anyone please explain the use of (16,1) here.

答:
The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block.  I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block.  I demonstrate this in the gif as well.

```<code>BEGIN TRY
    /* RAISERROR with severity 11-19 will cause execution
     |  to jump to the CATCH block.
    */
    RAISERROR ('Error raised in TRY block.', -- Message text.
               5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
               1 -- State.
               );
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage  NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState    INT;

    SELECT
        @ErrorMessage  = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState    = ERROR_STATE();

    /* Use RAISERROR inside the CATCH block to return error
     | information about the original error that caused
     | execution to jump to the CATCH block
    */
    RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
               @ErrorSeverity,                           /* Severity     */
               @ErrorState                               /* State        */
               );
END CATCH;
</code>```

Body:
I just created a Instead After Trigger whose syntax is given below:

Create trigger tgrInsteadTrigger on copytableto
Instead of Insert as
    Declare @store_name varchar(30);
    declare @sales int;
    declare @date datetime;

    select @store_name = i.store_name from inserted i
    select @sales = i.sales from inserted i
    select @date = i.Date from inserted i
begin
    if (@sales > 1000)
        begin
        RAISERROR('Cannot Insert where salary > 1000',16,1); ROLLBACK;
        end
    else
        begin
        insert into copytablefrom(store_name, sales, date) values (@store_name, @sales, @date);
        Print 'Instead After Trigger Executed';
        end
End

In the above syntax I have used RAISERROR('Cannot Insert where salary > 1000',16,1)

But when I write RAISERROR('Cannot Insert where salary > 1000') it gives the error "Incorrect syntax near ')'" on the same line.

Can anyone please explain the use of (16,1) here.

Body:
The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block.  I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block.  I demonstrate this in the gif as well.

BEGIN TRY
    /* RAISERROR with severity 11-19 will cause execution
     |  to jump to the CATCH block.
    */
    RAISERROR ('Error raised in TRY block.', -- Message text.
               5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
               1 -- State.
               );
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage  NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState    INT;

    SELECT
        @ErrorMessage  = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState    = ERROR_STATE();

    /* Use RAISERROR inside the CATCH block to return error
     | information about the original error that caused
     | execution to jump to the CATCH block
    */
    RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
               @ErrorSeverity,                           /* Severity     */
               @ErrorState                               /* State        */
               );
END CATCH;


问:
Python - Generate random dates to create Gantt sequenced tasks
The idea is to generate random but sequenced dates based on workload estimation in python.

The goal is to have an output like this:

Task,  Start_date, End_date

task1, 01/06/2020, 05/06/2020

task2, 08/06/2020, 11/06/2020

task3, 12/06/2020, 24/06/2020

...

So I started to work on this code but unable to find a way to randomize it.

```<code>#startdate
start_date = datetime.date(2020, 1, 1)
#enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
</code>```

Any idea on how to randomize?

答:
You need a seed:

```<code>random.seed(a=None)
</code>```

a is the seed value. If it is None then the system time is used by default. Add this line before you start generating random dates. Don't set the seed inside a loop because that causes bugs.

You can do something like this:

```<code>import datetime
import random
# startdate
start_date = datetime.date(2020, 1, 1)
# enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days

random.seed(a=None)

tasks = 10

for i in range(tasks):
    random_number_of_days = random.randrange(days_between_dates)
    random_date = start_date + datetime.timedelta(days=random_number_of_days)
    print("Task" + str(i+1) + "," + str(start_date) + "," + str(random_date))
    start_date = random_date # by @Makram
</code>```

You will need to change what start date is, too, unless you want all of them to start at the same date.

You can make a list of startdates and then index them with i. This will allow you to have a specific start date for each of the tasks.

Body:
The idea is to generate random but sequenced dates based on workload estimation in python.

The goal is to have an output like this:

Task,  Start_date, End_date

task1, 01/06/2020, 05/06/2020

task2, 08/06/2020, 11/06/2020

task3, 12/06/2020, 24/06/2020

...

So I started to work on this code but unable to find a way to randomize it.

#startdate
start_date = datetime.date(2020, 1, 1)
#enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)

Any idea on how to randomize?

Body:
You need a seed:

random.seed(a=None)

a is the seed value. If it is None then the system time is used by default. Add this line before you start generating random dates. Don't set the seed inside a loop because that causes bugs.

You can do something like this:

import datetime
import random
# startdate
start_date = datetime.date(2020, 1, 1)
# enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days

random.seed(a=None)

tasks = 10

for i in range(tasks):
    random_number_of_days = random.randrange(days_between_dates)
    random_date = start_date + datetime.timedelta(days=random_number_of_days)
    print("Task" + str(i+1) + "," + str(start_date) + "," + str(random_date))
    start_date = random_date # by @Makram

You will need to change what start date is, too, unless you want all of them to start at the same date.

You can make a list of startdates and then index them with i. This will allow you to have a specific start date for each of the tasks.


问:
Error: Unable to initialize gtk, is DISPLAY set properly?
I'm trying to run Image application from server "bert"

I connected through my OSX Maverick as

```<code>ssh ak324@bert.eecs.qmul.ac.uk
</code>```

I compiled my file with

```<code>$ make
</code>```

but when I run the resulting file

$ ./window

it gives me the following error:

```<code>Error: Unable to initialize gtk, is DISPLAY set properly?
</code>```

How can I solve this problem?

答:
Try running ssh with the flags -Y -v.

If the following line appears on the terminal during the ssh connection, install xauth on your remote system.

debug1: Remote: No xauth program; cannot forward with spoofing.

As suggested here.

Body:
I'm trying to run Image application from server "bert"

I connected through my OSX Maverick as

ssh ak324@bert.eecs.qmul.ac.uk

I compiled my file with

$ make

but when I run the resulting file

$ ./window

it gives me the following error:

Error: Unable to initialize gtk, is DISPLAY set properly?

How can I solve this problem?


问:
MSYS2 MinGW64 to build GMP/MPFR on Windows as static library, and link them in MSVC project compiled with CL
I'm working using Visual Studio 2019. I have a project that requires GMP and MPFR ; as far as I know, there are no recent binaries available for Windows and one has to build his own.

To build GMP/MPFR from source code, I used the mingw-w64-x86_64-toolchain installed with the command pacman -S mingw-w64-x86_64-toolchain in MSYS2 shell. Then, from the MinGW64 shell, I just used ./configure, make, make install and ended up with .a libraries, which is, unless I'm wrong, perfectly usable in a VS project.

So now back to my project in Visual Studio, I'm trying to compile it with default compiler CL => it fails with the following errors :

```<code>Severity    Code    Description                                                                             Project     File                                                Line    Suppression State
Error   LNK1120     2 unresolved externals                                                                  MyProject   MyProject.exe                                       1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(aors.o)                                    1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_bdiv_q.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_bdiv_qr.o)                           1
Error   LNK2019     unresolved external symbol ___chkstk_ms referenced in function mpn_dcpi1_divappr_q_n    MyProject   libgmp.a(dcpi1_divappr_q.o)                         1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_div_qr.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(divexact.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(gcd.o)                                     1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(hgcd_reduce.o)                             1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(invertappr.o)                              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt103-divexact.o)                          1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt31-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt55-cmp.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt57-cmp_ui.o)                             1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt64-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt82-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt97-gcd.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt99-tdiv_qr.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(mullo_n.o)                                 1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(mul_n.o)                                   1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(nussbaumer_mul.o)                          1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(sqr.o)                                     1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(toom42_mul.o)                              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(toom53_mul.o)                              1
Error   LNK2019     unresolved external symbol __mingw_raise_matherr referenced in function cos             MyProject   libmingwex.a(lib64_libmingwex_a-cos.o)              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libmingwex.a(lib64_libmingwex_a-mingw_pformat.o)    1
Error   LNK2001     unresolved external symbol __mingw_raise_matherr                                        MyProject   libmingwex.a(lib64_libmingwex_a-sin.o)              1
Error   LNK2001     unresolved external symbol __mingw_raise_matherr                                        MyProject   libmingwex.a(lib64_libmingwex_a-sqrt.o)             1

</code>```

I imagine that I need to link my VS project with a static-library from MSYS2 but I canno't figure which one. Following this topic I already linked with C:\msys64\mingw64\x86_64-w64-mingw32\lib\libmingwex.a but now I'm quite stuck. Any suggestion?

答:
___chkstk_ms is defined in libgcc (...\msys64\mingw64\lib\gcc\x86_64-w64-mingw32\10.1.0\libgcc.a).

__mingw_raise_matherr is defined in libmingw32 (...\msys64\mingw64\x86_64-w64-mingw32\lib\libmingw32.a).

I don't know if this will help you get a working executable though. :)  C++ is out of the question, but it seems you haven't bumped into that particular issue so far.

You can find these symbols using simple substring search and confirm using nm (T stands for a defined symbol, U for an undefined one).  You can also call GCC with verbosity turned up to see the exact linker command behind the scenes, or call gcc -dumpspecs to read exactly when is what linked in.

Body:
I'm working using Visual Studio 2019. I have a project that requires GMP and MPFR ; as far as I know, there are no recent binaries available for Windows and one has to build his own.

To build GMP/MPFR from source code, I used the mingw-w64-x86_64-toolchain installed with the command pacman -S mingw-w64-x86_64-toolchain in MSYS2 shell. Then, from the MinGW64 shell, I just used ./configure, make, make install and ended up with .a libraries, which is, unless I'm wrong, perfectly usable in a VS project.

So now back to my project in Visual Studio, I'm trying to compile it with default compiler CL => it fails with the following errors :

Severity    Code    Description                                                                             Project     File                                                Line    Suppression State
Error   LNK1120     2 unresolved externals                                                                  MyProject   MyProject.exe                                       1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(aors.o)                                    1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_bdiv_q.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_bdiv_qr.o)                           1
Error   LNK2019     unresolved external symbol ___chkstk_ms referenced in function mpn_dcpi1_divappr_q_n    MyProject   libgmp.a(dcpi1_divappr_q.o)                         1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(dcpi1_div_qr.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(divexact.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(gcd.o)                                     1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(hgcd_reduce.o)                             1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(invertappr.o)                              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt103-divexact.o)                          1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt31-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt55-cmp.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt57-cmp_ui.o)                             1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt64-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt82-mul.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt97-gcd.o)                                1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(lt99-tdiv_qr.o)                            1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(mullo_n.o)                                 1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(mul_n.o)                                   1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(nussbaumer_mul.o)                          1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(sqr.o)                                     1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(toom42_mul.o)                              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libgmp.a(toom53_mul.o)                              1
Error   LNK2019     unresolved external symbol __mingw_raise_matherr referenced in function cos             MyProject   libmingwex.a(lib64_libmingwex_a-cos.o)              1
Error   LNK2001     unresolved external symbol ___chkstk_ms                                                 MyProject   libmingwex.a(lib64_libmingwex_a-mingw_pformat.o)    1
Error   LNK2001     unresolved external symbol __mingw_raise_matherr                                        MyProject   libmingwex.a(lib64_libmingwex_a-sin.o)              1
Error   LNK2001     unresolved external symbol __mingw_raise_matherr                                        MyProject   libmingwex.a(lib64_libmingwex_a-sqrt.o)             1

I imagine that I need to link my VS project with a static-library from MSYS2 but I canno't figure which one. Following this topic I already linked with C:\msys64\mingw64\x86_64-w64-mingw32\lib\libmingwex.a but now I'm quite stuck. Any suggestion?


问:
C++, () operator overloading, what's its job
I was reading from a book in C++ and it says:

```<code>template<class T>
T max(const T& a, const T& b)
{
    return a>b?a:b;
}

int main()
{
int n1= 7,n2= 5;
Complex c1(2.0, 1.0), c2(0.0, 1.0);
cout << max(n1, n2) << endl;
cout << max(c1, c2) << endl;
//Compilation Error, can't compile max<complex> since there is no operator >() for complex numebrs.
return 0;
}
</code>```

What does that mean, where did I used the () operator for Complex numbers here and what's its job in general? (I don't understand the whole idea behind () operator even though I read about it)

Complex is a class with 2 fields one (two doubles) one for real number and one for imaginary number, plus it has > operator

答:
The problem is that your Complex class does not have an operator > defined that could be used within the max() function to compare two const Complex objects.

Check if the operator > is declared as a member function, whether the function is declared as a const function, or its parameter is a const reference.

The operator should be declared either as a member function like this:

```<code>bool operator >( const Complex & ) const;
</code>```

or, if it is declared as a non-member function (for example as a friend function), then it should be declared like this:

```<code>bool operator >( const Complex &, const Complex & );
</code>```

Body:
I was reading from a book in C++ and it says:

template<class T>
T max(const T& a, const T& b)
{
    return a>b?a:b;
}

int main()
{
int n1= 7,n2= 5;
Complex c1(2.0, 1.0), c2(0.0, 1.0);
cout << max(n1, n2) << endl;
cout << max(c1, c2) << endl;
//Compilation Error, can't compile max<complex> since there is no operator >() for complex numebrs.
return 0;
}

What does that mean, where did I used the () operator for Complex numbers here and what's its job in general? (I don't understand the whole idea behind () operator even though I read about it)

Complex is a class with 2 fields one (two doubles) one for real number and one for imaginary number, plus it has > operator

Body:
The problem is that your Complex class does not have an operator > defined that could be used within the max() function to compare two const Complex objects.

Check if the operator > is declared as a member function, whether the function is declared as a const function, or its parameter is a const reference.

The operator should be declared either as a member function like this:

bool operator >( const Complex & ) const;

or, if it is declared as a non-member function (for example as a friend function), then it should be declared like this:

bool operator >( const Complex &, const Complex & );


问:
instruction point value of dynamic linking and static linking
By using Intel's pin, I printed out the instruction pointer (ip) values for a program with dynamic linking and static linking.

And I've found that their ip values are quite different, even though they are the same program.

A program with static linking shows  0x400f50 for its very first ip value.

but a program with dynamic linking shows 0x7f94f0762090 for its first ip value

I am not sure why they have that quite a large gap.

It would be appreciated if anyone could help me find out the reason

答:
I am not sure why they have that quite a large gap.

Because a dynamically linked program does not start executing in the binary: the first few thousands of instructions are executed in the dynamic linker (ld-linux), before control is transferred to _start in the main executable.

See also this answer.


问:
How to interpret dplyr message `summarise()` regrouping output by 'x' (override with `.groups` argument)?
I started getting a new message (see post title) when running group_by and summarise() after updating to dplyr development version 0.8.99.9003.

Here is an example to recreate the output:

```<code>library(tidyverse)
library(hablar)
df <- read_csv("year, week, rat_house_females, rat_house_males, mouse_wild_females, mouse_wild_males
               2018,10,1,1,1,1
               2018,10,1,1,1,1
               2018,11,2,2,2,2
               2018,11,2,2,2,2
               2019,10,3,3,3,3
               2019,10,3,3,3,3
               2019,11,4,4,4,4
               2019,11,4,4,4,4") %>%
  convert(chr(year,week)) %>%
  mutate(total_rodents = rowSums(select_if(., is.numeric))) %>%
  convert(num(year,week)) %>%
  group_by(year,week) %>% summarise(average = mean(total_rodents))
</code>```

The output tibble is correct, but this message appears:

summarise() regrouping output by 'year' (override with .groups argument)

How should this be interpreted? Why does it report regrouping only by 'year' when I grouped by both year and week? Also, what does it mean to override and why would I want to do that?

I don't think the message indicates a problem because it appears throughout the dplyr vignette:
https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html

I believe it is a new message because it has only appeared on very recent SO questions such as How to melt pairwise.wilcox.test output using dplyr? and R Aggregate over multiple columns (neither of which addresses the regrouping/override message).

Thank you!

答:
It is just a friendly warning message about the resulting grouping structure; your output is correct.  By default, if there is any grouping before the summarise, it drops one group variable i.e. the last one specified in the group_by.  If there is only one grouping variable, there won't be any grouping attribute after the summarise. If there are more than one, the grouping is reduced by 1. So in your example since the input to summarise had two variables, the attribute for grouping is reduced to one, i.e. the resulting data frame would have 'year' as the grouping attribute.

As a reproducible example:

```<code>library(dplyr)
mtcars %>%
     group_by(am) %>%
     summarise(mpg = sum(mpg))
#`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 2 x 2
#     am   mpg
#* <dbl> <dbl>
#1     0  326.
#2     1  317.
</code>```

The message is that it is ungrouping i.e when there is a single group_by, it drops that grouping after the summarise

```<code>mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg))
#`summarise()` regrouping output by 'am' (override with `.groups` argument)
# A tibble: 4 x 3
# Groups:   am [2]
#     am    vs   mpg
#  <dbl> <dbl> <dbl>
#1     0     0  181.
#2     0     1  145.
#3     1     0  118.
#4     1     1  199.
</code>```

Here, it drops the last grouping and regroup with the 'am'

If we check the ?summarise, there is .groups argument which by default is "drop_last" and the other options are "drop", "keep", "rowwise"

.groups - Grouping structure of the result.

"drop_last": dropping the last level of grouping. This was the only supported option before version 1.0.0.

"drop": All levels of grouping are dropped.

"keep": Same grouping structure as .data.

"rowwise": Each row is its own group.

When .groups is not specified, you either get "drop_last" when all the results are size 1, or "keep" if the size varies. In addition, a message informs you of that choice, unless the option "dplyr.summarise.inform" is set to FALSE.

i.e. if we change the .groups in summarise, we don't get the message because the group attributes are removed

```<code>mtcars %>%
    group_by(am) %>%
    summarise(mpg = sum(mpg), .groups = 'drop')
# A tibble: 2 x 2
#     am   mpg
#* <dbl> <dbl>
#1     0  326.
#2     1  317.

mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg), .groups = 'drop')
# A tibble: 4 x 3
#     am    vs   mpg
#* <dbl> <dbl> <dbl>
#1     0     0  181.
#2     0     1  145.
#3     1     0  118.
#4     1     1  199.

mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg), .groups = 'drop') %>%
   str
#tibble [4 × 3] (S3: tbl_df/tbl/data.frame)
# $ am : num [1:4] 0 0 1 1
# $ vs : num [1:4] 0 1 0 1
# $ mpg: num [1:4] 181 145 118 199
</code>```

Previously, this warning was not issued and it could lead to situations where the OP does a mutate or something else assuming there is no grouping and results in unexpected output.  Now, the warning gives the user an indication that we should be careful that there is a grouping attribute

NOTE: The .groups right now is experimental in its lifecycle.  So, the behaviour could be modified in the future releases

Depending upon whether we need any further transformation of the data based on the same grouping variable (or not needed), we could select the different options in .groups.

Body:
I started getting a new message (see post title) when running group_by and summarise() after updating to dplyr development version 0.8.99.9003.

Here is an example to recreate the output:

library(tidyverse)
library(hablar)
df <- read_csv("year, week, rat_house_females, rat_house_males, mouse_wild_females, mouse_wild_males
               2018,10,1,1,1,1
               2018,10,1,1,1,1
               2018,11,2,2,2,2
               2018,11,2,2,2,2
               2019,10,3,3,3,3
               2019,10,3,3,3,3
               2019,11,4,4,4,4
               2019,11,4,4,4,4") %>%
  convert(chr(year,week)) %>%
  mutate(total_rodents = rowSums(select_if(., is.numeric))) %>%
  convert(num(year,week)) %>%
  group_by(year,week) %>% summarise(average = mean(total_rodents))

The output tibble is correct, but this message appears:

summarise() regrouping output by 'year' (override with .groups argument)

How should this be interpreted? Why does it report regrouping only by 'year' when I grouped by both year and week? Also, what does it mean to override and why would I want to do that?

I don't think the message indicates a problem because it appears throughout the dplyr vignette:
https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html

I believe it is a new message because it has only appeared on very recent SO questions such as How to melt pairwise.wilcox.test output using dplyr? and R Aggregate over multiple columns (neither of which addresses the regrouping/override message).

Thank you!

Body:
It is just a friendly warning message about the resulting grouping structure; your output is correct.  By default, if there is any grouping before the summarise, it drops one group variable i.e. the last one specified in the group_by.  If there is only one grouping variable, there won't be any grouping attribute after the summarise. If there are more than one, the grouping is reduced by 1. So in your example since the input to summarise had two variables, the attribute for grouping is reduced to one, i.e. the resulting data frame would have 'year' as the grouping attribute.

As a reproducible example:

library(dplyr)
mtcars %>%
     group_by(am) %>%
     summarise(mpg = sum(mpg))
#`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 2 x 2
#     am   mpg
#* <dbl> <dbl>
#1     0  326.
#2     1  317.

The message is that it is ungrouping i.e when there is a single group_by, it drops that grouping after the summarise

mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg))
#`summarise()` regrouping output by 'am' (override with `.groups` argument)
# A tibble: 4 x 3
# Groups:   am [2]
#     am    vs   mpg
#  <dbl> <dbl> <dbl>
#1     0     0  181.
#2     0     1  145.
#3     1     0  118.
#4     1     1  199.

Here, it drops the last grouping and regroup with the 'am'

If we check the ?summarise, there is .groups argument which by default is "drop_last" and the other options are "drop", "keep", "rowwise"

.groups - Grouping structure of the result.

"drop_last": dropping the last level of grouping. This was the only supported option before version 1.0.0.

"drop": All levels of grouping are dropped.

"keep": Same grouping structure as .data.

"rowwise": Each row is its own group.

When .groups is not specified, you either get "drop_last" when all the results are size 1, or "keep" if the size varies. In addition, a message informs you of that choice, unless the option "dplyr.summarise.inform" is set to FALSE.

i.e. if we change the .groups in summarise, we don't get the message because the group attributes are removed

mtcars %>%
    group_by(am) %>%
    summarise(mpg = sum(mpg), .groups = 'drop')
# A tibble: 2 x 2
#     am   mpg
#* <dbl> <dbl>
#1     0  326.
#2     1  317.

mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg), .groups = 'drop')
# A tibble: 4 x 3
#     am    vs   mpg
#* <dbl> <dbl> <dbl>
#1     0     0  181.
#2     0     1  145.
#3     1     0  118.
#4     1     1  199.

mtcars %>%
   group_by(am, vs) %>%
   summarise(mpg = sum(mpg), .groups = 'drop') %>%
   str
#tibble [4 × 3] (S3: tbl_df/tbl/data.frame)
# $ am : num [1:4] 0 0 1 1
# $ vs : num [1:4] 0 1 0 1
# $ mpg: num [1:4] 181 145 118 199

Previously, this warning was not issued and it could lead to situations where the OP does a mutate or something else assuming there is no grouping and results in unexpected output.  Now, the warning gives the user an indication that we should be careful that there is a grouping attribute

NOTE: The .groups right now is experimental in its lifecycle.  So, the behaviour could be modified in the future releases

Depending upon whether we need any further transformation of the data based on the same grouping variable (or not needed), we could select the different options in .groups.


问:
How can I use picker function in TableViewCell
I created 5 cells in my tableView. My first cell is imageCell and it consist of two parts. One is userImageView and the other is userNameText. I did all instructions such as writing delegate protocol and the others. I did not get any error, build was succeed but it did not work. I realized that I did not define my userImageView at cellForRowAt indexPath 0. I just only defined userNameText. I thought that it would be possibly reason. I tried to define as you seen the bottom. But there is a problem. if I equalize UIImage() cod, I don't see anything at the cell and I can not tap anything. if I write nothing about userImageView, I can see the image from Assets assigned and I can tap but nothing happen.
I will be very happy if someone helps me..

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! imageCell
        cell.userImageView.image = UIImage()
        cell.userNameText.text = ""
        return cell
</code>```

Here is my UITableViewController

```<code>import UIKit
protocol ImagePickerDelegate {
func pickImage()
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! imageCell
        cell.userImageView.image = UIImage()
        cell.userNameText.text = ""
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TCNumberCell") as! TCNumberCell
        cell.TCnumberText.text = ""
        return cell
    } else if indexPath.row == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "birthdayCell") as! birthdayCell
        cell.birthdayText.text = ""
        return cell
    } else if indexPath.row == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "companyCell") as! companyCell
        cell.companyNumberText.text = ""
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "schoolCell") as! schoolCell
        cell.schoolNumberText.text = ""
        return cell
    }

}

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    tableView.delegate = self
    tableView.dataSource = self

}

func pickImage() {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
    imagePicker.allowsEditing = false
    self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        let cell:imageCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! imageCell
        cell.userImageView.image = image
    }

    picker.dismiss(animated: true, completion: nil)
    }
}
</code>```

and here is my imageCell

```<code>import UIKit

class imageCell: UITableViewCell, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var userNameText: UITextField!
@IBOutlet weak var userImageView: UIImageView!

var delegate : ImagePickerDelegate?

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    addTapGestureRecognizer(for: userImageView)
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}

func addTapGestureRecognizer(for view: UIImageView) {
    let tap = UITapGestureRecognizer(target: self, action: #selector(pickImage))
    tap.numberOfTapsRequired = 1
    view.isUserInteractionEnabled = true
    view.addGestureRecognizer(tap)
}

@objc func pickImage() {
    delegate?.pickImage()
  }
}
</code>```

tableView

答:
The error is because UITableViewCell has no function present. You should have a callback to the UIViewController that's displaying this table view cell, and have it present the UIImagePickerController with presentViewController(imagePicker, animated: true, completion: nil).

If you're not sure how to do that callback, see this answer here: https://stackoverflow.com/a/22904272/4608154

Essentially, you create a protocol in your TableViewCell class, and have your ViewController assigned as the delegate. Then when your TableViewCell wants to display the UIImagePickerController, the ViewController will have a method triggered.

Body:
I created 5 cells in my tableView. My first cell is imageCell and it consist of two parts. One is userImageView and the other is userNameText. I did all instructions such as writing delegate protocol and the others. I did not get any error, build was succeed but it did not work. I realized that I did not define my userImageView at cellForRowAt indexPath 0. I just only defined userNameText. I thought that it would be possibly reason. I tried to define as you seen the bottom. But there is a problem. if I equalize UIImage() cod, I don't see anything at the cell and I can not tap anything. if I write nothing about userImageView, I can see the image from Assets assigned and I can tap but nothing happen.
I will be very happy if someone helps me..

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! imageCell
        cell.userImageView.image = UIImage()
        cell.userNameText.text = ""
        return cell

Here is my UITableViewController

import UIKit
protocol ImagePickerDelegate {
func pickImage()
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! imageCell
        cell.userImageView.image = UIImage()
        cell.userNameText.text = ""
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TCNumberCell") as! TCNumberCell
        cell.TCnumberText.text = ""
        return cell
    } else if indexPath.row == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "birthdayCell") as! birthdayCell
        cell.birthdayText.text = ""
        return cell
    } else if indexPath.row == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "companyCell") as! companyCell
        cell.companyNumberText.text = ""
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "schoolCell") as! schoolCell
        cell.schoolNumberText.text = ""
        return cell
    }

}

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    tableView.delegate = self
    tableView.dataSource = self

}

func pickImage() {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
    imagePicker.allowsEditing = false
    self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        let cell:imageCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! imageCell
        cell.userImageView.image = image
    }

    picker.dismiss(animated: true, completion: nil)
    }
}

and here is my imageCell

import UIKit

class imageCell: UITableViewCell, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var userNameText: UITextField!
@IBOutlet weak var userImageView: UIImageView!

var delegate : ImagePickerDelegate?

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    addTapGestureRecognizer(for: userImageView)
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}

func addTapGestureRecognizer(for view: UIImageView) {
    let tap = UITapGestureRecognizer(target: self, action: #selector(pickImage))
    tap.numberOfTapsRequired = 1
    view.isUserInteractionEnabled = true
    view.addGestureRecognizer(tap)
}

@objc func pickImage() {
    delegate?.pickImage()
  }
}

tableView


问:
JEST: Error in async method: ReferenceError: regeneratorRuntime is not defined
I'm trying to test the connection to database without getting data. To do this, I have made this test file.

```<code>import { PGConnection } from "../../../db";

test('two plus two is four', () => {
    expect(2 + 2).toBe(4);
});

test("Test connection to DDBB", () => {
    const db = new PGConnection();

    let result = db.test();
    expect(result).toBe("Connection to database has been established succesfully");

});
</code>```

I have a class where I create the connection with the database:

```<code>import Sequelize from "sequelize";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

//console.log("Usuario DDBB: " + loader.FEB_CONNECTION_USER);

class PGConnection{
    constructor(){
        this.db = this.setConnection();
    }

    setConnection(){
        /*console.log("host: " + process.env.FEB_CONNECTION_HOST + "\n" +
        "port: " + process.env.FEB_CONNECTION_PORT + "\n" +
        "user: " + process.env.FEB_CONNECTION_USER + "\n" +
        "password: " + process.env.FEB_CONNECTION_PASSWORD + "\n" +
        "database: " + process.env.FEB_CONNECTION_DDBBNAME);   */
        return(
            new Sequelize(
                process.env.DDBB_NAME,
                process.env.DDBB_USER,
                process.env.DDBB_PSWD, {
                    host: process.env.DDBB_HOST,
                    port: process.env.DDBB_PORT,
                    define: {
                        freezeTableName: true, /**Don't add 's to the end of each table/model */
                        timestamps: false,  /**Don't add fields createdAt and updatedAt */
        /*                 charset: 'utf8',
                        dialectOptions: {
                            collate: 'utf8_general_ci'
                        },     */
                    },
                    dialect: "postgres",
                    //Remove operatorAliases due to an error when we update to sequelize 6.0.0
                    //operatorsAliases: false,
                    pool: {
                        max: 5,
                        min: 0,
                        acquire: 30000,
                        idle: 10000
                    }
                }
            )
        );
    }

    async test(){
        try{
            console.log("host: " + process.env.FEB_CONNECTION_HOST +
            "port: " + process.env.FEB_CONNECTION_PORT +
            "user: " + process.env.FEB_CONNECTION_USER +
            "password: " + process.env.FEB_CONNECTION_PASSWORD +
            "database: " + process.env.FEB_CONNECTION_DDBBNAME)
            await this.db.authenticate();
            console.log("Connection to database has been established succesfully");
            return ("Connection to database has been established succesfully");
            //this.closeConnection();
        }catch (err){
            console.error("Unable to connect to database: " + err);
            return("Unable to connect to database: " + err);
        }
     }

    closeConnection(){
        this.db.close();
        console.log("Connection to database has been closed!!!")
    }
}

module.exports.PGConnection = PGConnection;
</code>```

This class works fine. But, when I try to make the test I've got this error:

```<code> FAIL  src/server/tests/test.spec.js
  ● Test suite failed to run

    ReferenceError: regeneratorRuntime is not defined

      65 |
      66 |     closeConnection(){
    > 67 |         this.db.close();
         |                                                   ^
      68 |         console.log("Connection to database has been closed!!!")
      69 |     }
      70 | }
</code>```

And my package.json is:

```<code>{
  "name": "",
  "version": "1.0.0",
  "description": "Code to build an API for projects, users and tasks",
  "main": "",
  "scripts": {
    "dev": "babel-node src/server/server.js",
    "test": "jest ./server/tests"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "helmet": "^3.22.0",
    "morgan": "^1.10.0",
    "pg": "^8.2.1",
    "pg-hstore": "^2.3.3",
    "sequelize": "^5.21.11"
  },
  "devDependencies": {
    "@babel/cli": "^7.10.1",
    "@babel/core": "^7.10.2",
    "@babel/node": "^7.10.1",
    "@babel/polyfill": "^7.10.1",
    "@babel/preset-env": "^7.10.2",
    "babel-loader": "^8.1.0",
    "jest": "^26.0.1",
    "webpack": "^4.43.0"
  }
}
</code>```

What am I doing wrong?

答:
I have found a solution which fix the error. To fix it you have to install the next plugin: @babel/plugin-transform-runtime

```<code>npm install @babel/plugin-transform-runtime --save-dev
</code>```

Also, you have to config the plugin in .babelrc file:

```<code>"env": {
    "test": {
      "plugins": ["@babel/plugin-transform-runtime"]
    }
}
</code>```

Body:
I'm trying to test the connection to database without getting data. To do this, I have made this test file.

import { PGConnection } from "../../../db";

test('two plus two is four', () => {
    expect(2 + 2).toBe(4);
});

test("Test connection to DDBB", () => {
    const db = new PGConnection();

    let result = db.test();
    expect(result).toBe("Connection to database has been established succesfully");

});

I have a class where I create the connection with the database:

import Sequelize from "sequelize";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

//console.log("Usuario DDBB: " + loader.FEB_CONNECTION_USER);

class PGConnection{
    constructor(){
        this.db = this.setConnection();
    }

    setConnection(){
        /*console.log("host: " + process.env.FEB_CONNECTION_HOST + "\n" +
        "port: " + process.env.FEB_CONNECTION_PORT + "\n" +
        "user: " + process.env.FEB_CONNECTION_USER + "\n" +
        "password: " + process.env.FEB_CONNECTION_PASSWORD + "\n" +
        "database: " + process.env.FEB_CONNECTION_DDBBNAME);   */
        return(
            new Sequelize(
                process.env.DDBB_NAME,
                process.env.DDBB_USER,
                process.env.DDBB_PSWD, {
                    host: process.env.DDBB_HOST,
                    port: process.env.DDBB_PORT,
                    define: {
                        freezeTableName: true, /**Don't add 's to the end of each table/model */
                        timestamps: false,  /**Don't add fields createdAt and updatedAt */
        /*                 charset: 'utf8',
                        dialectOptions: {
                            collate: 'utf8_general_ci'
                        },     */
                    },
                    dialect: "postgres",
                    //Remove operatorAliases due to an error when we update to sequelize 6.0.0
                    //operatorsAliases: false,
                    pool: {
                        max: 5,
                        min: 0,
                        acquire: 30000,
                        idle: 10000
                    }
                }
            )
        );
    }

    async test(){
        try{
            console.log("host: " + process.env.FEB_CONNECTION_HOST +
            "port: " + process.env.FEB_CONNECTION_PORT +
            "user: " + process.env.FEB_CONNECTION_USER +
            "password: " + process.env.FEB_CONNECTION_PASSWORD +
            "database: " + process.env.FEB_CONNECTION_DDBBNAME)
            await this.db.authenticate();
            console.log("Connection to database has been established succesfully");
            return ("Connection to database has been established succesfully");
            //this.closeConnection();
        }catch (err){
            console.error("Unable to connect to database: " + err);
            return("Unable to connect to database: " + err);
        }
     }

    closeConnection(){
        this.db.close();
        console.log("Connection to database has been closed!!!")
    }
}

module.exports.PGConnection = PGConnection;

This class works fine. But, when I try to make the test I've got this error:

 FAIL  src/server/tests/test.spec.js
  ● Test suite failed to run

    ReferenceError: regeneratorRuntime is not defined

      65 |
      66 |     closeConnection(){
    > 67 |         this.db.close();
         |                                                   ^
      68 |         console.log("Connection to database has been closed!!!")
      69 |     }
      70 | }

And my package.json is:

{
  "name": "",
  "version": "1.0.0",
  "description": "Code to build an API for projects, users and tasks",
  "main": "",
  "scripts": {
    "dev": "babel-node src/server/server.js",
    "test": "jest ./server/tests"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "helmet": "^3.22.0",
    "morgan": "^1.10.0",
    "pg": "^8.2.1",
    "pg-hstore": "^2.3.3",
    "sequelize": "^5.21.11"
  },
  "devDependencies": {
    "@babel/cli": "^7.10.1",
    "@babel/core": "^7.10.2",
    "@babel/node": "^7.10.1",
    "@babel/polyfill": "^7.10.1",
    "@babel/preset-env": "^7.10.2",
    "babel-loader": "^8.1.0",
    "jest": "^26.0.1",
    "webpack": "^4.43.0"
  }
}

What am I doing wrong?

Body:
I have found a solution which fix the error. To fix it you have to install the next plugin: @babel/plugin-transform-runtime

npm install @babel/plugin-transform-runtime --save-dev

Also, you have to config the plugin in .babelrc file:

"env": {
    "test": {
      "plugins": ["@babel/plugin-transform-runtime"]
    }
}


问:
Account names are not getting listed when using apex:repeat
This code works just fine for Contacts

```<code><apex:page standardController="Contact" recordSetVar="contacts">
      <apex:pageBlock title="Contact Names">
        <apex:repeat value="{! contacts }" var="ct">
            <li>
              <apex:outputLink value="{! URLFOR($Action.Contact.Edit, ct.Id) }"> {! ct.FirstName } </apex:outputLink>
            </li>
        </apex:repeat>
      </apex:pageBlock>
</apex:page>
</code>```

but almost identical code is not working for Accounts

```<code><apex:page standardController="Account" recordSetVar="accounts">
    <apex:pageBlock title="Account Names">
             <apex:repeat value="{! accounts }" var="a">
                <li>
                 <apex:outputLink value="{! URLFOR($Action.Account.Edit, a.Id) }">  {! a.Name}  </apex:outputLink>
             </li>
        </apex:repeat>
    </apex:pageBlock>
</apex:page>
</code>```

Why is this happeneing?

答:
Try to output {!filterId} somewhere on the page (it'd correspond to getFilterId).
See which listview it is. I expect it's a listview that has 0 results or "Recently Viewed" list (and it happens to be empty too). Or your user has no sharing permissions to see any accounts ;)

StandardSetController respects your last used listview. Select a good listview and refresh your page or view few random accounts.

If you want to display a specific listview you need something like https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_sosc_list_views.htm. Or you can pass view's Id as fcf parameter in the VF page's url.

Body:
This code works just fine for Contacts

<apex:page standardController="Contact" recordSetVar="contacts">
      <apex:pageBlock title="Contact Names">
        <apex:repeat value="{! contacts }" var="ct">

              <apex:outputLink value="{! URLFOR($Action.Contact.Edit, ct.Id) }"> {! ct.FirstName } </apex:outputLink>

        </apex:repeat>
      </apex:pageBlock>
</apex:page>

but almost identical code is not working for Accounts

<apex:page standardController="Account" recordSetVar="accounts">
    <apex:pageBlock title="Account Names">
             <apex:repeat value="{! accounts }" var="a">

                 <apex:outputLink value="{! URLFOR($Action.Account.Edit, a.Id) }">  {! a.Name}  </apex:outputLink>

        </apex:repeat>
    </apex:pageBlock>
</apex:page>

Why is this happeneing?


问:
Observed service module not included in jpackage
I use GluonHQ's backport of jpackager for the JDK 11, and running it with the --bind-services argument:

```<code>jpackager create-installer -o installer --name "Demo App" --class net.clementlevallois.monitor.Controller --module net.clementlevallois.monitor --module-path lib/ --add-modules net.clementlevallois.monitorobserver --bind-services --win-menu --win-shortcut --win-dir-chooser --strip-native-commands --singleton
</code>```

returns an installer but also throws :

```<code>Illegal argument [--bind-services]
</code>```

Is it me doing something wrong or is this backport of jpackager effectively not supporting this argument?
My app gets packaged with an installer and I can launch it, but indeed it is supposed to call a service and fails to do so. In this case, how could I package a modular application that includes ServiceProviders?

答: Why do you still use this ancient tooling? Instead you should use the new jpackage tool (note the spelling) which was released with JDK 14.</p>

Body:
I use GluonHQ's backport of jpackager for the JDK 11, and running it with the --bind-services argument:

jpackager create-installer -o installer --name "Demo App" --class net.clementlevallois.monitor.Controller --module net.clementlevallois.monitor --module-path lib/ --add-modules net.clementlevallois.monitorobserver --bind-services --win-menu --win-shortcut --win-dir-chooser --strip-native-commands --singleton

returns an installer but also throws :

Illegal argument [--bind-services]

Is it me doing something wrong or is this backport of jpackager effectively not supporting this argument?
My app gets packaged with an installer and I can launch it, but indeed it is supposed to call a service and fails to do so. In this case, how could I package a modular application that includes ServiceProviders?