问:
Using Google Docs from web app
We have a requirement for people to be able to look at documents people have uploaded to us (mainly word, possibly some rtf) via our web app. We want the user to be able to open the docs inside the browser, but keep the original formatting and not have the need for another application (like word, acrobat etc).

We thought about using google docs to do this, there appears to be some batch uploading options to get stuff in there but does anyone know if we can use the API's to keep the user on our site without them having to login to google docs themselves, and keep them still on our website with re-directing to google docs to view them.

Cheers

答:
There's an option to make documents public (Somewhere in Share->Advanced Options).

Using api you can get list of documents in your google docs account, you can even search em. In your app you could make a link to the document in google docs which opens in a new window. That way your user will never navigate away from your page. An alternative would be to use an IFrame, but it's considered bad practice.

A completely different approach could be to automatically generate and host a pdf each time someone uploads a file. There are scripts/programs which can do that, just call them after you receive a file.

OwnerDisplayName: beakersoft

Title: Using Google Docs from web app

OwnerDisplayName: Maiku Mori


来源: stackexchange

问:
Printing the 3 highest integers from an array without sorting
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

```<code>class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }
</code>```

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

答:
You have to keep a track of which is the lower grade in you best array an replace just that one </p>

```<code>class BestGrades {
public static void main(String args[]){
        Scanner sc = new Scanner(System.in);

        int grade[] = new int[6];
        int best[] = new int[3];

        System.out.println("Enter the student's grade...");

        for(int i = 0; i < grade.length; i++){

                grade[i] = sc.nextInt();

                boolean better = false;
                int lowerIndex = 0;

                for(int a = 0; a < best.length; a++){
                        if(grade[i] > best[a]){
                                better = true;
                        }
                        if(best[a] < best[lowerIndex]){
                            lowerIndex = a;
                        }
                }
                if(better){
                    best[lowerIndex] = grade[i];
                }
        }

        for(int i = 0; i < best.length; i++){
                System.out.println("Best degrees are: "+best[i]);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

Body:
You have to keep a track of which is the lower grade in you best array an replace just that one

class BestGrades {
public static void main(String args[]){
        Scanner sc = new Scanner(System.in);

        int grade[] = new int[6];
        int best[] = new int[3];

        System.out.println("Enter the student's grade...");

        for(int i = 0; i < grade.length; i++){

                grade[i] = sc.nextInt();

                boolean better = false;
                int lowerIndex = 0;

                for(int a = 0; a < best.length; a++){
                        if(grade[i] > best[a]){
                                better = true;
                        }
                        if(best[a] < best[lowerIndex]){
                            lowerIndex = a;
                        }
                }
                if(better){
                    best[lowerIndex] = grade[i];
                }
        }

        for(int i = 0; i < best.length; i++){
                System.out.println("Best degrees are: "+best[i]);
        }
    }
}


问:
Calculating difference in time
I'm trying to set the difference (in hours, minutes and seconds) between two dates into a variable. The format is +%y%m%d%H%M%S (for example: 170607162412).

For example: 170607162400 and 170607162410 = 00:00:10

I tried a lot but i couldn't figure it out.

答:
Take a look here: http://www.unix.com/tips-and-tutorials/31944-simple-date-time-calulation-bash.html.
The trick is to convert your date to a timestamp (seconds since Jan 01 1970. UTC). Than you can add and remove seconds and even substract dates from each other.</p>

```<code>date2stamp () {
    date --utc --date "$1" +%s
}

stamp2date (){
    date --utc --date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
}

dateDiff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp $1)
    dte2=$(date2stamp $2)
    diffSec=$((dte2-dte1))
    if ((diffSec < 0)); then abs=-1; else abs=1; fi
    echo $((diffSec/sec*abs))
}
</code>```

Title: Calculating difference in time

Body:
Take a look here: http://www.unix.com/tips-and-tutorials/31944-simple-date-time-calulation-bash.html.
The trick is to convert your date to a timestamp (seconds since Jan 01 1970. UTC). Than you can add and remove seconds and even substract dates from each other.

date2stamp () {
    date --utc --date "$1" +%s
}

stamp2date (){
    date --utc --date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
}

dateDiff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp $1)
    dte2=$(date2stamp $2)
    diffSec=$((dte2-dte1))
    if ((diffSec < 0)); then abs=-1; else abs=1; fi
    echo $((diffSec/sec*abs))
}


问:
How to target specific multiple cells when using a subtract/add quantity script in google sheets?
Here is my spreadsheet.

https://docs.google.com/spreadsheets/d/1F0hooJ0Wo62IOgKsGebI8flr7fTmPVIho_FBFAasn_Y/edit?usp=sharing

I currently have a script called inventory as follows

```<code>function subtractSoldBulk() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var maxRows = sheet.getMaxRows();

  var soldRange = sheet.getRange(3, 3, maxRows); // row, column, number of rows "Sold" column
  var totalRange = sheet.getRange(3, 4, maxRows); // row, column, max rows "Inventory" column

  var soldValues = soldRange.getValues();
  var totalValues = totalRange.getValues();
  for (var row in soldValues) {
    var soldCellData = soldValues[row][0];
    var totalCellData = totalValues[row][0];

    if (soldCellData != "" && totalCellData != "") {
      totalValues[row][0] = totalCellData - soldCellData;
      soldValues[row][0] = "";
    }
  }

  soldRange.setValues(soldValues);
  totalRange.setValues(totalValues);
}

function addBulk() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var maxRows = sheet.getMaxRows();

  var addRange = sheet.getRange(3, 5, maxRows); // row, column, number of rows "Add" column
  var totalRange = sheet.getRange(3, 4, maxRows); // row, column, max rows "Inventory" column

  var addValues = addRange.getValues();
  var totalValues = totalRange.getValues();
  for (var row in addValues) {
    var addCellData = addValues[row][0];
    var totalCellData = totalValues[row][0];

    if (addCellData != "" && totalCellData != "") {
      totalValues[row][0] = totalCellData + addCellData;
      addValues[row][0] = "";
    }
  }

  addRange.setValues(addValues);
  totalRange.setValues(totalValues);
  }
</code>```

This script allows me to use add and subtract buttons on my spreadsheet so that if i put a quantity in the add or sold columns on a particular row, that quantity will be added or subtracted from the Inventory Quantity on the same row once the add or subtract button is pressed. I want to edit this script so that when I put a quantity in the add or subtract columns add press the buttons, that quantity is added or subtracted from more than one cell in the inventory quantity column.

I need to be able to choose which cells the script applies to. For example- subtract 1 from cells b4  e2, e8 when quantity is entered in Sold column in cell c3 and subtract button is pressed.

I would also like to do this multiple times so for example

Subtract quantity from cells b4  e2, e8 when quantity is entered in Sold column in cell c3 and sold button is pressed
Subtract quantity from cells b6  e2, e5 when quantity is entered in Sold column in cell c4 and sold button is pressed
Subtract quantity from cells b9  e1, e7 when quantity is entered in Sold column in cell c5 and sold button is pressed

etc

It should be the same situation for adding quantities

I'm not sure how to get there from the script I have. I feel like I'm halfway there. I'm a beginner when it comes to scripting so please bare this in mind

Any help would be much appreciated

Thanks

Francis

答:
Have a look at the linked spreadsheet based on the one you provided above.

Spreadsheet

How to use it:

Enter a value in a cell (A cell specified in the ranges array) Note: you must commit the value to the cell i.e. click return or click out of the cell.

Important: Click on the cell again so that it is the active cell.

Click add or subtract button to have the value added or subtracted from the specified values in the inventory column.

Body:
Here is my spreadsheet.

https://docs.google.com/spreadsheets/d/1F0hooJ0Wo62IOgKsGebI8flr7fTmPVIho_FBFAasn_Y/edit?usp=sharing

I currently have a script called inventory as follows

function subtractSoldBulk() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var maxRows = sheet.getMaxRows();

  var soldRange = sheet.getRange(3, 3, maxRows); // row, column, number of rows "Sold" column
  var totalRange = sheet.getRange(3, 4, maxRows); // row, column, max rows "Inventory" column

  var soldValues = soldRange.getValues();
  var totalValues = totalRange.getValues();
  for (var row in soldValues) {
    var soldCellData = soldValues[row][0];
    var totalCellData = totalValues[row][0];

    if (soldCellData != "" && totalCellData != "") {
      totalValues[row][0] = totalCellData - soldCellData;
      soldValues[row][0] = "";
    }
  }

  soldRange.setValues(soldValues);
  totalRange.setValues(totalValues);
}

function addBulk() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var maxRows = sheet.getMaxRows();

  var addRange = sheet.getRange(3, 5, maxRows); // row, column, number of rows "Add" column
  var totalRange = sheet.getRange(3, 4, maxRows); // row, column, max rows "Inventory" column

  var addValues = addRange.getValues();
  var totalValues = totalRange.getValues();
  for (var row in addValues) {
    var addCellData = addValues[row][0];
    var totalCellData = totalValues[row][0];

    if (addCellData != "" && totalCellData != "") {
      totalValues[row][0] = totalCellData + addCellData;
      addValues[row][0] = "";
    }
  }

  addRange.setValues(addValues);
  totalRange.setValues(totalValues);
  }

This script allows me to use add and subtract buttons on my spreadsheet so that if i put a quantity in the add or sold columns on a particular row, that quantity will be added or subtracted from the Inventory Quantity on the same row once the add or subtract button is pressed. I want to edit this script so that when I put a quantity in the add or subtract columns add press the buttons, that quantity is added or subtracted from more than one cell in the inventory quantity column.

I need to be able to choose which cells the script applies to. For example- subtract 1 from cells b4  e2, e8 when quantity is entered in Sold column in cell c3 and subtract button is pressed.

I would also like to do this multiple times so for example

Subtract quantity from cells b4  e2, e8 when quantity is entered in Sold column in cell c3 and sold button is pressed
Subtract quantity from cells b6  e2, e5 when quantity is entered in Sold column in cell c4 and sold button is pressed
Subtract quantity from cells b9  e1, e7 when quantity is entered in Sold column in cell c5 and sold button is pressed

etc

It should be the same situation for adding quantities

I'm not sure how to get there from the script I have. I feel like I'm halfway there. I'm a beginner when it comes to scripting so please bare this in mind

Any help would be much appreciated

Thanks

Francis


问:
4 weeks or accounting month grouping in postgresql
I have a requirement to group data in transaction table into 4 week groups, or accounting month grouping, any suggestions on how to approach it on postgresql

Regards

答:
```<code>SELECT sum(ITEM_C._demand) AS aggre_demand,ITEM_C._week as account_month  FROM (SELECT  sum(quantity) AS _demand,( CASE WHEN floor((extract(doy from shipment_date)-1)/7)+1 > 0 AND floor((extract(doy from shipment_date)-1)/7)+1 <=4 THEN 1
ELSE (CASE WHEN floor((extract(doy from shipment_date)-1)/7)+1 >4 AND floor((extract(doy from shipment_date)-1)/7)+1 <=8 THEN 2 ELSE 3 END ) END)AS _week, date_trunc('year',shipment_date) AS _Year
FROM smp.shipment
GROUP BY floor((extract(doy from shipment_date)-1)/7)+1,date_trunc('year',shipment_date)) AS ITEM_C
GROUP BY ITEM_C._week, ITEM_C._Year
</code>```

I think this is not the idle way to do this, as i need to repeat this 1..52 weeks total 13 times

Body:
SELECT sum(ITEM_C._demand) AS aggre_demand,ITEM_C._week as account_month  FROM (SELECT  sum(quantity) AS _demand,( CASE WHEN floor((extract(doy from shipment_date)-1)/7)+1 > 0 AND floor((extract(doy from shipment_date)-1)/7)+1 <=4 THEN 1
ELSE (CASE WHEN floor((extract(doy from shipment_date)-1)/7)+1 >4 AND floor((extract(doy from shipment_date)-1)/7)+1 <=8 THEN 2 ELSE 3 END ) END)AS _week, date_trunc('year',shipment_date) AS _Year
FROM smp.shipment
GROUP BY floor((extract(doy from shipment_date)-1)/7)+1,date_trunc('year',shipment_date)) AS ITEM_C
GROUP BY ITEM_C._week, ITEM_C._Year

I think this is not the idle way to do this, as i need to repeat this 1..52 weeks total 13 times


问:
Android: Draggable Toast, Or Alternative?
I'm drawing a number of bitmaps on a canvas, and using MotionEvents to let me drag them around.

When each item is pressed, I'd like to display a Toast, or, Toast-like mini information-panel that tracks the movement of the bitmap being dragged during an ACTION_MOVE.  The "Toast" would appear on ACTION_DOWN and vanish on ACTION_UP.

The problem with using Toast is that I have to give it a duration, and, also, I can't change its position once it has been displayed.  Unless I can kill the Toast for each ACTION_MOVE, and display a new one right away at the current coordinates? (Sorry, thinking aloud at this point, can't get to my dev machine to test...)

I don't know what other options there might be to achieve this, and I'd very much appreciate suggestions from the community.

答:
Hope this helps, just whipped it up, might even compile!</p>

```<code>private boolean mDragging = false;
private float mTouchX = 0, mTouchY = 0;
private Paint mTextPaint = new Paint();//need to set this up in onCreate!

public boolean onTouchEvent(MotionEvent event)
{
  mTouchX = event.getX();
  mTouchY = event.getY();

  if(event.getAction() == ACTION_DOWN)
  {
    mDragging = true;
  }
  else if(event.getAction() == ACTION_UP)
  {
    mDragging = false;
  }

  return true;
}

protected void onDraw (Canvas canvas)
{
  /* Put all your bitmap drawing here. */

  /* Draw some info text on top of everything else. */
  if(mDragging)
  {
    String text = mTouchX + ", " + mTouchY;
    canvas.drawText(mTouchX, mTouchY + 50, text, mTextPaint);
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hope this helps, just whipped it up, might even compile!

private boolean mDragging = false;
private float mTouchX = 0, mTouchY = 0;
private Paint mTextPaint = new Paint();//need to set this up in onCreate!

public boolean onTouchEvent(MotionEvent event)
{
  mTouchX = event.getX();
  mTouchY = event.getY();

  if(event.getAction() == ACTION_DOWN)
  {
    mDragging = true;
  }
  else if(event.getAction() == ACTION_UP)
  {
    mDragging = false;
  }

  return true;
}

protected void onDraw (Canvas canvas)
{
  /* Put all your bitmap drawing here. */

  /* Draw some info text on top of everything else. */
  if(mDragging)
  {
    String text = mTouchX + ", " + mTouchY;
    canvas.drawText(mTouchX, mTouchY + 50, text, mTextPaint);
  }
}


问:
How to override route based on condition when application has multi-store functionality
We are using nopCommerce. We've override category page route in plugin. its working fine. But we want to override only for one store not for second store.

As per my review all the route are registered when application restart. So not sure how to make conditional route in mvc or nopcommerce.

Question related to: Click Here

答:
Definitely the way to go is to provide a custom route constraint (a class implementing IRouteConstraint), and use it when declaring your routes.

NopCommerce has one created you can use as an example. Check the GuidConstraint class.


问:
Django returns 403 error when sending a POST request
when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error.

```<code>url = 'http://www.sub.example.com/'
values = { 'var': 'test' }

try:
    data = urllib.urlencode(values, doseq=True)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
except:
    the_page = sys.exc_info()
    raise
</code>```

When I'm opening any other website it works properly.
example.com is Django website too, and it works properly too.
I think, that's Django config problem, can anyone tell me what should I do to provide access to my script?

答:
Or you can allow the permission to make this post request.

Note: Should be used in the cases where you don't need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

```<code>from rest_framework.permissions import AllowAny

class CreateUser(APIView):
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        return(Response("hi"))
</code>```

Further Note that, If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

Update the INSTALLED_APPS to use 'coreHeaders' :

INSTALLED_APPS = [

        'corsheaders',

     ]

White list your front end domain by adding following to settings file again:

CORS_ORIGIN_WHITELIST = (
'localhost:8080',
)

ContentLicense: CC BY-SA 4.0

Body:
when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error.

url = 'http://www.sub.example.com/'
values = { 'var': 'test' }

try:
    data = urllib.urlencode(values, doseq=True)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
except:
    the_page = sys.exc_info()
    raise

When I'm opening any other website it works properly.
example.com is Django website too, and it works properly too.
I think, that's Django config problem, can anyone tell me what should I do to provide access to my script?

Body:
Or you can allow the permission to make this post request.

Note: Should be used in the cases where you don't need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

from rest_framework.permissions import AllowAny

class CreateUser(APIView):
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        return(Response("hi"))

Further Note that, If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

Update the INSTALLED_APPS to use 'coreHeaders' :

INSTALLED_APPS = [

        'corsheaders',

     ]

White list your front end domain by adding following to settings file again:

CORS_ORIGIN_WHITELIST = (
'localhost:8080',
)


问:
How to prevent two events about the same thing happening
Basically,I am a beginner in C# and I just started working on a simple platformer game following a basic Visual Studio 2015 tutorial.This is the code:

```<code>public partial class Form1 : Form
{
    bool goleft = false;
    bool goright = false;
    bool jumping = false;

    int JumpSpeed = 10;
    int force = 8;
    int score = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void keyisdown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = true;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = true;
        }
        if (e.KeyCode == Keys.Space && !jumping)
        {
            jumping = true;
        }
    }

    private void keyisup(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = false;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = false;
        }
        if (jumping)
        {
            jumping = false;
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        player.Top += JumpSpeed;

        if (jumping && force < 0)
        {
            jumping = false;
        }
        if (goleft)
        {
            player.Left -= 5;
        }
        if (goright)
        {
            player.Left += 5;
        }
        if (jumping)
        {
            JumpSpeed = -12;
            force -= 1;
        }
        else
        {
            JumpSpeed = 12;
        }
        foreach (Control x in this.Controls)
        {
            if (x is PictureBox && x.Tag == "p")
            {
                if (player.Bounds.IntersectsWith(x.Bounds) && !jumping)
                {
                    force = 8;
                    player.Top = x.Top - player.Height;
                }
            }

            if (player.Bounds.IntersectsWith(Door.Bounds))
            {
                timer1.Stop();
                MessageBox.Show("You Won!");
                this.Close();
            }
        }
    }
}
</code>```

The gravity force and everything works great EXCEPT for one big problem with the player that I definitely can't solve without some help.

The problem is: the player is completely glitched and it keeps going up and down. I realised that this is because of two lines in private void timer1_Tick(object sender, EventArgs e):

```<code>player.Top += JumpSpeed;
</code>```

and

```<code>player.Top = x.Top - player.Height;
</code>```

Both of these try to change player.Top and interfere with each other. The trouble is that I can't just cut one of the two without destroying the gravity force code. What I think might work is applying player.Top += JumpSpeed; ONLY if(player.Bounds.IntersectsWith(x.Bounds) && !jumping) = false but I don't know how to write the code this way at all (previous tries always ended up with errors).

Thanks in advance for any help and please forgive any grammar errors that I made because I am not a native english speaker.

答:
I don't know how your Form looks like, but with what you provided I would change the code like that:

```<code>public partial class Form1 : Form
{
    bool goleft = false;
    bool goright = false;

    int JumpSpeed = 0; //current vertical speed
    int force = 8; //initial jump speed
    int score = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void keyisdown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = true;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = true;
        }
        if (e.KeyCode == Keys.Space && JumpSpeed==0) //JumpSpeed==0 to prevent "double jump"
        {
            JumpSpeed = force; //start jumping with full power
        }
    }

    private void keyisup(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = false;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = false;
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (goleft)
        {
            player.Left -= 5;
        }
        if (goright)
        {
            player.Left += 5;
        }

        JumpSpeed -= 1; //decrement the vertical speed = gravity -> choose higher value to bring him back on the ground quicker
        player.Top -= JumpSpeed;

        if (player.Bounds.IntersectsWith(Door.Bounds))
        {
            timer1.Stop();
            MessageBox.Show("You Won!");
            this.Close();
        }

        foreach (PictureBox x in this.Controls.OfType<PictureBox>())
        {
            if (x.Tag == "p")
            {
                if (player.Bounds.IntersectsWith(x.Bounds)) //if the player should be able to jump/walk on something the code is
                {
                    player.Top = x.Top - player.Height;
                    JumpSpeed = 0; //the player stops falling
                }
            }
        }
    }
}
</code>```

To make sure to player does not fall out of the window place PictureBoxes with tag == p on the floor!

PS:

Feel free to leave a comment!

Body:
Basically,I am a beginner in C# and I just started working on a simple platformer game following a basic Visual Studio 2015 tutorial.This is the code:

public partial class Form1 : Form
{
    bool goleft = false;
    bool goright = false;
    bool jumping = false;

    int JumpSpeed = 10;
    int force = 8;
    int score = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void keyisdown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = true;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = true;
        }
        if (e.KeyCode == Keys.Space && !jumping)
        {
            jumping = true;
        }
    }

    private void keyisup(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = false;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = false;
        }
        if (jumping)
        {
            jumping = false;
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        player.Top += JumpSpeed;

        if (jumping && force < 0)
        {
            jumping = false;
        }
        if (goleft)
        {
            player.Left -= 5;
        }
        if (goright)
        {
            player.Left += 5;
        }
        if (jumping)
        {
            JumpSpeed = -12;
            force -= 1;
        }
        else
        {
            JumpSpeed = 12;
        }
        foreach (Control x in this.Controls)
        {
            if (x is PictureBox && x.Tag == "p")
            {
                if (player.Bounds.IntersectsWith(x.Bounds) && !jumping)
                {
                    force = 8;
                    player.Top = x.Top - player.Height;
                }
            }

            if (player.Bounds.IntersectsWith(Door.Bounds))
            {
                timer1.Stop();
                MessageBox.Show("You Won!");
                this.Close();
            }
        }
    }
}

The gravity force and everything works great EXCEPT for one big problem with the player that I definitely can't solve without some help.

The problem is: the player is completely glitched and it keeps going up and down. I realised that this is because of two lines in private void timer1_Tick(object sender, EventArgs e):

player.Top += JumpSpeed;

and

player.Top = x.Top - player.Height;

Both of these try to change player.Top and interfere with each other. The trouble is that I can't just cut one of the two without destroying the gravity force code. What I think might work is applying player.Top += JumpSpeed; ONLY if(player.Bounds.IntersectsWith(x.Bounds) && !jumping) = false but I don't know how to write the code this way at all (previous tries always ended up with errors).

Thanks in advance for any help and please forgive any grammar errors that I made because I am not a native english speaker.

Body:
I don't know how your Form looks like, but with what you provided I would change the code like that:

public partial class Form1 : Form
{
    bool goleft = false;
    bool goright = false;

    int JumpSpeed = 0; //current vertical speed
    int force = 8; //initial jump speed
    int score = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void keyisdown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = true;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = true;
        }
        if (e.KeyCode == Keys.Space && JumpSpeed==0) //JumpSpeed==0 to prevent "double jump"
        {
            JumpSpeed = force; //start jumping with full power
        }
    }

    private void keyisup(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
        {
            goleft = false;
        }
        if (e.KeyCode == Keys.Right)
        {
            goright = false;
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (goleft)
        {
            player.Left -= 5;
        }
        if (goright)
        {
            player.Left += 5;
        }

        JumpSpeed -= 1; //decrement the vertical speed = gravity -> choose higher value to bring him back on the ground quicker
        player.Top -= JumpSpeed;

        if (player.Bounds.IntersectsWith(Door.Bounds))
        {
            timer1.Stop();
            MessageBox.Show("You Won!");
            this.Close();
        }

        foreach (PictureBox x in this.Controls.OfType<PictureBox>())
        {
            if (x.Tag == "p")
            {
                if (player.Bounds.IntersectsWith(x.Bounds)) //if the player should be able to jump/walk on something the code is
                {
                    player.Top = x.Top - player.Height;
                    JumpSpeed = 0; //the player stops falling
                }
            }
        }
    }
}

To make sure to player does not fall out of the window place PictureBoxes with tag == p on the floor!

PS:

Feel free to leave a comment!


问:
Jenkins build failing - missing file Microsoft.Build.Utilities.Core
I've set up a new project in Jenkins.
When I try to build it I get the following error:

"E:\Jenkins\workspace\MWAPIv1\My.WebAPIv1.sln" (default target) (1) ->
  "E:\Jenkins\workspace\MWAPIv1\My.WebAPIv1\My.WebAPIv1.csproj" (default target) (2) ->
  (CoreCompile target) ->
    C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.targets(316,9): error MSB4062: The "Microsoft.CodeAnalysis.BuildTasks.Csc" task could not be loaded from the assembly E:\Jenkins\workspace\MWAPIv1\packages\Microsoft.Net.Compilers.2.2.0\build..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the  declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask. [E:\Jenkins\workspace\MWAPIv1\My.WebAPIv1\My.WebAPIv1.csproj]

The project uses NET 4.5.2 Framework.

Some other possibly useful information:
Since the error mentions missing dlls, I checked in all files, including the packages folder and contents to SVN, but this didn't help.
I also updated all Nuget packages from within VS2015 and checked in any updates.
The project configuration in Jenkins is:
MSBuild Version: Microsoft.NET Framework v4.0
MSBuild Build File: My.WebAPIv1.sln
Command Line Arguments: /p:VisualStudioVersion=14.0

The following folders exist in my Jenkins server:

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v9.0

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0

Any ideas how to get my project to build?

Thanks

答:
Your build is running using the .net framework provided version of MSBuild (4.0.30319), which is quite old and has a different architecture that the Microsoft.Net.Compilers NuGet package expects, which you seem to use to override the old build targets to use a newer compiler.

Use a newer version of MSBuild for this to work, e.g. the one installed by VS 2015 at C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe (alternative: install and use the "build tools for visual studio" 2015 or 2017)


问:
Git - Diff between branches in old commits
I have this:

```<code>branch: commit 1, commit 2, 3,4
master: commit 1, commit 2, 3,4,5,6,7
</code>```

How can you make a diff between branch after commit 2 (in that point of history) and master in commit 3?

答:
You can always and in any time check the difference between commits with

```<code>git diff commit1..commit2
</code>```

You can substitute commit with branch names.

```<code>git diff master..foo
</code>```

or also with HEAD

```<code>git diff master..HEAD
</code>```

and so on.

Here a real example:

```<code>git diff e8e1956c174da9d..90f2b3ee988d8b6
</code>```

Note that the complete hash is not necessary.

Body:
I have this:

branch: commit 1, commit 2, 3,4
master: commit 1, commit 2, 3,4,5,6,7

How can you make a diff between branch after commit 2 (in that point of history) and master in commit 3?

Body:
You can always and in any time check the difference between commits with

git diff commit1..commit2

You can substitute commit with branch names.

git diff master..foo

or also with HEAD

git diff master..HEAD

and so on.

Here a real example:

git diff e8e1956c174da9d..90f2b3ee988d8b6

Note that the complete hash is not necessary.


问:
How to inject a Spring bean id into another Spring Configured Bean?
I want to be able to pass a bean ID into another bean by reference. So if I have this:

```<code><bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" value="<specialName.name>"/>
</bean>
</code>```

```<code>public class ReferenceBean {

    // The spring injected value of this should be 'specialName'
    public String refId;

    // getter & setter for refId
}
</code>```

The reason I need this, it that ReferenceBean is actually a route builder in Camel and it directs messages to SpecialBean through the Spring Registry. I'm new to Spring and Camel, so if this is an ill conceived questions, my apologies.

答:
You could use the idref element (see Spring XML Beans Schema):

```<code><bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId">
        <idref bean="specialName"/>
    </property>
</bean>
</code>```

Body:
I want to be able to pass a bean ID into another bean by reference. So if I have this:

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" value="<specialName.name>"/>
</bean>

public class ReferenceBean {

    // The spring injected value of this should be 'specialName'
    public String refId;

    // getter & setter for refId
}

The reason I need this, it that ReferenceBean is actually a route builder in Camel and it directs messages to SpecialBean through the Spring Registry. I'm new to Spring and Camel, so if this is an ill conceived questions, my apologies.

Body:
You could use the idref element (see Spring XML Beans Schema):

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId">
        <idref bean="specialName"/>
    </property>
</bean>


问:
Yeoman on Ubuntu with Vs Code issue (Aspnet Core)
I have created a Web App using Yeoman aspnet generator but I am not able to insert a new mvc controller to my app, I have tried to see

yo aspnet --help

to see all the available generators but I cannot see

aspnet:mvccontroller

I am only seeing one for nuget and one for web.config

Please help how can I add a controller from it

答:
You are missing the yo before the subgenerator aspnet:MvcController

The right command is yo aspnet:MvcController ControllerName

UPDATE:

The subgenerators are removed from generator during migration to RC version (now 0.3.* on NPM). I think you should add a controller manually in this last version.

Source: https://github.com/OmniSharp/generator-aspnet/issues/934#issuecomment-286722058


问:
How do I use enums in TSQL without hard coding magic number all over my SQL scripts/procs?
We have enums in our C# code:

```<code>public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}
</code>```

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

```<code>SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)
</code>```

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

答:
In pure TSQL the only similar thing I can think is a scalar UDF that returns the vale wanted.

In LINQ to SQL you can map members as c#/.NET enums, and it handles it for you.

But to be honest; in most pure TSQL I'd mainly just use the literals.

Body:
We have enums in our C# code:

public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".


问:
Is there a way to force a locale when formatting a date in Outlook?
I am wondering if there is an Outlook VBA equivalent to "[$-409]mmmm yyyy" that lets Excel display a date in the locale you want.

Format(Date, "[$-409]mmmm yyyy") is just silently ignored and only displays in the system locale (I need to use 2 different locales at two different places so changing the system locale is not an option).

EDIT: My question is actually pretty much a duplicate of this one and it seems not possible in either application Outlook or PowerPoint.

答:
Sorry I did not make my point clearly in my comment.

When you include “$-409” in a format, it is you that has decided that an American format date is required.  Excel may help you create an American format date but it will not help you decide which format date is required.

It is you who will have to determine that Jesse gets an American date, John gets a British date and Jacque gets a French date.  Once you have made that decision, VB will accept a country code when formatting a date but I do not believe that VBA offers any such functionality.  Since you only have two locales, I suggest you do the conversion yourself.

```<code>Option Explicit
Sub Demo()

 Dim Prompt As String
 Dim Recipient As String
 Dim MonthsFrench() As Variant
 Dim Today As Date

 Today = Now()
 MonthsFrench = VBA.Array("", "Janvier", "Févier", "Mars", "Avril", "Mai", "Juin", _
                          "Juillet", "Auguste", "Septembre", "Octobre", "Novembre", "Décembre")
 ' I have used VBA.Array so lower bound is zero regardless of option base setting

 Debug.Print Format(Today, "d mmmm yyyy")
 Debug.Print Format(Today, "mmmm d, yyyy")
 Debug.Print Day(Today) & " " & MonthsFrench(Month(Today)) & " " & Year(Today)

 Do While True
   If Recipient = "" Then
     Prompt = "Recipient name?"
   Else
     Prompt = "Last recipient, " & Recipient & " preferred date is "
     Select Case Recipient
       Case "Jesse"
         Prompt = Prompt & Format(Today, "mmmm d, yyyy")
       Case "John"
         Prompt = Prompt & Format(Today, "d mmmm yyyy")
       Case "Jacque"
         Prompt = Prompt & Day(Today) & " " & MonthsFrench(Month(Today)) & " " & Year(Today)
       Case Else
         Prompt = "Last recipient not known"
     End Select
     Prompt = Prompt & vbLf & "Next recipient name?"
   End If
   Recipient = InputBox(Prompt)
   If Recipient = "" Then
     Exit Sub
   End If
 Loop

End Sub
</code>```

Body:
Sorry I did not make my point clearly in my comment.

When you include “$-409” in a format, it is you that has decided that an American format date is required.  Excel may help you create an American format date but it will not help you decide which format date is required.

It is you who will have to determine that Jesse gets an American date, John gets a British date and Jacque gets a French date.  Once you have made that decision, VB will accept a country code when formatting a date but I do not believe that VBA offers any such functionality.  Since you only have two locales, I suggest you do the conversion yourself.

Option Explicit
Sub Demo()

 Dim Prompt As String
 Dim Recipient As String
 Dim MonthsFrench() As Variant
 Dim Today As Date

 Today = Now()
 MonthsFrench = VBA.Array("", "Janvier", "Févier", "Mars", "Avril", "Mai", "Juin", _
                          "Juillet", "Auguste", "Septembre", "Octobre", "Novembre", "Décembre")
 ' I have used VBA.Array so lower bound is zero regardless of option base setting

 Debug.Print Format(Today, "d mmmm yyyy")
 Debug.Print Format(Today, "mmmm d, yyyy")
 Debug.Print Day(Today) & " " & MonthsFrench(Month(Today)) & " " & Year(Today)

 Do While True
   If Recipient = "" Then
     Prompt = "Recipient name?"
   Else
     Prompt = "Last recipient, " & Recipient & " preferred date is "
     Select Case Recipient
       Case "Jesse"
         Prompt = Prompt & Format(Today, "mmmm d, yyyy")
       Case "John"
         Prompt = Prompt & Format(Today, "d mmmm yyyy")
       Case "Jacque"
         Prompt = Prompt & Day(Today) & " " & MonthsFrench(Month(Today)) & " " & Year(Today)
       Case Else
         Prompt = "Last recipient not known"
     End Select
     Prompt = Prompt & vbLf & "Next recipient name?"
   End If
   Recipient = InputBox(Prompt)
   If Recipient = "" Then
     Exit Sub
   End If
 Loop

End Sub


问:
What does In [*] at the upper left-hand of the cell mean when running a jupyter notebook?
What does In [*] at the upper left-hand of the cell mean when running a jupyter notebook and how I can resolve this?

Please any one can help me.

答:
It means that the cell is running, or in queue to be run. You don't solve it really, you just have to wait for the cell to finish executing. If you think the cell has gotten stuck for some reason, you can try to interrupt it by going to "Kernel" in the menu bar and selecting "Interrupt". When the cell is finished running, a number will appear instead of a star. The number is the order in which that cell was executed in this session.

If you have a cell that takes a really long time to execute, I suggest outputting some periodic status to the user. I like to do something like:

update_freq = 100  # or however often you want it to update you
print('Running', end='', flush=True)
for iter in range(a_whole_lot_of_iterations):
    # ... code that runs for a long time or for a ton of iterations ...
    if iter >= update_freq and iter % summary_freq == 0:
        print('.', end='', flush=True)  # periodically print something
print('done!')
```

You can get as fancy as you want with this approach, printing all kinds of cool stuff in your first line as a header, controlling how many updates are printed total to the screen so you can create a sort of ASCII status bar, etc. I found this guide to the Python string formatting language helpful when figuring out how to make nicely formatted status updates.

Body:
It means that the cell is running, or in queue to be run. You don't solve it really, you just have to wait for the cell to finish executing. If you think the cell has gotten stuck for some reason, you can try to interrupt it by going to "Kernel" in the menu bar and selecting "Interrupt". When the cell is finished running, a number will appear instead of a star. The number is the order in which that cell was executed in this session.

If you have a cell that takes a really long time to execute, I suggest outputting some periodic status to the user. I like to do something like:

update_freq = 100  # or however often you want it to update you
print('Running', end='', flush=True)
for iter in range(a_whole_lot_of_iterations):
    # ... code that runs for a long time or for a ton of iterations ...
    if iter >= update_freq and iter % summary_freq == 0:
        print('.', end='', flush=True)  # periodically print something
print('done!')

You can get as fancy as you want with this approach, printing all kinds of cool stuff in your first line as a header, controlling how many updates are printed total to the screen so you can create a sort of ASCII status bar, etc. I found this guide to the Python string formatting language helpful when figuring out how to make nicely formatted status updates.


问:
How to pass class name as generic type <T> based on enum value?
I have the below function.

```<code>public static string SerializeObjectToXML<T>(object mainColumn)
{
   return string.empty;
}
</code>```

I am trying to pass classname based on enum value as below.

```<code>var tempstr = ClassName.SerializeObjectToXML<EnumClass.class1 == enumvalue ? ClassA: ClassB>(value);
</code>```

Can I do this?  If not how can I achieve this using inline enum condition?

答:
I can't help but think you are not using generics to your full advantage.  Just change object in your code to T.  Something like this:

```<code>public string SerializeObjectToXml<T>(T obj)
{
    var sb = new StringBuilder();
    using (var wrt = new StringWriter(sb))
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        xs.Serialize(wrt, obj);
    }

    return sb.ToString();
}
</code>```

And then call it like this:

```<code>ClassA a = new ClassA();
string objXml = SerializeObjectToXml(a);
</code>```

Body:
I have the below function.

public static string SerializeObjectToXML<T>(object mainColumn)
{
   return string.empty;
}

I am trying to pass classname based on enum value as below.

var tempstr = ClassName.SerializeObjectToXML<EnumClass.class1 == enumvalue ? ClassA: ClassB>(value);

Can I do this?  If not how can I achieve this using inline enum condition?

Body:
I can't help but think you are not using generics to your full advantage.  Just change object in your code to T.  Something like this:

public string SerializeObjectToXml<T>(T obj)
{
    var sb = new StringBuilder();
    using (var wrt = new StringWriter(sb))
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        xs.Serialize(wrt, obj);
    }

    return sb.ToString();
}

And then call it like this:

ClassA a = new ClassA();
string objXml = SerializeObjectToXml(a);


问:
Jenkins - Run same job on DIFFERENT machine concurrently
Here is the scenario for the problem. I have one job which plays with machine host file.
I want to run that job with flag(to change host) as 0 and 1 concurrently.

Got to know about Jenkins plugin for concurrent run but it may happen that both job instances run on same slave and creating problem with host file(different flags to change/unchange the file)

I am looking for something by which i can run both instances, BUT ON DIFFERENT SLAVES.

Help needed.

Thanks in advance.

答:
As per my knowledge, you can use the "Throttle Concurrent Builds". It's compatible with Jenkins 2.0 as well.

To Configure this plugin, just download and install this plugin. Once done, go to job configuration and you will see "Throttle Concurrent Builds" in General section. Check that option and you will be asked for further configuration.

Please find below the screenshot for the same.

if you have multiple projects you can uncheck the "throttle this project alone"

and to utilize to the fullest, you can keep the "maximum total concurrent builds" to a number of slaves that you have. for example. let's say you have 8 nodes so you can configure it to run 8 concurrent instances of this build.

and for "maximum concurrent builds per node" you can keep it as 1 if you want only one node to build one instance.


问:
webpack-dev-middleware compiles twice on boot
With the same webpack.config.js, webpack-dev-server runs a compile once on boot, but my webpack-dev-middleware setup compiles twice immediately upon startup.

I've added some logging in chokidar to make sure that a file change isn't happening and it doesn't appear to be. Any ideas on how to tell what is triggering the second compile?

答:
My logging for file watching was in the wrong place. It was actually file changes that I kick off right before starting the dev server. I'm not sure how to make it less sensitive,  but that's a different issue.

For posterity, to add logging to find out what changed, I manually edited node_modules/watchpack/lib/watchpack.js and added a console.log(file) within the watcher.on("change"...


问:
Open and write an xml file in C#
I have a xml file which I want to open and write in. The xml file has this structure:

```<code> <?xml version="1.0" encoding="UTF-8"?>
   <polygons>
     <polygon name="polygon-1">
         <point>
            <x>38,241885</x>
            <y>-5,965407</y>
         </point>
          <point>
            <x>38,242251</x>
            <y>-5,965423</y>
         </point>
    </polygon>
    <polygon name="polygon-2">
        .
        .
    </polygon>
  </polygons>
</code>```

I want to add new polygons into my xml, so I have to read it and then add a polygon at the last position. ¿How can I do this?

答:
Here are a few different methods using xml linq</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication59
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><polygons></polygons>";

            XDocument doc = XDocument.Parse(xmlHeader);
            XElement polygons = doc.Root;

            polygons.Add(new XElement("polygon", new object[] {
                new XAttribute("name","polygon-1"),
                new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                })
            }));

            XElement polygon = polygons.Element("polygon");

            XElement newPoint = new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                });

            polygon.Add(newPoint);

        }
    }
}
</code>```

Title: Open and write an xml file in C#

Body:
I have a xml file which I want to open and write in. The xml file has this structure:

 <?xml version="1.0" encoding="UTF-8"?>
   <polygons>
     <polygon name="polygon-1">
         <point>
            <x>38,241885</x>
            <y>-5,965407</y>
         </point>
          <point>
            <x>38,242251</x>
            <y>-5,965423</y>
         </point>
    </polygon>
    <polygon name="polygon-2">
        .
        .
    </polygon>
  </polygons>

I want to add new polygons into my xml, so I have to read it and then add a polygon at the last position. ¿How can I do this?

Body:
Here are a few different methods using xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication59
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><polygons></polygons>";

            XDocument doc = XDocument.Parse(xmlHeader);
            XElement polygons = doc.Root;

            polygons.Add(new XElement("polygon", new object[] {
                new XAttribute("name","polygon-1"),
                new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                })
            }));

            XElement polygon = polygons.Element("polygon");

            XElement newPoint = new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                });

            polygon.Add(newPoint);

        }
    }
}


问:
Discovering Hazelcast Cluster Groups
I'm using a couple of Hazelcast clusters for separate purposes and don't want them to interact so have used different cluster groups. I've written a simple monitor application to keep track of the members of each cluster, but wondered if there's a way of determining which cluster groups are reachable? The monitor connects as a client and I've had to hard code cluster group names in my application configuration so it can attempt to create a connection with each. That's fine for the moment with only two groups but as my usage expands it would be helpful if I could programmatically determine all the clusters available for connection - is this possible?

Thanks

答:
Hazelcast members exposes monitoring data via JMX protocol. groupName and list of members can be discovered via JMX connection to a member:

http://docs.hazelcast.org/docs/latest-development/manual/html/Management/JMX_API_Per_Member.html

Title: Discovering Hazelcast Cluster Groups


问:
pgAdmin won't start (eternal loading)
Once upon a time I had a Postgres database that worked with pgAdmin. I have a webservice running on a WildFly server that made connections to the DB and everything worked fine.

After a while(a few months) I have tried to open pgAdmin again and it stuck on the loading...

I remove postgres and pgAdmin using Revo Uninstall, then installed postgres 9.6 and opened pgAdmin and it stays in the loading screen forever.

Can anyone help me ? [Using postgres 9.6 with pgAdmin v1.3],

On Event Viewer I saw the following error in pgAdmin :

Faulting application name: pgAdmin4.exe, version: 0.0.0.0, time stamp: 0x580f31f6
Faulting module name: MSVCP120.dll, version: 6.3.9600.18438, time stamp: 0x57ae642e
Exception code: 0xc0000135
Fault offset: 0x00000000000ecdd0
Faulting process id: 0x1de4
Faulting application start time: 0x01d2a7d1566324ba
Faulting application path: C:\Program Files\PostgreSQL\9.6\pgAdmin 4\bin\pgAdmin4.exe
Faulting module path: MSVCP120.dll
Report Id: 984dd9d8-13c4-11e7-832d-5ce0c535006f
Faulting package full name:
Faulting package-relative application ID:

答: I just had the same issue on a Windows 7, 64bit machine, DBA told me to "upgrade" to pgAdmin 3 (latest build) and it works.</p>

Title: pgAdmin won't start (eternal loading)


问:
documentdb emulator gatewayservice crashing on startup
I was looking to learn about documentdb and installed the emulator seemingly without error. However, upon startup I have a service crashing:

GatewayServiceStartup

Judging from the title I am guessing it is an important service to the emulator. Interestingly enough it seems like the emulator continues to load and attempts to open :
https://localhost:8081/_explorer/index.html

without success.

using the command prompt I attempted to start the gateway services manually and here is the results:

C:\Program Files\DocumentDB Emulator\Packages\GatewayService\GatewayService.Code>documentdb.gatewayservice.exe /?

Unhandled Exception: System.Runtime.InteropServices.COMException: Invalid value for registry (Exception from HRESULT: 0x80040153 (REGDB_E_INVALIDVALUE))
   at System.Runtime.InteropServices.RuntimeEnvironment.GetDeveloperPath()
   at System.AppDomain.SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
   at System.AppDomain.SetupDomain(Boolean allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)

C:\Program Files\DocumentDB Emulator\Packages\GatewayService\GatewayService.Code>documentdb.startupentrypoint.exe /?

Unhandled Exception: System.Runtime.InteropServices.COMException: Invalid value for registry (Exception from HRESULT: 0x80040153 (REGDB_E_INVALIDVALUE))
   at System.Runtime.InteropServices.RuntimeEnvironment.GetDeveloperPath()
   at System.AppDomain.SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
   at System.AppDomain.SetupDomain(Boolean allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)

C:\Program Files\DocumentDB Emulator\Packages\GatewayService\GatewayService.Code>

Is the gateway service relevant? Any idea how to fix?

Quick Edit:
I have followed the directions listed here:
https://learn.microsoft.com/en-us/azure/documentdb/documentdb-nosql-local-emulator#troubleshooting

No etl file is generated to be emailed.

Thanks in advance

答:
I got the following exception when debugging the GatewayServiceStartup process:

Cannot load Counter Name data because an invalid index '' was read
  from the registry.

Fixed it using Cannot load Counter Name data because an invalid index -Exception:

In an elevated command prompt:

```<code>C:\windows\SysWOW64> lodctr /r
</code>```

Body:
I got the following exception when debugging the GatewayServiceStartup process:

Cannot load Counter Name data because an invalid index '' was read
  from the registry.

Fixed it using Cannot load Counter Name data because an invalid index -Exception:

In an elevated command prompt:

C:\windows\SysWOW64> lodctr /r


问:
ABCpdf 64-bit core engine version 10105 is older than ABCpdf .NET version 10.1.0.7
I am using ABCpdf.net to merge few pdf files. but I am getting below error while creating object of Doc class...

ABCpdf 64-bit core engine version 10105 is older than ABCpdf .NET version 10.1.0.7.

There is no other error information available in exception snapshot. Code which is throwing error...

```<code>Doc mergedPdf = new Doc();
</code>```

I am using ABCPdf.net version 10.1.0.5 and have no reference of ABCpdf.net version 10.1.0.7.

How to resolve this?

答: The .dll version in production machine and the .dll version in developing machine is different; reinstalling .dll will fix the problem.

Body:
I am using ABCpdf.net to merge few pdf files. but I am getting below error while creating object of Doc class...

ABCpdf 64-bit core engine version 10105 is older than ABCpdf .NET version 10.1.0.7.

There is no other error information available in exception snapshot. Code which is throwing error...

Doc mergedPdf = new Doc();

I am using ABCPdf.net version 10.1.0.5 and have no reference of ABCpdf.net version 10.1.0.7.

How to resolve this?


问:
JDBC, connection is ok but does not execute query
I'm writing a small program with a mysql connection. I have to insert data into the database. The connection is ok but when I try to execute a query it doesn't work. all statements after executeQuery() statement doesn't work.

```<code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Connection connect=null;
    PreparedStatement preparedStatement;
    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql//localhost/jarvis";
    String USER = "test";
    String PASS = "test";
    try{
        Class.forName(JDBC_DRIVER);
        connect = DriverManager.getConnection(DB_URL, USER, PASS);
    }
    catch(ClassNotFoundException e){
        out.println("Errore: "+e);
    } catch (SQLException ex) {
        Logger.getLogger(Prova.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.println();
    out.println("qui");
    String query = "INSERT INTO users(Nome, Cognome, Username, Password) values(?, ?, ?, ?)";
    try (PreparedStatement insert = connect.prepareStatement(query)) {

        insert.setString(1, "name");
        insert.setString(2, "sur");
        insert.setString(3, "gvhgv");
        insert.setString(4, "qfwe");

        insert.executeUpdate();
    }
    catch(Exception e){
        out.println("Errore "+e);
    }
    out.println("Fine");

}
</code>```

on executeQuery it stop working and doesn't insert the values into the database.

P.S.: sorry for my English
foto

答:
Firstly your JDBC Connection URL is wrong, it should be this

```<code>String DB_URL = jdbc:mysql://localhost/jarvis
</code>```

instead of this:

```<code>String DB_URL = jdbc:mysql//localhost/jarvis
</code>```

You can follow the MySQL documentation whenever you are in doubt about anything.

Please note that mentioning port is not necessary if it is skipped it would default to MySQL's default port 3306.

Secondly, use executeUpdate() method instead of executeQuery method. It is best suggested to test your code in chunks, like DB Connection is successful, able to retrieve data from the underlying DB and then inserting into the DB.

Or even a better way is to debug your code and at least provide where you find the NullPointerException as you say you're getting now!

Edit:

You must have your JDBC Connector/J jar available for your code to access it if you use an IDE (then in its build path) and in the CLASSPATH global variable (for references when we don't use an IDE). It is better to have it on your CLASSPATH if you are not going to change these dependencies any often.

Hope this helps!

Body:
I'm writing a small program with a mysql connection. I have to insert data into the database. The connection is ok but when I try to execute a query it doesn't work. all statements after executeQuery() statement doesn't work.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Connection connect=null;
    PreparedStatement preparedStatement;
    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql//localhost/jarvis";
    String USER = "test";
    String PASS = "test";
    try{
        Class.forName(JDBC_DRIVER);
        connect = DriverManager.getConnection(DB_URL, USER, PASS);
    }
    catch(ClassNotFoundException e){
        out.println("Errore: "+e);
    } catch (SQLException ex) {
        Logger.getLogger(Prova.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.println();
    out.println("qui");
    String query = "INSERT INTO users(Nome, Cognome, Username, Password) values(?, ?, ?, ?)";
    try (PreparedStatement insert = connect.prepareStatement(query)) {

        insert.setString(1, "name");
        insert.setString(2, "sur");
        insert.setString(3, "gvhgv");
        insert.setString(4, "qfwe");

        insert.executeUpdate();
    }
    catch(Exception e){
        out.println("Errore "+e);
    }
    out.println("Fine");

}

on executeQuery it stop working and doesn't insert the values into the database.

P.S.: sorry for my English
foto

Body:
Firstly your JDBC Connection URL is wrong, it should be this

String DB_URL = jdbc:mysql://localhost/jarvis

instead of this:

String DB_URL = jdbc:mysql//localhost/jarvis

You can follow the MySQL documentation whenever you are in doubt about anything.

Please note that mentioning port is not necessary if it is skipped it would default to MySQL's default port 3306.

Secondly, use executeUpdate() method instead of executeQuery method. It is best suggested to test your code in chunks, like DB Connection is successful, able to retrieve data from the underlying DB and then inserting into the DB.

Or even a better way is to debug your code and at least provide where you find the NullPointerException as you say you're getting now!

Edit:

You must have your JDBC Connector/J jar available for your code to access it if you use an IDE (then in its build path) and in the CLASSPATH global variable (for references when we don't use an IDE). It is better to have it on your CLASSPATH if you are not going to change these dependencies any often.

Hope this helps!


问:
C++ Variable doesn't change until thread finished
I wrote a very simple code to reproduce my problem.

```<code>#include <iostream>
#include "tools.h"  //contains s_sleep()
#include <thread>
using namespace std;

void change( int *i)
{
        while (true)
        {
                *i = 4356;
        }
}

int main()
{
        int v=3;
        cout << v <<endl;
        thread t(change, &v);
        s_sleep(1); //sleep one second
        cout << v << endl;
        t.join();
}
</code>```

The output is 3, and after a second 3 again. But when I change one line to

```<code>//while ( true )
</code>```

I receive 3, and a second later 4356.

How can that be?
Hope somebody can help.

答:
Please specify what compiler you are using. I am using Microsoft Visual C++ compiler, and with my visual studio, I see for both time, the output is 3 followed by 4356.

Here is the code I ran on my computer.

```<code>#include <ctime>
#include <thread>
#include <iostream>
using namespace std;
void change(int *i) {
    while (true) { // commented out this later, the result is same.
        *i = 4356;
    }
}

int main() {
clock_t tstart = clock();
    int v = 3;
    cout << v << endl;
    thread t(change, &v);
    while(double(clock() - tstart)/CLOCKS_PER_SEC < 3.0) { // Instead of your s_sleep
        int x = 1; // Just a dummy instruction
    }
    cout << v << endl;
    t.join();
    return 0;
}
</code>```

The explanation to my result is that the thread "t" does not know anything about the variable "v". It just gets a pointer of type int and it edits the value at the pointers location directly to the memory. So, when the main(first) thread
again accesses the variable "v", it simply reads the memory assigned to "v" and prints what it gets.

And also, what code is in the "tools.h"? Does it have anything to do with the variable "v".

If it doesn't, then it must be a compiler variance(Your compiler may be different than mine, maybe gcc or g++?). That means, your compiler must have cached(or something like that) the variable for faster access. And as in the current thread, the variable has not been changed, whenever it is accessed, compiler gives the old value(which the compiler sees as unchanged) of the variable. (I AM NOT SURE ABOUT THIS)

Body:
I wrote a very simple code to reproduce my problem.

#include <iostream>
#include "tools.h"  //contains s_sleep()
#include <thread>
using namespace std;

void change( int *i)
{
        while (true)
        {
                *i = 4356;
        }
}

int main()
{
        int v=3;
        cout << v <<endl;
        thread t(change, &v);
        s_sleep(1); //sleep one second
        cout << v << endl;
        t.join();
}

The output is 3, and after a second 3 again. But when I change one line to

//while ( true )

I receive 3, and a second later 4356.

How can that be?
Hope somebody can help.

Body:
Please specify what compiler you are using. I am using Microsoft Visual C++ compiler, and with my visual studio, I see for both time, the output is 3 followed by 4356.

Here is the code I ran on my computer.

#include <ctime>
#include <thread>
#include <iostream>
using namespace std;
void change(int *i) {
    while (true) { // commented out this later, the result is same.
        *i = 4356;
    }
}

int main() {
clock_t tstart = clock();
    int v = 3;
    cout << v << endl;
    thread t(change, &v);
    while(double(clock() - tstart)/CLOCKS_PER_SEC < 3.0) { // Instead of your s_sleep
        int x = 1; // Just a dummy instruction
    }
    cout << v << endl;
    t.join();
    return 0;
}

The explanation to my result is that the thread "t" does not know anything about the variable "v". It just gets a pointer of type int and it edits the value at the pointers location directly to the memory. So, when the main(first) thread
again accesses the variable "v", it simply reads the memory assigned to "v" and prints what it gets.

And also, what code is in the "tools.h"? Does it have anything to do with the variable "v".

If it doesn't, then it must be a compiler variance(Your compiler may be different than mine, maybe gcc or g++?). That means, your compiler must have cached(or something like that) the variable for faster access. And as in the current thread, the variable has not been changed, whenever it is accessed, compiler gives the old value(which the compiler sees as unchanged) of the variable. (I AM NOT SURE ABOUT THIS)


问:
Call multiple stored procedures from Codeigniter last result contains the previous
I'm using this library in Codeigniter to retrieve multiple result sets from stored procedures :

```<code>class Multi_Results
{
   private $CI, $Data, $mysqli, $ResultSet;

   /**
   * The constructor
   */

   function __construct()
   {
     $this->CI =& get_instance();
     $this->Data = '';
     $this->ResultSet = array();
     $this->mysqli = $this->CI->db->conn_id;
   }

    public function GetMultiResults($SqlCommand)
    {
        /* execute multi query */
        if (mysqli_multi_query($this->mysqli, $SqlCommand)) {
            $i=1;
            do
            {
                if ($result = $this->mysqli->store_result())
                {
                    while ($row = $result->fetch_assoc())
                    {
                        $this->Data[$i][] = $row;
                    }
                    mysqli_free_result($result);
                }
                $i++;
            }
            while ($this->mysqli->more_results() && $this->mysqli->next_result());
        }
        return $this->Data;
    }

}
</code>```

I'm calling the procedure from the controller like

```<code>$result_array = $this->multi_results->GetMultiResults("CALL procedure_name($input_1, '$input_2')");
</code>```

It does what it is supposed to do. The problem arises when I call 2 DIFFERENT procedures from the controller one after another and assign the results to different variables.
When I var_dump the second (last) result, it contains also the result set from the 1st result.
I have checked the connection dbdriver in database.php (it is set to MSQLI), I tried to implement some suggestions like :
 CodeIgniter active records' problems calling multiple stored procedures and Calling a stored procedure from CodeIgniter's Active Record class
They both propose a solution with 'mysqli_free_result' however that is already done in the addon library (as you can see in the code snippet above).

Any suggestion will be highly appreciated!

答:
Initiate $this->data = '' into the function GetMultiResults() instead into constructor.
 I think this will solve your problem.

Body:
I'm using this library in Codeigniter to retrieve multiple result sets from stored procedures :

class Multi_Results
{
   private $CI, $Data, $mysqli, $ResultSet;

   /**
   * The constructor
   */

   function __construct()
   {
     $this->CI =& get_instance();
     $this->Data = '';
     $this->ResultSet = array();
     $this->mysqli = $this->CI->db->conn_id;
   }

    public function GetMultiResults($SqlCommand)
    {
        /* execute multi query */
        if (mysqli_multi_query($this->mysqli, $SqlCommand)) {
            $i=1;
            do
            {
                if ($result = $this->mysqli->store_result())
                {
                    while ($row = $result->fetch_assoc())
                    {
                        $this->Data[$i][] = $row;
                    }
                    mysqli_free_result($result);
                }
                $i++;
            }
            while ($this->mysqli->more_results() && $this->mysqli->next_result());
        }
        return $this->Data;
    }

}

I'm calling the procedure from the controller like

$result_array = $this->multi_results->GetMultiResults("CALL procedure_name($input_1, '$input_2')");

It does what it is supposed to do. The problem arises when I call 2 DIFFERENT procedures from the controller one after another and assign the results to different variables.
When I var_dump the second (last) result, it contains also the result set from the 1st result.
I have checked the connection dbdriver in database.php (it is set to MSQLI), I tried to implement some suggestions like :
 CodeIgniter active records' problems calling multiple stored procedures and Calling a stored procedure from CodeIgniter's Active Record class
They both propose a solution with 'mysqli_free_result' however that is already done in the addon library (as you can see in the code snippet above).

Any suggestion will be highly appreciated!


问:
Button Position in Xaml
I am trying to position a button at the bottom of the screen using Xaml or the code behind. This is what I am trying to achieve:

Here is the Xaml:

```<code><StackLayout>

            <Label Text="Identification"
                   x:Name="DriverLabel"/>

            <Image x:Name="VigoLogo"/>

            <Entry Placeholder="Driver Name"
                   Text="{Binding driverID}"/>

    <Button Text="Submit"
            Command="{Binding Submit}"
            x:Name="SubmitButton"
            HorizontalOptions="CenterAndExpand"
            ></Button>

</StackLayout>
</code>```

and the code behind:`

```<code>// Styling and resources
            // *************************
            // Whole page ino
            BackgroundColor = Color.White;
            // ID Label at top of screen styles
            DriverLabel.BackgroundColor = Color.LightBlue;
            DriverLabel.HorizontalTextAlignment = TextAlignment.Center;
            DriverLabel.VerticalTextAlignment = TextAlignment.Center;
            DriverLabel.FontSize = 20;
            DriverLabel.HeightRequest = 80;
            DriverLabel.TextColor = Color.Black;

            //VigoLogo Information
            VigoLogo.Source = "Resources/vigo_sign.png";

            // Submit button
            SubmitButton.BackgroundColor = Color.LightBlue;
            SubmitButton.VerticalOptions = LayoutOptions.End;`
</code>```

I have tried various things with relative and absolute positioning but because I am new to Xamarin I am getting in a mess more than anything else.
I got somewhere using AbsoluteLayout but it seems that only hard coding x and y coordinates works but it needs to be more dynamic than that for different devices.

Any help would be appreciated.

答:
You can do this with a Grid. We can define 4 rows (starting with index '0').
The last row (index 3) can be set to take all the remaining space so the button can be placed with VerticalOptions to End to keep stuck to the bottom.

```<code><Grid>
   <Grid.RowDefinitions>
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <RowDefinition Height="*" />
   </Grid.RowDefinitions>

            <Label Text="Identification" Grid.Row="0"
                   x:Name="DriverLabel"/>

            <Image x:Name="VigoLogo" Grid.Row="1"/>

            <Entry Placeholder="Driver Name" Grid.Row="2"
                   Text="{Binding driverID}"/>

    <Button Text="Submit"  Grid.Row="3"
            Command="{Binding Submit}"
            x:Name="SubmitButton"
            HorizontalOptions="FillAndExpand" VerticalOptions="End"
            ></Button>

</Grid>
</code>```

I suggest you read about Layouts in order to choose the best one for each situation. https://developer.xamarin.com/guides/xamarin-forms/user-interface/controls/layouts/

Title: Button Position in Xaml

Body:
I am trying to position a button at the bottom of the screen using Xaml or the code behind. This is what I am trying to achieve:

Here is the Xaml:

<StackLayout>

            <Image x:Name="VigoLogo"/>

            <Entry Placeholder="Driver Name"
                   Text="{Binding driverID}"/>

    <Button Text="Submit"
            Command="{Binding Submit}"
            x:Name="SubmitButton"
            HorizontalOptions="CenterAndExpand"
            ></Button>

</StackLayout>

and the code behind:`

// Styling and resources
            // *************************
            // Whole page ino
            BackgroundColor = Color.White;
            // ID Label at top of screen styles
            DriverLabel.BackgroundColor = Color.LightBlue;
            DriverLabel.HorizontalTextAlignment = TextAlignment.Center;
            DriverLabel.VerticalTextAlignment = TextAlignment.Center;
            DriverLabel.FontSize = 20;
            DriverLabel.HeightRequest = 80;
            DriverLabel.TextColor = Color.Black;

            //VigoLogo Information
            VigoLogo.Source = "Resources/vigo_sign.png";

            // Submit button
            SubmitButton.BackgroundColor = Color.LightBlue;
            SubmitButton.VerticalOptions = LayoutOptions.End;`

I have tried various things with relative and absolute positioning but because I am new to Xamarin I am getting in a mess more than anything else.
I got somewhere using AbsoluteLayout but it seems that only hard coding x and y coordinates works but it needs to be more dynamic than that for different devices.

Any help would be appreciated.

Body:
You can do this with a Grid. We can define 4 rows (starting with index '0').
The last row (index 3) can be set to take all the remaining space so the button can be placed with VerticalOptions to End to keep stuck to the bottom.

<Grid>
   <Grid.RowDefinitions>
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <RowDefinition Height="*" />
   </Grid.RowDefinitions>

            <Label Text="Identification" Grid.Row="0"
                   x:Name="DriverLabel"/>

            <Image x:Name="VigoLogo" Grid.Row="1"/>

            <Entry Placeholder="Driver Name" Grid.Row="2"
                   Text="{Binding driverID}"/>

    <Button Text="Submit"  Grid.Row="3"
            Command="{Binding Submit}"
            x:Name="SubmitButton"
            HorizontalOptions="FillAndExpand" VerticalOptions="End"
            ></Button>

</Grid>

I suggest you read about Layouts in order to choose the best one for each situation. https://developer.xamarin.com/guides/xamarin-forms/user-interface/controls/layouts/


问:
woocommerce place order with multiple payment methods
Is it possible to place order with different payment methods in woocommerce?

For example I have some products with only "COD" method and some products with both "COD and Online payment"  option.

While user pays for this order via Online payment method, It need to calculate only the Online payable products, and user pay for it. and other must be calculated as  Cash on dilivery. This need to happen at once.

Is there any plugin or way around to do this?

答:
The answer is NO.
At once you can't pay the order with multiple payment gateways.
But you can show/hide payment gateways depending on condition like, what products are there in your cart. </p>


问:
How to stop a program compiled with MinGW (g++) from opening a console window in windows
I compiled a program using MinGW g++. When I run it, it opens a console window in addition to the main application window. What's the compiler flag to stop this?</p>

答:
I believe the compiler switch for that is -Wl,-subsystem,windows.

The -Wl,<options> switch passes <options> to the linker. The -subsystem switch tells the linker which system to target when generating the executable.


问:
awk to create html table adds space at the end of each data entry
I am using below code for creating html table from an input file which works perfectly fine, However while creating the html table it adds a space to each entry to a cell. How do I avoid getting space at the end?

```<code>awk 'BEGIN{print "<tr>";print "<th>NAME</th>";print "<th>POLICY</th>";print "<th>STATUS</th>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}' /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y') >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y').html]
</code>```

now in the input file entries are going through script as echo "$x $y $z" >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y')

Let me know how can i avoid spaces at the end of each data entry to a cell.

Input File

```<code>cat /tmp/t
    Cindy   Today   Standard
    Victor  Today   Standard
    Bob     Today   Standard
    Martha  Tomorrow    Oracle
    Sam     Tomorrow    Oracle
</code>```

Guys the problem with my code was it had

 and 	 with a new line each time which added an extra unnecessary space to the final sheet cell>

Before the output was:
Thanks @karakfa, It did the trick, the issue in my code was every  was with new line, meaning it will append a space in the actual data.

Simply the difference in final output from before and after is
Before:

```<code></tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
</code>```

After:

```<code><tr><td>data1</td><td>data2</td><td>data3</td></tr>
<tr><td>data1</td><td>data2</td><td>data3</td></tr>
</code>```

答:
not efficient but a cleaner way of generating a html table with helper functions

```<code>awk 'function wrap(tag,x) {return "<"tag">"x"</"tag">"}
     function table(x)    {return wrap("table",ORS x)}
     function row(x)      {return wrap("tr",x) ORS}
     function cell(x)     {return wrap("td",x)}

     BEGIN {print table(row(cell(1) cell(2) cell(3)))}'

<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>
</code>```

with non-static data, perhaps this is better

```<code>$ awk 'function wrap(tag,x) {return "<"tag">"x"</"tag">"}
       function row(x)      {return wrap("tr",x)}
       function cell(x)     {return wrap("td",x)}

      BEGIN {print "<table>"}
            {print row(cell($1) cell($2) cell($3))}
      END   {print "</table>"}' <(echo -e "1 2 3\n4 5 6\n7 8 9")

<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</table>
</code>```

Body:
I am using below code for creating html table from an input file which works perfectly fine, However while creating the html table it adds a space to each entry to a cell. How do I avoid getting space at the end?

awk 'BEGIN{print "
";print "NAME	";print "POLICY	";print "STATUS	"} {print "
";for(i=1;i<=NF;i++)print "" $i"	";print "
"} END{print "
"}' /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y') >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y').html]

now in the input file entries are going through script as echo "$x $y $z" >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y')

Let me know how can i avoid spaces at the end of each data entry to a cell.

Input File

cat /tmp/t
    Cindy   Today   Standard
    Victor  Today   Standard
    Bob     Today   Standard
    Martha  Tomorrow    Oracle
    Sam     Tomorrow    Oracle

Guys the problem with my code was it had

 and 	 with a new line each time which added an extra unnecessary space to the final sheet cell>

Before the output was:
Thanks @karakfa, It did the trick, the issue in my code was every  was with new line, meaning it will append a space in the actual data.

Simply the difference in final output from before and after is
Before:

data1
data2
data3

data1
data2
data3

After:

data1	data2	data3

data1	data2	data3

Body:
not efficient but a cleaner way of generating a html table with helper functions

awk 'function wrap(tag,x) {return "<"tag">"x"</"tag">"}
     function table(x)    {return wrap("table",ORS x)}
     function row(x)      {return wrap("tr",x) ORS}
     function cell(x)     {return wrap("td",x)}

     BEGIN {print table(row(cell(1) cell(2) cell(3)))}'

<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>

with non-static data, perhaps this is better

$ awk 'function wrap(tag,x) {return "<"tag">"x"</"tag">"}
       function row(x)      {return wrap("tr",x)}
       function cell(x)     {return wrap("td",x)}

      BEGIN {print "<table>"}
            {print row(cell($1) cell($2) cell($3))}
      END   {print "</table>"}' <(echo -e "1 2 3\n4 5 6\n7 8 9")

<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</table>


问:
How can I get the total number of rows in a CSV file with PHP?
Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.</p>
```<code>if (($fp = fopen("test.csv", "r")) !== FALSE) {
  while (($record = fgetcsv($fp)) !== FALSE) {
      $row++;
  }

  echo $row;
}
</code>```

答:
In case you are getting the file from a form

```<code>$file = $_FILES['csv']['tmp_name'];
                $fp = new SplFileObject($file, 'r');
                $fp->seek(PHP_INT_MAX);
                echo $fp->key() + 1;
                $fp->rewind();
</code>```

Works like charm!!!!!!!!!!!!!!!!!!

Body:
Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.

if (($fp = fopen("test.csv", "r")) !== FALSE) {
  while (($record = fgetcsv($fp)) !== FALSE) {
      $row++;
  }

  echo $row;
}

Body:
In case you are getting the file from a form

$file = $_FILES['csv']['tmp_name'];
                $fp = new SplFileObject($file, 'r');
                $fp->seek(PHP_INT_MAX);
                echo $fp->key() + 1;
                $fp->rewind();

Works like charm!!!!!!!!!!!!!!!!!!