问:
django rest framework Serialization of foreign key
I just started to learn django rest framework and the following are files of my Topic app

======models.py=====

```<code>from django.contrib.auth.models import User
class Topic(models.Model):
    title = models.CharField(max_length=100,verbose_name="Topic Title")
    description = models.CharField(max_length=500, verbose_name="Topic Description")
    user = models.ForeignKey(to=User,related_name="user_topics")
</code>```

=====serializers.py=====

```<code>class TopicSerializer(ModelSerializer):
    class Meta:
        model = Topic
        fields = "__all__"
</code>```

=====views.py=====

```<code>class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer
</code>```

I'am able to create a "Topic" data using httpie as follows

```<code>http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
</code>```

NOW my need is that the topic detail should have the "user" key expanded for the User - (While maintaining the same  "user" key to PASS user id to create a topic) ie.,

making a GET request to the detail should return the following

```<code>http GET http://127.0.0.1:8989/api/v1/topics/1/
=====
HTTP/1.0 200 OK

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah"
        ...
        ...
     }
}
</code>```

AND

Making a post with user id in "user" key should create the "Topic" and should return the response with user expanded in "user" key ie.,

```<code>http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
HTTP/1.0 201 Created
....

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah", ...}
}
</code>```

What changes do i need to make, so that i will be able to use the SAME "user" key? for 3 following purpose

to make a POST with "user id" to create a Topic // user:1

The POST response returned while creating a Topic should have the user expanded in user key //user : { name:"blah blah", ...}

Also, to GET the detail expanded // user : { name:"blah blah", ...}

or
please suggest an better way of doing this.

答:
You can select a different version of PostSerializer depending of the type of request to receive.

Change your ModelViewSet's get_serializer_class method to do so:

```<code>class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()

    def get_serializer_class(self):
        if self.action == 'create':
            return PostSerializerWithUserID
        else:
            return PostSerializerWithNestedUser
</code>```

Body:
I just started to learn django rest framework and the following are files of my Topic app

======models.py=====

from django.contrib.auth.models import User
class Topic(models.Model):
    title = models.CharField(max_length=100,verbose_name="Topic Title")
    description = models.CharField(max_length=500, verbose_name="Topic Description")
    user = models.ForeignKey(to=User,related_name="user_topics")

=====serializers.py=====

class TopicSerializer(ModelSerializer):
    class Meta:
        model = Topic
        fields = "__all__"

=====views.py=====

class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer

I'am able to create a "Topic" data using httpie as follows

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1

NOW my need is that the topic detail should have the "user" key expanded for the User - (While maintaining the same  "user" key to PASS user id to create a topic) ie.,

making a GET request to the detail should return the following

http GET http://127.0.0.1:8989/api/v1/topics/1/
=====
HTTP/1.0 200 OK

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah"
        ...
        ...
     }
}

AND

Making a post with user id in "user" key should create the "Topic" and should return the response with user expanded in "user" key ie.,

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
HTTP/1.0 201 Created
....

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah", ...}
}

What changes do i need to make, so that i will be able to use the SAME "user" key? for 3 following purpose

to make a POST with "user id" to create a Topic // user:1

The POST response returned while creating a Topic should have the user expanded in user key //user : { name:"blah blah", ...}

Also, to GET the detail expanded // user : { name:"blah blah", ...}

or
please suggest an better way of doing this.

Body:
You can select a different version of PostSerializer depending of the type of request to receive.

Change your ModelViewSet's get_serializer_class method to do so:

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()

    def get_serializer_class(self):
        if self.action == 'create':
            return PostSerializerWithUserID
        else:
            return PostSerializerWithNestedUser


来源: stackexchange

问:
Powershell Set-ADUser userCertificate parameter type error
I have a script, which essentially does the following:

```<code>$user = Get-ADUser $someUserName -Server $someCertServer -Properties *
$user.userCertificate |% { Set-ADUser $someUserName -Certificates @{Add=$_} }
</code>```

It copies the cert data from a cert-server to the default server. $user.userCertificate is of type Microsoft.ActiveDirectory.Management.ADPropertyValueCollection and $user.userCertificate[0] is of type System.Byte[]. According to the docs, I can pass a Byte[] and be good to go. By using the foreach operator in the above script, I get the Byte[].

However, Powershell fails with the error message

the parameter certificates requires all values in the collection to be of the same type

(and underlines the @{Add=$_}; the message might not be 100% accurate, since I had to translate it to English). Because of the foreach operator, there is only one type: a Byte[]. What does that error message mean and how can I shove the certificate into the ADUser object?

I also tried to convert the Byte[] to a certificate object, however it ended up with the same error message:

```<code>$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($user.userCertificate[0])
Set-ADUser $someUserName -Certificates @{Add=$cert}
</code>```

答:
The very first issue I see is that you are calling on the wrong property for your example to work.

```<code>$user.userCertificate | ForEach-Object { Set-ADUser $someUserName -Certificates @{Add=$_}}
</code>```

While there is a property called userCertificate on that object that contains an collection of [byte[]]. For that code to work the way you want it to you should be using Certificates. Certificates is an collection of Security.Cryptography.X509Certificates.X509Certificate

So making that change I was able to add another users certificate to my own account.

```<code>$certUser = Get-Aduser "someGuy" -Properties certificates
$certUser.Certificates | %{ Set-ADUser "ME" -Certificates @{Add=$_}}
</code>```

Note: It is a better practice to only request the properties you need from AD. Using -properties * is a waste of effort and needless resources

While this exact scenario is not covered there is a nice write-up on the MSDN Blogs about dealing with certs.

Cert as a byte array

Now that we know userCertificate is a collection of byte arrays maybe we can look into how to use that.

I was having issues using the byte array with the certificate parameter for Set-Aduser even though it is supposed to support it. I got the error

```<code>Set-ADUser : Cannot validate argument on parameter 'Certificates'. Values in the argument collection should be of Type: 'System.Security.Cryptography.X509Certificates.X509Certificate'
</code>```

I did get this to work but I had to cast the byte array as a cert object first which was redundant considering this appear to be what the Certificates property already is.

```<code>$certUser.Usercertificate | ForEach-Object{
    Set-ADUser "ME" -certificate @{Add=[System.Security.Cryptography.X509Certificates.X509Certificate]$_}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a script, which essentially does the following:

$user = Get-ADUser $someUserName -Server $someCertServer -Properties *
$user.userCertificate |% { Set-ADUser $someUserName -Certificates @{Add=$_} }

It copies the cert data from a cert-server to the default server. $user.userCertificate is of type Microsoft.ActiveDirectory.Management.ADPropertyValueCollection and $user.userCertificate[0] is of type System.Byte[]. According to the docs, I can pass a Byte[] and be good to go. By using the foreach operator in the above script, I get the Byte[].

However, Powershell fails with the error message

the parameter certificates requires all values in the collection to be of the same type

(and underlines the @{Add=$_}; the message might not be 100% accurate, since I had to translate it to English). Because of the foreach operator, there is only one type: a Byte[]. What does that error message mean and how can I shove the certificate into the ADUser object?

I also tried to convert the Byte[] to a certificate object, however it ended up with the same error message:

$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($user.userCertificate[0])
Set-ADUser $someUserName -Certificates @{Add=$cert}

Body:
The very first issue I see is that you are calling on the wrong property for your example to work.

$user.userCertificate | ForEach-Object { Set-ADUser $someUserName -Certificates @{Add=$_}}

While there is a property called userCertificate on that object that contains an collection of [byte[]]. For that code to work the way you want it to you should be using Certificates. Certificates is an collection of Security.Cryptography.X509Certificates.X509Certificate

So making that change I was able to add another users certificate to my own account.

$certUser = Get-Aduser "someGuy" -Properties certificates
$certUser.Certificates | %{ Set-ADUser "ME" -Certificates @{Add=$_}}

Note: It is a better practice to only request the properties you need from AD. Using -properties * is a waste of effort and needless resources

While this exact scenario is not covered there is a nice write-up on the MSDN Blogs about dealing with certs.

Cert as a byte array

Now that we know userCertificate is a collection of byte arrays maybe we can look into how to use that.

I was having issues using the byte array with the certificate parameter for Set-Aduser even though it is supposed to support it. I got the error

Set-ADUser : Cannot validate argument on parameter 'Certificates'. Values in the argument collection should be of Type: 'System.Security.Cryptography.X509Certificates.X509Certificate'

I did get this to work but I had to cast the byte array as a cert object first which was redundant considering this appear to be what the Certificates property already is.

$certUser.Usercertificate | ForEach-Object{
    Set-ADUser "ME" -certificate @{Add=[System.Security.Cryptography.X509Certificates.X509Certificate]$_}
}


问:
Crosswalk Xwalk Webview conflict CollapsingToolbarLayout<android.support.design.widget>
My project has
CollapsingToolbarLayout
implemented for UI effect

when i add

compile 'org.xwalk:xwalk_core_library:20.50.533.12'

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'org.xwalk:xwalk_core_library:20.50.533.12'
   // compile 'org.xwalk:xwalk_core_library:16.45.421.19'
}
</code>```

http://pastebin.com/WwWw0VB3

And run my project i get the error

```<code>Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.design.widget.CollapsingToolbarLayout
</code>```

http://pastebin.com/V0XyqViC

On removing
compile 'org.xwalk:xwalk_core_library:20.50.533.12'
from gradle the error disappears

答:
Using the following snippet fixed the issue    </p>

```<code>compile('com.android.support:support-v4:25.2.0') {
        force = true;
    }
</code>```

Body:
My project has
CollapsingToolbarLayout
implemented for UI effect

when i add

compile 'org.xwalk:xwalk_core_library:20.50.533.12'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'org.xwalk:xwalk_core_library:20.50.533.12'
   // compile 'org.xwalk:xwalk_core_library:16.45.421.19'
}

http://pastebin.com/WwWw0VB3

And run my project i get the error

Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.design.widget.CollapsingToolbarLayout

http://pastebin.com/V0XyqViC

On removing
compile 'org.xwalk:xwalk_core_library:20.50.533.12'
from gradle the error disappears

Body:
Using the following snippet fixed the issue

compile('com.android.support:support-v4:25.2.0') {
        force = true;
    }


问:
How to make particular sub-select options appear when the value of the parent select option is changed
I am creating Select option.

Example: It's a sort of code I will be using for categories. When user selects on of the parent select's option another select option to be displayed as sub category of that category.

My code:

```<code><form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select>
<option value="car">car</option>
<option value="phone">phone</option>
<option value="tv">tv</option>
</select>

<select>
<option value="toyota">toyota</option>
<option value="nissan">nissan</option>
<option value="bmw">BMW</option>
</select>
</form>
</code>```

答:
$("#select1").change(function() {
  if ($(this).data('options') == undefined) {
    /*Taking an array of all options-2 and kind of embedding it on the select1*/
    $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
});```
<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>
<select name="select1" id="select1">
  <option value=""></option>
  <option value="1">car</option>
  <option value="2">phone</option>
  <option value="3">tv</option>
</select>

<select name="select2" id="select2">
  <option value=""></option>
  <option value="1">toyota</option>
  <option value="1">nissan</option>
  <option value="1">bmw</option>
  <option value="2">Iphone</option>
  <option value="2">LG</option>
  <option value="2">Samsung</option>
  <option value="3">Philips</option>
  <option value="3">Samsung</option>
</select></code>```

Body:
I am creating Select option.

Example: It's a sort of code I will be using for categories. When user selects on of the parent select's option another select option to be displayed as sub category of that category.

My code:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select>
<option value="car">car</option>
<option value="phone">phone</option>
<option value="tv">tv</option>
</select>

<select>
<option value="toyota">toyota</option>
<option value="nissan">nissan</option>
<option value="bmw">BMW</option>
</select>
</form>

Body:
$("#select1").change(function() {
  if ($(this).data('options') == undefined) {
    /*Taking an array of all options-2 and kind of embedding it on the select1*/
    $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select1" id="select1">
  <option value=""></option>
  <option value="1">car</option>
  <option value="2">phone</option>
  <option value="3">tv</option>
</select>

<select name="select2" id="select2">
  <option value=""></option>
  <option value="1">toyota</option>
  <option value="1">nissan</option>
  <option value="1">bmw</option>
  <option value="2">Iphone</option>
  <option value="2">LG</option>
  <option value="2">Samsung</option>
  <option value="3">Philips</option>
  <option value="3">Samsung</option>
</select>


问:
Angular2 Material2 bind to onMenuClose
I am trying to detect when the menu closes to unset a value, I have been using close that looks like this.

```<code><md-menu #dataActions="mdMenu"  (onMenuClose)="alert('a')">
    <button md-menu-item (click)="doEdit()" *ngIf="!isLocked()">
        <md-icon>edit</md-icon>
        <span>Edit</span>
    </button>
    <button md-menu-item (click)="doSubmit()" *ngIf="isEdit()">
        <md-icon>done</md-icon>
        <span>Submit</span>
    </button>
</md-menu>
</code>```

I can tell i am binding to something that exists because it does not throw an error ... however when the close events run it never registers to the actual event.  Does anyone have any ideas? or is this a bug in material?

答:
There were a few minor issues, the onMenuClose event is fired at the same level as the mdMenuTriggerFor ... therefore the bind needed to be on the calling item not the menu itself.  Also as @Edric stated, it had to be a typescript function and not a generic alert.  Here is another code snipit that works:</p>

```<code><md-icon [mdMenuTriggerFor]="dataActions" (onMenuOpen)="actionMenuOpen(row)" (onMenuClose)="actionMenuClose()" fxFill fxLayoutAlign="center">
    menu
</md-icon>

<md-menu #dataActions="mdMenu">
    <button md-menu-item (click)="doEdit()" *ngIf="!isLocked()">
        <md-icon>edit</md-icon>
        <span>Edit</span>
    </button>
    <button md-menu-item (click)="doSubmit()" *ngIf="isEdit()">
        <md-icon>done</md-icon>
        <span>Submit</span>
    </button>
</md-menu>
</code>```

Title: Angular2 Material2 bind to onMenuClose

Body:
I am trying to detect when the menu closes to unset a value, I have been using close that looks like this.

<md-menu #dataActions="mdMenu"  (onMenuClose)="alert('a')">
    <button md-menu-item (click)="doEdit()" *ngIf="!isLocked()">
        <md-icon>edit</md-icon>
        Edit
    </button>
    <button md-menu-item (click)="doSubmit()" *ngIf="isEdit()">
        <md-icon>done</md-icon>
        Submit
    </button>
</md-menu>

I can tell i am binding to something that exists because it does not throw an error ... however when the close events run it never registers to the actual event.  Does anyone have any ideas? or is this a bug in material?

Body:
There were a few minor issues, the onMenuClose event is fired at the same level as the mdMenuTriggerFor ... therefore the bind needed to be on the calling item not the menu itself.  Also as @Edric stated, it had to be a typescript function and not a generic alert.  Here is another code snipit that works:

<md-icon [mdMenuTriggerFor]="dataActions" (onMenuOpen)="actionMenuOpen(row)" (onMenuClose)="actionMenuClose()" fxFill fxLayoutAlign="center">
    menu
</md-icon>

<md-menu #dataActions="mdMenu">
    <button md-menu-item (click)="doEdit()" *ngIf="!isLocked()">
        <md-icon>edit</md-icon>
        <span>Edit</span>
    </button>
    <button md-menu-item (click)="doSubmit()" *ngIf="isEdit()">
        <md-icon>done</md-icon>
        <span>Submit</span>
    </button>
</md-menu>


问:
Tablesaw headers not shown on mobile
According to their examples and documentation you should be able to see the headers when you are on a mobile phone:

tablesaw doc

table-saw demo

However when i attempt this with the following table:

```<code><table id="table-client" class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack"
</code>```

i get this:

As you can see without the headers.

I searched around and saw a guy on github having the same problem however he did not have any luck with solving the issue.

My question to you guys is, has anyone ever encountered the problem and know of a way to fix it?

答:
I have just added the required dependency files.</p>

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="tablesaw.css">
    <script src="tablesaw.js"></script>
    <script src="tablesaw-init.js"></script>
</head>
<body>
    <table class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack">
            <thead>
                <tr>
                    <th>Movie Title</th>
                    <th>Rank</th>
                    <th>Year</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><a href="http://en.wikipedia.org/wiki/Avatar_(2009_film)">Avatar</a></td>
                    <td>1</td>
                    <td>2009</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                </tr>
                <tr>
                    <td><a href="http://en.wikipedia.org/wiki/Titanic_(1997_film)">Titanic</a></td>
                    <td>2</td>
                    <td>1997</td>
                    <td>88%</td>
                    <td>$2.1B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                </tr>
            </tbody>
    </table>
</body>
</html>
</code>```

Title: Tablesaw headers not shown on mobile

Body:
According to their examples and documentation you should be able to see the headers when you are on a mobile phone:

tablesaw doc

table-saw demo

However when i attempt this with the following table:

<table id="table-client" class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack"

i get this:

As you can see without the headers.

I searched around and saw a guy on github having the same problem however he did not have any luck with solving the issue.

My question to you guys is, has anyone ever encountered the problem and know of a way to fix it?

Body:
I have just added the required dependency files.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="tablesaw.css">
    <script src="tablesaw.js"></script>
    <script src="tablesaw-init.js"></script>
</head>
<body>
    <table class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack">
            <thead>
                <tr>
                    <th>Movie Title</th>
                    <th>Rank</th>
                    <th>Year</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                    <th>Rating</abbr></th>
                    <th>Gross</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><a href="http://en.wikipedia.org/wiki/Avatar_(2009_film)">Avatar</a></td>
                    <td>1</td>
                    <td>2009</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                </tr>
                <tr>
                    <td><a href="http://en.wikipedia.org/wiki/Titanic_(1997_film)">Titanic</a></td>
                    <td>2</td>
                    <td>1997</td>
                    <td>88%</td>
                    <td>$2.1B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                    <td>83%</td>
                    <td>$2.7B</td>
                </tr>
            </tbody>
    </table>
</body>
</html>


问:
Images not opening on Safari & apple devices
I am working on a website, the problem is some of the photos of website are not opening on some apple devices (iPad, iPad pro etc) and on safari browser. Example can be seen here (open in safari or apple device).

Even when I copy the image url and try to open it in a new tab, it doesn't opens, it just displays:

I tried almost every solution I found on stackoverflow to the related problems, but no luck!

Any idea why is it happening?

EDIT:

It is not duplicate question because in my case pics have nothing to do with size, many pics having much larger size are being displayed properly.

答:
Downloading and inspecting the images that doesn't show up, example...

```<code>$ file /Users/paolo/Desktop/14864236730ce9011e-original.jpg
/Users/paolo/Desktop/14864236730ce9011e-original.jpg: RIFF (little-endian) data
</code>```

...it turns out they are not jpeg as the extension suggest but riff

see https://en.wikipedia.org/wiki/Resource_Interchange_File_Format

The riff format is a wrapper and in this case it wraps a WEBP image.

This is why Chrome is able to open the file and show the image.

You can identify the RIFF images with the file command line tool.

One tool you may use to convert them is xnconvert  (free and multi-platform)

I just tried it with the image above and worked fine.

You can use it to batch process multiple images too.

I have no idea how these imagese ended up there in that format. Probably there is some server-side script that converts uploaded images to WEBP/RIFF. But's just a guess of course.

Body:
Downloading and inspecting the images that doesn't show up, example...

$ file /Users/paolo/Desktop/14864236730ce9011e-original.jpg
/Users/paolo/Desktop/14864236730ce9011e-original.jpg: RIFF (little-endian) data

...it turns out they are not jpeg as the extension suggest but riff

see https://en.wikipedia.org/wiki/Resource_Interchange_File_Format

The riff format is a wrapper and in this case it wraps a WEBP image.

This is why Chrome is able to open the file and show the image.

You can identify the RIFF images with the file command line tool.

One tool you may use to convert them is xnconvert  (free and multi-platform)

I just tried it with the image above and worked fine.

You can use it to batch process multiple images too.

I have no idea how these imagese ended up there in that format. Probably there is some server-side script that converts uploaded images to WEBP/RIFF. But's just a guess of course.


问:
What does the .size on number mean in ruby?
Why is my ruby giving incorrect size of number?  It doesn't matter what's the number. The output is always 4 for the size. What does that mean? I always thought it should give the number of digits.

```<code>number = 14
print number
print "\n"
print number.size
</code>```

output:

```<code>14
4
</code>```

ruby version

```<code>ruby 2.1.8p440 (2015-12-16 revision 53160) [i386-mingw32]
</code>```

答:
You are confusing the two methods String#size:

Returns the character length of str.

and Fixnum#size:

Returns the number of bytes in the machine representation of fix.

14 is an object of class Fixnum, so when you call size on it you are getting the number of bytes in the machine representation of the number.

If you would like to know how many digits there are in a number, you can simply convert it to a string first and then call size on that:

```<code>14.to_s
# => "14"
14.to_s.size
#=> 2
12345.to_s.size
#=> 5
</code>```

Body:
Why is my ruby giving incorrect size of number?  It doesn't matter what's the number. The output is always 4 for the size. What does that mean? I always thought it should give the number of digits.

number = 14
print number
print "\n"
print number.size

output:

14
4

ruby version

ruby 2.1.8p440 (2015-12-16 revision 53160) [i386-mingw32]

Body:
You are confusing the two methods String#size:

Returns the character length of str.

and Fixnum#size:

Returns the number of bytes in the machine representation of fix.

14 is an object of class Fixnum, so when you call size on it you are getting the number of bytes in the machine representation of the number.

If you would like to know how many digits there are in a number, you can simply convert it to a string first and then call size on that:

14.to_s
# => "14"
14.to_s.size
#=> 2
12345.to_s.size
#=> 5


问:
How to add an exception test for the below Http call that returns a json
```<code>[HttpPost]
[Route("TnC")]
public IHttpActionResult TnC(CustomViewModel myViewModel)
{
    try
    {
        return Json(_Internal.TnC(myViewModel, LoggedInUser));
    }
    catch (BusinessException exception)
    {
        return Json(BuildErrorModelBase(exception));
    }
}
</code>```

Where the _Internal is a Service with a guaranteed 99.99% up-time and not formalized fault contract interfaces defined.

Exceptions which are handled in my application level(business layer level) as a BusinessException - root class

Where BusinessException is defined as follows

```<code>public class BusinessException : Exception
{
    BusinessException()...
    BusinessExceptionFoo()...
    BusinessExceptionBar()...
    //...
}
</code>```

And the current test Method is

To do : Add Exception test

```<code>[TestMethod]
[ExpectedException(typeof(BusinessException),
        "Not a valid Business Case")]
public void TnCTest()
{
    var bookingService = myContainer.Resolve<mySvc>();

    var controller = new LinkBookingController(mySvc, myContainer);
    var expectedResult = controller.TnC(new myViewModel
    {
        ...params
    });

    var actualResult = GetData<Result<myViewModel>>(expectedResult);

    Assert.AreEqual(expectedResult, actualResult);
}
</code>```

expectedResult==actualResult does not test the exception block of the code.
How do I construct a request that makes the service throw the exception other than manually removing the ethernet cable to get this specific type of server error.

The best I could come up with was

```<code>#if DEBUG && UnitTestExceptions
        throw new BusinessException();
#endif
</code>```

But there is gotta be a better option.

答:
There are a few things of concern with the method under test.

It is mixing cross-cutting concerns in the action that should be refactored out into an ExceptionHandler. Chances are that piece of code is repeated many times in that controller and others like it (DRY).

```<code>public class WebApiExceptionHandler : ExceptionHandler {

    public override void Handle(ExceptionHandlerContext context) {
        var innerException = context.ExceptionContext.Exception;
        // Ignore HTTP errors
        if (innerException.GetType().IsAssignableFrom(typeof(System.Web.HttpException))) {
            return;
        }

        if(innerException is BusinessException) {
            context.Result = BuildErrorResult(exception);
            return;
        }

        //...other handler code
    }

    IHttpActionResult BuildErrorResult(BusinessException exception) {
        //... your logic here
    }
}
</code>```

The following extension method could be used to add the handler to the HttpConfiguration during startup which also assumes that the application is taking advantage of dependency inversion services.

```<code>public static HttpConfiguration ReplaceExceptionHandler(this HttpConfiguration config) {
    var errorHandler = config.Services.GetExceptionHandler();
    if (!(errorHandler is WebApiExceptionHandler)) {
        var service = config.Services.GetService(typeof(WebApiExceptionHandler));
        config.Services.Replace(typeof(IExceptionHandler), service);
    }
    return config;
}
</code>```

Now that cross-cutting concerns have been dealt with the action becomes a lot simpler and easier to test. This is a simplified example of an ApiController

```<code>public class LinkBookingController : ApiController {
    private IBookingService bookingService;

    public LinkBookingController(IBookingService service) {
        bookingService = service;
    }

    [HttpPost]
    [Route("TnC")]
    public IHttpActionResult TnC(CustomViewModel myViewModel) {

        return Json(bookingService.TnC(myViewModel, User));

    }
}
</code>```

where IBookingService is defined as

```<code>public interface IBookingService {
    BookingModel TnC(CustomViewModel viewModel, IPrincipal user);
}
</code>```

Using a mocking framework like Moq an exception can be made to be thrown as needed.

```<code>[TestMethod]
[ExpectedException(typeof(BusinessException), "Not a valid Business Case")]
public void TnC_Should_Throw_BusinessException() {
    //Arrange
    var bookingService = new Mock<IBookingService>();

    var controller = new LinkBookingController(bookingService.Object);

    var viewModel  = new myViewModel
    {
        //...params
    };

    bookingService.Setup(_ => _.TnC(viewModel, It.IsAny<IPrincipal>())).Throws<BusinessException>()

    //Act
    var expectedResult = controller.TnC(viewModel);

    //Assert
    //...the ExpectedException attribute should assert if it was thrown
}
</code>```

To test how that exception can be handled do a unit test on the exception handler and not the controller as that is not the responsibility of the controller.

Try to keep controllers lean and focused on its UI concerns.

Body:
[HttpPost]
[Route("TnC")]
public IHttpActionResult TnC(CustomViewModel myViewModel)
{
    try
    {
        return Json(_Internal.TnC(myViewModel, LoggedInUser));
    }
    catch (BusinessException exception)
    {
        return Json(BuildErrorModelBase(exception));
    }
}

Where the _Internal is a Service with a guaranteed 99.99% up-time and not formalized fault contract interfaces defined.

Exceptions which are handled in my application level(business layer level) as a BusinessException - root class

Where BusinessException is defined as follows

public class BusinessException : Exception
{
    BusinessException()...
    BusinessExceptionFoo()...
    BusinessExceptionBar()...
    //...
}

And the current test Method is

To do : Add Exception test

[TestMethod]
[ExpectedException(typeof(BusinessException),
        "Not a valid Business Case")]
public void TnCTest()
{
    var bookingService = myContainer.Resolve<mySvc>();

    var controller = new LinkBookingController(mySvc, myContainer);
    var expectedResult = controller.TnC(new myViewModel
    {
        ...params
    });

    var actualResult = GetData<Result<myViewModel>>(expectedResult);

    Assert.AreEqual(expectedResult, actualResult);
}

expectedResult==actualResult does not test the exception block of the code.
How do I construct a request that makes the service throw the exception other than manually removing the ethernet cable to get this specific type of server error.

The best I could come up with was

#if DEBUG && UnitTestExceptions
        throw new BusinessException();
#endif

But there is gotta be a better option.

Body:
There are a few things of concern with the method under test.

It is mixing cross-cutting concerns in the action that should be refactored out into an ExceptionHandler. Chances are that piece of code is repeated many times in that controller and others like it (DRY).

public class WebApiExceptionHandler : ExceptionHandler {

    public override void Handle(ExceptionHandlerContext context) {
        var innerException = context.ExceptionContext.Exception;
        // Ignore HTTP errors
        if (innerException.GetType().IsAssignableFrom(typeof(System.Web.HttpException))) {
            return;
        }

        if(innerException is BusinessException) {
            context.Result = BuildErrorResult(exception);
            return;
        }

        //...other handler code
    }

    IHttpActionResult BuildErrorResult(BusinessException exception) {
        //... your logic here
    }
}

The following extension method could be used to add the handler to the HttpConfiguration during startup which also assumes that the application is taking advantage of dependency inversion services.

public static HttpConfiguration ReplaceExceptionHandler(this HttpConfiguration config) {
    var errorHandler = config.Services.GetExceptionHandler();
    if (!(errorHandler is WebApiExceptionHandler)) {
        var service = config.Services.GetService(typeof(WebApiExceptionHandler));
        config.Services.Replace(typeof(IExceptionHandler), service);
    }
    return config;
}

Now that cross-cutting concerns have been dealt with the action becomes a lot simpler and easier to test. This is a simplified example of an ApiController

public class LinkBookingController : ApiController {
    private IBookingService bookingService;

    public LinkBookingController(IBookingService service) {
        bookingService = service;
    }

    [HttpPost]
    [Route("TnC")]
    public IHttpActionResult TnC(CustomViewModel myViewModel) {

        return Json(bookingService.TnC(myViewModel, User));

    }
}

where IBookingService is defined as

public interface IBookingService {
    BookingModel TnC(CustomViewModel viewModel, IPrincipal user);
}

Using a mocking framework like Moq an exception can be made to be thrown as needed.

[TestMethod]
[ExpectedException(typeof(BusinessException), "Not a valid Business Case")]
public void TnC_Should_Throw_BusinessException() {
    //Arrange
    var bookingService = new Mock<IBookingService>();

    var controller = new LinkBookingController(bookingService.Object);

    var viewModel  = new myViewModel
    {
        //...params
    };

    bookingService.Setup(_ => _.TnC(viewModel, It.IsAny<IPrincipal>())).Throws<BusinessException>()

    //Act
    var expectedResult = controller.TnC(viewModel);

    //Assert
    //...the ExpectedException attribute should assert if it was thrown
}

To test how that exception can be handled do a unit test on the exception handler and not the controller as that is not the responsibility of the controller.

Try to keep controllers lean and focused on its UI concerns.


问:
Why python configParser.read can only use filename as parameter to read config file
My python package directory structure shown as below:

```<code>./my_package
|---./lib
|   |----__init__.py
|   |----tools.py
|
|----__init__.py
|----my_package.py
|----setting.conf
</code>```

In the tools.py :

```<code>import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('setting.conf')
debug = config.getboolean('default', 'debug')
</code>```

I don't know why config.read is work. I can get debug value in section default.

答:
Your test works because the configuration file is in the current directory, because you're running your main module from the directory of the configuration file.

But if you're using another main file located somewhere else, that could fail.

Here's a clean way to make it work in any case: since your tool is one level below the configuration file, the path to the configuration file can be computed as follows from the tools.py module:

```<code>conf_file = os.path.join(os.path.dirname(os.path.dirname(__file__)),'setting.conf')
</code>```

os.path.dirname(__file__) yields the directory where tools.py is located. Perform one more dirname to get the directory where the conf file is located. Now compute absolute name of config file using os.path.join

Body:
My python package directory structure shown as below:

./my_package
|---./lib
|   |----__init__.py
|   |----tools.py
|
|----__init__.py
|----my_package.py
|----setting.conf

In the tools.py :

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('setting.conf')
debug = config.getboolean('default', 'debug')

I don't know why config.read is work. I can get debug value in section default.

Body:
Your test works because the configuration file is in the current directory, because you're running your main module from the directory of the configuration file.

But if you're using another main file located somewhere else, that could fail.

Here's a clean way to make it work in any case: since your tool is one level below the configuration file, the path to the configuration file can be computed as follows from the tools.py module:

conf_file = os.path.join(os.path.dirname(os.path.dirname(__file__)),'setting.conf')

os.path.dirname(__file__) yields the directory where tools.py is located. Perform one more dirname to get the directory where the conf file is located. Now compute absolute name of config file using os.path.join


问:
My show segue not using NavigationController

I am having problems segueing to my detail view, using Navigation Controller.

I was using a tableview, to display some exercises, and when you clicked the exercise you would seque into the detail view, embedded in nav controller
I have removed the Tableview, and added 3 buttons, each with its' own "show" segue to the detail view. It almost works, but it is now not using my Navigation controller, meaning that the view is just presented kind of like a modal presentation.
I have tried removing the segue on one button and replace with this action:

```<code>@IBAction func strengthButton(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destination = storyboard.instantiateViewController(withIdentifier: "ExerciseViewController") as! ExerciseViewController
    destination.componentaccessid = -1;
    destination.openedFromUrl = false;
    destination.exercise = self.strengthexercise
    destination.exercisetype = .strength
    self.navigationController?.present(destination, animated: true, completion: nil)
}
</code>```

But that does exactly the same.

I have a prepare function:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier,
        let destination = segue.destination as? ExerciseViewController{
        destination.componentaccessid = -1;
        destination.openedFromUrl = false;
        switch identifier{
        case "strengthsegue":
            destination.exercise = self.strengthexercise
            destination.exercisetype = .strength
        case "rangesegue":
            destination.exercise = self.rangeexercise
            destination.exercisetype = .range
        case "combinedsegue":
            destination.exercise = self.combinedexercise
            destination.exercisetype = .combined
        default:
            print("Nothing")
        }

    }
}
</code>```

答:
In your code you are using,

```<code>self.navigationController?.present(destination, animated: true, completion: nil)
</code>```

This will only present the UIViewController.

Instead use,

```<code>self.navigationController?.pushViewController(destination, animated: true)
</code>```

to push the viewController in which the NavigationController is inherited.

Body:
I am having problems segueing to my detail view, using Navigation Controller.

I was using a tableview, to display some exercises, and when you clicked the exercise you would seque into the detail view, embedded in nav controller
I have removed the Tableview, and added 3 buttons, each with its' own "show" segue to the detail view. It almost works, but it is now not using my Navigation controller, meaning that the view is just presented kind of like a modal presentation.
I have tried removing the segue on one button and replace with this action:

@IBAction func strengthButton(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destination = storyboard.instantiateViewController(withIdentifier: "ExerciseViewController") as! ExerciseViewController
    destination.componentaccessid = -1;
    destination.openedFromUrl = false;
    destination.exercise = self.strengthexercise
    destination.exercisetype = .strength
    self.navigationController?.present(destination, animated: true, completion: nil)
}

But that does exactly the same.

I have a prepare function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier,
        let destination = segue.destination as? ExerciseViewController{
        destination.componentaccessid = -1;
        destination.openedFromUrl = false;
        switch identifier{
        case "strengthsegue":
            destination.exercise = self.strengthexercise
            destination.exercisetype = .strength
        case "rangesegue":
            destination.exercise = self.rangeexercise
            destination.exercisetype = .range
        case "combinedsegue":
            destination.exercise = self.combinedexercise
            destination.exercisetype = .combined
        default:
            print("Nothing")
        }

    }
}

Body:
In your code you are using,

self.navigationController?.present(destination, animated: true, completion: nil)

This will only present the UIViewController.

Instead use,

self.navigationController?.pushViewController(destination, animated: true)

to push the viewController in which the NavigationController is inherited.


问:
Excel VBA: How to autocreate hyperlink from cell value?
I have a table called Table1

In Column B, I have the ticket number. e.g: 76537434

Requirement: when any change happens in any cell in column B, that cell (Target cell) to be changed into a hyperlink such that the hyperlink address would be example.com/id=76537434

Cell value i.e. 76537434 must remain the same

答:
```<code>=HYPERLINK(E14&F14,"Name")
</code>```

where cell E14 contains "http://www.example.com/id=" and cell F14 contains "76537434".
This soultions doesn't need VBA macros.

Body:
=HYPERLINK(E14&F14,"Name")

where cell E14 contains "http://www.example.com/id=" and cell F14 contains "76537434".
This soultions doesn't need VBA macros.


问:
recvmmsg() with timeout = 0 is equivalent to nonblocking recvmsg()?
I am on CentOS 6.5 with kernel version kernel-2.6.32-431.el6.

I was trying to find the implementation of recvmmsg(), and hopefully, I am not looking at the wrong source ~/rpmbuild/BUILD/kernel-2.6.32-431.el6/linux-2.6.32-431.el6.x86_64/net/socket.c.  If I am, please kindly point me to the right source.

```<code>int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
                   unsigned int flags, struct timespec *timeout)
{
        int fput_needed, err, datagrams;
        struct socket *sock;
        struct mmsghdr __user *entry;
        struct compat_mmsghdr __user *compat_entry;
        struct msghdr msg_sys;
        struct timespec end_time;

        if (timeout &&
            poll_select_set_timeout(&end_time, timeout->tv_sec,
                                    timeout->tv_nsec))
                return -EINVAL;

        datagrams = 0;

        sock = sockfd_lookup_light(fd, &err, &fput_needed);
        if (!sock)
                return err;

        err = sock_error(sock->sk);
        if (err)
                goto out_put;

        entry = mmsg;
        compat_entry = (struct compat_mmsghdr __user *)mmsg;

        while (datagrams < vlen) {
                /*
                 * No need to ask LSM for more than the first datagram.
                 */
                if (MSG_CMSG_COMPAT & flags) {
                        err = __sys_recvmsg(sock, (struct msghdr __user *)compat_entry,
                                            &msg_sys, flags, datagrams);
                        if (err < 0)
                                break;
                        err = __put_user(err, &compat_entry->msg_len);
                        ++compat_entry;
                } else {
                        err = __sys_recvmsg(sock, (struct msghdr __user *)entry,
                                            &msg_sys, flags, datagrams);
                        if (err < 0)
                                break;
                        err = put_user(err, &entry->msg_len);
                        ++entry;
                }

                if (err)
                        break;
                ++datagrams;

                if (timeout) {
                        ktime_get_ts(timeout);
                        *timeout = timespec_sub(end_time, *timeout);
                        if (timeout->tv_sec < 0) {
                                timeout->tv_sec = timeout->tv_nsec = 0;
                                break;
                        }

                        /* Timeout, return less than vlen datagrams */
                        if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
                                break;
                }

                /* Out of band data, return right away */
                if (msg_sys.msg_flags & MSG_OOB)
                        break;
        }

out_put:
        fput_light(sock->file, fput_needed);

        if (err == 0)
                return datagrams;

        if (datagrams != 0) {
                /*
                 * We may return less entries than requested (vlen) if the
                 * sock is non block and there aren't enough datagrams...
                 */
                if (err != -EAGAIN) {
                        /*
                         * ... or  if recvmsg returns an error after we
                         * received some datagrams, where we record the
                         * error to return on the next call or if the
                         * app asks about it using getsockopt(SO_ERROR).
                         */
                        sock->sk->sk_err = -err;
                }

                return datagrams;
        }

        return err;
}
</code>```

Let's say there are 2 packets at the socket, and I try:

```<code>timespec t = {0, 0};
recvmmsg(fd, mmsg, vlen, 0, &t);
</code>```

Then, because of these lines:

```<code>                    if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
                            break;
</code>```

recvmmsg() will just return 1 packet instead of 2.  Am I right?

It seems defecting the one of the main purposes of recvmmsg() -- trying to reduce # of system calls when there are packet queued.

Maybe I miss something?

Any suggestion is welcome.

Thanks!

============================

Update:

I tried to write a small snippet of code that waits for the packets to queue up and then call recvmmsg() with timeout=0 (not NULL).  It still picks up only 1 packet.  Hence, I think I am looking at the correct source code.

答: Yes, you are right. I think it is better to use NULL timeout + O_NONBLOCK if you want to read all packets in the queue</p>

Body:
I am on CentOS 6.5 with kernel version kernel-2.6.32-431.el6.

I was trying to find the implementation of recvmmsg(), and hopefully, I am not looking at the wrong source ~/rpmbuild/BUILD/kernel-2.6.32-431.el6/linux-2.6.32-431.el6.x86_64/net/socket.c.  If I am, please kindly point me to the right source.

int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
                   unsigned int flags, struct timespec *timeout)
{
        int fput_needed, err, datagrams;
        struct socket *sock;
        struct mmsghdr __user *entry;
        struct compat_mmsghdr __user *compat_entry;
        struct msghdr msg_sys;
        struct timespec end_time;

        if (timeout &&
            poll_select_set_timeout(&end_time, timeout->tv_sec,
                                    timeout->tv_nsec))
                return -EINVAL;

        datagrams = 0;

        sock = sockfd_lookup_light(fd, &err, &fput_needed);
        if (!sock)
                return err;

        err = sock_error(sock->sk);
        if (err)
                goto out_put;

        entry = mmsg;
        compat_entry = (struct compat_mmsghdr __user *)mmsg;

        while (datagrams < vlen) {
                /*
                 * No need to ask LSM for more than the first datagram.
                 */
                if (MSG_CMSG_COMPAT & flags) {
                        err = __sys_recvmsg(sock, (struct msghdr __user *)compat_entry,
                                            &msg_sys, flags, datagrams);
                        if (err < 0)
                                break;
                        err = __put_user(err, &compat_entry->msg_len);
                        ++compat_entry;
                } else {
                        err = __sys_recvmsg(sock, (struct msghdr __user *)entry,
                                            &msg_sys, flags, datagrams);
                        if (err < 0)
                                break;
                        err = put_user(err, &entry->msg_len);
                        ++entry;
                }

                if (err)
                        break;
                ++datagrams;

                if (timeout) {
                        ktime_get_ts(timeout);
                        *timeout = timespec_sub(end_time, *timeout);
                        if (timeout->tv_sec < 0) {
                                timeout->tv_sec = timeout->tv_nsec = 0;
                                break;
                        }

                        /* Timeout, return less than vlen datagrams */
                        if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
                                break;
                }

                /* Out of band data, return right away */
                if (msg_sys.msg_flags & MSG_OOB)
                        break;
        }

out_put:
        fput_light(sock->file, fput_needed);

        if (err == 0)
                return datagrams;

        if (datagrams != 0) {
                /*
                 * We may return less entries than requested (vlen) if the
                 * sock is non block and there aren't enough datagrams...
                 */
                if (err != -EAGAIN) {
                        /*
                         * ... or  if recvmsg returns an error after we
                         * received some datagrams, where we record the
                         * error to return on the next call or if the
                         * app asks about it using getsockopt(SO_ERROR).
                         */
                        sock->sk->sk_err = -err;
                }

                return datagrams;
        }

        return err;
}

Let's say there are 2 packets at the socket, and I try:

timespec t = {0, 0};
recvmmsg(fd, mmsg, vlen, 0, &t);

Then, because of these lines:

                    if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
                            break;

recvmmsg() will just return 1 packet instead of 2.  Am I right?

It seems defecting the one of the main purposes of recvmmsg() -- trying to reduce # of system calls when there are packet queued.

Maybe I miss something?

Any suggestion is welcome.

Thanks!

============================

Update:

I tried to write a small snippet of code that waits for the packets to queue up and then call recvmmsg() with timeout=0 (not NULL).  It still picks up only 1 packet.  Hence, I think I am looking at the correct source code.


问:
Mom file creation (5 product limit)
Ok, I realize this is a very niche issue, but I'm hoping the process is straight forward enough...

I'm tasked with creating a data file out of Customer/Order information.  Problem is, the datafile has a 5 product max limit.

Basically, I get my data, group by cust_id, create the file structure, within that loop, group by product_id, rewrite the fields in previous file_struct with new product info.  That's worked all well and good until a user exceeded that max.

A brief example..  (keep in mind, the structure of the array is set by another process, this CANNOT change)

```<code>orderArray = arranyew(2);
set order = 1;

loop over cust_id;

    field[order][1] = "field(1)"; // cust_id
    field[order][2] = "field(2)"; // name
    field[order][3] = "field(3)"; // phone
    field[order][4] = ""; // product_1
    field[order][5] = ""; // quantity_1
    field[order][6] = ""; // product_2
    field[order][7] = ""; // quantity_2
    field[order][8] = ""; // product_3
    field[order][9] = ""; // quantity_3
    field[order][10] = ""; // product_4
    field[order][11] = ""; // quantity_4
    field[order][12] = ""; // product_5
    field[order][13] = ""; // quantity_5
    field[order][14] = "field(4)"; // trx_id
    field[order][15] = "field(5)"; // total_cost

    counter = 0;

    loop over product_id

        field[order[4+counter] = productCode;
        field[order[5+counter] = quantity;

        counter = counter + 2;

    end inner loop;

    order = order + 1;

end outer loop;
</code>```

Like I said, this worked fine until I had a user who ordered more than 5 products.

What I basically want to do is check the number of products for each user if that number is greater than 5, start a new line in the text field, but I'm stufk on how to get there.

I've tried numerous fixes, but nothing gives the results I need.

I can send the entire file if It can help, but I don't want to post it all here.

答:
You need to move the inserting of the header and footer fields into product loop eg. the custid and trx_id fields.

Here's a rough idea of one why you can go about this based on the pseudo code you provided. I'm sure that there are more elegant ways that you could code this.

```<code>set order = 0;

loop over cust_id;

counter = 1;
order = order + 1;

loop over product_id
    if (counter == 1 || counter == 6) {
        if (counter == 6) {
            counter == 1;
            order= order+1;
        }
        field[order][1] = "field(1)"; // cust_id
        field[order][2] = "field(2)"; // name
        field[order][3] = "field(3)"; // phone
    }

    field[order][counter+3] = productCode; // product_1
    field[order][counter+4] = quantity; // quantity_1

    counter = counter + 1;
    if (counter == 6) {
        field[order][14] = "field(4)"; // trx_id
        field[order][15] = "field(5)"; // total_cost
    }

end inner loop;

if (counter == 6) {
    // loop here to insert blank columns and the totals field to fill out the row.
}

end outer loop;
</code>```

One thing goes concern me.  If you start a new line every five products then your transaction id and total cost is going to be entered into the file more than once. You know the receiving system.  It may be a non-issue.

Hope this helps

Title: Mom file creation (5 product limit)

Body:
Ok, I realize this is a very niche issue, but I'm hoping the process is straight forward enough...

I'm tasked with creating a data file out of Customer/Order information.  Problem is, the datafile has a 5 product max limit.

Basically, I get my data, group by cust_id, create the file structure, within that loop, group by product_id, rewrite the fields in previous file_struct with new product info.  That's worked all well and good until a user exceeded that max.

A brief example..  (keep in mind, the structure of the array is set by another process, this CANNOT change)

orderArray = arranyew(2);
set order = 1;

loop over cust_id;

    field[order][1] = "field(1)"; // cust_id
    field[order][2] = "field(2)"; // name
    field[order][3] = "field(3)"; // phone
    field[order][4] = ""; // product_1
    field[order][5] = ""; // quantity_1
    field[order][6] = ""; // product_2
    field[order][7] = ""; // quantity_2
    field[order][8] = ""; // product_3
    field[order][9] = ""; // quantity_3
    field[order][10] = ""; // product_4
    field[order][11] = ""; // quantity_4
    field[order][12] = ""; // product_5
    field[order][13] = ""; // quantity_5
    field[order][14] = "field(4)"; // trx_id
    field[order][15] = "field(5)"; // total_cost

    counter = 0;

    loop over product_id

        field[order[4+counter] = productCode;
        field[order[5+counter] = quantity;

        counter = counter + 2;

    end inner loop;

    order = order + 1;

end outer loop;

Like I said, this worked fine until I had a user who ordered more than 5 products.

What I basically want to do is check the number of products for each user if that number is greater than 5, start a new line in the text field, but I'm stufk on how to get there.

I've tried numerous fixes, but nothing gives the results I need.

I can send the entire file if It can help, but I don't want to post it all here.

Body:
You need to move the inserting of the header and footer fields into product loop eg. the custid and trx_id fields.

Here's a rough idea of one why you can go about this based on the pseudo code you provided. I'm sure that there are more elegant ways that you could code this.

set order = 0;

loop over cust_id;

counter = 1;
order = order + 1;

loop over product_id
    if (counter == 1 || counter == 6) {
        if (counter == 6) {
            counter == 1;
            order= order+1;
        }
        field[order][1] = "field(1)"; // cust_id
        field[order][2] = "field(2)"; // name
        field[order][3] = "field(3)"; // phone
    }

    field[order][counter+3] = productCode; // product_1
    field[order][counter+4] = quantity; // quantity_1

    counter = counter + 1;
    if (counter == 6) {
        field[order][14] = "field(4)"; // trx_id
        field[order][15] = "field(5)"; // total_cost
    }

end inner loop;

if (counter == 6) {
    // loop here to insert blank columns and the totals field to fill out the row.
}

end outer loop;

One thing goes concern me.  If you start a new line every five products then your transaction id and total cost is going to be entered into the file more than once. You know the receiving system.  It may be a non-issue.

Hope this helps

ContentLicense: CC BY-SA 2.5


问:
IBM MQ Open input count shows 2 for websphere MDB with max sessions 1 (Causing reordering of messages)
My issue is similar to : Spring JMS - IBM MQ has open input count issue

I have set up my Message Driven Bean to have max-sessions 1 for sequential message delivery in Websphere. So i assume only one connection should be open to that queue. I do see that open input count is 2 some times. Some times its two different process as in the picture, sometimes its the same. Is it normal behavior of websphere? Please do advise. I am investigating a messsage re-ordering issue, this will be of great help.

Websphere Version 8.5.1 and IBM MQ Version is 7.0
MDB is configured via Activation Spec

答:
The 2 instances your queue is opened are different as one has the queue opened for browsing and the other has it open for destructive gets. So I don't really see how having it opened twice like these would affect the ordering of the messages.

MQ doesn't guarantee the ordering of messages by default. If message ordering is really important you should use message groups, which explicitly define the ordering of messages in the MQMD of each message.

Without message groups you need to meet a number of requirements to assume message ordering is kept by MQ.


问:
OrientDB update a field with an addition to the already existing string
I have a vertex that contains a string. I would like to update this string by adding a string to the end. The outcome should be the original string + the new string. I thought I could do this with append but it keeps making an embedded set. The code below returns ['123abc'] instead of '123abc'

I've posted a similar question here, but did not find a remedy. This seems like a simple sql command but I do not know the code. Please note I have also tried using unwind but it did not work. Thank you.

```<code>CREATE VERTEX V SET foo = '123'
UPDATE V SET foo = (SELECT foo.append('abc')FROM(SELECT FROM V WHERE foo = '1'))
</code>```

答:
You can do it using

UPDATE V SET foo = foo.append('abc') where foo = '123'

Body:
I have a vertex that contains a string. I would like to update this string by adding a string to the end. The outcome should be the original string + the new string. I thought I could do this with append but it keeps making an embedded set. The code below returns ['123abc'] instead of '123abc'

I've posted a similar question here, but did not find a remedy. This seems like a simple sql command but I do not know the code. Please note I have also tried using unwind but it did not work. Thank you.

CREATE VERTEX V SET foo = '123'
UPDATE V SET foo = (SELECT foo.append('abc')FROM(SELECT FROM V WHERE foo = '1'))


问:
Ionic : Image Cropping
I am new to ionic framework and cordova. I have learnt to use the camera plugin.
Now after getting the image, I want to crop a part of it. The cropping aspect ratio must not be static, i.e, the cropping box should be scalable ( in up, down, right, left directions).

I went through jeduan/cordova-plugin-crop but was not able to understand as it used Ionic v2, and I am working with ionic v1.

Please guide me to achieve this..

Is there any plugin to do so ?

答:
I am using jr-rop library and it uses pure Angular approach.
You can use it as follows.

```<code>$jrCrop.crop({
    url: url,
    width: 200,
    height: 200
}).then(function(canvas) {
    // success!
    var image = canvas.toDataURL();
}, function() {
    // User canceled or couldn't load image.
});
</code>```

After cropping it returns canvas object that you can manipulate further if needed.

Regards.

Title: Ionic : Image Cropping

Body:
I am using jr-rop library and it uses pure Angular approach.
You can use it as follows.

$jrCrop.crop({
    url: url,
    width: 200,
    height: 200
}).then(function(canvas) {
    // success!
    var image = canvas.toDataURL();
}, function() {
    // User canceled or couldn't load image.
});

After cropping it returns canvas object that you can manipulate further if needed.

Regards.


问:
Clear button on addentry page doesn't work
This is my addentry blog page which I have made from scratch and there are underlying problems with this code particularly the clear button which is supposed to clear any text entered when the button is clicked on it doesn't work I have saved it as a html file is that the problem.

Also one other problem is the submit button it works but it doesn't pass any of the text to the index file I have written this as php and for some reason it whenever I click on the submit button it just redirects me back to the index page without posting the entry I have made.

```<code><!DOCTYPE html>
<html>
<head>

<script>
function message() {
    alert("Clear the form?");
}
</script>

<style>
body {background-color: beige;}
h1   {color: black;}
p    {color: black;}

textarea
{
    width: 50%;
    height: 150px;
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: white;
    font-size: 16px;
    resize: none;
}

div
{
    padding-left: 20px;
}

</style>
</head>
<meta charset="utf-8">

<link rel="stylesheet" href="../../main.css">
<title>Add an entry</title>
</head>

<body>

<div><h1>Add an entry</h1></div>
<div><p><b>Enter the title of the entry so the topic is clearly defined and then add the entry for the blog that you want to write about after finishing writing about your topic press the submit button to submit the entry which will be posted in the main page of the blog however if you wish to discard or clear your entry then press the clear button to remove your topic which you have written about.</b></p></div>

<form onreset="message()">
    <p><label>Title</label>
    <input type = "text" id = "myText"/></p>

    <p><label>Entry</label>
    <textarea>
<input type="clear">
</form>

<form>
    <p><label>Title</label>
    <input type = "text" id = "myText"/></p>

    <p><label>Entry</label>
    <textarea>

    </textarea></p>

</form>

<form method="post" action="index.html">
<button type="submit" value="Submit">Submit</button>  <input type="button" value="Clear" onclick="javascript:eraseText();">
</form>
</body>
</html>
</code>```

Particularly this part of the clear button code:

```<code><script>
    function message() {
        alert("Clear the form?");
    }
</script>

<form onreset="message()">
    <p><label>Title</label>
    <input type = "text" id = "myText"/></p>

    <p><label>Entry</label>
    <textarea>
    <input type="clear">
</form>
</code>```

And this is the submit button code:

```<code><form method="post" action="index.html">
    <button type="submit" value="Submit">Submit</button>
    <input type="button" value="Clear" onclick="javascript:eraseText();">
</form>
</code>```

答:
1) Just use input field with type="reset" it will clear the form

2) all your input field should be same form then only it will post to next page

note : your using more than one form and expecting other form values on index page.

<form method="post" action="index.html">

  Title
    <input type = "text" name="mytext" id ="myText"/>

  Entry
    <textarea name="area"> </textarea>

   <button type="submit" value="Submit">Submit</button>
    <input type="reset" value="Clear" >
</form>```

Body:
This is my addentry blog page which I have made from scratch and there are underlying problems with this code particularly the clear button which is supposed to clear any text entered when the button is clicked on it doesn't work I have saved it as a html file is that the problem.

Also one other problem is the submit button it works but it doesn't pass any of the text to the index file I have written this as php and for some reason it whenever I click on the submit button it just redirects me back to the index page without posting the entry I have made.

<!DOCTYPE html>

<meta charset="utf-8">

<link rel="stylesheet" href="../../main.css">
<title>Add an entry</title>

Add an entry

Enter the title of the entry so the topic is clearly defined and then add the entry for the blog that you want to write about after finishing writing about your topic press the submit button to submit the entry which will be posted in the main page of the blog however if you wish to discard or clear your entry then press the clear button to remove your topic which you have written about.

<form onreset="message()">

Title
    <input type = "text" id = "myText"/>

Entry
    <textarea>
<input type="clear">
</form>

<form>

Title
    <input type = "text" id = "myText"/>

Entry
    <textarea>

    </textarea>

</form>

<form method="post" action="index.html">
<button type="submit" value="Submit">Submit</button>  <input type="button" value="Clear" onclick="javascript:eraseText();">
</form>

Particularly this part of the clear button code:

<form onreset="message()">

Title
    <input type = "text" id = "myText"/>

Entry
    <textarea>
    <input type="clear">
</form>

And this is the submit button code:

<form method="post" action="index.html">
    <button type="submit" value="Submit">Submit</button>
    <input type="button" value="Clear" onclick="javascript:eraseText();">
</form>

Body:
1) Just use input field with type="reset" it will clear the form

2) all your input field should be same form then only it will post to next page

note : your using more than one form and expecting other form values on index page.

<form method="post" action="index.html">

  <label>Title</label>
    <input type = "text" name="mytext" id ="myText"/>
<br>
<br>
  <label>Entry</label>
    <textarea name="area"> </textarea>
<br>
<br>
   <button type="submit" value="Submit">Submit</button>
    <input type="reset" value="Clear" >
</form>


问:
You may need an appropriate loader to handle this file type upload image file
I am using an image file in react-babel-webpack. But it showing an error that

```<code>ERROR in ./public/assets/scissors.png
Module parse failed: /home/rohit/Desktop/game/public/assets/scissors.png
Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '�' (1:0)
</code>```

tool.component.js

```<code>import React from 'react';
import Paper from '../../public/assets/paper.png';
import Rock from '../../public/assets/rock.png';

class Tools extends React.Component {
  render(){
    return (
      <div>
      <img src={Paper} name="Paper" onClick={this.select.bind(this)} className="game-icon" alt="logo" />
      <img src={Rock} name="Rock" onClick={this.select.bind(this)} className="game-icon" alt="logo" />
      </div>
    );
  }
};

export default Tools;
</code>```

webpack.config.dev.js

```<code>import path from 'path'
import webpack from 'webpack';

export default {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, '/client/index.js')
  ],
  output: {
    path: '/',
    publicPath: '/'
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        include: path.join(__dirname, 'client'),
        loaders: [ 'react-hot', 'babel' ]
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]}
    ]
  },
  resolve: {
    extentions: [ '', '.js', '.css' ]
  }
}
</code>```

答:
add '.png' into the extensions array:

```<code>resolve: {
  extensions: [ '', '.js', '.css', '.png' ]
}
</code>```

edit: resolved typo

Body:
I am using an image file in react-babel-webpack. But it showing an error that

ERROR in ./public/assets/scissors.png
Module parse failed: /home/rohit/Desktop/game/public/assets/scissors.png
Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '�' (1:0)

tool.component.js

import React from 'react';
import Paper from '../../public/assets/paper.png';
import Rock from '../../public/assets/rock.png';

class Tools extends React.Component {
  render(){
    return (

    );
  }
};

export default Tools;

webpack.config.dev.js

import path from 'path'
import webpack from 'webpack';

export default {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, '/client/index.js')
  ],
  output: {
    path: '/',
    publicPath: '/'
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        include: path.join(__dirname, 'client'),
        loaders: [ 'react-hot', 'babel' ]
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]}
    ]
  },
  resolve: {
    extentions: [ '', '.js', '.css' ]
  }
}

Body:
add '.png' into the extensions array:

resolve: {
  extensions: [ '', '.js', '.css', '.png' ]
}

edit: resolved typo

ContentLicense: CC BY-SA 4.0


问:
html file page not showing in wordpress webpage?
If i add the following tag in wordpress page,

```<code><iframe src="file:///var/www/html/wordpress/wp-content/themes/codium-dn/fund.html" name="frame1" width="100%" height="100%" frameborder="no" scrolling="auto" align="center">
</iframe>
</code>```

it doesnt show that html file in wordpress webpage,

can anyone help me solve this. Is there any way to do it

Also help me if is there any way to convert that html file into shortcode

答:
It should be working, refer below link,

http://www.inmotionhosting.com/support/edu/wordpress/wordpress-introduction/adding-html-wordpress

Body:
If i add the following tag in wordpress page,

it doesnt show that html file in wordpress webpage,

can anyone help me solve this. Is there any way to do it

Also help me if is there any way to convert that html file into shortcode


问:
Veins delay does not change with beacon frequency or number of nodes
I'm trying to simulate an imergancy breaking application using veins and analyze its performance. Research papers on 802.11p shows that as beacon frequency and number of vehicles increase delay should increase considerably due to mac layer delay of the protocol ( for 50 vehicles at 8Hz  - about 300ms average delay).

But when simulating application with veins delay values does not show much different ( it ranges  from 1ms-4ms).I've checked the Mac layer functionality and it appears that the channel is idle most of the time. So when a packet reaches Mac layer the channel has already been idle for more than the DIFS so packet gets sent quickly. I tried increasing packet size and reducing bitrate. It increase the previous delay by a certain amount. But drastic increase of delay due to backoff process cannot be seen.
 Do you know why this happens ???

答:
As you use 802.11p the default data rate on the control channel is 6Mbits (source: ETSI EN 302 663)

750Mbyte/s = 750.000bytes/s

Your beacons contain 500bytes. So the transmission of a beacon takes about 0.0007 seconds. As you have about 50 cars in your multi lane scenario and for example they are sending beacons with a 10 hertz frequency, it takes about 0.35s from 1 second to transmit your 500 beacons.

In my opinion, this are to less cars to create your mentioned effect, because the channel is idling for about 60% of the time.


问:
Tomcat web.xml MIME mapping not working for .js.map file
Upon loading a page, I get the following lines in the log:

```<code>Mar 29, 2017 1:39:52 PM com.sun.faces.context.ExternalContextImpl getMimeType
WARNING: JSF1091: No mime type could be found for file jsxc.min.js.map.  To resolve this, add a mime-type mapping to the applications web.xml.
</code>```

To accomplish this, I added

```<code><mime-mapping>
    <extension>js.map</extension>
    <mime-type>application/json</mime-type>
</mime-mapping>
</code>```

to the web.xml file.  However, I am still getting the error. Why does it not accept the .js.map extension?

答:
The error is returned because of the way the Tomcat servlet looks up the MIME by extension, namely:

(file: java/org/apache/catalina/core/ApplicationContext.java)

```<code> // ...
 public String getMimeType(String file) {
    if (file == null)
        return (null);
    int period = file.lastIndexOf('.'); // <<<<<<<<<<<
    if (period < 0)
        return (null);
    String extension = file.substring(period + 1);
    if (extension.length() < 1)
        return (null);
    return (context.findMimeMapping(extension));
 }
 //...
</code>```

On the marked position, only the last bit of the file extension (.map) is preserved, and that will be what is looked up.

Body:
Upon loading a page, I get the following lines in the log:

Mar 29, 2017 1:39:52 PM com.sun.faces.context.ExternalContextImpl getMimeType
WARNING: JSF1091: No mime type could be found for file jsxc.min.js.map.  To resolve this, add a mime-type mapping to the applications web.xml.

To accomplish this, I added

<mime-mapping>
    <extension>js.map</extension>
    <mime-type>application/json</mime-type>
</mime-mapping>

to the web.xml file.  However, I am still getting the error. Why does it not accept the .js.map extension?

Body:
The error is returned because of the way the Tomcat servlet looks up the MIME by extension, namely:

(file: java/org/apache/catalina/core/ApplicationContext.java)

 // ...
 public String getMimeType(String file) {
    if (file == null)
        return (null);
    int period = file.lastIndexOf('.'); // <<<<<<<<<<<
    if (period < 0)
        return (null);
    String extension = file.substring(period + 1);
    if (extension.length() < 1)
        return (null);
    return (context.findMimeMapping(extension));
 }
 //...

On the marked position, only the last bit of the file extension (.map) is preserved, and that will be what is looked up.


问:
How to add external script to blogger
My blog is hosted in blogger and i want to add code snippet to my blogs. I followed this SO Post on how to add SyntaxHighlighter However i am not sure if that answer is still valid.

Questions

1>In html view, I don't see  element. Should i manually add  tag in html view? I thought html view is only for body element.

2>The SyntaxHighlighter scripts are hosted on CDN here. Which scripts i need to add for C#, html and javascript?

3> What is shAutoloader.js? does it load all the scripts?

I have created a sample blog here using Syntaxhighlighter but its not working

答:
Question no 1's Answer:

If you don't see any  tag you need to add it in your template but normally every HTML as well as blogger template has a  tag closed by

Second Question's Answer:

You need to use following attribute to load external files, you can use multiple but keep them in  of template for better performance:

```<code><script src="..../Link OF Code.js"></script>
</code>```

You can use defer="defer" tag in case if you want to load a script after the whole page is loaded successfully, here is a sample:

```<code><script defer="defer" src="..../Link OF Code.js"></script>
</code>```

Third Question's Answer:

I don't know it.

Title: How to add external script to blogger

Body:
Question no 1's Answer:

If you don't see any  tag you need to add it in your template but normally every HTML as well as blogger template has a  tag closed by

Second Question's Answer:

You need to use following attribute to load external files, you can use multiple but keep them in  of template for better performance:

<script src="..../Link OF Code.js"></script>

You can use defer="defer" tag in case if you want to load a script after the whole page is loaded successfully, here is a sample:

<script defer="defer" src="..../Link OF Code.js"></script>

Third Question's Answer:

I don't know it.


答:
The following Worksheet_Change event should be able to solve your problem:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range
Dim tmp As String
If Intersect(Range("B:B"), Target) Is Nothing Then Exit Sub

For Each cell In Target
    If cell.Column = 2 Then
        Application.EnableEvents = False
        tmp = cell.Value2
        cell.Parent.Hyperlinks.Add _
            Anchor:=Cells(cell.Row, 2), _
            Address:="http://example.com/id=" & tmp, _
            TextToDisplay:=tmp
        Application.EnableEvents = True
    End If
Next cell

End Sub
</code>```

Note, that you must copy it to the sheet and not into a separate module.

Title: Excel VBA: How to autocreate hyperlink from cell value?

Body:
I have a table called Table1

In Column B, I have the ticket number. e.g: 76537434

Requirement: when any change happens in any cell in column B, that cell (Target cell) to be changed into a hyperlink such that the hyperlink address would be example.com/id=76537434

Cell value i.e. 76537434 must remain the same

Body:
The following Worksheet_Change event should be able to solve your problem:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range
Dim tmp As String
If Intersect(Range("B:B"), Target) Is Nothing Then Exit Sub

For Each cell In Target
    If cell.Column = 2 Then
        Application.EnableEvents = False
        tmp = cell.Value2
        cell.Parent.Hyperlinks.Add _
            Anchor:=Cells(cell.Row, 2), _
            Address:="http://example.com/id=" & tmp, _
            TextToDisplay:=tmp
        Application.EnableEvents = True
    End If
Next cell

End Sub

Note, that you must copy it to the sheet and not into a separate module.


问:
timer fire twice
i ve used some ex from stackoverflow but sometimes my timer fire twice:
this clock should fire each one minute, but just assume that it fires 00:00:59.666
then step1 = 59;
step2 = 59;
step3 = 1;
return (1000-666); so it should fire not next minute but next 333 mili second, what can i do? </p>

```<code>public int SyncTime = 60;
Clock = new System.Timers.Timer {AutoReset = false};
            Clock.Elapsed += DoJob;
            Clock.Interval = GetSync(SyncTime);
            Clock.Start()
   private void DoJob(object sender, ElapsedEventArgs elapsedEventArgs)
   {

            Clock.Interval = GetSync(SyncTime);
            Clock.Start();

    }
    private static double GetSync(int syncTime)
    {
        DateTime now = DateTime.Now;
        int step1 = (now.Minute * 60 + now.Second); //amount of miliseconds in this hour
        int step2 = step1 % syncTime;               //amount of miliseconds since last update
        int step3 = syncTime - step2;               //amount of miliseconds to next upadte
        return (step3 * 1000 - now.Millisecond);
    }
</code>```

答:
I suspect that the issue is in the line:

```<code>Clock = new System.Timers.Timer {AutoReset = false};
</code>```

I think this should read:

```<code>Clock = new System.Timers.Timer {AutoReset = true};
</code>```

This will mean that the timer will fire only once until you reissue the Start command.

Title: timer fire twice

Body:
i ve used some ex from stackoverflow but sometimes my timer fire twice:
this clock should fire each one minute, but just assume that it fires 00:00:59.666
then step1 = 59;
step2 = 59;
step3 = 1;
return (1000-666); so it should fire not next minute but next 333 mili second, what can i do?

public int SyncTime = 60;
Clock = new System.Timers.Timer {AutoReset = false};
            Clock.Elapsed += DoJob;
            Clock.Interval = GetSync(SyncTime);
            Clock.Start()
   private void DoJob(object sender, ElapsedEventArgs elapsedEventArgs)
   {

            Clock.Interval = GetSync(SyncTime);
            Clock.Start();

    }
    private static double GetSync(int syncTime)
    {
        DateTime now = DateTime.Now;
        int step1 = (now.Minute * 60 + now.Second); //amount of miliseconds in this hour
        int step2 = step1 % syncTime;               //amount of miliseconds since last update
        int step3 = syncTime - step2;               //amount of miliseconds to next upadte
        return (step3 * 1000 - now.Millisecond);
    }

Body:
I suspect that the issue is in the line:

Clock = new System.Timers.Timer {AutoReset = false};

I think this should read:

Clock = new System.Timers.Timer {AutoReset = true};

This will mean that the timer will fire only once until you reissue the Start command.


问:
Best XML serialization library for a MFC C++ app
I have an application, written in C++ using MFC and Stingray libraries.  The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality.  I have also added options for XML serialization based on the Stingray libraries, which implements DOM via the Microsoft XML SDK.  While easy to implement the performance is terrible, to the extent that it is unusable on anything other than very small documents.

What other XML serialization tools would you folks recommend for this scenario.  I don't want DOM, as it seems to be a memory hog, and I'm already dealing with large in memory data.  Ideally, i'd like a streaming parser that is fast, and easy to use with MFC.  My current front runner is expat which is fast and simple, but would require a lot of class by class serialization code to be added.  Any other efficient and easier to implement alternatives out there that people would recommend?

答:
This is late in the game, I just want to mention that we also use LIBXML. It's robust and reliable, and has worked well. A little bit too low-level, you'll want to build some wrappers on top of its functions.

For instance, you'll get a different sequence of function returns depending on whether you have this:

```<code><tag attribute="value"/>
</code>```

or this:

```<code><tag attribute="value"> </tag>
</code>```

Sometimes you may want that, sometimes you don't care.

OwnerDisplayName: smacl

Body:
This is late in the game, I just want to mention that we also use LIBXML. It's robust and reliable, and has worked well. A little bit too low-level, you'll want to build some wrappers on top of its functions.

For instance, you'll get a different sequence of function returns depending on whether you have this:

<tag attribute="value"/>

or this:

<tag attribute="value"> </tag>

Sometimes you may want that, sometimes you don't care.


问:
Navigation bar item as tab bar item

I did search something similar with my question, but didn't find anything to help me solve my issue.

Is it possible to set behavior for navigation bar item as tab bar item?

I use TabBarController. Each tab item should show the corresponding ViewController. When user tap on the item in nav bar it should show the corresponding ViewController too with the bottom tab bar. And this ViewController should be as tab bar controller, but not display tab item in the bottom tab bar.

How I can achieve the scenario describe above? Or any alternative idea how it possible to implement, please! Almost always the top and bottom bars should be visible for each ViewController.

答:
Drag and drop from your bar button item in IB to your class file and define an outlet, then in viewDidLoad create a gesture recognizer, add an action to your gesture recognizer and you are all set. I hope it helps. </p>

```<code>class SomeClass: UIViewControler {

let someBarButton:UIBarButtonItem!
  override func viewDidLoad() {
    super.viewDidLoad()

      let tap = UITapGestureRecognizer(target: self, action: #selector(SomeClass.tapFunction))
             someBarButton.addGestureRecognizer(tap)
   }

  func tapFunction() {
    //take me to a view controller
   self.performSegue(withIdentifier: "myIdentifier", sender: self)
  }
}
</code>```

Title: Navigation bar item as tab bar item

Body:
Drag and drop from your bar button item in IB to your class file and define an outlet, then in viewDidLoad create a gesture recognizer, add an action to your gesture recognizer and you are all set. I hope it helps.

class SomeClass: UIViewControler {

let someBarButton:UIBarButtonItem!
  override func viewDidLoad() {
    super.viewDidLoad()

      let tap = UITapGestureRecognizer(target: self, action: #selector(SomeClass.tapFunction))
             someBarButton.addGestureRecognizer(tap)
   }

  func tapFunction() {
    //take me to a view controller
   self.performSegue(withIdentifier: "myIdentifier", sender: self)
  }
}


问:
Find an exact match from search in array of objects using mongodb
I'm querying for all of the data in my database and running a search against it using the following code.

The problem is that it doesn't query for an exact match, it's a keyword search.

If I enter "dog colorado" it returns all results containing the words "dog" and "colorado".

I'd like it to return results for "dog colorado".

I am using Mongodb for reference

```<code>$http.get('/sapi/search/contractors?query=' + $scope.data.query)
  .then(function(res) {
    console.log("response from query", res.data);
    // if it gets all the data
    if (res.data.users && res.data.users.length) {
      $scope.items = _.filter(res.data.users, function(user) {
        return user.roles && user.roles.indexOf('contractor') !== -1 && user.firstName;
      });
    } else {
      console.log('no items', res);
      $scope.items = null;
    }
</code>```

答:
Alright you are using mongodb, so you need to use the mongo querying system with a regex to get exact match.

```<code>db.collection.find({yourattributeyouwanttomatch: {$regex: new RegExp('^' +  query + '$', 'i')}})
</code>```

You can remove the 'i' if you want case sensitive and you can remove the ^ and $ if you want to match anywhere in the string.

Body:
I'm querying for all of the data in my database and running a search against it using the following code.

The problem is that it doesn't query for an exact match, it's a keyword search.

If I enter "dog colorado" it returns all results containing the words "dog" and "colorado".

I'd like it to return results for "dog colorado".

I am using Mongodb for reference

$http.get('/sapi/search/contractors?query=' + $scope.data.query)
  .then(function(res) {
    console.log("response from query", res.data);
    // if it gets all the data
    if (res.data.users && res.data.users.length) {
      $scope.items = _.filter(res.data.users, function(user) {
        return user.roles && user.roles.indexOf('contractor') !== -1 && user.firstName;
      });
    } else {
      console.log('no items', res);
      $scope.items = null;
    }

Body:
Alright you are using mongodb, so you need to use the mongo querying system with a regex to get exact match.

db.collection.find({yourattributeyouwanttomatch: {$regex: new RegExp('^' +  query + '$', 'i')}})

You can remove the 'i' if you want case sensitive and you can remove the ^ and $ if you want to match anywhere in the string.


问:
How to add offline event handling in Openfire plugin?
I am java newbie . I need to handle offline sessions in Openfire plugin. From plugin development doc I am able to understand the basics , but I am not getting how can I handle offline event of openfire.
There is a class "SessionEventDispatcher" in package org.jivesoftware.openfire.event

There we have following predefined events:

```<code>session_created
session_destroyed
anonymous_session_created
anonymous_session_destroyed
resource_bound
</code>```

These events then have listener , which is implemented in the Presence plugin.
Please help me understand how to proceed if I need to add offline event as well.

I am saving online users in redis but some how user sessions in openfire is less than users in redis, which means I am not handling some offline event in my plugin due to which user session is created and get added in redis , but user session is not closed explicitly which is handled to get remove from redis, and I face this discrepancy.

答:
please correct me if I don`t understand your question clearly.
Do you examine interface org.jivesoftware.openfire.user.PresenceEventListener?
For example I implement that interface :

```<code>public class CustomPresenceEventListener implements PresenceEventListener {

private static final Logger LOG = LoggerFactory.getLogger(CustomPresenceEventListener.class);

@Override
public void availableSession(ClientSession session, Presence presence) {
    LOG.info("\n\n=======SESSION AVAILABLE=========\n");
    try {
        LOG.info("USER : {}", session.getUsername());
    } catch (UserNotFoundException e) {
        LOG.info(e.getMessage(), e);
    }
    LOG.info("\n================\n\n");
}

@Override
public void unavailableSession(ClientSession session, Presence presence) {
    LOG.info("\n\n=======SESSION UNAVAILABLE=========\n");
    try {
        LOG.info("USER : {}", session.getUsername());
    } catch (UserNotFoundException e) {
        LOG.info(e.getMessage(), e);
    }
    LOG.info("\n================\n\n");
}

@Override
public void presenceChanged(ClientSession session, Presence presence) {
}

@Override
public void subscribedToPresence(JID subscriberJID, JID authorizerJID) {

}

@Override
public void unsubscribedToPresence(JID unsubscriberJID, JID recipientJID) {

}
</code>```

And add/remove this listener with :

```<code>PresenceEventDispatcher.addListener(presenceEventListener);
PresenceEventDispatcher.removeListener(presenceEventListener);
</code>```

And when I connect to Openfire I will see in the file info.log something like that :
=======SESSION AVAILABLE=========
2017.03.29 14:27:01 .CustomPresenceEventListener - USER : 25

2017.03.29 14:27:01 .CustomPresenceEventListener -

And when I leave Openfire logs will be :
=======SESSION UNAVAILABLE=========
2017.03.29 14:27:34  .CustomPresenceEventListener - USER : 25

2017.03.29 14:27:34  .CustomPresenceEventListener -

So you could add any action you want when user enter/leave Openfire.

Body:
I am java newbie . I need to handle offline sessions in Openfire plugin. From plugin development doc I am able to understand the basics , but I am not getting how can I handle offline event of openfire.
There is a class "SessionEventDispatcher" in package org.jivesoftware.openfire.event

There we have following predefined events:

session_created
session_destroyed
anonymous_session_created
anonymous_session_destroyed
resource_bound

These events then have listener , which is implemented in the Presence plugin.
Please help me understand how to proceed if I need to add offline event as well.

I am saving online users in redis but some how user sessions in openfire is less than users in redis, which means I am not handling some offline event in my plugin due to which user session is created and get added in redis , but user session is not closed explicitly which is handled to get remove from redis, and I face this discrepancy.

Body:
please correct me if I don`t understand your question clearly.
Do you examine interface org.jivesoftware.openfire.user.PresenceEventListener?
For example I implement that interface :

public class CustomPresenceEventListener implements PresenceEventListener {

private static final Logger LOG = LoggerFactory.getLogger(CustomPresenceEventListener.class);

@Override
public void availableSession(ClientSession session, Presence presence) {
    LOG.info("\n\n=======SESSION AVAILABLE=========\n");
    try {
        LOG.info("USER : {}", session.getUsername());
    } catch (UserNotFoundException e) {
        LOG.info(e.getMessage(), e);
    }
    LOG.info("\n================\n\n");
}

@Override
public void unavailableSession(ClientSession session, Presence presence) {
    LOG.info("\n\n=======SESSION UNAVAILABLE=========\n");
    try {
        LOG.info("USER : {}", session.getUsername());
    } catch (UserNotFoundException e) {
        LOG.info(e.getMessage(), e);
    }
    LOG.info("\n================\n\n");
}

@Override
public void presenceChanged(ClientSession session, Presence presence) {
}

@Override
public void subscribedToPresence(JID subscriberJID, JID authorizerJID) {

}

@Override
public void unsubscribedToPresence(JID unsubscriberJID, JID recipientJID) {

}

And add/remove this listener with :

PresenceEventDispatcher.addListener(presenceEventListener);
PresenceEventDispatcher.removeListener(presenceEventListener);

And when I connect to Openfire I will see in the file info.log something like that :
=======SESSION AVAILABLE=========
2017.03.29 14:27:01 .CustomPresenceEventListener - USER : 25

2017.03.29 14:27:01 .CustomPresenceEventListener -

And when I leave Openfire logs will be :
=======SESSION UNAVAILABLE=========
2017.03.29 14:27:34  .CustomPresenceEventListener - USER : 25

2017.03.29 14:27:34  .CustomPresenceEventListener -

So you could add any action you want when user enter/leave Openfire.