问:
NullPointerException's on StartActivityForResult, Struggling with SQLite in android i think?
I have one class called Budget.java, within that i start Keypad.java. This was all working fine up until recently when i added a bunch of code to Keypad.java (The added code was to update a row in my SQLite database on the press of a button, all the unrelated methods were working until i tried to implement this). Now using breakpoints i think i've figured out that i get the error message as soon as i try to open the Keypad activity and i don't have a clue what could be the problem.

Maybe it's my misunderstanding of the sqlite open helper? Or perhaps its because i'm using StartActivityForResult?

Any suggestions would be very appreciated! I can upload the logcat if you think that would help.
I uploaded the two little classes to pastebin, you might find it easier to read?

Budget.java ( look for ListItemCommonIntent )

keypad.java

答:
In your Keypad.java, you have the following outside the onCreate:

```<code> EditText userAmount=(EditText)this.findViewById(R.id.cost_input);
</code>```

This wont work because you have to use the setContentView to reference the layout where you want to find the view. And when it initializes userAmount, the object is not available yet (so this is null) .

Try this:

```<code>private EditText userAmount;

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.keypad);
    userAmount=(EditText)findViewById(R.id.cost_input);
    MySpinner();
    Main();
}
</code>```

Body:
In your Keypad.java, you have the following outside the onCreate:

 EditText userAmount=(EditText)this.findViewById(R.id.cost_input);

This wont work because you have to use the setContentView to reference the layout where you want to find the view. And when it initializes userAmount, the object is not available yet (so this is null) .

Try this:

private EditText userAmount;

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.keypad);
    userAmount=(EditText)findViewById(R.id.cost_input);
    MySpinner();
    Main();
}


来源: stackexchange

问:
CSS grids, how to color the area outside of grid
My grid:

```<code>.grid {
  display: grid;
  grid-template-columns: 370px 1fr 1fr 1fr 370px;
  grid-template-areas:
  ". title title title ."
  ". about about about ."
  ". sidebar content content ."
  ". footer footer footer. ";
}
</code>```

My about column:

```<code>.about {
  grid-area: about;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #EBEBEB;
}
</code>```

I want to make it so that #EBEBEB is the background color for the entire . about about about . row. So, how do I make those 370px parts also grey?

答:
You can specify grid-column-start and grid-column-end to control which sections are coloured. Assuming you're asking how you can make the entire row that holds the .about class grey, you're looking for 1 and 6 respectively:

```<code>.about {
    grid-column-start: 1;
    grid-column-end: 6;
}
</code>```

This can be seen in the following:

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.bg-img {
  opacity: 0.95;
  background-image: linear-gradient( rgba(0, 0, 0, 0.27), rgba(0, 0, 0, 0.27)), url(http://i.pi.gy/5mWAw.jpg);
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.centered {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

h1 {
  font-family: 'Lato', sans-serif;
  color: white;
  font-weight: 600;
  font-size: 100px;
}

h2 {
  font-family: 'Lato', sans-serif;
  color: black;
  font-size: 40px;
  text-align: center;
}

.grid {
  display: grid;
  grid-template-columns: 370px 1fr 1fr 1fr 370px;
  grid-template-areas: ". title title title ." ". about about about ." ". sidebar content content ." ". footer footer footer. ";
}

.title {
  grid-area: title;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #FFFFFF;
}

.about {
  grid-area: about;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #EBEBEB;
  grid-column-start: 1;
  grid-column-end: 6;
}

.sidebar {
  grid-area: sidebar;
}

.content {
  grid-area: content;
}

.footer {
  grid-area: footer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bg-img">
  <h1 class="centered">Hi, I'm Karlo,<br>a Web Developer.</h1>
</div>

<div class="grid">
  <div class="title">
    <h2>My skills</h2>
  </div>
  <div class="about">
    <h2>About Me</h2>
  </div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content
    <p>A</p>
    <p>B</p>
  </div>
  <div class="footer">Footer</div>
</div></code>```

And I've also created a new pen showcasing this here.

Hope this helps! :)

ContentLicense: CC BY-SA 3.0

Body:
My grid:

.grid {
  display: grid;
  grid-template-columns: 370px 1fr 1fr 1fr 370px;
  grid-template-areas:
  ". title title title ."
  ". about about about ."
  ". sidebar content content ."
  ". footer footer footer. ";
}

My about column:

.about {
  grid-area: about;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #EBEBEB;
}

I want to make it so that #EBEBEB is the background color for the entire . about about about . row. So, how do I make those 370px parts also grey?

Body:
You can specify grid-column-start and grid-column-end to control which sections are coloured. Assuming you're asking how you can make the entire row that holds the .about class grey, you're looking for 1 and 6 respectively:

.about {
    grid-column-start: 1;
    grid-column-end: 6;
}

This can be seen in the following:

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.bg-img {
  opacity: 0.95;
  background-image: linear-gradient( rgba(0, 0, 0, 0.27), rgba(0, 0, 0, 0.27)), url(http://i.pi.gy/5mWAw.jpg);
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.centered {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

h1 {
  font-family: 'Lato', sans-serif;
  color: white;
  font-weight: 600;
  font-size: 100px;
}

h2 {
  font-family: 'Lato', sans-serif;
  color: black;
  font-size: 40px;
  text-align: center;
}

.grid {
  display: grid;
  grid-template-columns: 370px 1fr 1fr 1fr 370px;
  grid-template-areas: ". title title title ." ". about about about ." ". sidebar content content ." ". footer footer footer. ";
}

.title {
  grid-area: title;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #FFFFFF;
}

.about {
  grid-area: about;
  padding-top: 50px;
  padding-bottom: 50px;
  background-color: #EBEBEB;
  grid-column-start: 1;
  grid-column-end: 6;
}

.sidebar {
  grid-area: sidebar;
}

.content {
  grid-area: content;
}

.footer {
  grid-area: footer;
}

<div class="bg-img">
  <h1 class="centered">Hi, I'm Karlo,<br>a Web Developer.</h1>
</div>

<div class="grid">
  <div class="title">
    <h2>My skills</h2>
  </div>
  <div class="about">
    <h2>About Me</h2>
  </div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content
    <p>A</p>
    <p>B</p>
  </div>
  <div class="footer">Footer</div>
</div>

And I've also created a new pen showcasing this here.

Hope this helps! :)


问:
how to find if specific value exists in a key, and then extract that array in new array in php
I have the following array:

```<code>Array
(
[0] => Array
    (
        [CODE] => OK
        [company_id] => 170647449000
        [taxnumber] => 944703420
        [name] => SOME NAME
        [title] => S.A

    )

[1] => Array
    (
        [CODE] => OK
        [company_id] => 17063649000
        [taxnumber] => 999033420
        [name] => SOME OTHER NAME
        [title] => ANOTHER DIFFERENT TITLE
    )
)
</code>```

If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.

I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:

```<code>function myfunction($agents, $field, $value)
{
   foreach($agents as $key => $agent)
   {
     if ( $agent[$field] === $value )
        return $key;
  }
 return false;
}
</code>```

I always get false, even I am sending the value that exists.

答:
Replace return $key with return $agent and operator === with ==.
=== checks type too, it could be reason why it doesn't work.

Body:
I have the following array:

Array
(
[0] => Array
    (
        [CODE] => OK
        [company_id] => 170647449000
        [taxnumber] => 944703420
        [name] => SOME NAME
        [title] => S.A

    )

[1] => Array
    (
        [CODE] => OK
        [company_id] => 17063649000
        [taxnumber] => 999033420
        [name] => SOME OTHER NAME
        [title] => ANOTHER DIFFERENT TITLE
    )
)

If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.

I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:

function myfunction($agents, $field, $value)
{
   foreach($agents as $key => $agent)
   {
     if ( $agent[$field] === $value )
        return $key;
  }
 return false;
}

I always get false, even I am sending the value that exists.


问:
How can I strip all punctuation from a string in JavaScript using regex?
If I have a string with any type of non-alphanumeric character in it:

```<code>"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"
</code>```

How would I get a no-punctuation version of it in JavaScript:

```<code>"This is an example of a string with punctuation"
</code>```

答:
It depends on what you are trying to return. I used this recently:</p>

```<code>return text.match(/[a-z]/i);
</code>```

Body:
If I have a string with any type of non-alphanumeric character in it:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"

How would I get a no-punctuation version of it in JavaScript:

"This is an example of a string with punctuation"

Body:
It depends on what you are trying to return. I used this recently:

return text.match(/[a-z]/i);


问:
How can I programmatically generate a thumbnail of a PDF with iOS?
We're displaying PDF content using UIWebViews at the moment.  Ideally I would like to be able to display thumbnails in the UITableView without loading many different UIWebViews concurrently... they're slow enough loading one document - never mind 10+!

How do I go about doing this?

I've thought about screen capturing a document loaded using UIDocumentInteractionController or UIWebView but this means they'd all have to be thumbnailed before displaying the table.

答:
Here is sample code considering transformation. :)</p>

```<code>NSURL* pdfFileUrl = [NSURL fileURLWithPath:finalPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGPDFPageRef page;

CGRect aRect = CGRectMake(0, 0, 70, 100); // thumbnail size
UIGraphicsBeginImageContext(aRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIImage* thumbnailImage;

NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);

for(int i = 0; i < totalNum; i++ ) {

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, aRect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetGrayFillColor(context, 1.0, 1.0);
    CGContextFillRect(context, aRect);

    // Grab the first PDF page
    page = CGPDFDocumentGetPage(pdf, i + 1);
    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
    // And apply the transform.
    CGContextConcatCTM(context, pdfTransform);

    CGContextDrawPDFPage(context, page);

    // Create the new UIImage from the context
    thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();

    //Use thumbnailImage (e.g. drawing, saving it to a file, etc)

    CGContextRestoreGState(context);

}

UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is sample code considering transformation. :)

NSURL* pdfFileUrl = [NSURL fileURLWithPath:finalPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGPDFPageRef page;

CGRect aRect = CGRectMake(0, 0, 70, 100); // thumbnail size
UIGraphicsBeginImageContext(aRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIImage* thumbnailImage;

NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);

for(int i = 0; i < totalNum; i++ ) {

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, aRect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetGrayFillColor(context, 1.0, 1.0);
    CGContextFillRect(context, aRect);

    // Grab the first PDF page
    page = CGPDFDocumentGetPage(pdf, i + 1);
    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
    // And apply the transform.
    CGContextConcatCTM(context, pdfTransform);

    CGContextDrawPDFPage(context, page);

    // Create the new UIImage from the context
    thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();

    //Use thumbnailImage (e.g. drawing, saving it to a file, etc)

    CGContextRestoreGState(context);

}

UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);

ContentLicense: CC BY-SA 2.5


问:
Rotating spite not showing
I tried to let the "Player" rotate. It's a picture of the head that needs to be rotateable. But the error is that the head is not displaying (Player is not displaying). The image (bigshaghoofdz.png) needs to be rotateable.
It is rotatable by pressing the K_UP en the K_DOWN. Can turn a full 360 degrees. In the end it needs to shoot lasers from its eyes. </p>

```<code>import pygame
import random
import math
GRAD = math.pi / 180

class Config(object):
    fullscreen = False
    width = 640
    height = 360
    fps = 60

class Player(pygame.sprite.Sprite):
    maxrotate = 360
    down = (pygame.K_DOWN)
    up = (pygame.K_UP)
    number = 1

    def __init__(self, startpos = (-1,223), angle=0):
        self.number = Player.number
        Player.number += 1
        Player.book[self.number] = self
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.pos = [startpos[-1], startpos[223]]
        self.down = Player.down[self.number]
        self.up = Player.up[self.number]

        image = pygame.image.load('BigShagHoofdz.png')

    def update(self, seconds):

        pressedkeys = pygame.key.get_pressed()

        self.turndirection = 0
        if pressedkeys[self.down]:
            self.turndirection -= 1
        if pressedkeys[self.up]:
            self.turndirection += 1

#end classes
#defs

def radians_to_degrees(radians):
    return (radians / math.pi) * 180.0

def degrees_to_radians(degrees):
    return degrees * (math.pi / 180.0)

def main():
    #game
    pygame.init()
    screen=pygame.display.set_mode((Config.width,Config.height))
    background = pygame.image.load('background.jpg')

    background = background.convert()
    screen.blit(background, (0,0))
    clock = pygame.time.Clock()
    FPS = Config.fps
    playtime = 0

    Playergroup = pygame.sprite.Group()
    allgroup = pygame.sprite.LayeredUpdates()

    Player.groups = Playergroup, allgroup

    mainloop = True
    while mainloop:
        millisecond = clock.tick(Config.fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mailoop = False

        pygame.display.set_caption("say hi")
        allgroup.clear(screen, background)
        allgroup.draw(screen)
        pygame.display.flip()
    return 0

if __name__ == '__main__':
    main()
</code>```

答:
You can increment the angle if a key gets pressed, then transform the original image, assign it to the self.image attribute and get a new rect with the center of the old rect.

```<code>import pygame

class Config(object):
    fullscreen = False
    width = 640
    height = 360
    fps = 60

class Player(pygame.sprite.Sprite):
    maxrotate = 360
    down = (pygame.K_DOWN)
    up = (pygame.K_UP)

    def __init__(self, startpos=(100,223), angle=0):
        super().__init__()
        self.pos = list(startpos)
        self.image = pygame.Surface((70, 70), pygame.SRCALPHA)
        pygame.draw.circle(self.image, pygame.Color('dodgerblue'), (35, 35), 35)
        pygame.draw.circle(self.image, pygame.Color('black'), (35, 15), 8)
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=startpos)
        self.angle = angle

    def update(self, seconds):
        pressedkeys = pygame.key.get_pressed()
        if pressedkeys[self.down]:
            self.angle -= 2
            self.rotate_image()
        if pressedkeys[self.up]:
            self.angle += 2
            self.rotate_image()

    def rotate_image(self):
        self.image = pygame.transform.rotate(self.orig_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    pygame.init()
    screen=pygame.display.set_mode((Config.width,Config.height))
    clock = pygame.time.Clock()
    FPS = Config.fps
    allgroup = pygame.sprite.LayeredUpdates()
    player = Player()
    allgroup.add(player)

    mainloop = True
    while mainloop:
        millisecond = clock.tick(Config.fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mailoop = False

        allgroup.update(millisecond)

        screen.fill((50, 50, 70))
        allgroup.draw(screen)
        pygame.display.flip()

if __name__ == '__main__':
    main()
    pygame.quit()
</code>```

Title: Rotating spite not showing

Body:
I tried to let the "Player" rotate. It's a picture of the head that needs to be rotateable. But the error is that the head is not displaying (Player is not displaying). The image (bigshaghoofdz.png) needs to be rotateable.
It is rotatable by pressing the K_UP en the K_DOWN. Can turn a full 360 degrees. In the end it needs to shoot lasers from its eyes.

import pygame
import random
import math
GRAD = math.pi / 180

class Config(object):
    fullscreen = False
    width = 640
    height = 360
    fps = 60

class Player(pygame.sprite.Sprite):
    maxrotate = 360
    down = (pygame.K_DOWN)
    up = (pygame.K_UP)
    number = 1

    def __init__(self, startpos = (-1,223), angle=0):
        self.number = Player.number
        Player.number += 1
        Player.book[self.number] = self
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.pos = [startpos[-1], startpos[223]]
        self.down = Player.down[self.number]
        self.up = Player.up[self.number]

        image = pygame.image.load('BigShagHoofdz.png')

    def update(self, seconds):

        pressedkeys = pygame.key.get_pressed()

        self.turndirection = 0
        if pressedkeys[self.down]:
            self.turndirection -= 1
        if pressedkeys[self.up]:
            self.turndirection += 1

#end classes
#defs

def radians_to_degrees(radians):
    return (radians / math.pi) * 180.0

def degrees_to_radians(degrees):
    return degrees * (math.pi / 180.0)

def main():
    #game
    pygame.init()
    screen=pygame.display.set_mode((Config.width,Config.height))
    background = pygame.image.load('background.jpg')

    background = background.convert()
    screen.blit(background, (0,0))
    clock = pygame.time.Clock()
    FPS = Config.fps
    playtime = 0

    Playergroup = pygame.sprite.Group()
    allgroup = pygame.sprite.LayeredUpdates()

    Player.groups = Playergroup, allgroup

    mainloop = True
    while mainloop:
        millisecond = clock.tick(Config.fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mailoop = False

        pygame.display.set_caption("say hi")
        allgroup.clear(screen, background)
        allgroup.draw(screen)
        pygame.display.flip()
    return 0

if __name__ == '__main__':
    main()

Body:
You can increment the angle if a key gets pressed, then transform the original image, assign it to the self.image attribute and get a new rect with the center of the old rect.

import pygame

class Config(object):
    fullscreen = False
    width = 640
    height = 360
    fps = 60

class Player(pygame.sprite.Sprite):
    maxrotate = 360
    down = (pygame.K_DOWN)
    up = (pygame.K_UP)

    def __init__(self, startpos=(100,223), angle=0):
        super().__init__()
        self.pos = list(startpos)
        self.image = pygame.Surface((70, 70), pygame.SRCALPHA)
        pygame.draw.circle(self.image, pygame.Color('dodgerblue'), (35, 35), 35)
        pygame.draw.circle(self.image, pygame.Color('black'), (35, 15), 8)
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=startpos)
        self.angle = angle

    def update(self, seconds):
        pressedkeys = pygame.key.get_pressed()
        if pressedkeys[self.down]:
            self.angle -= 2
            self.rotate_image()
        if pressedkeys[self.up]:
            self.angle += 2
            self.rotate_image()

    def rotate_image(self):
        self.image = pygame.transform.rotate(self.orig_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    pygame.init()
    screen=pygame.display.set_mode((Config.width,Config.height))
    clock = pygame.time.Clock()
    FPS = Config.fps
    allgroup = pygame.sprite.LayeredUpdates()
    player = Player()
    allgroup.add(player)

    mainloop = True
    while mainloop:
        millisecond = clock.tick(Config.fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mailoop = False

        allgroup.update(millisecond)

        screen.fill((50, 50, 70))
        allgroup.draw(screen)
        pygame.display.flip()

if __name__ == '__main__':
    main()
    pygame.quit()


问:
Find the second largest number in array
I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.

Example :

```<code>array = [21,23,34]
</code>```

Second_largest = 23;

Position is = 1;

答:
You could create a copy of the original array using spread and sort() it. From you'd just get the second to last number from the array and use indexOf to reveal it's index.

const array = [21,23,34];
const arrayCopy = [...array];

const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));```
</div>
</div>
</p>

<p>Alternatively you can use <code>concat</code> to copy the array if compatibility is an issue:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [21, 23, 34];
var arrayCopy = [].concat(array);

var secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));</code>```

Title: Find the second largest number in array

Body:
I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.

Example :

array = [21,23,34]

Second_largest = 23;

Position is = 1;

Body:
You could create a copy of the original array using spread and sort() it. From you'd just get the second to last number from the array and use indexOf to reveal it's index.

const array = [21,23,34];
const arrayCopy = [...array];

const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));

Alternatively you can use concat to copy the array if compatibility is an issue:

var array = [21, 23, 34];
var arrayCopy = [].concat(array);

var secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));


问:
Find the center of the ellipsoid
I want to use the following Matlab script to fit an ellipsoid:

https://de.mathworks.com/matlabcentral/fileexchange/24693-ellipsoid-fit

But I want also understand the math. I am stuck here:

```<code>% find the center of the ellipsoid
center = -A( 1:3, 1:3 ) \ v( 7:9 );
</code>```

Where 'A' is the algebraic form of the ellipsoid. So my question is: What is the relation between the 'algebraic ellipsoid form' and the 'ellipsoid center'.

答:
The equation of the ellipsoid is given in homogeneous coordinates as

```<code>            ⎡v1 v4 v5 v7 ⎤   ⎡x⎤
            ⎢v4 v2 v6 v8 ⎥   ⎢y⎥
[x y z 1] * ⎢v5 v6 v3 v9 ⎥ * ⎢z⎥ = 0
            ⎣v7 v8 v9 v10⎦   ⎣1⎦
</code>```

which you can also write without homogeneous coordinates as

```<code>          ⎡v1 v4 v5⎤   ⎡x⎤                 ⎡v7⎤
[x y z] * ⎢v4 v2 v6⎥ * ⎢y⎥ + 2 * [x y z] * ⎢v8⎥ + v10 = 0
          ⎣v5 v6 v3⎦   ⎣z⎦                 ⎣v9⎦
</code>```

If the second summand is zero, this describes an ellipsoid centered in the origin, since for every point [x,y,z] its mirror image [-x,-y,-z] will lead to the same result. So the second (i.e. linear) term is what shifts the ellipsoid out from the center.

If you start with an ellipsoid centered at the origin and then shift the center to [cx,cy,cz] you'd end up with something of the form

```<code>                   ⎡v1 v4 v5⎤   ⎡x-cx⎤
[x-cx y-cy z-cz] * ⎢v4 v2 v6⎥ * ⎢y-cy⎥ = const.
                   ⎣v5 v6 v3⎦   ⎣z-cz⎦
</code>```

or in vector notation (writing A for the 3×3 matrix in question)

```<code>(x-c) * A * (x-c) = x*A*x - 2*x*A*c + c*A*c = const.
</code>```

I know in Matlab you'd need some ' in there somewhere to transpose some of the vectors, but you get the idea. Comparing the above to what I wrote further up, you can see that essentially you want the linear terms to be equal, i.e.

```<code>-2*x*A*c = 2*x*v(7:9)
    -A*c = v(7:9)

  ⎡v1 v4 v5⎤   ⎡cx⎤   ⎡v7⎤
- ⎢v4 v2 v6⎥ * ⎢cy⎥ = ⎢v8⎥
  ⎣v5 v6 v3⎦   ⎣cz⎦   ⎣v9⎦
</code>```

which means you have a linear system of equations here which you can solve for c, using the code you quoted. It takes the upper left 3×3 matrix from the homogeneous description, and it takes the three elements from v corresponding to the linear term (which I assume could have been written as A(4, 1:3) but I'm no Matlab expert) then it uses \ to solve the linear system of equations. Not sure whether operator precedence is such that the - gets applied to the matrix A or to the solution, but as the result is the same either way, it doesn't really matter.

Title: Find the center of the ellipsoid

Body:
I want to use the following Matlab script to fit an ellipsoid:

https://de.mathworks.com/matlabcentral/fileexchange/24693-ellipsoid-fit

But I want also understand the math. I am stuck here:

% find the center of the ellipsoid
center = -A( 1:3, 1:3 ) \ v( 7:9 );

Where 'A' is the algebraic form of the ellipsoid. So my question is: What is the relation between the 'algebraic ellipsoid form' and the 'ellipsoid center'.

Body:
The equation of the ellipsoid is given in homogeneous coordinates as

            ⎡v1 v4 v5 v7 ⎤   ⎡x⎤
            ⎢v4 v2 v6 v8 ⎥   ⎢y⎥
[x y z 1] * ⎢v5 v6 v3 v9 ⎥ * ⎢z⎥ = 0
            ⎣v7 v8 v9 v10⎦   ⎣1⎦

which you can also write without homogeneous coordinates as

          ⎡v1 v4 v5⎤   ⎡x⎤                 ⎡v7⎤
[x y z] * ⎢v4 v2 v6⎥ * ⎢y⎥ + 2 * [x y z] * ⎢v8⎥ + v10 = 0
          ⎣v5 v6 v3⎦   ⎣z⎦                 ⎣v9⎦

If the second summand is zero, this describes an ellipsoid centered in the origin, since for every point [x,y,z] its mirror image [-x,-y,-z] will lead to the same result. So the second (i.e. linear) term is what shifts the ellipsoid out from the center.

If you start with an ellipsoid centered at the origin and then shift the center to [cx,cy,cz] you'd end up with something of the form

                   ⎡v1 v4 v5⎤   ⎡x-cx⎤
[x-cx y-cy z-cz] * ⎢v4 v2 v6⎥ * ⎢y-cy⎥ = const.
                   ⎣v5 v6 v3⎦   ⎣z-cz⎦

or in vector notation (writing A for the 3×3 matrix in question)

(x-c) * A * (x-c) = x*A*x - 2*x*A*c + c*A*c = const.

I know in Matlab you'd need some ' in there somewhere to transpose some of the vectors, but you get the idea. Comparing the above to what I wrote further up, you can see that essentially you want the linear terms to be equal, i.e.

-2*x*A*c = 2*x*v(7:9)
    -A*c = v(7:9)

  ⎡v1 v4 v5⎤   ⎡cx⎤   ⎡v7⎤
- ⎢v4 v2 v6⎥ * ⎢cy⎥ = ⎢v8⎥
  ⎣v5 v6 v3⎦   ⎣cz⎦   ⎣v9⎦

which means you have a linear system of equations here which you can solve for c, using the code you quoted. It takes the upper left 3×3 matrix from the homogeneous description, and it takes the three elements from v corresponding to the linear term (which I assume could have been written as A(4, 1:3) but I'm no Matlab expert) then it uses \ to solve the linear system of equations. Not sure whether operator precedence is such that the - gets applied to the matrix A or to the solution, but as the result is the same either way, it doesn't really matter.


问:
Unity: How to draw GUI texture under UI elements?
In Unity: How can I draw GUI texture (GUI.DrawTexture) on my 2D application and at the same time have some UI buttons to appear over the drawn GUI and also to be able to interact with these buttons?</p>

答:
Use Unity's LineRenderer and Image or RawImage because GUI.DrawTexture is from IMGUI and should only be used to make Editor plugins or tools.

I tried it but it didn't get what i want from it (LineRenderer is
  drawn under all UI elements which is the opposite of GUI.DrawTexture )

The problem is how you setup the Canvas. The default Canvas Render Mode is "Screen Space - Overlay". When the Canvas is set to "Screen Space - Overlay", it will display on top of everything.

Change your Canvas Render Mode to "Screen Space - Camera" then add your main camera to the Canvas' "Render Camera" slot. You can also use "World Space" as Render Mode. LineRenderer  should now display on top of the Canvas.


问:
Session variable in ASP.NET MVC
I need to create something like a session variable in .net MVC.
I'm using ViewData. First I set it in my Controller Index:

```<code>public ActionResult Index(int id)
    {
        ViewData["myID"] = id;
    }
</code>```

Then, I'll need to use it in another function of the same controller. However, I have to send it to my view. Store the data into a . Then read it again.
View:

```<code><input type="hidden" id="myID" name="myID" value='@ViewData["myID"]'  />
</code>```

Other function of the controller where I get the id:

```<code>[HttpPost, ValidateInput(false)]
    public ActionResult Test(FormCollection form)
    {
        var pId = form["myID"];
    }
</code>```

It works, but looks wrong (I'm new in .net mvc). Is there a way where I can set this id one time in my controller and then read/get it when I need?

Thanks

答:
try this

for set

```<code>System.Web.HttpContext.Current.Session["Id"] = 1;
</code>```

for get

```<code>var id=Convert.ToInt32(System.Web.HttpContext.Current.Session["Id"]);
</code>```

Title: Session variable in ASP.NET MVC

Body:
I need to create something like a session variable in .net MVC.
I'm using ViewData. First I set it in my Controller Index:

public ActionResult Index(int id)
    {
        ViewData["myID"] = id;
    }

Then, I'll need to use it in another function of the same controller. However, I have to send it to my view. Store the data into a . Then read it again.
View:

<input type="hidden" id="myID" name="myID" value='@ViewData["myID"]'  />

Other function of the controller where I get the id:

[HttpPost, ValidateInput(false)]
    public ActionResult Test(FormCollection form)
    {
        var pId = form["myID"];
    }

It works, but looks wrong (I'm new in .net mvc). Is there a way where I can set this id one time in my controller and then read/get it when I need?

Thanks

Body:
try this

for set

System.Web.HttpContext.Current.Session["Id"] = 1;

for get

var id=Convert.ToInt32(System.Web.HttpContext.Current.Session["Id"]);


问:
Write an array of values to a range of cells in a spreadsheet
Using Google Apps Script, is there a way to write the values in a Google Spreadsheet array to a range without looping?

I am thinking something like the following to put one name each into cells A1:A3:

function demoWriteFromArray() {
   var employees=["Adam","Barb","Chris"];
   ssActive = SpreadsheetApp.getActiveSheet();
   rgMyRange = ssActive.getRange("A1:A3");
   rgMyRange.setValue(employees);
}
```

Problem with above is that after execution, A1:A3 all contain ={"Adam","Barb","Chris"} and display "Adam".

答:
I saw this question when researching an answer for my own application.  An alternative solution is to use a custom function that returns a 2D array.

Here's an example.  Suppose "Adam, Barb, Chris; Aaron, Bill, Cindy" is text in A1.  If you put a reference to a custom function in B1, you can fill the range B1:D2 with individual names.

Custom function written in Apps Script:

```<code>function splitNames(names) {
  // you could do any other work necessary here
  var arr = names.split("; ");
  arr[0] = arr[0].split(", ");
  arr[1] = arr[1].split(", ");

  // output should be 2D array where each element of the
  // main array is a range spanning 1 or more columns and
  // one row and each sub array are cells within that range
  return arr;
}
</code>```

The formula in B1 referencing the custom function:
=splitNames(A1)

Note, this function will throw an exception if the cells adjacent to B1 are not empty.  This could be handled with the IFERROR formula or possibly try/catch within the custom formula.

Body:
Using Google Apps Script, is there a way to write the values in a Google Spreadsheet array to a range without looping?

I am thinking something like the following to put one name each into cells A1:A3:

function demoWriteFromArray() {
   var employees=["Adam","Barb","Chris"];
   ssActive = SpreadsheetApp.getActiveSheet();
   rgMyRange = ssActive.getRange("A1:A3");
   rgMyRange.setValue(employees);
}

Problem with above is that after execution, A1:A3 all contain ={"Adam","Barb","Chris"} and display "Adam".

Body:
I saw this question when researching an answer for my own application.  An alternative solution is to use a custom function that returns a 2D array.

Here's an example.  Suppose "Adam, Barb, Chris; Aaron, Bill, Cindy" is text in A1.  If you put a reference to a custom function in B1, you can fill the range B1:D2 with individual names.

Custom function written in Apps Script:

function splitNames(names) {
  // you could do any other work necessary here
  var arr = names.split("; ");
  arr[0] = arr[0].split(", ");
  arr[1] = arr[1].split(", ");

  // output should be 2D array where each element of the
  // main array is a range spanning 1 or more columns and
  // one row and each sub array are cells within that range
  return arr;
}

The formula in B1 referencing the custom function:
=splitNames(A1)

Note, this function will throw an exception if the cells adjacent to B1 are not empty.  This could be handled with the IFERROR formula or possibly try/catch within the custom formula.


问:
What's the benefit of postfixing arrays with "List" for variables?
I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:

```<code>// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';
</code>```

The idea applies to any language with support for arrays.

答:
I think this is mostly a matter of taste. I tend to name things to reflect what they are or what they do. So if I have a collection or array of File instances, the variable would most probably named files, or have a more specific name if the context allows it. Naming an array of Files fileList is in my humble opinion plain wrong, because, at least in Java, an array is not a List. But then, the compiler won't complain...

More complex collections like a Map get names like keyToValue. So if I had a map which assigns teachers to classrooms this would be called teacherToRoom in my code. I hate grepping through the code to find out what the variables are meant to do, so I try to be as specific as needed with the names.

In conclusion it's all about correct code, and variable names can not influence this outcome from the compiler perspective. But they can very well affect the outcome when it comes to humans working with the code, so it's best to do whatever works for the majority of people working on a codebase.

Body:
I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:

// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';

The idea applies to any language with support for arrays.


问:
How to extract text from a PDF file?
I'm trying to extract the text included in this PDF file using Python.

I'm using the PyPDF2 package (version 1.27.2), and have the following script:

import PyPDF2

with open("sample.pdf", "rb") as pdf_file:
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    number_of_pages = read_pdf.getNumPages()
    page = read_pdf.pages[0]
    page_content = page.extractText()
print(page_content)
```
<p>When I run the code, I get the following output which is different from that included in the PDF document:</p>
``` ! " # $ % # $ % &% $ &' ( ) * % + , - % . / 0 1 ' * 2 3% 4
5
 ' % 1 $ # 2 6 % 3/ % 7 / ) ) / 8 % &) / 2 6 % 8 # 3" % 3" * % 31 3/ 9 # &)
%
```

How can I extract the text as is in the PDF document?

答:
You can use PDFtoText
https://github.com/jalan/pdftotext

PDF to text keeps text format indentation, doesn't matter if you have tables.

Title: How to extract text from a PDF file?

Body:
I'm trying to extract the text included in this PDF file using Python.

I'm using the PyPDF2 package (version 1.27.2), and have the following script:

import PyPDF2

with open("sample.pdf", "rb") as pdf_file:
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    number_of_pages = read_pdf.getNumPages()
    page = read_pdf.pages[0]
    page_content = page.extractText()
print(page_content)

When I run the code, I get the following output which is different from that included in the PDF document:

 ! " # $ % # $ % &% $ &' ( ) * % + , - % . / 0 1 ' * 2 3% 4
5
 ' % 1 $ # 2 6 % 3/ % 7 / ) ) / 8 % &) / 2 6 % 8 # 3" % 3" * % 31 3/ 9 # &)
%

How can I extract the text as is in the PDF document?


问:
Do you make safe and unsafe version of your functions or just stick to the safe version? (Embedded System)
let's say you have a function that set an index and then update few variables based on the value stored in the array element which the index is pointing to. Do you check the index to make sure it is in range? (In embedded system environment to be specific Arduino)
So far I have made a safe and unsafe version for all functions, is that a good idea? In some of my other codes I noticed that having only safe functions result in checking conditions multiple time as the libraries get larger, so I started to develop both. The safe function checks the condition and call the unsafe function as shown in example below for the case explained above.

Safe version:

```<code>bool RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS)
    {
        setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
        return true;
    }

    return false;
}
</code>```

Unsafe version:

```<code>void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex)
{
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}
</code>```

If I am doing it wrong fundamentally please let me know why and how I could avoid that. Also I would like to know, generally when you program, do you consider the future user to be a fool or you expect them to follow the minimal documentation provided? (the reason I say minimal is because I do not have the time to write a proper documentation)

```<code>void RcChannelModule::setCuurentFactorIndexUnsafe(const factorIndex_T factorIndex)
{
    currentFactorIndex_ = factorIndex;
}
</code>```

答:
Do you make safe and unsafe version of your functions or just stick to the safe version?

For higher level code, I recommend one version, a safe one.

High level code, with a large set of related functions and data, the combinations of interactions of data and code are not possible to fully check at development time.  When an error is detected, the data should be set to indicate an error state.  Subsequent use of data within these functions would be aware of the error state.

For lowest level -time critical routines, I'd go with @dasblinkenlight answer.  Create one source code that compiles 2 ways per the debug and release compiles.

Yet keep in mind @pete becker, it this really likely a performance bottle neck to do a check?

With floating-point related routines, use the NaN to help keep track of an unrecoverable error.

Lastly, as able, create functions that do not fail and avoid the issue.  With many, not all, this only requires small code additions.  It often only adds a constant of time performance penalty and not a O(n) penalty.

Example: Consider a function to lop off the first character of a string - in place.

```<code>// This work fine as long as s[0] != 0
char *slop_1(char *s) {
  size_t len = strlen(s);         // most work is here
  return memmove(s, s + 1, len);  // and here
}
</code>```

Instead define the function, and code it, to do nothing when s[0] == 0

```<code>char *slop_2(char *s) {
  size_t len = strlen(s);
  if (len > 0) {                // negligible additional work
    memmove(s, s + 1, len);
  }
  return s;
}
</code>```

Similar code can be applied to OP's example.  Note that it is "safe", at least within the function.  The assert() scheme can still be used to discovery development issues.  Yet the released code, without the assert(), still checks the range.

```<code>void RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS) {
      setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
    } else {
      assert(1);
    }
}
</code>```

Body:
let's say you have a function that set an index and then update few variables based on the value stored in the array element which the index is pointing to. Do you check the index to make sure it is in range? (In embedded system environment to be specific Arduino)
So far I have made a safe and unsafe version for all functions, is that a good idea? In some of my other codes I noticed that having only safe functions result in checking conditions multiple time as the libraries get larger, so I started to develop both. The safe function checks the condition and call the unsafe function as shown in example below for the case explained above.

Safe version:

bool RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS)
    {
        setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
        return true;
    }

    return false;
}

Unsafe version:

void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex)
{
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}

If I am doing it wrong fundamentally please let me know why and how I could avoid that. Also I would like to know, generally when you program, do you consider the future user to be a fool or you expect them to follow the minimal documentation provided? (the reason I say minimal is because I do not have the time to write a proper documentation)

void RcChannelModule::setCuurentFactorIndexUnsafe(const factorIndex_T factorIndex)
{
    currentFactorIndex_ = factorIndex;
}

Body:
Do you make safe and unsafe version of your functions or just stick to the safe version?

For higher level code, I recommend one version, a safe one.

High level code, with a large set of related functions and data, the combinations of interactions of data and code are not possible to fully check at development time.  When an error is detected, the data should be set to indicate an error state.  Subsequent use of data within these functions would be aware of the error state.

For lowest level -time critical routines, I'd go with @dasblinkenlight answer.  Create one source code that compiles 2 ways per the debug and release compiles.

Yet keep in mind @pete becker, it this really likely a performance bottle neck to do a check?

With floating-point related routines, use the NaN to help keep track of an unrecoverable error.

Lastly, as able, create functions that do not fail and avoid the issue.  With many, not all, this only requires small code additions.  It often only adds a constant of time performance penalty and not a O(n) penalty.

Example: Consider a function to lop off the first character of a string - in place.

// This work fine as long as s[0] != 0
char *slop_1(char *s) {
  size_t len = strlen(s);         // most work is here
  return memmove(s, s + 1, len);  // and here
}

Instead define the function, and code it, to do nothing when s[0] == 0

char *slop_2(char *s) {
  size_t len = strlen(s);
  if (len > 0) {                // negligible additional work
    memmove(s, s + 1, len);
  }
  return s;
}

Similar code can be applied to OP's example.  Note that it is "safe", at least within the function.  The assert() scheme can still be used to discovery development issues.  Yet the released code, without the assert(), still checks the range.

void RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS) {
      setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
    } else {
      assert(1);
    }
}


答:
Make a clone of your original array using .slice(0) like :

```<code>var temp_arr = arr.slice(0);
</code>```

Then sor it so you get the second largest value at the index temp_arr.length - 2 of your array :

```<code>temp_arr.sort()[temp_arr.length - 2]
</code>```

Now you could use indexOf() function to get the index of this value retrieved like :

```<code>arr.indexOf(second_largest_value);
</code>```

var arr = [23, 21, 34, 34];
var temp_arr = [...new Set(arr)].slice(0); //clone array
var second_largest_value = temp_arr.sort()[temp_arr.length - 2];
var index_of_largest_value = arr.indexOf(second_largest_value);

console.log(second_largest_value);
console.log(index_of_largest_value);```

Title: Find the second largest number in array

Body:
Make a clone of your original array using .slice(0) like :

var temp_arr = arr.slice(0);

Then sor it so you get the second largest value at the index temp_arr.length - 2 of your array :

temp_arr.sort()[temp_arr.length - 2]

Now you could use indexOf() function to get the index of this value retrieved like :

arr.indexOf(second_largest_value);

var arr = [23, 21, 34, 34];
var temp_arr = [...new Set(arr)].slice(0); //clone array
var second_largest_value = temp_arr.sort()[temp_arr.length - 2];
var index_of_largest_value = arr.indexOf(second_largest_value);

console.log(second_largest_value);
console.log(index_of_largest_value);


问:
Vector of object pointers returns odd values
I have a task to create an object Stos which would feature a heap of objects Obiekt, to which I could add things as I please.

In order to make the program better support dynamic arrays I decided to use a Vector.
The whole implementation seems to run perfectly, the returned value is completely off.
Here is an example with code:

```<code>class Obiekt {
private:
    int id;

public:
    Obiekt::Obiekt(int i) {
        id = i;
    }

    void Obiekt::display() {
        cout << "This object has id of: " << id << endl;
    }
};

class Stos {
private:
    vector < Obiekt* > stos;
public:
    Stos::Stos(Obiekt n) {
        add(n);
    }

    void Stos::add(Obiekt n) {
        stos.push_back(&n);
    }

    void Stos::display() {
        cout << endl << "===HEAP DISPLAY===" << endl;
        for (int i = 0; i < stos.size(); i++) {
            stos[i]->display();
        }
    }
};

void Zad1()
{
    Obiekt obj1(5);
    Obiekt obj2(23);

    Stos s1(obj1);
    s1.add(obj2);
    s1.display();

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

And the outcome being:

===HEAP DISPLAY===

This object has id of: -858993460

This object has id of:9805925

I'm not a cpp expert, and believe the issue is related to the stos.push_back(&n) portion, but I can't catch the moment the id gets so distorted.

It's probably a noob question, so sorry for that on start.

Any help would be amazing.

答:
The parameters Obiekt n in

```<code>Stos::Stos(Obiekt n) {
    add(n);
}

void Stos::add(Obiekt n) {
    stos.push_back(&n);
}
</code>```

are temporary copies destroyed immediatly after each call.

You have to use a reference Obiekt & n instead, or better: by pointer Obiekt * n.

Body:
I have a task to create an object Stos which would feature a heap of objects Obiekt, to which I could add things as I please.

In order to make the program better support dynamic arrays I decided to use a Vector.
The whole implementation seems to run perfectly, the returned value is completely off.
Here is an example with code:

class Obiekt {
private:
    int id;

public:
    Obiekt::Obiekt(int i) {
        id = i;
    }

    void Obiekt::display() {
        cout << "This object has id of: " << id << endl;
    }
};

class Stos {
private:
    vector < Obiekt* > stos;
public:
    Stos::Stos(Obiekt n) {
        add(n);
    }

    void Stos::add(Obiekt n) {
        stos.push_back(&n);
    }

    void Stos::display() {
        cout << endl << "===HEAP DISPLAY===" << endl;
        for (int i = 0; i < stos.size(); i++) {
            stos[i]->display();
        }
    }
};

void Zad1()
{
    Obiekt obj1(5);
    Obiekt obj2(23);

    Stos s1(obj1);
    s1.add(obj2);
    s1.display();

    getchar();
}

And the outcome being:

===HEAP DISPLAY===

This object has id of: -858993460

This object has id of:9805925

I'm not a cpp expert, and believe the issue is related to the stos.push_back(&n) portion, but I can't catch the moment the id gets so distorted.

It's probably a noob question, so sorry for that on start.

Any help would be amazing.

Body:
The parameters Obiekt n in

Stos::Stos(Obiekt n) {
    add(n);
}

void Stos::add(Obiekt n) {
    stos.push_back(&n);
}

are temporary copies destroyed immediatly after each call.

You have to use a reference Obiekt & n instead, or better: by pointer Obiekt * n.


问:
National Weather Service API Internal server error

I keep getting error 500 when trying to get data using their new API, even when I include UserAgent string that they request: https://forecast-v3.weather.gov/documentation

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weather.gov/points/40,-90/forecast/hourly");

request.UserAgent = "WeatherTest/v1.0 (http://www.website.com/; Email@email.com)";

// exception occurs here
using (Stream stream = request.GetResponse().GetResponseStream())
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
        var jsonData = streamReader.ReadToEnd();
    }
}
</code>```

But I can use the endpoint on a browser just fine using the same url: https://api.weather.gov/points/40,-90/forecast/hourly

I have also tested this code with another API (Weather Underground) and it works, but my boss wants me to use National Weather Service api instead. Any help is appreciated!

答:
Error 500 is Internal Server Error - this means that the server knows that it errored and recorded it.

Since your method of retrieving data is working for a different API, it seems most likely that the NWS API is quietly refusing the service on purpose. Perhaps it doesn't like the email string you provided, or so on and so forth.

When it comes to third party APIs like this one, your best bet is (1) defer to the manual, if one exists (eg, "RTFM") or (2) to experiment a bit and try different things until you find something that works.

For example, I found that many services - APIs included - did not like one of my email addresses in the format of username@subdomain.domain.com and would refuse service. Only with experimentation was I able to figure this out.

Body:
I keep getting error 500 when trying to get data using their new API, even when I include UserAgent string that they request: https://forecast-v3.weather.gov/documentation

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weather.gov/points/40,-90/forecast/hourly");

request.UserAgent = "WeatherTest/v1.0 (http://www.website.com/; Email@email.com)";

// exception occurs here
using (Stream stream = request.GetResponse().GetResponseStream())
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
        var jsonData = streamReader.ReadToEnd();
    }
}

But I can use the endpoint on a browser just fine using the same url: https://api.weather.gov/points/40,-90/forecast/hourly

I have also tested this code with another API (Weather Underground) and it works, but my boss wants me to use National Weather Service api instead. Any help is appreciated!


问:
Is it possible to determine if a GeoJSON point is inside a GeoJSON polygon using JavasScript?
Is it possible to determine whether a GeoJSON point at a given lat,lon lies within a given GeoJSON polygon using only JavaScript (either through d3, topojson, or any other way)?

For example, I can draw a map showing countries in the UK based on the tutorial here.

I then have a some points which have coordinates but no indication as to which country they lie within.

I would like to display a total point count for each country.

Can I work out which country contains each point in the browser, or do I need to preprocess my point data on the server using PostGIS or similar?

答: Expanding the @thedude answer's you can also use geojson-lookup if you need to do this check more than once on a given GeoJSON.


问:
Is it possible in TFS NOT to trigger a CI build when the content of an active (i.e. NOT cloaked) directory changes?
My scenario is as follows:

Developers check-in SQL changes to directory ClientDB

A dedicated build wakes up, extracts the metadata from the checked-in files, processes it and checks the result in into a sibling directory ClientMetadata

(Developers are not allowed to check-in under ClientMetadata)

The annoying side effect, is that because the dedicated build is a CI build it wakes up twice:

Once for the changes in ClientDB, which makes it update ClientMetadata

Second time, because of its own changes in the ClientMetadata - after all, this directory appears as an Active directory in the Source Settings section of the build:

Ideally, I would like the ClientMetadata directory to be available in the workspace, but I do not want changes there to trigger the build.

Is it possible?

答: Not with XAML build. It's absolutely possible in the build system introduced in TFS 2015.</p>


问:
pyspark 1.4 how to get list in aggregated function
I want to get list of a column values in aggregated function, in pyspark 1.4. The collect_list is not available. Does anyone have suggestion how to do it?

Original columns:

```<code>ID, date, hour, cell
1, 1030, 01, cell1
1, 1030, 01, cell2
2, 1030, 01, cell3
2, 1030, 02, cell4
</code>```

I want output like below, groupby (ID, date, hour)

```<code>ID, date, hour, cell_list
1, 1030, 01, cell1, cell2
2, 1030, 01, cell3
2, 1030, 02, cell4
</code>```

But my pyspark is in 1.4.0, collect_list is not available. I can't do:
df.groupBy("ID","date","hour").agg(collect_list("cell")).

答:
Spark 1.4 is old, not supported, slow, buggy and compatible with current versions. You should really consider upgrading Spark installation

Enable Hive support, register DataFrame as a temporary table, and use

```<code>sqlContext  = HiveContext(sc)

df = ...  # create table using HiveContext
df.registerTempTable("df")

sqlContext.sql(
  "SELECT id, date, hour, collect_list(cell) GROUP BY id, date, hour FROM df"
)
</code>```

Since you use YARN you should should be able to submit any version of Spark code, but it might require placing custom PySpark version on the PYTHONPATH.

Body:
I want to get list of a column values in aggregated function, in pyspark 1.4. The collect_list is not available. Does anyone have suggestion how to do it?

Original columns:

ID, date, hour, cell
1, 1030, 01, cell1
1, 1030, 01, cell2
2, 1030, 01, cell3
2, 1030, 02, cell4

I want output like below, groupby (ID, date, hour)

ID, date, hour, cell_list
1, 1030, 01, cell1, cell2
2, 1030, 01, cell3
2, 1030, 02, cell4

But my pyspark is in 1.4.0, collect_list is not available. I can't do:
df.groupBy("ID","date","hour").agg(collect_list("cell")).

Body:
Spark 1.4 is old, not supported, slow, buggy and compatible with current versions. You should really consider upgrading Spark installation

Enable Hive support, register DataFrame as a temporary table, and use

sqlContext  = HiveContext(sc)

df = ...  # create table using HiveContext
df.registerTempTable("df")

sqlContext.sql(
  "SELECT id, date, hour, collect_list(cell) GROUP BY id, date, hour FROM df"
)

Since you use YARN you should should be able to submit any version of Spark code, but it might require placing custom PySpark version on the PYTHONPATH.


问:
Can I turn off the Node.js server process associated with Visual Studio 2017?
I'm working on an ASP.NET application in Visual Studio 2017, and I'm noticing a "Node.js: Server-side JavaScript" process running at 1.3 GB to 1.8 GB of memory. My IIS worker process is the normal size it is in Visual Studio 2015.

My application doesn't include any Node.js libraries.  I'm not able to figure out how to turn this Node.js: Server-side JavaScript process off. It's eating up too much memory for something I have no use for.

Is there a way to kill this apart from uninstalling Visual Studio 2017 and switching back to Visual Studio 2015?

Killing the main process in Task Manager doesn't affect anything in Visual Studio. However, if I go to the Details tab and kill the individual running processes, it crashes Visual Studio.  I took a video of what happened after I killed the process and ran my local web page (sorry for the quality; Stack Overflow limited image size to 2 MB):

答:
Something that can help the projects mitigate the Node.js weight is to reassign the node version used under menu Tools → Options → Projects and Solutions → Web Package Management to an installed 64-bit version.  Visual Studio will still launch its internal Node.js process for a tsserver.js instance, but any TypeScript code in the project will default to the supplied version -- and this helped me firsthand.

Also, another time I found the language service to be running down, I discovered using a simple tsconfig.json file above the directories used as repositories, and specify to skipLibCheck: true, and add node_modules to exclude—it tremendously helped along the service, and one file does all folders beneath it, regardless of direct project references.  P.S.—if you do want JavaScript intellisense support still, make sure to set the allowJs: true and noEmit: true option.

Lastly, verify in the TypeScript Options under the menu Tools → Options → Text Editor → JavaScript/Typescript → Project that it is not checked to Automatically compile TypeScript files which are not part of a project since that can also tie up resources for auxiliary third-party projects using Node.js or TypeScript.

These are not foolproof. Each has to find their exact bottleneck, but I have found these have worked for me and my team more often than not.


问:
Exception: Parameter 'index' must be a int
I'm trying to insert a row in a MySQL database using PDO, and I'm using parameter binding, but I'm getting a stranger error. The important functions are:

```<code>private static function getConnection() : \Pdo
{
    $con = new \PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'myuser', 'mypassword');
    return $con;
}

public static function runBool(string $query, ?array $bind = []) : bool
{
    return self::getConnection()
        ->prepare($query)
        ->execute($bind);
}
</code>```

As you can see, getConnection() is only returning a connection (and it's working fine), the problem is with the function runBool() which is throwing an error on the ->execute($bind); line:

Exception: Parameter 'index' must be a int

For example, my $query is

INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)

And my $bind is

```<code>array(8) {
    ["company_id"]=> int(1)
    ["name"]=> string(3) "John Doe"
    ["phone"]=> string(11) "123456789"
    ["cpf"]=> string(0) ""
    ["rg"]=> string(0) ""
    ["city_id"]=> int(79)
    ["address"]=> string(0) ""
    ["obs"]=> string(0) ""
}
</code>```

I've already tryed to foreach $bind and to use bindParam() or bindValue() individually, and then run execute but I get the same error on the execute().
I've already included : before each key of the array and removed it (following this comment), but nothing changes.
I've already searched a lot on Google but nobody seems to have the same type of trouble.

Info:

PHP 7.1.12

Ubuntu 16.04.03

MySQL 5.7.20

Vagrant 2.0.0

Every help is appreciated.

---------------- EDIT ----------------

As asked, I've checked my namespaces, but I'm using \Pdo, so I think it's the native PHP PDO class. Here's the var_dump of self::getConnection()->prepare($query):

object(PDOStatement)#90 (1) { ["queryString"]=> string(149) "INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)" }

And here's my table:

```<code>CREATE TABLE `client` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `city_id` int(10) UNSIGNED NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `cpf` varchar(14) DEFAULT NULL,
  `rg` varchar(15) DEFAULT NULL,
  `obs` varchar(100) DEFAULT NULL,
  `company_id` int(10) UNSIGNED NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `client`
  ADD PRIMARY KEY (`id`),
  ADD KEY `city_id` (`city_id`),
  ADD KEY `company_id` (`company_id`);
ALTER TABLE `client` ADD FULLTEXT KEY `search` (`name`,`phone`,`address`,`cpf`,`rg`,`obs`);
ALTER TABLE `client` ADD FULLTEXT KEY `search_basic` (`name`);

ALTER TABLE `client`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=613;

ALTER TABLE `client`
  ADD CONSTRAINT `client-city_id` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  ADD CONSTRAINT `client-company_id` FOREIGN KEY (`company_id`) REFERENCES     `company` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
</code>```

答:
Change your $bind variable to</p>

```<code>array(8) {
    [":company_id"]=> int(1)
    [":name"]=> string(3) "John Doe"
    [":phone"]=> string(11) "123456789"
    [":cpf"]=> string(0) ""
    [":rg"]=> string(0) ""
    [":city_id"]=> int(79)
    [":address"]=> string(0) ""
    [":obs"]=> string(0) ""
}
</code>```

Body:
I'm trying to insert a row in a MySQL database using PDO, and I'm using parameter binding, but I'm getting a stranger error. The important functions are:

private static function getConnection() : \Pdo
{
    $con = new \PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'myuser', 'mypassword');
    return $con;
}

public static function runBool(string $query, ?array $bind = []) : bool
{
    return self::getConnection()
        ->prepare($query)
        ->execute($bind);
}

As you can see, getConnection() is only returning a connection (and it's working fine), the problem is with the function runBool() which is throwing an error on the ->execute($bind); line:

Exception: Parameter 'index' must be a int

For example, my $query is

INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)

And my $bind is

array(8) {
    ["company_id"]=> int(1)
    ["name"]=> string(3) "John Doe"
    ["phone"]=> string(11) "123456789"
    ["cpf"]=> string(0) ""
    ["rg"]=> string(0) ""
    ["city_id"]=> int(79)
    ["address"]=> string(0) ""
    ["obs"]=> string(0) ""
}

I've already tryed to foreach $bind and to use bindParam() or bindValue() individually, and then run execute but I get the same error on the execute().
I've already included : before each key of the array and removed it (following this comment), but nothing changes.
I've already searched a lot on Google but nobody seems to have the same type of trouble.

Info:

PHP 7.1.12

Ubuntu 16.04.03

MySQL 5.7.20

Vagrant 2.0.0

Every help is appreciated.

---------------- EDIT ----------------

As asked, I've checked my namespaces, but I'm using \Pdo, so I think it's the native PHP PDO class. Here's the var_dump of self::getConnection()->prepare($query):

object(PDOStatement)#90 (1) { ["queryString"]=> string(149) "INSERT INTO client (company_id, name, phone, cpf, rg, city_id, address, obs) VALUES (:company_id, :name, :phone, :cpf, :rg, :city_id, :address, :obs)" }

And here's my table:

CREATE TABLE `client` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `city_id` int(10) UNSIGNED NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `cpf` varchar(14) DEFAULT NULL,
  `rg` varchar(15) DEFAULT NULL,
  `obs` varchar(100) DEFAULT NULL,
  `company_id` int(10) UNSIGNED NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `client`
  ADD PRIMARY KEY (`id`),
  ADD KEY `city_id` (`city_id`),
  ADD KEY `company_id` (`company_id`);
ALTER TABLE `client` ADD FULLTEXT KEY `search` (`name`,`phone`,`address`,`cpf`,`rg`,`obs`);
ALTER TABLE `client` ADD FULLTEXT KEY `search_basic` (`name`);

ALTER TABLE `client`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=613;

ALTER TABLE `client`
  ADD CONSTRAINT `client-city_id` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  ADD CONSTRAINT `client-company_id` FOREIGN KEY (`company_id`) REFERENCES     `company` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;

Body:
Change your $bind variable to

array(8) {
    [":company_id"]=> int(1)
    [":name"]=> string(3) "John Doe"
    [":phone"]=> string(11) "123456789"
    [":cpf"]=> string(0) ""
    [":rg"]=> string(0) ""
    [":city_id"]=> int(79)
    [":address"]=> string(0) ""
    [":obs"]=> string(0) ""
}


问:
Converting column values into datetime to insert into AccessDB
I am trying to populate values of Pandas Dataframe into MS Access table. I am using the following Pandas built-in DF.iterrows() to iterate through each row of a DataFrame and insert each row into Access table.

```<code>for index,row in df.iterrows():
    print(repr(row['Vote_date'])) #Using iterrows() temporarily converts datetime64[ns] values into Timestamps
    row['Vote_date'] = row['Vote_date'].to_pydatetime() #This converts all values in this column, except NaT values.

    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])
</code>```

When I run this code, I get the following error:

```<code>pyodbc.DataError: ('22008', '[22008] [Microsoft][ODBC Microsoft Access Driver]Datetime field overflow  (36) (SQLExecDirectW)')
</code>```

Pandas Timestamps values cannot be inserted into MS Access table. Research has shown that I would need to convert the column values into Python datetime values in order to insert into Access DB.

Is there another iteration method that I can use to successfully insert Python datetime values into MS Access? And also handle NaT values?

答:
Have you considered just converting it to datetime and then running the loop?
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_pydatetime.html</p>

```<code>df['Vote_date'] = df['Vote_date'].dt.to_pydatetime()
df.loc[df['Vote_date'].isnull(),"Vote_date"] = None
for index,row in df.iterrows():
    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])
</code>```

Body:
I am trying to populate values of Pandas Dataframe into MS Access table. I am using the following Pandas built-in DF.iterrows() to iterate through each row of a DataFrame and insert each row into Access table.

for index,row in df.iterrows():
    print(repr(row['Vote_date'])) #Using iterrows() temporarily converts datetime64[ns] values into Timestamps
    row['Vote_date'] = row['Vote_date'].to_pydatetime() #This converts all values in this column, except NaT values.

    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])

When I run this code, I get the following error:

pyodbc.DataError: ('22008', '[22008] [Microsoft][ODBC Microsoft Access Driver]Datetime field overflow  (36) (SQLExecDirectW)')

Pandas Timestamps values cannot be inserted into MS Access table. Research has shown that I would need to convert the column values into Python datetime values in order to insert into Access DB.

Is there another iteration method that I can use to successfully insert Python datetime values into MS Access? And also handle NaT values?

Body:
Have you considered just converting it to datetime and then running the loop?
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_pydatetime.html

df['Vote_date'] = df['Vote_date'].dt.to_pydatetime()
df.loc[df['Vote_date'].isnull(),"Vote_date"] = None
for index,row in df.iterrows():
    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])


问:
Firestore Cloud Functions - Keeping Count of Amount of Documents in Collection
I am trying to write a cloud function that will keep track of the amount of Documents in the Collection. There isn't a ton of documentation on this probably because of Firestore is so now.. so I was trying to think of the best way to do this.. this is the solution I come up with.. I can't figure out how to return the count

Document 1 -> Collection - > Documents

In Document 1 there would ideally store the Count of Documents in the Collection, but I can't seem to figure out how to relate this

答:
Let's just assume Document1 is a Blog post and the subcollection is comments.

Trigger the function on comment doc create.

Read the parent doc and increment its existing count

Write the data to the parent doc.

Note: If your the count value changes faster than once-per-second, you may need a distributed counter https://firebase.google.com/docs/firestore/solutions/counters

exports.aggregateComments = functions.firestore
    .document('posts/{postId}/comments/{commentId}')
    .onCreate(event => {

    const commentId = event.params.commentId;
    const postId = event.params.postId;

    // ref to the parent document
    const docRef = admin.firestore().collection('posts').doc(postId)

    return docRef.get().then(snap => {

           // get the total comment count and add one
           const commentCount = snap.data().commentCount + 1;

           const data = { commentCount }

           // run update
           return docRef.update(data)
     })

});
```

I put together a detailed firestore aggregation example if you need to run advanced aggregation calculations beyond a simple count.

Body:
Let's just assume Document1 is a Blog post and the subcollection is comments.

Trigger the function on comment doc create.

Read the parent doc and increment its existing count

Write the data to the parent doc.

Note: If your the count value changes faster than once-per-second, you may need a distributed counter https://firebase.google.com/docs/firestore/solutions/counters

exports.aggregateComments = functions.firestore
    .document('posts/{postId}/comments/{commentId}')
    .onCreate(event => {

    const commentId = event.params.commentId;
    const postId = event.params.postId;

    // ref to the parent document
    const docRef = admin.firestore().collection('posts').doc(postId)

    return docRef.get().then(snap => {

           // get the total comment count and add one
           const commentCount = snap.data().commentCount + 1;

           const data = { commentCount }

           // run update
           return docRef.update(data)
     })

});

I put together a detailed firestore aggregation example if you need to run advanced aggregation calculations beyond a simple count.


问:
Passing an Asterisk into a string in c
I have a question about putting a * into a concatenated string and having it print out the asterisk. My code takes 2 parameter strings, and needs to return a pointer that is the First string and Second string concatenated BUT I need it to have * inbetween each character. (Ex: String 1: 09876;  String 2; 12345  result; 0*9*8*7*6*1*2*3*4*5); My issue isn't with trying to print this result, it's adding the asterisk, especially since C won't let me just declare a * or have a pointer point to *. So I'm a bit stuck. Here's my code

```<code>   char* widen_stars(char * str1, char *str2)
{
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(strlen(str1) + strlen(str2)+ 29);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    char *asterix;
    *asterix = '*'; //Pointer pointing to *, won't let me though//
        while(*p1 != '\0'){
        *p3 = *p1;
        p1++;
        p3++;
        *p3 = *asterix; // Needs to add an *, after printing the first element.//
        }
        while(*p2 != '\0'){
        *p3 = *p2;
        p2++;
        p3++;
        *p3 = *asterix;
        }
    return str4;
}
</code>```

I supplied just my function, because this is the only part of my code I get problems. EDIT: The 29 in my Malloc is to keep account of asterisks and the NULL character (The parameter strings have a maximum of 30 characters) I fixed my problem of adding the asterisk thanks to the community, now I get a segmentation fault, this should be fun.

答:
asterix doesn't need to be a pointer, it's just a single character.

You're not using the correct size when allocating the result string. It needs to have 2 characters for each character in the two original strings -- 1 for each of the characters you're copying, and 1 for the asterisks in between.

You need to add a null terminator to the final result. This can replace the final asterisk, since you're only supposed to have asterisks between the characters, not after each character.

```<code>char* widen_stars(char * str1, char *str2)
{
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(2 * ls1 + 2 * ls2);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    const char asterix = '*';
    while(*p1 != '\0'){
        *p3++ = *p1++;
        *p3++ = asterix; // Needs to add an *, after printing the first element.//
    }
    while(*p2 != '\0'){
        *p3++ = *p2++;
        *p3++ = asterix;
    }
    // Replace last asterisk with null byte
    if (p3 > str4) {
        p3--;
    }
    *p3 = '\0';
    return str4;
}
</code>```

Title: Passing an Asterisk into a string in c

Body:
I have a question about putting a * into a concatenated string and having it print out the asterisk. My code takes 2 parameter strings, and needs to return a pointer that is the First string and Second string concatenated BUT I need it to have * inbetween each character. (Ex: String 1: 09876;  String 2; 12345  result; 0*9*8*7*6*1*2*3*4*5); My issue isn't with trying to print this result, it's adding the asterisk, especially since C won't let me just declare a * or have a pointer point to *. So I'm a bit stuck. Here's my code

   char* widen_stars(char * str1, char *str2)
{
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(strlen(str1) + strlen(str2)+ 29);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    char *asterix;
    *asterix = '*'; //Pointer pointing to *, won't let me though//
        while(*p1 != '\0'){
        *p3 = *p1;
        p1++;
        p3++;
        *p3 = *asterix; // Needs to add an *, after printing the first element.//
        }
        while(*p2 != '\0'){
        *p3 = *p2;
        p2++;
        p3++;
        *p3 = *asterix;
        }
    return str4;
}

I supplied just my function, because this is the only part of my code I get problems. EDIT: The 29 in my Malloc is to keep account of asterisks and the NULL character (The parameter strings have a maximum of 30 characters) I fixed my problem of adding the asterisk thanks to the community, now I get a segmentation fault, this should be fun.

Body:
asterix doesn't need to be a pointer, it's just a single character.

You're not using the correct size when allocating the result string. It needs to have 2 characters for each character in the two original strings -- 1 for each of the characters you're copying, and 1 for the asterisks in between.

You need to add a null terminator to the final result. This can replace the final asterisk, since you're only supposed to have asterisks between the characters, not after each character.

char* widen_stars(char * str1, char *str2)
{
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(2 * ls1 + 2 * ls2);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    const char asterix = '*';
    while(*p1 != '\0'){
        *p3++ = *p1++;
        *p3++ = asterix; // Needs to add an *, after printing the first element.//
    }
    while(*p2 != '\0'){
        *p3++ = *p2++;
        *p3++ = asterix;
    }
    // Replace last asterisk with null byte
    if (p3 > str4) {
        p3--;
    }
    *p3 = '\0';
    return str4;
}


问:
Heroku build directory is not a git repo, need something in HEAD
I have a repo that I am pushing to Heroku and building the app there.

It works fine, it builds in some tmp/9d3ec2fc13fca868bfb7c417c28fd79f directory.

Now, I am using using an npm package git-revision-webpack-plugin that adds the git tag as Version number.

It turns out that the directory is actually not a git repo, so the command fails. Ideally, I'd like to get this working. At worst, I can do without the tag and version, but be able to at least build.

I tried

git init to create a dummy git repo

and the npm package ran git describe --always --tags

That also didn't work because there's no head

fatal: Not a valid object name HEAD

Is there a way to fix so that I can assign something to HEAD

答:
You don't have access to the git repo on Heroku even during build time. Running git init creates an empty repo, but you'd need to add and commit all files to get a SHA for git to describe. Even then, it would be different than the one your repo has on GitHub, locally, and what you push to Heroku.

I don't think the git-revision-webpack-plugin is going to work for you on Heroku unfortunately.


问:
Handling exceptions from methods in map of Optional
I have a method like this.

```<code>@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
    return connector.getConnection(authDTO).map(p->p.getOrders());
}
</code>```

Here

```<code>connector.getConnection(authDTO)
</code>```

returns an Optional of Connection and

```<code>p->p.getOrders()
</code>```

throws KException which I cannot change and is of the form

```<code>public class KException extends Throwable {

    // variables
    public String message;
    public int code;

    // constructor that sets the message
    public KException(String message){
        this.message = message;
    }

    // constructor that sets the message and code
    public KException(String message, int code){
        this.message = message;
        this.code = code;
    }
}
</code>```

and this the strucute of MyException

```<code>public class MyException extends KException {

    public MyException(String message, int code) {
        super(message, code);
    }
}
</code>```

The code is not compiling with the below error

```<code>unreported exception com.something.exceptions.KException; must be caught or declared to be thrown
</code>```

I want to convert this KException to MyException. Is there are an elegant way to do this? PLease help.

答:
as suggested by some of the comments, you can trap the exception within the map operation and then perform any further logic you need to do:

```<code>return getConnection(authDTO).map(p -> {
        try {
            return p.getOrders();
        } catch (KException e) {
            // perform some other logic
        }
});
</code>```

Body:
I have a method like this.

@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
    return connector.getConnection(authDTO).map(p->p.getOrders());
}

Here

connector.getConnection(authDTO)

returns an Optional of Connection and

p->p.getOrders()

throws KException which I cannot change and is of the form

public class KException extends Throwable {

    // variables
    public String message;
    public int code;

    // constructor that sets the message
    public KException(String message){
        this.message = message;
    }

    // constructor that sets the message and code
    public KException(String message, int code){
        this.message = message;
        this.code = code;
    }
}

and this the strucute of MyException

public class MyException extends KException {

    public MyException(String message, int code) {
        super(message, code);
    }
}

The code is not compiling with the below error

unreported exception com.something.exceptions.KException; must be caught or declared to be thrown

I want to convert this KException to MyException. Is there are an elegant way to do this? PLease help.

Body:
as suggested by some of the comments, you can trap the exception within the map operation and then perform any further logic you need to do:

return getConnection(authDTO).map(p -> {
        try {
            return p.getOrders();
        } catch (KException e) {
            // perform some other logic
        }
});


问:
Is it possible to combine 'px' and 'vh' into the height of 1 component in react js
I have a few components and some of them are sized with px.  The others I want to be variable size.  However, the ones that are variable size are not a constant percentage of the page because of the components with a fixed px height.  So I want a component to be about 80% of the screen height('80vh') minus the height of the other component.  I was hoping to use something like

```<code>style={{height:'80vh-40px'}}
</code>```

but that does not work.

I found this page which gets close but that my program does not recognize that calc function. Do I need to require it from some library maybe?

Any ideas on how to make this work?

Thanks!

答:
Note - you can get the window.innerHeight (see http://ryanve.com/lab/dimensions/ for height and width options in javascript) and just calculate this yourself in react and set the width or height in pixels.

If you do this with height, you'd need to recalculate if it changes

```<code>state = {
  windowHeight: window.innerHeight
}

componentWillMount () {
  window.addEventListener('resize', this.handleResize)
}

componentWillUnmount () {
  window.removeEventListener('resize', this.handleResize)
}

handleResize = () => {
  this.setState({ windowHeight: window.innerHeight })
}
</code>```

in your div

```<code><div style={{height: this.state.windowHeight}} > ... </div>
</code>```

You wouldn't want to do this everywhere, but it's very handy for some situations.  For example - setting 100% height on Android mobile web, where 100vh does not work and device buttons cover up part of the screen.

Body:
I have a few components and some of them are sized with px.  The others I want to be variable size.  However, the ones that are variable size are not a constant percentage of the page because of the components with a fixed px height.  So I want a component to be about 80% of the screen height('80vh') minus the height of the other component.  I was hoping to use something like

style={{height:'80vh-40px'}}

but that does not work.

I found this page which gets close but that my program does not recognize that calc function. Do I need to require it from some library maybe?

Any ideas on how to make this work?

Thanks!

Body:
Note - you can get the window.innerHeight (see http://ryanve.com/lab/dimensions/ for height and width options in javascript) and just calculate this yourself in react and set the width or height in pixels.

If you do this with height, you'd need to recalculate if it changes

state = {
  windowHeight: window.innerHeight
}

componentWillMount () {
  window.addEventListener('resize', this.handleResize)
}

componentWillUnmount () {
  window.removeEventListener('resize', this.handleResize)
}

handleResize = () => {
  this.setState({ windowHeight: window.innerHeight })
}

in your div

<div style={{height: this.state.windowHeight}} > ... </div>

You wouldn't want to do this everywhere, but it's very handy for some situations.  For example - setting 100% height on Android mobile web, where 100vh does not work and device buttons cover up part of the screen.


问:
Getting null values in the ASP.NET MVC Controller from checkboxes using jQuery AJAX
I want to post data to the server.  In the form, I've selected checked checkboxes and retrieve values from them.  I used the following code:

```<code>$(".DownloadSelected").click(function () {
    var values = [];
    var chks = $(':checkbox[name="ids"]:checked');

    $(chks).each(function (i) {
        values[i] = $(this).val();
    });

    $.post("/Documents/DownloadSelected/", { ids: values });
});
</code>```

In controller I have this:

```<code>[HttpPost]
public ActionResult DownloadSelected(int[] ids)
{
}
</code>```

The problem is that in controller I retrieved null values in int[]ids array.

Can anybody help me?

答:
you should define a complex type and define a property int[] .

```<code>public class PostModel
{
    public int[] Ids { get; set; }
}
</code>```

and in controller

```<code>[HttpPost]
public ActionResult DownloadSelected(PostModel postModel)
{
}
</code>```

Body:
I want to post data to the server.  In the form, I've selected checked checkboxes and retrieve values from them.  I used the following code:

$(".DownloadSelected").click(function () {
    var values = [];
    var chks = $(':checkbox[name="ids"]:checked');

    $(chks).each(function (i) {
        values[i] = $(this).val();
    });

    $.post("/Documents/DownloadSelected/", { ids: values });
});

In controller I have this:

[HttpPost]
public ActionResult DownloadSelected(int[] ids)
{
}

The problem is that in controller I retrieved null values in int[]ids array.

Can anybody help me?

Body:
you should define a complex type and define a property int[] .

public class PostModel
{
    public int[] Ids { get; set; }
}

and in controller

[HttpPost]
public ActionResult DownloadSelected(PostModel postModel)
{
}


问:
have classes in separte files access it's other c++
Well I have 2 classes in 2 header and 2 cpp files

```<code>#class1.h
#ifndef class1_h
#define class1_h
class myclass;
#endif

#class2.h
#ifndef class2_h
#define class2_h
class anotherclass;
#endif

#class1.cpp

class myclass
{
    anotherclass test1;
}

#class2.cpp

class anotherclass
{
    myclass test2;
}
</code>```

And of course a simple main
Well I think it's obvious why this thing wont even compile
my question here is how to make it compile?

Having the classes in different files is mandatory..

答:
If the class definitions (the bodies that is) must be in separate files then the members of the declared type can only be a pointer (or a reference but that is unusual). You would then need a function in the source file where the class is actually defined that returns a pointer-to-instance of the type.

MyClass.h:

```<code>#if !defined(MYCLASS_H)
#define MYCLASS_H
class MyClass;
MyClass * CreateMyClass();
#endif
</code>```

OtherClass.h:

```<code>#if !defined(OTHERCLASS_H)
#define OTHERCLASS_H
class OtherClass;
OtherClass * CreateOther();
#endif
</code>```

myclass.cpp

```<code>#include "otherclass.h"
class MyClass
{
OtherClass * ptrOther;
public:
MyClass()
: ptrOther(CreateOther())
{}
};
</code>```

otherclass.cpp:

```<code>#include "myclass.h"
class OtherClass
{
MyClass * ptrMyClass;
public:
OtherClass()
: ptrMyClass(CreateMyClass())
{}
};
</code>```

Note that doing things this way you would not actually be able to do anything with ptrOther or ptrMyClass ((possibly not even free them correctly), It would be much more typical to place the class definitions in the header and separate out the member definitions (for functions and statics), like the following:

MyClass2.h:

```<code>#if !defined(MYCLASS2_H)
#define MYCLASS2_H
#include "OtherClass.h"
class MyClass2
{
OtherClass * ptrOther;
public:
MyClass2();
};
#endif
</code>```

cMyClass.cpp:

```<code>#include "MyClass2.h"
MyClass2::MyClass2()
: ptrOther(CreateOther())
{}
</code>```

Body:
Well I have 2 classes in 2 header and 2 cpp files

#class1.h
#ifndef class1_h
#define class1_h
class myclass;
#endif

#class2.h
#ifndef class2_h
#define class2_h
class anotherclass;
#endif

#class1.cpp

class myclass
{
    anotherclass test1;
}

#class2.cpp

class anotherclass
{
    myclass test2;
}

And of course a simple main
Well I think it's obvious why this thing wont even compile
my question here is how to make it compile?

Having the classes in different files is mandatory..

Body:
If the class definitions (the bodies that is) must be in separate files then the members of the declared type can only be a pointer (or a reference but that is unusual). You would then need a function in the source file where the class is actually defined that returns a pointer-to-instance of the type.

MyClass.h:

#if !defined(MYCLASS_H)
#define MYCLASS_H
class MyClass;
MyClass * CreateMyClass();
#endif

OtherClass.h:

#if !defined(OTHERCLASS_H)
#define OTHERCLASS_H
class OtherClass;
OtherClass * CreateOther();
#endif

myclass.cpp

#include "otherclass.h"
class MyClass
{
OtherClass * ptrOther;
public:
MyClass()
: ptrOther(CreateOther())
{}
};

otherclass.cpp:

#include "myclass.h"
class OtherClass
{
MyClass * ptrMyClass;
public:
OtherClass()
: ptrMyClass(CreateMyClass())
{}
};

Note that doing things this way you would not actually be able to do anything with ptrOther or ptrMyClass ((possibly not even free them correctly), It would be much more typical to place the class definitions in the header and separate out the member definitions (for functions and statics), like the following:

MyClass2.h:

#if !defined(MYCLASS2_H)
#define MYCLASS2_H
#include "OtherClass.h"
class MyClass2
{
OtherClass * ptrOther;
public:
MyClass2();
};
#endif

cMyClass.cpp:

#include "MyClass2.h"
MyClass2::MyClass2()
: ptrOther(CreateOther())
{}


问:
Gradle Build failed for the task "processBasicDebugResources" error: com.github.javaparser.TokenMgrError
There was some update to the XML resource file for ES Strings.  After the changes with these String the Build fails with below error:

```<code>Error:com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""
</code>```

The error states that issue is with Superscript char \u00b3, however, I have not added this in the resource file.

To debug this issue, I run Gradlew directly from terminal with stacktrace, which give the below details:

```<code>Caused by: com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""
    at com.github.javaparser.ASTParserTokenManager.getNextToken(ASTParserTokenManager.java:2480)
    at com.github.javaparser.ASTParser.jj_scan_token(ASTParser.java:9115)
    at com.github.javaparser.ASTParser.jj_3R_92(ASTParser.java:5504)
    at com.github.javaparser.ASTParser.jj_3_5(ASTParser.java:5574)
    at com.github.javaparser.ASTParser.jj_2_5(ASTParser.java:5198)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBodyDeclaration(ASTParser.java:944)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBody(ASTParser.java:865)
    at com.github.javaparser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:470)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBodyDeclaration(ASTParser.java:932)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBody(ASTParser.java:865)
    at com.github.javaparser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:470)
    at com.github.javaparser.ASTParser.TypeDeclaration(ASTParser.java:398)
    at com.github.javaparser.ASTParser.CompilationUnit(ASTParser.java:203)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:111)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:158)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:177)
    at butterknife.plugin.FinalRClassBuilder.brewJava(FinalRClassBuilder.java:36)
    at butterknife.plugin.FinalRClassBuilder$brewJava.call(Unknown Source)
    at butterknife.plugin.ButterKnifePlugin$_apply_closure1$_closure2$_closure3$_closure4.doCall(ButterKnifePlugin.groovy:34)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:596)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:577)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 70 more
</code>```

Could anyone please suggest on how this can be fixed, any ideas!

答:
You say:

There was some update to the XML resource file for ES Strings. After
  the changes with these String the Build fails with below error:

```<code>Error:com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""
</code>```

What's happening

In your Spanish res/values-es/strings.xml file you have a unicode charachter,

  (U+00B3) ('SUPERSCRIPT THREE') at line 5563, column 57.

(Remember the Android strings.xml resource file is UTF-8 encoded).

How to fix it (general fix)

This is how you encode that character in strings.xml (&#x00b3):

```<code>  <string name="SUPERSCRIPT THREE">&#x00b3</string>
</code>```

How to fix it (specific)

It is not clear how or why you are using com.github.javaparser to process your resource strings instead of the default (as I know it) XmlPullParser (you have not shared your build.gradle file's). It is clear you are using an old (with known bugs in this area) version. To upgrade:

```<code>dependencies {
    compile 'com.github.javaparser:javaparser-core:3.5.5'
}
</code>```

Links

See Special-characters-in-your-XML.

Body:
There was some update to the XML resource file for ES Strings.  After the changes with these String the Build fails with below error:

Error:com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""

The error states that issue is with Superscript char \u00b3, however, I have not added this in the resource file.

To debug this issue, I run Gradlew directly from terminal with stacktrace, which give the below details:

Caused by: com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""
    at com.github.javaparser.ASTParserTokenManager.getNextToken(ASTParserTokenManager.java:2480)
    at com.github.javaparser.ASTParser.jj_scan_token(ASTParser.java:9115)
    at com.github.javaparser.ASTParser.jj_3R_92(ASTParser.java:5504)
    at com.github.javaparser.ASTParser.jj_3_5(ASTParser.java:5574)
    at com.github.javaparser.ASTParser.jj_2_5(ASTParser.java:5198)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBodyDeclaration(ASTParser.java:944)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBody(ASTParser.java:865)
    at com.github.javaparser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:470)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBodyDeclaration(ASTParser.java:932)
    at com.github.javaparser.ASTParser.ClassOrInterfaceBody(ASTParser.java:865)
    at com.github.javaparser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:470)
    at com.github.javaparser.ASTParser.TypeDeclaration(ASTParser.java:398)
    at com.github.javaparser.ASTParser.CompilationUnit(ASTParser.java:203)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:111)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:158)
    at com.github.javaparser.JavaParser.parse(JavaParser.java:177)
    at butterknife.plugin.FinalRClassBuilder.brewJava(FinalRClassBuilder.java:36)
    at butterknife.plugin.FinalRClassBuilder$brewJava.call(Unknown Source)
    at butterknife.plugin.ButterKnifePlugin$_apply_closure1$_closure2$_closure3$_closure4.doCall(ButterKnifePlugin.groovy:34)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:596)
    at org.gradle.api.internal.AbstractTask$ClosureTaskAction.execute(AbstractTask.java:577)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 70 more

Could anyone please suggest on how this can be fixed, any ideas!

Body:
You say:

There was some update to the XML resource file for ES Strings. After
  the changes with these String the Build fails with below error:

Error:com.github.javaparser.TokenMgrError: Lexical error at line 5563, column 57.  Encountered: "\u00b3" (179), after : ""

What's happening

In your Spanish res/values-es/strings.xml file you have a unicode charachter,

  (U+00B3) ('SUPERSCRIPT THREE') at line 5563, column 57.

(Remember the Android strings.xml resource file is UTF-8 encoded).

How to fix it (general fix)

This is how you encode that character in strings.xml (&#x00b3):

  <string name="SUPERSCRIPT THREE">&#x00b3</string>

How to fix it (specific)

It is not clear how or why you are using com.github.javaparser to process your resource strings instead of the default (as I know it) XmlPullParser (you have not shared your build.gradle file's). It is clear you are using an old (with known bugs in this area) version. To upgrade:

dependencies {
    compile 'com.github.javaparser:javaparser-core:3.5.5'
}

Links

See Special-characters-in-your-XML.