问:
Is there a C snippet that computes overflow-safe addition efficiently without using compiler builtins?
Here is a C function that adds an int to another, failing if overflow would happen:

```<code>int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}
</code>```

Unfortunately it is not optimized well by GCC or Clang:

```<code>safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret
</code>```

This version with __builtin_add_overflow()

```<code>int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}
</code>```

is optimized better:

```<code>safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret
</code>```

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

答:
Tthe best one I came up with, if you don't have access to the overflow flag of the architecture, is to do things in unsigned. Just think of all bit arithmetic here in that we are only interested in the highest bit, which is the sign bit when interpreted as signed values.

(All that modulo sign errors, I didn't check this thouroughly, but I hope the idea is clear)

```<code>#include <stdbool.h>

bool overadd(int a[static 1], int b) {
  unsigned A = a[0];
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  bool ret = (AeB & AuAB) > M;

  if (!ret) a[0] += b;
  return ret;
}
</code>```

If you find a version of the addition that is free of UB, such as an atomic one, the assembler is even without branch (but with a lock prefix)

```<code>#include <stdbool.h>
#include <stdatomic.h>
bool overadd(_Atomic(int) a[static 1], int b) {
  unsigned A = a[0];
  atomic_fetch_add_explicit(a, b, memory_order_relaxed);
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  bool ret = (AeB & AuAB) > M;
  return ret;
}
</code>```

So if we had such an operation, but even more "relaxed" this could improve the situation even further.

Take3: If we use a special "cast" from the unsigned result to the signed one, this now is branch free:

```<code>#include <stdbool.h>
#include <stdatomic.h>

bool overadd(int a[static 1], int b) {
  unsigned A = a[0];
  //atomic_fetch_add_explicit(a, b, memory_order_relaxed);
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  unsigned res = (AeB & AuAB);
  signed N = M-1;
  N = -N - 1;
  a[0] =  ((AB > M) ? -(int)(-AB) : ((AB != M) ? (int)AB : N));
  return res > M;
}
</code>```

Body:
Here is a C function that adds an int to another, failing if overflow would happen:

int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}

Unfortunately it is not optimized well by GCC or Clang:

safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret

This version with __builtin_add_overflow()

int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}

is optimized better:

safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

Body:
Tthe best one I came up with, if you don't have access to the overflow flag of the architecture, is to do things in unsigned. Just think of all bit arithmetic here in that we are only interested in the highest bit, which is the sign bit when interpreted as signed values.

(All that modulo sign errors, I didn't check this thouroughly, but I hope the idea is clear)

#include <stdbool.h>

bool overadd(int a[static 1], int b) {
  unsigned A = a[0];
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  bool ret = (AeB & AuAB) > M;

  if (!ret) a[0] += b;
  return ret;
}

If you find a version of the addition that is free of UB, such as an atomic one, the assembler is even without branch (but with a lock prefix)

#include <stdbool.h>
#include <stdatomic.h>
bool overadd(_Atomic(int) a[static 1], int b) {
  unsigned A = a[0];
  atomic_fetch_add_explicit(a, b, memory_order_relaxed);
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  bool ret = (AeB & AuAB) > M;
  return ret;
}

So if we had such an operation, but even more "relaxed" this could improve the situation even further.

Take3: If we use a special "cast" from the unsigned result to the signed one, this now is branch free:

#include <stdbool.h>
#include <stdatomic.h>

bool overadd(int a[static 1], int b) {
  unsigned A = a[0];
  //atomic_fetch_add_explicit(a, b, memory_order_relaxed);
  unsigned B = b;
  // This computation will be done anyhow
  unsigned AB = A + B;
  // See if the sign bits are equal
  unsigned AeB = ~(A^B);
  unsigned AuAB = (A^AB);
  // The function result according to these should be:
  //
  // AeB \ AuAB | false | true
  //------------+-------+------
  // false      | false | false
  // true       | false | true
  //
  // So the expression to compute from the sign bits is (AeB & AuAB)

  // This is INT_MAX
  unsigned M = -1U/2;
  unsigned res = (AeB & AuAB);
  signed N = M-1;
  N = -N - 1;
  a[0] =  ((AB > M) ? -(int)(-AB) : ((AB != M) ? (int)AB : N));
  return res > M;
}


来源: stackexchange

问:
onEdit Trigger for a specified cell range only
I have written a script to copy a range of cells from a single sheet to a new sheet that will be used to track work, this is working well although only with the trigger for onedit. I would like to modify the script so that it only updates the tracking sheet when the specified range of cells are edited. I believe this can be done with onEdit(e) but I have been unable to figure it out so far.</p>

```<code>

  var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet

  var ts = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/MYSHEET');//target spreadsheet for tracking

  var sourceSheet = ss.getSheetByName("Report Template");//source sheet

  var targetSheet = ts.getSheetByName("Tracker");//target sheet

  var values = sourceSheet.getRange("H7:I7").getValues();//source sheet cell range to copy to target sheet

  var valuesLength = values.length;

  if (!valuesLength) return;

  var lastRow = targetSheet.getLastRow();

  var requiredRows = lastRow + valuesLength - targetSheet.getMaxRows();

  if (requiredRows > 0) targetSheet.insertRowsAfter(lastRow, requiredRows);

  values[0].push(new Date()); //Add Date to the 2D array.

  targetSheet.getRange(lastRow + 1, 1, valuesLength, values[0].length).setValues(values);

}```

</code>```

答:
You need an if statement that evaluates which cells are being edited

To access the edited cell, you can use the event object range, that returns you the cell that has been edited

Sample:

```<code>function onEdit(event){
var cellName = event.range.getA1Notation();
  if(cellName == "A1" || cellName == "A2"){
    var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet
    ...
  }
}
</code>```

UPDATE:

You also have some other minor errors, like e.g. the requiredRows definition.

You full code would look something like the following, whereby you should replace cells A1 and A2 through the cells you actually would like to watch:

```<code>function onEdit(event){
  var cellName = event.range.getA1Notation();
  if(cellName == "A1" || cellName == "A2"){
    var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet
    var ts = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/MYSHEET');//target spreadsheet for tracking
    var sourceSheet = ss.getSheetByName("Report Template");//source sheet
    var targetSheet = ts.getSheetByName("Tracker");//target sheet
    var values = sourceSheet.getRange("H7:I7").getValues();//source sheet cell range to copy to target sheet
    var valuesLength = values.length;
    if (!valuesLength) return;
    var lastRow = targetSheet.getLastRow();
    var requiredRows = valuesLength;
    values[0].push(new Date()); //Add Date to the 2D array.
    targetSheet.getRange(lastRow + 1, 1, valuesLength, values[0].length).setValues(values);
  }
}
</code>```

IMPORTANT:

To use services that require authorization, such as SpreadsheetApp.openByUrl(), you need to replace your simple onEdit trigger through an installable one.

ContentLicense: CC BY-SA 4.0

Body:
I have written a script to copy a range of cells from a single sheet to a new sheet that will be used to track work, this is working well although only with the trigger for onedit. I would like to modify the script so that it only updates the tracking sheet when the specified range of cells are edited. I believe this can be done with onEdit(e) but I have been unable to figure it out so far.

  var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet

  var ts = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/MYSHEET');//target spreadsheet for tracking

  var sourceSheet = ss.getSheetByName("Report Template");//source sheet

  var targetSheet = ts.getSheetByName("Tracker");//target sheet

  var values = sourceSheet.getRange("H7:I7").getValues();//source sheet cell range to copy to target sheet

  var valuesLength = values.length;

  if (!valuesLength) return;

  var lastRow = targetSheet.getLastRow();

  var requiredRows = lastRow + valuesLength - targetSheet.getMaxRows();

  if (requiredRows > 0) targetSheet.insertRowsAfter(lastRow, requiredRows);

  values[0].push(new Date()); //Add Date to the 2D array.

  targetSheet.getRange(lastRow + 1, 1, valuesLength, values[0].length).setValues(values);

}```

Body:
You need an if statement that evaluates which cells are being edited

To access the edited cell, you can use the event object range, that returns you the cell that has been edited

Sample:

function onEdit(event){
var cellName = event.range.getA1Notation();
  if(cellName == "A1" || cellName == "A2"){
    var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet
    ...
  }
}

UPDATE:

You also have some other minor errors, like e.g. the requiredRows definition.

You full code would look something like the following, whereby you should replace cells A1 and A2 through the cells you actually would like to watch:

function onEdit(event){
  var cellName = event.range.getA1Notation();
  if(cellName == "A1" || cellName == "A2"){
    var ss = SpreadsheetApp.getActiveSpreadsheet();//source spreadsheet
    var ts = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/MYSHEET');//target spreadsheet for tracking
    var sourceSheet = ss.getSheetByName("Report Template");//source sheet
    var targetSheet = ts.getSheetByName("Tracker");//target sheet
    var values = sourceSheet.getRange("H7:I7").getValues();//source sheet cell range to copy to target sheet
    var valuesLength = values.length;
    if (!valuesLength) return;
    var lastRow = targetSheet.getLastRow();
    var requiredRows = valuesLength;
    values[0].push(new Date()); //Add Date to the 2D array.
    targetSheet.getRange(lastRow + 1, 1, valuesLength, values[0].length).setValues(values);
  }
}

IMPORTANT:

To use services that require authorization, such as SpreadsheetApp.openByUrl(), you need to replace your simple onEdit trigger through an installable one.


问:
Page Redirection
To help better explain my Question, here is what i have:

I am using a Precoded service, on it i have access to the Template HTML Files Only.

The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired

The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite

What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.

I got from "Sitifensys" a code

Sitifensys

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"

Hope this explanation is a bit better.

答:
```<code>if (location.pathname.indexOf(login.php) >= 0) {
   //don't redirect
} else {
   /...
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Page Redirection


问:
PDF OPI (Open Prepress Interface), what are the steps to replace low resolution proxy with high resolution image?
There is close to none information about OPI on the internet, and there is none about replacing OPI with high resolution source image. Is there anyone that have any knowledge about it?

I have to both generate eps proxy with OPI link, and make a tool to be able to replace the OPI entries with high resolution source document.

The main problem that I have now is how to use %ALDImagePosition. The unit of this entry supposed to be in points (72 units per inch) how to relate that to %ALDImageDimensions and %ALDImageCropRect which are in pixels?
How to relate all those to original high resolution image?

If anyone could point me to any sources other than OPI reference manual, I would be very thankful. Other thing that I lack is any other software that would be able to do OPI replacement so I could test the files with OPI entries that I'm generating.

Edit1:
The whole workflow looks like this, high resolution source file (usually PDF, I know it sound weird) is converted into 2 low resolution images, one is placed into EPS body and is surrounded with OPI comments, the other goes to binary header of EPS. This makes an "EPS proxy". Those proxies are used in indesign or illustrator projects, and the output is saved to PDF. This PDF contains OPI entries from EPS proxies, that I need to replace back to high-res sources.

Going back to EPS with OPI, the specification says that %ALDImageDimensions gives dimensions of placed TIFF. What is the placed TIFF? The header image, body image or original high-res image? I'm setting this from body image.
It also says that %ALDImagePosition specifies where on the page the cropped portion of the image is to be printed. What is the page in this case? I guess that would be the bounding box of the EPS, right? But how do I get it from PDF I process? I'm trying to rely on OPI entries alone to calculate the scaling and cropping that is applied to high resolution document I'm replacing with.
What I do is in the PDF in the place of low-res image I inject the high-res one but for that I have to calculate transformation matrix. I did that by taking the size and position (also the crop rect) but those two are in different units so when my low-res image has resolution different than 72dpi the scaling is wrong.

This is the stream that I put in place of the low-res objects stream:

```<code>q
/GS0 gs
x x x x x x cm
/Fm0 Do
Q
</code>```

What would be the steps for doing that correctly? What parameters are essential to take into account to fit the high-res in place of the low-res object?

This is the best I can explain the problem, this isn't easy to describe :)

答:
OPI is basically dead, it has been for years because these days nobody really cares about shuffling multi-megabyte images around.

The OPI manual is all there is, but I'm unclear on why you're having a problem. The whole point of OPI is that you don't really need to worry about this stuff.

The position is in points and the image dimensions are the number of image samples (or pixels if you prefer, but these are image pixels, not pixels on the output).

The high resolution image occupies the same area on the output as the low resolution image, but it has (obviously!) more image samples in each dimension.

To understand how this works you really need to understand how PostScript draws images which is non-trivial.

To use an image in PostScript you define an image dictionary which contains the image dimensions, the language maps these to 'the unit square', which is a square 1x1 points in size. It then uses the ImageMatrix (supplied in the dictionary) to scale that up to cover an area of the page. So an ImageMatrix [72 0 0 72 0 0] would cover 1 inch.

Crucially, this means the image covers one inch in the output, not matter how large the original image data is. This means I can 'swap out' the image and replace it with a higher resolution one by simply altering the Width and Height entries in the dictionary, and changing the image data.

Note that when it comes to OPI, the comments are only instructions to the OPI software, the PostScript interpreter ignores comments (anything beginning with %). There are two ways to replace the OPI images;

1) The PostScript interpreter is itself an OPI server. In this case it does not ignore the comments but acts upon them.

2) A pre-processor scans the PostScript program looking for OPI comments and uses them to identify and replace the low resolution images.

In either case there should be a pre-prepared high resolution OPI replacement. All that the server needs to do is identify the replacement and put it in the PostScript program in place of the low resolution one (which is delimited byt comments).

I've modified your tags because OPI isn't anything to do with EPS (although there are similar aims) and you can't do OPI with PDF.

Body:
There is close to none information about OPI on the internet, and there is none about replacing OPI with high resolution source image. Is there anyone that have any knowledge about it?

I have to both generate eps proxy with OPI link, and make a tool to be able to replace the OPI entries with high resolution source document.

The main problem that I have now is how to use %ALDImagePosition. The unit of this entry supposed to be in points (72 units per inch) how to relate that to %ALDImageDimensions and %ALDImageCropRect which are in pixels?
How to relate all those to original high resolution image?

If anyone could point me to any sources other than OPI reference manual, I would be very thankful. Other thing that I lack is any other software that would be able to do OPI replacement so I could test the files with OPI entries that I'm generating.

Edit1:
The whole workflow looks like this, high resolution source file (usually PDF, I know it sound weird) is converted into 2 low resolution images, one is placed into EPS body and is surrounded with OPI comments, the other goes to binary header of EPS. This makes an "EPS proxy". Those proxies are used in indesign or illustrator projects, and the output is saved to PDF. This PDF contains OPI entries from EPS proxies, that I need to replace back to high-res sources.

Going back to EPS with OPI, the specification says that %ALDImageDimensions gives dimensions of placed TIFF. What is the placed TIFF? The header image, body image or original high-res image? I'm setting this from body image.
It also says that %ALDImagePosition specifies where on the page the cropped portion of the image is to be printed. What is the page in this case? I guess that would be the bounding box of the EPS, right? But how do I get it from PDF I process? I'm trying to rely on OPI entries alone to calculate the scaling and cropping that is applied to high resolution document I'm replacing with.
What I do is in the PDF in the place of low-res image I inject the high-res one but for that I have to calculate transformation matrix. I did that by taking the size and position (also the crop rect) but those two are in different units so when my low-res image has resolution different than 72dpi the scaling is wrong.

This is the stream that I put in place of the low-res objects stream:

q
/GS0 gs
x x x x x x cm
/Fm0 Do
Q

What would be the steps for doing that correctly? What parameters are essential to take into account to fit the high-res in place of the low-res object?

This is the best I can explain the problem, this isn't easy to describe :)


问:
How can I optimize This Code Into Lesser Line of Code
How can I optimize this code.

I want to reduce lines of code.

```<code>public class CoolDude {
    public static void main(String[] args) {
        for(int i = 100; i <= 500; ++i) {
            if(i%5 == 0 && i%11 == 0) {
                System.out.print("Cool Dude- ");
                System.out.print(i + "\n");
            } else if (i%5 == 0) {
                System.out.print("Cool - ");
                System.out.print(i + "\n");
            } else if (i%11 == 0) {
                System.out.print("Dude - ");
                System.out.print(i + "\n");
            }
        }
    }

}
</code>```

Is there any way ?

答:
While Stephen M Irving's answer is pretty spot on and corrects all the beliefs found in your question, this still answers your question, trying to minimize the number of statements.

```<code>public class CoolDude {
  public static void main(String[] args) {
    for (int i = 100; i <= 500; i++)
      if (i % 5 == 0 || i % 11 == 0) // This is the condition where we decide to print something
        System.out.printf("%s%s- %d%n", i % 5 == 0 ? "Cool " : "", i % 11 == 0 ? "Dude " : "", i);
  }
}
</code>```

However, this code duplicates one of the most expensive part: the modulo. Also, this solution is not readable !

When trying to figure solutions is useful to try several KPI and then find the best to optimize. In this case, you wanted to optimize the number of lines, it's definitely not the best as you can see above. If anything try first to get a working solution then a readable one and finally an optimized one where you document why it's optimized so that the readability is maintained.

Here, for instance, is the most optimized version I could come up with. It definitely contains more lines, but also is definitely faster, since I skip all invalid numbers and never do a modulo (only two divisions and two multiplications for the whole program).

```<code>public class CoolDude {
  public static void main(String[] args) {
    final int min = 100;
    final int max = 500;
    for (int i5 = nextMultiple(min, 5), i11 = nextMultiple(min, 11); i5 <= max || i11 <= max; ) {
      if (i5 < i11) {
        System.out.printf("Cool - %d%n", i5);
        i5 += 5;
      } else if (i11 < i5) {
        System.out.printf("Dude - %d%n", i11);
        i11 += 11;
      } else { // i5 == i11
        System.out.printf("Cool Dude - %d%n", i5);
        i5 += 5;
        i11 += 11;
      }
    }
  }
  static int nextMultiple(int number, int divisor) {
    int roundToLower = (number - 1) / divisor * divisor;
    return roundToLower + divisor;
  }
}
</code>```

Body:
How can I optimize this code.

I want to reduce lines of code.

public class CoolDude {
    public static void main(String[] args) {
        for(int i = 100; i <= 500; ++i) {
            if(i%5 == 0 && i%11 == 0) {
                System.out.print("Cool Dude- ");
                System.out.print(i + "\n");
            } else if (i%5 == 0) {
                System.out.print("Cool - ");
                System.out.print(i + "\n");
            } else if (i%11 == 0) {
                System.out.print("Dude - ");
                System.out.print(i + "\n");
            }
        }
    }

}

Is there any way ?

Body:
While Stephen M Irving's answer is pretty spot on and corrects all the beliefs found in your question, this still answers your question, trying to minimize the number of statements.

public class CoolDude {
  public static void main(String[] args) {
    for (int i = 100; i <= 500; i++)
      if (i % 5 == 0 || i % 11 == 0) // This is the condition where we decide to print something
        System.out.printf("%s%s- %d%n", i % 5 == 0 ? "Cool " : "", i % 11 == 0 ? "Dude " : "", i);
  }
}

However, this code duplicates one of the most expensive part: the modulo. Also, this solution is not readable !

When trying to figure solutions is useful to try several KPI and then find the best to optimize. In this case, you wanted to optimize the number of lines, it's definitely not the best as you can see above. If anything try first to get a working solution then a readable one and finally an optimized one where you document why it's optimized so that the readability is maintained.

Here, for instance, is the most optimized version I could come up with. It definitely contains more lines, but also is definitely faster, since I skip all invalid numbers and never do a modulo (only two divisions and two multiplications for the whole program).

public class CoolDude {
  public static void main(String[] args) {
    final int min = 100;
    final int max = 500;
    for (int i5 = nextMultiple(min, 5), i11 = nextMultiple(min, 11); i5 <= max || i11 <= max; ) {
      if (i5 < i11) {
        System.out.printf("Cool - %d%n", i5);
        i5 += 5;
      } else if (i11 < i5) {
        System.out.printf("Dude - %d%n", i11);
        i11 += 11;
      } else { // i5 == i11
        System.out.printf("Cool Dude - %d%n", i5);
        i5 += 5;
        i11 += 11;
      }
    }
  }
  static int nextMultiple(int number, int divisor) {
    int roundToLower = (number - 1) / divisor * divisor;
    return roundToLower + divisor;
  }
}


问:
How to remove the first weather in weather forecast using weather api
here's the code.

```<code>setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }
</code>```

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.

答:
You should use splice

```<code>this.forecast.splice(0, 1)
</code>```

where 0 is the index position and 1 the number of element to remove

example

```<code>list=["bar", "baz", "foo", "qux"]
list.splice(2, 1)
// Starting at index position 2, remove one element
["bar", "baz", "qux"]
</code>```

Body:
here's the code.

setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.

Body:
You should use splice

this.forecast.splice(0, 1)

where 0 is the index position and 1 the number of element to remove

example

list=["bar", "baz", "foo", "qux"]
list.splice(2, 1)
// Starting at index position 2, remove one element
["bar", "baz", "qux"]


问:
How to find button element with webdriver?
I have the following code for a button :

```<code><div class="buttons">
<button class="btn dialog-confirm btn-primary" style="margin-left: 4px;">Confirm</button>
<button class="btn dialog-cancel" style="margin-left: 4px;">Cancel</button>
</div>
</code>```

There are two buttons on is Confirm and another is Cancel
I can find the button with XPath but I don't want to use XPath.
Is there another way to find the button element in this case?

I tried this:

```<code>driver.findElement(By.className("btn dialog-confirm btn-primary")).click();
</code>```

It did not find the button
Thank you for your help

答:
this worked for me:</p>

```<code>driver.find_element_by_class_name('buyable-full-width').click();
</code>```

Body:
I have the following code for a button :

<button class="btn dialog-confirm btn-primary" style="margin-left: 4px;">Confirm</button>
<button class="btn dialog-cancel" style="margin-left: 4px;">Cancel</button>

There are two buttons on is Confirm and another is Cancel
I can find the button with XPath but I don't want to use XPath.
Is there another way to find the button element in this case?

I tried this:

driver.findElement(By.className("btn dialog-confirm btn-primary")).click();

It did not find the button
Thank you for your help

Body:
this worked for me:

driver.find_element_by_class_name('buyable-full-width').click();


问:
package to switch on or off 3g and wifi on Android
Can anyone please tell me which SDK packages are used for switching on or off 3g and wifi on Android devices.</p>

答:
I can't help with 3G (I know the procedure is different between CDMA and GSM networks) but for Wifi, look into the WifiManager class for handling that sort of thing. For example, you could use this to toggle Wifi on and off:

```<code>WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(!wifi.isWifiEnabled());
</code>```

EDIT: The package is android.net.wifi

Body:
I can't help with 3G (I know the procedure is different between CDMA and GSM networks) but for Wifi, look into the WifiManager class for handling that sort of thing. For example, you could use this to toggle Wifi on and off:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(!wifi.isWifiEnabled());

EDIT: The package is android.net.wifi


问:
MinGW Ld creating final executable of zero size after linking object files
I'm trying to link object files generated by MinGW gcc with ld.exe supplied with MinGW to create a final 32 bit executable on Windows 10 64 bit . The code is more than simple enough. I have a maindefined.c file with the main function:

void main(int argc, char **argv) {}

For the mainCRTStartup I'm using a custom C startup code nocrt0 I found on GitHub that claims is fully compatible with MinGW:
https://github.com/matveyt/nocrt0 which parses the command line arguments and calls main() by supplying these arguments.

I've put this startup code nocrt0c.c (as I'm trying to develop a simple console application) on a file called maincaller.c

I'm creating object file for these two C source via the MinGW gcc command line

gcc -g -O -c maincaller.c -m32

gcc -g -O -c maindefined.c -m32

I've looked through the nocrt0 startup code and found it uses the GetCommandLine() API exported by kernel32.dll to fetch the command line arguments before parsing them and supplying them to main, so during linking with ld I supplied the 32 bit version of kernel32.dll on my PC in the input as well

ld --verbose -o output.exe maincaller.o maindefined.o "c:\windows\syswow64\kernel32.dll"

This throws no unresolved external error as expected, but the final output.exe produced is a zero kb file with absolutely no input. Ld verbose doesn't emit any useful error output either. What could be going wrong? Would love some help regarding this

答: This turned out to be a silly issue but I want to leave it here regardless for anyone checking in later. The Symantec Antivirus on my PC was deleting the content of the entire binary after it was successfully being created by ld.exe. So if you're doing anything MinGW or linking related with any other toolchain, a good idea would be to disable any Antivirus/Access Protection solution that you have.</p>


问:
Why does my game made with Pygame suddenly lag for a few seconds?
I made a little space invaders game with pygame, I noticed that the game lags for a few seconds periodically. I do not know what the problem is. I am a beginner.
Can you tell me why this happens? Is there any fix to this?

Also, why does everything slow down once you add the background image in the main game loop?

```<code>import pygame
from pygame import mixer
import random
import math

# Starting pygame
pygame.init()

# window
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png')

# title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

# background
mixer.music.load('galaxy.ogg')
mixer.music.play(-1)

# player
playerimg = pygame.image.load('rocket.png')
playerX = 370
playerY = 480
playerX_change = 0

# Enemy
enemy_img = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 1

for i in range(num_of_enemies):
    enemy_img.append(pygame.image.load('Enemy.png'))
    enemyX.append(random.randint(0, 735))
    enemyY.append(random.randint(50, 300))
    enemyX_change.append(4)
    enemyY_change.append(40)

# Bullet
bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"

# ready = you can't see the bullet on the screen
# fire = the bullet is currently moving

# score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)

textX = 10
textY = 10

# gameover text
over_font = pygame.font.Font('freesansbold.ttf', 70)

def show_score(x, y):
    score = font.render("Score: " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x, y))

def game_over_text():
    over_text = over_font.render("GAME OVER!", True, (255, 0, 0))
    screen.blit(over_text, (200, 250))

def player(x, y):
    screen.blit(playerimg, (x, y))

def enemy(x, y, i):
    screen.blit(enemy_img[i], (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletimg, (x + 25, y + 10))

def iscollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(enemyY - bulletY, 2))
    if distance < 30:
        return True
    else:
        return False

# gameloop
running = True
while running:
    # RGB screen
    screen.fill((0, 0, 0))
    screen.blit(background, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Check keystroke left or right
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -10
            if event.key == pygame.K_RIGHT:
                playerX_change = 10
            if event.key == pygame.K_SPACE:
                if bullet_state is "ready":
                    bullet_sound = mixer.Sound('shoot.wav')
                    bullet_sound.play()
                    # gets the current x cor of the player
                    bulletX = playerX
                    fire_bullet(bulletX, bulletY)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                playerX_change = 0
            if event.key == pygame.K_RIGHT:
                playerX_change = 0

    playerX += playerX_change

    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    for i in range(num_of_enemies):

        # game over
        if enemyY[i] > 440:
            for j in range(num_of_enemies):
                enemyY[j] = 2000
            game_over_text()
            break

        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] *= -1
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 736:
            enemyX_change[i] *= -1
            enemyY[i] += enemyY_change[i]

        # collision
        collision = iscollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosion_sound = mixer.Sound('explosion.wav')
            explosion_sound.play()
            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            # print(score)
            enemyX[i] = random.randint(0, 735)
            enemyY[i] = random.randint(50, 300)

        enemy(enemyX[i], enemyY[i], i)

    # if enemyY <= 50:
    # enemyY_change *= -1
    # elif enemyY >= 300:
    # enemyY_change *= -1

    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state is "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    player(playerX, playerY)
    show_score(textX, textY)
    pygame.display.update()
</code>```

答:
Call convert() on the background image. That ensures that the image has the same pixel format as the display Surface and will help blit to operate with optimal performance:

screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png').convert()
```

Note, if the surface has a different format than the display, then blit has to convert the format on the fly in every frame.

Body:
I made a little space invaders game with pygame, I noticed that the game lags for a few seconds periodically. I do not know what the problem is. I am a beginner.
Can you tell me why this happens? Is there any fix to this?

Also, why does everything slow down once you add the background image in the main game loop?

import pygame
from pygame import mixer
import random
import math

# Starting pygame
pygame.init()

# window
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png')

# title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

# background
mixer.music.load('galaxy.ogg')
mixer.music.play(-1)

# player
playerimg = pygame.image.load('rocket.png')
playerX = 370
playerY = 480
playerX_change = 0

# Enemy
enemy_img = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 1

for i in range(num_of_enemies):
    enemy_img.append(pygame.image.load('Enemy.png'))
    enemyX.append(random.randint(0, 735))
    enemyY.append(random.randint(50, 300))
    enemyX_change.append(4)
    enemyY_change.append(40)

# Bullet
bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"

# ready = you can't see the bullet on the screen
# fire = the bullet is currently moving

# score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)

textX = 10
textY = 10

# gameover text
over_font = pygame.font.Font('freesansbold.ttf', 70)

def show_score(x, y):
    score = font.render("Score: " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x, y))

def game_over_text():
    over_text = over_font.render("GAME OVER!", True, (255, 0, 0))
    screen.blit(over_text, (200, 250))

def player(x, y):
    screen.blit(playerimg, (x, y))

def enemy(x, y, i):
    screen.blit(enemy_img[i], (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletimg, (x + 25, y + 10))

def iscollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(enemyY - bulletY, 2))
    if distance < 30:
        return True
    else:
        return False

# gameloop
running = True
while running:
    # RGB screen
    screen.fill((0, 0, 0))
    screen.blit(background, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Check keystroke left or right
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -10
            if event.key == pygame.K_RIGHT:
                playerX_change = 10
            if event.key == pygame.K_SPACE:
                if bullet_state is "ready":
                    bullet_sound = mixer.Sound('shoot.wav')
                    bullet_sound.play()
                    # gets the current x cor of the player
                    bulletX = playerX
                    fire_bullet(bulletX, bulletY)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                playerX_change = 0
            if event.key == pygame.K_RIGHT:
                playerX_change = 0

    playerX += playerX_change

    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    for i in range(num_of_enemies):

        # game over
        if enemyY[i] > 440:
            for j in range(num_of_enemies):
                enemyY[j] = 2000
            game_over_text()
            break

        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] *= -1
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 736:
            enemyX_change[i] *= -1
            enemyY[i] += enemyY_change[i]

        # collision
        collision = iscollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosion_sound = mixer.Sound('explosion.wav')
            explosion_sound.play()
            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            # print(score)
            enemyX[i] = random.randint(0, 735)
            enemyY[i] = random.randint(50, 300)

        enemy(enemyX[i], enemyY[i], i)

    # if enemyY <= 50:
    # enemyY_change *= -1
    # elif enemyY >= 300:
    # enemyY_change *= -1

    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state is "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    player(playerX, playerY)
    show_score(textX, textY)
    pygame.display.update()

Body:
Call convert() on the background image. That ensures that the image has the same pixel format as the display Surface and will help blit to operate with optimal performance:

screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png').convert()

Note, if the surface has a different format than the display, then blit has to convert the format on the fly in every frame.


问:
Unable to copy to memorystream from gzipstream
I want to compress a binary file in memory using System.IO.Compression.GZipStream. For this, I am using the following method

```<code>public byte[] Encrypt()
{
    var payload = GetPayload();
    Console.WriteLine("[!] Payload Size: {0} bytes", payload.Length);

    using (var compressedStream = new MemoryStream(payload))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    using (var resultStream = new MemoryStream())
    {
        zipStream.CopyTo(resultStream);
        return resultStream.ToArray();
    }
}
</code>```

But while .CopyTo, I am getting System.NotSupportedException: Stream does not support reading.

答:
You need to "inverse" your logic: create GZipStream over empty MemoryStream and copy your original content into this gzip stream:</p>

```<code>using var compressedData = new MemoryStream();
using var gzip = new GZipStream(compressedData);
originalUncompressedStream.CopyTo(gzip); // <- "magic" happens here
gzip.Flush();

// and "rewind" result stream back to beginning (for next reads)
compressedData.Position = 0;
</code>```

Body:
I want to compress a binary file in memory using System.IO.Compression.GZipStream. For this, I am using the following method

public byte[] Encrypt()
{
    var payload = GetPayload();
    Console.WriteLine("[!] Payload Size: {0} bytes", payload.Length);

    using (var compressedStream = new MemoryStream(payload))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    using (var resultStream = new MemoryStream())
    {
        zipStream.CopyTo(resultStream);
        return resultStream.ToArray();
    }
}

But while .CopyTo, I am getting System.NotSupportedException: Stream does not support reading.

Body:
You need to "inverse" your logic: create GZipStream over empty MemoryStream and copy your original content into this gzip stream:

using var compressedData = new MemoryStream();
using var gzip = new GZipStream(compressedData);
originalUncompressedStream.CopyTo(gzip); // <- "magic" happens here
gzip.Flush();

// and "rewind" result stream back to beginning (for next reads)
compressedData.Position = 0;


问:
String reverse - segfault
This is not a repeated qn. A new method is used to reverse a string from already asked qn.

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    char *retStr;

    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }

    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}

int main()
{
    char *str = NULL, *revStr2 = NULL;
    str = (char *) malloc (5);
    strcpy(str, "hello");
    printf("\n%s\n", str);
    printf("\n%s\n", revStr(str));
}
</code>```

gives me the output as
O/P:

```<code>
hello
first h for 0
first e for 1
first l for 2
first l for 3
first o for 4
thrd h for 4
thrd e for 3
thrd l for 2
thrd l for 1
thrd o for 0
olleh

Segmentation fault

</code>```

Can someone pls help how string reveral can be acheived using this method.
Thanks,
Preethi

答:
You need to assign memory to retstr like below   </p>

```<code>char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }
 char *retStr = (char*)malloc(count);
    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}
</code>```

Title: String reverse - segfault

Body:
This is not a repeated qn. A new method is used to reverse a string from already asked qn.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    char *retStr;

    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }

    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}

int main()
{
    char *str = NULL, *revStr2 = NULL;
    str = (char *) malloc (5);
    strcpy(str, "hello");
    printf("\n%s\n", str);
    printf("\n%s\n", revStr(str));
}

gives me the output as
O/P:

hello
first h for 0
first e for 1
first l for 2
first l for 3
first o for 4
thrd h for 4
thrd e for 3
thrd l for 2
thrd l for 1
thrd o for 0
olleh

Segmentation fault

Can someone pls help how string reveral can be acheived using this method.
Thanks,
Preethi

Body:
You need to assign memory to retstr like below

char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }
 char *retStr = (char*)malloc(count);
    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}


问:
Getting posts from category of custom post type Wordpress
I have the code below, used to to create a category. How can i get posts using this category ? I can get the id of this category, but can`t get all the posts of the category.

```<code>function create_taxonomy()
{
    $labels= array(
    'name' => 'Kategórie',
    'singular_name' => 'Kategórie',
    'search_items' => 'Vyhladať kategórie',
    'all_items' => 'Všetky kategórie',
    'edit_item' => 'Upraviť',
    'update_item' => 'Aktualizovať',
    'add_new_item' => 'Pridať',
    'new_item_name' => 'Nový názov',
    'menu_name' => 'Kategórie',
    );
    register_taxonomy('Categories', array('service'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array('slug' => 'categories')
    ));
}
add_action('init','create_taxonomy',0);
</code>```

here is post type

https://pastebin.com/0eAPeBMr

答:
The below code should do the trick.

```<code>$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'categories',
            'field' => 'slug', //can be set to ID
            'terms' => 'category-slug' //if field is ID you can reference by cat/term number
        )
    )
);
$query = new WP_Query( $args );
</code>```

Set the 'taxonomy' to your category taxonomy and change the terms to your category-slug.
If you want to do it by Category ID, then change the field value to "term_id" and provide the category ID in terms value.

Body:
I have the code below, used to to create a category. How can i get posts using this category ? I can get the id of this category, but can`t get all the posts of the category.

function create_taxonomy()
{
    $labels= array(
    'name' => 'Kategórie',
    'singular_name' => 'Kategórie',
    'search_items' => 'Vyhladať kategórie',
    'all_items' => 'Všetky kategórie',
    'edit_item' => 'Upraviť',
    'update_item' => 'Aktualizovať',
    'add_new_item' => 'Pridať',
    'new_item_name' => 'Nový názov',
    'menu_name' => 'Kategórie',
    );
    register_taxonomy('Categories', array('service'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array('slug' => 'categories')
    ));
}
add_action('init','create_taxonomy',0);

here is post type

https://pastebin.com/0eAPeBMr

Body:
The below code should do the trick.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'categories',
            'field' => 'slug', //can be set to ID
            'terms' => 'category-slug' //if field is ID you can reference by cat/term number
        )
    )
);
$query = new WP_Query( $args );

Set the 'taxonomy' to your category taxonomy and change the terms to your category-slug.
If you want to do it by Category ID, then change the field value to "term_id" and provide the category ID in terms value.


问:
batch file findstr, how to?
I'm writing a batch file:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('DIR %BASE_FLDR% /S /B /A:D') DO (
    ECHO [%%F] | FINDSTR /E /X /IC:"%BLD_TYPE%" [%%F] >NUL && (
        ECHO %%F
    )
)
</code>```

What I want to do is be able to call the batch file like so:

```<code>copydlls ./ Release
</code>```

I want the batch file to use command line argument 1 (%1) to specify the starting location, %2 would be either "Debug" or "Release", this parsing of the arguments is fine.

In the loop I am trying to use FINDSTR to find all sub-folders that end with the folder name supplied in %2.

This bit isn't correct and is where I need help.

So far my code will capture folders correctly event where a folder contains spaces the [] fixes that, but now it doesn't match the end of string.

答:
Instead of using if %errorlevel% try if !errorlevel!, because percent expansion is evaluated when a block is parsed, before it is executed.

But that wouldn't help, as your code is broken.
Findstr /X can't never match, because /X full line must match can't be true for BLD_TYPE only.

Btw. it could be simplyfied by moving the findstr into the FOR loop.

```<code>FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /E /IC:"%BLD_TYPE%" "') DO (
   echo #1 %%F
)
</code>```

Title: batch file findstr, how to?

Body:
I'm writing a batch file:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('DIR %BASE_FLDR% /S /B /A:D') DO (
    ECHO [%%F] | FINDSTR /E /X /IC:"%BLD_TYPE%" [%%F] >NUL && (
        ECHO %%F
    )
)

What I want to do is be able to call the batch file like so:

copydlls ./ Release

I want the batch file to use command line argument 1 (%1) to specify the starting location, %2 would be either "Debug" or "Release", this parsing of the arguments is fine.

In the loop I am trying to use FINDSTR to find all sub-folders that end with the folder name supplied in %2.

This bit isn't correct and is where I need help.

So far my code will capture folders correctly event where a folder contains spaces the [] fixes that, but now it doesn't match the end of string.

Body:
Instead of using if %errorlevel% try if !errorlevel!, because percent expansion is evaluated when a block is parsed, before it is executed.

But that wouldn't help, as your code is broken.
Findstr /X can't never match, because /X full line must match can't be true for BLD_TYPE only.

Btw. it could be simplyfied by moving the findstr into the FOR loop.

FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /E /IC:"%BLD_TYPE%" "') DO (
   echo #1 %%F
)


问:
How to present SFSafariViewController in UIView
i have a custom UIView that has a button property, i want to add an action to it to open webview in-app. To do that i want to use SFSafariViewController. Here is how i am trying to achieve this.

```<code>import UIKit
import SafariServices

class CustomViewScreen: UIView, SFSafariViewControllerDelegate {

@IBAction func privacyNoteBtnAction(_ sender: UIButton) {
    if #available(iOS 9.0, *) {
        let urlString = "https://stackoverflow.com/"
        if let url = URL(string: urlString) {
            let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
            vc.delegate = self
           UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
        }
    } else {
        // Fallback on earlier versions
    }
}

func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
  controller .dismiss(animated: true, completion: nil) // also not able to trigger this method when i tap "Done"
}
</code>```

I cant even propery use this way , since i am getting " whose view is not in the window hierarchy!" Also i am not able to call SFSafariViewControllerDelegate method to dismiss the view after tap "Done" button. Any idea to give action while i am in the UIView or any idea to connect this action to my main controller to use properly present method?

答:
```<code>import UIKit
import SafariServices

class ViewController: UIViewController {

    var safariVC = SFSafariViewController(url: URL(string: "https://apple.com")!)

    override func viewDidLoad() {
        super.viewDidLoad()
        addViewControllerAsChildViewController()
    }

    //firstVCIdentifier

    func addViewControllerAsChildViewController() {
        addChild(safariVC)
        self.view.addSubview(safariVC.view)
        safariVC.didMove(toParent: self)
        self.setUpConstraints()
    }

    func setUpConstraints() {
        self.safariVC.view.translatesAutoresizingMaskIntoConstraints = false
        self.safariVC.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 100).isActive = true
        self.safariVC.view.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -100).isActive = true
        self.safariVC.view.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 100).isActive = true
        self.safariVC.view.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -100).isActive = true
    }

}
</code>```

Body:
i have a custom UIView that has a button property, i want to add an action to it to open webview in-app. To do that i want to use SFSafariViewController. Here is how i am trying to achieve this.

import UIKit
import SafariServices

class CustomViewScreen: UIView, SFSafariViewControllerDelegate {

@IBAction func privacyNoteBtnAction(_ sender: UIButton) {
    if #available(iOS 9.0, *) {
        let urlString = "https://stackoverflow.com/"
        if let url = URL(string: urlString) {
            let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
            vc.delegate = self
           UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
        }
    } else {
        // Fallback on earlier versions
    }
}

func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
  controller .dismiss(animated: true, completion: nil) // also not able to trigger this method when i tap "Done"
}

I cant even propery use this way , since i am getting " whose view is not in the window hierarchy!" Also i am not able to call SFSafariViewControllerDelegate method to dismiss the view after tap "Done" button. Any idea to give action while i am in the UIView or any idea to connect this action to my main controller to use properly present method?


问:
How to find same values and mark them in a separate column in a dataframe in Python?
I have a bunch of column that i want to concatenate and then find how many of them are same in the concat column. I written some code but my dataframe is too big and it takes too long to complete this exercise.

This is what i have done.

```<code>import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (df.iloc[i,df.shape[1]-2] == df.iloc[j,df.shape[1]-2]):
                df.iloc[i,df.shape[1]-1] = "yes"
</code>```

This works on the smaller dataframe but on a bigger one it takes too long. Is there a more efficient way to produce the same result?

答:
You can use broadcasting rules to avoid one loop.</p>

```<code>import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
  any_eq = df.iloc[i, -2] == df.Conc
  df.iloc[i, -1] = 'yes' if any_eq.any() else 'no'
</code>```

Body:
I have a bunch of column that i want to concatenate and then find how many of them are same in the concat column. I written some code but my dataframe is too big and it takes too long to complete this exercise.

This is what i have done.

import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (df.iloc[i,df.shape[1]-2] == df.iloc[j,df.shape[1]-2]):
                df.iloc[i,df.shape[1]-1] = "yes"

This works on the smaller dataframe but on a bigger one it takes too long. Is there a more efficient way to produce the same result?

Body:
You can use broadcasting rules to avoid one loop.

import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
  any_eq = df.iloc[i, -2] == df.Conc
  df.iloc[i, -1] = 'yes' if any_eq.any() else 'no'


问:
How to return bool value with navigator.pop?
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.</p>

```<code>final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}
</code>```

答:
You pass the value you want to return to Navigator.pop and it will be returned by showDialog:

final result = await showDialog(
  ...
  // At some point, Navigator.pop is called
  Navigator.pop(context, true);
);

print(result); // Prints: true
```

Body:
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.

final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}


问:
How can you disable Gutter Indicators in VS Code?
In VS Code, if there's version control in a folder you're working in, it will try and indicate what lines are new and what lines are changed with little color patches in the "gutter" section. Actually, both on the left side near the line numbers, and also on the right side in the scroll bar. Is there a way to turn that off?</p>

答: Just go to Settings and search for "Scm Diff Decorations" and set to none.


问:
Storing Hierarchical Data (MySQL) for Referral Marketing
I need to have a 5 levels hierarchy for the users registered to a website. Every user is invited by another, and I need to know all descendants for a user. And also ancestors for a user.

I have in mind 2 solution.

Keeping a table with relationships this way. A closure table:

```<code>
    ancestor_id  descendant_id  distance
    1            1              0
    2            2              0
    3            3              0
    4            4              0
    5            5              0
    6            6              0
    2            3              1
</code>```

Having this table for relationships. Keeping in a table 5 levels ancestors. A "ancestors" table:

```<code>
   user_id ancestor_level1_id ancestor_level2_id ancestor_level3_id ancestor_level4_id ancestor_level5_id
   10      9                  7                  4                  3                  2
   9       7                  4                  3                  2                  1
</code>```

Are these good ideas?

I know about "the adjacency list model" and "the modified preorder tree traversal algorithm", but are these good solutions for a "referral" system?

The queries that I need to perform on this tree are:

frequently adding a new users

when a user buys something, their referrers get a percentage commission

every user should be able to find out how many people they've referred (and how many people were referred by people who they referred....) at each level

答:
Closure Table

```<code>ancestor_id  descendant_id  distance
    1            1              0
    2            2              0
    3            3              0
    4            4              0
    5            5              0
    6            6              0
    2            3              1
</code>```

To add user 10, referred by user 3. (I don't think you need to lock the table between these two insertions):

```<code>insert into ancestor_table
select ancestor_id, 10, distance+1
from ancestor_table
where descendant_id=3;

insert into ancestor_table values (10,10,0);
</code>```

To find all users referred by user 3.

```<code>select descendant_id from ancestor_table where ancestor_id=3;
</code>```

To count those users by depth:

```<code>select distance, count(*) from ancestor_table where ancestor_id=3 group by distance;
</code>```

To find the ancestors of user 10.

```<code>select ancestor_id, distance from ancestor_table where descendant_id=10;
</code>```

The drawback to this method is amount of storage space this table will take.

Body:
I need to have a 5 levels hierarchy for the users registered to a website. Every user is invited by another, and I need to know all descendants for a user. And also ancestors for a user.

I have in mind 2 solution.

Keeping a table with relationships this way. A closure table:

    ancestor_id  descendant_id  distance
    1            1              0
    2            2              0
    3            3              0
    4            4              0
    5            5              0
    6            6              0
    2            3              1

Having this table for relationships. Keeping in a table 5 levels ancestors. A "ancestors" table:

   user_id ancestor_level1_id ancestor_level2_id ancestor_level3_id ancestor_level4_id ancestor_level5_id
   10      9                  7                  4                  3                  2
   9       7                  4                  3                  2                  1

Are these good ideas?

I know about "the adjacency list model" and "the modified preorder tree traversal algorithm", but are these good solutions for a "referral" system?

The queries that I need to perform on this tree are:

frequently adding a new users

when a user buys something, their referrers get a percentage commission

every user should be able to find out how many people they've referred (and how many people were referred by people who they referred....) at each level

Body:
Closure Table

ancestor_id  descendant_id  distance
    1            1              0
    2            2              0
    3            3              0
    4            4              0
    5            5              0
    6            6              0
    2            3              1

To add user 10, referred by user 3. (I don't think you need to lock the table between these two insertions):

insert into ancestor_table
select ancestor_id, 10, distance+1
from ancestor_table
where descendant_id=3;

insert into ancestor_table values (10,10,0);

To find all users referred by user 3.

select descendant_id from ancestor_table where ancestor_id=3;

To count those users by depth:

select distance, count(*) from ancestor_table where ancestor_id=3 group by distance;

To find the ancestors of user 10.

select ancestor_id, distance from ancestor_table where descendant_id=10;

The drawback to this method is amount of storage space this table will take.


问:
How do i return data where that contain empty string instead of NULL in laravel
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code</p>

```<code>public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

</code>```

答:
Your code are using an not equal to an empty string condition. To retrieve all persons where pi_vendor_id's is empty, do the following where condition.</p>

```<code>->where('pi_vendor_id', '=', '')
</code>```

Body:
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code

public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

Body:
Your code are using an not equal to an empty string condition. To retrieve all persons where pi_vendor_id's is empty, do the following where condition.

->where('pi_vendor_id', '=', '')


问:
Is it possible in Hybris backoffice to have multiples editors for the same qualifier in the same section?
Every time I try to put a different editor for the same qualifier it gets replaced. I tried to use merge-mode="append" But it didn't work.
Is it possibile to do what I want?

In my case I am trying to add 2 editors for the qualifier members from B2BUnit.
Here is what I have:

```<code><context merge-by="type" parent="Company" type="B2BUnit" component="editor-area">
    <editorArea:editorArea xmlns:editorArea="http://www.hybris.com/cockpitng/component/editorArea" >
        <editorArea:tab name="hmc.tab.groups" >
            <editorArea:section name="hmc.section.groups">
                <editorArea:attribute qualifier="groups"/>
                <editorArea:attribute qualifier="members" editor="com.hybris.cockpitng.editor.defaultmultireferenceeditor" />
                <editorArea:attribute
                        editor="de.hybris.platform.platformbackoffice.editors.membersfindereditor.MembersFinderEditor"
                        qualifier="members" label="hmc.text.usergroup.usesearchtogetmembers" merge-mode="append"/>
            </editorArea:section>
        </editorArea:tab>
    </editorArea:editorArea>
</context>
</code>```

答: I would assign a custom editor with a custom renderer where you put your own logic combining two or more editors.</p>

Body:
Every time I try to put a different editor for the same qualifier it gets replaced. I tried to use merge-mode="append" But it didn't work.
Is it possibile to do what I want?

In my case I am trying to add 2 editors for the qualifier members from B2BUnit.
Here is what I have:

<context merge-by="type" parent="Company" type="B2BUnit" component="editor-area">
    <editorArea:editorArea xmlns:editorArea="http://www.hybris.com/cockpitng/component/editorArea" >
        <editorArea:tab name="hmc.tab.groups" >
            <editorArea:section name="hmc.section.groups">
                <editorArea:attribute qualifier="groups"/>
                <editorArea:attribute qualifier="members" editor="com.hybris.cockpitng.editor.defaultmultireferenceeditor" />
                <editorArea:attribute
                        editor="de.hybris.platform.platformbackoffice.editors.membersfindereditor.MembersFinderEditor"
                        qualifier="members" label="hmc.text.usergroup.usesearchtogetmembers" merge-mode="append"/>
            </editorArea:section>
        </editorArea:tab>
    </editorArea:editorArea>
</context>


问:
Visual Studio stuck at "build must be stopped before the solution can be closed"
When the Visual Basic compiler (Vbc.exe) crashes, Visual Studio fails to detect this and becomes stuck in an inoperable state. The "Build" menu appears as it would if the solution were building, but the Cancel Build (Ctrl+Break) menu item has no effect. Trying to close the application or the solution gives the error:

The build must be stopped before the solution can be closed.

I can't find any way to remedy this short of terminating the devenv.exe process and restarting Visual Studio completely. Is there anything quicker and less severe?

(Microsoft claims to have fixed this bug in 2005, but I'm experiencing it with VS2008.)

答:
S O L V E D it!

Had this problem in VS2017 prof vs15.9.16.
When performing a build, build starts to compile but never finishes.
Build-menu items are grayed out except for 'cancel'. And cancel does not work.
Using a different compiler worked!
'Kill process' was the only way to kill the build.

Stripping the program to its bare minimum showed the real problem.
There where referenced DLL's that hung the build.
Compiling the DLL's and re-referencing them solved the problem.


问:
how to check the SharedPreferences string is empty or null
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.

```<code>SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);

urlfoto = sharedPrefNew.getString("fotonew", "");

if(urlfoto!= null && !urlfoto.equals(""))
{
    ...
}
else {
    System.out.println("boş");
    ...
}
</code>```

答:
You already declared default value of SharedPreference on Code.

```<code>urlfoto = sharedPrefNew.getString("fotonew", "");
</code>```

This means if "fotonew" is empty or null sharedPrefNew returns a value ""

Body:
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.

SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);

urlfoto = sharedPrefNew.getString("fotonew", "");

if(urlfoto!= null && !urlfoto.equals(""))
{
    ...
}
else {
    System.out.println("boş");
    ...
}

Body:
You already declared default value of SharedPreference on Code.

urlfoto = sharedPrefNew.getString("fotonew", "");

This means if "fotonew" is empty or null sharedPrefNew returns a value ""


问:
Why is text output from one CmdLet formatted and text output from another is not?
I have written 2 cmdlets, for converting between GUIDs and Oracle's Guid equivalent, the strings it displays for RAW columns used to store GUIDs. The first, Convert-GuidToRaw, accepts a GUID string param and outputs a raw string:

```<code>var raw = GuidConverter.Core.GuidConverter.ToRaw(Input);
WriteObject(raw);
</code>```

Where raw has type string. When I run this cmdlet, I get a plain and simple string output:

```<code>PS D:\SANRAL\NRA2> New-Guid | Convert-GuidToRaw
DD8386EE09231A43B7731880CCAD6B87
PS D:\SANRAL\NRA2>
</code>```

My other cmdlet, Convert-RawToGuid, accepts a RAW string param representing a GUID and outputs a raw GUID:

```<code>var guid = GuidConverter.Core.GuidConverter.FromRaw(Input);
WriteObject(guid);
</code>```

Where guid has type Guid. When I run this cmdlet, I get output formatted like a table:

```<code>PS D:\SANRAL\NRA2> Convert-RawToGuid DD8386EE09231A43B7731880CCAD6B87

Guid
----
ee8683dd-2309-431a-b773-1880ccad6b87

PS D:\SANRAL\NRA2>
</code>```

In both cases I output a single object, not a list, and in both cases the object is easily represented by a simple string. Why do I get tabular output when I return a Guid type?

It may be worth noting that the Convert-GuidToRaw cmdlet, with its plain, un-formatted, string output, doesn't seem to properly write to the pipeline. Both cmdlets take one parameter, from the pipeline. I would expect this cmdlet pipeline below to output a GUID, when instead the last cmdlet in the pipeline is till looking for input:

```<code>PS C:\WINDOWS\system32> New-Guid | Convert-GuidToRaw | Convert-RawToGuid

cmdlet Convert-RawToGuid at command pipeline position 3
Supply values for the following parameters:
Input:
</code>```

Why is Convert-RawToGuid not getting a "pipelined" string from Convert-GuidToRaw? Swapping the order of the pipeline as below, causes the expected behaviour:

```<code>PS C:\WINDOWS\system32> Convert-RawToGuid F3BD9411DE8E4F4BBCACECFCED6D305D | Convert-GuidToRaw
F3BD9411DE8E4F4BBCACECFCED6D305D
PS C:\WINDOWS\system32>
</code>```

The Convert-RawToGuid cmdlet looks like this:

```<code>[Cmdlet(VerbsData.Convert, "RawToGuid")]
public class ConvertRawToGuidCommand : System.Management.Automation.Cmdlet
{
    [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
    public string Input { get; set; }

    protected override void ProcessRecord()
    {
        if (string.IsNullOrEmpty(Input) || Input.Length != 32)
        {
            throw new ArgumentException("Input must be a 32 character hex string");
        }
        var guid = GuidConverter.Core.GuidConverter.FromRaw(Input);
        WriteObject(guid);
    }
}
</code>```

The Convert-GuidToRaw cmdlet looks like this:

```<code>[Cmdlet(VerbsData.Convert, "GuidToRaw")]
public class ConvertGuidToRawCommand : System.Management.Automation.Cmdlet
{
    [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
    public Guid Input { get; set; }

    protected override void ProcessRecord()
    {
        var raw = GuidConverter.Core.GuidConverter.ToRaw(Input);
        WriteObject(raw);
    }
}
</code>```

答:
Part 1

In both cases I output a single object, not a list, and in both cases the object is easily represented by a simple string. Why do I get tabular output when I return a Guid type?

When a command in an interactive session returns an unassigned value, PowerShell passes it to a default Format Command to generate the text before it's written to the console. PowerShell is pre-configured with a bunch of Format Commands for some specific types, and System.Guid is one of those types.

For example:

PS> [Guid]::NewGuid()

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420
```

<p>The default formatters for various types are configured in *.Format.ps1xml files in PowerShell 5.1, and are baked into the source code from PowerShell 6 onwards as per About Format.ps1xml</p>

<p>In PowerShell 5.1, the default formatter configuration for System.Guid can be found in <code>$PSHOME\DotNetTypes.format.ps1xml</code> and looks like this:</p>

```<View>
  <Name>System.Guid</Name>
  <ViewSelectedBy>
    <TypeName>System.Guid</TypeName>
  </ViewSelectedBy>
  <TableControl>
    <TableRowEntries>
      <TableRowEntry>
        <TableColumnItems>
          <TableColumnItem>
            <PropertyName>Guid</PropertyName>
          </TableColumnItem>
        </TableColumnItems>
      </TableRowEntry>
    </TableRowEntries>
  </TableControl>
</View>
```

<p>so you get a table with a single column that contains the <code>Guid</code> property.</p>

<p>You get exactly the same result if you do this:</p>

<pre class="lang-bsh prettyprint-override"><code>PS> [Guid]::NewGuid() | Format-Table -Property "Guid"

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420
</code>```

and if you want to capture the result of the default formatting command into a string variable (e.g. to write to a log file) you can do this:

PS> $text = [Guid]::NewGuid() | Out-String
PS> $text

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420
```

<p><strong>Part 2</strong></p>

<blockquote>
  <p>Why is Convert-RawToGuid not getting a "pipelined" string from Convert-GuidToRaw? Swapping the order of the pipeline as below, causes the expected behaviour:</p>
</blockquote>

<p>I'm not able to reproduce your issue, but the following works for me (with the caveat that I couldn't find a library with the the class <code>GuidConverter.Core.GuidConverter</code> so I'm assuming it's a private implementation and I'm using the default string fomat instead - e.g. : "024673b5-9c65-447a-be87-dae5f11f5142"). You could try this locally and see if you get the same result or the issue you reported, and go from there...</p>

<ul>
<li>Create a new C# Class Library solution using .Net Framework 4.7.2 in Visual Studio</li>
<li>Add a reference to the Microsoft.PowerShell.5.1.ReferenceAssemblies NuGet package</li>
<li>Add the code below into a new class file and build the project:</li>
</ul>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Management.Automation;

namespace MyCmdlet
{

    [Cmdlet(VerbsData.Convert, "RawToGuid")]
    public class ConvertRawToGuidCommand : Cmdlet
    {
        [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
        public string Input { get; set; }
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(this.Input) || this.Input.Length != 36)
            {
                throw new ArgumentException("Input must be a 36 character hex string");
            }
            var guid = new Guid(this.Input);
            WriteObject(guid);
        }
    }

    [Cmdlet(VerbsData.Convert, "GuidToRaw")]
    public class ConvertGuidToRawCommand : Cmdlet
    {
        [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
        public Guid Input { get; set; }
        protected override void ProcessRecord()
        {
            var raw = this.Input.ToString();
            WriteObject(raw);
        }
    }

}
</code>```

If I build this code I can reference it from PowerShell and the following code works:

```<code>PS> Import-Module ".\MyCmdlet.dll"
PS> New-Guid | Convert-GuidToRaw | Convert-RawToGuid

Guid
----
15591624-44c9-4c55-acd7-22b7a2d0bee0
</code>```

Body:
I have written 2 cmdlets, for converting between GUIDs and Oracle's Guid equivalent, the strings it displays for RAW columns used to store GUIDs. The first, Convert-GuidToRaw, accepts a GUID string param and outputs a raw string:

var raw = GuidConverter.Core.GuidConverter.ToRaw(Input);
WriteObject(raw);

Where raw has type string. When I run this cmdlet, I get a plain and simple string output:

PS D:\SANRAL\NRA2> New-Guid | Convert-GuidToRaw
DD8386EE09231A43B7731880CCAD6B87
PS D:\SANRAL\NRA2>

My other cmdlet, Convert-RawToGuid, accepts a RAW string param representing a GUID and outputs a raw GUID:

var guid = GuidConverter.Core.GuidConverter.FromRaw(Input);
WriteObject(guid);

Where guid has type Guid. When I run this cmdlet, I get output formatted like a table:

PS D:\SANRAL\NRA2> Convert-RawToGuid DD8386EE09231A43B7731880CCAD6B87

Guid
----
ee8683dd-2309-431a-b773-1880ccad6b87

PS D:\SANRAL\NRA2>

In both cases I output a single object, not a list, and in both cases the object is easily represented by a simple string. Why do I get tabular output when I return a Guid type?

It may be worth noting that the Convert-GuidToRaw cmdlet, with its plain, un-formatted, string output, doesn't seem to properly write to the pipeline. Both cmdlets take one parameter, from the pipeline. I would expect this cmdlet pipeline below to output a GUID, when instead the last cmdlet in the pipeline is till looking for input:

PS C:\WINDOWS\system32> New-Guid | Convert-GuidToRaw | Convert-RawToGuid

cmdlet Convert-RawToGuid at command pipeline position 3
Supply values for the following parameters:
Input:

Why is Convert-RawToGuid not getting a "pipelined" string from Convert-GuidToRaw? Swapping the order of the pipeline as below, causes the expected behaviour:

PS C:\WINDOWS\system32> Convert-RawToGuid F3BD9411DE8E4F4BBCACECFCED6D305D | Convert-GuidToRaw
F3BD9411DE8E4F4BBCACECFCED6D305D
PS C:\WINDOWS\system32>

The Convert-RawToGuid cmdlet looks like this:

[Cmdlet(VerbsData.Convert, "RawToGuid")]
public class ConvertRawToGuidCommand : System.Management.Automation.Cmdlet
{
    [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
    public string Input { get; set; }

    protected override void ProcessRecord()
    {
        if (string.IsNullOrEmpty(Input) || Input.Length != 32)
        {
            throw new ArgumentException("Input must be a 32 character hex string");
        }
        var guid = GuidConverter.Core.GuidConverter.FromRaw(Input);
        WriteObject(guid);
    }
}

The Convert-GuidToRaw cmdlet looks like this:

[Cmdlet(VerbsData.Convert, "GuidToRaw")]
public class ConvertGuidToRawCommand : System.Management.Automation.Cmdlet
{
    [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
    public Guid Input { get; set; }

    protected override void ProcessRecord()
    {
        var raw = GuidConverter.Core.GuidConverter.ToRaw(Input);
        WriteObject(raw);
    }
}

Body:
Part 1

In both cases I output a single object, not a list, and in both cases the object is easily represented by a simple string. Why do I get tabular output when I return a Guid type?

When a command in an interactive session returns an unassigned value, PowerShell passes it to a default Format Command to generate the text before it's written to the console. PowerShell is pre-configured with a bunch of Format Commands for some specific types, and System.Guid is one of those types.

For example:

PS> [Guid]::NewGuid()

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420

The default formatters for various types are configured in *.Format.ps1xml files in PowerShell 5.1, and are baked into the source code from PowerShell 6 onwards as per About Format.ps1xml

In PowerShell 5.1, the default formatter configuration for System.Guid can be found in $PSHOME\DotNetTypes.format.ps1xml and looks like this:

<View>
  <Name>System.Guid</Name>
  <ViewSelectedBy>
    <TypeName>System.Guid</TypeName>
  </ViewSelectedBy>
  <TableControl>
    <TableRowEntries>
      <TableRowEntry>
        <TableColumnItems>
          <TableColumnItem>
            <PropertyName>Guid</PropertyName>
          </TableColumnItem>
        </TableColumnItems>
      </TableRowEntry>
    </TableRowEntries>
  </TableControl>
</View>

so you get a table with a single column that contains the Guid property.

You get exactly the same result if you do this:

PS> [Guid]::NewGuid() | Format-Table -Property "Guid"

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420

and if you want to capture the result of the default formatting command into a string variable (e.g. to write to a log file) you can do this:

PS> $text = [Guid]::NewGuid() | Out-String
PS> $text

Guid
----
ee737b6f-7f68-4015-8841-1278b37a6420

Part 2

Why is Convert-RawToGuid not getting a "pipelined" string from Convert-GuidToRaw? Swapping the order of the pipeline as below, causes the expected behaviour:

I'm not able to reproduce your issue, but the following works for me (with the caveat that I couldn't find a library with the the class GuidConverter.Core.GuidConverter so I'm assuming it's a private implementation and I'm using the default string fomat instead - e.g. : "024673b5-9c65-447a-be87-dae5f11f5142"). You could try this locally and see if you get the same result or the issue you reported, and go from there...

Create a new C# Class Library solution using .Net Framework 4.7.2 in Visual Studio

Add a reference to the Microsoft.PowerShell.5.1.ReferenceAssemblies NuGet package

Add the code below into a new class file and build the project:

using System;
using System.Management.Automation;

namespace MyCmdlet
{

    [Cmdlet(VerbsData.Convert, "RawToGuid")]
    public class ConvertRawToGuidCommand : Cmdlet
    {
        [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
        public string Input { get; set; }
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(this.Input) || this.Input.Length != 36)
            {
                throw new ArgumentException("Input must be a 36 character hex string");
            }
            var guid = new Guid(this.Input);
            WriteObject(guid);
        }
    }

    [Cmdlet(VerbsData.Convert, "GuidToRaw")]
    public class ConvertGuidToRawCommand : Cmdlet
    {
        [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)]
        public Guid Input { get; set; }
        protected override void ProcessRecord()
        {
            var raw = this.Input.ToString();
            WriteObject(raw);
        }
    }

}

If I build this code I can reference it from PowerShell and the following code works:

PS> Import-Module ".\MyCmdlet.dll"
PS> New-Guid | Convert-GuidToRaw | Convert-RawToGuid

Guid
----
15591624-44c9-4c55-acd7-22b7a2d0bee0


问:
How to URL route based on UICulture settings?
I have ASP.NET 4 project (not MVC). I need to create url route based on user input language.

Project has only two languages "he" and "en".

User can enter the site and if his culture is set to anything besides he-IL i want to re-route him to website.com/en/ otherwise to website.com/he/

Default.aspx should remain same page which uses Globalization features translate values based on user's culture settings in browser.

How can i do that? what should i do besides writing a route in Global.asax and How to write this route.

答:
This shouldnt be hard.  Yes the Global.ascx is the best place to start.

First map the Routes,

```<code>    protected void RegisterRoutes(RouteCollection routes)
    {
        //Contact route for EN culture
        routes.MapPageRoute(
            "contactRouteEN",
            "en/contact",
            "~/Contact.aspx"
        );

        routes.MapPageRoute(
            "contactRouteHE",
            "he/contact",
            "~/Contact.aspx"
        );
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
</code>```

That much establishes the routes.

The problem your describing sounds more like a Globalization issue than url routing problem.  The url portion of the issue will be cosmetic to the user but won't attack the underlying issue in my view.  ASP.Net provides facilities for Globalization.  For example you can use LocalResources.  To do this for the pages at your applications root level (not nested inside folders)
Right click the website and choose Add ASP.Net Folder
Choose App_LocalResources.
Right click the App_LocalResources folder and choose Add Item
Choose Resource File.

It is important that you name the file according to the culture you plan to target

You can create the first file to be Contact.aspx.resx to be the default resource file (maybe english?)

ASP.Net will try to find the most specific culture to match the resource files to and will resort to the default if a more specific is not provided.

The naming convention follows PageName.aspx.languageID-cultureId.resx

You could have Contact.aspx.he.resx

In a label control for example you could set it like this

```<code><asp:Label ID="lbContactMessage" runat="server" Text="something" meta:resourcekey="yourmatchingkeyfromresourcefile"></asp:Label>
</code>```

For more info see
http://msdn.microsoft.com/en-us/library/c6zyy3s9.aspx

Body:
This shouldnt be hard.  Yes the Global.ascx is the best place to start.

First map the Routes,

    protected void RegisterRoutes(RouteCollection routes)
    {
        //Contact route for EN culture
        routes.MapPageRoute(
            "contactRouteEN",
            "en/contact",
            "~/Contact.aspx"
        );

        routes.MapPageRoute(
            "contactRouteHE",
            "he/contact",
            "~/Contact.aspx"
        );
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

That much establishes the routes.

The problem your describing sounds more like a Globalization issue than url routing problem.  The url portion of the issue will be cosmetic to the user but won't attack the underlying issue in my view.  ASP.Net provides facilities for Globalization.  For example you can use LocalResources.  To do this for the pages at your applications root level (not nested inside folders)
Right click the website and choose Add ASP.Net Folder
Choose App_LocalResources.
Right click the App_LocalResources folder and choose Add Item
Choose Resource File.

It is important that you name the file according to the culture you plan to target

You can create the first file to be Contact.aspx.resx to be the default resource file (maybe english?)

ASP.Net will try to find the most specific culture to match the resource files to and will resort to the default if a more specific is not provided.

The naming convention follows PageName.aspx.languageID-cultureId.resx

You could have Contact.aspx.he.resx

In a label control for example you could set it like this

<asp:Label ID="lbContactMessage" runat="server" Text="something" meta:resourcekey="yourmatchingkeyfromresourcefile"></asp:Label>

For more info see
http://msdn.microsoft.com/en-us/library/c6zyy3s9.aspx


答:
this line:

```<code>sharedPrefNew.getString("fotonew", "")
</code>```

is responsible for taking value from shared pref. First parameter is a key, second one is a default value that will be returned if key is not found.
In your case, if there is no object stored for key "fotoNew" an empty string will be returned.

You can return null :

```<code>sharedPrefNew.getString("fotonew", null);
</code>```

Hope that helps.

Title: how to check the SharedPreferences string is empty or null

Body:
this line:

sharedPrefNew.getString("fotonew", "")

is responsible for taking value from shared pref. First parameter is a key, second one is a default value that will be returned if key is not found.
In your case, if there is no object stored for key "fotoNew" an empty string will be returned.

You can return null :

sharedPrefNew.getString("fotonew", null);

Hope that helps.