问:
Converting ControlTemplate XAML to C#
I have been stumped with trying to convert the following code into pure c#.  This XAML code is from Cavanaghs blog on how to make rounded corners on anything.  The code works but I need to convert it to c# as i need it to be dynamic in some cases.  If you could help that would be great.

```<code><Setter Property="Template">
<Setter.Value>
    <ControlTemplate TargetType='{x:Type ListViewItem}'>
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Setter.Value>
</code>```

So far I have the following but I am getting errors.

```<code>FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(8, 8, 8, 8));
border.SetValue(Border.NameProperty, "roundedMask");
</code>```

As far as I can tell I cant make the VisualBrush as a FrameworkElementFactory (crashes), but if i declare it as a regular element VisualBrush i cant pass border in as a Visual since its a FrameworkElementFactory.

Simply i am getting lost, any help would be appreciated.
Thanks for any help

答:
You do not want to know this. Seriously, you don't, it's a nightmare.

Edit: If i did not make any mistake this is the translation of your code...

```<code>Setter setter = new Setter();
setter.Property = ListViewItem.TemplateProperty;
ControlTemplate template = new ControlTemplate(typeof(ListViewItem));
var grid = new FrameworkElementFactory(typeof(Grid));
var border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.NameProperty, "mask");
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(15));
grid.AppendChild(border);
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.BackgroundProperty, Brushes.Beige);
var visualBrush = new FrameworkElementFactory(typeof(VisualBrush));
visualBrush.SetBinding(VisualBrush.VisualProperty, new Binding() { ElementName = "mask" });
stackPanel.SetValue(StackPanel.OpacityMaskProperty, visualBrush);
var gridViewRowPresenter = new FrameworkElementFactory(typeof(GridViewRowPresenter));
gridViewRowPresenter.SetValue(GridViewRowPresenter.ContentProperty, new TemplateBindingExtension(GridViewRowPresenter.ContentProperty));
gridViewRowPresenter.SetValue(GridViewRowPresenter.ColumnsProperty, new TemplateBindingExtension(GridView.ColumnCollectionProperty));
stackPanel.AppendChild(gridViewRowPresenter);
var textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.BackgroundProperty, Brushes.LightBlue);
textBlock.SetBinding(TextBlock.TextProperty, new Binding("News"));
stackPanel.AppendChild(textBlock);
grid.AppendChild(stackPanel);
template.VisualTree = grid;
setter.Value = template;
</code>```

Edit: There is still a bug left, the VisualBrush cannot be created like that, the rest seems to work.

Title: Converting ControlTemplate XAML to C#

Body:
I have been stumped with trying to convert the following code into pure c#.  This XAML code is from Cavanaghs blog on how to make rounded corners on anything.  The code works but I need to convert it to c# as i need it to be dynamic in some cases.  If you could help that would be great.

<Setter Property="Template">
<Setter.Value>
    <ControlTemplate TargetType='{x:Type ListViewItem}'>
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Setter.Value>

So far I have the following but I am getting errors.

FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(8, 8, 8, 8));
border.SetValue(Border.NameProperty, "roundedMask");

As far as I can tell I cant make the VisualBrush as a FrameworkElementFactory (crashes), but if i declare it as a regular element VisualBrush i cant pass border in as a Visual since its a FrameworkElementFactory.

Simply i am getting lost, any help would be appreciated.
Thanks for any help

Body:
You do not want to know this. Seriously, you don't, it's a nightmare.

Edit: If i did not make any mistake this is the translation of your code...

Setter setter = new Setter();
setter.Property = ListViewItem.TemplateProperty;
ControlTemplate template = new ControlTemplate(typeof(ListViewItem));
var grid = new FrameworkElementFactory(typeof(Grid));
var border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.NameProperty, "mask");
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(15));
grid.AppendChild(border);
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.BackgroundProperty, Brushes.Beige);
var visualBrush = new FrameworkElementFactory(typeof(VisualBrush));
visualBrush.SetBinding(VisualBrush.VisualProperty, new Binding() { ElementName = "mask" });
stackPanel.SetValue(StackPanel.OpacityMaskProperty, visualBrush);
var gridViewRowPresenter = new FrameworkElementFactory(typeof(GridViewRowPresenter));
gridViewRowPresenter.SetValue(GridViewRowPresenter.ContentProperty, new TemplateBindingExtension(GridViewRowPresenter.ContentProperty));
gridViewRowPresenter.SetValue(GridViewRowPresenter.ColumnsProperty, new TemplateBindingExtension(GridView.ColumnCollectionProperty));
stackPanel.AppendChild(gridViewRowPresenter);
var textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.BackgroundProperty, Brushes.LightBlue);
textBlock.SetBinding(TextBlock.TextProperty, new Binding("News"));
stackPanel.AppendChild(textBlock);
grid.AppendChild(stackPanel);
template.VisualTree = grid;
setter.Value = template;

Edit: There is still a bug left, the VisualBrush cannot be created like that, the rest seems to work.


来源: stackexchange

问:
In .NET, when do I have to reference a DLL that an external library also references?
I'm trying to understand when it's necessary for my .NET project to reference a DLL that an external library references.

A practical example: Microsoft.Bot.Builder depends on Chronic.Signed.dll

If I reference Microsoft.Bot.Builder.dll, do I always have to also add a reference to Chronic.Signed.dll in my own project, even if I'm not using it directly? Or do I only have to only under certain circumstances?

答: You need to do this when you make use of something in Microsoft.Bot.Builder that exposes something from Chronic.Signed in its public API.  For example (and without going through the libraries myself), let's say Chronic.Signed.IFoo is an interface that Microsoft.Bot.Builder.FooImpl implements.  If you reference Microsoft.Bot.Builder.FooImpl in your code then you also need to reference Chronic.Signed so that your code has access to the interface.

ContentLicense: CC BY-SA 3.0


问:
SQL ORACLE SELECT WILDCARD Invalid Number
I encountered a weird error in Oracle SQL. It prompts me an error that says 'Invalid Number' even though the field/column is not Number.

Y'all have any idea what's going on?

Here's the SQL.

```<code>Select * from Products where Prod_nm like '%A%';
</code>```

I use this same SQL statement on other Tables and got no errors.

Thanks in Advance!

答:
As you can read here:

An ORA-01722 ("invalid number") error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a valid number... When doing a SELECT... Check for a numeric column being compared to a character column...

The conclusion is that your table column Prod_nm must be a numeric column, otherwise this error message would have never appeard. Double check your database structure.

EDIT

As you mentioned in the comments, the query you are using:

```<code>Select * from Products
Inner join Review
ON Products.prod_id = Review.prod_id
where Products.prod_nm like '%A%'
</code>```

Is joining (using ON) a numeric column (Review.prod_id) with a varchar column (Products.prod_id), and that is where the error comes from.

Body:
I encountered a weird error in Oracle SQL. It prompts me an error that says 'Invalid Number' even though the field/column is not Number.

Y'all have any idea what's going on?

Here's the SQL.

Select * from Products where Prod_nm like '%A%';

I use this same SQL statement on other Tables and got no errors.

Thanks in Advance!

Body:
As you can read here:

An ORA-01722 ("invalid number") error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a valid number... When doing a SELECT... Check for a numeric column being compared to a character column...

The conclusion is that your table column Prod_nm must be a numeric column, otherwise this error message would have never appeard. Double check your database structure.

EDIT

As you mentioned in the comments, the query you are using:

Select * from Products
Inner join Review
ON Products.prod_id = Review.prod_id
where Products.prod_nm like '%A%'

Is joining (using ON) a numeric column (Review.prod_id) with a varchar column (Products.prod_id), and that is where the error comes from.


问:
Nativescript command run
I have installed Android-SDK in my ARC Linux system.
but when run command tns run android

The ANDROID_HOME environment variable is not set or it points to a non-existent directory. You will not be able to perform any build-related operations for Android.

Please help.
Thanks.

答:
Add ANDROID_HOME and PATH in .profile file in $HOME directory as :

```<code>export ANDROID_HOME="path/to/android-sdk" export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
</code>```

Then try add android as :

```<code>tns platform add android
</code>```

For any doubt refer here : https://github.com/NativeScript/nativescript-cli/issues/1097
This is the original post in NativeScript Github page

Title: Nativescript command run

Body:
Add ANDROID_HOME and PATH in .profile file in $HOME directory as :

export ANDROID_HOME="path/to/android-sdk" export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Then try add android as :

tns platform add android

For any doubt refer here : https://github.com/NativeScript/nativescript-cli/issues/1097
This is the original post in NativeScript Github page


问:
How to get the DataSet to recognize the table names from stored procedure?
I have a stored procedures which returns about 5 tables and I am returning them something like this:

```<code>select <fields> from Products where ProductId = @ProductId
select <fields> from RelatedProducts where ProductId = @ProductId
select <fields> from MetaData where ProductId = @ProductId
</code>```

well, you get the gist. Now in the Dataset, If I do this:

```<code>DataSet ProductDs = DAL.RetreiveProductMetadata(someInteger);

ProductName = DataSet.Tables["Products"].Rows[0]["columnName"].ToString();
</code>```

Its throwing up an exception... well, error saying TableName is null and upon debugging, turns out, the table names are actually named as "Results1", "Results2" and so on.

I tried changing stored proc to:

```<code>select * From products AS Products
</code>```

no effect.

How can I get C# to detect and use the Table Names from the database?

ps: I have all sorts of Coalesces and cases in the field, that shouldn't present a problem right?

Also, tried googling and banging head - neither worked.

答:
You can't. The table name has no meaning in the result set because a query can contain many tables.

You should know what your resultsets are and should not have to derive table names.

Otherwise,

```<code>select 'Products' AS ThisTable, <fields> from Products where ProductId = @ProductId
</code>```

Or JOIN first and unpick later

Or define your dataset.xsd etc up front and map according.

ContentLicense: CC BY-SA 2.5

Body:
I have a stored procedures which returns about 5 tables and I am returning them something like this:

select <fields> from Products where ProductId = @ProductId
select <fields> from RelatedProducts where ProductId = @ProductId
select <fields> from MetaData where ProductId = @ProductId

well, you get the gist. Now in the Dataset, If I do this:

DataSet ProductDs = DAL.RetreiveProductMetadata(someInteger);

ProductName = DataSet.Tables["Products"].Rows[0]["columnName"].ToString();

Its throwing up an exception... well, error saying TableName is null and upon debugging, turns out, the table names are actually named as "Results1", "Results2" and so on.

I tried changing stored proc to:

select * From products AS Products

no effect.

How can I get C# to detect and use the Table Names from the database?

ps: I have all sorts of Coalesces and cases in the field, that shouldn't present a problem right?

Also, tried googling and banging head - neither worked.

Body:
You can't. The table name has no meaning in the result set because a query can contain many tables.

You should know what your resultsets are and should not have to derive table names.

Otherwise,

select 'Products' AS ThisTable, <fields> from Products where ProductId = @ProductId

Or JOIN first and unpick later

Or define your dataset.xsd etc up front and map according.


问:
Image scaling on canvas with fabric js
Please check attached screenshot
I have set image using setFill to svg image. Once image get set I have to change width, height or perform operation on image. How I can get fill image object when user select svg on canvas.</p>

答:
scaling : </p>

```<code>        image.on('scaling', function (opt) {

        var r = canvas.getRetinaScaling();
        var sX = Math.abs(this.scaleX) * r;
        var sY = Math.abs(this.scaleY) * r;

        canvas.setWidth(image.width * sX);
        canvas.setHeight(image.height * sY);

        canvas.renderAll();
   });

   $("#save1").click(function () {

var arrFormat = g_filename.split('.');
var arrFilename = g_filename.split('/');
var filename;
var format;

if (arrFormat.length == 1)
    format = "image/" + "jpg";
else {
    format = "image/" + arrFormat[arrFormat.length - 1];
}

if (arrFilename == 1)
    filename = g_filename;
else {
    filename = arrFilename[arrFilename.length - 1];
}

var serverUrl = "/Home/UploadImg5";
var imageName = filename;

// 이미지를 첫번째것을 가져온다.
var obj = canvas.item(0);

var width = Math.abs(image.width * image.scaleX);
var height = Math.abs(image.height * image.scaleY);

var dataURL = canvas.toDataURL({ format: format, left: obj.left, top: obj.top, width: width / ratio, height: height / ratio });

canvas.discardActiveObject();
canvas.renderAll();

$.ajax({
    type: 'POST',
    url: serverUrl,
    data: {
        title: imageName,
        type: "jpg",
        image: dataURL // Step 1에서 가져온 데이터
    }
}).done(function () {

    console.log('saved!');
});
</code>```

Title: Image scaling on canvas with fabric js

Body:
scaling :

        image.on('scaling', function (opt) {

        var r = canvas.getRetinaScaling();
        var sX = Math.abs(this.scaleX) * r;
        var sY = Math.abs(this.scaleY) * r;

        canvas.setWidth(image.width * sX);
        canvas.setHeight(image.height * sY);

        canvas.renderAll();
   });

   $("#save1").click(function () {

var arrFormat = g_filename.split('.');
var arrFilename = g_filename.split('/');
var filename;
var format;

if (arrFormat.length == 1)
    format = "image/" + "jpg";
else {
    format = "image/" + arrFormat[arrFormat.length - 1];
}

if (arrFilename == 1)
    filename = g_filename;
else {
    filename = arrFilename[arrFilename.length - 1];
}

var serverUrl = "/Home/UploadImg5";
var imageName = filename;

// 이미지를 첫번째것을 가져온다.
var obj = canvas.item(0);

var width = Math.abs(image.width * image.scaleX);
var height = Math.abs(image.height * image.scaleY);

var dataURL = canvas.toDataURL({ format: format, left: obj.left, top: obj.top, width: width / ratio, height: height / ratio });

canvas.discardActiveObject();
canvas.renderAll();

$.ajax({
    type: 'POST',
    url: serverUrl,
    data: {
        title: imageName,
        type: "jpg",
        image: dataURL // Step 1에서 가져온 데이터
    }
}).done(function () {

    console.log('saved!');
});


问:
Angular 4 resolve component from dynamic HTML
I am currently facing an issue while trying to parse and inject HTML into my application.

I get a string from an API

String is parsed, and some content is replaced by a tag at the service level. The new string looks like this:

```<code>[mention]{\"label\": \"Stack\"}[/mention] with some other text
and a second [mention]{\"label\": \"Overflow\"}[/mention] with text
</code>```

Then the string is displayed by a component in the view

{{ parsedString }}

```</li>
</ol>

<p>I tried multiple methods like using <code>innerHTML</code> with a sanitizeHTML pipe, and read some posts of people having this issue when adding router links to their HTML, but I seem to not understand properly how to use <code>viewContainerRef</code> in my case.</p>

<p>I saw this answer linked multiple times, but to me it's a mashed potato of code and I cannot get the logic behind it...</p>

<hr>

<h2>Update</h2>

<p>So I ended up using a <code>Pipe</code> to parse the string and have a template using each part of the string to display a component if needed.</p>

<ol>
<li>My view component gets the string from an API  </li>
<li>The view component inserts the string in its template and use a pipe to parse it.</li>
<li>The filter returns an array of strings which can be used in an <code>*ngFor</code> loop</li>
</ol>

<p><strong><code>view.component.ts</code></strong></p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let string of text | mentions">
    <ng-container *ngIf="string.label">
        <mention> <!-- We can use a component with dynamic HTML ! -->
            {{ string.label }}
        </mention>
    </ng-container>

    <ng-container *ngIf="!string.label">
        {{ string }}
    </ng-container>
</div>
</code>```

mentions.pipe.ts

/* Angular */
import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'mentions'
})

@Injectable()
export class MentionsPipe implements PipeTransform {
    tryParseJSON(string: string) {
        try {
            const json = JSON.parse(string);

            if (json && typeof json === 'object') {
                return json;
            }
        } catch (e) {}

        return string;
    };

    transform(value: string) {
        const regex = /\[mention\]([^[]*(?:\[(?!mention\]|\/mention\])[^[]*)*)\[\/mention\]/ig;

        return value
            .split(regex)
            .map((match: string) => {
                // The mention is a stringified JSON, so we want to parse it
                return this.tryParseJSON(match);
            });
    }
}
```

This may not be the best solution as it would mean using the pipe in an *ngFor loop each time we know that dynamic HTML will include mentions (in my case), but for now I am ok with this, until Angular provides a nice and secured way to detect and replace components in injected HTML.

答:
Angular blocks run time compile. So you need to do some tricks.
https://github.com/patrikx3/angular-compile => works on Angular 4. Not 5, so it has no future.

I've solved this problem using dynamic components.
I can recommend https://medium.com/front-end-hacking/dynamically-add-components-to-the-dom-with-angular-71b0cb535286 this guide.

Body:
I am currently facing an issue while trying to parse and inject HTML into my application.

I get a string from an API

String is parsed, and some content is replaced by a tag at the service level. The new string looks like this:

[mention]{\"label\": \"Stack\"}[/mention] with some other text
and a second [mention]{\"label\": \"Overflow\"}[/mention] with text

Then the string is displayed by a component in the view

{{ parsedString }}

I tried multiple methods like using innerHTML with a sanitizeHTML pipe, and read some posts of people having this issue when adding router links to their HTML, but I seem to not understand properly how to use viewContainerRef in my case.

I saw this answer linked multiple times, but to me it's a mashed potato of code and I cannot get the logic behind it...

Update

So I ended up using a Pipe to parse the string and have a template using each part of the string to display a component if needed.

My view component gets the string from an API

The view component inserts the string in its template and use a pipe to parse it.

The filter returns an array of strings which can be used in an *ngFor loop

view.component.ts

    <ng-container *ngIf="string.label">
        <mention>
            {{ string.label }}
        </mention>
    </ng-container>

    <ng-container *ngIf="!string.label">
        {{ string }}
    </ng-container>

mentions.pipe.ts

/* Angular */
import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'mentions'
})

@Injectable()
export class MentionsPipe implements PipeTransform {
    tryParseJSON(string: string) {
        try {
            const json = JSON.parse(string);

            if (json && typeof json === 'object') {
                return json;
            }
        } catch (e) {}

        return string;
    };

    transform(value: string) {
        const regex = /\[mention\]([^[]*(?:\[(?!mention\]|\/mention\])[^[]*)*)\[\/mention\]/ig;

        return value
            .split(regex)
            .map((match: string) => {
                // The mention is a stringified JSON, so we want to parse it
                return this.tryParseJSON(match);
            });
    }
}

This may not be the best solution as it would mean using the pipe in an *ngFor loop each time we know that dynamic HTML will include mentions (in my case), but for now I am ok with this, until Angular provides a nice and secured way to detect and replace components in injected HTML.


问:
PowerShell: Parsing Through XML with the name "ADDRESS"
XML:

```<code><ServerList>
<ServerInfo ServerType="text" RPCServerPort="111" Port="110" Address="Server01" Name="Name1">
<ServerInfo ServerType="text" RPCServerPort="111" Port="110" Address="Server02" Name="Name2">
</code>```

When I try to navigate in XML as such, it works:

```<code>[xml]$results = Get-Content C:\Users\myself\Desktop\file.xml
$results.ServerList.ServerInfo
</code>```

Also:

This works: $results.ServerList.Name

This works: $results.ServerList.Port

This works: $results.ServerList.RPCServerPort

However, this doesn't work: $results.ServerList.Address

I am getting a OverloadDefinitions result which has nothing to do with the content of the XML.

'Address' seems to do try to do something else, does anyone knows how to list the ADDRESS content in the XML ?

答:
Arrays have a method known as Address defined in the CIL for retrieving items in the array.

```<code>$results.ServerList.ServerInfo.Address

OverloadDefinitions
-------------------
System.Object&, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Address(int )
</code>```

In this case when you call Address you assume PowerShell should retrieve each items' Address property, but PowerShell is returning the definition for the Address method of the array that contains those items.

If you want to access the properties you will need to change the property names so that they no longer match a method signature or loop through the items in the array and retrieve the properties the way TheMadTechnician suggested.

```<code>$results.ServerList.ServerInfo | Select-Object -ExpandProperty Address
$results.ServerList.ServerInfo | Foreach-Object {$_.Address}
</code>```

Body:
XML:

<ServerList>
<ServerInfo ServerType="text" RPCServerPort="111" Port="110" Address="Server01" Name="Name1">
<ServerInfo ServerType="text" RPCServerPort="111" Port="110" Address="Server02" Name="Name2">

When I try to navigate in XML as such, it works:

[xml]$results = Get-Content C:\Users\myself\Desktop\file.xml
$results.ServerList.ServerInfo

Also:

This works: $results.ServerList.Name

This works: $results.ServerList.Port

This works: $results.ServerList.RPCServerPort

However, this doesn't work: $results.ServerList.Address

I am getting a OverloadDefinitions result which has nothing to do with the content of the XML.

'Address' seems to do try to do something else, does anyone knows how to list the ADDRESS content in the XML ?

Body:
Arrays have a method known as Address defined in the CIL for retrieving items in the array.

$results.ServerList.ServerInfo.Address

OverloadDefinitions
-------------------
System.Object&, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Address(int )

In this case when you call Address you assume PowerShell should retrieve each items' Address property, but PowerShell is returning the definition for the Address method of the array that contains those items.

If you want to access the properties you will need to change the property names so that they no longer match a method signature or loop through the items in the array and retrieve the properties the way TheMadTechnician suggested.

$results.ServerList.ServerInfo | Select-Object -ExpandProperty Address
$results.ServerList.ServerInfo | Foreach-Object {$_.Address}


问:
how to set SO_REUSEADDR on the socket used by QTcpServer?
I have been using a QTcpServer subclass as a http server, but now I need to reuse the server port.

I have tried to set ShareAddress | ReuseAddressHint in a QTcpSocket, it seems worked, because the same port can be bound twice. But I did not find a way to get a QTcpSocket object from an existing QTcpServer object.

I also used the socketDescriptor() to get the native socket, because I want to use the linux C way to setsockopt, but I don't know how to use linux C code with Qt code together to set socket options.(I followed the Qt style until now.)

I am on ubuntu and Qt5.4. And I am stuck...
Any help would be appreciated. Thanks in advance.

答:
Because SO_REUSEPORT needs to be set before bind/listen is called you need to create descriptor first, set all needed flags, bind, listen and forward your descriptor to QTcpServer for future usage with it.

Here is an example which will listen on port 9999 on any interface

mytcpserver.h:

```<code>#ifndef MYTCPSERVER_H
#define MYTCPSERVER_H

#include <QObject>
#include <QTcpSocket>
#include <QTcpServer>

class MyTcpServer : public QObject
{
    Q_OBJECT
public:
    explicit MyTcpServer(QObject *parent = 0);

public slots:
    void newConnection();

private:
    QTcpServer *server;
};

#endif // MYTCPSERVER_H
</code>```

mytcpserver.cpp:

```<code>#include "mytcpserver.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

MyTcpServer::MyTcpServer(QObject *parent):QObject(parent)
{
    this->server = new QTcpServer(this);
    connect(server, &QTcpServer::newConnection, this, &MyTcpServer::newConnection);

    // open server and listen on given port
    int sockfd = 0;
    struct sockaddr_in serv_addr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        qDebug() << "ERROR: IoT Omega Daemon can't open socket";
        exit(EXIT_FAILURE);
    }

    int flag = 1;
    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)) == -1)
    {
        qDebug() << "ERROR: Can't set SO_REUSEADDR";
        exit(EXIT_FAILURE);
    }

    //set Address,IFace, Port...
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(9999);

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(sockaddr_in)) < 0)
    {
        qDebug() << "ERROR: can't bind socket";
        exit(EXIT_FAILURE);
    }

    if(listen(sockfd,SOMAXCONN) < 0)
    {
        qDebug() << "ERROR: can't listen on port";
        exit(EXIT_FAILURE);
    }

    //forward our descriptor with SO_REUSEPORT to QTcpServer member
    server->setSocketDescriptor(sockfd);
}

void MyTcpServer::newConnection()
{
    qDebug() << "NEW CONNECTION " << __LINE__;

    QTcpSocket * socket = server->nextPendingConnection();

    socket->write("Hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);

    socket->close();
}
</code>```

Maybe you would like to optimize your socket usage even more? For example setting SO_LINGER timeout of zero to avoid large numbers of connections sitting in the TIME_WAIT state? Maybe you don't ned waiting for ACKs(TCP_NODELAY)?

Then your newConnection function can look like this:

```<code>void MyTcpServer::newConnection()
{
    qDebug() << "NEW CONNECTION " << __LINE__;

    QTcpSocket * socket = server->nextPendingConnection();
    int flag = 1;
    struct linger l = {1,0};

    if(setsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) < 0)
    {
        qDebug() << "ERROR: Can't set SO_REUSEADDR";
    }

    if(setsockopt(socket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) < 0)
    {
        qDebug() << "ERROR: can't fork set TCP_NODELAY";
    }

    socket->write("Hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);

    if(setsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_LINGER, (const char *)&l,sizeof(l)) < 0)
    {
        qDebug() << "ERROR: Can't set SO_LINGER";
    }

    socket->close();
}
</code>```

This will just do the job and free any used socket resource so they can be reused just right after that. Usefull for heavyload microservers, etc..

Body:
Because SO_REUSEPORT needs to be set before bind/listen is called you need to create descriptor first, set all needed flags, bind, listen and forward your descriptor to QTcpServer for future usage with it.

Here is an example which will listen on port 9999 on any interface

mytcpserver.h:

#ifndef MYTCPSERVER_H
#define MYTCPSERVER_H

#include <QObject>
#include <QTcpSocket>
#include <QTcpServer>

class MyTcpServer : public QObject
{
    Q_OBJECT
public:
    explicit MyTcpServer(QObject *parent = 0);

public slots:
    void newConnection();

private:
    QTcpServer *server;
};

#endif // MYTCPSERVER_H

mytcpserver.cpp:

#include "mytcpserver.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

MyTcpServer::MyTcpServer(QObject *parent):QObject(parent)
{
    this->server = new QTcpServer(this);
    connect(server, &QTcpServer::newConnection, this, &MyTcpServer::newConnection);

    // open server and listen on given port
    int sockfd = 0;
    struct sockaddr_in serv_addr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        qDebug() << "ERROR: IoT Omega Daemon can't open socket";
        exit(EXIT_FAILURE);
    }

    int flag = 1;
    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)) == -1)
    {
        qDebug() << "ERROR: Can't set SO_REUSEADDR";
        exit(EXIT_FAILURE);
    }

    //set Address,IFace, Port...
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(9999);

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(sockaddr_in)) < 0)
    {
        qDebug() << "ERROR: can't bind socket";
        exit(EXIT_FAILURE);
    }

    if(listen(sockfd,SOMAXCONN) < 0)
    {
        qDebug() << "ERROR: can't listen on port";
        exit(EXIT_FAILURE);
    }

    //forward our descriptor with SO_REUSEPORT to QTcpServer member
    server->setSocketDescriptor(sockfd);
}

void MyTcpServer::newConnection()
{
    qDebug() << "NEW CONNECTION " << __LINE__;

    QTcpSocket * socket = server->nextPendingConnection();

    socket->write("Hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);

    socket->close();
}

Maybe you would like to optimize your socket usage even more? For example setting SO_LINGER timeout of zero to avoid large numbers of connections sitting in the TIME_WAIT state? Maybe you don't ned waiting for ACKs(TCP_NODELAY)?

Then your newConnection function can look like this:

void MyTcpServer::newConnection()
{
    qDebug() << "NEW CONNECTION " << __LINE__;

    QTcpSocket * socket = server->nextPendingConnection();
    int flag = 1;
    struct linger l = {1,0};

    if(setsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) < 0)
    {
        qDebug() << "ERROR: Can't set SO_REUSEADDR";
    }

    if(setsockopt(socket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) < 0)
    {
        qDebug() << "ERROR: can't fork set TCP_NODELAY";
    }

    socket->write("Hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);

    if(setsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_LINGER, (const char *)&l,sizeof(l)) < 0)
    {
        qDebug() << "ERROR: Can't set SO_LINGER";
    }

    socket->close();
}

This will just do the job and free any used socket resource so they can be reused just right after that. Usefull for heavyload microservers, etc..


问:
Access-Control-Allow-Origin contains invalid value
when i send a request in angular 2 using http service ,the browser showing following error.
can any one tell the solution ???

XMLHttpRequest cannot load http://192.168.1.59:1340/User/add. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value ''. Origin 'http://192.168.1.59:8083' is therefore not allowed access.

答:
You nead the server to enable CORS (cross origin resource sharing)

Ref: http://sailsjs.org/documentation/concepts/security/cors

simply enable allRoutes in config/cors.js:  allRoutes: true


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
Does this means that first value now stores 10. (line 1)

Yes.

line 2 means that p2 and p1 point to the value stored at the address of the second value.

No. It means that the value p2 points to gets a copy of the value that p1 points to. It is the equivalent of saying secondvalue = firstvalue; because p2 points to secondvalue and p1 points to firatvalue and the * in *p1 or *p2 in this context accesses the value the pointer points to.

I have no clue of line 3.

This says that p1 will now point at the same place that p2 points to. So both p1 and p2 point to secondvalue.

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.


问:
Why can't get the main window handle for a started process?
I have a situation where I'm starting a process in my code in order to set up an IPC channel.  The process I'm starting is an MFC application with no CLR support.  The application from which I am starting this process is a C# module in a WPF application (thought I don't think that that is consequential to my problem).  This works with a version of the application that does support CLR, and it works on every computer except the deployment target, a touch screen computer with Windows 7.   But for some reason, when I try it with this exact scenario, the Process object never resolves a main window handle (Process.MainWindowHandle).   Is there another (perhaps even pinvoke) method of doing this?  Is this a security thing?  I'm the one staring the process.  The process's main window handle does exist.  I don't see what could be wrong.

If it helps, here is my code.

```<code>        _applicationProcess = new Process();
        _applicationProcess.StartInfo.FileName = _strProcessPath;
        _applicationProcess.StartInfo.Arguments = _strProcessArguments;
        _applicationProcess.Start();

        long nTicks = Environment.TickCount;
        if (_applicationProcess.WaitForInputIdle(1 /*minute(s)*/ * 60000))
        {
            try
            {
                do
                {
                    // Don't let total processing take more than 1 minute(s).
                    if (Environment.TickCount > nTicks + 1 /*minute(s)*/ * 60000)
                        throw new ApplicationException("MFCApplication.Startup failed! The main window handle is zero!");

                    _applicationProcess.Refresh();
                }
                while (_applicationProcess.MainWindowHandle.ToInt32() == 0);

                _applicationHandle = new IntPtr(_applicationProcess.MainWindowHandle.ToInt32());
            }
            catch (Exception ex)
            {
                //Do some stuff...
                throw;
            }
        }
        else
        {
            // Do exception handling.
        }
</code>```

The ApplicationException is hit after a minute of trying to get a main window handle other than zero.

答:
My habit is to call EnumWindows in a loop combined with GetWindowThreadProcessId to find the window handle.</p>

```<code>C Code, adapt to your language

DWORD TargetHWND;

//...
    while (EnumWindows(EnumWndProc, (LPARAM)(DWORD)pid)) {
        Sleep(100);
    }

//...

BOOL EnumWndProc(HWND hWnd, LPARAM lParam) {
    DWORD pid = (DWORD)-1;
    GetWindowThreadProcessId(hWnd, &pid);
    if (pid == (DWORD)lParam) {
        TargetHWND = hWnd;
        return FALSE;
    }
    return TRUE;
}
</code>```

Body:
I have a situation where I'm starting a process in my code in order to set up an IPC channel.  The process I'm starting is an MFC application with no CLR support.  The application from which I am starting this process is a C# module in a WPF application (thought I don't think that that is consequential to my problem).  This works with a version of the application that does support CLR, and it works on every computer except the deployment target, a touch screen computer with Windows 7.   But for some reason, when I try it with this exact scenario, the Process object never resolves a main window handle (Process.MainWindowHandle).   Is there another (perhaps even pinvoke) method of doing this?  Is this a security thing?  I'm the one staring the process.  The process's main window handle does exist.  I don't see what could be wrong.

If it helps, here is my code.

        _applicationProcess = new Process();
        _applicationProcess.StartInfo.FileName = _strProcessPath;
        _applicationProcess.StartInfo.Arguments = _strProcessArguments;
        _applicationProcess.Start();

        long nTicks = Environment.TickCount;
        if (_applicationProcess.WaitForInputIdle(1 /*minute(s)*/ * 60000))
        {
            try
            {
                do
                {
                    // Don't let total processing take more than 1 minute(s).
                    if (Environment.TickCount > nTicks + 1 /*minute(s)*/ * 60000)
                        throw new ApplicationException("MFCApplication.Startup failed! The main window handle is zero!");

                    _applicationProcess.Refresh();
                }
                while (_applicationProcess.MainWindowHandle.ToInt32() == 0);

                _applicationHandle = new IntPtr(_applicationProcess.MainWindowHandle.ToInt32());
            }
            catch (Exception ex)
            {
                //Do some stuff...
                throw;
            }
        }
        else
        {
            // Do exception handling.
        }

The ApplicationException is hit after a minute of trying to get a main window handle other than zero.

Body:
My habit is to call EnumWindows in a loop combined with GetWindowThreadProcessId to find the window handle.

C Code, adapt to your language

DWORD TargetHWND;

//...
    while (EnumWindows(EnumWndProc, (LPARAM)(DWORD)pid)) {
        Sleep(100);
    }

//...

BOOL EnumWndProc(HWND hWnd, LPARAM lParam) {
    DWORD pid = (DWORD)-1;
    GetWindowThreadProcessId(hWnd, &pid);
    if (pid == (DWORD)lParam) {
        TargetHWND = hWnd;
        return FALSE;
    }
    return TRUE;
}


问:
Unable to deploy a Ceph manager daemon with ceph-deploy: Error EACCES: access denied
I am trying to set up a Ceph storage cluster using the quick start guide found here: http://docs.ceph.com/docs/master/start/quick-ceph-deploy/

When I try to deploy a manager daemon using this command:

```<code>    ceph-deploy mgr create enickel7
</code>```

I get this error:

```<code>    [ceph_deploy.mgr][ERROR ] OSError: [Errno 2] No such file or directory: '/var/lib/ceph/mgr/ceph-enickel7'
    [ceph_deploy][ERROR ] GenericError: Failed to create 1 MGRs
</code>```

(enickel7 is the name of the node I'm using - the Ceph documentation calls the nodes node1, node2, and node3.) I tried to manually create the directory /var/lib/ceph/mgr, then ran the command again. Then I got this error:

```<code>    [enickel7][ERROR ] Error EACCES: access denied
    [enickel7][ERROR ] exit code from command was: 13
    [ceph_deploy.mgr][ERROR ] could not create mgr
    [ceph_deploy][ERROR ] GenericError: Failed to create 1 MGRs
</code>```

Does anyone know what this error means, or how to fix it? ceph-deploy definitely has sudo permissions, and the mgr directory has the same permissions as other directories in /var/lib/ceph.

Thank you for your time!

答:
It's because your ceph version is not Luminous >=12.2.0, you must use ceph-deploy to install ceph as the document said, the default version installed by ceph-deploy is 10.2.10 Jewel for now.

If you want to create a manager daemon process, you need to upgrade your ceph to Luminous 12.2.1. The doc is here: http://docs.ceph.com/docs/master/release-notes/#v12-2-1-luminous

Body:
I am trying to set up a Ceph storage cluster using the quick start guide found here: http://docs.ceph.com/docs/master/start/quick-ceph-deploy/

When I try to deploy a manager daemon using this command:

    ceph-deploy mgr create enickel7

I get this error:

    [ceph_deploy.mgr][ERROR ] OSError: [Errno 2] No such file or directory: '/var/lib/ceph/mgr/ceph-enickel7'
    [ceph_deploy][ERROR ] GenericError: Failed to create 1 MGRs

(enickel7 is the name of the node I'm using - the Ceph documentation calls the nodes node1, node2, and node3.) I tried to manually create the directory /var/lib/ceph/mgr, then ran the command again. Then I got this error:

    [enickel7][ERROR ] Error EACCES: access denied
    [enickel7][ERROR ] exit code from command was: 13
    [ceph_deploy.mgr][ERROR ] could not create mgr
    [ceph_deploy][ERROR ] GenericError: Failed to create 1 MGRs

Does anyone know what this error means, or how to fix it? ceph-deploy definitely has sudo permissions, and the mgr directory has the same permissions as other directories in /var/lib/ceph.

Thank you for your time!


问:
scraping webpage data modification
its just that i have come up with some code, which does the copy paste webpage into text format in my excel sheet.

few modification were required.
Addition modification requires to make a loop through code so that it access the input from Excel(in attachment-Input sheet) and make changes to URL(i noticed in URL that only last word needs to be changed which will be taken from excel file column 1and so on till its find blank).

As, its looping correctly but there is no loop for data pasting henece its dumping all the looped data to one cell.

My basic requirment of this macro is to access link from column A, and paste its data to column B.

Sub Trial()
    Dim IE As Object
Dim URL As Range

For Each URL In Range("A1:A3").Cells

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True

        .navigate "1ox11is" & URL
        Do Until .readyState = 4: DoEvents: Loop

            'Range("B1").Value = .document.body.innerText
            'wsSheet.Range("B" & Rows).Value = .document.body.innerText
            Sheets("Sheet1").Range("B1").Value = .document.body.innerText

            .Quit

        End With
Next

End Sub```

答:
Assuming that links are in cells A1,A2,A3 etc. and data from websites is supposed to appear next to them in cells B1,B2,B3 etc, change:

```<code>Sheets("Sheet1").Range("B1").Value = .document.body.innerText
</code>```

to:

```<code>Sheets("Sheet1").Range("B" & URL.Row).Value = .document.body.innerText
</code>```

Title: scraping webpage data modification

Body:
Assuming that links are in cells A1,A2,A3 etc. and data from websites is supposed to appear next to them in cells B1,B2,B3 etc, change:

Sheets("Sheet1").Range("B1").Value = .document.body.innerText

to:

Sheets("Sheet1").Range("B" & URL.Row).Value = .document.body.innerText


问:
Distribution Profile requesting a Developer certificate
Using Xcode 9.1, after building an iOS app, I try to archive it.
But I get the following error message:

Provisioning profile "MyAppProfile" doesn't include signing certificate "iPhone Developer: My Name (X1YZ2AB3CD)".

After looking closer, I see that MyAppProfile is a Distribution Provisioning Profile (this is what I want) and X1YZ2AB3CD matches a Developer certificate.But when building MyAppProfile (for App Store) I was provided with the choice of a unique Distribution certificate (No Developer certificate). So why do I get this message complaining about MyAppProfile not including a Developer certificate. I am kind of lost. Anyone can shed some light here?

In case I give up with manual signing, here is what I get when trying to upload to appStore:

Automatic signing is unable to resolve an issue with the "MyApp.app" target's entitlements.
Switch to manual signing and resolve the issue by downloading a matching provisioning profile from the developer website. Atlernatively, to continue using automatic signing, remove these entitlements from your entitlements file and their associated functionality from your code. Then rebuild your archive and try again.

Provisioning profile failed qualification
Profile doesn't match the entitlements file's value for the application-identifier entitlement.

答:
I finally was able to upload.

Here is what I did:
I enabled in-app-purchase in the list of Application Capabilities and disabled it right after. (Giving up in-app-purchase at least temporarily)

There is a lot I don't understand here, but I am just giving this info in case it may be useful for someone with similar problems.


问:
How to use value from list without repeating? (Random.Range)
I have one list(planePosition). I want to use those list value randomly without repetition  so I am using

```<code> for( int a=0; a< planePosition.Count; a++)
    {
    int r=Random.Range(0,planePosition.Count);
    Newplan.transform.position =  new Vector3 (planePosition[r].x, planePosition[r].y ,9.990011f);
    planePosition.RemoveAt(r);
    }
</code>```

but still I am getting duplicate value..

答:
```<code>  private void ScoreRandomize()
    {
        List<int> listRnd = new List<int>();
        listRnd.AddRange(scoreAmount); //scoreAmount is array or list with orginal data
        for (int i = 0; i < listRnd.Count + i; i++)
        {
            int rnd = UnityEngine.Random.Range(0, listRnd.Count);
            scoreDisplayTxts[i].text = listRnd[rnd].ToString();
            scoreAmount[i] = listRnd[rnd];
            listRnd.RemoveAt(rnd);
        }

    }
</code>```

Body:
I have one list(planePosition). I want to use those list value randomly without repetition  so I am using

 for( int a=0; a< planePosition.Count; a++)
    {
    int r=Random.Range(0,planePosition.Count);
    Newplan.transform.position =  new Vector3 (planePosition[r].x, planePosition[r].y ,9.990011f);
    planePosition.RemoveAt(r);
    }

but still I am getting duplicate value..


问:
Swift iOS: custom keyboard only slightly different from default keyboard
For a word game, I want to create a UITextField programmatically in Swift that only allows users to enter and delete uppercase letters (no space bar, return, capitalization, etc). Like this:

Desired Keyboard Layout

This doesn't appear to be one of the built-in keyboard options, but it seems like overkill to create a custom keyboard from scratch. What's the best way to do this?

答:
Make a UILabel that looks like UITextField, this will help you to prevent system keyboard appearing. You can set text for the UILabel from your custom buttons. Try.

First make UILabel, add Tap gesture to it to handle click event.Let me know if the hint is not enough for you.

Here . here you can learn how to make UILabel looks like UITextField


问:
How to connect Netsuite Rest Api with Pentaho Spoon Rest Client
I trying to access data from restlet using spoon rest client but it is not working. I am creating a field in add rows named creadentials. And passing this hole string in heders of rest client. </p>

```<code>Authorization: NLAuth nlauth_account=12345, nlauth_email=jsmith@ABC.com, nlauth_signature=xxxx, nlauth_role=4
</code>```

<p>But i am getting error as no authorization headers. </p>

答:
I got the answer. We have to put authorization as name and </p>

```<code>NLAuth nlauth_account=123, nlauth_email=abc@abc.com, nlauth_signature=password, nlauth_role=3
</code>```

<p>as value in add rows of spoon client and also add content-type as name and application/json as value then add all the fields in parameters. You have to add name as authorization and field authorization again name content-type field content-type. Remove default authorization username and password because we are sending it with the headers.  </p>

Body:
I trying to access data from restlet using spoon rest client but it is not working. I am creating a field in add rows named creadentials. And passing this hole string in heders of rest client.

Authorization: NLAuth nlauth_account=12345, nlauth_email=jsmith@ABC.com, nlauth_signature=xxxx, nlauth_role=4

But i am getting error as no authorization headers.

Body:
I got the answer. We have to put authorization as name and

NLAuth nlauth_account=123, nlauth_email=abc@abc.com, nlauth_signature=password, nlauth_role=3

as value in add rows of spoon client and also add content-type as name and application/json as value then add all the fields in parameters. You have to add name as authorization and field authorization again name content-type field content-type. Remove default authorization username and password because we are sending it with the headers.


问:
Cannot set high resolution image(1920x1280) to image view on android 7.0
I run this app lot of devices. less than android 7 and more than android 7, that is fine. but when i run this app on samsung s6(android 7.0) it gives this error

Fatal Exception: java.lang.RuntimeException: Canvas: trying to draw
  too large(120422400bytes) bitmap.
         at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
         at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
         at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
         at android.view.View.getDrawableRenderNode(View.java:18591)
         at android.view.View.drawBackground(View.java:18527)
         at android.view.View.draw(View.java:18315)
         at android.view.View.updateDisplayListIfDirty(View.java:17302)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.draw(View.java:18327)
         at com.android.internal.policy.DecorView.draw(DecorView.java:919)
         at android.view.View.updateDisplayListIfDirty(View.java:17302)
         at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
         at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
         at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
         at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
         at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
         at android.view.Choreographer.doCallbacks(Choreographer.java:702)
         at android.view.Choreographer.doFrame(Choreographer.java:638)
         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
         at android.os.Handler.handleCallback(Handler.java:751)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6682)
         at java.lang.reflect.Method.invoke(Method.java)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

答: Move your image in the (hi-res) drawable to drawable-xxhdpi and largeheap=true in manifest file.</p>


问:
How to publish a WPF clickonce app when building a solution?
I have a solution with many projects, some of which have an Outputtype of exe.

I'm using the following arguments as part of my MsBuild call

```<code>/target:publish /p:PublishDir="$(build.artifactstagingdirectory)\
</code>```

However, this publishes all projects with an Outputtype of exe. However, I only want to publish one specific project.

Most of what I have read states to reference the named PublishProfile. However, I don't see a way of creating a PublishProfile for this project type. When I click Publish I get a basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file. So how can I request a specific project to be published?

答:
However, I don't see a way of creating a PublishProfile for this project type. When I click Publish I get a basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file. So how can I request a specific project to be published?

The PublishProfile is used for web project not click once. Just as you said, "basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file", so PublishProfile should not be a correct option.

If you want to publish a specific project from solution with msbuild, the simple way is to build the entire solution but only publish one project file, like:

```<code>msbuild.exe "ProjectName.csproj" /target:publish /p:PublishDir="$(build.artifactstagingdirectory)\
</code>```

If using one command line to build and publish is your persistence, you can custom a target to publish the project in the project file, which you want to publish. For example:

```<code><PropertyGroup>
    <!-- the folder of the project to build -->
    <ProjLocation>..\YourProjectFolder</ProjLocation>
    <ProjLocationReleaseDir>$(ProjLocation)\bin\Release</ProjLocationReleaseDir>
    <ProjPublishLocation>$(ProjLocationReleaseDir)\app.publish</ProjPublishLocation>
    <!-- This is the web-folder, which provides the artefacts for click-once. After this
     build the project is actually deployed on the server -->
    <DeploymentFolder>D:\server\releases\</DeploymentFolder>
</PropertyGroup>

<Target Name="Publish" DependsOnTargets="Clean">
    <Message Text="Publish-Build started for build no $(ApplicationRevision)" />
    <MSBuild Projects="$(ProjLocation)/YourProject.csproj" Properties="Configuration=Release" Targets="Publish"/>

    <ItemGroup>
        <SchoolPlannerSetupFiles Include="$(ProjPublishLocation)\*.*"/>
        <SchoolPlannerUpdateFiles Include="$(ProjPublishLocation)\Application Files\**\*.*"/>
    </ItemGroup>
    <Copy
        SourceFiles="@(SchoolPlannerSetupFiles)"
        DestinationFolder="$(DeploymentFolder)\"
    />
    <Copy
        SourceFiles="@(SchoolPlannerUpdateFiles)"
        DestinationFolder="$(DeploymentFolder)\Application Files\%(RecursiveDir)"
    />
    <CallTarget Targets="RestoreLog"/>
</Target>
<Target Name="Clean">
    <Message Text="Clean project:" />
    <MSBuild Projects="$(ProjLocation)/YourProject.csproj" Properties="Configuration=Release" Targets="Clean"/>
</Target>
</code>```

With this custom target, you do not need to publish the project, just need build the solution.

Hope this helps.

Body:
I have a solution with many projects, some of which have an Outputtype of exe.

I'm using the following arguments as part of my MsBuild call

/target:publish /p:PublishDir="$(build.artifactstagingdirectory)\

However, this publishes all projects with an Outputtype of exe. However, I only want to publish one specific project.

Most of what I have read states to reference the named PublishProfile. However, I don't see a way of creating a PublishProfile for this project type. When I click Publish I get a basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file. So how can I request a specific project to be published?

Body:
However, I don't see a way of creating a PublishProfile for this project type. When I click Publish I get a basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file. So how can I request a specific project to be published?

The PublishProfile is used for web project not click once. Just as you said, "basic publish wizard and the publish settings are stored in the .csproj file not a .pubxml file", so PublishProfile should not be a correct option.

If you want to publish a specific project from solution with msbuild, the simple way is to build the entire solution but only publish one project file, like:

msbuild.exe "ProjectName.csproj" /target:publish /p:PublishDir="$(build.artifactstagingdirectory)\

If using one command line to build and publish is your persistence, you can custom a target to publish the project in the project file, which you want to publish. For example:

<PropertyGroup>
    <!-- the folder of the project to build -->
    <ProjLocation>..\YourProjectFolder</ProjLocation>
    <ProjLocationReleaseDir>$(ProjLocation)\bin\Release</ProjLocationReleaseDir>
    <ProjPublishLocation>$(ProjLocationReleaseDir)\app.publish</ProjPublishLocation>
    <!-- This is the web-folder, which provides the artefacts for click-once. After this
     build the project is actually deployed on the server -->
    <DeploymentFolder>D:\server\releases\</DeploymentFolder>
</PropertyGroup>

<Target Name="Publish" DependsOnTargets="Clean">
    <Message Text="Publish-Build started for build no $(ApplicationRevision)" />
    <MSBuild Projects="$(ProjLocation)/YourProject.csproj" Properties="Configuration=Release" Targets="Publish"/>

    <ItemGroup>
        <SchoolPlannerSetupFiles Include="$(ProjPublishLocation)\*.*"/>
        <SchoolPlannerUpdateFiles Include="$(ProjPublishLocation)\Application Files\**\*.*"/>
    </ItemGroup>
    <Copy
        SourceFiles="@(SchoolPlannerSetupFiles)"
        DestinationFolder="$(DeploymentFolder)\"
    />
    <Copy
        SourceFiles="@(SchoolPlannerUpdateFiles)"
        DestinationFolder="$(DeploymentFolder)\Application Files\%(RecursiveDir)"
    />
    <CallTarget Targets="RestoreLog"/>
</Target>
<Target Name="Clean">
    <Message Text="Clean project:" />
    <MSBuild Projects="$(ProjLocation)/YourProject.csproj" Properties="Configuration=Release" Targets="Clean"/>
</Target>

With this custom target, you do not need to publish the project, just need build the solution.

Hope this helps.


问:
Tab sliding - how to?
The problem is with tab activity. when i'm run this app with  is worked fine.but when i slide or tap the tab it's totally shut down.please anyone help me out.

```<code>    public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    tab1 tab1 = new tab1();
                    return tab1;

                case 1:
                    tab2 tab2 = new tab2();
                    return tab2;
                case 3:
                    tab3 tab3 =new tab3();
                    return tab3;

                default: return null ;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Protisthan";
                case 1:`enter code here`
                    return "Eknojore";
                case 2:
                    return "Onnorokom";
            }
            return null;
        }
    }
}
</code>```

and here is logcat file . app run smoothly but when i try to chage the tab then it's get cushed.

```<code>11-14 12:08:12.460 30777-30777/? I/art: Late-enabling -Xcheck:jni
11-14 12:08:12.535 30777-30777/? I/System.out: Sending WAIT chunk
11-14 12:08:12.729 30777-30783/com.example.mn.tabt I/art: Debugger is active
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: Debugger has connected
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:12.936 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.136 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.336 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.537 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.737 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.938 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.138 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.339 30777-30777/com.example.mn.tabt I/System.out: debugger has settled (1406)
11-14 12:08:14.356 30777-30777/com.example.mn.tabt W/System: ClassLoader referenced unknown path: /data/app/com.example.mn.tabt-1/lib/arm64
11-14 12:08:14.399 30777-30777/com.example.mn.tabt W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-14 12:08:14.544 30777-30777/com.example.mn.tabt I/HwSecImmHelper: mSecurityInputMethodService is null
11-14 12:08:14.557 30777-30777/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt I/OpenGLRenderer: Initialized EGL, version 1.4
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: load: so=/system/lib64/libhwuibp.so
                                                                     dlopen failed: library "/system/lib64/libhwuibp.so" not found
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: Initialize Binary Program Cache: Load Failed
11-14 12:08:14.655 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:21.698 30777-30777/com.example.mn.tabt I/Process: Sending signal. PID: 30777 SIG: 9
</code>```

`

here the tab1 class. similarly i create two more class.for 3 fragment.
 `

```<code>    public class tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1, container, false);
        return rootView;
    }

}
</code>```

if anyone want to see the xml file of main class . here it is .

`

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

  </android.support.design.widget.CoordinatorLayout>
</code>```

`

答:
```<code> @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                tab1 tab1 = new tab1();
                return tab1;

            case 1:
                tab2 tab2 = new tab2();
                return tab2;
            case 3: // Should be 2
                tab3 tab3 =new tab3();
                return tab3;

            default: return null ;
        }
</code>```

At first, rectify your CASE section.

```<code> case 2:
            tab3 tab3 =new tab3();
            return tab3;
</code>```

Disable Instant Run .

Title: Tab sliding - how to?

Body:
The problem is with tab activity. when i'm run this app with  is worked fine.but when i slide or tap the tab it's totally shut down.please anyone help me out.

    public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    tab1 tab1 = new tab1();
                    return tab1;

                case 1:
                    tab2 tab2 = new tab2();
                    return tab2;
                case 3:
                    tab3 tab3 =new tab3();
                    return tab3;

                default: return null ;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Protisthan";
                case 1:`enter code here`
                    return "Eknojore";
                case 2:
                    return "Onnorokom";
            }
            return null;
        }
    }
}

and here is logcat file . app run smoothly but when i try to chage the tab then it's get cushed.

11-14 12:08:12.460 30777-30777/? I/art: Late-enabling -Xcheck:jni
11-14 12:08:12.535 30777-30777/? I/System.out: Sending WAIT chunk
11-14 12:08:12.729 30777-30783/com.example.mn.tabt I/art: Debugger is active
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: Debugger has connected
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:12.936 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.136 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.336 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.537 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.737 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.938 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.138 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.339 30777-30777/com.example.mn.tabt I/System.out: debugger has settled (1406)
11-14 12:08:14.356 30777-30777/com.example.mn.tabt W/System: ClassLoader referenced unknown path: /data/app/com.example.mn.tabt-1/lib/arm64
11-14 12:08:14.399 30777-30777/com.example.mn.tabt W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-14 12:08:14.544 30777-30777/com.example.mn.tabt I/HwSecImmHelper: mSecurityInputMethodService is null
11-14 12:08:14.557 30777-30777/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt I/OpenGLRenderer: Initialized EGL, version 1.4
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: load: so=/system/lib64/libhwuibp.so
                                                                     dlopen failed: library "/system/lib64/libhwuibp.so" not found
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: Initialize Binary Program Cache: Load Failed
11-14 12:08:14.655 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:21.698 30777-30777/com.example.mn.tabt I/Process: Sending signal. PID: 30777 SIG: 9

`

here the tab1 class. similarly i create two more class.for 3 fragment.
 `

    public class tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1, container, false);
        return rootView;
    }

}

if anyone want to see the xml file of main class . here it is .

`

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

  </android.support.design.widget.CoordinatorLayout>

`

Body:
 @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                tab1 tab1 = new tab1();
                return tab1;

            case 1:
                tab2 tab2 = new tab2();
                return tab2;
            case 3: // Should be 2
                tab3 tab3 =new tab3();
                return tab3;

            default: return null ;
        }

At first, rectify your CASE section.

 case 2:
            tab3 tab3 =new tab3();
            return tab3;

Disable Instant Run .


问:
Eclipse Plugin Development : How to add option in Right Click Menu
I have created an eclipse plugin. I am able to add a menu and submenu.

However, I am not able to add an option in the Right Click menu. Does anyone have any idea how to do that?

答:
Here's an example (this code has filled with your preferences and classes and to be added to the plugin.xml): </p>

```<code><extension point="org.eclipse.ui.popupMenus">
    <objectContribution
      adaptable="true"
      id=""
      nameFilter=""
      objectClass="org.eclipse.core.resources.IFile">
      <action
         id="org.eclipse.ui.articles.action.contribution.object.action1"
         label=""
         icon=""
         menubarPath="additions"
         class="">
      </action>
    </objectContribution>
</extension>
</code>```

Body:
Here's an example (this code has filled with your preferences and classes and to be added to the plugin.xml):

<extension point="org.eclipse.ui.popupMenus">
    <objectContribution
      adaptable="true"
      id=""
      nameFilter=""
      objectClass="org.eclipse.core.resources.IFile">
      <action
         id="org.eclipse.ui.articles.action.contribution.object.action1"
         label=""
         icon=""
         menubarPath="additions"
         class="">
      </action>
    </objectContribution>
</extension>


问:
how to bind event with sqldependency and unsubscribe in c#
i have problem to bind event with custom parameter, its not unsubscribe while subscribe next time. basically when 1st time subscribe event, its hold the 1st event and make new event when 2nd time subscribe. mean there are 2 events and 3rd time there will be 3 events and so on. but i need 1 event only each time while subscribe and unsubcribe last event.

dependency_Update function

```<code>public void dependency_Update(Guid clientid)
{
    SqlDependency.Stop(connString);
    using (SqlCommand command = new SqlCommand(SQL.newemailmessagescountbyclient_sql(), connection))
    {
       connection.Open();
       command.Parameters.Add(new SqlParameter("@clientid", clientid));
       command.Notification = null;
       SqlDependency.Start(connString);
       SqlDependency dependency = new SqlDependency(command);
       dependency.OnChange += new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
       dependency.OnChange -= new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
       var reader = command.ExecuteReader();
       connection.Close();

     }
 }
</code>```

dependency_OnChange event

```<code>public void dependency_OnChange(object sender, SqlNotificationEventArgs e, SqlDependency dependency, Guid clientid)
{
   if (e.Type == SqlNotificationType.Change)
   {
     //subscribe function again
     dependency_Update(clientid);
   }
}
</code>```

can any one have solution for that, please help me, i appreciate your valuable time, thanks

答:
This block

```<code>dependency.OnChange += new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
dependency.OnChange -= new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
</code>```

Doesn't do anything useful. First, its intention is strange - you are trying to subscribe and immediately unsubscribe. Second, it doesn't work as expected, because, despite looking the same - your two anonymous function handlers are different. In effect - you never really unsubscribe your handler from OnChange event. If you want to use anonymoys function, do it like that:

```<code>SqlDependency dependency = new SqlDependency(command);
OnChangeEventHandler handler = null;
handler = (s, e) => dependency_OnChange(s, e, clientid, handler);
dependency.OnChange += handler;

public void dependency_OnChange(object sender, SqlNotificationEventArgs e, Guid clientid, OnChangeEventHandler handler) {
    var dependency = (SqlDependency)sender;
    if (e.Type == SqlNotificationType.Change) {
        dependency.OnChange -= handler;
        //subscribe function again
        dependency_Update(clientid);
    }
}
</code>```

Or like this:

```<code>OnChangeEventHandler handler = null;
handler = (s, e) => {
      dependency.OnChange -= handler;
      dependency_OnChange(s, e, clientid);
};
dependency.OnChange += handler;
</code>```

Body:
i have problem to bind event with custom parameter, its not unsubscribe while subscribe next time. basically when 1st time subscribe event, its hold the 1st event and make new event when 2nd time subscribe. mean there are 2 events and 3rd time there will be 3 events and so on. but i need 1 event only each time while subscribe and unsubcribe last event.

dependency_Update function

public void dependency_Update(Guid clientid)
{
    SqlDependency.Stop(connString);
    using (SqlCommand command = new SqlCommand(SQL.newemailmessagescountbyclient_sql(), connection))
    {
       connection.Open();
       command.Parameters.Add(new SqlParameter("@clientid", clientid));
       command.Notification = null;
       SqlDependency.Start(connString);
       SqlDependency dependency = new SqlDependency(command);
       dependency.OnChange += new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
       dependency.OnChange -= new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
       var reader = command.ExecuteReader();
       connection.Close();

     }
 }

dependency_OnChange event

public void dependency_OnChange(object sender, SqlNotificationEventArgs e, SqlDependency dependency, Guid clientid)
{
   if (e.Type == SqlNotificationType.Change)
   {
     //subscribe function again
     dependency_Update(clientid);
   }
}

can any one have solution for that, please help me, i appreciate your valuable time, thanks

Body:
This block

dependency.OnChange += new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));
dependency.OnChange -= new OnChangeEventHandler((s, e) => dependency_OnChange(s, e, dependency, clientid));

Doesn't do anything useful. First, its intention is strange - you are trying to subscribe and immediately unsubscribe. Second, it doesn't work as expected, because, despite looking the same - your two anonymous function handlers are different. In effect - you never really unsubscribe your handler from OnChange event. If you want to use anonymoys function, do it like that:

SqlDependency dependency = new SqlDependency(command);
OnChangeEventHandler handler = null;
handler = (s, e) => dependency_OnChange(s, e, clientid, handler);
dependency.OnChange += handler;

public void dependency_OnChange(object sender, SqlNotificationEventArgs e, Guid clientid, OnChangeEventHandler handler) {
    var dependency = (SqlDependency)sender;
    if (e.Type == SqlNotificationType.Change) {
        dependency.OnChange -= handler;
        //subscribe function again
        dependency_Update(clientid);
    }
}

Or like this:

OnChangeEventHandler handler = null;
handler = (s, e) => {
      dependency.OnChange -= handler;
      dependency_OnChange(s, e, clientid);
};
dependency.OnChange += handler;


问:
Python - return intersection of two arrays
I have two arrays and I am trying to return a new array that equals the intersection of my original two arrays. The two original arrays should be of the same length. For example, if I have:

arr1 = np.array([(255, 255, 255), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get:

intersectedArr = ([(255, 255, 255), (255, 255, 255])

However, if I have:

arr1 = np.array([(100, 100, 100), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get

([(255, 255, 255)])

So far i've tried:

intersectedArr = np.intersect1d(arr1, arr2)

but this returns [255] instead of the expected ([(255, 255, 255)])

Can someone help? Thanks in advance!

Body:
For larger arrays it might help to use pandas' groupby and cumcount:

In [11]: df1 = pd.DataFrame(arr1)

In [12]: df1["cumcount"] = df1.groupby([0, 1, 2]).cumcount()

In [13]: df1
Out[13]:
     0    1    2  cumcount
0  100  100  100         0
1  255  255  255         0

In [14]: df2 = pd.DataFrame(arr2)

In [15]: df2["cumcount"] = df2.groupby([0, 1, 2]).cumcount()

In [16]: df2
Out[16]:
     0    1    2  cumcount
0  255  255  255         0
1  255  255  255         1

Now a merge gets you the array you desire:

In [21]: df1.merge(df1).iloc[:, :3].values
Out[21]:
array([[100, 100, 100],
       [255, 255, 255]])

In [22]: df1.merge(df2).iloc[:, :3].values
Out[22]: array([[255, 255, 255]])

In [23]: df2.merge(df2).iloc[:, :3].values
Out[23]:
array([[255, 255, 255],
       [255, 255, 255]])


问:
How to get first 50 post url from instagram
I want to get the first 50 post for any public instagram url. To get the first 12 posts which are visible by default is easy and below code is doing that just fine but I am not sure how to access other urls which is visible when you hit "load more" button at the bottom and scroll further down for more. Is this possible? Can anyone help me with this? </p>

```<code>Sub getData()

Dim urL As String, instaID As String, totalPost As Long, fRow As Long
Dim ie, var1, var2, a

urL = "https://www.instagram.com/nike/"
OUT.Range("A2:A" & OUT.Rows.Count).Clear

Set ie = CreateObject("internetexplorer.application")
ie.Visible = True

fRow = 2

'----------------------
With OUT

    ie.navigate urL

    'Busy
    Do While ie.Busy
      Application.Wait DateAdd("s", 1, Now)
    Loop

    Set var1 = ie.document.getElementsByclassname("_mck9w _gvoze _f2mse")
    Do While IsObject(var1) = False
        Application.Wait Now + TimeValue("00:00:03")
        Set var1 = ie.document.getElementsByclassname("_mck9w _gvoze _f2mse")
    Loop

    Set var2 = var1(0).document.getElementsBytagname("a")

    For Each a In var2
        If Trim(a.href) <> "" And a.parentelement.classname = "_mck9w _gvoze _f2mse" Then

            .Range("A" & fRow) = a.href
            Debug.Print a.innertext & " " & a.parentelement.classname

             fRow = fRow + 1
        End If
    Next a

End With

'------------------
ie.Quit
Set ie = Nothing

Application.ScreenUpdating = True

End Sub
</code>```

答:
try this </p>

```<code>Sub getData()

    Dim urL As String, instaID As String, totalPost As Long, fRow As Long
    Dim ie As Object, var1 As Object, a As Variant

    urL = "https://www.instagram.com/nike/"

    Set ie = CreateObject("internetexplorer.application")
    ie.Visible = True

    ie.navigate urL

    Do While ie.Busy Or ie.readystate <> 4
        DoEvents
    Loop

    Do
        Set var1 = ie.Document.getElementsByclassname("_1cr2e _epyes")  ' wait for "load more"
    Loop While var1 Is Nothing

    var1(0).Click                                                       ' click "load more"

    Do While ie.Busy Or ie.readystate <> 4                              ' not sure if this is needed
        DoEvents
    Loop

    For a = 1 To 4
        ie.Document.parentWindow.scrollBy 0, 60000                      ' roll to bottom
        Application.Wait Now + TimeValue("00:00:01")                    ' wait for "fill in"
    Next a

    Set var1 = ie.Document.getElementsBytagname("a")

    Range("A2:A" & Rows.count).Clear
    fRow = 2

    For Each a In var1
        If Trim(a.href) <> "" And a.parentelement.classname = "_mck9w _gvoze _f2mse" Then
            Range("A" & fRow) = a.href
            Debug.Print a.innertext & " " & a.parentelement.classname
            fRow = fRow + 1
        End If
    Next a

    ' ------------------
    ie.Quit
    Set ie = Nothing

End Sub
</code>```

Body:
I want to get the first 50 post for any public instagram url. To get the first 12 posts which are visible by default is easy and below code is doing that just fine but I am not sure how to access other urls which is visible when you hit "load more" button at the bottom and scroll further down for more. Is this possible? Can anyone help me with this?

Sub getData()

Dim urL As String, instaID As String, totalPost As Long, fRow As Long
Dim ie, var1, var2, a

urL = "https://www.instagram.com/nike/"
OUT.Range("A2:A" & OUT.Rows.Count).Clear

Set ie = CreateObject("internetexplorer.application")
ie.Visible = True

fRow = 2

'----------------------
With OUT

    ie.navigate urL

    'Busy
    Do While ie.Busy
      Application.Wait DateAdd("s", 1, Now)
    Loop

    Set var1 = ie.document.getElementsByclassname("_mck9w _gvoze _f2mse")
    Do While IsObject(var1) = False
        Application.Wait Now + TimeValue("00:00:03")
        Set var1 = ie.document.getElementsByclassname("_mck9w _gvoze _f2mse")
    Loop

    Set var2 = var1(0).document.getElementsBytagname("a")

    For Each a In var2
        If Trim(a.href) <> "" And a.parentelement.classname = "_mck9w _gvoze _f2mse" Then

            .Range("A" & fRow) = a.href
            Debug.Print a.innertext & " " & a.parentelement.classname

             fRow = fRow + 1
        End If
    Next a

End With

'------------------
ie.Quit
Set ie = Nothing

Application.ScreenUpdating = True

End Sub

Body:
try this

Sub getData()

    Dim urL As String, instaID As String, totalPost As Long, fRow As Long
    Dim ie As Object, var1 As Object, a As Variant

    urL = "https://www.instagram.com/nike/"

    Set ie = CreateObject("internetexplorer.application")
    ie.Visible = True

    ie.navigate urL

    Do While ie.Busy Or ie.readystate <> 4
        DoEvents
    Loop

    Do
        Set var1 = ie.Document.getElementsByclassname("_1cr2e _epyes")  ' wait for "load more"
    Loop While var1 Is Nothing

    var1(0).Click                                                       ' click "load more"

    Do While ie.Busy Or ie.readystate <> 4                              ' not sure if this is needed
        DoEvents
    Loop

    For a = 1 To 4
        ie.Document.parentWindow.scrollBy 0, 60000                      ' roll to bottom
        Application.Wait Now + TimeValue("00:00:01")                    ' wait for "fill in"
    Next a

    Set var1 = ie.Document.getElementsBytagname("a")

    Range("A2:A" & Rows.count).Clear
    fRow = 2

    For Each a In var1
        If Trim(a.href) <> "" And a.parentelement.classname = "_mck9w _gvoze _f2mse" Then
            Range("A" & fRow) = a.href
            Debug.Print a.innertext & " " & a.parentelement.classname
            fRow = fRow + 1
        End If
    Next a

    ' ------------------
    ie.Quit
    Set ie = Nothing

End Sub


问:
Ruby strange quoting
sorry for bad English. Why Ruby quoting so strange? Or may be this is a bug?

```<code>irb(main):027:0> p eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""
</code>```

produces

```<code>=> "    +     +    +     \\+    \\+    "
</code>```

or

```<code>irb(main):027:0> puts eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""
</code>```

produces

```<code>=> +     +    +     \+    \+
</code>```

or another example

```<code>irb(main):067:0> "  \"  " =~ Regexp.new(eval("\"  \\\"  \""))
=> 0

irb(main):068:0> "  +  " =~ Regexp.new(eval("\"  \\\\+  \""))
=> 0
</code>```

答:
When you write \"    \+     \\+    \\\+     \\\\+     \" you get "    +     \+    \+     \\+     ". After, you use eval to execute this string, that contains another double-quoted string. You get, then, +     +    +     \+.

\\ => \

\x => x (se não for nenhum caso especial, como \n)

Title: Ruby strange quoting

Body:
sorry for bad English. Why Ruby quoting so strange? Or may be this is a bug?

irb(main):027:0> p eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""

produces

=> "    +     +    +     \\+    \\+    "

or

irb(main):027:0> puts eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""

produces

=> +     +    +     \+    \+

or another example

irb(main):067:0> "  \"  " =~ Regexp.new(eval("\"  \\\"  \""))
=> 0

irb(main):068:0> "  +  " =~ Regexp.new(eval("\"  \\\\+  \""))
=> 0


问:
RegisterTempTable using dataset Spark Java
I have been using dataframe in my Java Spark Project (Spark version 1.6.1).
Now I am refactoring, trying to use the dataset in order to exploit the strong typed feature which comes with them.
In some part of the project I was using the following code:

```<code>dataframe.registerTempTable("table")
</code>```

in order to use pure sql queries.

This kind of feature looks to be not present with dataset, I cannot find any similar method offered by them.

Can you confirm that?

答:
I confirm that no method available in spark 1.6 for registering temp table or view using dataset.

https://spark.apache.org/docs/1.6.0/api/java/org/apache/spark/sql/Dataset.html

These methods were introduced in spark 2.0.

https://spark.apache.org/docs/2.0.0/api/java/org/apache/spark/sql/Dataset.html

Body:
I have been using dataframe in my Java Spark Project (Spark version 1.6.1).
Now I am refactoring, trying to use the dataset in order to exploit the strong typed feature which comes with them.
In some part of the project I was using the following code:

dataframe.registerTempTable("table")

in order to use pure sql queries.

This kind of feature looks to be not present with dataset, I cannot find any similar method offered by them.

Can you confirm that?


问:
asp.net js controlID increase dynamically
I want to increase ASP controlID each time I click button. Like adding more phone numbers. Each time new asp:textbox is added, new ID should be created.
Adding more div/textbox is working fine, but ID of each textbox is same.

function GetDynamicMobileNo(value) {
        return '
<asp:TextBox ID="txtAddMoreNumber" runat="server" CssClass="form-control" MaxLength="11" Placeholder="Mobile No"></asp:TextBox>

';
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("");
        document.getElementById("MobileNoContainer").appendChild(div);

    }```

Anyone can help?

答:
Id is same because you are generating html with the same Id.

```<code>//Here is your problem
function GetDynamicMobileNo(value) {
        return '<div><asp:TextBox ID="txtAddMoreNumber" runat="server" CssClass="form-control" MaxLength="11" Placeholder="Mobile No"></asp:TextBox></div></br>';
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("");
        document.getElementById("MobileNoContainer").appendChild(div);

    }
</code>```

Change it to this code

```<code>function GetDynamicMobileNo(value, id) {
        return "<div><asp:TextBox ID=\" + id + \" runat=\"server\" CssClass=\"form-control\" MaxLength=\"11\" Placeholder=\"Mobile No\"></asp:TextBox></div></br>";
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("", someRandomIdGenerator());
        document.getElementById("MobileNoContainer").appendChild(div);

    }
</code>```

Body:
I want to increase ASP controlID each time I click button. Like adding more phone numbers. Each time new asp:textbox is added, new ID should be created.
Adding more div/textbox is working fine, but ID of each textbox is same.

function GetDynamicMobileNo(value) {
        return '
<asp:TextBox ID="txtAddMoreNumber" runat="server" CssClass="form-control" MaxLength="11" Placeholder="Mobile No"></asp:TextBox>

';
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("");
        document.getElementById("MobileNoContainer").appendChild(div);

    }

Anyone can help?

Body:
Id is same because you are generating html with the same Id.

//Here is your problem
function GetDynamicMobileNo(value) {
        return '<div><asp:TextBox ID="txtAddMoreNumber" runat="server" CssClass="form-control" MaxLength="11" Placeholder="Mobile No"></asp:TextBox></div></br>';
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("");
        document.getElementById("MobileNoContainer").appendChild(div);

    }

Change it to this code

function GetDynamicMobileNo(value, id) {
        return "<div><asp:TextBox ID=\" + id + \" runat=\"server\" CssClass=\"form-control\" MaxLength=\"11\" Placeholder=\"Mobile No\"></asp:TextBox></div></br>";
    }

    function AddMobileNo() {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicMobileNo("", someRandomIdGenerator());
        document.getElementById("MobileNoContainer").appendChild(div);

    }