问:
Why does this switch Statement not return anything when switching compilers from G++ to MSVC?
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}
</code>```

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}
</code>```

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?

答:
Return value

Your return statement in the first sample applies to the default case only since the execution of the switch block ends with a break statement in every other case.

In a non-default case, you leave the return value of your function uninitialized. MSVC does warn about that while debugging (see https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-use-native-run-time-checks for details) but GCC does not. This problem might be detected during compile time but you cannot rely on that.

The return statement added to the second sample is correct. You can remove the original one which becomes superfluous.

Braces

Notice that the braces inside the switch block are not necessary and introduce confusion here. They would be only useful if you created a local variable just to be used in a single case. Anyway, the braces should be indented more than the braces of the switch block. This part

```<code>}
return rtnValue;
}
</code>```

demonstrates the misleading indentation clearly. The indentation used in the second example is one of the good solutions to this problem.

Body:
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?

Body:
Return value

Your return statement in the first sample applies to the default case only since the execution of the switch block ends with a break statement in every other case.

In a non-default case, you leave the return value of your function uninitialized. MSVC does warn about that while debugging (see https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-use-native-run-time-checks for details) but GCC does not. This problem might be detected during compile time but you cannot rely on that.

The return statement added to the second sample is correct. You can remove the original one which becomes superfluous.

Braces

Notice that the braces inside the switch block are not necessary and introduce confusion here. They would be only useful if you created a local variable just to be used in a single case. Anyway, the braces should be indented more than the braces of the switch block. This part

}
return rtnValue;
}

demonstrates the misleading indentation clearly. The indentation used in the second example is one of the good solutions to this problem.


来源: stackexchange

问:
Perform hourly logrotate on JBoss EAP 7 access log
By default, JBoss EAP 7 rotates its access log daily.
I needed to set this to like, HOURLY.

Reason:

We have a script that automatically downloads the rotated access log file.

But doing this ^  would greatly increase CPU usage (because the access log at the end of the day is VERY large, and our system's performance is unfortunately reduced while downloading it)

What I know is that, in the standalone.xml, I've tried adding the one below to make the JBoss server log to rotate every hour.

```<code>    <suffix value=".yyyy-MM-dd-HH"/>
</code>```

But this method does not apply to access log (because its settings is weirdly placed in a different part of the standalone.xml)

I've tried experimenting with the access-log tags to have any of the following. But it just throws an error.

<access-log suffix=".yyyy-MM-dd-HH" ...

<access-log rotate="hourly" ...

...and i can't seem to find a VERY detailed guide about standalone.xml of JBoss EAP 7. I'm thinking that I should use a tag value for the access-log part.

Please help. Does anyone know of a way to do this? :(

System specs

Oracle Linux 6.9

JBoss EAP 7

Thanks and best regards.

答:
Try following</p>

```<code><subsystem xmlns="urn:jboss:domain:logging:3.0">
    ...(snip)...
    <!-- size-based log rotation -->
    <size-rotating-file-handler name="access-log" autoflush="true">
        <formatter>
            <named-formatter name="access-log-formatter"/>
        </formatter>
        <file relative-to="jboss.server.log.dir" path="access.log"/>
        <rotate-size value="10m"/>
        <max-backup-index value="10"/>
        <append value="true"/>
    </size-rotating-file-handler>
    <! -- or custom interval (hourly) log rotation
    <periodic-rotating-file-handler name="access-log-custom" autoflush="true">
        <formatter>
            <named-formatter name="access-log-formatter"/>
        </formatter>
        <file relative-to="jboss.server.log.dir" path="access.log"/>
        <suffix value=".yyyy-MM-dd-HH"/>
        <append value="true"/>
    </periodic-rotating-file-handler>
    --->
    ...(snip)...
    <logger category="io.undertow.accesslog" use-parent-handlers="false">
        <handlers>
            <handler name="access-log"/>
        </handlers>
    </logger>
    ...(snip)...
    <formatter name="access-log-formatter">
        <pattern-formatter pattern="%s%n"/>
    </formatter>
</subsystem>

...(snip)...

<subsystem xmlns="urn:jboss:domain:undertow:3.1" statistics-enabled="true">
    ...(snip)...
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https" record-request-start-time="true"/>
        <host name="default-host" alias="localhost">
            ...(snip)...
            <access-log use-server-log="true" pattern="%h %l %u %t "%r" %s %b "%{i,Referer}" "%{i,User-Agent}" "%{i,COOKIE}" "%{o,SET-COOKIE}" %S "%I" %T"/>
            ...(snip)...
        </host>
    </server>
    ...(snip)...
</subsystem>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
By default, JBoss EAP 7 rotates its access log daily.
I needed to set this to like, HOURLY.

Reason:

We have a script that automatically downloads the rotated access log file.

But doing this ^  would greatly increase CPU usage (because the access log at the end of the day is VERY large, and our system's performance is unfortunately reduced while downloading it)

What I know is that, in the standalone.xml, I've tried adding the one below to make the JBoss server log to rotate every hour.

    <suffix value=".yyyy-MM-dd-HH"/>

But this method does not apply to access log (because its settings is weirdly placed in a different part of the standalone.xml)

I've tried experimenting with the access-log tags to have any of the following. But it just throws an error.

<access-log suffix=".yyyy-MM-dd-HH" ...

<access-log rotate="hourly" ...

...and i can't seem to find a VERY detailed guide about standalone.xml of JBoss EAP 7. I'm thinking that I should use a tag value for the access-log part.

Please help. Does anyone know of a way to do this? :(

System specs

Oracle Linux 6.9

JBoss EAP 7

Thanks and best regards.

Body:
Try following

<subsystem xmlns="urn:jboss:domain:logging:3.0">
    ...(snip)...
    <!-- size-based log rotation -->
    <size-rotating-file-handler name="access-log" autoflush="true">
        <formatter>
            <named-formatter name="access-log-formatter"/>
        </formatter>
        <file relative-to="jboss.server.log.dir" path="access.log"/>
        <rotate-size value="10m"/>
        <max-backup-index value="10"/>
        <append value="true"/>
    </size-rotating-file-handler>
    <! -- or custom interval (hourly) log rotation
    <periodic-rotating-file-handler name="access-log-custom" autoflush="true">
        <formatter>
            <named-formatter name="access-log-formatter"/>
        </formatter>
        <file relative-to="jboss.server.log.dir" path="access.log"/>
        <suffix value=".yyyy-MM-dd-HH"/>
        <append value="true"/>
    </periodic-rotating-file-handler>
    --->
    ...(snip)...
    <logger category="io.undertow.accesslog" use-parent-handlers="false">
        <handlers>
            <handler name="access-log"/>
        </handlers>
    </logger>
    ...(snip)...
    <formatter name="access-log-formatter">
        <pattern-formatter pattern="%s%n"/>
    </formatter>
</subsystem>

...(snip)...

<subsystem xmlns="urn:jboss:domain:undertow:3.1" statistics-enabled="true">
    ...(snip)...
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https" record-request-start-time="true"/>
        <host name="default-host" alias="localhost">
            ...(snip)...
            <access-log use-server-log="true" pattern="%h %l %u %t &quot;%r&quot; %s %b &quot;%{i,Referer}&quot; &quot;%{i,User-Agent}&quot; &quot;%{i,COOKIE}&quot; &quot;%{o,SET-COOKIE}&quot; %S &quot;%I&quot; %T"/>
            ...(snip)...
        </host>
    </server>
    ...(snip)...
</subsystem>


问:
CSS Reset is not working on my machine but is working on codepen
I am using the CSS reset as shown below but however, it is not working.

HTML

```<code><!--Document type declaration-->
<!DOCTYPE html>

<head>
  <!--Linking to our CSS file-->
  <link rel="stylesheet" href="main.css">
  <!--Character encoding of the page-->
  <meta charset="utf-8">
  <title>Learning</title>
</head>

<body>
  <div class="introduction">
    <h1>H1 Text</h1>
    <h2>H2 Text</h2>
  </div>
</body>
</html>
</code>```

CSS

```<code><style>
/* CSS Reset */
* {
  margin: 0;
  padding: 0;
}

body {
  color: white;
}

.introduction {
  background-color: black;
}
</style>
</code>```

Updated Image

I am starting to doubt it's my machine because the CSS reset works on CodePen.

Thanks for looking into this silly question. If you need more information please don't hesitate to ask me.

Edit:
I have uploaded my code to Codepen and it is working fine. Added new screenshot.
https://codepen.io/anon/pen/xPBVLV

Added my HTML and CSS code.

Body:
I am using the CSS reset as shown below but however, it is not working.

HTML

<!DOCTYPE html>

  <link rel="stylesheet" href="main.css">

  <meta charset="utf-8">
  <title>Learning</title>

H1 Text

H2 Text

CSS

Updated Image

I am starting to doubt it's my machine because the CSS reset works on CodePen.

Thanks for looking into this silly question. If you need more information please don't hesitate to ask me.

Edit:
I have uploaded my code to Codepen and it is working fine. Added new screenshot.
https://codepen.io/anon/pen/xPBVLV

Added my HTML and CSS code.

Body:
I found the problem.

in CSS files I do not need to add <style>. I can just write my CSS code into the CSS file.

I am sorry everyone and especially @Quentin for looking into this silly mistake.


问:
How do you find the average of a dictionary?
So let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West']}
</code>```

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
</code>```

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

```<code>average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)
</code>```

I have tried many other ways too through online search and the common error I get is this:

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

答:
```<code> average = 0
 sum = 0
 for v in data.values():
      sum = sum + len(v)

 average = sum / len(data.keys())
</code>```

Body:
So let's say I have this dictionary

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'


问:
Camera orientation issue in Android
I am building an application that uses camera to take pictures. Here is my source code to do this:

```<code>File file = new File(Environment.getExternalStorageDirectory(),
            imageFileName);
imageFilePath = file.getPath();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, ACTIVITY_NATIVE_CAMERA_AQUIRE);
</code>```

On onActivityResult() method, I use BitmapFactory.decodeStream() to pickup the image.

When I run my application on Nexus one, it runs well. But when I run on Samsung Galaxy S or HTC Inspire 4G, the image's direction is not correct.

Capture with portrait mode, the real image (save on SD card) always rotates 90 degree.

Image preview after shot --------- Real image on SD card

Capture with landscape mode, all things are good.

Image preview after shot --------- Real image on SD card

答:
two One line solutions using Picasso and glide library

After spending a lot of time with a lot of solutions for image rotation problem I finally found two simple solutions. We don't need to do any additional works. Picasso and Glide are a very powerful library for handling images in your app includes. It will read image EXIF data and auto-rotates the images.

Using glide library  https://github.com/bumptech/glide

```<code>Glide.with(this).load("http url or sdcard url").into(imgageView);
</code>```

Using Picasso library https://github.com/square/picasso

```<code>Picasso.with(context).load("http url or sdcard url").into(imageView);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Camera orientation issue in Android

Body:
I am building an application that uses camera to take pictures. Here is my source code to do this:

File file = new File(Environment.getExternalStorageDirectory(),
            imageFileName);
imageFilePath = file.getPath();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, ACTIVITY_NATIVE_CAMERA_AQUIRE);

On onActivityResult() method, I use BitmapFactory.decodeStream() to pickup the image.

When I run my application on Nexus one, it runs well. But when I run on Samsung Galaxy S or HTC Inspire 4G, the image's direction is not correct.

Capture with portrait mode, the real image (save on SD card) always rotates 90 degree.

Image preview after shot --------- Real image on SD card

Capture with landscape mode, all things are good.

Image preview after shot --------- Real image on SD card

Body:
two One line solutions using Picasso and glide library

After spending a lot of time with a lot of solutions for image rotation problem I finally found two simple solutions. We don't need to do any additional works. Picasso and Glide are a very powerful library for handling images in your app includes. It will read image EXIF data and auto-rotates the images.

Using glide library  https://github.com/bumptech/glide

Glide.with(this).load("http url or sdcard url").into(imgageView);

Using Picasso library https://github.com/square/picasso

Picasso.with(context).load("http url or sdcard url").into(imageView);


问:
hide php page name in url
I have created a site with php and is working fine.I need to hide page urls like for example server.com/login/login.php(which is main page) should be seen as server.com/index

Other files like server.com/login/sqlserver.php,server.com/login/oracle.php,
server.com/login/mysql.php all should be visible like server.com/index.No page names should come.Please suggest how to do it.

I have seen editing the .htaccess file but it says only file extension be removed .I dont want other user to see any file names.

I am using XAMP 7.1

答:
You can do the same by using .htaccess.
Check the URL-htaccess</p>

Title: hide php page name in url


问:
Ionic 3 invalid css value in variables.scss file
I'm getting a weird error in my colors variable, my code:

```<code>$colors: (
  primary:    (base: #488aff, contrast:#000),
  secondary:  (base: #32db64, contrast:#000),
  danger:     (base: #f53d3d, contrast:#000),
  light:      (base: #f4f4f4, contrast:#000),
  dark:       (base: #222, contrast:#000),
  font:        (base: #fe5295, contrast:#000)
);
</code>```

the error I'm getting

```<code>(primary: (base: #488aff, contrast: #000), secondary: (base: #32db64, contrast: #000), danger: (base: #f53d3d, contrast: #000), light: (base: #f4f4f4, contrast: #000), dark: (base: #222, contrast: #000), font: (base: #fe5295, contrast: #000)) isn't a valid CSS value.
</code>```

My setup:

```<code>    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 6.4.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : android 6.2.3 ios 4.4.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v6.9.2
    npm  : 5.5.1
    OS   : Windows 10
</code>```

Any ideas about what might be the issue?

答: Although the error was coming from variables.scss file, actually it was appearing because a npm library called ion2-calendar, once I removed it from my code everything went back to normal!

Body:
I'm getting a weird error in my colors variable, my code:

$colors: (
  primary:    (base: #488aff, contrast:#000),
  secondary:  (base: #32db64, contrast:#000),
  danger:     (base: #f53d3d, contrast:#000),
  light:      (base: #f4f4f4, contrast:#000),
  dark:       (base: #222, contrast:#000),
  font:        (base: #fe5295, contrast:#000)
);

the error I'm getting

(primary: (base: #488aff, contrast: #000), secondary: (base: #32db64, contrast: #000), danger: (base: #f53d3d, contrast: #000), light: (base: #f4f4f4, contrast: #000), dark: (base: #222, contrast: #000), font: (base: #fe5295, contrast: #000)) isn't a valid CSS value.

My setup:

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 6.4.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : android 6.2.3 ios 4.4.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v6.9.2
    npm  : 5.5.1
    OS   : Windows 10

Any ideas about what might be the issue?


答:
Taking "average" as "the average number of items in the lists", you can achieve it as:

```<code>average_length = sum( len(v) for v in data.values() ) / len(data)
</code>```

The first part adds together the length of all the lists you have as dictionary values, while len(data) is the number of key:value pair you have in the dictionary.

Title: How do you find the average of a dictionary?

Body:
Taking "average" as "the average number of items in the lists", you can achieve it as:

average_length = sum( len(v) for v in data.values() ) / len(data)

The first part adds together the length of all the lists you have as dictionary values, while len(data) is the number of key:value pair you have in the dictionary.


问:
django NOT NULL constraint failed error
I am having an error in the form django.db.utils.IntegrityError: NOT NULL constraint failed:

in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team.

I am getting that error when trying to assign an existing user in the data base

here is my code :

```<code>def TeamRegister2(request):
    #import pdb; pdb.set_trace()
    InviteFormSet = formset_factory(InviteForm2)

    if request.method == 'POST':
        formset = InviteFormSet(request.POST)

        if(formset.is_valid()):
            for i in formset:
                mail = i.cleaned_data['Email']
                if MyUser.objects.filter(email = mail).exists():
                    user = MyUser(email = mail)
                    u1 = user.id # get user ID
                    a1 = MyUser.objects.get(email = request.user.email) #get user email
                    a2 = Project.objects.filter(project_hr_admin = a1)  #get all project created by the user
                    a3 = a2.latest('id') # extract the last project
                    a4 = a3.team_id # extract the team linked to the project
                    a4.members.add(u1) # add the member to the team

                    invited_user = MyUser.objects.get(email = mail)
                    current_site = get_current_site(request)
                    message = render_to_string('acc_join_email.html', {
                        'user': invited_user.first_name,
                        'domain':current_site.domain,
                        })
                    mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
                    to_email = mail
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                else:
                    user = MyUser(email = mail)
                    password = MyUser.objects.make_random_password()
                    user.set_password(password)
                    user.is_active = False
                    user.is_employee = True
                    user.save()
                    u1 = user.id #get user id
                    a1 = MyUser.objects.get(email = request.user.email) #get user email
                    a2 = Project.objects.filter(project_hr_admin = a1)  #get all project created by the user
                    a3 = a2.latest('id') # extract the last project
                    a4 = a3.team_id # extract the team linked to the project
                    a4.members.add(u1) # add the member to the team

                    current_site = get_current_site(request)
                    message = render_to_string('acc_active_email.html', {
                    'user':user,
                    'domain':current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                    })
                    mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
                    to_email = user.email
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
            messages.success(request, 'testouille la fripouille')
            return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':a3.id}))
        else:
            print("The entered form is not valid")

    else:
        formset = InviteFormSet()
    return render(request,'team_register.html', {'formset':formset})
</code>```

MyUser Model:

```<code>class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=150, blank=True, null=True)
    last_name = models.CharField(max_length=150, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_hr = models.BooleanField(default=False)
    is_candidate = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)
    company = models.CharField(max_length=100, blank=True, null=True)
</code>```

Team model:

```<code>class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

def __str__(self):
    return self.team_name
</code>```

Project models:

```<code>class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
    candidat_answers = models.ManyToManyField('survey.response')
</code>```

any idea how to fix that error and add the user to the team ?
thx you ;)

traceback:

```<code>File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: website_team_members.myuser_id) was the direct cause of the following exception:

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/raphaelbendenoun/Documents/Django Projects/Authentication_project/registration/views.py" in TeamRegister2
  85.                     a4.members.add(u1) # add the member to the team

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in add
  934.                 self._add_items(self.source_field_name, self.target_field_name, *objs)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
  1103.                         for obj_id in new_ids

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in bulk_create
  443.                 ids = self._batched_insert(objs_without_pk, fields, batch_size)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _batched_insert
  1099.                 self._insert(item, fields=fields, using=self.db)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _insert
  1076.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1107.                 cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /registration/auth_team_register3/
Exception Value: NOT NULL constraint failed: website_team_members.myuser_id
</code>```

答:
You are trying to add an unsaved MyUser instance to the manytomany field. You have to get the object instead of creating a new object.

```<code>user = MyUser.objects.get(email=mail)
a4.members.add(user)
</code>```

Title: django NOT NULL constraint failed error

Body:
I am having an error in the form django.db.utils.IntegrityError: NOT NULL constraint failed:

in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team.

I am getting that error when trying to assign an existing user in the data base

here is my code :

def TeamRegister2(request):
    #import pdb; pdb.set_trace()
    InviteFormSet = formset_factory(InviteForm2)

    if request.method == 'POST':
        formset = InviteFormSet(request.POST)

        if(formset.is_valid()):
            for i in formset:
                mail = i.cleaned_data['Email']
                if MyUser.objects.filter(email = mail).exists():
                    user = MyUser(email = mail)
                    u1 = user.id # get user ID
                    a1 = MyUser.objects.get(email = request.user.email) #get user email
                    a2 = Project.objects.filter(project_hr_admin = a1)  #get all project created by the user
                    a3 = a2.latest('id') # extract the last project
                    a4 = a3.team_id # extract the team linked to the project
                    a4.members.add(u1) # add the member to the team

                    invited_user = MyUser.objects.get(email = mail)
                    current_site = get_current_site(request)
                    message = render_to_string('acc_join_email.html', {
                        'user': invited_user.first_name,
                        'domain':current_site.domain,
                        })
                    mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
                    to_email = mail
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                else:
                    user = MyUser(email = mail)
                    password = MyUser.objects.make_random_password()
                    user.set_password(password)
                    user.is_active = False
                    user.is_employee = True
                    user.save()
                    u1 = user.id #get user id
                    a1 = MyUser.objects.get(email = request.user.email) #get user email
                    a2 = Project.objects.filter(project_hr_admin = a1)  #get all project created by the user
                    a3 = a2.latest('id') # extract the last project
                    a4 = a3.team_id # extract the team linked to the project
                    a4.members.add(u1) # add the member to the team

                    current_site = get_current_site(request)
                    message = render_to_string('acc_active_email.html', {
                    'user':user,
                    'domain':current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                    })
                    mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
                    to_email = user.email
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
            messages.success(request, 'testouille la fripouille')
            return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':a3.id}))
        else:
            print("The entered form is not valid")

    else:
        formset = InviteFormSet()
    return render(request,'team_register.html', {'formset':formset})

MyUser Model:

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=150, blank=True, null=True)
    last_name = models.CharField(max_length=150, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_hr = models.BooleanField(default=False)
    is_candidate = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)
    company = models.CharField(max_length=100, blank=True, null=True)

Team model:

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

def __str__(self):
    return self.team_name

Project models:

class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
    candidat_answers = models.ManyToManyField('survey.response')

any idea how to fix that error and add the user to the team ?
thx you ;)

traceback:

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: website_team_members.myuser_id) was the direct cause of the following exception:

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/raphaelbendenoun/Documents/Django Projects/Authentication_project/registration/views.py" in TeamRegister2
  85.                     a4.members.add(u1) # add the member to the team

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in add
  934.                 self._add_items(self.source_field_name, self.target_field_name, *objs)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
  1103.                         for obj_id in new_ids

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in bulk_create
  443.                 ids = self._batched_insert(objs_without_pk, fields, batch_size)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _batched_insert
  1099.                 self._insert(item, fields=fields, using=self.db)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _insert
  1076.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1107.                 cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /registration/auth_team_register3/
Exception Value: NOT NULL constraint failed: website_team_members.myuser_id

Body:
You are trying to add an unsaved MyUser instance to the manytomany field. You have to get the object instead of creating a new object.

user = MyUser.objects.get(email=mail)
a4.members.add(user)


问:
Best IoT Database?
I have many IoT devices sending data currently to MySQL Database.

I want to port it to some other Database, which will be Open Source and provide me with:

JSON support

Scalability

Flexibility to add multiple columns automatically as per payload

Python and PHP Support

Extremely Fast Read, Write

Ability to export at least 6 months of data in CSV format

Please revert back soon.
Any help will be appreciated.

Thanks

答: Why do you want to move away from MySQL?  It is open source and can meet all of the criteria you listed above.  This is a very subjective question so it's hard to give a good answer, but MySQL is not a bad option</p>

Title: Best IoT Database?


问:
How to store a date from server in UTC format in realm DB (date from server is also in UTC)
The date from server is 2017-12-04T16:30:00+00:00
the date which i converted using format "dd/MM/yyyy hh:mm:ss a" is 04/12/2017 04:40:00 PM.

答:
You can use this. I use it as an extension. You can just modify the format as you want it.</p>

```<code>extension Formatter {
static let iso8601: DateFormatter = {
    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.locale = Locale.current
    formatter.timeZone = TimeZone(secondsFromGMT: 0)

    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    return formatter
}()}
</code>```

Body:
You can use this. I use it as an extension. You can just modify the format as you want it.

extension Formatter {
static let iso8601: DateFormatter = {
    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.locale = Locale.current
    formatter.timeZone = TimeZone(secondsFromGMT: 0)

    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    return formatter
}()}


问:
Can Django's ORM output the SQL query it is using?
I know that you can output the SQL to see tables that are created. Is it possible for Django to output the sql used for any query like:

```<code>Protocols.objects.filter(active=False)
</code>```

?  I couldn't find this in the docs, so hopefully someone can point them to me, if in fact Django can do this.

答:
See Django FAQ: How can I see the raw SQL queries Django is running?:</p>
```<code>>>> from django.db import connection
>>> connection.queries = []
>>> Protocols.objects.filter(active=False)
>>> print(connection.queries)
</code>```

Body:
I know that you can output the SQL to see tables that are created. Is it possible for Django to output the sql used for any query like:

Protocols.objects.filter(active=False)

?  I couldn't find this in the docs, so hopefully someone can point them to me, if in fact Django can do this.

Body:
See Django FAQ: How can I see the raw SQL queries Django is running?:

>>> from django.db import connection
>>> connection.queries = []
>>> Protocols.objects.filter(active=False)
>>> print(connection.queries)


问:
Read multi-index on the columns from csv file
I have a .csv file that looks like this:

```<code>Male, Male, Male, Female, Female
R, R, L, R, R
.86, .67, .88, .78, .81
</code>```

I want to read that into a df, so that I have:

```<code>    Male        Female
    R       L   R
0   .86 .67 .88 .78 .81
</code>```

I did:

```<code>df = pd.read_csv('file.csv', header=[0,1])
</code>```

But headers does not cut it. Which results in

```<code>Empty DataFrame
Columns: [(Male, R), (Male, R), (Male, L), (Female, R), (Female, R)]
Index: []
</code>```

Yet, the docs on headers says:

```<code>(...)Can be a list of integers that specify row
locations for a multi-index on the columns E.g. [0,1,3]
</code>```

What am I doing wrong? How can I possibly make it work?

答: As of version 0.21 of pandas, MultiIndexes are created by default so df = pd.read_csv('file.csv', header=[0,1]) should do the job.

Body:
I have a .csv file that looks like this:

Male, Male, Male, Female, Female
R, R, L, R, R
.86, .67, .88, .78, .81

I want to read that into a df, so that I have:

    Male        Female
    R       L   R
0   .86 .67 .88 .78 .81

I did:

df = pd.read_csv('file.csv', header=[0,1])

But headers does not cut it. Which results in

Empty DataFrame
Columns: [(Male, R), (Male, R), (Male, L), (Female, R), (Female, R)]
Index: []

Yet, the docs on headers says:

(...)Can be a list of integers that specify row
locations for a multi-index on the columns E.g. [0,1,3]

What am I doing wrong? How can I possibly make it work?


问:
How to store structured square grid data suitable for paraview?
I have some data like this

```<code>i  j  Rho  ux   vy
1  1  1.0  0    1.5
2  1  1.0  0.1  1
...
</code>```

These numbers are center of cells coordinates (i and j) and other property values of that cell.
all cells are in the same size and are square.
how can I save my data so it can be read by Paraview?
Thank you for your attention.

答:
I think that you could develop a ParaView writer converting your data into a VTK compatible format. Regarding the kind of cells you have, I suggest the .vti format specialized for vtkImageData for example.

The first step would be to transform the coordinates of center of cells into coordinates of points. Assuming s is the size of the cell and (i,j) the coordinates of its center :

```<code>// using d for visiblity
d = s/2

// the embedding is in the plane, the value of z is arbitrary
z = 0

// list of points for one cell
p0 = (i-d, j-d, z)
p1 = (i-d, j+d, z)
p2 = (i+d, j-d, z)
p3 = (i+d, j+d, z)
</code>```

I used pseudo-code as you did not specify a language in particular. With this transformation, keep in mind that you should avoid duplicated points as connected cells shared common points.

Then the second step is to add the property values as scalar or vector fields (see vtkDataArray) associated on the cells (see vtkCellData).

Body:
I have some data like this

i  j  Rho  ux   vy
1  1  1.0  0    1.5
2  1  1.0  0.1  1
...

These numbers are center of cells coordinates (i and j) and other property values of that cell.
all cells are in the same size and are square.
how can I save my data so it can be read by Paraview?
Thank you for your attention.

Body:
I think that you could develop a ParaView writer converting your data into a VTK compatible format. Regarding the kind of cells you have, I suggest the .vti format specialized for vtkImageData for example.

The first step would be to transform the coordinates of center of cells into coordinates of points. Assuming s is the size of the cell and (i,j) the coordinates of its center :

// using d for visiblity
d = s/2

// the embedding is in the plane, the value of z is arbitrary
z = 0

// list of points for one cell
p0 = (i-d, j-d, z)
p1 = (i-d, j+d, z)
p2 = (i+d, j-d, z)
p3 = (i+d, j+d, z)

I used pseudo-code as you did not specify a language in particular. With this transformation, keep in mind that you should avoid duplicated points as connected cells shared common points.

Then the second step is to add the property values as scalar or vector fields (see vtkDataArray) associated on the cells (see vtkCellData).


问:
Splitting an array dynamically based on values using Javascript/jQuery

I'm trying to find an easier way of splitting an array dynamically based on values of an inner array within a JSON object.

Assume that I am receiving said data from OpenWeatherAPI:

 var jsonData={
    "cod":"200",
    "message":0.0895,
    "cnt":5,
    "list":[
      {
         "dt":1512388800,
         "main":{
            "temp":301.9,
            "temp_min":299.858,
            "temp_max":301.9,
            "pressure":1017.53,
            "sea_level":1020.58,
            "grnd_level":1017.53,
            "humidity":98,
            "temp_kf":2.04
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":80
         },
         "wind":{
            "speed":2.36,
            "deg":161.003
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 12:00:00"
      },
      {
         "dt":1512399600,
         "main":{
            "temp":300.75,
            "temp_min":299.389,
            "temp_max":300.75,
            "pressure":1019.04,
            "sea_level":1022.09,
            "grnd_level":1019.04,
            "humidity":100,
            "temp_kf":1.36
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":2.04,
            "deg":133.002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 15:00:00"
      },
      {
         "dt":1512410400,
         "main":{
            "temp":299.41,
            "temp_min":298.726,
            "temp_max":299.41,
            "pressure":1017.89,
            "sea_level":1020.93,
            "grnd_level":1017.89,
            "humidity":100,
            "temp_kf":0.68
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.08,
            "deg":108.001
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 18:00:00"
      },
      {
         "dt":1512421200,
         "main":{
            "temp":298.19,
            "temp_min":298.19,
            "temp_max":298.19,
            "pressure":1017.39,
            "sea_level":1020.45,
            "grnd_level":1017.39,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.26,
            "deg":94.0002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 21:00:00"
      },
      {
         "dt":1512432000,
         "main":{
            "temp":298.444,
            "temp_min":298.444,
            "temp_max":298.444,
            "pressure":1019.32,
            "sea_level":1022.39,
            "grnd_level":1019.32,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{
            "all":20
         },
         "wind":{
            "speed":2.5,
            "deg":89.0016
         },
         "rain":{

         },
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2017-12-05 00:00:00"
      }
    ],
    "city":{
      "id":1735158,
      "name":"Petaling Jaya",
      "coord":{
         "lat":3.1073,
         "lon":101.6067
      },
      "country":"MY"
     }
    }

 $.each(jsonData['list'], function(index, value) {

              $.each(value, function(index, value){
                if(index == 'dt_txt')
                {
                    var regExDate = new RegExp('^.{0,10}');
                    value = regExDate.exec(value).toString();
                    console.log(value);
                }
              });
     });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

How do I iterate the elements in list to split based on dt_txt?

This is pretty much as far as I got to manually convert the dates into YYYY-MM-DD format but I'm still struggling to make a dynamic array based out of the results that I'm getting:

Result:

EDIT #1:

The end result I'm looking for should look something like this:

```<code>var array20171204 = [{"dt":1512388800,"main":{"temp":301.9,"temp_min":299.858,"temp_max":301.9,"pressure":1017.53,"sea_level":1020.58,"grnd_level":1017.53,"humidity":98,"temp_kf":2.04},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":80},"wind":{"speed":2.36,"deg":161.003},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 12:00:00"},{"dt":1512399600,"main":{"temp":300.75,"temp_min":299.389,"temp_max":300.75,"pressure":1019.04,"sea_level":1022.09,"grnd_level":1019.04,"humidity":100,"temp_kf":1.36},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":68},"wind":{"speed":2.04,"deg":133.002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 15:00:00"},{"dt":1512410400,"main":{"temp":299.41,"temp_min":298.726,"temp_max":299.41,"pressure":1017.89,"sea_level":1020.93,"grnd_level":1017.89,"humidity":100,"temp_kf":0.68},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.08,"deg":108.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 18:00:00"},{"dt":1512421200,"main":{"temp":298.19,"temp_min":298.19,"temp_max":298.19,"pressure":1017.39,"sea_level":1020.45,"grnd_level":1017.39,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.26,"deg":94.0002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 21:00:00"}];

var array20171205 = [{"dt":1512432000,"main":{"temp":298.444,"temp_min":298.444,"temp_max":298.444,"pressure":1019.32,"sea_level":1022.39,"grnd_level":1019.32,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"clouds":{"all":20},"wind":{"speed":2.5,"deg":89.0016},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-05 00:00:00"}];
</code>```

Body:
I'm trying to find an easier way of splitting an array dynamically based on values of an inner array within a JSON object.

Assume that I am receiving said data from OpenWeatherAPI:

 var jsonData={
    "cod":"200",
    "message":0.0895,
    "cnt":5,
    "list":[
      {
         "dt":1512388800,
         "main":{
            "temp":301.9,
            "temp_min":299.858,
            "temp_max":301.9,
            "pressure":1017.53,
            "sea_level":1020.58,
            "grnd_level":1017.53,
            "humidity":98,
            "temp_kf":2.04
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":80
         },
         "wind":{
            "speed":2.36,
            "deg":161.003
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 12:00:00"
      },
      {
         "dt":1512399600,
         "main":{
            "temp":300.75,
            "temp_min":299.389,
            "temp_max":300.75,
            "pressure":1019.04,
            "sea_level":1022.09,
            "grnd_level":1019.04,
            "humidity":100,
            "temp_kf":1.36
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":2.04,
            "deg":133.002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 15:00:00"
      },
      {
         "dt":1512410400,
         "main":{
            "temp":299.41,
            "temp_min":298.726,
            "temp_max":299.41,
            "pressure":1017.89,
            "sea_level":1020.93,
            "grnd_level":1017.89,
            "humidity":100,
            "temp_kf":0.68
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.08,
            "deg":108.001
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 18:00:00"
      },
      {
         "dt":1512421200,
         "main":{
            "temp":298.19,
            "temp_min":298.19,
            "temp_max":298.19,
            "pressure":1017.39,
            "sea_level":1020.45,
            "grnd_level":1017.39,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.26,
            "deg":94.0002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 21:00:00"
      },
      {
         "dt":1512432000,
         "main":{
            "temp":298.444,
            "temp_min":298.444,
            "temp_max":298.444,
            "pressure":1019.32,
            "sea_level":1022.39,
            "grnd_level":1019.32,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{
            "all":20
         },
         "wind":{
            "speed":2.5,
            "deg":89.0016
         },
         "rain":{

         },
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2017-12-05 00:00:00"
      }
    ],
    "city":{
      "id":1735158,
      "name":"Petaling Jaya",
      "coord":{
         "lat":3.1073,
         "lon":101.6067
      },
      "country":"MY"
     }
    }

 $.each(jsonData['list'], function(index, value) {

              $.each(value, function(index, value){
                if(index == 'dt_txt')
                {
                    var regExDate = new RegExp('^.{0,10}');
                    value = regExDate.exec(value).toString();
                    console.log(value);
                }
              });
     });

How do I iterate the elements in list to split based on dt_txt?

This is pretty much as far as I got to manually convert the dates into YYYY-MM-DD format but I'm still struggling to make a dynamic array based out of the results that I'm getting:

Result:

EDIT #1:

The end result I'm looking for should look something like this:

var array20171204 = [{"dt":1512388800,"main":{"temp":301.9,"temp_min":299.858,"temp_max":301.9,"pressure":1017.53,"sea_level":1020.58,"grnd_level":1017.53,"humidity":98,"temp_kf":2.04},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":80},"wind":{"speed":2.36,"deg":161.003},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 12:00:00"},{"dt":1512399600,"main":{"temp":300.75,"temp_min":299.389,"temp_max":300.75,"pressure":1019.04,"sea_level":1022.09,"grnd_level":1019.04,"humidity":100,"temp_kf":1.36},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":68},"wind":{"speed":2.04,"deg":133.002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 15:00:00"},{"dt":1512410400,"main":{"temp":299.41,"temp_min":298.726,"temp_max":299.41,"pressure":1017.89,"sea_level":1020.93,"grnd_level":1017.89,"humidity":100,"temp_kf":0.68},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.08,"deg":108.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 18:00:00"},{"dt":1512421200,"main":{"temp":298.19,"temp_min":298.19,"temp_max":298.19,"pressure":1017.39,"sea_level":1020.45,"grnd_level":1017.39,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.26,"deg":94.0002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 21:00:00"}];

var array20171205 = [{"dt":1512432000,"main":{"temp":298.444,"temp_min":298.444,"temp_max":298.444,"pressure":1019.32,"sea_level":1022.39,"grnd_level":1019.32,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"clouds":{"all":20},"wind":{"speed":2.5,"deg":89.0016},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-05 00:00:00"}];

Body:
I couldnt create dynamic variable name; besides that this code does handles the other aspects;

var jsonData={
    "cod":"200",
    "message":0.0895,
    "cnt":5,
    "list":[
      {
         "dt":1512388800,
         "main":{
            "temp":301.9,
            "temp_min":299.858,
            "temp_max":301.9,
            "pressure":1017.53,
            "sea_level":1020.58,
            "grnd_level":1017.53,
            "humidity":98,
            "temp_kf":2.04
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":80
         },
         "wind":{
            "speed":2.36,
            "deg":161.003
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 12:00:00"
      },
      {
         "dt":1512399600,
         "main":{
            "temp":300.75,
            "temp_min":299.389,
            "temp_max":300.75,
            "pressure":1019.04,
            "sea_level":1022.09,
            "grnd_level":1019.04,
            "humidity":100,
            "temp_kf":1.36
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":2.04,
            "deg":133.002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 15:00:00"
      },
      {
         "dt":1512410400,
         "main":{
            "temp":299.41,
            "temp_min":298.726,
            "temp_max":299.41,
            "pressure":1017.89,
            "sea_level":1020.93,
            "grnd_level":1017.89,
            "humidity":100,
            "temp_kf":0.68
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.08,
            "deg":108.001
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 18:00:00"
      },
      {
         "dt":1512421200,
         "main":{
            "temp":298.19,
            "temp_min":298.19,
            "temp_max":298.19,
            "pressure":1017.39,
            "sea_level":1020.45,
            "grnd_level":1017.39,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.26,
            "deg":94.0002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 21:00:00"
      },
      {
         "dt":1512432000,
         "main":{
            "temp":298.444,
            "temp_min":298.444,
            "temp_max":298.444,
            "pressure":1019.32,
            "sea_level":1022.39,
            "grnd_level":1019.32,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{
            "all":20
         },
         "wind":{
            "speed":2.5,
            "deg":89.0016
         },
         "rain":{

         },
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2017-12-05 00:00:00"
      }
    ],
    "city":{
      "id":1735158,
      "name":"Petaling Jaya",
      "coord":{
         "lat":3.1073,
         "lon":101.6067
      },
      "country":"MY"
     }
    }

let dtArray = [];
jsonData["list"].map((obj) => {
   let dt = obj["dt_txt"].split(" ")[0]
   if(dtArray.indexOf(dt) == -1) {
      dtArray.push(dt)
   }
});
let tempArray;
for(i=0 ;i<dtArray.length; i++) {
   //let array+str(date) = [];
   tempArray = [];
   jsonData["list"].map((obj) => {
      if(dtArray[i] == obj["dt_txt"].split(" ")[0]) {
         tempArray.push(obj)
      }
   });
   console.log(tempArray)
}


问:
Is it possible to install scipy under pypy?
I created a virtualenv with pypy and tried to install scipy, but installation ended with the following error:

distutils.errors.DistutilsError: Setup script exited with error: Command "cc -O2 -fPIC -Wimplicit -O2 -fPIC -Wimplicit -O2 -fPIC -Wimplicit -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=1 -DHAVE_CBLAS -Ibuild/src.linux-x86_64-3.2/numpy/core/src/private -Inumpy/core/include -Ibuild/src.linux-x86_64-3.2/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/home/luke/Programowanie/Python/connect4/venv-pypy/include -Ibuild/src.linux-x86_64-3.2/numpy/core/src/private -Ibuild/src.linux-x86_64-3.2/numpy/core/src/private -Ibuild/src.linux-x86_64-3.2/numpy/core/src/private -c numpy/core/src/multiarray/scalarapi.c -o build/temp.linux-x86_64-3.2/numpy/core/src/multiarray/scalarapi.o" failed with exit status 1

There is a specific numpy version suited for pypy, but the only thing I found about scipy is an old call for donations. Has anything changed since then?

答:
No, but miraculously, matplotlib happens to work with pypy, both in jupyter notebook and as a standalone version (through wx widgets).

So it isn't that impossible.


问:
How does NuGet contentFiles work?
I'm trying to create a nuget package with content which work with different kinds of projects.

TestSource.nuspec look like this:

    <contentFiles>
      <files include="cs\any\TestSource.cs" buildAction="Compile" />
    </contentFiles>
  </metadata>
  <files>
    <file src="TestFolder\TestSource.cs" target="content/TestFolder" />
  </files>

(the file is available both as contentFiles\cs\any\TestSource.cs and TestFolder\TestSource.cs)

The created package works fine in a "normal" project but nothing happens in a packagereference project.

I assume I'm missing something simple

答:
Found this out myself.

You need to add the file twice in the files section

```<code>  <contentFiles>
    <files include="cs\any\TestSource.cs" buildAction="Compile" />
  </contentFiles>
</metadata>
<files>
  <file src="TestFolder\TestSource.cs" target="content/TestFolder" />
  <file src="TestFolder\TestSource.cs" target="contentFiles/cs/any" />
</files>
</code>```

The package will then work for both normal and packagereference projects.

Title: How does NuGet contentFiles work?

Body:
Found this out myself.

You need to add the file twice in the files section

  <contentFiles>
    <files include="cs\any\TestSource.cs" buildAction="Compile" />
  </contentFiles>
</metadata>
<files>
  <file src="TestFolder\TestSource.cs" target="content/TestFolder" />
  <file src="TestFolder\TestSource.cs" target="contentFiles/cs/any" />
</files>

The package will then work for both normal and packagereference projects.


问:
Write image downloaded in the media content
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks

答:
For TargetSDK 23 or higher, you need to give runtime permission As per Android's guideline. Check this link for code snippet and more description.

https://developer.android.com/training/permissions/requesting.html

Body:
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks


答:
Use simple for loop

```<code>var= {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler':
['Johnny Depp', 'Tom Hanks']}

sum = 0
for value in var.values():
    sum = len(value)+sum

Average = sum/len(var)
print(Average)
</code>```

Output

```<code>2.0
</code>```

Body:
So let's say I have this dictionary

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Body:
Use simple for loop

var= {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler':
['Johnny Depp', 'Tom Hanks']}

sum = 0
for value in var.values():
    sum = len(value)+sum

Average = sum/len(var)
print(Average)

Output

2.0


问:
How to check the text that is already in RecyclerView or not
```<code>public class ChatsFragment extends Fragment {
    public static final String TITLE = "Chats";

FirebaseDatabase database;
DatabaseReference myRef;
List<Listdata> list;
RecyclerView recyclerview;

public static ChatsFragment newInstance() {

    return new ChatsFragment();
}

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                Listdata listdata = new Listdata();
                String name = userdetails.getName();
                String message = userdetails.getMessage();
                listdata.setName(name);
                listdata.setMessage(message);
                list.add(listdata);

            }

            RecyclerviewAdapter recycler = new RecyclerviewAdapter(list);
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

        @Override
        public void onCancelled(DatabaseError error) {

        }
    });

    return view;
}
}
</code>```

I have a recycler CardView with a list of names.The names sent by the firebase database. When I sent the same name twice it shows count 2.I want to check a name that is already listed or not. If the name is already in RecyclerView I want to show the count 2. How to check the name list and show the count.

答:
public class ChatsFragment extends Fragment {

```<code>FirebaseDatabase database;
DatabaseReference myRef;
List<ListData> list;
RecyclerView recyclerview;
HashMap<String,String> hashMap;

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
                       for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message)) {

                        hashMap.remove(name);
                        hashMap.put(name + "-2", message);
                    }
                } else
                    hashMap.put(name, message);

            }

            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

        @Override
        public void onCancelled(DatabaseError error) {

        }
    });

    return view;
}
private ArrayList<ListData> convertHashToObjectList(HashMap<String, String> chatHashmap){

    ArrayList<ListData> listData = new ArrayList<>();
    for(Map.Entry<String, String> entry: chatHashmap.entrySet()) {
        listData.add(new ListData(entry.getKey(),entry.getValue()));
    }

    return listData;

}
</code>```

}

This the Answer given by @ankit. Thank you for your solution.

Body:
public class ChatsFragment extends Fragment {
    public static final String TITLE = "Chats";

FirebaseDatabase database;
DatabaseReference myRef;
List<Listdata> list;
RecyclerView recyclerview;

public static ChatsFragment newInstance() {

    return new ChatsFragment();
}

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                Listdata listdata = new Listdata();
                String name = userdetails.getName();
                String message = userdetails.getMessage();
                listdata.setName(name);
                listdata.setMessage(message);
                list.add(listdata);

            }

            RecyclerviewAdapter recycler = new RecyclerviewAdapter(list);
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

        @Override
        public void onCancelled(DatabaseError error) {

        }
    });

    return view;
}
}

I have a recycler CardView with a list of names.The names sent by the firebase database. When I sent the same name twice it shows count 2.I want to check a name that is already listed or not. If the name is already in RecyclerView I want to show the count 2. How to check the name list and show the count.

Body:
public class ChatsFragment extends Fragment {

FirebaseDatabase database;
DatabaseReference myRef;
List<ListData> list;
RecyclerView recyclerview;
HashMap<String,String> hashMap;

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
                       for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message)) {

                        hashMap.remove(name);
                        hashMap.put(name + "-2", message);
                    }
                } else
                    hashMap.put(name, message);

            }

            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

        @Override
        public void onCancelled(DatabaseError error) {

        }
    });

    return view;
}
private ArrayList<ListData> convertHashToObjectList(HashMap<String, String> chatHashmap){

    ArrayList<ListData> listData = new ArrayList<>();
    for(Map.Entry<String, String> entry: chatHashmap.entrySet()) {
        listData.add(new ListData(entry.getKey(),entry.getValue()));
    }

    return listData;

}

}

This the Answer given by @ankit. Thank you for your solution.


问:
How do I assign a value, to a 2D array location in C?
So I'm quite a newbie, so please go soft.

I have created a 2D array, 60x30 and want to display it on the screen as a grid, by doing a double for loop. I am using a simple character '.' for each slot of the grid just for a test.

```<code>char FrameBuffer[29][59];
for (int i = 0; i <= 29; i++)
{
    for (int j = 0; j <= 59; j++)
    {
        FrameBuffer[i, j] = '.';
        printf("%c ", FrameBuffer[i,j]);
    }
    printf("\n");
}
</code>```

However, whenever I try and assign a value to a position in my 2D array, e.g.

```<code>FrameBuffer[0,1] = '.',
</code>```

I am greeted with an error:

```<code>Expression must be a modifiable lvalue
</code>```

答:
FrameBuffer[29][59] This is a 29x59 array, you need a 30x60.

Please don't mix up array declarations with array indexing. Array declarations are fully sane; if you need 30x60 then you type FrameBuffer[30][60]. When you access the array however, you start at index 0.

Simply change the code to:

```<code>char FrameBuffer[30][60];
for (int i = 0; i < 30; i++)
{
  for (int j = 0; j < 60; j++)
  {
    FrameBuffer[i][j] = '.'; // note the correct syntax here
</code>```

EDIT

As a curious side-effect, FrameBuffer[i, j] is interpreted as something entirely different than intended. The comma here is regarded as the comma operator, a special kind of operator which evaluates the left expression i, then the right expression j, then returns j.

Meaning that the code ended up completely equivalent to FrameBuffer[j] = '.'. Where FrameBuffer[j] is a whole array, not a char. You can't assign a value to an array this way, an array is not a "lvalue", which explains the compiler error text.

Body:
So I'm quite a newbie, so please go soft.

I have created a 2D array, 60x30 and want to display it on the screen as a grid, by doing a double for loop. I am using a simple character '.' for each slot of the grid just for a test.

char FrameBuffer[29][59];
for (int i = 0; i <= 29; i++)
{
    for (int j = 0; j <= 59; j++)
    {
        FrameBuffer[i, j] = '.';
        printf("%c ", FrameBuffer[i,j]);
    }
    printf("\n");
}

However, whenever I try and assign a value to a position in my 2D array, e.g.

FrameBuffer[0,1] = '.',

I am greeted with an error:

Expression must be a modifiable lvalue

Body:
FrameBuffer[29][59] This is a 29x59 array, you need a 30x60.

Please don't mix up array declarations with array indexing. Array declarations are fully sane; if you need 30x60 then you type FrameBuffer[30][60]. When you access the array however, you start at index 0.

Simply change the code to:

char FrameBuffer[30][60];
for (int i = 0; i < 30; i++)
{
  for (int j = 0; j < 60; j++)
  {
    FrameBuffer[i][j] = '.'; // note the correct syntax here

EDIT

As a curious side-effect, FrameBuffer[i, j] is interpreted as something entirely different than intended. The comma here is regarded as the comma operator, a special kind of operator which evaluates the left expression i, then the right expression j, then returns j.

Meaning that the code ended up completely equivalent to FrameBuffer[j] = '.'. Where FrameBuffer[j] is a whole array, not a char. You can't assign a value to an array this way, an array is not a "lvalue", which explains the compiler error text.


答:
Try this</p>

```<code>average = 0
sum = 0
for key in data.keys():
    sum = sum +len(data[key])
average = sum / len(data)
</code>```

Body:
Try this

average = 0
sum = 0
for key in data.keys():
    sum = sum +len(data[key])
average = sum / len(data)


问:
WPF databinding: database or objects?
I'm trying to create this:

Tag1 has the ordered list of objects: O1, O3, O2.
Tag2 has the ordered list of objects: O1, O4.

Every time I click a tag, I want to see the list of objects. So clicking Tag1 would show in a listbox:

O1

O3

O2

But I would like to keep the auto update so every time I edit or add/delete an object it auto updates (I suppose I need to implement something like the interfaces INotifyCollectionChanged and INotifyPropertyChanged?).

I could use a database and have the tables Tag, Object and TagObject, this last one with the TagID and ObjectID. But I also would like to avoid databases, since it's a desktop application.

I could also use objects like ObservableCollections, but I have the problem of having duplicate objects. I can use references to the objects but it gets messy.

Anyone has any suggestion on how to do this?

Thank you.

答:
One option would be to create an object that contains a dataset (System.Data namespace). Inside the dataset it would have 3 tables that would be linked using defined foreign keys the same as if it was in a database. These can later be stored to XML if need be.

Your object would then have to expose a dataview which can be set as the datacontext and bound too.

Editing the dataset in code then updates the screen and editing the screen will update the dataset.

OwnerDisplayName: Artur Carvalho

Title: WPF databinding: database or objects?

OwnerDisplayName: John

ContentLicense: CC BY-SA 2.5


问:
Finding smallest value for parameterised answer that satisfies condition
I want to find the smallest integer l that satisfies l^2 >= x, and mod(l,2)=0.

In the following example x=75, and hence l=10, since the previous even number doesn't fulfil the inequation: 8^2 <= 75 <= 10^2

I have tried this (ignoring the even-number requirement, which I can't to work):

```<code>syms l integer
eqn1 = l^2 >= 75;
% eqn2 = mod(l,2) == 0;
[sol_l, param, cond] = solve(eqn1, l, 'ReturnConditions', true);
</code>```

But this does not give me anything helpful directly:

```<code>sol_l =
k
param =
k
cond =
(75^(1/2) <= k | k <= -75^(1/2)) & in(k, 'integer')
</code>```

I would like to evaluate the conditions on the parameter and find the smallest value that satisfies the conditions.

Also, I would like to enforce the mod(l,2)=0 condition somehow, but I don't seem to get that work.

答:
Using the solve for this task is like using a cannon to kill a mosquito. Actually, the answer of Lidia Parrilla is good and fast, although it can be simplified as follows:

```<code>l = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l = l + 1;
end

% if x = 75, then l = 10
</code>```

But I would like to point out something that no one else noticed. The condition provided by the solve function for l^2 >= 75 is:

```<code>75^(1/2) <= k | k <= -75^(1/2)
</code>```

and it's absolutely correct. Since l is being raised to the power of 2, and since a negative number raised to the power of 2 produces a positive number, the equation will always have two distinct solutions: a negative one and a positive one.

For x = 75, the solutions will be l = 10 and l = -10. So, if you want to find the smallest number (and a negative number is always smaller than a positive one), the right solution will be:

```<code>l = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l = l + 1;
end

l = l * -1;
</code>```

If you want to return both solutions, the result will be:

```<code>l_pos = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l_pos = l_pos + 1;
end

l_neg = l_pos * -1;

l = [l_neg l_pos];
</code>```

Body:
I want to find the smallest integer l that satisfies l^2 >= x, and mod(l,2)=0.

In the following example x=75, and hence l=10, since the previous even number doesn't fulfil the inequation: 8^2 <= 75 <= 10^2

I have tried this (ignoring the even-number requirement, which I can't to work):

syms l integer
eqn1 = l^2 >= 75;
% eqn2 = mod(l,2) == 0;
[sol_l, param, cond] = solve(eqn1, l, 'ReturnConditions', true);

But this does not give me anything helpful directly:

sol_l =
k
param =
k
cond =
(75^(1/2) <= k | k <= -75^(1/2)) & in(k, 'integer')

I would like to evaluate the conditions on the parameter and find the smallest value that satisfies the conditions.

Also, I would like to enforce the mod(l,2)=0 condition somehow, but I don't seem to get that work.

Body:
Using the solve for this task is like using a cannon to kill a mosquito. Actually, the answer of Lidia Parrilla is good and fast, although it can be simplified as follows:

l = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l = l + 1;
end

% if x = 75, then l = 10

But I would like to point out something that no one else noticed. The condition provided by the solve function for l^2 >= 75 is:

75^(1/2) <= k | k <= -75^(1/2)

and it's absolutely correct. Since l is being raised to the power of 2, and since a negative number raised to the power of 2 produces a positive number, the equation will always have two distinct solutions: a negative one and a positive one.

For x = 75, the solutions will be l = 10 and l = -10. So, if you want to find the smallest number (and a negative number is always smaller than a positive one), the right solution will be:

l = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l = l + 1;
end

l = l * -1;

If you want to return both solutions, the result will be:

l_pos = ceil(sqrt(x));

if (mod(x,2) ~= 0)
    l_pos = l_pos + 1;
end

l_neg = l_pos * -1;

l = [l_neg l_pos];


问:
Random BigFloats Julia
Is it possible to generate random numbers of BigFloat type uniformly distributed in the interval [0,1)?

I mean, since rand(BigFloat) is not available it seems we have to use BigFloat(rand()) for that ending. However this is not satisfactory for me as  we are generating random Float64 numbers that are converted to BigFloats basically by "adding" a string of zeros, but in essence they are Float64 random numbers. Is this correct? If yes, is there any special library to generate random numbers with arbitrary precision?

Title: Random BigFloats Julia

Body:
For future readers (using Julia 0.7+) you can just do this with rand(BigFloat).
As of https://github.com/JuliaLang/julia/pull/22720
(You could certainly port that code to 0.6, and use it under the MIT license).

This is now working on 0.7-dev:

julia> rand(BigFloat)
5.381468355278042619008060591939155580805097923053455073547599255767645416051576e-01

julia> rand(BigFloat)
6.678413824545014328186230919629061895976571434256056298415613736582692882364622e-01

julia> rand(BigFloat)
1.388732949711447354224342960598222355426512649106497530016925083999303683268617e-01


问:
SQL Server index with condition
I have table Range with columns

```<code>Start (date), RangeTypeId (integer), ChannelId (integer), IsActive (bit)
</code>```

I have this index:

```<code>CREATE UNIQUE NONCLUSTERED INDEX [IX_Range_Unique]
ON [dbo].[Range] ([Start] ASC, [RangeTypeId] ASC, [ChannelId] ASC, [IsActive] ASC)
</code>```

I want my index to prevent inserting or updating only in case of 2 rows with IsActive = 1. So I want index or some sort of trigger that will allow to have multiple Ranges with IsActive = 0 and same start date, channel id and type, but only one with IsActive = 1 and same start date, channel id and type.

Example of valid db table state:

```<code>Start | RangeTypeId | ChannelId | IsActive
------------------------------------------
23:00        5           1          0
23:00        5           1          0
23:00        5           1          0
23:00        5           1          1
</code>```

invalid:

```<code>Start | RangeTypeId | ChannelId | IsActive
------------------------------------------
23:00        5           1          0
23:00        5           1          0
23:00        5           1          1
23:00        5           1          1
</code>```

Is it possible?

答:
IMHO,There is one big disadvantage of UNIQUE FILTERED INDEX .

Main purpose of index is to speed up select query.
So it is possible that above index are not utilize in most of the select query,in that case  we often  change index .

So main purpose of index is defeated.In that case we drop the index and create index on some other column/columns.

Idea of Filtered index is also different than use here.Purpose of filtered index is that if among huge data,we query on certain value very frequently then we create filtered index on that column using that value like above.Its purpose is not to provide uniqueness.

Suppose DBA is not aware of this plan and DBA decide to drop this index then you may start getting duplicate records.

So best way to check duplicate in this case will be to check via code .

```<code>if not exists (select id from mytable where [Start]=@Start and  [RangeTypeId]=@RangeTypeId
    and  [ChannelId]=@ChannelId and [IsActive]=1)
    BEGIN
    print 'insert'
    END
</code>```

If  insert/update can happen from several places then it is wise to use trigger.

Title: SQL Server index with condition

Body:
I have table Range with columns

Start (date), RangeTypeId (integer), ChannelId (integer), IsActive (bit)

I have this index:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Range_Unique]
ON [dbo].[Range] ([Start] ASC, [RangeTypeId] ASC, [ChannelId] ASC, [IsActive] ASC)

I want my index to prevent inserting or updating only in case of 2 rows with IsActive = 1. So I want index or some sort of trigger that will allow to have multiple Ranges with IsActive = 0 and same start date, channel id and type, but only one with IsActive = 1 and same start date, channel id and type.

Example of valid db table state:

Start | RangeTypeId | ChannelId | IsActive
------------------------------------------
23:00        5           1          0
23:00        5           1          0
23:00        5           1          0
23:00        5           1          1

invalid:

Start | RangeTypeId | ChannelId | IsActive
------------------------------------------
23:00        5           1          0
23:00        5           1          0
23:00        5           1          1
23:00        5           1          1

Is it possible?

Body:
IMHO,There is one big disadvantage of UNIQUE FILTERED INDEX .

Main purpose of index is to speed up select query.
So it is possible that above index are not utilize in most of the select query,in that case  we often  change index .

So main purpose of index is defeated.In that case we drop the index and create index on some other column/columns.

Idea of Filtered index is also different than use here.Purpose of filtered index is that if among huge data,we query on certain value very frequently then we create filtered index on that column using that value like above.Its purpose is not to provide uniqueness.

Suppose DBA is not aware of this plan and DBA decide to drop this index then you may start getting duplicate records.

So best way to check duplicate in this case will be to check via code .

if not exists (select id from mytable where [Start]=@Start and  [RangeTypeId]=@RangeTypeId
    and  [ChannelId]=@ChannelId and [IsActive]=1)
    BEGIN
    print 'insert'
    END

If  insert/update can happen from several places then it is wise to use trigger.