问:
Draw line before marker appear Highchart
I am working on dynamic update using highchart.
Is there a way, wherein the line will go first on the next point before marker appear?
Currently what is happening is that, the marker appear first on the point before the line connects.

```<code>$(document).ready(function () {
Highcharts.setOptions({
    global: {
        useUTC: false
    }
});

Highcharts.chart('container', {
    chart: {
        type: 'spline',
        animation: Highcharts.svg, // don't animate in old IE
        marginRight: 10,
        events: {
            load: function () {

                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.random();
                    series.addPoint([x, y], true, true);
                }, 1000);
            }
        }
    },
    title: {
        text: 'Live random data'
    },
    xAxis: {
        type: 'datetime',
        tickPixelInterval: 150
    },
    yAxis: {
        title: {
            text: 'Value'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        formatter: function () {
            return '<b>' + this.series.name + '</b><br/>' +
                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                Highcharts.numberFormat(this.y, 2);
        }
    },
    legend: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    series: [{
        name: 'Random data',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -19; i <= 0; i += 1) {
                data.push({
                    x: time + i * 1000,
                    y: Math.random()
                });
            }
            return data;
        }())
    }]
});
});
</code>```

and also if there is a way I could do to move the line movements on the center so that the right will always be blank like the image below

Please refer to this link.
Appreciate your help. Thank you.

答:
Spacing can be achieved with axis minPadding (space on the left) and maxPadding (space on the right).

```<code>xAxis: {
  type: 'datetime',
  tickPixelInterval: 150,
  maxPadding: 0.5
},
</code>```

As for the animation - you can add point with a disabled marker and then set timeout which will fire after the animation is finished and it will enable marker.

```<code>    load: function() {

      // set up the updating of the chart each second
      var series = this.series[0];
      setInterval(function() {
        var x = (new Date()).getTime(), // current time
          y = Math.random();

        series.addPoint({
          x: x,
          y: y,
          marker: {
            enabled: false
          }
        }, true, true);

        setTimeout(() => series.data[series.data.length - 1].update({marker: {enabled: true}}, true, false), 500)
      }, 1000);
    }
</code>```

By default the animation for adding point is set to 500 so if you change the animation aduration, you need to change the delay param in setTimeout.

example: http://jsfiddle.net/687215jj/1/

Body:
I am working on dynamic update using highchart.
Is there a way, wherein the line will go first on the next point before marker appear?
Currently what is happening is that, the marker appear first on the point before the line connects.

$(document).ready(function () {
Highcharts.setOptions({
    global: {
        useUTC: false
    }
});

Highcharts.chart('container', {
    chart: {
        type: 'spline',
        animation: Highcharts.svg, // don't animate in old IE
        marginRight: 10,
        events: {
            load: function () {

                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function () {
                    var x = (new Date()).getTime(), // current time
                        y = Math.random();
                    series.addPoint([x, y], true, true);
                }, 1000);
            }
        }
    },
    title: {
        text: 'Live random data'
    },
    xAxis: {
        type: 'datetime',
        tickPixelInterval: 150
    },
    yAxis: {
        title: {
            text: 'Value'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        formatter: function () {
            return '' + this.series.name + '
' +
                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '
' +
                Highcharts.numberFormat(this.y, 2);
        }
    },
    legend: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    series: [{
        name: 'Random data',
        data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -19; i <= 0; i += 1) {
                data.push({
                    x: time + i * 1000,
                    y: Math.random()
                });
            }
            return data;
        }())
    }]
});
});

and also if there is a way I could do to move the line movements on the center so that the right will always be blank like the image below

Please refer to this link.
Appreciate your help. Thank you.

Body:
Spacing can be achieved with axis minPadding (space on the left) and maxPadding (space on the right).

xAxis: {
  type: 'datetime',
  tickPixelInterval: 150,
  maxPadding: 0.5
},

As for the animation - you can add point with a disabled marker and then set timeout which will fire after the animation is finished and it will enable marker.

    load: function() {

      // set up the updating of the chart each second
      var series = this.series[0];
      setInterval(function() {
        var x = (new Date()).getTime(), // current time
          y = Math.random();

        series.addPoint({
          x: x,
          y: y,
          marker: {
            enabled: false
          }
        }, true, true);

        setTimeout(() => series.data[series.data.length - 1].update({marker: {enabled: true}}, true, false), 500)
      }, 1000);
    }

By default the animation for adding point is set to 500 so if you change the animation aduration, you need to change the delay param in setTimeout.

example: http://jsfiddle.net/687215jj/1/


来源: stackexchange

问:
chart.js filltext object moved when tooltip is generated because of legend not displaying
I wonder if anyone ran into similar situation like this.
I am using Chart.js to create a bar chart. One of the requirements for the bar chart component is to display bar data value on the bar itself. I created a simple plugin to do so and it works fine until I notice a display bug.

When hovering over any bars and the tooltip displays, the bar data value got pushed down a bit. I am not sure what happened. It seems that somehow the tooltip adds some sort of space in the chart.

Does anyone ever experience similar behavior?

Below is the plugin created to add the bar data value:

```<code>  Chart.pluginService.register({
afterDraw : function (chart ,easingValue, options) {
  var configOptions = chart.config.options;
  if (configOptions.barValueDisplay){
    var ctx = chart.chart.ctx;
    var scales = chart.scales;
    var datasets = chart.config.data.datasets;

    for(var i = 0; i< datasets.length; i++){
      var meta = chart.getDatasetMeta(i);
      var elements = meta.data
      var yScale = scales['y-axis-0'];
      for (var j = 0; j < elements.length; j++) {
        var view = elements[j]._view;

        var text = configOptions.barGoals ? datasets[i].rawData[j] :datasets[i].data[j];
        var textWidth = ctx.measureText(text).width
        var x = view.x - textWidth / 2;
        var y = yScale.bottom-15;
        ctx.save();
        ctx.fillStyle = configOptions.barValueDisplay.color;
        ctx.fillText(text, x, y);
        ctx.restore();
      }
    }
  }
}});
</code>```

UPDATE:
After creating a JSFiddler example, I realize that this behavior is related to legend not displaying.

So, any ideas how this could be addressed without displaying legend? Thanks

https://jsfiddle.net/charleschiu/9fc8n7cb/29/

答:
I was facing the same issue and posted an issue on the repository. Here's the reply:

The reason this is happening is that the tooltip is drawing text using
  a different textBaseline. The plugin in your fiddle doesn't set it so
  it will be whatever it last was.

I would change your plugin to have the following

```<code>var text = 'test';
var x = view.x;
var y = yScale.bottom;
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
ctx.fillStyle = 'rgba(255, 0, 255, 1)';
ctx.fillText(text, x, y);
</code>```

I tried it on the Fiddle and it works now!

ContentLicense: CC BY-SA 3.0

Body:
I wonder if anyone ran into similar situation like this.
I am using Chart.js to create a bar chart. One of the requirements for the bar chart component is to display bar data value on the bar itself. I created a simple plugin to do so and it works fine until I notice a display bug.

When hovering over any bars and the tooltip displays, the bar data value got pushed down a bit. I am not sure what happened. It seems that somehow the tooltip adds some sort of space in the chart.

Does anyone ever experience similar behavior?

Below is the plugin created to add the bar data value:

  Chart.pluginService.register({
afterDraw : function (chart ,easingValue, options) {
  var configOptions = chart.config.options;
  if (configOptions.barValueDisplay){
    var ctx = chart.chart.ctx;
    var scales = chart.scales;
    var datasets = chart.config.data.datasets;

    for(var i = 0; i< datasets.length; i++){
      var meta = chart.getDatasetMeta(i);
      var elements = meta.data
      var yScale = scales['y-axis-0'];
      for (var j = 0; j < elements.length; j++) {
        var view = elements[j]._view;

        var text = configOptions.barGoals ? datasets[i].rawData[j] :datasets[i].data[j];
        var textWidth = ctx.measureText(text).width
        var x = view.x - textWidth / 2;
        var y = yScale.bottom-15;
        ctx.save();
        ctx.fillStyle = configOptions.barValueDisplay.color;
        ctx.fillText(text, x, y);
        ctx.restore();
      }
    }
  }
}});

UPDATE:
After creating a JSFiddler example, I realize that this behavior is related to legend not displaying.

So, any ideas how this could be addressed without displaying legend? Thanks

https://jsfiddle.net/charleschiu/9fc8n7cb/29/

Body:
I was facing the same issue and posted an issue on the repository. Here's the reply:

The reason this is happening is that the tooltip is drawing text using
  a different textBaseline. The plugin in your fiddle doesn't set it so
  it will be whatever it last was.

I would change your plugin to have the following

var text = 'test';
var x = view.x;
var y = yScale.bottom;
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
ctx.fillStyle = 'rgba(255, 0, 255, 1)';
ctx.fillText(text, x, y);

I tried it on the Fiddle and it works now!


问:
Load text into SQL Server via Powershell
I am loading character data read from a file row by row into a SQL table.  The table is:

```<code>CREATE TABLE [dbo].[PSFileOrder](
    [PSFOrder_Id] [int] IDENTITY(0,1) NOT NULL,
    [PSFile] [varchar](255) NOT NULL,
 CONSTRAINT [PK_PSFileOrder] PRIMARY KEY CLUSTERED
(
    [PSFOrder_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

The powershell code I am using is

```<code>#LoadPSFile
$PSFile = "d:\ps\xx.ps1"
cls
$xy = Get-content $PSFile
$xy
foreach($xy in $xy) {invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}
</code>```

If the file I am loading is:

```<code>#Filename
#The first line will always be the file name
cls
$filter = "*.*"
$folder = "\\localhost\d$\Master\men and their toys"
$filecount = (Get-ChildItem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Count
If ($filecount -lt 1) {$filecount = 0}
"There are {0} files in the {1} directory" -f $filecount, $folder
</code>```

the file loads without error.  If there is a single quote in the text

```<code>"There are {0} files in the {1} d'irectory" -f $filecount, $folder
</code>```

then I will recieve this error

```<code>Invoke-Sqlcmd : Incorrect syntax near 'irectory'.
Unclosed quotation mark after the character string ' -f $filecount, $folder')
;'.
At C:\Users\RC\AppData\Local\Temp\2ed13f21-5b46-4df4-a5ee-2488c3dd5ee4.ps1:6 char:35
+ foreach($xy in $xy) {invoke-sqlcmd <<<<  -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
</code>```

I do believe the error is caused by the way I have written the "-query" statement using single quotes arount the $xy variable.

My questions are:

Have I crafted the Invoke-sqlcmd correctly?

Is there a substitue for the single quote around $xy?

Is there a better way to load the text?

I want to maintain the one to one relationship of the text file and row in the db.

Thanks
RC

Two answers put me on the correct path of doubling the single quote prior to loading to SQL.  The revised code is

```<code>#LoadPSFile
cls
Get-content "d:\ps\xx.ps1" |
Foreach-Object {$_ -replace "'", "''"} |
ForEach-Object{invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$_')"}
</code>```

答:
You get malformed SQL syntax. I believe the quick fix is to replace any single quote with two single quotes in $xy:

```<code>$escaped = $xy.Replace("'", "''")
invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$escaped')"

# or (the same but without the intermediate variable):

invoke-sqlcmd -serverInstance localhost\sqlexpress -query @"
Insert AA.dbo.PSFileOrder(PSFile) Values ('$($xy.Replace("'", "''"))')
"@
</code>```

But this is perhaps not the best way. Unfortunately I am not familiar with invoke-sqlcmd capabilities. If it supports parameterized queries I would go that way and supply $xy value as it is as a parameter value (no preparation of $xy would be needed in such a case).

ContentLicense: CC BY-SA 2.5

Body:
I am loading character data read from a file row by row into a SQL table.  The table is:

CREATE TABLE [dbo].[PSFileOrder](
    [PSFOrder_Id] [int] IDENTITY(0,1) NOT NULL,
    [PSFile] [varchar](255) NOT NULL,
 CONSTRAINT [PK_PSFileOrder] PRIMARY KEY CLUSTERED
(
    [PSFOrder_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

The powershell code I am using is

#LoadPSFile
$PSFile = "d:\ps\xx.ps1"
cls
$xy = Get-content $PSFile
$xy
foreach($xy in $xy) {invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}

If the file I am loading is:

#Filename
#The first line will always be the file name
cls
$filter = "*.*"
$folder = "\\localhost\d$\Master\men and their toys"
$filecount = (Get-ChildItem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Count
If ($filecount -lt 1) {$filecount = 0}
"There are {0} files in the {1} directory" -f $filecount, $folder

the file loads without error.  If there is a single quote in the text

"There are {0} files in the {1} d'irectory" -f $filecount, $folder

then I will recieve this error

Invoke-Sqlcmd : Incorrect syntax near 'irectory'.
Unclosed quotation mark after the character string ' -f $filecount, $folder')
;'.
At C:\Users\RC\AppData\Local\Temp\2ed13f21-5b46-4df4-a5ee-2488c3dd5ee4.ps1:6 char:35
+ foreach($xy in $xy) {invoke-sqlcmd <<<<  -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

I do believe the error is caused by the way I have written the "-query" statement using single quotes arount the $xy variable.

My questions are:

Have I crafted the Invoke-sqlcmd correctly?

Is there a substitue for the single quote around $xy?

Is there a better way to load the text?

I want to maintain the one to one relationship of the text file and row in the db.

Thanks
RC

Two answers put me on the correct path of doubling the single quote prior to loading to SQL.  The revised code is

#LoadPSFile
cls
Get-content "d:\ps\xx.ps1" |
Foreach-Object {$_ -replace "'", "''"} |
ForEach-Object{invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$_')"}

Body:
You get malformed SQL syntax. I believe the quick fix is to replace any single quote with two single quotes in $xy:

$escaped = $xy.Replace("'", "''")
invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$escaped')"

# or (the same but without the intermediate variable):

invoke-sqlcmd -serverInstance localhost\sqlexpress -query @"
Insert AA.dbo.PSFileOrder(PSFile) Values ('$($xy.Replace("'", "''"))')
"@

But this is perhaps not the best way. Unfortunately I am not familiar with invoke-sqlcmd capabilities. If it supports parameterized queries I would go that way and supply $xy value as it is as a parameter value (no preparation of $xy would be needed in such a case).


问:
Android Instant Apps : How to test an Instant app after deploying?
I recently made an Instant app and uploaded it on Google Play Console as pre-release.

Now, I want to test if it is working or not. As most of the smartphones currently do not have Instant apps facility. How can I test if it is working or not?

答:
First of all you are gonna need to use a device or an emulator with at least MarshMallow(6.0) and enable it (https://support.google.com/googleplay/answer/7240211?hl=en-GB).

Then you need to run the url that you set using the App Links Assistant. For example, using Slack(its like a whatsapp/telegram for the office) I m sending that url as a message and when I click on it in the device/emulator it runs the InstantApp.

In the Google IO 2016 they did a sample using a messaging app (https://www.youtube.com/watch?v=Z5GUTXmGUz8)

I hope this helps.

Cheers ;)

Pd: I tried the same using gmail and sending an email just with the url but it didnt work


问:
Getting a value of a table with maximum date and time
In my database (SQL Server 11), I have the next situation:

```<code>SELECT Npa, Vty, Dat, Hou FROM DleVldAud WHERE Npa = '4-130325x01'
</code>```

Result:

```<code>_____Npa____|____Vty_____|___________Dat___________|___Hou___
4-130325x01 | Definitive | 2013-03-25 00:00:00.000 | 12:13:57
4-130325x01 | Sent BNP   | 2013-03-25 00:00:00.000 | 12:14:04
</code>```

QUESTION is, I would like to get the value of Vty for a concrete Npa with higher (MAX) value of Dat and Hou... how?

In this case, I would like to get the 2nd row:

```<code>_____Npa____|____Vty_____|___________Dat___________|___Hou___
4-130325x01 | Sent BNP   | 2013-03-25 00:00:00.000 | 12:14:04
</code>```

答:
If I understand correctly:</p>

```<code>select top 1 vty
from t
where npa = @npa
order by dat desc, hou desc;
</code>```

Body:
In my database (SQL Server 11), I have the next situation:

SELECT Npa, Vty, Dat, Hou FROM DleVldAud WHERE Npa = '4-130325x01'

Result:

_____Npa____|____Vty_____|___________Dat___________|___Hou___
4-130325x01 | Definitive | 2013-03-25 00:00:00.000 | 12:13:57
4-130325x01 | Sent BNP   | 2013-03-25 00:00:00.000 | 12:14:04

QUESTION is, I would like to get the value of Vty for a concrete Npa with higher (MAX) value of Dat and Hou... how?

In this case, I would like to get the 2nd row:

_____Npa____|____Vty_____|___________Dat___________|___Hou___
4-130325x01 | Sent BNP   | 2013-03-25 00:00:00.000 | 12:14:04

Body:
If I understand correctly:

select top 1 vty
from t
where npa = @npa
order by dat desc, hou desc;


问:
core data nstableview searchbar
i have a nstableview which i fill with data of core data.

NSManagedObject

```<code>import Foundation
import CoreData

@objc(Person)
public class Person: NSManagedObject {
    @NSManaged public var firstName: String
    @NSManaged public var secondName: String
}
</code>```

RequestData

```<code> func requestData() {
        let appdelegate = NSApplication.shared().delegate as! AppDelegate
        let context = appdelegate.persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        do {
            person = try context.fetch(request) as! [Person]
            tableViewn.reloadData()
        } catch { }
    }
</code>```

i also have a custom cell view for my tableView.
I fill the data like this:

```<code>func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let view = tableView.make(withIdentifier: "Cell", owner: self) as? CustomCell

        view?.txtfirstName.stringValue = person.firstName
        view?.txtsecondName.stringValue = person.secondName
        return view
}
</code>```

Now i would like to realize a searchbar (which i have already in my view controller) for searching with first or second name.

but i have no idea how i can realize this.

答:
Set the delegate of the NSSearchField to the target class

implement controlTextDidChange

```<code>override func controlTextDidChange(_ notification: Notification) {
    if let field = notification.object as? NSSearchField {
        let query = field.stringValue
        let predicate : NSPredicate?
        if query.isEmpty {
            predicate = nil
        } else {
            predicate = NSPredicate(format: "firstName contains[cd] %@ OR lastName contains[cd] %@", query, query)
        }
        requestData(with: predicate)
    } else {
        super.controlTextDidChange(notification)
    }
}
</code>```

Change requestData to

```<code>func requestData(with predicate : NSPredicate? = nil) {
    let appdelegate = NSApplication.shared().delegate as! AppDelegate
    let context = appdelegate.persistentContainer.viewContext
    let request = NSFetchRequest<Person>(entityName: "Person")
    request.predicate = predicate

    do {
        person = try context.fetch(request)
        tableViewn.reloadData()
    } catch { }
}
</code>```

Side note:

If you are using NSManagedObject subclasses create the fetch request more specific NSFetchRequest<Person>(entityName... rather than NSFetchRequest<NSFetchRequestResult>(entityName..., that avoids the type cast in the fetch line.

Title: core data nstableview searchbar

Body:
i have a nstableview which i fill with data of core data.

NSManagedObject

import Foundation
import CoreData

@objc(Person)
public class Person: NSManagedObject {
    @NSManaged public var firstName: String
    @NSManaged public var secondName: String
}

RequestData

 func requestData() {
        let appdelegate = NSApplication.shared().delegate as! AppDelegate
        let context = appdelegate.persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        do {
            person = try context.fetch(request) as! [Person]
            tableViewn.reloadData()
        } catch { }
    }

i also have a custom cell view for my tableView.
I fill the data like this:

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let view = tableView.make(withIdentifier: "Cell", owner: self) as? CustomCell

        view?.txtfirstName.stringValue = person.firstName
        view?.txtsecondName.stringValue = person.secondName
        return view
}

Now i would like to realize a searchbar (which i have already in my view controller) for searching with first or second name.

but i have no idea how i can realize this.

Body:
Set the delegate of the NSSearchField to the target class

implement controlTextDidChange

override func controlTextDidChange(_ notification: Notification) {
    if let field = notification.object as? NSSearchField {
        let query = field.stringValue
        let predicate : NSPredicate?
        if query.isEmpty {
            predicate = nil
        } else {
            predicate = NSPredicate(format: "firstName contains[cd] %@ OR lastName contains[cd] %@", query, query)
        }
        requestData(with: predicate)
    } else {
        super.controlTextDidChange(notification)
    }
}

Change requestData to

func requestData(with predicate : NSPredicate? = nil) {
    let appdelegate = NSApplication.shared().delegate as! AppDelegate
    let context = appdelegate.persistentContainer.viewContext
    let request = NSFetchRequest<Person>(entityName: "Person")
    request.predicate = predicate

    do {
        person = try context.fetch(request)
        tableViewn.reloadData()
    } catch { }
}

Side note:

If you are using NSManagedObject subclasses create the fetch request more specific NSFetchRequest<Person>(entityName... rather than NSFetchRequest<NSFetchRequestResult>(entityName..., that avoids the type cast in the fetch line.


问:
I got the same message twice
I used this code to send a different message if a new user start conversation :

```<code>IConversationUpdateActivity update = message;
            var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
            if (update.MembersAdded != null && update.MembersAdded.Any())
            {
                foreach (var newMember in update.MembersAdded)
                {
                    if (newMember.Id != message.Recipient.Id)
                    {
                        var reply = message.CreateReply();
                        reply.Text = $"Welcome {newMember.Name}! You are a new member! If you want to see help menu , type : help";
                        client.Conversations.ReplyToActivityAsync(reply);
                    }
                }
            }
</code>```

My problem is that when a user click in facebook : Get started  this message comes twice.

Can you please help me ?

答:
Facebook includes the conversation itself in the list of members:

So you need to change the if statement to this:

```<code>if (newMember.Id != message.Recipient.Id && newMember.Id != message.Conversation.Id)
{
   // send welcome message
</code>```

Title: I got the same message twice

Body:
I used this code to send a different message if a new user start conversation :

IConversationUpdateActivity update = message;
            var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
            if (update.MembersAdded != null && update.MembersAdded.Any())
            {
                foreach (var newMember in update.MembersAdded)
                {
                    if (newMember.Id != message.Recipient.Id)
                    {
                        var reply = message.CreateReply();
                        reply.Text = $"Welcome {newMember.Name}! You are a new member! If you want to see help menu , type : help";
                        client.Conversations.ReplyToActivityAsync(reply);
                    }
                }
            }

My problem is that when a user click in facebook : Get started  this message comes twice.

Can you please help me ?

Body:
Facebook includes the conversation itself in the list of members:

So you need to change the if statement to this:

if (newMember.Id != message.Recipient.Id && newMember.Id != message.Conversation.Id)
{
   // send welcome message


答:
You must double the apostrophes within the string

```<code>foreach($xy in $xy)
{
    $xy = $xy -replace "'", "''"
    invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"
}
</code>```

when performance is an issue, you choose some bulkcopy solultion. In the SQLPSX project
there is a module adolib.psm1 which contains a function invoke-bulkcopy

link text

Title: Load text into SQL Server via Powershell

Body:
You must double the apostrophes within the string

foreach($xy in $xy)
{
    $xy = $xy -replace "'", "''"
    invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"
}

when performance is an issue, you choose some bulkcopy solultion. In the SQLPSX project
there is a module adolib.psm1 which contains a function invoke-bulkcopy

link text


问:
How to check different conditions into if statement based on different scenario
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

```<code>$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}
</code>```

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

答:
Potentially turn it into a function that funnels into a switch statement like so:

```<code>function evaluateCondition($status, $a, $b) {
    switch ($status) {
        case 'Y':
            return $a >= $b;
            break;
        case 'N':
            return $a <= $b;
            break;
        default:
            // Error Log. Unknown Status.
    }
}
</code>```

Any future addition can be appended onto the switch statement as necessary, if it gets more convoluted have each case return a separate function() to improve readability.

In terms of the current version you could use it like so:

```<code>$result = evaluateCondition('Y', 5, 6);
var_dump($result); // bool(false)
</code>```

Hope that helps.

Body:
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

Body:
Potentially turn it into a function that funnels into a switch statement like so:

function evaluateCondition($status, $a, $b) {
    switch ($status) {
        case 'Y':
            return $a >= $b;
            break;
        case 'N':
            return $a <= $b;
            break;
        default:
            // Error Log. Unknown Status.
    }
}

Any future addition can be appended onto the switch statement as necessary, if it gets more convoluted have each case return a separate function() to improve readability.

In terms of the current version you could use it like so:

$result = evaluateCondition('Y', 5, 6);
var_dump($result); // bool(false)

Hope that helps.


问:
Why variable not renders on page?
I have following thymeleaf snippet:

```<code>    ...
    <p>///////</p>
    ${userName}
    <p>///////</p>
    ...
</code>```

And I have followinf controller:

```<code>GetMapping(value = {"/main"})
    public String showPersonsPage(Model model) {
        // don't fill models here. All data got via web socket's subscription.
        model.addAttribute("userName", startupHouseKeeper.getUser().getUserName());
        return "main";
    }
</code>```

But on page I see:

What did I wrong?

答:
Inteads of ${userName} use:

```<code>[[${userName}]]
</code>```

Always surround variables with square brackets if they are outside of a HTML tag. Below solution without additional brackets:

```<code><p th:text="${userName}"></p>
</code>```

Title: Why variable not renders on page?

Body:
I have following thymeleaf snippet:

    ...

///////

    ${userName}

///////

    ...

And I have followinf controller:

GetMapping(value = {"/main"})
    public String showPersonsPage(Model model) {
        // don't fill models here. All data got via web socket's subscription.
        model.addAttribute("userName", startupHouseKeeper.getUser().getUserName());
        return "main";
    }

But on page I see:

What did I wrong?

Body:
Inteads of ${userName} use:

[[${userName}]]

Always surround variables with square brackets if they are outside of a HTML tag. Below solution without additional brackets:

<p th:text="${userName}"></p>


问:
Dynamic hyperlink from code behind asp.net
I want dynamic hyperlink on each field in a table column from code behind in asp.net, I implement it thus:

```<code>table.Append("<td><asp:HyperLink ID='HyperLink1' NavigateUrl='#' runat='server'>" + (string)strNAME + "</asp:HyperLink></td>");
</code>```

on the field but when I run it there is no link to click. it is not effective. what is the correct way of implementing it?

答:
You need to approach this in a different way. Server side controls cannot be added as string literals, they should be objects. So what you can do is either add it as a server side control:

```<code>HyperLink hl = new HyperLink();
hl.ID = "HyperLink1";
hl.NavigateUrl = "#";
hl.Text = (string)strNAME;
TableCell tc = new TableCell();
tc.Controls.Add(hl);
table.Controls.Add(tc);
</code>```

Or add it as a client side link:

```<code>table.Append("<td><a href='#'>" + (string)strNAME + "</a></td>");
</code>```

Side note: adding table cell to "table" kind of does not make sense because there supposed to be a row, not a table, but I just left your code as is, adjust as needed.

Body:
I want dynamic hyperlink on each field in a table column from code behind in asp.net, I implement it thus:

table.Append("<asp:HyperLink ID='HyperLink1' NavigateUrl='#' runat='server'>" + (string)strNAME + "</asp:HyperLink>	");

on the field but when I run it there is no link to click. it is not effective. what is the correct way of implementing it?

Body:
You need to approach this in a different way. Server side controls cannot be added as string literals, they should be objects. So what you can do is either add it as a server side control:

HyperLink hl = new HyperLink();
hl.ID = "HyperLink1";
hl.NavigateUrl = "#";
hl.Text = (string)strNAME;
TableCell tc = new TableCell();
tc.Controls.Add(hl);
table.Controls.Add(tc);

Or add it as a client side link:

table.Append("<td><a href='#'>" + (string)strNAME + "</a></td>");

Side note: adding table cell to "table" kind of does not make sense because there supposed to be a row, not a table, but I just left your code as is, adjust as needed.


问:
How to handle both a promise or variable return from a function
Here is a simplified version of what I have:

```<code>function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}
</code>```

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

```<code>var testResponseTrue = test(true);
var testResponseFalse = test(false);
</code>```

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)

答:
It makes it a bit complicated that your consumers would have to check if they now got a promise back or not. I would rather choose to internally go for an autoresolving promise in case the boolean is false, so that you can handle the response in the same way as you would with a boolean that is true

// mock
function makeAPIrequest() {
  return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) );
}

function test(thisBool){
  return new Promise( (resolve, reject) => {
    if (thisBool) {
      makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) );
      return;
    }
    setTimeout( () => resolve('does not matter'), 0);
  });
}

test(true).then( response => console.log('response from true = ' + response ) );
test(false).then( response => console.log('response from false = ' + response ) );```
</div>
</div>
</p>

<p>If you really want to catch the values in variables, I guess you could also use the <code>async/await pattern</code>, like in the following snippet</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(async () => { // mock
  function makeAPIrequest() {
    return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) );
  }

  let test = function async(thisBool){
    return new Promise( (resolve, reject) => {
      if (thisBool) {
        makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) );
        return;
      }
      setTimeout( () => resolve('does not matter'), 0);
    });
  }

  var testResponse1 = await test(true);
  var testResponse2 = await test(false);
  console.log( testResponse1 );
  console.log( testResponse2 );
})();</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a simplified version of what I have:

function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

var testResponseTrue = test(true);
var testResponseFalse = test(false);

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)

Body:
It makes it a bit complicated that your consumers would have to check if they now got a promise back or not. I would rather choose to internally go for an autoresolving promise in case the boolean is false, so that you can handle the response in the same way as you would with a boolean that is true

// mock
function makeAPIrequest() {
  return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) );
}

function test(thisBool){
  return new Promise( (resolve, reject) => {
    if (thisBool) {
      makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) );
      return;
    }
    setTimeout( () => resolve('does not matter'), 0);
  });
}

test(true).then( response => console.log('response from true = ' + response ) );
test(false).then( response => console.log('response from false = ' + response ) );

If you really want to catch the values in variables, I guess you could also use the async/await pattern, like in the following snippet

(async () => { // mock
  function makeAPIrequest() {
    return new Promise( (resolve) => setTimeout( () => resolve('done'), 100 ) );
  }

  let test = function async(thisBool){
    return new Promise( (resolve, reject) => {
      if (thisBool) {
        makeAPIrequest().then( result => resolve(result) ).catch( err => reject(err) );
        return;
      }
      setTimeout( () => resolve('does not matter'), 0);
    });
  }

  var testResponse1 = await test(true);
  var testResponse2 = await test(false);
  console.log( testResponse1 );
  console.log( testResponse2 );
})();


问:
Google Analytics - Setting Custom Variable Failed!
i am attempting to set a custom variable on a contact form that tracks when a form submission is success.  However, in my google analytics page the custom variable isn't showing up in Visitor -> Custom Variable.  I understand it takes a few hours for it to refresh but it has been a week.  So, my basic assumption is that it didn't work.  I am using async _gaq.push() to achieve this.  Basically, i set custom variable after my ajax function call to submitting the contact form and within the callback function if success i set the following:

```<code>_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);
</code>```

This is my google analytic code in the head.

```<code>var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-x']); //my google analytic api key
_gaq.push(['_trackPageview']);
(function() {
     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();
</code>```

Actually a better question is, does a _gaq.push(['_trackPageview']); need to be called after a _gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]); for it to "register" the _setCustomVar call, and is it ok for me to call _gaq.push(['_trackPageview']); more than once after DOM is loaded via javascript (weather it be off an event or callback ajax function).  Thanks guys.

答:
setCustomVar has to be set prior to a request sent to Google. It doesn't set it's own request; it merely queues up the variable to be sent anytime within that page session.

If it's set after the pageview, and the page changes before any requests are sent to Google Analytics (like making a pageview or event track call), then Google will never receive the data about your custom variable.

So, if you can't set the variable before the initial pageview, you need to either generate a 2nd pageview. Or, you can make a google analytics event tracking call, which can also carry your custom variable to Google Analytics.

So, what you need to do is set another call directly after your setCustomVar to do something like this:

```<code>_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);
_gaq.push(['_trackEvent', 'contact', 'success',"", 0, true]);
</code>```

Body:
i am attempting to set a custom variable on a contact form that tracks when a form submission is success.  However, in my google analytics page the custom variable isn't showing up in Visitor -> Custom Variable.  I understand it takes a few hours for it to refresh but it has been a week.  So, my basic assumption is that it didn't work.  I am using async _gaq.push() to achieve this.  Basically, i set custom variable after my ajax function call to submitting the contact form and within the callback function if success i set the following:

_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);

This is my google analytic code in the head.

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-x']); //my google analytic api key
_gaq.push(['_trackPageview']);
(function() {
     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();

Actually a better question is, does a _gaq.push(['_trackPageview']); need to be called after a _gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]); for it to "register" the _setCustomVar call, and is it ok for me to call _gaq.push(['_trackPageview']); more than once after DOM is loaded via javascript (weather it be off an event or callback ajax function).  Thanks guys.

Body:
setCustomVar has to be set prior to a request sent to Google. It doesn't set it's own request; it merely queues up the variable to be sent anytime within that page session.

If it's set after the pageview, and the page changes before any requests are sent to Google Analytics (like making a pageview or event track call), then Google will never receive the data about your custom variable.

So, if you can't set the variable before the initial pageview, you need to either generate a 2nd pageview. Or, you can make a google analytics event tracking call, which can also carry your custom variable to Google Analytics.

So, what you need to do is set another call directly after your setCustomVar to do something like this:

_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);
_gaq.push(['_trackEvent', 'contact', 'success',"", 0, true]);


问:
Continue timer through View Controllers
I am working on an app that requires timing. The timer activates in one View Controller and it needs to continue until the last View Controller. For example, I have 5 View Controllers and the timer need to start in first View Controller at 15 minutes, then the user starts using the next four View Controllers. When the user reaches the fourth View Controller, then the timer should stop and the user should be shown with an alert how long it took for them to finish.</p>

答:
Create a Singleton Class for Timer and initialise the timer when First View is loaded, when you reach your final view check the timer current status.

In order to receive callbacks for time-up you will have to implement local notification, and add each of the view controllers as observers (don't forget to remove them from notification pool when views are destroyed)

Title: Continue timer through View Controllers


问:
Creating a Cordova plugin for Ionic based on Android SDK
I need to create an Ionic app that uses a native Android SDK in order to perform the functionality I want. The SDK is an AAR and allows me to develop an Android app that handles things like web services, bluetooth, etc. The problem is that I need to develop the app cross platform using Ionic and that means ultimately creating a Cordova plugin. I've looked around the net for information on Cordova plugins but I'm not quite sure how to develop a plugin larger than an echo because thats all anyone ever seems to show.

So my question is, where do I begin? Do I develop the Android app first and then copy the java code into my Cordova plugin or do I develop the Cordova plugin at the same time as creating the java code based on the Android SDK I've been provided with?

If I build the Cordova plugin without the Android application first I won't be able to test, so maybe I should build the Android app first and then port it into a Cordova plugin?

Thanks

答:
where do I begin?

Use an existing (real) Cordova plugin as reference.

Depending how your SDK is packaged, depends how you'll need to install it from your plugin.

If your SDK is a JAR file, you'll need to place it in your plugin folder and add an entry to your plugin.xml to deploy it. For example cordova-plugin-cipherlab-rs30 does this.

Or if your SDK is available via Maven, you can use <framework> tags to satisfy the dependency via Gradle: e.g. cordova-plugin-facebook.

Do I develop the Android app first and then copy the java code into my Cordova plugin

I wouldn't recommend this if you're ultimately developing a Cordova plugin, otherwise you will create more work than necessary.

If I build the Cordova plugin without the Android application first I won't be able to test

This is not true:

create your plugin locally e.g. /path/to/my/plugin

then create a Cordova test app project which you'll use to test it, e.g. cordova create myplugintest

add your plugin to your test project: cd myplugintest && cordova plugin add /path/to/my/plugin

add the Android platform: cordova platform add android

Open the native Android project in Android Studio: /path/to/myplugintest/platforms/android

Set breakpoints and debug your plugin by running your test app in Android studio.

Any code changes you make to your plugin Java in Android Studio will need to be copied back to your plugin source in /path/to/my/plugin/


问:
In My Laravel Passport Application, how can I accept access_tokens (when the client does not send a Bearer header)
I am using an OAuth2 client that does not send Authorization: Bearer but the standard laravel/passport setup checks this header. How to make it compatible from Laravel side?</p>

答:
Add the following middle ware

```<code><?php

namespace App\Http\Middleware;

class ConvertTokenToBearer
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param                          $next
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, $next)
    {
        if ($request->get('access_token')) {
            $request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
        }
        $response = $next($request);
        return $response;
    }
}
</code>```

And add it to your  app/Http/Kernel.php file.

```<code>class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\ConvertTokenToBearer::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];
</code>```

Body:
Add the following middle ware

<?php

namespace App\Http\Middleware;

class ConvertTokenToBearer
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param                          $next
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, $next)
    {
        if ($request->get('access_token')) {
            $request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
        }
        $response = $next($request);
        return $response;
    }
}

And add it to your  app/Http/Kernel.php file.

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\ConvertTokenToBearer::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];


问:
How to print a variable of type NVARCHAR(MAX) while looping over a CURSOR
I am trying to write a stored procedure which generates dynamic views for tables. For that purpose I am storing the generated View in a NVARCHAR(MAX) type variable. But due to size limitations the variable is getting truncated.

I tried a couple of work around techniques but none of them seem to work for me. I can't split the variable into chunks because I do not know what size the variable will be and I want to write a generic logic for generating views.

Here is the code snippet -

```<code>DECLARE CURTABLE CURSOR FOR
SELECT A
FROM TABLE A
WHERE ID = 189
Order By ID
OPEN curTable
FETCH NEXT FROM curTable INTO @columnname
DECLARE @tsql NVARCHAR(MAX)
WHILE @@fetch_status=0
BEGIN
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' ' + quotename(@columnname,'[')
    ELSE
        SET @tsql=@tsql+@ViewFunctionValue
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' AS ' + quotename(@columnname,'[')

    SET @tsql = @tsql + ', '  + CHAR(10)

    FETCH NEXT FROM curTable INTO @columnname
END
CLOSE curTable
DEALLOCATE curTable

SET @tsql = LEFT(@tsql,LEN(@tsql)-3) + CHAR(10)
SET @tsql= @tsql+' FROM ' + TABLEA

PRINT @tsql
</code>```

答:
I resolved my issue by printing in chunks.

There's a catch here. PRINT command in SQL Server prints a newline character at the end.

Since the code aimed to form a dynamic view for a table, I didn't want any new line characters at the wrong places. So, I parsed the code to find a comma( since my view has comma separated statements) after which I could safely put a new line character.

```<code>IF LEN(@tsql) > 3000
BEGIN
    SET @Count = 0
    WHILE @Count < LEN(@tsql)
    BEGIN
        SET @pos = CHARINDEX(',',@tsql,3000)
        PRINT SUBSTRING(@tsql,@Count,@pos+1)
        SET @Count += @pos+1
    END
END
ELSE
    PRINT @tsql
</code>```

Body:
I am trying to write a stored procedure which generates dynamic views for tables. For that purpose I am storing the generated View in a NVARCHAR(MAX) type variable. But due to size limitations the variable is getting truncated.

I tried a couple of work around techniques but none of them seem to work for me. I can't split the variable into chunks because I do not know what size the variable will be and I want to write a generic logic for generating views.

Here is the code snippet -

DECLARE CURTABLE CURSOR FOR
SELECT A
FROM TABLE A
WHERE ID = 189
Order By ID
OPEN curTable
FETCH NEXT FROM curTable INTO @columnname
DECLARE @tsql NVARCHAR(MAX)
WHILE @@fetch_status=0
BEGIN
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' ' + quotename(@columnname,'[')
    ELSE
        SET @tsql=@tsql+@ViewFunctionValue
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' AS ' + quotename(@columnname,'[')

    SET @tsql = @tsql + ', '  + CHAR(10)

    FETCH NEXT FROM curTable INTO @columnname
END
CLOSE curTable
DEALLOCATE curTable

SET @tsql = LEFT(@tsql,LEN(@tsql)-3) + CHAR(10)
SET @tsql= @tsql+' FROM ' + TABLEA

PRINT @tsql

Body:
I resolved my issue by printing in chunks.

There's a catch here. PRINT command in SQL Server prints a newline character at the end.

Since the code aimed to form a dynamic view for a table, I didn't want any new line characters at the wrong places. So, I parsed the code to find a comma( since my view has comma separated statements) after which I could safely put a new line character.

IF LEN(@tsql) > 3000
BEGIN
    SET @Count = 0
    WHILE @Count < LEN(@tsql)
    BEGIN
        SET @pos = CHARINDEX(',',@tsql,3000)
        PRINT SUBSTRING(@tsql,@Count,@pos+1)
        SET @Count += @pos+1
    END
END
ELSE
    PRINT @tsql


问:
Java convert String of byte array to byte array
I got a byte array sent from javascript by ajax looking like this:

```<code>"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."
</code>```

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

```<code>    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }
</code>```

答:
EDIT: Actually parseByte doesn't seems to be a safe choice for your case because of this, so I took inspiration from this answer to change it.

You can do:

```<code>String bytesAsStringWithCommas = "89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ...";
String[] bytesStr = bytesAsStringWithCommas.split(",");
byte[] byteArray = new byte[bytesStr.length];
for (int j = 0; j < bytesStr.length; j++) {
    byteArray[j] = (byte) ((Character.digit(bytesStr[j].charAt(0), 16) << 4) + Character.digit(bytesStr[j].charAt(1), 16));
}
</code>```

You should probably change your server code or client code to send data directly instead of using convoluted solutions like this one. Or you can also use Base64 encoding, which is going to be already better than your current solution.

Body:
I got a byte array sent from javascript by ajax looking like this:

"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }

Body:
EDIT: Actually parseByte doesn't seems to be a safe choice for your case because of this, so I took inspiration from this answer to change it.

You can do:

String bytesAsStringWithCommas = "89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ...";
String[] bytesStr = bytesAsStringWithCommas.split(",");
byte[] byteArray = new byte[bytesStr.length];
for (int j = 0; j < bytesStr.length; j++) {
    byteArray[j] = (byte) ((Character.digit(bytesStr[j].charAt(0), 16) << 4) + Character.digit(bytesStr[j].charAt(1), 16));
}

You should probably change your server code or client code to send data directly instead of using convoluted solutions like this one. Or you can also use Base64 encoding, which is going to be already better than your current solution.


问:
How does WebRTC work?
I'm interested in Peer-to-Peer connections in the browser. Since this seems to be possible with WebRTC, I'm wondering how it works exaclty.

I've read some explanations and saw diagrams about it and now it's clear to me, that the connection establishmet works over the server. The server seems to exchange some data between the client that are willing to connect to each other, so that they can start a direct connection, that is independent of the server.

But that's exaclty what I don't understand. Until now, I thought the only way to create connections is to listen on a port on computer A and connect to that port from computer B. But this does not seem to be the case in WebRTC. I think none of the clients starts to listen on a port. Somehow, they can create a connection without listening on ports and accepting connections. Neither client A, nor client B starts acting as a server.

But how? What data is exchanged over the WebRTC server, that the clients can use to connect to each other?

Thanks for your explanations for this :)

Edit

I found this article. It's not related to WebRTC, but I think it answers a part of my question. I'm not sure, tough. It still would be cool, if someone could explain it to me and give me some additional links.

答:
Establishing a p2p WebRTC connection has 3 steps (10.000 feet overview) :

Step 1: Signaling: both peers connect to a signaling server (using websockets over 80/443, comet, SIP,etc..) and exchange information (about their media capabilities, public IP:port pairs when they become available, etc.)

Step 2: Discovery: Devices connected to LAN or mobile networks are not aware of their public IP (and port) where they can be reached at so they use STUN/TURN servers located on the public Internet to discover their ip:port pair (ICE candidates). In the process they punch a hole through the NAT/router which is used in step3:

Step 3: P2P connection: once the ICE candidates are exchanged through the initial signaling channel each peer is aware of each other's ip:port (and holes have been punched in NATs/routers) so a peer to peer UDP connection can be established.

The scheme above explains the process with 2 devices connected to local networks. It's part of an article I wrote that deals with troubleshooting connection issues but it does a good job of explaining how WebRTC works.

Title: How does WebRTC work?


问:
How to pass dynamic initial values to redux-form
I'm using redux form in a table, I'm passing id as initial value to update some record.

If I pass initial value, it's taking same id to all the rows.

How can I do this ?

```<code>initialValues: { lead_id: id} //from component

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);
</code>```

Thank You

答:
Make use of connect to set the intialValues

```<code>initialValues: { lead_id: id}

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);

Leads = connect(
  state => ({
    initialValues: initialValues
  })
)(Leads);
</code>```

Body:
I'm using redux form in a table, I'm passing id as initial value to update some record.

If I pass initial value, it's taking same id to all the rows.

How can I do this ?

initialValues: { lead_id: id} //from component

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);

Thank You

Body:
Make use of connect to set the intialValues

initialValues: { lead_id: id}

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);

Leads = connect(
  state => ({
    initialValues: initialValues
  })
)(Leads);


答:
Creating hyperlink from code-behind

```<code>HyperLink hlnk = new HyperLink();
        hlnk.InnerText = (string)strNAME;
        hlnk.ID = "HyperLink1";
        hlnk.NavigateUrl = "/test.aspx";
table.Controls.Add(hlnk);
</code>```

hope it helps

Title: Dynamic hyperlink from code behind asp.net

Body:
Creating hyperlink from code-behind

HyperLink hlnk = new HyperLink();
        hlnk.InnerText = (string)strNAME;
        hlnk.ID = "HyperLink1";
        hlnk.NavigateUrl = "/test.aspx";
table.Controls.Add(hlnk);

hope it helps


问:
How to hide notification icons in Android Status Bar?
I'm working on a German Learning app project, inspired by Duolingo app.

I need to make my app to be a little bit similar with this feature. It's like making the user to focus on the quiz, and ignore everything in status bar (notification bar). Now, what I need is i want to hide the icons on notification bar. Is there a way to do so?

This is what I want

And this is the fact

答:
You can dim the status and navigation bars by setting the SYSTEM_UI_FLAG_LOW_PROFILE flag.

```<code>View decorView = getActivity().getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
</code>```

https://developer.android.com/training/system-ui/dim.html

This decoration is reset whenever the keyboard is made visible, but you can watch for the keyboard being hidden (using an onGlobalLayoutListener) and resetting the flag.

Body:
You can dim the status and navigation bars by setting the SYSTEM_UI_FLAG_LOW_PROFILE flag.

View decorView = getActivity().getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);

https://developer.android.com/training/system-ui/dim.html

This decoration is reset whenever the keyboard is made visible, but you can watch for the keyboard being hidden (using an onGlobalLayoutListener) and resetting the flag.


答:
you can use unpivot as below:</p>

```<code>Select * from #temp
unpivot (fieldvalue for fieldName in([make],[model])) p
</code>```

Title: Transpose columns in SQL

Body:
I'm trying to take the following data;

|-----------------|-----------------|-----------------|
|        ID       |       Make      |       Model     |
|-----------------|-----------------|-----------------|
|        A1       |       Ford      |       Fiesta    |
|-----------------|-----------------|-----------------|
|        A2       |       Peugeot   |       106       |
|-----------------|-----------------|-----------------|

And transpose it so that it looks like so;

|-----------------|-----------------|-----------------|
|        ID       |     FieldName   |    FieldValue   |
|-----------------|-----------------|-----------------|
|        A1       |       Make      |       Ford      |
|-----------------|-----------------|-----------------|
|        A1       |       Model     |       Fiesta    |
|-----------------|-----------------|-----------------|
|        A2       |       Make      |       Peugeot   |
|-----------------|-----------------|-----------------|
|        A2       |       Model     |       106       |
|-----------------|-----------------|-----------------|

Is this possible within SQL?

Body:
you can use unpivot as below:

Select * from #temp
unpivot (fieldvalue for fieldName in([make],[model])) p


问:
Monthly interval between two date
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

```<code>2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28
</code>```

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

```<code>foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}
</code>```

The code for RecuperoDate is:

```<code>public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)
</code>```

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

答:
I think what you are looking for is the latest day in each month. The DateTime struct provides a static DaysInMonthmethod, that takes the year and the month as parameters.

Going from there, you could iterate from the start date to the end date and get the dates.

This code will print the desired dates to the console, although the format isn't exaclty what you requested:

```<code>    DateTime start = new DateTime(2017,10,05);
    DateTime end = new DateTime(2018,2,20);
    DateTime current = start;

    Console.WriteLine(start.ToShortDateString());
    int startLastDay = DateTime.DaysInMonth(start.Year, start.Month);
    if(startLastDay != start.Day)
        Console.WriteLine(new DateTime(start.Year, start.Month, startLastDay).ToShortDateString());

    while(current < end)
    {
        current = current.AddMonths(1);
        if(current > end)
            Console.WriteLine(end.ToShortDateString());

        int lastDay = DateTime.DaysInMonth(current.Year, current.Month);
        current = new DateTime(current.Year, current.Month, lastDay);
        Console.WriteLine(current.ToShortDateString());
    }
</code>```

edit:

Here the console output on my machine:

```<code>10/5/2017
10/31/2017
11/30/2017
12/31/2017
1/31/2018
2/20/2018
2/28/2018
</code>```

Title: Monthly interval between two date

Body:
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}

The code for RecuperoDate is:

public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

Body:
I think what you are looking for is the latest day in each month. The DateTime struct provides a static DaysInMonthmethod, that takes the year and the month as parameters.

Going from there, you could iterate from the start date to the end date and get the dates.

This code will print the desired dates to the console, although the format isn't exaclty what you requested:

    DateTime start = new DateTime(2017,10,05);
    DateTime end = new DateTime(2018,2,20);
    DateTime current = start;

    Console.WriteLine(start.ToShortDateString());
    int startLastDay = DateTime.DaysInMonth(start.Year, start.Month);
    if(startLastDay != start.Day)
        Console.WriteLine(new DateTime(start.Year, start.Month, startLastDay).ToShortDateString());

    while(current < end)
    {
        current = current.AddMonths(1);
        if(current > end)
            Console.WriteLine(end.ToShortDateString());

        int lastDay = DateTime.DaysInMonth(current.Year, current.Month);
        current = new DateTime(current.Year, current.Month, lastDay);
        Console.WriteLine(current.ToShortDateString());
    }

edit:

Here the console output on my machine:

10/5/2017
10/31/2017
11/30/2017
12/31/2017
1/31/2018
2/20/2018
2/28/2018


问:
How to change JSON array to another format
Array has objects. Example is below;

```<code>  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]
</code>```

I want to change it to

```<code>  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]
</code>```

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;

答:
This is how you read a json.

```<code>var text = '[{"description":"about_text","value1":"test1","value2":"test2"}]';

obj = JSON.parse(text);
var yourvar_description = obj[0].description;
var yourvar_value1 = obj[0].value1 ;
var yourvar_value2 = obj[0].value2 ;
</code>```

so if i wanted it to be
    var text = '[{"description": [{ "value1": "test1", "value1": "test2"}]}];

```<code>var newJson = "[{ description : [{ value1 :"+yourvar_value1+", value2:"+yourvar_value2+" ...etc"
</code>```

I´m sure you get the idea.

As @charlietfl explained, this is not a free code writing service. Objetive is to help you improve your code, but for that you have to post some.

Body:
Array has objects. Example is below;

  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]

I want to change it to

  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;

Body:
This is how you read a json.

var text = '[{"description":"about_text","value1":"test1","value2":"test2"}]';

obj = JSON.parse(text);
var yourvar_description = obj[0].description;
var yourvar_value1 = obj[0].value1 ;
var yourvar_value2 = obj[0].value2 ;

so if i wanted it to be
    var text = '[{"description": [{ "value1": "test1", "value1": "test2"}]}];

var newJson = "[{ description : [{ value1 :"+yourvar_value1+", value2:"+yourvar_value2+" ...etc"

I´m sure you get the idea.

As @charlietfl explained, this is not a free code writing service. Objetive is to help you improve your code, but for that you have to post some.


问:
Accessing data in a loop of text field with ColdFusion
I am fairly new to ColdFusion, and don't quite understand how variable access works. I've created a table that generates a number of text fields named condesc#i#, where i is the current index in a cfloop.

I then have a second loop, that attempts to access the contents of each field that has been created. I have attempted to make access using #condesc#i##, but with no success.

How should I go about getting the information from these fields?

答:
You can reference dynamic variable names by using bracket notation and string concatenation:</p>

```<code><cfloop from="1" to="#count#" index="i">
    #form['condesc' & i]#  <br />
</cfloop>
</code>```

Body:
You can reference dynamic variable names by using bracket notation and string concatenation:

<cfloop from="1" to="#count#" index="i">
    #form['condesc' & i]#  <br />
</cfloop>


问:
A PHP Error was encountered Severity: Notice Message: Undefined variable: result

A PHP Error was encountered Severity: Notice

Message: Undefined variable: result

Filename: user/messages.php

Line Number: 87

Backtrace:

File: E:\xampp\htdocs\ci\application\views\user\messages.php Line: 87
  Function: _error_handler

File: E:\xampp\htdocs\ci\application\controllers\users\Dashboard.php
  Line: 12 Function: view

File: E:\xampp\htdocs\ci\index.php Line: 315 Function: require_once

here is my code
Controller

```<code>      <?php defined('BASEPATH') OR exit('No direct script access allowed');
        class Bills extends CI_Controller{
       function __construct(){
      parent::__construct();
     }

     public function bill(){
     $id = $this->session->userdata('email');
     $this->load->database();
     $this->load->helper(array('form', 'url', 'html'));
     $this->load->model('fuser/Bill');
     $data['result'] = $this->Bill->bills();
     $this->load->view('user/messages',$data);
      }
      }
      ?>

**Model**

      <?php
     class Bill extends CI_Model
     {
      function __construct()
      {
         // Call the Model constructor
         parent::__construct();
      }
      //we will use the select function
      public function bills($id)
      {
         //data is retrive from this query

     $query = $this->db->get('invoices');
       return $query->result();
      }

      }
     ?>

**View**
      <div class="billing_tabs_text_part">
                <?php foreach($result as $row){?>
                  <p><?php echo $row['book_id']; }?></p>
                </div>
</code>```

答:
use <?php echo $row->book_id; }?> in view

because your data is object array.

Body:
A PHP Error was encountered Severity: Notice

Message: Undefined variable: result

Filename: user/messages.php

Line Number: 87

Backtrace:

File: E:\xampp\htdocs\ci\application\views\user\messages.php Line: 87
  Function: _error_handler

File: E:\xampp\htdocs\ci\application\controllers\users\Dashboard.php
  Line: 12 Function: view

File: E:\xampp\htdocs\ci\index.php Line: 315 Function: require_once

here is my code
Controller

      <?php defined('BASEPATH') OR exit('No direct script access allowed');
        class Bills extends CI_Controller{
       function __construct(){
      parent::__construct();
     }

     public function bill(){
     $id = $this->session->userdata('email');
     $this->load->database();
     $this->load->helper(array('form', 'url', 'html'));
     $this->load->model('fuser/Bill');
     $data['result'] = $this->Bill->bills();
     $this->load->view('user/messages',$data);
      }
      }
      ?>

**Model**

      <?php
     class Bill extends CI_Model
     {
      function __construct()
      {
         // Call the Model constructor
         parent::__construct();
      }
      //we will use the select function
      public function bills($id)
      {
         //data is retrive from this query

     $query = $this->db->get('invoices');
       return $query->result();
      }

      }
     ?>

**View**

                <?php foreach($result as $row){?>

<?php echo $row['book_id']; }?>


问:
Parser/split const char* in c++
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";
</code>```

Example 2 of fildedata:

```<code>const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";
</code>```

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

```<code>1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
</code>```

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.

答:
You can use this regex

```<code>const char *regex_str  = "\\d{10};[\\d,-]{10} [\\d,:]{8}"; //verified in http://regexr.com/
</code>```

And then find all regex from your input const char * - get help from finding all regex - for windows.

In mac os std::regex may not work directly. need to add -stdlib=libc++ in the command line

Title: Parser/split const char* in c++

Body:
I tried to find a solution but I did not find anything that solved my question.

I have a C++ program that receive a const char* variable (filedata) and the size (filesize). The contents of this variable is a csv format. Each field is separated by ';'. The content is also dynamic, and may have more or less content, since this variable represents a set of logs. There is also a delimiter \n to represent the line break.

Example 1 of filedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68";

Example 2 of fildedata:

const char* filedata =
    "1496843100;2017-06-07 13:45:00;000002D8;2800;0x23000CCD.VARIABLE67\n"
    "1496843100;2017-06-07 13:45:00;000002D9;2800;0x23000CCD.VARIABLE68\n"
    "1496843100;2017-06-07 13:45:00;000002DA;2800;0x23000CCD.VARIABLE69";

If you see the example 1 only have 2 lines, and the example 2 have 3 lines. I never know how many lines I have. I can have 2, 3, 200, 1000, etc. lines and the filedata variable save all content.

So my objective is to receive this filedata variable (I also have access to filesize) and for each line I need to parse the field 1 and 2 (timestamp and the data in normal format).

Expected output (for the example 2):

1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00
1496843100 2017-06-07 13:45:00

In example 2 I have 3 lines, so I need to iterate all lines and for each line parse the specific fields, very similar to the output.
After this i pick each parser fields and save to object list (This part is already implemented. I'm just having trouble parsing filedata.

Body:
You can use this regex

const char *regex_str  = "\\d{10};[\\d,-]{10} [\\d,:]{8}"; //verified in http://regexr.com/

And then find all regex from your input const char * - get help from finding all regex - for windows.

In mac os std::regex may not work directly. need to add -stdlib=libc++ in the command line


问:
Django-admin linked column issue
Following this answer I wanted to add a linked column to my admin page,

```<code>class AnswerAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote')

    def link_to_question(self, obj):
        link = urlresolvers.reverse("admin:QnA_question_change",
                                    args=[obj.question.id])  # model name has to be lowercase
        text = obj.question.__str__
        str = format_html("{}", text)

        return mark_safe(u'<a href="%s">%s</a>' % (link, str))

    class Meta:
        model = Answer
</code>```

but what I get in return is this:

```<code><bound method Entry.__str__ of <Question: This is a question about technology?>>
</code>```

I only want the "This is a question ..." part shown in my admin.

Sidenote:
when I use something like obj.question.text instead of a function it works smoothly.

答:
It isn't clear why you are using format_html then passing the result to mark_safe. You should be able to do it in one step with format_html. This has the advantage of escaping text, in case a use has inserted malicious content.

```<code>    link = urlresolvers.reverse(...)
    text = obj.question
    link_str = format_html('<a href="{}">{}</a>', link, text)
</code>```

To call the __str__ method you need to call it with obj.question.__str__(). However, it's more pythonic to call str(obj.question) rather than obj.question.__str__(). In this case, I don't think you need to use str() at all, since you are using format_html.

Title: Django-admin linked column issue

Body:
Following this answer I wanted to add a linked column to my admin page,

class AnswerAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote')

    def link_to_question(self, obj):
        link = urlresolvers.reverse("admin:QnA_question_change",
                                    args=[obj.question.id])  # model name has to be lowercase
        text = obj.question.__str__
        str = format_html("{}", text)

        return mark_safe(u'%s' % (link, str))

    class Meta:
        model = Answer

but what I get in return is this:

<bound method Entry.__str__ of <Question: This is a question about technology?>>

I only want the "This is a question ..." part shown in my admin.

Sidenote:
when I use something like obj.question.text instead of a function it works smoothly.

Body:
It isn't clear why you are using format_html then passing the result to mark_safe. You should be able to do it in one step with format_html. This has the advantage of escaping text, in case a use has inserted malicious content.

    link = urlresolvers.reverse(...)
    text = obj.question
    link_str = format_html('<a href="{}">{}</a>', link, text)

To call the __str__ method you need to call it with obj.question.__str__(). However, it's more pythonic to call str(obj.question) rather than obj.question.__str__(). In this case, I don't think you need to use str() at all, since you are using format_html.


问:
UFT - Select File from TreeView
I have recorded a script to Click on an XML file(highlight, right-click and open) from a popup treeview, the popup contains a number of files(varying amounts/types and they can appear in any order), the one I will always want to select always begins with 'AB', the numerics of the filename will change per test however:

```<code>SwfWindow("APPMAIN").SwfWindow("2000HOME").SwfTreeView("MainTreeList").SelectCell "AB99872","Object Name"

SwfWindow("APP-MAIN").SwfToolbar("SwfToolbar").Select "Open"
</code>```

After Recording, I run the script, but I get the following error:

SelectCell :SelectCell :Cannot identify the specified item = AB99872 of the TreeView.

So my question is 2 part:

Why can it not select the file AB99872 after the initial record using SelectCell?

Considering that the filename will change per test(ie... AB*), what is the best way to automate this to be robust enough to select any Filename beginning with 'AB'. I did try UI Automation/Object Recognition and I used a regular expression like ^AB.* but UFT(v12.54) continually crashed with this approach.

答: You can use the tree's GetContent method and then use regular expressions to find the name of the node to select (then use that value in SelectCell.

Title: UFT - Select File from TreeView

Body:
I have recorded a script to Click on an XML file(highlight, right-click and open) from a popup treeview, the popup contains a number of files(varying amounts/types and they can appear in any order), the one I will always want to select always begins with 'AB', the numerics of the filename will change per test however:

SwfWindow("APPMAIN").SwfWindow("2000HOME").SwfTreeView("MainTreeList").SelectCell "AB99872","Object Name"

SwfWindow("APP-MAIN").SwfToolbar("SwfToolbar").Select "Open"

After Recording, I run the script, but I get the following error:

SelectCell :SelectCell :Cannot identify the specified item = AB99872 of the TreeView.

So my question is 2 part:

Why can it not select the file AB99872 after the initial record using SelectCell?

Considering that the filename will change per test(ie... AB*), what is the best way to automate this to be robust enough to select any Filename beginning with 'AB'. I did try UI Automation/Object Recognition and I used a regular expression like ^AB.* but UFT(v12.54) continually crashed with this approach.


问:
LocationProvider costAllowed
When you choose a locationProvider by Criteria you can choose to allowCost or not.
But of which cost we are talking about?
If I choose to don't allow cost I allow the network provider?
Which providers can have a cost?</p>

答: The API Documentation here just says 'incur monetary value'. From that I can only assume data traffic over a celluar connection, i.e Using Assisted GPS or CellID lookup when a WiFi connection isn't available.</p>

Title: LocationProvider costAllowed


问:
HorizontalScrollView does not work in SlidingUpPanel
The layout is like the following.

```<code><com.sothree.slidinguppanel.SlidingUpPanelLayout
        android:gravity="bottom"
        sothree:umanoScrollableView="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </ScrollView>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>
</code>```

The version of SlidingUpPanelLayout library is 3.3.1.
ScrollView can slide normally, but the HorizontalScrollView has a sliding conflict

答:
Delete parent ScrollView and use only HorizontalScrollView.

```<code><android.support.design.widget.TabLayout.SlidingTabStrip
        android:gravity="bottom"
        sothree:umanoScrollableView="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</android.support.design.widget.TabLayout.SlidingTabStrip>
</code>```

And put any parent view inside HorizontalScrollView.

Body:
The layout is like the following.

<com.sothree.slidinguppanel.SlidingUpPanelLayout
        android:gravity="bottom"
        sothree:umanoScrollableView="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </ScrollView>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>

The version of SlidingUpPanelLayout library is 3.3.1.
ScrollView can slide normally, but the HorizontalScrollView has a sliding conflict

Body:
Delete parent ScrollView and use only HorizontalScrollView.

<android.support.design.widget.TabLayout.SlidingTabStrip
        android:gravity="bottom"
        sothree:umanoScrollableView="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</android.support.design.widget.TabLayout.SlidingTabStrip>

And put any parent view inside HorizontalScrollView.


问:
Android Button with Left and Right Margin
I have the following layout

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><Button
    android:id="@+id/sign_in"
    style="@style/ButtonText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_green"
    android:text="@string/signin_via_email"
    android:textSize="15sp"
    android:typeface="sans" />
</code>```

Now the button i dont really want to fit the whole width rather i want a margin of 10dp from the left and 10dp from the right. I have set the padding and layout_marginLeft and right attributes but they dont work. Any help ?

Kind Regards

答:
I added

```<code>android:padding="10dp"
</code>```

to

```<code>input.xml
</code>```

..and it worked!

(I using SoftKeyboard source code and also have the same problem)

Body:
I have the following layout

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:id="@+id/sign_in"
    style="@style/ButtonText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_green"
    android:text="@string/signin_via_email"
    android:textSize="15sp"
    android:typeface="sans" />

Now the button i dont really want to fit the whole width rather i want a margin of 10dp from the left and 10dp from the right. I have set the padding and layout_marginLeft and right attributes but they dont work. Any help ?

Kind Regards

Body:
I added

android:padding="10dp"

to

input.xml

..and it worked!

(I using SoftKeyboard source code and also have the same problem)


问:
More efficient way to create dataframe of top n values - python
I have a dataframe of categories that I need to clean up by limiting the values to the top n categories. Any value that isn't in the top n categories, should be binned under 0 (or "other").

I tried the code below, which loops through each row of a column, then through each column in a dataframe to check if the value in that position is found in that column's top n value_counts. If yes, then it keeps the value, if not then replaces with 0.

This implementation technically works, but when the number of rows is large, it takes too long to run. What is the quicker way of accomplishing this in pandas/numpy?

```<code>z = pd.DataFrame(np.random.randint(1,4,size=(100000, 4)))
x=pd.DataFrame()
n=10
for j in z:
    for i in z[j].index:
        if z.at[i,j] in z[j].value_counts().head(n).index.tolist():
            x.at[i,j] = z.at[i,j]
        else:
            x.at[i,j]= 0
print(x)
</code>```

答:
I think you can use apply for loop columns with custom function with value_counts for top values and where with isin for boolean mask for replacing:

```<code>def f(x):
    y = x.value_counts().head(n).index
    return x.where(x.isin(y), 0)

print (z.apply(f))
</code>```

What is same as:

```<code>print (z.apply(lambda x: x.where(x.isin(x.value_counts().head(n).index), 0)))
</code>```

Sample:

```<code>#N =100000
N = 10
np.random.seed(123)
z = pd.DataFrame(np.random.randint(1,4,size=(N, 4)))
print (z)
   0  1  2  3
0  3  2  3  3
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  1  2  3
7  1  3  1  1
8  2  1  2  1
9  1  1  3  2
</code>```

```<code>x=pd.DataFrame()
n=2
for j in z:
    for i in z[j].index:
        if z.at[i,j] in z[j].value_counts().head(n).index.tolist():
            x.at[i,j] = z.at[i,j]
        else:
            x.at[i,j]= 0
print(x)
     0    1    2    3
0  3.0  2.0  3.0  0.0
1  1.0  3.0  3.0  2.0
2  3.0  2.0  3.0  2.0
3  1.0  2.0  3.0  2.0
4  1.0  3.0  1.0  2.0
5  3.0  2.0  1.0  1.0
6  1.0  0.0  0.0  0.0
7  1.0  3.0  1.0  1.0
8  0.0  0.0  0.0  1.0
9  1.0  0.0  3.0  2.0
</code>```

```<code>print (z.apply(lambda x: x.where(x.isin(x.value_counts().head(n).index), 0)))
   0  1  2  3
0  3  2  3  0
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  0  0  0
7  1  3  1  1
8  0  0  0  1
9  1  0  3  2
</code>```

Similar solution with numpy.where:

```<code>print (z.apply(lambda x: np.where(x.isin(x.value_counts().head(n).index), x, 0)))
   0  1  2  3
0  3  2  3  0
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  0  0  0
7  1  3  1  1
8  0  0  0  1
9  1  0  3  2
</code>```

Body:
I have a dataframe of categories that I need to clean up by limiting the values to the top n categories. Any value that isn't in the top n categories, should be binned under 0 (or "other").

I tried the code below, which loops through each row of a column, then through each column in a dataframe to check if the value in that position is found in that column's top n value_counts. If yes, then it keeps the value, if not then replaces with 0.

This implementation technically works, but when the number of rows is large, it takes too long to run. What is the quicker way of accomplishing this in pandas/numpy?

z = pd.DataFrame(np.random.randint(1,4,size=(100000, 4)))
x=pd.DataFrame()
n=10
for j in z:
    for i in z[j].index:
        if z.at[i,j] in z[j].value_counts().head(n).index.tolist():
            x.at[i,j] = z.at[i,j]
        else:
            x.at[i,j]= 0
print(x)

Body:
I think you can use apply for loop columns with custom function with value_counts for top values and where with isin for boolean mask for replacing:

def f(x):
    y = x.value_counts().head(n).index
    return x.where(x.isin(y), 0)

print (z.apply(f))

What is same as:

print (z.apply(lambda x: x.where(x.isin(x.value_counts().head(n).index), 0)))

Sample:

#N =100000
N = 10
np.random.seed(123)
z = pd.DataFrame(np.random.randint(1,4,size=(N, 4)))
print (z)
   0  1  2  3
0  3  2  3  3
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  1  2  3
7  1  3  1  1
8  2  1  2  1
9  1  1  3  2

x=pd.DataFrame()
n=2
for j in z:
    for i in z[j].index:
        if z.at[i,j] in z[j].value_counts().head(n).index.tolist():
            x.at[i,j] = z.at[i,j]
        else:
            x.at[i,j]= 0
print(x)
     0    1    2    3
0  3.0  2.0  3.0  0.0
1  1.0  3.0  3.0  2.0
2  3.0  2.0  3.0  2.0
3  1.0  2.0  3.0  2.0
4  1.0  3.0  1.0  2.0
5  3.0  2.0  1.0  1.0
6  1.0  0.0  0.0  0.0
7  1.0  3.0  1.0  1.0
8  0.0  0.0  0.0  1.0
9  1.0  0.0  3.0  2.0

print (z.apply(lambda x: x.where(x.isin(x.value_counts().head(n).index), 0)))
   0  1  2  3
0  3  2  3  0
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  0  0  0
7  1  3  1  1
8  0  0  0  1
9  1  0  3  2

Similar solution with numpy.where:

print (z.apply(lambda x: np.where(x.isin(x.value_counts().head(n).index), x, 0)))
   0  1  2  3
0  3  2  3  0
1  1  3  3  2
2  3  2  3  2
3  1  2  3  2
4  1  3  1  2
5  3  2  1  1
6  1  0  0  0
7  1  3  1  1
8  0  0  0  1
9  1  0  3  2