问:
React Native - Setting return value of function to a component's property not working
I am using the react native switch component and want to change the state of a switch (on/off) programmatically when state changes for another switch. Below is the code I have:

```<code>update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.state.somekey = !val;
    }
};

<Switch onValueChange={(v) => this.update('somekey', v)} value={this.state.somekey} />

<Switch onValueChange={(v) => this.update('togglekey', v)} value={this.state.togglekey} />
</code>```

When I click on the togglekey switch, I am expecting the somekey switch to toggle on or off, but it is not working. Any pointers?

答:
You can't mutate state directly. You must use setState instead, only then will React acknowledge the state update.

```<code>update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.setState({somekey: !val});
    }
};
</code>```

Body:
I am using the react native switch component and want to change the state of a switch (on/off) programmatically when state changes for another switch. Below is the code I have:

update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.state.somekey = !val;
    }
};

<Switch onValueChange={(v) => this.update('somekey', v)} value={this.state.somekey} />

<Switch onValueChange={(v) => this.update('togglekey', v)} value={this.state.togglekey} />

When I click on the togglekey switch, I am expecting the somekey switch to toggle on or off, but it is not working. Any pointers?

Body:
You can't mutate state directly. You must use setState instead, only then will React acknowledge the state update.

update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.setState({somekey: !val});
    }
};


来源: stackexchange

问:
Android onTouch() method doesn't work (swipe detection)
I'm programming Snake on Android with Android Studio 2.3.2

And in order to move the snake i've made an onTouchListener to detect if the user is swiping and in which direction (North, South, East, West)

In the following is the onTouch method of View.onTouchListener:

```<code>@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            prevX = event.getX();
            prevY = event.getY();

            break;
        case MotionEvent.ACTION_UP:
            float newX = event.getX();
            float newY = event.getY();

            //Calculates where we swiped

            if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                //LEFT - RiGHT Direction

                if( newX > prevX) {
                    //RIGHT
                    gameEngine.updateDirection(Direction.East);
                } else {
                    //LEFT
                    gameEngine.updateDirection(Direction.West);
                }
            } else {
                // UP-DOWN Direction
                if (newY > prevY) {
                    //DOWN
                    gameEngine.updateDirection(Direction.South);
                } else {
                    //UP
                    gameEngine.updateDirection(Direction.North);
                }
            }

            break;
    }
    return false;
}
</code>```

The problem is that it only detects LEFT and RIGHT (so EAST and WEST).
And i don't know why UP and DOWN doesn't get detected.

答:
Try the following code. It works for me.

Java:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MainSnake extends AppCompatActivity implements View.OnTouchListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_snake);
        findViewById(R.id.main_view).setOnTouchListener(this);
    }

    float prevX, prevY;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                prevX = event.getX();
                prevY = event.getY();

                return true;
            case MotionEvent.ACTION_UP:
                float newX = event.getX();
                float newY = event.getY();

                //Calculates where we swiped

                if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                    //LEFT - RiGHT Direction

                    if( newX > prevX) {
                        //RIGHT
                        Log.i("TOUCH INFO", "Right");
                    } else {
                        //LEFT
                        Log.i("TOUCH INFO", "Left");
                    }
                } else {
                    // UP-DOWN Direction
                    if (newY > prevY) {
                        //DOWN
                        Log.i("TOUCH INFO", "Down");
                    } else {
                        //UP
                        Log.i("TOUCH INFO", "Up");
                    }
                }

                break;
        }
        return false;
    }
}
</code>```

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_view">

</android.support.constraint.ConstraintLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm programming Snake on Android with Android Studio 2.3.2

And in order to move the snake i've made an onTouchListener to detect if the user is swiping and in which direction (North, South, East, West)

In the following is the onTouch method of View.onTouchListener:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            prevX = event.getX();
            prevY = event.getY();

            break;
        case MotionEvent.ACTION_UP:
            float newX = event.getX();
            float newY = event.getY();

            //Calculates where we swiped

            if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                //LEFT - RiGHT Direction

                if( newX > prevX) {
                    //RIGHT
                    gameEngine.updateDirection(Direction.East);
                } else {
                    //LEFT
                    gameEngine.updateDirection(Direction.West);
                }
            } else {
                // UP-DOWN Direction
                if (newY > prevY) {
                    //DOWN
                    gameEngine.updateDirection(Direction.South);
                } else {
                    //UP
                    gameEngine.updateDirection(Direction.North);
                }
            }

            break;
    }
    return false;
}

The problem is that it only detects LEFT and RIGHT (so EAST and WEST).
And i don't know why UP and DOWN doesn't get detected.

Body:
Try the following code. It works for me.

Java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MainSnake extends AppCompatActivity implements View.OnTouchListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_snake);
        findViewById(R.id.main_view).setOnTouchListener(this);
    }

    float prevX, prevY;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                prevX = event.getX();
                prevY = event.getY();

                return true;
            case MotionEvent.ACTION_UP:
                float newX = event.getX();
                float newY = event.getY();

                //Calculates where we swiped

                if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
                    //LEFT - RiGHT Direction

                    if( newX > prevX) {
                        //RIGHT
                        Log.i("TOUCH INFO", "Right");
                    } else {
                        //LEFT
                        Log.i("TOUCH INFO", "Left");
                    }
                } else {
                    // UP-DOWN Direction
                    if (newY > prevY) {
                        //DOWN
                        Log.i("TOUCH INFO", "Down");
                    } else {
                        //UP
                        Log.i("TOUCH INFO", "Up");
                    }
                }

                break;
        }
        return false;
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_view">

</android.support.constraint.ConstraintLayout>


问:
Eclipse 'Installing Software' - chmod failed
I'm new to Java and Eclipse and I'm not sure what this error message means:

*An error occurred while installing the items session context was:

(profile=epp.package.java,
  phase=org.eclipse.equinox.internal.p2.engine.phases.Install,
  operand=null --> [R]com.sap.ide.support.feature_root.gtk.linux.x86_64
  1.11.1, action=org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ChmodAction).
  The action chmod failed - file
  /opt/eclipse/collectSupportInformation.sh does not exist*

This happened while I was trying to install a ui tool. I've used Help->Install New Software before and it worked just fine then but now I'm getting this error no matter what I'm trying to install (I tried several different tools). What am I supposed to do?

I'm using Eclipse Luna on Ubuntu 14.04

答: I was having this issue on my mac. I got it working by moving the Eclipse app to the Applications folder (I was running it from Downloads).</p>


问:
Wordpress and ninja forms - styling forms
I need some help to style a form.

I tried some CSS but the form has no background color, could someone help me?

```<code> #nf-form-8-cont {
     background-color: rgb(214, 214, 194,0.5);
     padding: 15px;
     box-shadow: 0px 3px 5px #444;
     border-radius: 10px;
 }
</code>```

答:
You're using RGBA but have it set as RGB. Try:</p>

```<code>background-color: rgba(214, 214, 194, 0.5);
</code>```

Body:
I need some help to style a form.

I tried some CSS but the form has no background color, could someone help me?

 #nf-form-8-cont {
     background-color: rgb(214, 214, 194,0.5);
     padding: 15px;
     box-shadow: 0px 3px 5px #444;
     border-radius: 10px;
 }

Body:
You're using RGBA but have it set as RGB. Try:

background-color: rgba(214, 214, 194, 0.5);


问:
how to handle OverflowException in C#?
I need to handle OverflowException in method mul().

```<code>class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}
</code>```

But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

What can I do to fix it?

答:
mul() does not return a value when an exception is caught. Add a return statement to the catch block or at the end of the method:

```<code>public short mul()
{
    try {
        return checked((short)(a * b)); }
    catch(OverflowException exc) {
        Console.WriteLine(exc);
        return 0; // or whatever
    }
    return 0; // this goes as well
}
</code>```

Title: how to handle OverflowException in C#?

Body:
I need to handle OverflowException in method mul().

class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}

But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

What can I do to fix it?

Body:
mul() does not return a value when an exception is caught. Add a return statement to the catch block or at the end of the method:

public short mul()
{
    try {
        return checked((short)(a * b)); }
    catch(OverflowException exc) {
        Console.WriteLine(exc);
        return 0; // or whatever
    }
    return 0; // this goes as well
}


问:
PHP MySQL while loop not returning anything
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

```<code><?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "<b>Quests Available for ".$npcname."</b><br>";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>
</code>```

To go with this I have some tables whcih look like this:

```<code>npcs
name|location|npcid

quests
name|qid|npcid
</code>```

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

```<code>Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1
</code>```

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

```<code>  $listquests3['name'];
</code>```

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.

答: The results are already fetched, since there is only one rule and you fetched it in $listquests3 :). It will work if you remove that line I think.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

<?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "Quests Available for ".$npcname."
";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>

To go with this I have some tables whcih look like this:

npcs
name|location|npcid

quests
name|qid|npcid

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

  $listquests3['name'];

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.


问:
Sails Query Returns Nothing After count() Query
The following returns empty results when executed. It's fine without the Count query, but even still, the correct values are returned but the response is always empty. Am I having a race condition issue?

```<code>module.exports = {
getSites: function (req, res) {
    var sites = [];
    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

        for (index in results) {

            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                sails.log.debug(counted); // Prints correct number
                siteObj['user_count'] = counted;
                sails.log.debug(siteObj['user_count']); // Shows value is present
                sites.push(siteObj);
            });
        }
    });

    sails.log.debug(sites); // Nothing
    return res.json(sites); // Nothing
},}
</code>```

Update:

```<code>module.exports = {
getSites: function (req, res) {
    var sites = [];

    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {
        var completedResults = 0;

        for (index in results) {
            sails.log.debug(results);
            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                siteObj['user_count'] = counted;
                sites.push(siteObj);

                completedResults++;
                if(completedResults === results.length) {
                    sails.log.debug(sites);
                    res.json(sites);
                }
            });
        }
    });
},
}
</code>```

After updating to the above, logging "results" produces all the correct records. However, when returning "sites", the two entries returned are duplicates.

Update 2

I have a feeling that the async query is not completing before the next item in the for loop is being accessed, thus assigning the values to the wrong object.

Update 3
Provided logs for help.

Here is the log for the "results"

```<code>[ { locations: [],
company: 1,
name: 'N',
id: 1,
createdAt: '2017-06-06T10:07:25.000Z',
updatedAt: '2017-06-06T10:07:26.000Z' },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z' } ]
</code>```

This is the log for "sites"

```<code>[ { locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 } ]
</code>```

答:
It's because

```<code>sails.log.debug(sites); // Nothing
return res.json(sites); // Nothing
</code>```

Executes before

```<code>sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
    if (err) {
        sails.log.error(err);
    }
    sails.log.debug(counted); // Prints correct number
    siteObj['user_count'] = counted;
    sails.log.debug(siteObj['user_count']); // Shows value is present
    sites.push(siteObj);
});
</code>```

To fix it, you need to call sails.log.debug and res.json once the async exec function has completed for all results. Like this:

```<code>module.exports = {
    getSites: function (req, res) {
        const sites = [];
        Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

            let completedResults = 0;

            for (index in results) {

                const siteObj = results[index];

                sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                    if (err) {
                        sails.log.error(err);
                    }
                    sails.log.debug(counted); // Prints correct number
                    siteObj['user_count'] = counted;
                    sails.log.debug(siteObj['user_count']); // Shows value is present
                    sites.push(siteObj);

                    completedResults++;
                    if(completedResults === results.length) {
                        sails.log.debug(sites);
                        res.json(sites);
                    }
                });
            }
        });

    }
}
</code>```

Body:
The following returns empty results when executed. It's fine without the Count query, but even still, the correct values are returned but the response is always empty. Am I having a race condition issue?

module.exports = {
getSites: function (req, res) {
    var sites = [];
    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

        for (index in results) {

            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                sails.log.debug(counted); // Prints correct number
                siteObj['user_count'] = counted;
                sails.log.debug(siteObj['user_count']); // Shows value is present
                sites.push(siteObj);
            });
        }
    });

    sails.log.debug(sites); // Nothing
    return res.json(sites); // Nothing
},}

Update:

module.exports = {
getSites: function (req, res) {
    var sites = [];

    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {
        var completedResults = 0;

        for (index in results) {
            sails.log.debug(results);
            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                siteObj['user_count'] = counted;
                sites.push(siteObj);

                completedResults++;
                if(completedResults === results.length) {
                    sails.log.debug(sites);
                    res.json(sites);
                }
            });
        }
    });
},
}

After updating to the above, logging "results" produces all the correct records. However, when returning "sites", the two entries returned are duplicates.

Update 2

I have a feeling that the async query is not completing before the next item in the for loop is being accessed, thus assigning the values to the wrong object.

Update 3
Provided logs for help.

Here is the log for the "results"

[ { locations: [],
company: 1,
name: 'N',
id: 1,
createdAt: '2017-06-06T10:07:25.000Z',
updatedAt: '2017-06-06T10:07:26.000Z' },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z' } ]

This is the log for "sites"

[ { locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 } ]

Body:
It's because

sails.log.debug(sites); // Nothing
return res.json(sites); // Nothing

Executes before

sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
    if (err) {
        sails.log.error(err);
    }
    sails.log.debug(counted); // Prints correct number
    siteObj['user_count'] = counted;
    sails.log.debug(siteObj['user_count']); // Shows value is present
    sites.push(siteObj);
});

To fix it, you need to call sails.log.debug and res.json once the async exec function has completed for all results. Like this:

module.exports = {
    getSites: function (req, res) {
        const sites = [];
        Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

            let completedResults = 0;

            for (index in results) {

                const siteObj = results[index];

                sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                    if (err) {
                        sails.log.error(err);
                    }
                    sails.log.debug(counted); // Prints correct number
                    siteObj['user_count'] = counted;
                    sails.log.debug(siteObj['user_count']); // Shows value is present
                    sites.push(siteObj);

                    completedResults++;
                    if(completedResults === results.length) {
                        sails.log.debug(sites);
                        res.json(sites);
                    }
                });
            }
        });

    }
}


问:
Merging different SQL scripts into one script
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

```<code>select count(*) as total_rows from <table_name>
</code>```

To count the duplicated rows:

```<code>select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1
</code>```

To count the unique rows:

```<code>select COUNT(DISTINCT <column_name>) as total_unique from <table_name>
</code>```

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

答:
Try to do it this way:</p>

```<code>select count(*) as total_rows,COUNT(DISTINCT <column_name>) as total_unique,
    (select COUNT (<column_name>)
     from <table_name>
     group by (<column_name>)
     HAVING count(<column_name>) > 1) as total_duplicate
from <table_name>
</code>```

Body:
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

select count(*) as total_rows from <table_name>

To count the duplicated rows:

select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1

To count the unique rows:

select COUNT(DISTINCT <column_name>) as total_unique from <table_name>

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

Body:
Try to do it this way:

select count(*) as total_rows,COUNT(DISTINCT <column_name>) as total_unique,
    (select COUNT (<column_name>)
     from <table_name>
     group by (<column_name>)
     HAVING count(<column_name>) > 1) as total_duplicate
from <table_name>


问:
Styling for Grid inside Another Grid
I have a GridView(B) inside a GridView(A).
The style for GridView-A is different from style for GridView-B, but the issue arises when my GridView-B inherits all the style from GridView-A.

I don't want that to happen.

Is their any way, I can achieve this in xaml only ?

答:
Just Follow the follwoing steps and let me know if you have any problem with this. Out of these you meight be aware already. May be you miss something.

1) Add ResourceDictionary as style sheet.

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:XYZApplication">
 <!-- Style 1-->
  <Style x:Key="GridStyle1" TargetType="{x:Type Grid}">
        <Setter Property="Background" Value="BlanchedAlmond"></Setter>
        <Setter Property="Margin" Value="1,1,1,1"></Setter>
    </Style>
<!-- Style 2-->
    <Style x:Key="GridStyle2" TargetType="{x:Type Grid}">
        <Setter Property="Background" Value="Aqua"></Setter>
        <Setter Property="Margin" Value="5,5,5,5"></Setter>
    </Style>
</ResourceDictionary>
</code>```

2) Add resource file into your user control/window as follows...

```<code><UserControl x:Class="XYZApplication.Views.Payment"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:XYZApplication.Views"
             mc:Ignorable="d">

 <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Style/Styles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
</UserControl>
</code>```

3) Use those specific styles to designated grid inside the usercontrol/window

```<code> <Grid Style="{StaticResource GridStyle1}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
       <Grid Grid.Column="1" Grid.Row="1"  Style="{StaticResource GridStyle2}" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
        <Label  Grid.Column="0" Grid.Row="0">Bank Name</Label>
            <Label  Grid.Column="1" Grid.Row="0">Branch</Label>
            <Label  Grid.Column="2" Grid.Row="0">Account holder</Label>
            <Label  Grid.Column="3" Grid.Row="0">Account Number</Label>
            <Label  Grid.Column="4" Grid.Row="0">Balance</Label>
            <Label  Grid.Column="0" Grid.Row="1">Bank of ...</Label>
            <Label  Grid.Column="1" Grid.Row="1">...Branch</Label>
            <Label  Grid.Column="2" Grid.Row="1">My Name</Label>
            <Label  Grid.Column="3" Grid.Row="1">Account Number 123</Label>
            <Label  Grid.Column="4" Grid.Row="1">1 billion</Label>
        </Grid>
    </Grid>
</code>```

You can add these both styles in code behind also.
Hope it helps!!!

Title: Styling for Grid inside Another Grid

Body:
Just Follow the follwoing steps and let me know if you have any problem with this. Out of these you meight be aware already. May be you miss something.

1) Add ResourceDictionary as style sheet.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:XYZApplication">
 <!-- Style 1-->
  <Style x:Key="GridStyle1" TargetType="{x:Type Grid}">
        <Setter Property="Background" Value="BlanchedAlmond"></Setter>
        <Setter Property="Margin" Value="1,1,1,1"></Setter>
    </Style>
<!-- Style 2-->
    <Style x:Key="GridStyle2" TargetType="{x:Type Grid}">
        <Setter Property="Background" Value="Aqua"></Setter>
        <Setter Property="Margin" Value="5,5,5,5"></Setter>
    </Style>
</ResourceDictionary>

2) Add resource file into your user control/window as follows...

<UserControl x:Class="XYZApplication.Views.Payment"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:XYZApplication.Views"
             mc:Ignorable="d">

 <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Style/Styles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
</UserControl>

3) Use those specific styles to designated grid inside the usercontrol/window

 <Grid Style="{StaticResource GridStyle1}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
       <Grid Grid.Column="1" Grid.Row="1"  Style="{StaticResource GridStyle2}" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
        <Label  Grid.Column="0" Grid.Row="0">Bank Name</Label>
            <Label  Grid.Column="1" Grid.Row="0">Branch</Label>
            <Label  Grid.Column="2" Grid.Row="0">Account holder</Label>
            <Label  Grid.Column="3" Grid.Row="0">Account Number</Label>
            <Label  Grid.Column="4" Grid.Row="0">Balance</Label>
            <Label  Grid.Column="0" Grid.Row="1">Bank of ...</Label>
            <Label  Grid.Column="1" Grid.Row="1">...Branch</Label>
            <Label  Grid.Column="2" Grid.Row="1">My Name</Label>
            <Label  Grid.Column="3" Grid.Row="1">Account Number 123</Label>
            <Label  Grid.Column="4" Grid.Row="1">1 billion</Label>
        </Grid>
    </Grid>

You can add these both styles in code behind also.
Hope it helps!!!


问:
How to read tabular format pdf document using python pandas?
I want to read one pdf file which is in below format-

data.pdf

```<code>       Jan1 Jan2 Jan3 Jan4 Jan5 total
ABC    1.0  2.0  3.0  4.0  5.0  15.0
PQR    1    2    3    4    5    15
XYZ    2    2    2    2    2    10
</code>```

I'm trying to read this file using python pandas but I didn't get any success yet. Actually I want to convert this file in csv format like below -

output.csv

```<code>names,Jan1,Jan2,Jan3,Jan4,Jan5,total
ABC,1.0,2.0,3.0,4.0,5.0,15.0
PQR,1,2,3,4,5,15
XYZ,2,2,2,2,2,10
</code>```

I already tried with pdfminer but didn't get any success. It's html output only gives me blank pages.

Is their any way to read pdf file using python pandas or can we convert pdf to any format and then read it using python pandas?

答:
If you have tabula installed then:

```<code>from tabula import read_pdf
data = read_pdf('data.pdf')
</code>```

then you can print your data

```<code>print (df)
</code>```

I hope this will help you !

Body:
I want to read one pdf file which is in below format-

data.pdf

       Jan1 Jan2 Jan3 Jan4 Jan5 total
ABC    1.0  2.0  3.0  4.0  5.0  15.0
PQR    1    2    3    4    5    15
XYZ    2    2    2    2    2    10

I'm trying to read this file using python pandas but I didn't get any success yet. Actually I want to convert this file in csv format like below -

output.csv

names,Jan1,Jan2,Jan3,Jan4,Jan5,total
ABC,1.0,2.0,3.0,4.0,5.0,15.0
PQR,1,2,3,4,5,15
XYZ,2,2,2,2,2,10

I already tried with pdfminer but didn't get any success. It's html output only gives me blank pages.

Is their any way to read pdf file using python pandas or can we convert pdf to any format and then read it using python pandas?

Body:
If you have tabula installed then:

from tabula import read_pdf
data = read_pdf('data.pdf')

then you can print your data

print (df)

I hope this will help you !


答:
When exception is thrown you write something to console but don't return any value.

Your method return value is short so you should return some value in catch (because method should return some short value in every execution path or throw):

```<code>try
{
    return checked((short)(a * b));
}

catch(OverflowException exc)
{
    Console.WriteLine(exc);

    throw;
}
</code>```

Title: how to handle OverflowException in C#?

Body:
When exception is thrown you write something to console but don't return any value.

Your method return value is short so you should return some value in catch (because method should return some short value in every execution path or throw):

try
{
    return checked((short)(a * b));
}

catch(OverflowException exc)
{
    Console.WriteLine(exc);

    throw;
}


问:
How to handle bad data quality in a SQL query
The code below is a sample of grouped data containing Temperature (bear in mind it's temperature taken of a human being in hospital) from our source system.

Obviously the data is horrible but wondered if it was possible to somehow turn this data into and INT as we have a UOM (Unit of measure) field so we only need the number.

Data issues:

88 degree is obviously Fahrenheit and not Celsius
3635 would be 36.35
.368 would be 36.8
37.3. would be 37.3
.37.7 would be 37.7
377 would be 37.7
.3.8 would be 38

I think any other variation should just be excluded invalid data to be fair as cannot accurately make an informed assumption.

```<code>DECLARE @Test TABLE (
    [Temperature] VARCHAR(500),
    [Count] VARCHAR(50)
                 )
INSERT INTO @Test ([Temperature],[Count])
 VALUES

('34.4                oC',' 9   '),
('36.02               oC',' 1   '),
('36.36               oC',' 3   '),
('36.5                oC',' 5593    '),
('36.5.               oC',' 1   '),
('36.6.               oC',' 2   '),
('36.74               oC',' 2   '),
('36.82               oC',' 2   '),
('37.36               oC',' 2   '),
('37.49               oC',' 4   '),
('40                  oC',' 1   '),
('88                  oC',' 1   '),
('        3635                  oC','   1   '),
('  .368              oC',' 1   '),
('33.5                oC',' 1   '),
('35.2                oC',' 84  '),
('35.20               oC',' 1   '),
('35.99               oC',' 1   '),
('36.35               oC',' 2   '),
('37.3.               oC',' 1   '),
('39.5                oC',' 5   '),
('86                  oC',' 1   '),
('         356                  oC','   12  '),
('         364                  oC','   72  '),
('         379                  oC','   9   '),
('         385                  oC','   2   '),
('        3535                  oC','   1   '),
('  .37.7             oC',' 1   '),
('35.5                oC',' 290 '),
('35.87               oC',' 1   '),
('36..6               oC',' 1   '),
('36.25               oC',' 2   '),
('36.45               oC',' 2   '),
('36.62               oC',' 2   '),
('36.68               oC',' 5   '),
('36.8.               oC',' 2   '),
('37.03               oC',' 5   '),
('37.1                oC',' 3610    '),
('37.16               oC',' 3   '),
('37.2      oCC000715799',' 1   '),
('37.27               oC',' 2   '),
('37.91               oC',' 1   '),
('38.9                oC',' 28  '),
('63.5                oC',' 1   '),
('71                  oC',' 1   '),
('         377                  oC','   8   '),
('               36.5 oC',' 1   '),
(' 3.4                oC',' 3   '),
(' 3.7                oC',' 3   '),
('36.59               oC',' 1   '),
('36.67               oC',' 5   '),
('37.13               oC',' 1   '),
('37.18               oC',' 1   '),
('37.24               oC',' 1   '),
('39.7                oC',' 5   '),
('76                  oC',' 2   '),
('80                  oC',' 2   '),
('         347                  oC','   1   '),
('         352                  oC','   2   '),
('         368                  oC','   64  '),
('        3602                  oC','   1   '),
('        3688                  oC','   1   '),
('  .36.4             oC',' 1   '),
('  .8                oC',' 1   '),
(' 3.2                oC',' 2   '),
('34.3                oC',' 5   '),
('34.9                oC',' 20  '),
('35                  oC',' 124 '),
('35.81               oC',' 1   '),
('36.17               oC',' 2   '),
('36.23               oC',' 1   '),
('36.37               oC',' 2   '),
('36.38               oC',' 4   '),
('36.42               oC',' 1   '),
('36.76               oC',' 2   '),
('37..2               oC',' 1   '),
('37.00               oC',' 4   '),
('37.07               oC',' 6   '),
('37.12               oC',' 2   '),
('37.2                oC',' 3151    '),
('37.48               oC',' 2   '),
('39.                 oC',' 1   '),
('39.2                oC',' 9   '),
('39.9                oC',' 2   '),
('         370                  oC','   1   '),
('30.1                oC',' 1   '),
('34.1                oC',' 2   '),
('34.8                oC',' 17  '),
('35.43               oC',' 1   '),
('36..8               oC',' 2   '),
('36.05               oC',' 1   '),
('36.21               oC',' 4   '),
('36.31               oC',' 2   '),
('36.41               oC',' 1   '),
('36.58               oC',' 8   '),
('36.8                oC',' 8134    '),
('36.81               oC',' 3   '),
('36.88               oC',' 2   '),
('36.89               oC',' 2   '),
('36.99               oC',' 4   '),
('37.01               oC',' 6   '),
('37.14               oC',' 3   '),
('37.33               oC',' 1   '),
('37.37               oC',' 6   '),
('37.44               oC',' 1   '),
('37.59               oC',' 2   '),
('38.5                oC',' 85  '),
('39.4                oC',' 9   '),
('78                  oC',' 2   '),
('92                  oC',' 1   '),
('         361                  oC','   19  '),
('         383                  oC','   1   '),
('         391                  oC','   1   '),
('        3642                  oC','   1   '),
('        3699                  oC','   2   '),
('               37.6 oC',' 1   '),
('35.59               oC',' 1   '),
('35.69               oC',' 1   '),
('35.90               oC',' 1   '),
('36..9               oC',' 1   '),
('36.08               oC',' 2   '),
('36.27               oC',' 1   '),
('36.365              oC',' 1   '),
('36.51               oC',' 1   '),
('36.78               oC',' 4   '),
('36.84               oC',' 1   '),
('36.85               oC',' 3   '),
('36.97               oC',' 2   '),
('37.29               oC',' 1   '),
('37.3                oC',' 2306    '),
('37.8                oC',' 730 '),
('38.08               oC',' 1   '),
('38.4                oC',' 113 '),
('38.49               oC',' 1   '),
('38.7                oC',' 53  '),
('39.3                oC',' 10  '),
('70                  oC',' 2   '),
('         357                  oC','   5   '),
('         362                  oC','   49  '),
('         396.8                oC','   1   '),
('        3700                  oC','   1   '),
('        3752                  oC','   1   '),
('  .381              oC',' 1   '),
(' 0.37               oC',' 1   '),
(' 3.1                oC',' 1   '),
('14                  oC',' 1   '),
('27                  oC',' 1   '),
('34.2                oC',' 5   '),
('34.5                oC',' 22  '),
('35.9                oC',' 633 '),
('36.44               oC',' 2   '),
('36.57               oC',' 1   '),
('36.65               oC',' 1   '),
('36.66               oC',' 3   '),
('37.04               oC',' 7   '),
('65.9                oC',' 1   '),
('82                  oC',' 2   '),
('         118                  oC','   1   '),
('         358                  oC','   6   '),
('         381                  oC','   2   '),
('         396.6                oC','   1   '),
('        3704                  oC','   1   '),
('        3801                  oC','   1   '),
('      ',' 195340  '),
('                362 oC',' 1   '),
('  .374              oC',' 1   '),
(' 3.6                oC',' 3   '),
('26.5                oC',' 1   '),
('35.0                oC',' 28  '),
('35.79               oC',' 1   '),
('36..7               oC',' 1   '),
('36.00               oC',' 2   '),
('36.18               oC',' 1   '),
('36.48               oC',' 4   '),
('36.49               oC',' 3   '),
('37.19               oC',' 2   '),
('37.46               oC',' 1   '),
('37.9                oC',' 465 '),
('38.12               oC',' 1   '),
('39                  oC',' 25  '),
('         351                  oC','   2   '),
('         369.                 oC','   1   '),
('         389                  oC','   1   '),
('        3736                  oC','   1   '),
('  NULL    ',' 7   '),
('35.98               oC',' 1   '),
('36                  oC',' 2948    '),
('36.28               oC',' 1   '),
('36.69               oC',' 1   '),
('36.72               oC',' 2   '),
('36.77               oC',' 4   '),
('36.98               oC',' 7   '),
('37.05               oC',' 3   '),
('37.06               oC',' 2   '),
('37.15               oC',' 3   '),
('37.25               oC',' 5   '),
('37.26               oC',' 3   '),
('37.39               oC',' 3   '),
('37.42               oC',' 1   '),
('37.68               oC',' 3   '),
('38.3                oC',' 160 '),
('38.6.               oC',' 1   '),
('         376                  oC','   18  '),
('        3617                  oC','   1   '),
('        3703                  oC','   1   '),
(' 3.8                oC',' 2   '),
(' 7.6                oC',' 1   '),
('30.6                oC',' 1   '),
('34                  oC',' 3   '),
('34.7                oC',' 9   '),
('35.06               oC',' 1   '),
('35.7                oC',' 324 '),
('35.74               oC',' 1   '),
('36.01               oC',' 2   '),
('36.1                oC',' 1517    '),
('36.12               oC',' 1   '),
('36.4                oC',' 5001    '),
('36.6                oC',' 7044    '),
('36.79               oC',' 5   '),
('36.86               oC',' 1   '),
('36.90               oC',' 1   '),
('36.93               oC',' 1   '),
('37.30               oC',' 1   '),
('37.92               oC',' 1   '),
('38.                 oC',' 5   '),
('38.6                oC',' 65  '),
('38.8                oC',' 46  '),
('97                  oC',' 1   '),
('         354                  oC','   4   '),
('         355                  oC','   5   '),
('         365                  oC','   107 '),
('        3654                  oC','   1   '),
('35.8                oC',' 495 '),
('36.09               oC',' 6   '),
('36.2                oC',' 2526    '),
('36.3.               oC',' 1   '),
('36.47               oC',' 1   '),
('36.53               oC',' 2   '),
('36.9                oC',' 5449    '),
('37.0                oC',' 1209    '),
('37.1.               oC',' 1   '),
('37.32               oC',' 2   '),
('37.38               oC',' 5   '),
('37.45               oC',' 1   '),
('37.5                oC',' 1477    '),
('37.6                oC',' 1101    '),
('37.80               oC',' 1   '),
('38.1                oC',' 215 '),
('40.2                oC',' 1   '),
('62                  oC',' 1   '),
('         366                  oC','   61  '),
('         375                  oC','   28  '),
('16                  oC',' 1   '),
('34.0                oC',' 1   '),
('35.                 oC',' 3   '),
('35.1                oC',' 61  '),
('35.23               oC',' 1   '),
('35.58               oC',' 2   '),
('36.                 oC',' 59  '),
('36.03               oC',' 1   '),
('36.16               oC',' 2   '),
('36.94               oC',' 2   '),
('37.08               oC',' 7   '),
('37.21               oC',' 1   '),
('37.47               oC',' 1   '),
('39.8                oC',' 3   '),
('         346                  oC','   1   '),
('         353                  oC','   2   '),
('         369                  oC','   57  '),
('         374                  oC','   28  '),
('        3677                  oC','   1   '),
('               37.4 oC',' 1   '),
('34.6                oC',' 15  '),
('35.3                oC',' 74  '),
('35.4                oC',' 120 '),
('35.6                oC',' 320 '),
('36.06               oC',' 1   '),
('36.07               oC',' 2   '),
('36.14               oC',' 1   '),
('36.19               oC',' 1   '),
('36.54               oC',' 1   '),
('36.71               oC',' 1   '),
('36.92               oC',' 1   '),
('37.50               oC',' 1   '),
('37.54               oC',' 1   '),
('37.7                oC',' 836 '),
('39.0                oC',' 8   '),
('39.6                oC',' 3   '),
('60                  oC',' 1   '),
('         127                  oC','   1   '),
('         336.8                oC','   1   '),
('        1500                  oC','   1   '),
('               36.4 oC',' 1   '),
('36.0                oC',' 829 '),
('36.3                oC',' 3192    '),
('36.56               oC',' 3   '),
('36.63               oC',' 2   '),
('36.7                oC',' 6348    '),
('36.73               oC',' 3   '),
('36.96               oC',' 4   '),
('37.                 oC',' 64  '),
('37.4                oC',' 1861    '),
('37.69               oC',' 1   '),
('38.01               oC',' 1   '),
('93                  oC',' 1   '),
('         351.                 oC','   1   '),
('         371                  oC','   24  '),
('         372                  oC','   45  '),
('         373                  oC','   30  '),
('        3722                  oC','   1   '),
('  .3.8              oC',' 1   '),
('26.1                oC',' 1   '),
('35.97               oC',' 4   '),
('36.61               oC',' 3   '),
('37                  oC',' 4890    '),
('37.02               oC',' 3   '),
('37.66               oC',' 1   '),
('38                  oC',' 367 '),
('38.0                oC',' 72  '),
('38.2                oC',' 225 '),
('39.1                oC',' 22  '),
('         359                  oC','   14  '),
('         360                  oC','   3   '),
('         363                  oC','   49  '),
('         367                  oC','   112 '),
('         378                  oC','   8   ')

Select

*
from @Test
</code>```

答:
This worked fine but doesn't account for the DQ issues which we are keeping in as this is what was recorded </p>

```<code>TRY_CAST(REPLACE(Temperature, 'oC', '') AS DECIMAL(19,8))
</code>```

Body:
The code below is a sample of grouped data containing Temperature (bear in mind it's temperature taken of a human being in hospital) from our source system.

Obviously the data is horrible but wondered if it was possible to somehow turn this data into and INT as we have a UOM (Unit of measure) field so we only need the number.

Data issues:

88 degree is obviously Fahrenheit and not Celsius
3635 would be 36.35
.368 would be 36.8
37.3. would be 37.3
.37.7 would be 37.7
377 would be 37.7
.3.8 would be 38

I think any other variation should just be excluded invalid data to be fair as cannot accurately make an informed assumption.

DECLARE @Test TABLE (
    [Temperature] VARCHAR(500),
    [Count] VARCHAR(50)
                 )
INSERT INTO @Test ([Temperature],[Count])
 VALUES

('34.4                oC',' 9   '),
('36.02               oC',' 1   '),
('36.36               oC',' 3   '),
('36.5                oC',' 5593    '),
('36.5.               oC',' 1   '),
('36.6.               oC',' 2   '),
('36.74               oC',' 2   '),
('36.82               oC',' 2   '),
('37.36               oC',' 2   '),
('37.49               oC',' 4   '),
('40                  oC',' 1   '),
('88                  oC',' 1   '),
('        3635                  oC','   1   '),
('  .368              oC',' 1   '),
('33.5                oC',' 1   '),
('35.2                oC',' 84  '),
('35.20               oC',' 1   '),
('35.99               oC',' 1   '),
('36.35               oC',' 2   '),
('37.3.               oC',' 1   '),
('39.5                oC',' 5   '),
('86                  oC',' 1   '),
('         356                  oC','   12  '),
('         364                  oC','   72  '),
('         379                  oC','   9   '),
('         385                  oC','   2   '),
('        3535                  oC','   1   '),
('  .37.7             oC',' 1   '),
('35.5                oC',' 290 '),
('35.87               oC',' 1   '),
('36..6               oC',' 1   '),
('36.25               oC',' 2   '),
('36.45               oC',' 2   '),
('36.62               oC',' 2   '),
('36.68               oC',' 5   '),
('36.8.               oC',' 2   '),
('37.03               oC',' 5   '),
('37.1                oC',' 3610    '),
('37.16               oC',' 3   '),
('37.2      oCC000715799',' 1   '),
('37.27               oC',' 2   '),
('37.91               oC',' 1   '),
('38.9                oC',' 28  '),
('63.5                oC',' 1   '),
('71                  oC',' 1   '),
('         377                  oC','   8   '),
('               36.5 oC',' 1   '),
(' 3.4                oC',' 3   '),
(' 3.7                oC',' 3   '),
('36.59               oC',' 1   '),
('36.67               oC',' 5   '),
('37.13               oC',' 1   '),
('37.18               oC',' 1   '),
('37.24               oC',' 1   '),
('39.7                oC',' 5   '),
('76                  oC',' 2   '),
('80                  oC',' 2   '),
('         347                  oC','   1   '),
('         352                  oC','   2   '),
('         368                  oC','   64  '),
('        3602                  oC','   1   '),
('        3688                  oC','   1   '),
('  .36.4             oC',' 1   '),
('  .8                oC',' 1   '),
(' 3.2                oC',' 2   '),
('34.3                oC',' 5   '),
('34.9                oC',' 20  '),
('35                  oC',' 124 '),
('35.81               oC',' 1   '),
('36.17               oC',' 2   '),
('36.23               oC',' 1   '),
('36.37               oC',' 2   '),
('36.38               oC',' 4   '),
('36.42               oC',' 1   '),
('36.76               oC',' 2   '),
('37..2               oC',' 1   '),
('37.00               oC',' 4   '),
('37.07               oC',' 6   '),
('37.12               oC',' 2   '),
('37.2                oC',' 3151    '),
('37.48               oC',' 2   '),
('39.                 oC',' 1   '),
('39.2                oC',' 9   '),
('39.9                oC',' 2   '),
('         370                  oC','   1   '),
('30.1                oC',' 1   '),
('34.1                oC',' 2   '),
('34.8                oC',' 17  '),
('35.43               oC',' 1   '),
('36..8               oC',' 2   '),
('36.05               oC',' 1   '),
('36.21               oC',' 4   '),
('36.31               oC',' 2   '),
('36.41               oC',' 1   '),
('36.58               oC',' 8   '),
('36.8                oC',' 8134    '),
('36.81               oC',' 3   '),
('36.88               oC',' 2   '),
('36.89               oC',' 2   '),
('36.99               oC',' 4   '),
('37.01               oC',' 6   '),
('37.14               oC',' 3   '),
('37.33               oC',' 1   '),
('37.37               oC',' 6   '),
('37.44               oC',' 1   '),
('37.59               oC',' 2   '),
('38.5                oC',' 85  '),
('39.4                oC',' 9   '),
('78                  oC',' 2   '),
('92                  oC',' 1   '),
('         361                  oC','   19  '),
('         383                  oC','   1   '),
('         391                  oC','   1   '),
('        3642                  oC','   1   '),
('        3699                  oC','   2   '),
('               37.6 oC',' 1   '),
('35.59               oC',' 1   '),
('35.69               oC',' 1   '),
('35.90               oC',' 1   '),
('36..9               oC',' 1   '),
('36.08               oC',' 2   '),
('36.27               oC',' 1   '),
('36.365              oC',' 1   '),
('36.51               oC',' 1   '),
('36.78               oC',' 4   '),
('36.84               oC',' 1   '),
('36.85               oC',' 3   '),
('36.97               oC',' 2   '),
('37.29               oC',' 1   '),
('37.3                oC',' 2306    '),
('37.8                oC',' 730 '),
('38.08               oC',' 1   '),
('38.4                oC',' 113 '),
('38.49               oC',' 1   '),
('38.7                oC',' 53  '),
('39.3                oC',' 10  '),
('70                  oC',' 2   '),
('         357                  oC','   5   '),
('         362                  oC','   49  '),
('         396.8                oC','   1   '),
('        3700                  oC','   1   '),
('        3752                  oC','   1   '),
('  .381              oC',' 1   '),
(' 0.37               oC',' 1   '),
(' 3.1                oC',' 1   '),
('14                  oC',' 1   '),
('27                  oC',' 1   '),
('34.2                oC',' 5   '),
('34.5                oC',' 22  '),
('35.9                oC',' 633 '),
('36.44               oC',' 2   '),
('36.57               oC',' 1   '),
('36.65               oC',' 1   '),
('36.66               oC',' 3   '),
('37.04               oC',' 7   '),
('65.9                oC',' 1   '),
('82                  oC',' 2   '),
('         118                  oC','   1   '),
('         358                  oC','   6   '),
('         381                  oC','   2   '),
('         396.6                oC','   1   '),
('        3704                  oC','   1   '),
('        3801                  oC','   1   '),
('      ',' 195340  '),
('                362 oC',' 1   '),
('  .374              oC',' 1   '),
(' 3.6                oC',' 3   '),
('26.5                oC',' 1   '),
('35.0                oC',' 28  '),
('35.79               oC',' 1   '),
('36..7               oC',' 1   '),
('36.00               oC',' 2   '),
('36.18               oC',' 1   '),
('36.48               oC',' 4   '),
('36.49               oC',' 3   '),
('37.19               oC',' 2   '),
('37.46               oC',' 1   '),
('37.9                oC',' 465 '),
('38.12               oC',' 1   '),
('39                  oC',' 25  '),
('         351                  oC','   2   '),
('         369.                 oC','   1   '),
('         389                  oC','   1   '),
('        3736                  oC','   1   '),
('  NULL    ',' 7   '),
('35.98               oC',' 1   '),
('36                  oC',' 2948    '),
('36.28               oC',' 1   '),
('36.69               oC',' 1   '),
('36.72               oC',' 2   '),
('36.77               oC',' 4   '),
('36.98               oC',' 7   '),
('37.05               oC',' 3   '),
('37.06               oC',' 2   '),
('37.15               oC',' 3   '),
('37.25               oC',' 5   '),
('37.26               oC',' 3   '),
('37.39               oC',' 3   '),
('37.42               oC',' 1   '),
('37.68               oC',' 3   '),
('38.3                oC',' 160 '),
('38.6.               oC',' 1   '),
('         376                  oC','   18  '),
('        3617                  oC','   1   '),
('        3703                  oC','   1   '),
(' 3.8                oC',' 2   '),
(' 7.6                oC',' 1   '),
('30.6                oC',' 1   '),
('34                  oC',' 3   '),
('34.7                oC',' 9   '),
('35.06               oC',' 1   '),
('35.7                oC',' 324 '),
('35.74               oC',' 1   '),
('36.01               oC',' 2   '),
('36.1                oC',' 1517    '),
('36.12               oC',' 1   '),
('36.4                oC',' 5001    '),
('36.6                oC',' 7044    '),
('36.79               oC',' 5   '),
('36.86               oC',' 1   '),
('36.90               oC',' 1   '),
('36.93               oC',' 1   '),
('37.30               oC',' 1   '),
('37.92               oC',' 1   '),
('38.                 oC',' 5   '),
('38.6                oC',' 65  '),
('38.8                oC',' 46  '),
('97                  oC',' 1   '),
('         354                  oC','   4   '),
('         355                  oC','   5   '),
('         365                  oC','   107 '),
('        3654                  oC','   1   '),
('35.8                oC',' 495 '),
('36.09               oC',' 6   '),
('36.2                oC',' 2526    '),
('36.3.               oC',' 1   '),
('36.47               oC',' 1   '),
('36.53               oC',' 2   '),
('36.9                oC',' 5449    '),
('37.0                oC',' 1209    '),
('37.1.               oC',' 1   '),
('37.32               oC',' 2   '),
('37.38               oC',' 5   '),
('37.45               oC',' 1   '),
('37.5                oC',' 1477    '),
('37.6                oC',' 1101    '),
('37.80               oC',' 1   '),
('38.1                oC',' 215 '),
('40.2                oC',' 1   '),
('62                  oC',' 1   '),
('         366                  oC','   61  '),
('         375                  oC','   28  '),
('16                  oC',' 1   '),
('34.0                oC',' 1   '),
('35.                 oC',' 3   '),
('35.1                oC',' 61  '),
('35.23               oC',' 1   '),
('35.58               oC',' 2   '),
('36.                 oC',' 59  '),
('36.03               oC',' 1   '),
('36.16               oC',' 2   '),
('36.94               oC',' 2   '),
('37.08               oC',' 7   '),
('37.21               oC',' 1   '),
('37.47               oC',' 1   '),
('39.8                oC',' 3   '),
('         346                  oC','   1   '),
('         353                  oC','   2   '),
('         369                  oC','   57  '),
('         374                  oC','   28  '),
('        3677                  oC','   1   '),
('               37.4 oC',' 1   '),
('34.6                oC',' 15  '),
('35.3                oC',' 74  '),
('35.4                oC',' 120 '),
('35.6                oC',' 320 '),
('36.06               oC',' 1   '),
('36.07               oC',' 2   '),
('36.14               oC',' 1   '),
('36.19               oC',' 1   '),
('36.54               oC',' 1   '),
('36.71               oC',' 1   '),
('36.92               oC',' 1   '),
('37.50               oC',' 1   '),
('37.54               oC',' 1   '),
('37.7                oC',' 836 '),
('39.0                oC',' 8   '),
('39.6                oC',' 3   '),
('60                  oC',' 1   '),
('         127                  oC','   1   '),
('         336.8                oC','   1   '),
('        1500                  oC','   1   '),
('               36.4 oC',' 1   '),
('36.0                oC',' 829 '),
('36.3                oC',' 3192    '),
('36.56               oC',' 3   '),
('36.63               oC',' 2   '),
('36.7                oC',' 6348    '),
('36.73               oC',' 3   '),
('36.96               oC',' 4   '),
('37.                 oC',' 64  '),
('37.4                oC',' 1861    '),
('37.69               oC',' 1   '),
('38.01               oC',' 1   '),
('93                  oC',' 1   '),
('         351.                 oC','   1   '),
('         371                  oC','   24  '),
('         372                  oC','   45  '),
('         373                  oC','   30  '),
('        3722                  oC','   1   '),
('  .3.8              oC',' 1   '),
('26.1                oC',' 1   '),
('35.97               oC',' 4   '),
('36.61               oC',' 3   '),
('37                  oC',' 4890    '),
('37.02               oC',' 3   '),
('37.66               oC',' 1   '),
('38                  oC',' 367 '),
('38.0                oC',' 72  '),
('38.2                oC',' 225 '),
('39.1                oC',' 22  '),
('         359                  oC','   14  '),
('         360                  oC','   3   '),
('         363                  oC','   49  '),
('         367                  oC','   112 '),
('         378                  oC','   8   ')

Select

*
from @Test

Body:
This worked fine but doesn't account for the DQ issues which we are keeping in as this is what was recorded

TRY_CAST(REPLACE(Temperature, 'oC', '') AS DECIMAL(19,8))


答:
find,count  and .exec are asynchronous in nature
You  are returning  the sites variable  , which is initally  an empty array , even before your afterFind function is computed , Not to mention the second exec after count .</p>

Title: Sails Query Returns Nothing After count() Query


问:
iOS message composer view inside titanium application
Currently I'm using the following code to display the message composer, but it opens the native iOS message app and my application goes to background.

```<code>Titanium.Platform.openURL('sms:'+e.rowData.value);
</code>```

But I want to show the message composer inside my application.

Is there any way to display the message composing window of iOS in my titanium application ?

I searched a lot but didn't get any solution. And there is nothing in the appcelerator documentation regarding the message composer.

Thanks in advance

答:
I have better solution without using module

Ti.Platform.openURL('sms://' +Your_phone_number + '&body=' + encodeURIComponent(MESSAGE_IN_STRING));

It worked for me.

Body:
Currently I'm using the following code to display the message composer, but it opens the native iOS message app and my application goes to background.

Titanium.Platform.openURL('sms:'+e.rowData.value);

But I want to show the message composer inside my application.

Is there any way to display the message composing window of iOS in my titanium application ?

I searched a lot but didn't get any solution. And there is nothing in the appcelerator documentation regarding the message composer.

Thanks in advance


问:
Creating a generic array for CompletableFuture
I need to create a generic array of CompletableFuture objects so that I can pass it to the CompletableFuture.allOf method to get one CompletableFuture to sync the threads. But since it is a generic I cannot create it. One obvious solution is to create a List and then call toArray on it but it'll be inefficient. Are there any better methods? Here is my code:

```<code>// Current solution:
List<CompletableFuture<List<ReportComparable>>> newReports = new ArrayList<>();

// Loop and add CompletableFuture objects to this list

// Collect all the retrieved objects here(Sync Threads).
    try {
        List<List<ReportComparable>> newReps = CompletableFuture.allOf((CompletableFuture<?>[]) newReports.toArray()).get();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答:
There are several wrong assumptions in your question

You can’t do (CompletableFuture<?>[]) newReports.toArray(). The parameterless toArray() method will return Object[] and the casting attempt will cause a ClassCastException. Only the toArray(T[]) method accepting an existing array will return an array of the same type, which brings you back to square zero

CompletableFuture.allOf returns a CompletableFuture<Void>, so you can’t call get() on it and expect to get a List<List<ReportComparable>>. You have to assemble the result list yourself after completion.

There is no problem creating an array of a generic class, when all type arguments are wildcards. So

```<code>CompletableFuture<?>[] array = new CompletableFuture<?>[100];
</code>```

works.

When you have an arbitrary number of elements, adding them to a List and invoking toArray on it, isn’t necessarily inefficient. The alternative, dealing with an array and an index manually, is doing the same as an ArrayList, but error prone. The single copying step of toArray is rarely performance relevant.

Also keep in mind, since the CompletableFuture.allOf returns CompletableFuture<Void> you might need the List<CompletableFuture<List<ReportComparable>>> anyway to be able to construct the desired List<List<ReportComparable>> after the completion.

On the other hand, when you have a fixed number of arguments, you may call the varargs method CompletableFuture.allOf directly without manual array creation.

But when all you want to do with the CompletableFuture returned by allOf, is to call get() immediately, the “wait for all” operation doesn’t have any benefit anyway.

You get the same effect implicitly when querying the individual CompletableFuture instances via get() or join() and adding the result to your resulting List, which you have to do anyway after completion, as CompletableFuture.allOf does not do that for you.

Body:
I need to create a generic array of CompletableFuture objects so that I can pass it to the CompletableFuture.allOf method to get one CompletableFuture to sync the threads. But since it is a generic I cannot create it. One obvious solution is to create a List and then call toArray on it but it'll be inefficient. Are there any better methods? Here is my code:

// Current solution:
List<CompletableFuture<List<ReportComparable>>> newReports = new ArrayList<>();

// Loop and add CompletableFuture objects to this list

// Collect all the retrieved objects here(Sync Threads).
    try {
        List<List<ReportComparable>> newReps = CompletableFuture.allOf((CompletableFuture<?>[]) newReports.toArray()).get();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Body:
There are several wrong assumptions in your question

You can’t do (CompletableFuture<?>[]) newReports.toArray(). The parameterless toArray() method will return Object[] and the casting attempt will cause a ClassCastException. Only the toArray(T[]) method accepting an existing array will return an array of the same type, which brings you back to square zero

CompletableFuture.allOf returns a CompletableFuture<Void>, so you can’t call get() on it and expect to get a List<List<ReportComparable>>. You have to assemble the result list yourself after completion.

There is no problem creating an array of a generic class, when all type arguments are wildcards. So

CompletableFuture<?>[] array = new CompletableFuture<?>[100];

works.

When you have an arbitrary number of elements, adding them to a List and invoking toArray on it, isn’t necessarily inefficient. The alternative, dealing with an array and an index manually, is doing the same as an ArrayList, but error prone. The single copying step of toArray is rarely performance relevant.

Also keep in mind, since the CompletableFuture.allOf returns CompletableFuture<Void> you might need the List<CompletableFuture<List<ReportComparable>>> anyway to be able to construct the desired List<List<ReportComparable>> after the completion.

On the other hand, when you have a fixed number of arguments, you may call the varargs method CompletableFuture.allOf directly without manual array creation.

But when all you want to do with the CompletableFuture returned by allOf, is to call get() immediately, the “wait for all” operation doesn’t have any benefit anyway.

You get the same effect implicitly when querying the individual CompletableFuture instances via get() or join() and adding the result to your resulting List, which you have to do anyway after completion, as CompletableFuture.allOf does not do that for you.


问:
How to use abstract methods in inherited classes?
I'm currently working on a school project that's due to friday & I've got a whole lot to do.
The assignment is to make a video game with XNA framework using Monogame. I'm currently working with collisions.

The structure for gameobjects looks somewhat like this:

For collisions, I have a simple collision class

```<code>     class Collision{

public GameObject Other;

public GameObject Obj1;

public Collision(GameObject obj1, GameObject other)
{
    Other = other;
    Obj1 = obj1;
}}
</code>```

The collisions are handled in a static method in the GameObject class:

```<code>public static void UpdateCollisions()
{
    //Empty the list
    AllCollisions.Clear();

    for (int a = 0; a < AllGameObjectsWithCollision.Count; a++)
    {
        GameObject obja = AllGameObjectsWithCollision[a];
        for (int b = 0; b < AllGameObjectsWithCollision.Count; b++)
        {
            GameObject objb = AllGameObjectsWithCollision[b];

            if (obja.Mask != null & objb.Mask!= null && obja != objb)
            {
                if (obja.Mask.CollisionRectangle.Intersects(objb.Mask.CollisionRectangle))
                    AllCollisions.Add(new Collision(obja, objb));
            }
        }
    }

}
</code>```

This far it's working, the game is finding all collisions like it should. However now I need to let my objects know that they're colliding, and tell them what to do.
For this, I made the entity class abstract to be able to declare an abstract method called "OnCollision(Collision collision)"

abstract class Entity : GameObject
{
    public float Health;
    public float MaxHealth;
    public bool Alive;
    public float OriginalDmg;
    public float Dmg;

    public abstract void OnCollision(Collision collision);
}```
</div>
</div>
</p>

<p>Then I'm overriding the method in the classes that inherit the Entity class</p>

<p>Ex. Projectile</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-css lang-css prettyprint-override"><code>class Projectile : Entity
{
    Entity Owner;
    ProjectileType pType;

    public Projectile(Texture2D image, float maxSpeed, Entity owner, float dmg, ProjectileType type)
    {
        Image = image;
        MaxSpeed = maxSpeed;
        AccelerationSpeed = MaxSpeed;
        Owner = owner;
        Dmg = dmg;
        pType = type;
    }

    public override void OnCollision(Collision collision)
    {
        #region If this projectile friendly
        if (pType == ProjectileType.Friendly)
        {
            //If colliding with an enemy
            if (collision.Other.GetType() == typeof(Enemy))
            {
                var enemy = (Enemy)collision.Other;
                enemy.Health -= Dmg;
                Destroy(this);
            }
        }
        #endregion

        #region If this projectile is hostile
        if (pType == ProjectileType.Hostile)
        {

        }
        #endregion
    }
}</code>```

Then I'm trying to call the OnCollision method from my Update in the GameObject class.
This is how I try to inform my objects if they are collding and who they're colliding with:

        if (GetType().IsAssignableFrom(typeof(Entity)))
        {
            Entity entity = (Entity)this;

            if (GetType() == typeof(Player))
                entity = (Player)this;
            if (GetType() == typeof(Enemy))
                entity = (Enemy)this;
            if (GetType() == typeof(Projectile))
                entity = (Projectile)this;

            var entityCol = FindCollision(entity);

            if (entityCol != null)
                entity.OnCollision(entityCol);
        }```

I'm new to abstract classes & overriding, so I might have gotten the whole idea wrong.
But it seems the OnCollision method isn't reached as I've tried to Debug.WriteLine stuff but nothing shows up in the output window.

Thanks for reading & perhaps trying to help me out :)

Mediafire link to download the project in case you want to see all the code.

答:
Eh, wrong if statement...

Using

```<code>if (GetType().IsSubclassOf(typeof(Entity)))
</code>```

fixed it.

Silly mistake, my bad.

Body:
I'm currently working on a school project that's due to friday & I've got a whole lot to do.
The assignment is to make a video game with XNA framework using Monogame. I'm currently working with collisions.

The structure for gameobjects looks somewhat like this:

For collisions, I have a simple collision class

     class Collision{

public GameObject Other;

public GameObject Obj1;

public Collision(GameObject obj1, GameObject other)
{
    Other = other;
    Obj1 = obj1;
}}

The collisions are handled in a static method in the GameObject class:

public static void UpdateCollisions()
{
    //Empty the list
    AllCollisions.Clear();

    for (int a = 0; a < AllGameObjectsWithCollision.Count; a++)
    {
        GameObject obja = AllGameObjectsWithCollision[a];
        for (int b = 0; b < AllGameObjectsWithCollision.Count; b++)
        {
            GameObject objb = AllGameObjectsWithCollision[b];

            if (obja.Mask != null & objb.Mask!= null && obja != objb)
            {
                if (obja.Mask.CollisionRectangle.Intersects(objb.Mask.CollisionRectangle))
                    AllCollisions.Add(new Collision(obja, objb));
            }
        }
    }

}

This far it's working, the game is finding all collisions like it should. However now I need to let my objects know that they're colliding, and tell them what to do.
For this, I made the entity class abstract to be able to declare an abstract method called "OnCollision(Collision collision)"

abstract class Entity : GameObject
{
    public float Health;
    public float MaxHealth;
    public bool Alive;
    public float OriginalDmg;
    public float Dmg;

    public abstract void OnCollision(Collision collision);
}

Then I'm overriding the method in the classes that inherit the Entity class

Ex. Projectile

class Projectile : Entity
{
    Entity Owner;
    ProjectileType pType;

    public Projectile(Texture2D image, float maxSpeed, Entity owner, float dmg, ProjectileType type)
    {
        Image = image;
        MaxSpeed = maxSpeed;
        AccelerationSpeed = MaxSpeed;
        Owner = owner;
        Dmg = dmg;
        pType = type;
    }

    public override void OnCollision(Collision collision)
    {
        #region If this projectile friendly
        if (pType == ProjectileType.Friendly)
        {
            //If colliding with an enemy
            if (collision.Other.GetType() == typeof(Enemy))
            {
                var enemy = (Enemy)collision.Other;
                enemy.Health -= Dmg;
                Destroy(this);
            }
        }
        #endregion

        #region If this projectile is hostile
        if (pType == ProjectileType.Hostile)
        {

        }
        #endregion
    }
}

Then I'm trying to call the OnCollision method from my Update in the GameObject class.
This is how I try to inform my objects if they are collding and who they're colliding with:

        if (GetType().IsAssignableFrom(typeof(Entity)))
        {
            Entity entity = (Entity)this;

            if (GetType() == typeof(Player))
                entity = (Player)this;
            if (GetType() == typeof(Enemy))
                entity = (Enemy)this;
            if (GetType() == typeof(Projectile))
                entity = (Projectile)this;

            var entityCol = FindCollision(entity);

            if (entityCol != null)
                entity.OnCollision(entityCol);
        }

I'm new to abstract classes & overriding, so I might have gotten the whole idea wrong.
But it seems the OnCollision method isn't reached as I've tried to Debug.WriteLine stuff but nothing shows up in the output window.

Thanks for reading & perhaps trying to help me out :)

Mediafire link to download the project in case you want to see all the code.

Body:
Eh, wrong if statement...

Using

if (GetType().IsSubclassOf(typeof(Entity)))

fixed it.

Silly mistake, my bad.


问:
QImage class : file loading
If I want to load file directly (QImage i1("image1.jpg");) where should I store it?

If I have to give full path of file or only short path is required?

答:
Use the absolution path or copying the image1.jpg to the current path.

My current path in qt creator is not same as *.exe, but its parent (debug/Release). Use the below code to find.

```<code>QString fileName = QFileDialog::getOpenFileName(this,
                                tr("Open Image"),
                                QDir::currentPath(),
                                tr("Image Files (*.png *.jpg *.bmp)"));
</code>```

Title: QImage class : file loading

Body:
Use the absolution path or copying the image1.jpg to the current path.

My current path in qt creator is not same as *.exe, but its parent (debug/Release). Use the below code to find.

QString fileName = QFileDialog::getOpenFileName(this,
                                tr("Open Image"),
                                QDir::currentPath(),
                                tr("Image Files (*.png *.jpg *.bmp)"));


问:
r: subsetting with square brackets not working
I made data frame called x:

```<code>a  b
1  2
3  NA
3  32
21 7
12 8
</code>```

When I run

```<code>y <- x["a">2,]
</code>```

The object y returned is identical to x. If I run

```<code>y <- x["a" == 1,]
</code>```

y is an empty frame.

I made sure that the names of the x data frame have no white spaces (I named them myself with names() ) and also that a and are numeric.

PS: If I try

```<code> y <- x["a">2]
</code>```

y is also returned as identical to x.

答:
A simple alternative would be using data.table

```<code>library(data.table)

setDT(x)

y <- x[ a > 2, ]

y <- x[ a == 1, ]
</code>```

Body:
I made data frame called x:

a  b
1  2
3  NA
3  32
21 7
12 8

When I run

y <- x["a">2,]

The object y returned is identical to x. If I run

y <- x["a" == 1,]

y is an empty frame.

I made sure that the names of the x data frame have no white spaces (I named them myself with names() ) and also that a and are numeric.

PS: If I try

 y <- x["a">2]

y is also returned as identical to x.

Body:
A simple alternative would be using data.table

library(data.table)

setDT(x)

y <- x[ a > 2, ]

y <- x[ a == 1, ]

ContentLicense: CC BY-SA 4.0


问:
HTML 5 video autoplay not work in iphone
I created a website for preview of HTML5 video autoplay, but it is not working on iPhone

Can anyone please let me know how can i make it work?

答:
You can find more information about under which conditions iOS will allow autoplay here: https://webkit.org/blog/6784/new-video-policies-for-ios/.

As far as I understand you are only allowed to autoplay if your video is muted or doesn't have a audio track in general (so basically a "modern gif").


问:
Flatmap scala [String, String,List[String]]
I have this prbolem, I have an RDD[(String,String,  List[String]), and I would like to "flatmap" it to obtain a RDD[(String,String,  String)]:

e.g:

```<code>val x :RDD[(String,String,  List[String]) =
RDD[(a,b, list[ "ra", "re", "ri"])]
</code>```

I would like get:

```<code>val result: RDD[(String,String,String)] =
RDD[(a, b, ra),(a, b, re),(a, b, ri)])]
</code>```

答:
Use flatMap:

```<code>val rdd = sc.parallelize(Seq(("a", "b", List("ra", "re", "ri"))))
// rdd: org.apache.spark.rdd.RDD[(String, String, List[String])] = ParallelCollectionRDD[7] at parallelize at <console>:28

rdd.flatMap{ case (x, y, z) => z.map((x, y, _)) }.collect
// res23: Array[(String, String, String)] = Array((a,b,ra), (a,b,re), (a,b,ri))
</code>```

Body:
I have this prbolem, I have an RDD[(String,String,  List[String]), and I would like to "flatmap" it to obtain a RDD[(String,String,  String)]:

e.g:

val x :RDD[(String,String,  List[String]) =
RDD[(a,b, list[ "ra", "re", "ri"])]

I would like get:

val result: RDD[(String,String,String)] =
RDD[(a, b, ra),(a, b, re),(a, b, ri)])]

Body:
Use flatMap:

val rdd = sc.parallelize(Seq(("a", "b", List("ra", "re", "ri"))))
// rdd: org.apache.spark.rdd.RDD[(String, String, List[String])] = ParallelCollectionRDD[7] at parallelize at <console>:28

rdd.flatMap{ case (x, y, z) => z.map((x, y, _)) }.collect
// res23: Array[(String, String, String)] = Array((a,b,ra), (a,b,re), (a,b,ri))


答:
You have to throw exception from catch block. For example:</p>

```<code>catch(OverflowException exc)
{
    Console.WriteLine(exc)
    throw exc;
}
</code>```

Title: how to handle OverflowException in C#?

Body:
I need to handle OverflowException in method mul().

class B
{
    short a, b;
    public B(short a, short b) { this.a = a; this.b = b; }
    public short mul()
    {
        try
        {
            return checked((short)(a * b));
        }
        catch (OverflowException exc) { Console.WriteLine(exc); }
    }
}

class MainClass
{
    public static void Main(string[] args)
    {
        B m1 = new B(1000, 500);
        m1.mul();
    }
}

But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)

What can I do to fix it?

Body:
You have to throw exception from catch block. For example:

catch(OverflowException exc)
{
    Console.WriteLine(exc)
    throw exc;
}


问:
Not able to connect with ftp to upload file in php
I have file on my local and I want to upload that file on ftp server on specific  folder but I am not able to do it, Can anyone give some light on it. Below is my code.

```<code>$ftp = ftp_connect("server path",22);

ftp_login($ftp,username,password);

$ret = ftp_nb_put($ftp,
    "/incoming/in/",
    "http://localhost:8888/cardManagement/newfile.dat",
    FTP_BINARY,
    FTP_AUTORESUME);

print_r($ret);
</code>```

Note- It's SFTP

答:
```<code>$strServer = "##";
 $strServerPort = "22";
 $strServerUsername = "##";
 $strServerPassword = "##";

 //connect to server

 $sftp = new Net_SFTP($strServer);
 if (!$sftp->login($strServerUsername, $strServerPassword)) {
     exit('Login Failed');
 }

 // puts a three-byte file named filename.remote on the SFTP server
 $sftp->put('/incoming/'.$fileName, $fileName);
 // puts an x-byte file named filename.remote on the SFTP server,
 // where x is the size of filename.local
 $sftp->put('/incoming/in/'.$fileName, $fileName, NET_SFTP_LOCAL_FILE);
</code>```

Body:
I have file on my local and I want to upload that file on ftp server on specific  folder but I am not able to do it, Can anyone give some light on it. Below is my code.

$ftp = ftp_connect("server path",22);

ftp_login($ftp,username,password);

$ret = ftp_nb_put($ftp,
    "/incoming/in/",
    "http://localhost:8888/cardManagement/newfile.dat",
    FTP_BINARY,
    FTP_AUTORESUME);

print_r($ret);

Note- It's SFTP


问:
Download time remaning predictor
Are there any widgets for predicting when a download (or any other process) will finish based on percent done history?

The trivial version would just do a 2 point fit based on the start time, current time and percent done but better option are possible.

A GUI widgest would be nice but a class that just returns the value would be just fine.

答:
Most progress bar widgets have an update() method which takes a percentage done.

They then calculate the time remainging based on the time since start and the latest percentage.  If you have a process with a long setup time you might want to add more functionality so that it doesn't include this time, perhaps by having the prediction clock reset when sent a 0% update.

OwnerDisplayName: BCS

Title: Download time remaning predictor

LastEditorDisplayName: BCS

OwnerDisplayName: mgb


问:
AR Query for jsonb attribute column
I'm using Postgres for my db, and I have a column in my Auction model as a jsonb column. I want to create a query that searches the Auction's json column to see whether a user's name OR email exists in any Auction instance's json column.

Right now I have @auctions = Auction.where('invitees @> ?', {current_user.name.downcase => current_user.email.downcase}.to_json), but that only brings back exact key => value matches I want to know whether the name OR the email exists.

答:
This is just a temporary patch until I add an Invite model, but casting the invitee column to text I can search the columns. Like so

```<code>SELECT * FROM auctions
WHERE data::text LIKE "%#{string I'm searching for}%"
</code>```

So, AR:

```<code>Auction.where('data::text LIKE ?', "%#{string I'm searching for}%")
</code>```

Title: AR Query for jsonb attribute column

Body:
This is just a temporary patch until I add an Invite model, but casting the invitee column to text I can search the columns. Like so

SELECT * FROM auctions
WHERE data::text LIKE "%#{string I'm searching for}%"

So, AR:

Auction.where('data::text LIKE ?', "%#{string I'm searching for}%")


问:
How to access outer class from an inner class?
I have a situation like so...

```<code>class Outer(object):

    def some_method(self):
        # do something

    class Inner(object):
        def __init__(self):
            self.Outer.some_method()    # <-- this is the line in question
</code>```

How can I access the Outer class's method from the Inner class?

答:
You can easily access to outer class using metaclass: after creation of outer class check it's attribute dict for any classes (or apply any logic you need - mine is just trivial example) and set corresponding values:

```<code>import six
import inspect

# helper method from `peewee` project to add metaclass
_METACLASS_ = '_metaclass_helper_'
def with_metaclass(meta, base=object):
    return meta(_METACLASS_, (base,), {})

class OuterMeta(type):
    def __new__(mcs, name, parents, dct):
        cls = super(OuterMeta, mcs).__new__(mcs, name, parents, dct)
        for klass in dct.values():
            if inspect.isclass(klass):
                print("Setting outer of '%s' to '%s'" % (klass, cls))
                klass.outer = cls

        return cls

# @six.add_metaclass(OuterMeta) -- this is alternative to `with_metaclass`
class Outer(with_metaclass(OuterMeta)):
    def foo(self):
        return "I'm outer class!"

    class Inner(object):
        outer = None  # <-- by default it's None

        def bar(self):
            return "I'm inner class"

print(Outer.Inner.outer)
>>> <class '__main__.Outer'>
assert isinstance(Outer.Inner.outer(), Outer)

print(Outer().foo())
>>> I'm outer class!
print(Outer.Inner.outer().foo())
>>> I'm outer class!
print(Outer.Inner().outer().foo())
>>> I'm outer class!
print(Outer.Inner().bar())
>>> I'm inner class!
</code>```

Using this approach, you can easily bind and refer two classes between each other.

Body:
I have a situation like so...

class Outer(object):

    def some_method(self):
        # do something

    class Inner(object):
        def __init__(self):
            self.Outer.some_method()    # <-- this is the line in question

How can I access the Outer class's method from the Inner class?

Body:
You can easily access to outer class using metaclass: after creation of outer class check it's attribute dict for any classes (or apply any logic you need - mine is just trivial example) and set corresponding values:

import six
import inspect

# helper method from `peewee` project to add metaclass
_METACLASS_ = '_metaclass_helper_'
def with_metaclass(meta, base=object):
    return meta(_METACLASS_, (base,), {})

class OuterMeta(type):
    def __new__(mcs, name, parents, dct):
        cls = super(OuterMeta, mcs).__new__(mcs, name, parents, dct)
        for klass in dct.values():
            if inspect.isclass(klass):
                print("Setting outer of '%s' to '%s'" % (klass, cls))
                klass.outer = cls

        return cls

# @six.add_metaclass(OuterMeta) -- this is alternative to `with_metaclass`
class Outer(with_metaclass(OuterMeta)):
    def foo(self):
        return "I'm outer class!"

    class Inner(object):
        outer = None  # <-- by default it's None

        def bar(self):
            return "I'm inner class"

print(Outer.Inner.outer)
>>> <class '__main__.Outer'>
assert isinstance(Outer.Inner.outer(), Outer)

print(Outer().foo())
>>> I'm outer class!
print(Outer.Inner.outer().foo())
>>> I'm outer class!
print(Outer.Inner().outer().foo())
>>> I'm outer class!
print(Outer.Inner().bar())
>>> I'm inner class!

Using this approach, you can easily bind and refer two classes between each other.


问:
Graph is not displaying in Node Js Application
I'm integrating JSReport in Node JSApplication. The JSReport uses several 3rd party api's to display chart etc. When I run JSReporn alone it works perfectly. enter image description here

When i run This with Node JS application, It doesn't display the graph. enter image description here

Here i attached my code is on jsreport studio
Template is :

```<code>    <h1>{{country}}</h1>

    <canvas id='orders' style="margin-top:30px"></canvas>
    <table class="table striped">
        <thead>
            <tr>
                <th>OrderID</th>
                <th>ShipAddress</th>
                <th>ShipCity</th>
                <th>ShipCountry</th>
            </tr>
        </thead>
        <tbody>
            {{#each orders}}
            <tr>
                <td>{{OrderID}}</td>
                <td>{{ShipAddress}}</td>
                <td>{{ShipCity}}</td>
                <td>{{ShipCountry}}</td>
            </tr>
            {{/each}}
        </tbody>
    </table>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js'></script>

    <script>
        var data = {{{toJSON this}}}
        Chart.defaults.global.legend.display = false;
        var orders = document.getElementById("orders").getContext('2d');
        var chartObj = new Chart(orders, {
            type: 'bar',
            data: {
                labels: Object.keys(data.accumulatedOrders),
                datasets: [{
                    fillColor: 'blue',
                    label: "Orders in time",
                    backgroundColor: "rgba(27,161,226,0.2)",
                    borderColor: "rgba(27,161,226,1)",
                    borderWidth: 1,
                    hoverBackgroundColor: "rgba(27,161,226,0.4)",
                    hoverBorderColor: "rgba(27,161,226,1)",
                    data: Object.keys(data.accumulatedOrders).map(function (o) {
                        return data.accumulatedOrders[o].value;
                    })
                }]

            },
            options: {
                animation: {
                    onComplete: function () {
                        // set the PDF printing trigger when the animation is done
                        // to have this working, the phantom-pdf menu in the left must
                        // have the wait for printing trigger option selected
                        //window.JSREPORT_READY_TO_START = true
                    }
                }
            }
        });

    </script>

Script code is :

// custom server side script used to fetch data from remote REST API
var http = require('http');

function getOrders(country, cb) {
    http.get({
        hostname: 'services.odata.org',
        port: 80,
        path: `/V4/Northwind/Northwind.svc/Orders?$filter=${encodeURI(`ShipCountry eq '${country}'`)}`,
    }, (result) => {
        var str = '';
        result.on('data', (b) => str += b);
        result.on('error', cb);
        result.on('end', () => cb(null, JSON.parse(str)));
    });
}

function beforeRender(req, res, done) {
    // the report parameter country can be send from the client API request
    req.data.country = req.data.country || 'France'
    getOrders(req.data.country, (err, json) => {
        if (err) {
            return done(err);
        }

        var orders = json.value;
        var ordersByQuarter = {};

        orders.forEach((o) => {
            o.OrderDate = new Date(o.OrderDate);
            var key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1);
            ordersByQuarter[key] = ordersByQuarter[key] || {
                value: 0,
                orderDate: o.OrderDate
            };
            ordersByQuarter[key].value++;
        });

        req.data.orders = orders;
        req.data.accumulatedOrders = ordersByQuarter;

        done();
    });
}
</code>```

答: Without knowing more about your code it's hard to answer, but the answer is probably that the chart renders asynchronously and the report snapshot is being taken before it finishes.  If there's animation on the chart, turn it off.  If not, there are a few ways you can delay rendering to ensure it shows up.</p>

Body:
I'm integrating JSReport in Node JSApplication. The JSReport uses several 3rd party api's to display chart etc. When I run JSReporn alone it works perfectly. enter image description here

When i run This with Node JS application, It doesn't display the graph. enter image description here

Here i attached my code is on jsreport studio
Template is :

{{country}}

    <canvas id='orders' style="margin-top:30px"></canvas>

                OrderID
                ShipAddress
                ShipCity
                ShipCountry

            {{#each orders}}

                {{OrderID}}
                {{ShipAddress}}
                {{ShipCity}}
                {{ShipCountry}}

            {{/each}}

Script code is :

// custom server side script used to fetch data from remote REST API
var http = require('http');

function getOrders(country, cb) {
    http.get({
        hostname: 'services.odata.org',
        port: 80,
        path: `/V4/Northwind/Northwind.svc/Orders?$filter=${encodeURI(`ShipCountry eq '${country}'`)}`,
    }, (result) => {
        var str = '';
        result.on('data', (b) => str += b);
        result.on('error', cb);
        result.on('end', () => cb(null, JSON.parse(str)));
    });
}

function beforeRender(req, res, done) {
    // the report parameter country can be send from the client API request
    req.data.country = req.data.country || 'France'
    getOrders(req.data.country, (err, json) => {
        if (err) {
            return done(err);
        }

        var orders = json.value;
        var ordersByQuarter = {};

        orders.forEach((o) => {
            o.OrderDate = new Date(o.OrderDate);
            var key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1);
            ordersByQuarter[key] = ordersByQuarter[key] || {
                value: 0,
                orderDate: o.OrderDate
            };
            ordersByQuarter[key].value++;
        });

        req.data.orders = orders;
        req.data.accumulatedOrders = ordersByQuarter;

        done();
    });
}