问:
tableview appear to be nil in ViewController when it's root by a navigation controller [SWIFT 3]
I'm having an issue with my current project.
At the beginning my main focus was to create a overlay button in a TableViewController but i saw that it was more simple to use a ViewController and set on it a tableView :

```<code>class MemoList : UIViewController, UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var myTableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.delegate = self
        #datasource is linked manually in the StoryBoard
        ...
    }
}
</code>```

When this View Controller is set as the initial controller, everything work fine but in my case, when the projet is rooted by a navigation controller, the tableview appears to be nil in the context of the 'Memolist' (when pushing on it).

Do you have any idea about this issue ? And how can I solve it ?

Thanks,

答:
For me the problem was that I used

```<code>present(myViewController, animated: true, completion: nil)
</code>```

After I tried to use segue and

```<code>performSegue(withIdentifier: "myIdentifier", sender: self)
</code>```

it worked properly and tableView was no longer nil.

Why did I have this problem:
When you use present(), you initialise the View Controller from code and it doesn't watch on your Storyboard. When you use segues, it uses the Storyboard and of course see all you did in your Interface Builder

You also can:

```<code>UIStoryboard(name: "StoryboardName", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerId")
</code>```

This creates view controller from Storyboard, so that tableView is initialized now

Body:
I'm having an issue with my current project.
At the beginning my main focus was to create a overlay button in a TableViewController but i saw that it was more simple to use a ViewController and set on it a tableView :

class MemoList : UIViewController, UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var myTableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.delegate = self
        #datasource is linked manually in the StoryBoard
        ...
    }
}

When this View Controller is set as the initial controller, everything work fine but in my case, when the projet is rooted by a navigation controller, the tableview appears to be nil in the context of the 'Memolist' (when pushing on it).

Do you have any idea about this issue ? And how can I solve it ?

Thanks,

Body:
For me the problem was that I used

present(myViewController, animated: true, completion: nil)

After I tried to use segue and

performSegue(withIdentifier: "myIdentifier", sender: self)

it worked properly and tableView was no longer nil.

Why did I have this problem:
When you use present(), you initialise the View Controller from code and it doesn't watch on your Storyboard. When you use segues, it uses the Storyboard and of course see all you did in your Interface Builder

You also can:

UIStoryboard(name: "StoryboardName", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerId")

This creates view controller from Storyboard, so that tableView is initialized now


来源: stackexchange

问:
How to set CONSISTENCY level in cassandra permanently?
I want to set consistency level to QUORUM, I am able to do this using cqlsh with using 'CONSISTENCY QUORUM'. but the problem is that that was set to only for that particular time. I don't see any property related to CONSISTENCY level in cassandra.yaml.

Is there any way to set it permanently, any configuration file?

答:
The consistency level is set per request so its up to the client (ie cqlsh or your driver in whatever language) to set. It cannot be done from Cassandra's side.

cqlsh does allow you to setup some options via its cqlshrc file but setting the default consistency level is not one of them. The default is actually hard coded to CL.ONE. If you really want you can just change that line in cqlsh.py and it will be applied globally like Arun recommended above.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Kendo Angular 2 dynamic tooltip
I have a page using Kendo/Angular2.  The page has a lot of link/buttons.  When the user clicks on a link, a tooltip needs to appear next to the clicked link and any previous instances close.  The tooltip needs to use a template and display dynamic content based on the link that was clicked.   It would be nice to be able reuse a single tooltip control on the page.

Is it possible to get a demo of something like this?

答:
I am using a single kendo-popup control as a tooltip.  The offset property allows you to position the popup.  The offset is based on pageX and pageY values of the click event that opens the popup

Here are the relevant snippets from what I have:

component.html

<kendo-popup [popupClass]="" *ngIf="tooltipVisible" [offset]="tooltipOffset">

        {{tooltipValue}}

</kendo-popup>

<button class="btn-link"
    (mouseover)="showTooltip($event,theData)"
    (mouseout)="hideTooltip()"
                        style="cursor: pointer; text-decoration: underline;">
                    {{theData}}
</button>```
</div>
</div>
</p>

<p>component.ts</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>    tooltipOffset = { left: 0, top: 0 };
    tooltipVisible = false;
    tooltipValue = "";

    showTooltip(event: any, data: string) {
        this.tooltipOffset = { left: event.pageX + 4, top: event.pageY + 4 };
        this.tooltipVisible = true;
        this.tooltipValue = data;
    }

    hideTooltip() {
        this.tooltipVisible = false;
    }</code>```

Title: Kendo Angular 2 dynamic tooltip

Body:
I am using a single kendo-popup control as a tooltip.  The offset property allows you to position the popup.  The offset is based on pageX and pageY values of the click event that opens the popup

Here are the relevant snippets from what I have:

component.html

<kendo-popup [popupClass]="" *ngIf="tooltipVisible" [offset]="tooltipOffset">
    <div style="clear: both; padding: 2px;">
        {{tooltipValue}}
    </div>
</kendo-popup>

<button class="btn-link"
    (mouseover)="showTooltip($event,theData)"
    (mouseout)="hideTooltip()"
                        style="cursor: pointer; text-decoration: underline;">
                    {{theData}}
</button>

component.ts

    tooltipOffset = { left: 0, top: 0 };
    tooltipVisible = false;
    tooltipValue = "";

    showTooltip(event: any, data: string) {
        this.tooltipOffset = { left: event.pageX + 4, top: event.pageY + 4 };
        this.tooltipVisible = true;
        this.tooltipValue = data;
    }

    hideTooltip() {
        this.tooltipVisible = false;
    }


问:
Make a activity screen which shows up only once
I want to make a activity in an app which shows up only when the user installs the app and never again. How can I do that?</p>

答:
My issue solved by trying out this</p>

```<code>boolean isFirstRun = getSharedPreferences("Preference", MODE_PRIVATE).getBoolean("isfirstrun",true);

    if(isFirstRun){
        getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isfirstrun",false).commit();
        Intent IntentFirstRunAct = new Intent(MainActivity.this,FirstRunActivity.class);
        startActivity(IntentFirstRunAct);
    }
</code>```

Body:
My issue solved by trying out this

boolean isFirstRun = getSharedPreferences("Preference", MODE_PRIVATE).getBoolean("isfirstrun",true);

    if(isFirstRun){
        getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isfirstrun",false).commit();
        Intent IntentFirstRunAct = new Intent(MainActivity.this,FirstRunActivity.class);
        startActivity(IntentFirstRunAct);
    }


问:
How to get the pixel coordinates from a SVG path String
I want to display geometric objects on a map using go.js in combination with leaflet.js
It is important for me that the geometric object sticks to their geo-position. I simply translate the pixel coordinates to lat/lng geo-coordinates.

However, for some geometric objects it is not that easy for me to get all the necessary geo-coordinates.
For a polygon I get an SVG-Path String like :

```<code>"F M54 77 L39 128 L0 146 L18 178 L45 215 L87 220 L79 321 L79 400 L153 371 L246 340 L296 325 L332 255 L324 207 L355 164 L338 138 L368 105 L380 23 L336 0 L282 35 L222 10 L147 10 L95 38 L60 44z"
</code>```

as well as the pixel coordinates of the middle Point.

So I would need the pixel coordinate of every corner point.
Do you have any idea or suggestion how I could translate the SVG path to its pixel coordinates?

Hope you guys can help me.

Best regards!

enter image description here

答:
Do you have a GoJS Part (or Node) that holds a Shape whose Shape.geometryString is what you posted?

If so, I suggest that you look at the Shape.geometry and look at its Geometry.figures' PathFigures and their PathSegments.  For each of those points you can convert to GoJS document coordinates by adding the Part.position plus half the Shape.strokeWidth.  Then you can convert document coordinates to LatLng by calling Leaflet map's containerPointToLatLng method.

Body:
I want to display geometric objects on a map using go.js in combination with leaflet.js
It is important for me that the geometric object sticks to their geo-position. I simply translate the pixel coordinates to lat/lng geo-coordinates.

However, for some geometric objects it is not that easy for me to get all the necessary geo-coordinates.
For a polygon I get an SVG-Path String like :

"F M54 77 L39 128 L0 146 L18 178 L45 215 L87 220 L79 321 L79 400 L153 371 L246 340 L296 325 L332 255 L324 207 L355 164 L338 138 L368 105 L380 23 L336 0 L282 35 L222 10 L147 10 L95 38 L60 44z"

as well as the pixel coordinates of the middle Point.

So I would need the pixel coordinate of every corner point.
Do you have any idea or suggestion how I could translate the SVG path to its pixel coordinates?

Hope you guys can help me.

Best regards!

enter image description here


问:
Take the sum of a list as variable and edit it at runtime
I'm trying to calculate the end value of a specific variable that depends whether a checkbox is checked. This is however dynamically done.

What I'm trying to achieve:

The example above works fine but it starts going wrong when I start to uncheck the check boxes. It subtracts by the double amount of the time and I have no idea why:

My Code (TimeSpent is the variable that I want to have at the end):

Class

```<code>public class Activity
{
    public int ID { get; set; }
    public int IncidentID { get; set; }
    public string Description { get; set; }
    public int TimeSpent { get; set; }
    public static int StartX { get; set; } = 10;
    public static int StartY { get; set; } = 10;

    private TextBox textBox = null;

    private CheckBox checkBox = null;

    public Activity(int iD, int incidentID, string description, int timeSpent)
    {
        this.ID = iD;
        this.IncidentID = incidentID;
        this.Description = description;
        this.TimeSpent = timeSpent;
    }

    public Activity()
    { }

    public bool isChecked() {
        return checkBox.Checked;
    }

    public void setTimeSpent(int timeSpent) {
        this.TimeSpent = timeSpent;
        textBox.Text = timeSpent.ToString();
    }

    public int getTimeSpent()
    {
        return Int32.Parse(textBox.Text);
    }

    public void DrawToForm(Panel p)
    {
        var label = new Label();
        textBox = new TextBox();
        checkBox = new CheckBox();
        checkBox.Checked = true;
        textBox.Size = new System.Drawing.Size(40, 20);
        label.Text = Description.ToString();
        label.AutoSize = true;
        textBox.Text = TimeSpent.ToString();
        label.Left = StartX;
        label.Top = StartY;
        StartX += 430;// Move position to right
        textBox.Left = StartX;
        textBox.Top = StartY;
        StartX += 160;// Move position to right
        checkBox.Left = StartX;
        checkBox.Top = StartY;
        StartX = 10;// Reset to start
        StartY += 50;// Move position to down
        p.Controls.Add(label);
        p.Controls.Add(textBox);
        p.Controls.Add(checkBox);
    }
}
</code>```

GUI:

```<code>private void Btn_Validate_Click(object sender, EventArgs e)
{
    tb_TotalTime.Text = calculateTotalTime().ToString();
}

public int calculateTotalTime()
{
    int total = 0;
    foreach (Activity a in activities)
    {
        if(a.isChecked())
        {
            total += a.getTimeSpent();
        }else
        {
            total -= a.getTimeSpent();
        }
    }
    return total;
}
</code>```

Why is subtracting not done correctly?

答:
You subtract when the checkbox is not checked:

```<code>if(a.isChecked())
{
    total += a.getTimeSpent();
}
else
{
    total -= a.getTimeSpent();// << THIS
}
</code>```

So with the setup of your 2nd image (top 2 unchecked bottom one checked) you do this:

```<code>0 - 5 - 5 + 5 = -5
</code>```

The 0 comes from the default value of Total (int)

To fix this you could just remove the else clause as you don't need to subtract billable time ever.

Body:
I'm trying to calculate the end value of a specific variable that depends whether a checkbox is checked. This is however dynamically done.

What I'm trying to achieve:

The example above works fine but it starts going wrong when I start to uncheck the check boxes. It subtracts by the double amount of the time and I have no idea why:

My Code (TimeSpent is the variable that I want to have at the end):

Class

public class Activity
{
    public int ID { get; set; }
    public int IncidentID { get; set; }
    public string Description { get; set; }
    public int TimeSpent { get; set; }
    public static int StartX { get; set; } = 10;
    public static int StartY { get; set; } = 10;

    private TextBox textBox = null;

    private CheckBox checkBox = null;

    public Activity(int iD, int incidentID, string description, int timeSpent)
    {
        this.ID = iD;
        this.IncidentID = incidentID;
        this.Description = description;
        this.TimeSpent = timeSpent;
    }

    public Activity()
    { }

    public bool isChecked() {
        return checkBox.Checked;
    }

    public void setTimeSpent(int timeSpent) {
        this.TimeSpent = timeSpent;
        textBox.Text = timeSpent.ToString();
    }

    public int getTimeSpent()
    {
        return Int32.Parse(textBox.Text);
    }

    public void DrawToForm(Panel p)
    {
        var label = new Label();
        textBox = new TextBox();
        checkBox = new CheckBox();
        checkBox.Checked = true;
        textBox.Size = new System.Drawing.Size(40, 20);
        label.Text = Description.ToString();
        label.AutoSize = true;
        textBox.Text = TimeSpent.ToString();
        label.Left = StartX;
        label.Top = StartY;
        StartX += 430;// Move position to right
        textBox.Left = StartX;
        textBox.Top = StartY;
        StartX += 160;// Move position to right
        checkBox.Left = StartX;
        checkBox.Top = StartY;
        StartX = 10;// Reset to start
        StartY += 50;// Move position to down
        p.Controls.Add(label);
        p.Controls.Add(textBox);
        p.Controls.Add(checkBox);
    }
}

GUI:

private void Btn_Validate_Click(object sender, EventArgs e)
{
    tb_TotalTime.Text = calculateTotalTime().ToString();
}

public int calculateTotalTime()
{
    int total = 0;
    foreach (Activity a in activities)
    {
        if(a.isChecked())
        {
            total += a.getTimeSpent();
        }else
        {
            total -= a.getTimeSpent();
        }
    }
    return total;
}

Why is subtracting not done correctly?

Body:
You subtract when the checkbox is not checked:

if(a.isChecked())
{
    total += a.getTimeSpent();
}
else
{
    total -= a.getTimeSpent();// << THIS
}

So with the setup of your 2nd image (top 2 unchecked bottom one checked) you do this:

0 - 5 - 5 + 5 = -5

The 0 comes from the default value of Total (int)

To fix this you could just remove the else clause as you don't need to subtract billable time ever.


问:
c++ create text fits edit box
Well..  I know that title is not that clear, I couldn't think of better one.

I wanna know how to do this...

when you have edit box and it only can show 10 characters.

Something like this

ssssssssss

let just say i have more than 10 characters.  Some of them will go in the back.

Like we have this string "123456789010" it will show just these ones "3456789010".

My problem is that some characters are small and don't take that much space and some do.

So i can't find a way to break the string and get some characters in the back.

any idea?

答:
you only want to see the far left or far right?

here is your string "0123456789"

you can only display 5 values due to pixel size of box....

do you want it to be "...56789" more like "56789"

or "01234..." more like "01234"?

ContentLicense: CC BY-SA 2.5

Title: c++ create text fits edit box


问:
Espresso tests with Kotlin
Every time I try to test my Android app and I rewrite my tests in Kotlin I always get:

Class not found: "my.package.modules.container.ContainerViewInstrumentedTest"

  Empty test suite.

I am trying everything to make Espresso see my tests... but no luck. Does anyone know what can be wrong?

答:
The problem was not my tests... There was something wrong with Android Studio - Canary1... It is fixed now in the Canary 4

When it doesn't work in AS, running in the command line normally work.

```<code>./gradlew connectedCheck
</code>```

Title: Espresso tests with Kotlin

Body:
The problem was not my tests... There was something wrong with Android Studio - Canary1... It is fixed now in the Canary 4

When it doesn't work in AS, running in the command line normally work.

./gradlew connectedCheck


答:
You should remove subtracting at all.
So change it to :

```<code>if(a.isChecked())
{
     total += a.getTimeSpent();
}
</code>```

You have total=0, you have not added all values before calculating. So you don't need subtracting.

Title: Take the sum of a list as variable and edit it at runtime

Body:
You should remove subtracting at all.
So change it to :

if(a.isChecked())
{
     total += a.getTimeSpent();
}

You have total=0, you have not added all values before calculating. So you don't need subtracting.


问:
Auto Download PDF thru URLDownloadToFile
How do I pull the default name of a PDF from a website instead of blah.pdf in following code?</p>

```<code>Option Explicit

Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long _
) As Long

Sub z()

    Dim strSource As String
    Dim strDest As String
    strSource = "http://www.cran.r-project.org/doc/manuals/R-intro.pdf"
    strDest = "c:\temp\blah.pdf"
    URLDownloadToFile 0, strSource, strDest, 0, 0

End Sub
</code>```

答:
Using your original method of downloading the file is fine, but how are you actually determining the path and filename?  Do you have a list?  Do you need to get it from the website?  With regards to retrieving the instrument number, first set references (VBE > Tools > References) to Microsoft XML, vx.0 and Microsoft HTML Object Library, then change the specified URL accordingly, and then try...</p>

```<code>Option Explicit

Sub GetInstrumentNumber()

    'Set a reference (VBE > Tools > References) to the following libraries:
    '   1) Microsoft XML, v6.0 (or whatever version you have)
    '   2) Microsoft HTML Object Library

    Dim XMLReq As New MSXML2.XMLHTTP60
    Dim HTMLDoc As New MSHTML.HTMLDocument
    Dim sURL As String
    Dim sInstrument As String

    sURL = "http://www.cran.r-project.org/..." 'change the URL adddress accordingly

    With XMLReq
        .Open "GET", sURL, False
        .send
        Do While .readyState <> 4
            DoEvents
        Loop
    End With

    If XMLReq.Status <> 200 Then
        MsgBox "Error " & XMLReq.Status & ":  " & XMLReq.statusText
        Exit Sub
    End If

    HTMLDoc.body.innerHTML = XMLReq.responseText

    sInstrument = HTMLDoc.getElementById("6063270").getElementsByTagName("tr")(0).Cells(0).innerText
    sInstrument = Trim(Split(sInstrument, ":")(1))

    MsgBox "Instrument number:  " & sInstrument, vbInformation

    Set XMLReq = Nothing
    Set HTMLDoc = Nothing

End Sub
</code>```

Body:
How do I pull the default name of a PDF from a website instead of blah.pdf in following code?

Option Explicit

Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long _
) As Long

Sub z()

    Dim strSource As String
    Dim strDest As String
    strSource = "http://www.cran.r-project.org/doc/manuals/R-intro.pdf"
    strDest = "c:\temp\blah.pdf"
    URLDownloadToFile 0, strSource, strDest, 0, 0

End Sub

Body:
Using your original method of downloading the file is fine, but how are you actually determining the path and filename?  Do you have a list?  Do you need to get it from the website?  With regards to retrieving the instrument number, first set references (VBE > Tools > References) to Microsoft XML, vx.0 and Microsoft HTML Object Library, then change the specified URL accordingly, and then try...

Option Explicit

Sub GetInstrumentNumber()

    'Set a reference (VBE > Tools > References) to the following libraries:
    '   1) Microsoft XML, v6.0 (or whatever version you have)
    '   2) Microsoft HTML Object Library

    Dim XMLReq As New MSXML2.XMLHTTP60
    Dim HTMLDoc As New MSHTML.HTMLDocument
    Dim sURL As String
    Dim sInstrument As String

    sURL = "http://www.cran.r-project.org/..." 'change the URL adddress accordingly

    With XMLReq
        .Open "GET", sURL, False
        .send
        Do While .readyState <> 4
            DoEvents
        Loop
    End With

    If XMLReq.Status <> 200 Then
        MsgBox "Error " & XMLReq.Status & ":  " & XMLReq.statusText
        Exit Sub
    End If

    HTMLDoc.body.innerHTML = XMLReq.responseText

    sInstrument = HTMLDoc.getElementById("6063270").getElementsByTagName("tr")(0).Cells(0).innerText
    sInstrument = Trim(Split(sInstrument, ":")(1))

    MsgBox "Instrument number:  " & sInstrument, vbInformation

    Set XMLReq = Nothing
    Set HTMLDoc = Nothing

End Sub


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
Try this:

```<code>public static int MyCustomOrder (Status status)
{
    switch (status)
    {
        case Status.Draft     : return 1;
        case Status.Pending   : return 2;
        case Status.Validated : return 4;
        case Status.Refused   : return 3;

        default: return -1;
    }
}
</code>```

And now:

```<code>var result = projects.OrderBy (x => MyCustomOrder (x.StatusId));
</code>```

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
Try this:

public static int MyCustomOrder (Status status)
{
    switch (status)
    {
        case Status.Draft     : return 1;
        case Status.Pending   : return 2;
        case Status.Validated : return 4;
        case Status.Refused   : return 3;

        default: return -1;
    }
}

And now:

var result = projects.OrderBy (x => MyCustomOrder (x.StatusId));


问:
Any example or scenario where Angular router Params Observable is usable?
I was learning on Angular Router Params Observable in Pluralsight course(Routing).

```<code>this.route.params.subscribe(params => {let id = params['id']})});
</code>```

I understand within component, when there is change in params, we use above code.

I would like to know an example, or scenario this plays role in real time application?

答:
Suppose you are building a social networking site and on one page you list all your friends and the user can open the profile page of the friend by clicking on his name.

Now to build your listing page you would display all your friends in a *ngFor loop like below :

```<code><div *ngFor="let friend of friends">
    <a routerLink="/detailPage">
      <img [src]="friend.profilePic" />
      <span>{{friend.name}}</span>
    </a>
</div>
</code>```

When we navigate to the detailPage how would you know to show the details of which friend ?

There are a few ways of doing this:

Store the userId of friend in a service

Store it in localStorage

Pass it as route param in the URl

Let's take an example, suppose you click on the name of your friend Batman

First Approach:

You can easily do this by creating a shared service between two component, the ListComponent which displays the list of friends and DetailComponent which shows a particular friend's details.

The problem with this approach is when you refresh your page you will not have the userId as the javascript scope is destroyed by the browser and you cannot share it any other friend who might wanna see the profile of your friend. Let's say you have a friend called catwoman who asks you to give link to Batman's account, oops you can't because you don't know it !!

Second Approach:

Here you will know what is the userId on page refresh but the problem of not sharing someone's link still exists which defeats the purpose of a social network.

Third Approach:

This is the best approach in this scenario as you will have the userId on refresh and you can send the link of Batman's profile to catwoman :)

So you change routerLink="/detailPage" to routerLink="/detailPage/{{friend.userId}}".

Body:
I was learning on Angular Router Params Observable in Pluralsight course(Routing).

this.route.params.subscribe(params => {let id = params['id']})});

I understand within component, when there is change in params, we use above code.

I would like to know an example, or scenario this plays role in real time application?

Body:
Suppose you are building a social networking site and on one page you list all your friends and the user can open the profile page of the friend by clicking on his name.

Now to build your listing page you would display all your friends in a *ngFor loop like below :

<div *ngFor="let friend of friends">
    <a routerLink="/detailPage">
      <img [src]="friend.profilePic" />
      <span>{{friend.name}}</span>
    </a>
</div>

When we navigate to the detailPage how would you know to show the details of which friend ?

There are a few ways of doing this:

Store the userId of friend in a service

Store it in localStorage

Pass it as route param in the URl

Let's take an example, suppose you click on the name of your friend Batman

First Approach:

You can easily do this by creating a shared service between two component, the ListComponent which displays the list of friends and DetailComponent which shows a particular friend's details.

The problem with this approach is when you refresh your page you will not have the userId as the javascript scope is destroyed by the browser and you cannot share it any other friend who might wanna see the profile of your friend. Let's say you have a friend called catwoman who asks you to give link to Batman's account, oops you can't because you don't know it !!

Second Approach:

Here you will know what is the userId on page refresh but the problem of not sharing someone's link still exists which defeats the purpose of a social network.

Third Approach:

This is the best approach in this scenario as you will have the userId on refresh and you can send the link of Batman's profile to catwoman :)

So you change routerLink="/detailPage" to routerLink="/detailPage/{{friend.userId}}".


问:
How to match Underscore in String - MYSQL
if column value is 2_apples or final_chapter how do i match a value that contains an underscore "_" ?

I've tried with:

```<code>SELECT DISTINCT brand FROM `items` WHERE brand like '%\\_'
SELECT DISTINCT brand FROM `items` WHERE brand like '_'
SELECT DISTINCT brand FROM `items` WHERE brand like '%_%'
SELECT DISTINCT brand FROM `items` WHERE brand like LIKE '\_'
</code>```

It either shows all results or none. Any suggestions?

答:
Try

```<code>WHERE brand LIKE '%\_%'
</code>```

The underscore is a wildcard for a single character whereas the % is a wildcard for multiple (or none) characters. Put a backslash in front to escape them.

If you don't like escaping things, because it's ugly or scary, then an alternative would be to use the REGEXP operator with underscore directly:

```<code>WHERE brand REGEXP '_'
</code>```

Body:
if column value is 2_apples or final_chapter how do i match a value that contains an underscore "_" ?

I've tried with:

SELECT DISTINCT brand FROM `items` WHERE brand like '%\\_'
SELECT DISTINCT brand FROM `items` WHERE brand like '_'
SELECT DISTINCT brand FROM `items` WHERE brand like '%_%'
SELECT DISTINCT brand FROM `items` WHERE brand like LIKE '\_'

It either shows all results or none. Any suggestions?

Body:
Try

WHERE brand LIKE '%\_%'

The underscore is a wildcard for a single character whereas the % is a wildcard for multiple (or none) characters. Put a backslash in front to escape them.

If you don't like escaping things, because it's ugly or scary, then an alternative would be to use the REGEXP operator with underscore directly:

WHERE brand REGEXP '_'


问:
Profiling ZeroMQ
Question about ZeroMQ profiling and debugging.
I'm interested to find out two information for a 0MQ socket. 1) queue length and 2) the messages (# of messages and total message size).

Is there anyway we can monitor and log the above information in 0MQ sockets? Does 0MQ expose such counters? I think it quite useful for us to profile and debug the system that we build on top of 0MQ. We are using the C++ API.
Thanks.

答:
No, AFAIK, this view is not exposed to user-programs. Why?

The reason is that all the ZeroMQ maxims are doing their best to fine-tune internal mechanics so as to leave user-programs as free from the underlying duties as possible and minimise the service overheads and latencies.

If indeed in a need to reach such nice-to haves:

One may, either, fork and add these user-side service management-plane layer into the core elements of the ZeroMQ data-pumps.

Next possible move is to stay within the as-is core implementation and just make each socket / queue connect and "run"-traffic through a simple, single purpose "gas-meter"-proxy, that would have none other duty, than to count bytes, messages ( and handle all the mechanics of the possible distribution / aggregation patterns the SUT-is using, so as to meter the 1:1 the flow ).

The costs of the former are much higher than of the latter, but the latter adds a way larger portion of end-to-end SUT-skew, as the "inserted" latencies are much higher and resources consumption grows both in ( SPACE ( {RX|TX}-HWM queues + buffers ) and TIME ( thread-count ).

Title: Profiling ZeroMQ


问:
Get percentage of NULL for all columns in Hive
I would like to get the percentage of NULL values in a table in Hive. Is there an easy way to do this without having to enumerate all column names in the query? In this case there are about 50k rows and 20 columns. Thanks in advance!

Something like:

SELECT count(each_column) / count(*) FROM TABLE_1
 WHERE each_column = NULL;

答:
The approach you need depends on the situation that you have:

For 20 fixed columns: Just type your query

For 200 fixed columns: Copy the column names to your favorite tool (excel) and build the query there

For n columns that may not be fixed: Write a script to generate your code

I once wrote a python script. I now don't have it at hand but it is quite easy to create with the following logic:

Query the first 1 (or 0?) rows of the table, to get all the headers.

Build the desired queries to generate column based statistics (like percentage of null values) and union the result

Then executed the query.

Of course it can be expanded to run for different tables, and statistics, but do realize that this may not scale well.

In my case I think I had to cut the query building in batches of 20 columns each time which would then be concatenated afterwards, because running it on 400 columns just generated a too complex query.


问:
Download a pdf using ajax and spring mvc doesn't work
I'm trying to implement an ajax download. This is my code for the ajax request:

```<code>$('#download').click(function(){
                    $.ajax({
                        url: '${downloadPath}',
                        type: 'GET',
                        data: {${_csrf.parameterName}:'${_csrf.token}'},
                        success: function (res) {
                        }
                    });
                });
</code>```

And this is my controller's method:

```<code>    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
    @ResponseBody
    public void download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {

        CheckList checkList = checkListService.findById(id);
//      byte[] byteItem  = checkListService.getFileByIdDocument(id);

        File f = new File(VariabiliGlobali.PATH_CHECKLIST+checkList.getPratica().getId()+"/"+id);
        ServletOutputStream out = response.getOutputStream();

        response.setContentType("application/pdf");
        response.setContentLength((int)f.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");

        FileInputStream in = new FileInputStream(f);
        byte[] buffer = new byte[4096];

        int length;
        while( (length = in.read(buffer) ) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
</code>```

I can see the pdf inside the response:

But my browser (Chrome) doens't do anything.

Where am I wrong? How can I dowload it?

答:
You don't need ajax and you are using as content type application/octet-stream as we can see in your code here:

```<code> response.setContentType("application/octet-stream");
</code>```

If you want to display the pdf inside the browser (if the browser has the proper plugin to read pdf) you should use:

the right pdf content type

set the proper header

In my code i did the following:

```<code>response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=pdfFileName.pdf;");
</code>```

In any case I'd suggest to yuo to use the "spring" way like this:

```<code>    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET)
        public ResponseEntity<InputStreamResource> download(@PathVariable(value="id") final Long id) throws IOException {
    HttpHeaders respHeaders = new HttpHeaders();

                    MediaType mediaType = new MediaType("application","pdf");
                    respHeaders.setContentType(mediaType);
                    respHeaders.setContentDispositionFormData("inline", "pdfFileName.pdf");
//Here you have to take the InputStream of the file you want to download
                    InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
                    return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
    }
</code>```

I hope it's useful

Angelo

Body:
I'm trying to implement an ajax download. This is my code for the ajax request:

$('#download').click(function(){
                    $.ajax({
                        url: '${downloadPath}',
                        type: 'GET',
                        data: {${_csrf.parameterName}:'${_csrf.token}'},
                        success: function (res) {
                        }
                    });
                });

And this is my controller's method:

    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
    @ResponseBody
    public void download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {

        CheckList checkList = checkListService.findById(id);
//      byte[] byteItem  = checkListService.getFileByIdDocument(id);

        File f = new File(VariabiliGlobali.PATH_CHECKLIST+checkList.getPratica().getId()+"/"+id);
        ServletOutputStream out = response.getOutputStream();

        response.setContentType("application/pdf");
        response.setContentLength((int)f.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");

        FileInputStream in = new FileInputStream(f);
        byte[] buffer = new byte[4096];

        int length;
        while( (length = in.read(buffer) ) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }

I can see the pdf inside the response:

But my browser (Chrome) doens't do anything.

Where am I wrong? How can I dowload it?

Body:
You don't need ajax and you are using as content type application/octet-stream as we can see in your code here:

 response.setContentType("application/octet-stream");

If you want to display the pdf inside the browser (if the browser has the proper plugin to read pdf) you should use:

the right pdf content type

set the proper header

In my code i did the following:

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=pdfFileName.pdf;");

In any case I'd suggest to yuo to use the "spring" way like this:

    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET)
        public ResponseEntity<InputStreamResource> download(@PathVariable(value="id") final Long id) throws IOException {
    HttpHeaders respHeaders = new HttpHeaders();

                    MediaType mediaType = new MediaType("application","pdf");
                    respHeaders.setContentType(mediaType);
                    respHeaders.setContentDispositionFormData("inline", "pdfFileName.pdf");
//Here you have to take the InputStream of the file you want to download
                    InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
                    return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
    }

I hope it's useful

Angelo


问:
I am trying to get the DateTimeFormatter for a date string in joda time
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

```<code>DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
</code>```

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

```<code>String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);
</code>```

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

答:
"Z" in format is RFC 822 time zone

For formatting, if the offset value from GMT is 0, "Z" is produced. If
  the number of pattern letters is 1, any fraction of an hour is
  ignored.

For parsing, "Z" is parsed as the UTC time zone designator. General
  time zones are not accepted.

If you want to get string for UTC - you should force timezone:

```<code>DateTime dateTime = new DateTime(DateTimeZone.UTC);
String strNow = dateTime.toString(DT_SCHEDULE_FORMATTER_START_TIME);
</code>```

Body:
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

Body:
"Z" in format is RFC 822 time zone

For formatting, if the offset value from GMT is 0, "Z" is produced. If
  the number of pattern letters is 1, any fraction of an hour is
  ignored.

For parsing, "Z" is parsed as the UTC time zone designator. General
  time zones are not accepted.

If you want to get string for UTC - you should force timezone:

DateTime dateTime = new DateTime(DateTimeZone.UTC);
String strNow = dateTime.toString(DT_SCHEDULE_FORMATTER_START_TIME);


问:
NullPointerException on setVisibility function in FrameLayout
I have developed android project and published to a google playstore.
In this app, for tab use, at one activity, calling frameLayout.setVisibility(View.INVISIBLE) for showing other layouts.
It is working perfectly on my android devices.

But when i check crashlytics, i can see applications crashed on that function.

I tried many google searches but i did not found the solution and did not fix yet.

Please help me on this issue.

答: Well, without any code snippets will be hard to realise, but since is a NPE error I am guessing that your layout is not a valid one or the fragment it was in, has been changed. </p>


问:
Mongodb can't start
today I updated my Mongo.. mongodb-stable (from 10gen repo)

but my service has down.
the following command not working

```<code>$ sudo service mongodb start
$ start: Unknown job: mongodb
</code>```

even this command not working

```<code>$ sudo /etc/init.d/mongodb start
$ Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service mongodb start
Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the start(8) utility, e.g. start mongodb
start: Unknown job: mongodb
</code>```

there is no mongo process running

```<code>$ ps -ef|grep mongo
$ user  9689  8121  0 13:01 pts/1    00:00:00 grep --color=auto mongo
</code>```

log is here

```<code>tail /var/log/mongodb/mongodb.log
Fri Dec 10 11:24:35 [conn4] end connection 127.0.0.1:54217
Fri Dec 10 11:25:35 [initandlisten] connection accepted from 127.0.0.1:54229 #5
Fri Dec 10 11:26:25 [initandlisten] connection accepted from 127.0.0.1:54243 #6
Fri Dec 10 11:26:30 [conn6] end connection 127.0.0.1:54243
Fri Dec 10 11:30:13 got kill or ctrl c or hup signal 15 (Terminated), will terminate after current cmd ends
Fri Dec 10 11:30:13 [interruptThread] now exiting
Fri Dec 10 11:30:13 dbexit:

Fri Dec 10 11:30:13 [interruptThread] shutdown: going to close listening sockets...
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 5
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 6
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 7
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 8
Fri Dec 10 11:30:13 [interruptThread] shutdown: going to flush oplog...
Fri Dec 10 11:30:13 [interruptThread] shutdown: going to close sockets...
Fri Dec 10 11:30:13 [interruptThread] shutdown: waiting for fs preallocator...
Fri Dec 10 11:30:13 [interruptThread] shutdown: closing all files...
Fri Dec 10 11:30:13     closeAllFiles() finished

Fri Dec 10 11:30:13 [interruptThread] shutdown: removing fs lock...
Fri Dec 10 11:30:13 dbexit: really exiting now
</code>```

for now, I'm running Mongo through this command just for a while, creating process manually

```<code>$ sudo mongod -f /etc/mongodb.conf
</code>```

any idea?
or has anyone updated Mongo-stable via Update manager?

Edits:

This mongodb version was v1.6.5 and it seems mongo team released it as stable with a bug. And they fixed it immediately at v1.7.4. You can see the major priority issue.

答: I run ubuntu server 10.04 minimal installation in a chroot environment. I always have same massage even after I executed the above. Only the following sudo mongod -f /etc/mongodb.conf works, any hints?

Title: Mongodb can't start

Body:
today I updated my Mongo.. mongodb-stable (from 10gen repo)

but my service has down.
the following command not working

$ sudo service mongodb start
$ start: Unknown job: mongodb

even this command not working

$ sudo /etc/init.d/mongodb start
$ Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service mongodb start
Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the start(8) utility, e.g. start mongodb
start: Unknown job: mongodb

there is no mongo process running

$ ps -ef|grep mongo
$ user  9689  8121  0 13:01 pts/1    00:00:00 grep --color=auto mongo

log is here

tail /var/log/mongodb/mongodb.log
Fri Dec 10 11:24:35 [conn4] end connection 127.0.0.1:54217
Fri Dec 10 11:25:35 [initandlisten] connection accepted from 127.0.0.1:54229 #5
Fri Dec 10 11:26:25 [initandlisten] connection accepted from 127.0.0.1:54243 #6
Fri Dec 10 11:26:30 [conn6] end connection 127.0.0.1:54243
Fri Dec 10 11:30:13 got kill or ctrl c or hup signal 15 (Terminated), will terminate after current cmd ends
Fri Dec 10 11:30:13 [interruptThread] now exiting
Fri Dec 10 11:30:13 dbexit:

Fri Dec 10 11:30:13 [interruptThread] shutdown: going to close listening sockets...
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 5
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 6
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 7
Fri Dec 10 11:30:13 [interruptThread] closing listening socket: 8
Fri Dec 10 11:30:13 [interruptThread] shutdown: going to flush oplog...
Fri Dec 10 11:30:13 [interruptThread] shutdown: going to close sockets...
Fri Dec 10 11:30:13 [interruptThread] shutdown: waiting for fs preallocator...
Fri Dec 10 11:30:13 [interruptThread] shutdown: closing all files...
Fri Dec 10 11:30:13     closeAllFiles() finished

Fri Dec 10 11:30:13 [interruptThread] shutdown: removing fs lock...
Fri Dec 10 11:30:13 dbexit: really exiting now

for now, I'm running Mongo through this command just for a while, creating process manually

$ sudo mongod -f /etc/mongodb.conf

any idea?
or has anyone updated Mongo-stable via Update manager?

Edits:

This mongodb version was v1.6.5 and it seems mongo team released it as stable with a bug. And they fixed it immediately at v1.7.4. You can see the major priority issue.


问:
Custom entity resolver for XMLStreamReader not working
I have an xml to parse with XMLStreamReader, but it has some html entities (not part of xml standard) like accented characters that make the next() method to throw XMLStreamException: The entity "uacute" was referenced, but not declared.

I try to add a custom entity resolver implementing XMLResolver (https://docs.oracle.com/javase/8/docs/api/javax/xml/stream/XMLResolver.html), which documentation states that:

If an application wishes to perform custom entity resolution it must register an instance of this interface with the XMLInputFactory using the setXMLResolver method.

Ok, so I made this class to reproduce the error:

```<code>private void testXMLResolver() throws XMLStreamException {
    String xml = "<example>You know ó is an accented character</example>";
    XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // instantiate XMLInputFactory
    inputFactory.setXMLResolver(new MyEntityResolver()); // Append custom entity resolver
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes())); // create XMLStreamReader for the xml
    xmlStreamReader.next(); // reads <example>
    xmlStreamReader.next(); // reads the text inside <example> tag
    System.out.println("Text is: " + xmlStreamReader.getText());
    xmlStreamReader.next();
}

class MyEntityResolver implements XMLResolver {
    @Override
    public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
        return new ByteArrayInputStream("huehey!!".getBytes());
    }
}
</code>```

}

Executing testXMLResolver() outputs first:

Text is: You know

And then, when the last next() is executed it throws the exception

```
Exception in thread "main" javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,27]
Message: The entity "oacute" was referenced, but not declared.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:601)
    at Test.testXMLResolver(Test.java:21)
    at Test.main(Test.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

```

First: I don't know why MyXMLResolver is not resolving the entity

Second: Why does the exception is thorwn in the last next() and not the previous one? because the text is parsed in the previous one.

PS: I make the resolveEntity(...) to return an InputStream because the documentation of the method says that:

Retrieves a resource. This resource can be of the following three return types: (1) java.io.InputStream (2) javax.xml.stream.XMLStreamReader (3) java.xml.stream.XMLEventReader

答:
Isn't it because you have not declared ó ("uacute") ?
something like this maybe:</p>

```<code><!DOCTYPE definition [<!ENTITY oacute "ó">]>
</code>```

Body:
I have an xml to parse with XMLStreamReader, but it has some html entities (not part of xml standard) like accented characters that make the next() method to throw XMLStreamException: The entity "uacute" was referenced, but not declared.

I try to add a custom entity resolver implementing XMLResolver (https://docs.oracle.com/javase/8/docs/api/javax/xml/stream/XMLResolver.html), which documentation states that:

If an application wishes to perform custom entity resolution it must register an instance of this interface with the XMLInputFactory using the setXMLResolver method.

Ok, so I made this class to reproduce the error:

private void testXMLResolver() throws XMLStreamException {
    String xml = "<example>You know ó is an accented character</example>";
    XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // instantiate XMLInputFactory
    inputFactory.setXMLResolver(new MyEntityResolver()); // Append custom entity resolver
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes())); // create XMLStreamReader for the xml
    xmlStreamReader.next(); // reads <example>
    xmlStreamReader.next(); // reads the text inside <example> tag
    System.out.println("Text is: " + xmlStreamReader.getText());
    xmlStreamReader.next();
}

class MyEntityResolver implements XMLResolver {
    @Override
    public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
        return new ByteArrayInputStream("huehey!!".getBytes());
    }
}

}

Executing testXMLResolver() outputs first:

Text is: You know

And then, when the last next() is executed it throws the exception

Exception in thread "main" javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,27]
Message: The entity "oacute" was referenced, but not declared.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:601)
    at Test.testXMLResolver(Test.java:21)
    at Test.main(Test.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

First: I don't know why MyXMLResolver is not resolving the entity

Second: Why does the exception is thorwn in the last next() and not the previous one? because the text is parsed in the previous one.

PS: I make the resolveEntity(...) to return an InputStream because the documentation of the method says that:

Retrieves a resource. This resource can be of the following three return types: (1) java.io.InputStream (2) javax.xml.stream.XMLStreamReader (3) java.xml.stream.XMLEventReader

Body:
Isn't it because you have not declared ó ("uacute") ?
something like this maybe:

<!DOCTYPE definition [<!ENTITY oacute "&#243;">]>


问:
how to transform json into beans when msg received from the queue
Java 8 Apache camel

I have camel route which listens to the active MQ. my queue contains the JSON payload. i have crated the mapper bean wondering how can i convert json response into list of mapper objects.

```<code>from ("activemq:queue:my.queue")
.log("msg received").log("body" + ${body}");

class myMapper{
String name;
String addr;
}
</code>```

答:
```<code>from ("activemq:queue:my.queue")
.log("msg received")
.unmarshal().json(Jackson, MyMapper.class).to("sendToAnotherRoute");
</code>```

Body:
Java 8 Apache camel

I have camel route which listens to the active MQ. my queue contains the JSON payload. i have crated the mapper bean wondering how can i convert json response into list of mapper objects.

from ("activemq:queue:my.queue")
.log("msg received").log("body" + ${body}");

class myMapper{
String name;
String addr;
}


问:
onchange() function not defined (inaccessible from index.html?)
i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.

Whenever the onchange event tries to use the function i have defined
 filterChanged(), it provides a reference error: "filterChanged is not defined
    at HTMLSelectElement.onchange"

i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.

see below the code -

main.js

```<code>var filterChanged = function() {
    console.log('filter changed');
}

window.onload = function() {
    let filter = document.getElementById('filter-list');
    filter.setAttribute('onchange', 'filterChanged()');
}
</code>```

index.html

```<code><!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>TestProj</title>
    <script type="text/javascript" charset="UTF-8" src="build/bundle.js"></script>
</head>
<body>
    <h3>Todos</h3>
    <p>Number of items to show</p>
    <select id="filter-list" name="filter">
            <option selected="true" value="list10">10</option>
            <option value="list20">20</option>
            <option value="list30">30</option>
    </select>
    <ul id="todo_list">
        <!-- Inject list here with JS (main.js getTodos()) -->
    </ul>
</body>
</html>
</code>```

答:
You can use different ways.
First way adding onchange to your select:

```<code><select id="filter-list" name="filter" onchange="filterChanged();">
</code>```

Second way using eventListener:

```<code>filter.addEventListener('change', filterChanged);
</code>```

Third way :

```<code>window.onload=function() {
  let filter = document.getElementById('filter-list');
  filter.onchange=function() {
    // The code of your function
  }
}
</code>```

Body:
i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.

Whenever the onchange event tries to use the function i have defined
 filterChanged(), it provides a reference error: "filterChanged is not defined
    at HTMLSelectElement.onchange"

i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.

see below the code -

main.js

var filterChanged = function() {
    console.log('filter changed');
}

window.onload = function() {
    let filter = document.getElementById('filter-list');
    filter.setAttribute('onchange', 'filterChanged()');
}

index.html

<!doctype html>

    <meta charset="UTF-8">
    <title>TestProj</title>

Todos

Number of items to show

    <select id="filter-list" name="filter">
            <option selected="true" value="list10">10</option>
            <option value="list20">20</option>
            <option value="list30">30</option>
    </select>

Body:
You can use different ways.
First way adding onchange to your select:

<select id="filter-list" name="filter" onchange="filterChanged();">

Second way using eventListener:

filter.addEventListener('change', filterChanged);

Third way :

window.onload=function() {
  let filter = document.getElementById('filter-list');
  filter.onchange=function() {
    // The code of your function
  }
}


问:
How to wait for the data to be fetched from Firebase Database
I am trying to get recieverUID from a certain table and then get the Value of username cooresponding the UID from another table.
What I think is happening is that the Adapter is being set before the receivedNames Array List has been fetched as the App runs fine when I set the receivedName Array list as a constant.
Please tell me what's wrong here and if this is the correct way to do this
Here's what my database looks like,
Firebase DB

My code for Tab 3 Fragment

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

private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<String> reminderMessages;
protected static ArrayList<String> receiverNames;
String senderUID;
private DatabaseReference mDatabase;
//Overriden method onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Change R.layout.tab1 in you classes
    View v = inflater.inflate(R.layout.tab3, container, false);
    //get current user
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    reminderMessages = new ArrayList<>();
    receiverNames = new ArrayList<>();

    senderUID = user.getUid();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    Query query = mDatabase.child("reminders").orderByChild("senderUID").equalTo(senderUID);

    //Setting size of recycler view as constant
    recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
    recyclerView.setHasFixedSize(true);

    //Setting Linear Layout
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                //Getting message from database
                String message = ds.child("reminderMessage").getValue(String.class);
                //Adding database to ArrayList
                reminderMessages.add(message);
                //Getting ReceiverUID
                String rUID = ds.child("receiverUID").getValue(String.class);
                //Getting corresponding username of the ReceiverUID
                GetName getName = new GetName();
                getName.GetName(rUID);
                reminderMessages.add(message);
               // Log.d("String names", receiverNames.toString());
            }

            adapter = new DataAdapter(reminderMessages,receiverNames);
            recyclerView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //Error in Reaching Database
            Toast.makeText(getContext(), "Something went Wrong!", Toast.LENGTH_SHORT).show();
        }

    });
    //Returning the layout file after inflating
    return v;
}
</code>```

And here is my GetName Class

```<code>public class GetName {
private FirebaseAuth auth;
ListView listView;
private DatabaseReference mDatabase;
String receiverName;
public void GetName(String UID){
    mDatabase = FirebaseDatabase.getInstance().getReference().child("users");

    Query query = mDatabase.orderByKey().equalTo(UID);
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot2) {

            // dataSnapshot is the "issue" node with all children with id 0
            for (DataSnapshot users : dataSnapshot2.getChildren()) {
                receiverName = users.child("username").getValue(String.class);

                receiverNames.add(receiverName);
                Log.d("name retrieved",receiverNames.toString());

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
</code>```

答: To solve this problem, please add the declaration of your receiverNames ArrayList inside the onDataChange() method, otherwise it will be null. This is happening due to asynchronous behaviour of that method. If you want to use those values outside that method, please see my answer from this post.

Body:
I am trying to get recieverUID from a certain table and then get the Value of username cooresponding the UID from another table.
What I think is happening is that the Adapter is being set before the receivedNames Array List has been fetched as the App runs fine when I set the receivedName Array list as a constant.
Please tell me what's wrong here and if this is the correct way to do this
Here's what my database looks like,
Firebase DB

My code for Tab 3 Fragment

public class Tab3 extends Fragment {

private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<String> reminderMessages;
protected static ArrayList<String> receiverNames;
String senderUID;
private DatabaseReference mDatabase;
//Overriden method onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Change R.layout.tab1 in you classes
    View v = inflater.inflate(R.layout.tab3, container, false);
    //get current user
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    reminderMessages = new ArrayList<>();
    receiverNames = new ArrayList<>();

    senderUID = user.getUid();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    Query query = mDatabase.child("reminders").orderByChild("senderUID").equalTo(senderUID);

    //Setting size of recycler view as constant
    recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
    recyclerView.setHasFixedSize(true);

    //Setting Linear Layout
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                //Getting message from database
                String message = ds.child("reminderMessage").getValue(String.class);
                //Adding database to ArrayList
                reminderMessages.add(message);
                //Getting ReceiverUID
                String rUID = ds.child("receiverUID").getValue(String.class);
                //Getting corresponding username of the ReceiverUID
                GetName getName = new GetName();
                getName.GetName(rUID);
                reminderMessages.add(message);
               // Log.d("String names", receiverNames.toString());
            }

            adapter = new DataAdapter(reminderMessages,receiverNames);
            recyclerView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //Error in Reaching Database
            Toast.makeText(getContext(), "Something went Wrong!", Toast.LENGTH_SHORT).show();
        }

    });
    //Returning the layout file after inflating
    return v;
}

And here is my GetName Class

public class GetName {
private FirebaseAuth auth;
ListView listView;
private DatabaseReference mDatabase;
String receiverName;
public void GetName(String UID){
    mDatabase = FirebaseDatabase.getInstance().getReference().child("users");

    Query query = mDatabase.orderByKey().equalTo(UID);
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot2) {

            // dataSnapshot is the "issue" node with all children with id 0
            for (DataSnapshot users : dataSnapshot2.getChildren()) {
                receiverName = users.child("username").getValue(String.class);

                receiverNames.add(receiverName);
                Log.d("name retrieved",receiverNames.toString());

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}


问:
Pass textbox values from view to ViewComponent
I have a view which calls a view component  and passes a model called Konstant in the following way:

```<code>@foreach (Konstant item in Model)
{
    <div class="tab-content">
        <div id="@item.KANAL" class="tab-pane fade in">
            @await Component.InvokeAsync("MeterReader2", new { k = item })
        </div>
    </div>
}
</code>```

If we look at the ViewComponent, it looks like this:

```<code>public class MeterReader2ViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(Models.Konstant k)
    // Endast en kanal.
    {
     // logic....
    }
}
</code>```

So far, this works for me. My question however is, how do I introduce two textboxes in the view which should include start and end date fields, where the inputed values should be sent to the view component?

I was thinking something like:

```<code><input type="text" id="startDate", name="start" value="" />
<input type="text" id="endDate", name="end" value="" />
</code>```

And then:

```<code>@foreach (Konstant item in Model)
{
    <div class="tab-content">
        <div id="@item.KANAL" class="tab-pane fade in">
            @await Component.InvokeAsync("MeterReader2", new { k = item, start = startDate, end = endDate })
        </div>
    </div>
}
</code>```

Lastly, within the View Component itself: include the parameters:

```<code>public async Task<IViewComponentResult> InvokeAsync(Models.Konstant k, string start, string end) // Endast en kanal.
{
  // logic....
}
</code>```

Any ideas?

答:
Rather than having the model as IEnumerable, I'd recommend creating:

```<code>public class KonstantViewModel
{
   public List<Konstant> Konstants { get; set; }

   public string start { get; set; }

   public string end { get; set; }
}
</code>```

Since the name of your inputs are start and end, named inputs will postback and map to the start and end properties in this model (You could also use NameFor extension to explicitly map if you like too).  So on postback, the model will receive the start/end, and then you can pass these model properties to the view component.

The problem you are having is you need a middle man to pass the values.  This solution expects that you need to get the values and pass them in during a postback scenario.  If you were expecting that to happen on the client, then a JavaScript solution is needed.

Body:
I have a view which calls a view component  and passes a model called Konstant in the following way:

@foreach (Konstant item in Model)
{

            @await Component.InvokeAsync("MeterReader2", new { k = item })

}

If we look at the ViewComponent, it looks like this:

public class MeterReader2ViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(Models.Konstant k)
    // Endast en kanal.
    {
     // logic....
    }
}

So far, this works for me. My question however is, how do I introduce two textboxes in the view which should include start and end date fields, where the inputed values should be sent to the view component?

I was thinking something like:

<input type="text" id="startDate", name="start" value="" />
<input type="text" id="endDate", name="end" value="" />

And then:

@foreach (Konstant item in Model)
{

            @await Component.InvokeAsync("MeterReader2", new { k = item, start = startDate, end = endDate })

}

Lastly, within the View Component itself: include the parameters:

public async Task<IViewComponentResult> InvokeAsync(Models.Konstant k, string start, string end) // Endast en kanal.
{
  // logic....
}

Any ideas?

Body:
Rather than having the model as IEnumerable, I'd recommend creating:

public class KonstantViewModel
{
   public List<Konstant> Konstants { get; set; }

   public string start { get; set; }

   public string end { get; set; }
}

Since the name of your inputs are start and end, named inputs will postback and map to the start and end properties in this model (You could also use NameFor extension to explicitly map if you like too).  So on postback, the model will receive the start/end, and then you can pass these model properties to the view component.

The problem you are having is you need a middle man to pass the values.  This solution expects that you need to get the values and pass them in during a postback scenario.  If you were expecting that to happen on the client, then a JavaScript solution is needed.


问:
What std::locale names are available on common windows compilers?
The standard is pretty much silent on what constitutes a valid locale name; only that passing an invalid locale name results in std::runtime_error. What locale names are usable on common windows compilers such as MSVC, MinGW, and ICC?

答:
Ok, there is a difference between C and C++ locales.

Let's start:

MSVC C++ std::locale and C setlocale

Accepts locale names as "Language[_Country][.Codepage]" for example "English_United States.1251" Otherwise would throws. Note: codepage can't be 65001/UTF-8 and should be consistent with ANSI codepage for this locale (or just omitted)

MSVC C++ std::locale and C setlocale in Vista and 7 should accept locales
[Language][-Script][-Country] like "en-US" using ISO-631 language codes and
ISO 3166 regions and script names.

I tested it with Visual Studio on Windows 7 - it does not work.

MinGW C++ std::locale accepts "C" and "POSIX" it does not support other locales,
actually gcc supports locales only over GNU C library - basically only under Linux.

setlocale is native Windows API call so should support all I mentioned above.

It may support wider range of locales when used with alternative C++ libraries
like Apache stdcxx or STL Port.

ICC - I hadn't tested it but it depends on the standard C++ library it uses. For
example under Linux it used GCC's libstdc++ so it supports all the locales gcc
supports. I don't know what standard C++ library it uses under Windows.

If you want to have "compiler and platform" independent locales support (and actually
much better support) take a look on Boost.Locale

Artyom


问:
Close FFMPEG if connection with ipcam lost
this is my scrit that transmit a live camera rtsp stream to youtube rtmp stream.

The Script before start verify if connection with camera is alive.

The problem is during the process, if network connection lost ffmpeg remain in locked state.

It's possibile to close ffmpeg or restart task if connection with camera lost?

```<code>:LOOP
timeout /t 10
ping 192.168.1.11
IF ERRORLEVEL 1 goto exit
IF ERRORLEVEL 0 goto START
:START

ffmpeg  -f lavfi -i anullsrc -rtsp_transport tcp -i rtsp://192.168.1.11:10554/tcp/av0_0 -tune zerolatency -vcodec libx264 -t 12:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/(secret code)

goto LOOP
</code>```

答:
This is the solution:

CHECK Task run every minutes
If there is a problem with the connetection of camera, the process kill all  istance off ffmpeg and restart the primary task.

```<code>@echo off
set "host=192.168.1.11"

ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"

if %errorlevel% == 0 (
    echo Success.
) else (
echo Camera offline il %date% alle ore %time% >>C:\Users\Gianluca\Desktop\script\log.txt
WMIC PROCESS WHERE "COMMANDLINE LIKE '%%ffmpeg%%'" call terminate
schtasks /Run /TN "webcam"

)
</code>```

The primary task check the  connetection of camera and if connection lost, close the windows.

```<code>:LOOP
set "host=192.168.1.11"

ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"

if %errorlevel% == 0 (
   goto START
) else (

exit

)
pause

:START

ffmpeg  -f lavfi -i anullsrc -rtsp_transport tcp -i rtsp://%host%:10554/tcp/av0_0 -tune zerolatency -vcodec libx264 -t 12:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/code

goto LOOP
</code>```

Body:
this is my scrit that transmit a live camera rtsp stream to youtube rtmp stream.

The Script before start verify if connection with camera is alive.

The problem is during the process, if network connection lost ffmpeg remain in locked state.

It's possibile to close ffmpeg or restart task if connection with camera lost?

:LOOP
timeout /t 10
ping 192.168.1.11
IF ERRORLEVEL 1 goto exit
IF ERRORLEVEL 0 goto START
:START

ffmpeg  -f lavfi -i anullsrc -rtsp_transport tcp -i rtsp://192.168.1.11:10554/tcp/av0_0 -tune zerolatency -vcodec libx264 -t 12:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/(secret code)

goto LOOP

Body:
This is the solution:

CHECK Task run every minutes
If there is a problem with the connetection of camera, the process kill all  istance off ffmpeg and restart the primary task.

@echo off
set "host=192.168.1.11"

ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"

if %errorlevel% == 0 (
    echo Success.
) else (
echo Camera offline il %date% alle ore %time% >>C:\Users\Gianluca\Desktop\script\log.txt
WMIC PROCESS WHERE "COMMANDLINE LIKE '%%ffmpeg%%'" call terminate
schtasks /Run /TN "webcam"

)

The primary task check the  connetection of camera and if connection lost, close the windows.

:LOOP
set "host=192.168.1.11"

ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"

if %errorlevel% == 0 (
   goto START
) else (

exit

)
pause

:START

ffmpeg  -f lavfi -i anullsrc -rtsp_transport tcp -i rtsp://%host%:10554/tcp/av0_0 -tune zerolatency -vcodec libx264 -t 12:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/code

goto LOOP


问:
how to close GTK window with C
i was doing a small project where i had a a fullscreen GUI (Glade, GTK and C) and needed to give the user a way to close the screen (obviously the window manager was not available due to the window being fullscreen).

problem rices when i attempt to compile this piece of code

```<code>//close sidebar1
 void on_window_sidebar1_back_clicked()
 {
    gtk_window_close (GtkWindow *window);
 }
</code>```

i receive the following error

```<code>    /usr/bin/arm-linux-gnueabihf-gcc -c -g -O0 -Wall -pthread -pipe src/main.c `pkg-config --cflags --libs gtk+-3.0` -o main.o
src/main.c: In function 'on_window_sidebar1_back_clicked':
src/main.c:61:2: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'gtk_window_close'
  gtk_window_close (GtkWindow *window);
  ^
src/main.c:61:20: error: expected expression before 'GtkWindow'
  gtk_window_close (GtkWindow *window);
                    ^
makefile:30: recipe for target 'main.o' failed
make: *** [main.o] Error 1
</code>```

I tried to follow the documentation here, but seem to have failed badly

Does anyone have any ideas?

PS.

here is the full main.c if someone is intrested. Its my first attempt at C with gtk, so dont be too harsh, Thank you (=

```<code>#include <gtk/gtk.h>

GtkWidget *g_lbl_test;
GtkWidget *g_lbl_count;

int main(int argc, char *argv[])
{
    GtkBuilder      *builder;
    GtkWidget       *window;

    gtk_init(&argc, &argv);

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
    gtk_builder_connect_signals(builder, NULL);

    //pointers for the labels (...used in button press)
    g_lbl_test = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_test"));
    g_lbl_count = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_count"));

    g_object_unref(builder);

    gtk_widget_show(window);
    //gtk_window_fullscreen (GtkWindow *window);  //dont know how to use this, same with gtk_window_close
    gtk_main();

    return 0;
}

//button press (just a test to make sure the window didnt freeze)
void on_btn_count_clicked()
{
        static unsigned int count= 0;
        char str_count[30] = {0};

        gtk_label_set_text(GTK_LABEL(g_lbl_test), "Test success!");
        count++;
        sprintf(str_count, "%d", count);
        gtk_label_set_text(GTK_LABEL(g_lbl_count), str_count);
}

//sidebar1
void on_sidebar_1_clicked()
{
    GtkBuilder      *builder;
    GtkWidget       *window;

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_sidebar1"));

    gtk_widget_show(window);
}
//close sidebar1
 void on_window_sidebar1_back_clicked()
 {
    gtk_window_close (GtkWindow *window);
 }

// called on closing window
void on_window_main_destroy()
{
    gtk_main_quit();
}
</code>```

答:
You probably should call

```<code> gtk_close_window(window);
</code>```

But that window should come from somewhere.

(you may use a Gtk closure with a connection, or a callback with a client data, etc. or store somehow that window in a global variable, etc...)

Read more about C programming, then read a bit about callbacks and closures, then read more about GTK, and the signal mechanism of Gobject.

(your code shows a lot of confusion; I suggest to read the Getting started with GTK chapter after having read a good C programming book; BTW, I suggest to first write something which is not fullscreen, and only later improve it)

Don't forget to enable all warnings and debug info when compiling, that is compile with
 gcc -Wall -Wextra -g (and other arguments, perhaps using $(pkg-config --cflags gtk+-3.0) and also $(pkg-config --libs gtk+-3.0) for linking).

Title: how to close GTK window with C

Body:
i was doing a small project where i had a a fullscreen GUI (Glade, GTK and C) and needed to give the user a way to close the screen (obviously the window manager was not available due to the window being fullscreen).

problem rices when i attempt to compile this piece of code

//close sidebar1
 void on_window_sidebar1_back_clicked()
 {
    gtk_window_close (GtkWindow *window);
 }

i receive the following error

    /usr/bin/arm-linux-gnueabihf-gcc -c -g -O0 -Wall -pthread -pipe src/main.c `pkg-config --cflags --libs gtk+-3.0` -o main.o
src/main.c: In function 'on_window_sidebar1_back_clicked':
src/main.c:61:2: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'gtk_window_close'
  gtk_window_close (GtkWindow *window);
  ^
src/main.c:61:20: error: expected expression before 'GtkWindow'
  gtk_window_close (GtkWindow *window);
                    ^
makefile:30: recipe for target 'main.o' failed
make: *** [main.o] Error 1

I tried to follow the documentation here, but seem to have failed badly

Does anyone have any ideas?

PS.

here is the full main.c if someone is intrested. Its my first attempt at C with gtk, so dont be too harsh, Thank you (=

#include <gtk/gtk.h>

GtkWidget *g_lbl_test;
GtkWidget *g_lbl_count;

int main(int argc, char *argv[])
{
    GtkBuilder      *builder;
    GtkWidget       *window;

    gtk_init(&argc, &argv);

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
    gtk_builder_connect_signals(builder, NULL);

    //pointers for the labels (...used in button press)
    g_lbl_test = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_test"));
    g_lbl_count = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_count"));

    g_object_unref(builder);

    gtk_widget_show(window);
    //gtk_window_fullscreen (GtkWindow *window);  //dont know how to use this, same with gtk_window_close
    gtk_main();

    return 0;
}

//button press (just a test to make sure the window didnt freeze)
void on_btn_count_clicked()
{
        static unsigned int count= 0;
        char str_count[30] = {0};

        gtk_label_set_text(GTK_LABEL(g_lbl_test), "Test success!");
        count++;
        sprintf(str_count, "%d", count);
        gtk_label_set_text(GTK_LABEL(g_lbl_count), str_count);
}

//sidebar1
void on_sidebar_1_clicked()
{
    GtkBuilder      *builder;
    GtkWidget       *window;

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_sidebar1"));

    gtk_widget_show(window);
}
//close sidebar1
 void on_window_sidebar1_back_clicked()
 {
    gtk_window_close (GtkWindow *window);
 }

// called on closing window
void on_window_main_destroy()
{
    gtk_main_quit();
}

Body:
You probably should call

 gtk_close_window(window);

But that window should come from somewhere.

(you may use a Gtk closure with a connection, or a callback with a client data, etc. or store somehow that window in a global variable, etc...)

Read more about C programming, then read a bit about callbacks and closures, then read more about GTK, and the signal mechanism of Gobject.

(your code shows a lot of confusion; I suggest to read the Getting started with GTK chapter after having read a good C programming book; BTW, I suggest to first write something which is not fullscreen, and only later improve it)

Don't forget to enable all warnings and debug info when compiling, that is compile with
 gcc -Wall -Wextra -g (and other arguments, perhaps using $(pkg-config --cflags gtk+-3.0) and also $(pkg-config --libs gtk+-3.0) for linking).


问:
Dynamically added checkbox don't look the same
By adding a mdl-checkbox element to the HTML file, I get the following result:

```<code><label id="check" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
<input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value="0" />
<span class="mdl-checkbox__label">Check Me</span>
</code>```

By adding the same code by injection the checkbox becomes plain:

```<code>var html = '<label id="check" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect"><input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value="0" /><span class="mdl-checkbox__label">Check Me</span></label>';
$("#dynamic-checkbox").append(html);
</code>```

Here is the jsFiddle

I have tried to use ready

```<code>$(function() {
  $("#dynamic-checkbox").append(html);
)};
</code>```

No change.

Any recommended way to dynamically add mdl element?

答:
Whenever I dynamically add something I just upgrade everything:

```<code>function refreshMDL(){
    if(typeof componentHandler !=="undefined"){
        componentHandler.upgradeAllRegistered();
    }
}
</code>```

I run this function after I have dynamically added anything mdl dependent.

Body:
By adding a mdl-checkbox element to the HTML file, I get the following result:

<input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value="0" />
Check Me

By adding the same code by injection the checkbox becomes plain:

var html = '<input id="MdlCheckBox" type="checkbox" class="mdl-checkbox__input" value="0" />Check Me';
$("#dynamic-checkbox").append(html);

Here is the jsFiddle

I have tried to use ready

$(function() {
  $("#dynamic-checkbox").append(html);
)};

No change.

Any recommended way to dynamically add mdl element?

Body:
Whenever I dynamically add something I just upgrade everything:

function refreshMDL(){
    if(typeof componentHandler !=="undefined"){
        componentHandler.upgradeAllRegistered();
    }
}

I run this function after I have dynamically added anything mdl dependent.


问:
Qt override widget shortcut (window shortcut)
I have a Qt app with several window shortcuts defined in a Qt Designer form action. The shortcuts works well until they are pressed while the focus is on a widget that handles the same combination (overriding my window shortcut).

I would like to have the opposite behavior: window shortcuts overriding focused widget shortcuts.

I tried using eventFilter and I can catch the desired events, but I'm not able to resend them in a way that the global shortcuts are called. I could use a big switch and call the actions myself, but of course, I would like to avoid that.

I used postEvent and sendEvent inside the eventFilter using the MainWindow as the receiver, but the events are ignored:

```<code>bool MainWindow::eventFilter(QObject*, QEvent* event) {
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Z
            && keyEvent->modifiers() == Qt::ControlModifier) {
            //Calling the triggers directly works
            ui->actionUndo->trigger();
            return true;
        } else if (keyEvent->modifiers().testFlag(
                       Qt::KeypadModifier)) {
            QKeyEvent* ev2
                = new QKeyEvent(keyEvent->type(), keyEvent->key(), 0);
            qDebug() << keyEvent << ev2;
            //This sendEvent doesn't work
            QApplication::sendEvent(ui->widget, ev2);
            event->accept();
            return true;
        } else {
            return false;
        }
    }
    return false;
}
</code>```

答:
As one of the solutions you can install QEvent::ShortcutOverride event filters:

For QEvent::ShortcutOverride the receiver needs to explicitly accept
  the event to trigger the override. Calling ignore() on a key event
  will propagate it to the parent widget. The event is propagated up the
  parent widget chain until a widget accepts it or an event filter
  consumes it.

That event would be called when some widget tries to override a shortcut event, e.g. just a simple example:

I have just a new Qt app with one lineEdit and window menu with Ctrl+V shortcut (overrides the paste shortcut in lineEdit).

Here how it works:

1.Create the filtering method that would ignore (return true) the shortcut overrides (I've used MainWindow::eventFilter in sample app, however you can use any filtering object you need or want). It might be better to follow Qt docs and use the accept()/ignore() as stated above, however on my app it worked just fine without them just returning true/false.

2.Install the event filter from p.1 to widget that should ignore shortcut action if overriding.

3.I've added the menu action with Ctrl+V shortcut in designer. In code below you would see the "Hello from window shortcut!" - the menu action result, when trying to Paste (Ctrl+V) instead of actual lineEdit paste operation.

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->lineEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::ShortcutOverride) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        // Ignore only the Ctrl + V shortcut override, you can customize check for your needs
        if (keyEvent->modifiers().testFlag(Qt::ControlModifier) && keyEvent->key() == 'V') {
            qDebug() << "Ignoring" << keyEvent->modifiers() << "+" << (char)keyEvent->key() << "for" << watched;
            event->ignore();
            return true;
        }
    }

    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::on_action1_triggered()
{
    qDebug() << "Hello from window shortcut!";
}
</code>```

Sample debug output:

Ignoring QFlags(ControlModifier) + V for QLineEdit(0x575b10, name = "lineEdit")

Hello from window shortcut!

Note: Unfortunatelly you should install such filters for all widgets you want not to override the shortcuts manually.

UPDATE: Shortly - you are ignoring the underlying widget shortcut event and propagating it to the parent widget.

Below is comparison for Ctrl-Z (triggers Undo in edit) and Ctrl-V (ignored in edit instead of Paste, and triggers menu Action):

Block I - events in beginning are the same for both Ctrl-Z and ignored Ctrl-V:

QLineEdit  recieves QKeyEvent(ShortcutOverride, Key_Control, ControlModifier)

QLineEdit  recieves QKeyEvent(KeyPress, Key_Control, ControlModifier)

MainWindow recieves QKeyEvent(KeyPress, Key_Control, ControlModifier)

QLineEdit  recieves QKeyEvent(ShortcutOverride, Key_Z, ControlModifier)

Block II - where the difference happens...

For Ctrl-Z - lineEdit receives the Ctrl+Z KeyPress event, triggering the Undo operation:

QLineEdit  recieves QKeyEvent(KeyPress, Key_Z, ControlModifier)

Here the MainWindow recieves no events, not depending of has it Ctrl+Z action shortcuts or not, it's just swallowed by QLineEdit

For Ctrl-V - MainWindow receives the Ctrl+V ShortcutOverride event propagated from QLineEdit:

Ignoring "Ctrl+V" for QLineEdit code executes in filterEvent

MainWindow recieves QKeyEvent(ShortcutOverride, Key_V, ControlModifier)

"Hello from window shortcut!" code from menu Action triggered slot executed.

Here the QLineEdit receives no events after filter tells it to ignore ShortcutOverride, the MainWindow shortcut executed instead

Block III - events in ending are also the same for both Ctrl-Z and ignored Ctrl-V - just key release events:

QLineEdit  recieves QKeyEvent(KeyRelease, Key_Z, ControlModifier)

MainWindow recieves QKeyEvent(KeyRelease, Key_Z, ControlModifier)

QLineEdit  recieves QKeyEvent(KeyRelease, Key_Control)

MainWindow recieves QKeyEvent(KeyRelease, Key_Control)

P.S. I really don't know why it happens the exactly so - but this is just how it works :)

Body:
I have a Qt app with several window shortcuts defined in a Qt Designer form action. The shortcuts works well until they are pressed while the focus is on a widget that handles the same combination (overriding my window shortcut).

I would like to have the opposite behavior: window shortcuts overriding focused widget shortcuts.

I tried using eventFilter and I can catch the desired events, but I'm not able to resend them in a way that the global shortcuts are called. I could use a big switch and call the actions myself, but of course, I would like to avoid that.

I used postEvent and sendEvent inside the eventFilter using the MainWindow as the receiver, but the events are ignored:

bool MainWindow::eventFilter(QObject*, QEvent* event) {
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Z
            && keyEvent->modifiers() == Qt::ControlModifier) {
            //Calling the triggers directly works
            ui->actionUndo->trigger();
            return true;
        } else if (keyEvent->modifiers().testFlag(
                       Qt::KeypadModifier)) {
            QKeyEvent* ev2
                = new QKeyEvent(keyEvent->type(), keyEvent->key(), 0);
            qDebug() << keyEvent << ev2;
            //This sendEvent doesn't work
            QApplication::sendEvent(ui->widget, ev2);
            event->accept();
            return true;
        } else {
            return false;
        }
    }
    return false;
}

Body:
As one of the solutions you can install QEvent::ShortcutOverride event filters:

For QEvent::ShortcutOverride the receiver needs to explicitly accept
  the event to trigger the override. Calling ignore() on a key event
  will propagate it to the parent widget. The event is propagated up the
  parent widget chain until a widget accepts it or an event filter
  consumes it.

That event would be called when some widget tries to override a shortcut event, e.g. just a simple example:

I have just a new Qt app with one lineEdit and window menu with Ctrl+V shortcut (overrides the paste shortcut in lineEdit).

Here how it works:

1.Create the filtering method that would ignore (return true) the shortcut overrides (I've used MainWindow::eventFilter in sample app, however you can use any filtering object you need or want). It might be better to follow Qt docs and use the accept()/ignore() as stated above, however on my app it worked just fine without them just returning true/false.

2.Install the event filter from p.1 to widget that should ignore shortcut action if overriding.

3.I've added the menu action with Ctrl+V shortcut in designer. In code below you would see the "Hello from window shortcut!" - the menu action result, when trying to Paste (Ctrl+V) instead of actual lineEdit paste operation.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->lineEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::ShortcutOverride) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        // Ignore only the Ctrl + V shortcut override, you can customize check for your needs
        if (keyEvent->modifiers().testFlag(Qt::ControlModifier) && keyEvent->key() == 'V') {
            qDebug() << "Ignoring" << keyEvent->modifiers() << "+" << (char)keyEvent->key() << "for" << watched;
            event->ignore();
            return true;
        }
    }

    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::on_action1_triggered()
{
    qDebug() << "Hello from window shortcut!";
}

Sample debug output:

Ignoring QFlags(ControlModifier) + V for QLineEdit(0x575b10, name = "lineEdit")

Hello from window shortcut!

Note: Unfortunatelly you should install such filters for all widgets you want not to override the shortcuts manually.

UPDATE: Shortly - you are ignoring the underlying widget shortcut event and propagating it to the parent widget.

Below is comparison for Ctrl-Z (triggers Undo in edit) and Ctrl-V (ignored in edit instead of Paste, and triggers menu Action):

Block I - events in beginning are the same for both Ctrl-Z and ignored Ctrl-V:

QLineEdit  recieves QKeyEvent(ShortcutOverride, Key_Control, ControlModifier)

QLineEdit  recieves QKeyEvent(KeyPress, Key_Control, ControlModifier)

MainWindow recieves QKeyEvent(KeyPress, Key_Control, ControlModifier)

QLineEdit  recieves QKeyEvent(ShortcutOverride, Key_Z, ControlModifier)

Block II - where the difference happens...

For Ctrl-Z - lineEdit receives the Ctrl+Z KeyPress event, triggering the Undo operation:

QLineEdit  recieves QKeyEvent(KeyPress, Key_Z, ControlModifier)

Here the MainWindow recieves no events, not depending of has it Ctrl+Z action shortcuts or not, it's just swallowed by QLineEdit

For Ctrl-V - MainWindow receives the Ctrl+V ShortcutOverride event propagated from QLineEdit:

Ignoring "Ctrl+V" for QLineEdit code executes in filterEvent

MainWindow recieves QKeyEvent(ShortcutOverride, Key_V, ControlModifier)

"Hello from window shortcut!" code from menu Action triggered slot executed.

Here the QLineEdit receives no events after filter tells it to ignore ShortcutOverride, the MainWindow shortcut executed instead

Block III - events in ending are also the same for both Ctrl-Z and ignored Ctrl-V - just key release events:

QLineEdit  recieves QKeyEvent(KeyRelease, Key_Z, ControlModifier)

MainWindow recieves QKeyEvent(KeyRelease, Key_Z, ControlModifier)

QLineEdit  recieves QKeyEvent(KeyRelease, Key_Control)

MainWindow recieves QKeyEvent(KeyRelease, Key_Control)

P.S. I really don't know why it happens the exactly so - but this is just how it works :)


问:
In Delphi, Is there a way to adjust the line spacing of a TMemo?
I'm working with a TMemo component to display some text in a limited space. Currently it's using a truetype font which doesn't ship with windows and is installed by the app when it runs.

On my PC (Running Windows XP), the spacing between each line of text seems to be about eight pixels. On a different PC running Windows 7, the line spacing seems to be about 14 pixels, which is pushing the bottom row of text out of visibility on the memo.

So, My question is really this:

Is this caused by the different versions of Windows? It's all I could think that was different.

Is there some way I can adjust this value so it would be consistent across all instances of the application, wherever it was running?

Alternatatively, is there a different component I could use which might let me tweak this value?

答: In addition to Mohsen's answer I'd like to mention LMD ElPack and it's ElEdit component which also has it's own text rendering engine. Unlike TRichView ElEdit is a plain text edit / memo component, so it's a drop-in replacement for TEdit / TMemo. And line height is configurable there </p>