问:
creating an auto increment field within a mongo document
In my Spring Boot application I am using Spring-Data MongoDB, and I have a simple POJO that represents users:

```<code>@EqualsAndHashCode
public class User implements Storable {

  @Id
  public ObjectId id;

  @Getter @Setter public String firstName;
  @Getter @Setter public String lastName;
  @Getter @Setter public long userNum;
  @DBRef(lazy = true)
  @Getter @Setter public List<Section> sections = new ArrayList<Section>();

...
rest of class omitted
...

}
</code>```

my UserController looks something like this:

```<code>@Controller
public class UserController {

  @Autowired
  UserRepository repository;

  @ModelAttribute("allSections")
  public List<Section> getSections() {
    return sectionRepository.findAll();
  }

  @RequestMapping(value = "/users/new", method = RequestMethod.POST)
  public String newUser(@ModelAttribute("user") User user) {
    User newUser = new User();
    newUser.userNum = user.userNum;
    newUser.firstName = user.firstName;
    newUser.lastName = user.lastName;
    newUser.sections = user.sections;
    newUser = repository.save(newUser);

    for (Section section : newUser.sections) {
      section.addToUsers(newUser);
      sectionRepository.save(section);
    }

    return "redirect:/users";
  }
... rest of controller omitted
}
</code>```

please notice that the field that I want to be auto-generated is not the ID field.

I would like for the userNum attribute to be auto incrementing such that the first user object created and stored in the database starts at a certain value... say 9000 and each user created after that is incremented by 1.

What are my options to do this? I have seen examples using JPA's @GeneratedValue, others that rely on custom Mongo queries to create a sequence collection, but I have not been able to get either to work...

答:
Create Counter collection:

```<code>public class Counter {

    @Id
    private String id;

    private long seq;

    public Counter(String id, long seq) {
        this.id = id;
        this.seq = seq;
    }

    // Getters and setters
}
</code>```

Then a MongoRepository:

```<code>@Repository
public interface CounterRepository extends MongoRepository<Counter, String> {}
</code>```

And a Service/DAO:

```<code>@Service
public class CounterServiceImpl implements CounterService {

    @Autowired
    private CounterRepository counterRepository;

    @Override
    public long getNext(String sequenceId) {
        Counter counter = counterRepository.findOne(sequenceId);
        long id = counter.getSeq();
        counter.setSeq(id + 1);
        counterRepository.save(counter);
        return id;
    }
}
</code>```

Body:
In my Spring Boot application I am using Spring-Data MongoDB, and I have a simple POJO that represents users:

@EqualsAndHashCode
public class User implements Storable {

  @Id
  public ObjectId id;

  @Getter @Setter public String firstName;
  @Getter @Setter public String lastName;
  @Getter @Setter public long userNum;
  @DBRef(lazy = true)
  @Getter @Setter public List
 sections = new ArrayList
();

...
rest of class omitted
...

}

my UserController looks something like this:

@Controller
public class UserController {

  @Autowired
  UserRepository repository;

  @ModelAttribute("allSections")
  public List
 getSections() {
    return sectionRepository.findAll();
  }

  @RequestMapping(value = "/users/new", method = RequestMethod.POST)
  public String newUser(@ModelAttribute("user") User user) {
    User newUser = new User();
    newUser.userNum = user.userNum;
    newUser.firstName = user.firstName;
    newUser.lastName = user.lastName;
    newUser.sections = user.sections;
    newUser = repository.save(newUser);

    for (Section section : newUser.sections) {
      section.addToUsers(newUser);
      sectionRepository.save(section);
    }

    return "redirect:/users";
  }
... rest of controller omitted
}

please notice that the field that I want to be auto-generated is not the ID field.

I would like for the userNum attribute to be auto incrementing such that the first user object created and stored in the database starts at a certain value... say 9000 and each user created after that is incremented by 1.

What are my options to do this? I have seen examples using JPA's @GeneratedValue, others that rely on custom Mongo queries to create a sequence collection, but I have not been able to get either to work...

Body:
Create Counter collection:

public class Counter {

    @Id
    private String id;

    private long seq;

    public Counter(String id, long seq) {
        this.id = id;
        this.seq = seq;
    }

    // Getters and setters
}

Then a MongoRepository:

@Repository
public interface CounterRepository extends MongoRepository<Counter, String> {}

And a Service/DAO:

@Service
public class CounterServiceImpl implements CounterService {

    @Autowired
    private CounterRepository counterRepository;

    @Override
    public long getNext(String sequenceId) {
        Counter counter = counterRepository.findOne(sequenceId);
        long id = counter.getSeq();
        counter.setSeq(id + 1);
        counterRepository.save(counter);
        return id;
    }
}


来源: stackexchange

问:
How can I set big array size in pascal?
I need to create an array in pascal with an enormous size, is such thing possible ?
I know the size number, I mean it's not n or unknown, it's just a really really big number:

2 ^ 255

Can I do that or not ? and if not is there any other way I can make something like that happen ?
Thanks in advance

Update:
The peoblem I'm trying to solve is, by giving a number between 1 to 255 (including 1 & 255), I need to print all Gray Code with length of that number, for example:
giving n=2 the program should print:
00, 01, 11, 10

since I have the max number of size that I can enter I assumed I'd make an array with the max number, the thing is maybe I can solve this with recursion, but I;m very new to pascal so I don't know how can I do that (at least not yet)

here's what I meant:
type arr = array[1..255,1..MAXINT] of integer;

hints and tips can be very helpful <3

答:
I am not proficient in pascal but here is something I have written. It takes a numeric input and converts it in binary then into gray code.

This is the best I could do as again Pascal is not my main lang of work. :)

```<code>Uses Math;

var
a,b,d,e,f:integer;
c:array[1..255] of integer;

begin
write('input a decimal number! ');
readln(a);
write('grey code of decimal ',a,' is ');

if a<=1 then write(a) else

repeat
 b:=b+1;
 d:=a div 2;
 c[b]:=a mod 2;
 if d<=1 then
 begin
  b:=b+1;
  c[b]:=d;
 end;
 a:=d;
until d<=1;

for e:=b downto 1 do
begin
 //HERE YOU WOULD NEED TO EDIT AND FIX THIS, I THINK THIS WILL ONLY WORK FOR
 //1-9
 write(c[e -1] xor 1 shl (c[e]>>1));
end;

readln
end.
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can I set big array size in pascal?

Body:
I am not proficient in pascal but here is something I have written. It takes a numeric input and converts it in binary then into gray code.

This is the best I could do as again Pascal is not my main lang of work. :)

Uses Math;

var
a,b,d,e,f:integer;
c:array[1..255] of integer;

begin
write('input a decimal number! ');
readln(a);
write('grey code of decimal ',a,' is ');

if a<=1 then write(a) else

repeat
 b:=b+1;
 d:=a div 2;
 c[b]:=a mod 2;
 if d<=1 then
 begin
  b:=b+1;
  c[b]:=d;
 end;
 a:=d;
until d<=1;

for e:=b downto 1 do
begin
 //HERE YOU WOULD NEED TO EDIT AND FIX THIS, I THINK THIS WILL ONLY WORK FOR
 //1-9
 write(c[e -1] xor 1 shl (c[e]>>1));
end;

readln
end.


问:
WP display ACF value from all posts on a page
I would like to create a page that displays 3 ACF Values in an alphabetized list. I have a custom post type ="product" and would like to display the following twi fields (Both are ACF text fields) 1. vendor_or_brand_name and 2. product_url

I can output all post titles from the product post type like this:

```<code>function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product';
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="products">';
            foreach( $results as $index => $post ) {
                    $output .= '<li id="' . $post['ID'] . '">' . $post['post_title'] . '</li>';
                }
            $output .= '</ul>'; // end of select element
            return $output;
}
</code>```

But when I try and modify 'post_title' to either of the ACF field values I get no output. Please advise.

答:
That's because you're querying specifics in the DB... the fields don't exist there. ACF has existing functions to get field values e.g. get_field()

So in your case:

```<code>function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product';
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="products">';
            foreach( $results as $index => $post ) {
                    $output .= '<li id="' . $post['ID'] . '">' . get_field('ACF_FIELD_NAME',$post['ID']) . '</li>';
                }
            $output .= '</ul>'; // end of select element
            return $output;
}
</code>```

Be sure to change the ACF_FIELD_NAME to what ever you named the ACF field in the WP Admin

Body:
I would like to create a page that displays 3 ACF Values in an alphabetized list. I have a custom post type ="product" and would like to display the following twi fields (Both are ACF text fields) 1. vendor_or_brand_name and 2. product_url

I can output all post titles from the product post type like this:

function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product';
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '
';
            foreach( $results as $index => $post ) {
                    $output .= '
' . $post['post_title'] . '
';
                }
            $output .= '
'; // end of select element
            return $output;
}

But when I try and modify 'post_title' to either of the ACF field values I get no output. Please advise.

Body:
That's because you're querying specifics in the DB... the fields don't exist there. ACF has existing functions to get field values e.g. get_field()

So in your case:

function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product';
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="products">';
            foreach( $results as $index => $post ) {
                    $output .= '<li id="' . $post['ID'] . '">' . get_field('ACF_FIELD_NAME',$post['ID']) . '</li>';
                }
            $output .= '</ul>'; // end of select element
            return $output;
}

Be sure to change the ACF_FIELD_NAME to what ever you named the ACF field in the WP Admin


问:
Best way to record a HTML Canvas/WebGL animation server-side into a video?
I have a set of animations which I can make in Canvas (fabric.js) or WebGL (three.js). I need to record them automatically, server-side, through a script and output a video file.

The animations include:

Pictures

Videos (with audio)

Other animations/effects

I have researched a lot during last few months on this.

Results

1. Use PhantomJS + FFMPEG

Run HTML Canvas animations on headless browser(PhantomJS) and record with FFMPEG. Here the issue is PhantomJS supports neither WebGL nor Video element. http://phantomjs.org/supported-web-standards.html

2. Use Websockets to send data back to server using DataURL

Here again, we will need to run the animations on browser (which we can't because we have to do everything on server).

3. Use node-canvas

This is a library by TJ Holowaychuk which allows rendering HTML Canvas on Node.js. But it has its own limitations plus I haven't really explored this field much.
(If someone could shed more light on this library)

If anyone has done it before or can guide me somewhere useful.

All we need to do is use some data to create animations and record it into a video, everything on server side.

答:
I think that the chromium headless mode might support WebGL already and is another possibility. The video rendering part is yet to come though:
https://bugs.chromium.org/p/chromium/issues/detail?id=781117</p>

ContentLicense: CC BY-SA 4.0


问:
Random item from collection - Javascript
I have a collection with objects in them.

```<code>Collection { '378570673196367892' => [Object], '37858392' => [Object], '28284' => [Object] }
</code>```

In the object there is a function I want to call, add emoji.

For the first object it's easy. I just use:

```<code><Collection>.first().addemoji('abc', 'def')
</code>```

But: I want to take a random object to execute the addemoji thing on.

So it will be

```<code><Random selected Object>.addemoji('abc', 'def')
</code>```

答:
```<code>var allkeys = Object.keys(collection)
var randomObject = collection.get(allKeys[ allKeys.length * Math.random() << 0]);
randomObject.addemoji('abc', 'def');
</code>```

Body:
I have a collection with objects in them.

Collection { '378570673196367892' => [Object], '37858392' => [Object], '28284' => [Object] }

In the object there is a function I want to call, add emoji.

For the first object it's easy. I just use:

<Collection>.first().addemoji('abc', 'def')

But: I want to take a random object to execute the addemoji thing on.

So it will be

<Random selected Object>.addemoji('abc', 'def')


问:
Angular 4 *ngFor current element value to increase and decrease
I'm making a little application in Angular 4, I'm displaying a table with some data, I wanna increase and decrease the current value by clicking DecreaseVal() and IncreaseVal() function, but it change all the value in the loop.

```<code><tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal()">&nbsp</div>
            <div class="entry value"><span>{{count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal()"> </div>
        </div>
    </div>
  </td>
</tr>
</code>```

This is my component

```<code> count=1;
    DecreaseVal()
    {
    this.count=this.count>1?this.count-1:this.count;
    }
    IncreaseVal()
    {
     this.count=this.count<5?this.count+1:this.count;
    }
</code>```

答:
There are two possible solutions for your problem. First of all, it will increase all the values because is the same variable for all elements you are iterating. The first and quick solution is to add that count to your heroe object in your heroes array. Something like

heroes = [{heroName:'example', count : 0}, {heroName:'other', count : 0}];

Then, in your event you have to send the index to make the method know where to increase.

(click)="IncreaseVal(i)"

In your component then you have to increase the counter of that object.

IncreaseVal(index){ this.heroes[index].count++; }

The other solution is to create a child component for heroes. It will have the completed td and the counter val.

Body:
I'm making a little application in Angular 4, I'm displaying a table with some data, I wanna increase and decrease the current value by clicking DecreaseVal() and IncreaseVal() function, but it change all the value in the loop.

&nbsp

{{count}}

This is my component

 count=1;
    DecreaseVal()
    {
    this.count=this.count>1?this.count-1:this.count;
    }
    IncreaseVal()
    {
     this.count=this.count<5?this.count+1:this.count;
    }


问:
Wordpress Visually Group / Separate Outputted Posts From Categories using query_posts
In my wordpress site, I'm outputting posts sorted by category ascending and this is working fine.

The code for accomplishing this so far is:

```<code><?php query_posts('cat=1,2,3&showposts=5&orderby=category&order=ASC'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
    <?php the_excerpt() ?>
  </li>
<?php endwhile; endif; ?>
</code>```

Right now all the posts are displayed as one group, sorted by category ascended which is great ... but I'm trying to visually separate the categories.

So, my code right now would work smth like:

```<code>Cat1 Post1 Cat1 Post2 Cat2 Post1 Cat2 Post2 Cat2 Post3 Cat3 Post1 ... and so on
</code>```

I want to separate them like this:

```<code>CATEGORY ONE:
Cat1 Post1 Cat1 Post2

CATEGORY TWO:
Cat2 Post1 Cat2 Post2 Cat2 Post3

CATEGORY THREE:
Cat3 Post1 ... and so on
</code>```

Is this a paramater I can add to the query_posts loop or something?  Seems like something easy to accomplish but I have no idea how to!  Any helps appreciated.

答: Yes, that's how to do it. You can do the same thing with my SEO Siloing plugin, but you would definitely need to use three separate calls to it, which is what you've done.</p>

ContentLicense: CC BY-SA 2.5

Body:
In my wordpress site, I'm outputting posts sorted by category ascending and this is working fine.

The code for accomplishing this so far is:

<?php query_posts('cat=1,2,3&showposts=5&orderby=category&order=ASC'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<a href="<?php the_permalink() ?>"><?php the_title(); ?>
    <?php the_excerpt() ?>

<?php endwhile; endif; ?>

Right now all the posts are displayed as one group, sorted by category ascended which is great ... but I'm trying to visually separate the categories.

So, my code right now would work smth like:

Cat1 Post1 Cat1 Post2 Cat2 Post1 Cat2 Post2 Cat2 Post3 Cat3 Post1 ... and so on

I want to separate them like this:

CATEGORY ONE:
Cat1 Post1 Cat1 Post2

CATEGORY TWO:
Cat2 Post1 Cat2 Post2 Cat2 Post3

CATEGORY THREE:
Cat3 Post1 ... and so on

Is this a paramater I can add to the query_posts loop or something?  Seems like something easy to accomplish but I have no idea how to!  Any helps appreciated.


问:
Angular 4/5 Bootstrap 4 Navbar NgbModule
I'm trying to create a navbar dropdown when the window is halved in size. The dropdown doesn't work at window width 950px, however it works at window width 768px.

navbar.component.html

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" (click)="toggleMenu()">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarNav" [ngbCollapse]="isCollapsed">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

navbar.component.ts

```<code>import { Component } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
  public isCollapsed = true;

 toggleMenu() {
    this.isCollapsed = !this.isCollapsed;
  }
}
</code>```

At 950px the dropdown doesn't hide the menu items. However, if I uncheck 'display: block !important' for class '.navbar-collapse.collapse' then it works.

At 768px the dropdown starts to work (it hides the menu items) and the dropdown button moves over to the left.

答: I'm not sure this qualifies as a 'solution' but hopefully this will help others.  I switched from ng-bootstrap to ngx-bootstrap and using the same component (Collapse) my issue was resolved.</p>

Body:
I'm trying to create a navbar dropdown when the window is halved in size. The dropdown doesn't work at window width 950px, however it works at window width 768px.

navbar.component.html

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" (click)="toggleMenu()">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

navbar.component.ts

import { Component } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
  public isCollapsed = true;

 toggleMenu() {
    this.isCollapsed = !this.isCollapsed;
  }
}

At 950px the dropdown doesn't hide the menu items. However, if I uncheck 'display: block !important' for class '.navbar-collapse.collapse' then it works.

At 768px the dropdown starts to work (it hides the menu items) and the dropdown button moves over to the left.


问:
How to resolve “Error: bad index – Fatal: index file corrupt” when using Git-SVN
i'm currently using git svn in one of my repo and when i do

```<code>git svn fetch
</code>```

i got

```<code>Found possible branch point: coherent tag ref
Initializing parent: ok stuff

error: bad index file sha1 signature
fatal: index file corrupt
command returned error: 128
</code>```

Is ther a way to fix this ? It's a kind of an horrible repo. It take days to synch to that point, i dont want to start from begining :/.

I try the

```<code>rm .git/index
</code>```

from How to resolve "Error: bad index – Fatal: index file corrupt" when using Git but there is no such file.

答:
Were you able to spot the .git folder manually by going into your repository?   you can try running below command to possibly get more information?</p>

```<code>git fsck --full
</code>```

Body:
i'm currently using git svn in one of my repo and when i do

git svn fetch

i got

Found possible branch point: coherent tag ref
Initializing parent: ok stuff

error: bad index file sha1 signature
fatal: index file corrupt
command returned error: 128

Is ther a way to fix this ? It's a kind of an horrible repo. It take days to synch to that point, i dont want to start from begining :/.

I try the

rm .git/index

from How to resolve "Error: bad index – Fatal: index file corrupt" when using Git but there is no such file.

Body:
Were you able to spot the .git folder manually by going into your repository?   you can try running below command to possibly get more information?

git fsck --full


问:
What's the difference between OC xor and Java xor?
I hava a question about  Java and OC  xor:

First xor, the second  Base64

In  java, the code :

```<code>     String  numberStr = ("123456");

    char[] array = numberStr.toCharArray();
    for (int i = 0; i < array.length; i++)
    {
        array[i] = (char) (array[i] ^ 1984);
    }
    String xorStr = new String(array);

    byte[] b = null;
    String s = null;
    try {
        b = xorStr.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        try {
            s = Base64.encodeToString(b, Base64.DEFAULT);;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }
</code>```

the result is : 37Hfst+z37Tftd+2

In OC,the code:

```<code>    NSString *numberString = @"123456";
    NSData* bytes = [numberString dataUsingEncoding:NSUTF8StringEncoding];
    int8_t * bytePtr = ( int8_t * )[bytes bytes];
    NSInteger totalData = [bytes length] / sizeof(int8_t);
    NSMutableString *finalString = [NSMutableString new];
    for (int i = 0 ; i < totalData; i ++){
    bytePtr[i] = (int8_t)(bytePtr[i]) ^ (1984);
    [finalString appendString:[NSString stringWithFormat:@"%c",bytePtr[i]]];
    NSLog(@"encrypt data = %d", bytePtr[i]);
    }

    NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseString = [finalData base64EncodedStringWithOptions:0];
</code>```

the  result  baseString is : w7HDssOzw7TDtcO2

why  the result  is different?  I just know  my  OC  code  is wrong !
Could someone  tell  me  the  correct answer ?

答:
You are not using types that are equivalent to each other.

From the Java specification:

"The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)"

In your Java code, you're iterating over 16-bit objects. In the OC code, you're iterating over 8-bit objects.

For an 8-bit Java primitive type, use byte.

Body:
I hava a question about  Java and OC  xor:

First xor, the second  Base64

In  java, the code :

     String  numberStr = ("123456");

    char[] array = numberStr.toCharArray();
    for (int i = 0; i < array.length; i++)
    {
        array[i] = (char) (array[i] ^ 1984);
    }
    String xorStr = new String(array);

    byte[] b = null;
    String s = null;
    try {
        b = xorStr.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        try {
            s = Base64.encodeToString(b, Base64.DEFAULT);;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

the result is : 37Hfst+z37Tftd+2

In OC,the code:

    NSString *numberString = @"123456";
    NSData* bytes = [numberString dataUsingEncoding:NSUTF8StringEncoding];
    int8_t * bytePtr = ( int8_t * )[bytes bytes];
    NSInteger totalData = [bytes length] / sizeof(int8_t);
    NSMutableString *finalString = [NSMutableString new];
    for (int i = 0 ; i < totalData; i ++){
    bytePtr[i] = (int8_t)(bytePtr[i]) ^ (1984);
    [finalString appendString:[NSString stringWithFormat:@"%c",bytePtr[i]]];
    NSLog(@"encrypt data = %d", bytePtr[i]);
    }

    NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseString = [finalData base64EncodedStringWithOptions:0];

the  result  baseString is : w7HDssOzw7TDtcO2

why  the result  is different?  I just know  my  OC  code  is wrong !
Could someone  tell  me  the  correct answer ?


问:
Apache Beam TextIO PCollection of files instead of lines
Using Apache Beam Java SDK 2.1.0

We have several error logs in a bucket of Google Cloud storage, we are reading all the files in this path, with TextIO.read

We need to aggregate them in order to find errors in messages being sent. We have a regex that works, filtering different lines from each file, the problem is that with the nature of TextIO.read we get a PCollection of lines, so when try to apply the regex in the pardo, its processing it  line by line and the Regex never finds a match.

Regex: "MESSAGE:(.*)\\n\\[MESSAGE\\].*(\\\"entityName\\\":\\\"\\w+\\\")"

Is there anyway that TextIO.read returns a PCollection of files, one file per element so then when it gets the parDo we have access to complete element?

As a plan b, is there a way to combine all the lines of each file into one, with Apache Beam, so the regex pattern works?

```<code>public static class ExtractWordsFn extends DoFn<String, String> {

    @ProcessElement
    public void processElement(ProcessContext c) {
        final String regex = "MESSAGE:(.*)\\n\\[MESSAGE\\].*(\\\"entityName\\\":\\\"\\w+\\\")";
        final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher m = pattern.matcher(c.element());
        List<String> entities = new ArrayList<String>();
        while (m.find()) {
            System.out.println("Full match: " + m.group(0));
            for (int i = 1; i <= m.groupCount(); i++) {
                entities.add(m.group(i));
            }
        }

        // Output each word encountered into the output PCollection.
        for (String entity : entities) {
            c.output(entity);
        }
    }
}
</code>```

答: TextIO.readAll(), available in Beam 2.2 (release is currently ongoing but you can already use it from a snapshot version or build from github), reads a PCollection of filepatterns or filenames.

Body:
Using Apache Beam Java SDK 2.1.0

We have several error logs in a bucket of Google Cloud storage, we are reading all the files in this path, with TextIO.read

We need to aggregate them in order to find errors in messages being sent. We have a regex that works, filtering different lines from each file, the problem is that with the nature of TextIO.read we get a PCollection of lines, so when try to apply the regex in the pardo, its processing it  line by line and the Regex never finds a match.

Regex: "MESSAGE:(.*)\\n\\[MESSAGE\\].*(\\\"entityName\\\":\\\"\\w+\\\")"

Is there anyway that TextIO.read returns a PCollection of files, one file per element so then when it gets the parDo we have access to complete element?

As a plan b, is there a way to combine all the lines of each file into one, with Apache Beam, so the regex pattern works?

public static class ExtractWordsFn extends DoFn<String, String> {

    @ProcessElement
    public void processElement(ProcessContext c) {
        final String regex = "MESSAGE:(.*)\\n\\[MESSAGE\\].*(\\\"entityName\\\":\\\"\\w+\\\")";
        final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher m = pattern.matcher(c.element());
        List<String> entities = new ArrayList<String>();
        while (m.find()) {
            System.out.println("Full match: " + m.group(0));
            for (int i = 1; i <= m.groupCount(); i++) {
                entities.add(m.group(i));
            }
        }

        // Output each word encountered into the output PCollection.
        for (String entity : entities) {
            c.output(entity);
        }
    }
}


问:
Gradle incremental java compilation leads to full recompile
I change only one source file and relaunch the build:

```<code>$ gradle jar
Incremental java compilation is an incubating feature.
:compileJava
Full recompilation is required because 'XXX.java' was changed.
Analysis took 0.241 secs.
</code>```

My gradle configuration has:

```<code>compileJava {
  options.fork = true
  options.incremental = true
}
</code>```

I would expect Gradle to only recompile XXX.java, is it not what it should do?

答:
You probably have a non-private constant in that java file.

Check this issue.

Body:
I change only one source file and relaunch the build:

$ gradle jar
Incremental java compilation is an incubating feature.
:compileJava
Full recompilation is required because 'XXX.java' was changed.
Analysis took 0.241 secs.

My gradle configuration has:

compileJava {
  options.fork = true
  options.incremental = true
}

I would expect Gradle to only recompile XXX.java, is it not what it should do?


问:
Please explain this base 62 PHP conversion function/algorithm
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

```<code>private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}
</code>```

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

答:
You're over-complicating:</p>

```<code>private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters); // 62
    $string = self::$_characters[$num % $base];

    while (($num = intval($num / $base)) > 0)
    {
        $string = self::$_characters[$num % $base] . $string;
    }

    return $string;
}
</code>```

Body:
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

Body:
You're over-complicating:

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters); // 62
    $string = self::$_characters[$num % $base];

    while (($num = intval($num / $base)) > 0)
    {
        $string = self::$_characters[$num % $base] . $string;
    }

    return $string;
}


问:
String encrypted in Ruby gives: 'BadPaddingException' when decrypted in Java
I'm using the following Ruby code to encrypt a string

```<code>require 'openssl'
require 'base64'

public_key = OpenSSL::PKey::RSA.new(File.read('public_key'))

Base64.encode64(public_key.public_encrypt('Some random string that I want to encrypt.'))
</code>```

I need to pass the encrypted text in a request to the API, and on the API end, I'm getting the following error(read through the API logs):

```<code>javax.crypto.BadPaddingException: Decryption error
</code>```

Now, I have gone through numerous questions over at Stackoverflow, but given my Ruby code, what I'm doing wrong that the encrypted text can't be decrypted on the API end. Obviously, the API end is using Java.

I'm a completely noob when it comes to encryption, but through encrypting and decrypting in Ruby, I have made sure that the implementation is correct in Ruby. The problem arises when the text encrypted through Ruby language gets decrypted through Java on the API end.

答:
I wrote a very simple Java program to decrypt the output from that very simple Ruby program and it worked fine. Thus, not surprisingly, there's no inherent incompatibility between the ruby openssl module and standard Java cryptography. Without any more info about the Java side, all we can do is list some of the possibilities:

Mismatched keys

The public key you are using must correspond to the private key the Java side is using. If not, you'll likely receive the BadPadding exception.

Formatting issues

Obviously what you transmit, base64 encoded strings with embedded newlines, must be correctly parsed and decoded on the Java side. Getting a single byte wrong can cause the error you see. Most base64 decoders either choke on the newlines and throw an exception or ignore them. Neither explanation would result in a BadPaddingException. Perhaps the Java side is expecting Base64URL instead of Base64? If the Java side is expecting base64url encoding and if it ignores invalid characters then this could be the problem. It's worth trying to remove whitespace including newlines from the base64 output, and if that doesn't work then try encoding with a base64url encoder (again, remove any whitespace from the output).

Body:
I'm using the following Ruby code to encrypt a string

require 'openssl'
require 'base64'

public_key = OpenSSL::PKey::RSA.new(File.read('public_key'))

Base64.encode64(public_key.public_encrypt('Some random string that I want to encrypt.'))

I need to pass the encrypted text in a request to the API, and on the API end, I'm getting the following error(read through the API logs):

javax.crypto.BadPaddingException: Decryption error

Now, I have gone through numerous questions over at Stackoverflow, but given my Ruby code, what I'm doing wrong that the encrypted text can't be decrypted on the API end. Obviously, the API end is using Java.

I'm a completely noob when it comes to encryption, but through encrypting and decrypting in Ruby, I have made sure that the implementation is correct in Ruby. The problem arises when the text encrypted through Ruby language gets decrypted through Java on the API end.


问:
How to avoid expanding variables in bash here-string, like with here-document
shell scripting features can be disabled in a here-document by escaping characters in the ending marker defined on the first line.  For example:

```<code>$ cat <<'EOF'
→ $PATH
→ EOF
$PATH
</code>```

Is there any way to do the same thing with a here-string so that one doesn't have to prepend each variable with a backslash?

$ cat <<< $PATH expands the variable before executing the bash command

答:
Just backslash the dollar sign:

```<code>cat <<< \$PATH
</code>```

or use single quotes

```<code>cat <<< '$PATH'
</code>```

Body:
shell scripting features can be disabled in a here-document by escaping characters in the ending marker defined on the first line.  For example:

$ cat <<'EOF'
→ $PATH
→ EOF
$PATH

Is there any way to do the same thing with a here-string so that one doesn't have to prepend each variable with a backslash?

$ cat <<< $PATH expands the variable before executing the bash command

Body:
Just backslash the dollar sign:

cat <<< \$PATH

or use single quotes

cat <<< '$PATH'


问:
Getting body content sent using socket php using ports
I have code below that accepts connection using sockets and displays it, then sends back a few headers, I however cannot see the body content that has been sent to the listener, I only get the headers as indicated below the code, with the Content-length clearly indicating that content has been sent, please help

```<code>    $host = "192.168.8.121";
    $port = 454;

    // don't timeout!
    set_time_limit(0);

    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
    $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
    $result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

    do {
       $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");

    // read client input
       $input = socket_read($spawn, 1024) or die("Could not read input\n");

       $inputJSON = file_get_contents('php://input');
       $body = json_decode($inputJSON, TRUE);
       print_r($input);
       print_r($body);
       print_r($inputJSON);

    // set inital headers
       $headers = [];
       $headers['Date'] = gmdate('D, d M Y H:i:s T');
       $headers['Content-Type'] = 'text/html; charset=utf-8';
       $headers['Server'] = $_SERVER['SERVER_NAME'];

       $lines = [];
       $lines[] = "HTTP/1.1 200 OK";

       // add the headers
       foreach ($headers as $key => $value) {
           $lines[] = $key . ": " . $value;
       }

       socket_write($spawn, implode("\r\n", $lines) . "\r\n\r\n" . $body) or die("Could not write output\n");
       socket_close($spawn);
    } while (true);

    // close sockets
    socket_close($socket);
</code>```

I tried a different ways to print out the content, but I have only been able to print out the headers, this is what I get when printing the $input variable

```<code>     POST /test HTTP/1.1 Accept: application/json, application/xml,
     text/json, text/x-json, text/javascript, text/xml User-Agent:
     RestSharp/105.2.3.0 Content-Type: application/json Host:
     192.168.8.102:454 Content-Length: 779 Accept-Encoding: gzip,
     deflate
</code>```

答:
TCP sends data in packets and reassembles them back into a stream. This means while you can read data byte by byte without caring for the correct order of the packets arriving at the receiver, it can still happen that one call to socket_read() only returns the content of one IP packet. The sender probably sends the headers as one packet, and then sends the content in one or more additional packets.

What one usually does is call the receive function in a loop similar to this:

```<code>$readTotal = 0;
while ($readTotal < $toRead) {
  $read = socket_read(...);
  if ($read === FALSE) {
    // error, cancel operation
  }
  $readTotal += $read;
}
</code>```

In your case, you would have to extract the amount to read from the Content-Length field, and maybe put a timeout in the loop if you can't read the number of bytes that was promised in the header.

Body:
I have code below that accepts connection using sockets and displays it, then sends back a few headers, I however cannot see the body content that has been sent to the listener, I only get the headers as indicated below the code, with the Content-length clearly indicating that content has been sent, please help

    $host = "192.168.8.121";
    $port = 454;

    // don't timeout!
    set_time_limit(0);

    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
    $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
    $result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

    do {
       $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");

    // read client input
       $input = socket_read($spawn, 1024) or die("Could not read input\n");

       $inputJSON = file_get_contents('php://input');
       $body = json_decode($inputJSON, TRUE);
       print_r($input);
       print_r($body);
       print_r($inputJSON);

    // set inital headers
       $headers = [];
       $headers['Date'] = gmdate('D, d M Y H:i:s T');
       $headers['Content-Type'] = 'text/html; charset=utf-8';
       $headers['Server'] = $_SERVER['SERVER_NAME'];

       $lines = [];
       $lines[] = "HTTP/1.1 200 OK";

       // add the headers
       foreach ($headers as $key => $value) {
           $lines[] = $key . ": " . $value;
       }

       socket_write($spawn, implode("\r\n", $lines) . "\r\n\r\n" . $body) or die("Could not write output\n");
       socket_close($spawn);
    } while (true);

    // close sockets
    socket_close($socket);

I tried a different ways to print out the content, but I have only been able to print out the headers, this is what I get when printing the $input variable

     POST /test HTTP/1.1 Accept: application/json, application/xml,
     text/json, text/x-json, text/javascript, text/xml User-Agent:
     RestSharp/105.2.3.0 Content-Type: application/json Host:
     192.168.8.102:454 Content-Length: 779 Accept-Encoding: gzip,
     deflate

Body:
TCP sends data in packets and reassembles them back into a stream. This means while you can read data byte by byte without caring for the correct order of the packets arriving at the receiver, it can still happen that one call to socket_read() only returns the content of one IP packet. The sender probably sends the headers as one packet, and then sends the content in one or more additional packets.

What one usually does is call the receive function in a loop similar to this:

$readTotal = 0;
while ($readTotal < $toRead) {
  $read = socket_read(...);
  if ($read === FALSE) {
    // error, cancel operation
  }
  $readTotal += $read;
}

In your case, you would have to extract the amount to read from the Content-Length field, and maybe put a timeout in the loop if you can't read the number of bytes that was promised in the header.


问:
Counting the (year)quarters between two dates
I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.

Here are the quarters(i used numerical representations for the months)

01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter

I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.

I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.

Thanks for your help in advance.

答:
Not sure if the following is what you are meaning but might be useful</p>

```<code>$date_start='2015/03/12';
$date_end='2017/11/14';

$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );

$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );

printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );

/*
   This will output
   ----------------

   Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
</code>```

Body:
Not sure if the following is what you are meaning but might be useful

$date_start='2015/03/12';
$date_end='2017/11/14';

$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );

$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );

printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );

/*
   This will output
   ----------------

   Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/


问:
jQuery click events stopping works
I have a problem. jQuery('#FinishTest').click() works, but it stops when you select all the answers. The error does not appear in the console.

my code

```<code>jQuery('#FinishTest').click(function() {

  var names = {};
  jQuery(':radio').each(function() {
    names[jQuery(this).attr('name')] = true;
  });
  var count = 0;
  jQuery.each(names, function() {
    count++;
  });

  if (jQuery(':radio:checked').length > 3) {
    if (jQuery(':radio:checked').length < count) {
      if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
        finishtest();
      } else {
        jQuery('#FinishTest').bind('click');
        return;
      }
    }
  } else {
    alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
  }
});
</code>```

答:
There is no error in your code. Just only condition is wrong in if statement.
I have tested on my browser(chrome) with debug.
enter image description here

I hope it will be help you.

Title: jQuery click events stopping works

Body:
I have a problem. jQuery('#FinishTest').click() works, but it stops when you select all the answers. The error does not appear in the console.

my code

jQuery('#FinishTest').click(function() {

  var names = {};
  jQuery(':radio').each(function() {
    names[jQuery(this).attr('name')] = true;
  });
  var count = 0;
  jQuery.each(names, function() {
    count++;
  });

  if (jQuery(':radio:checked').length > 3) {
    if (jQuery(':radio:checked').length < count) {
      if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
        finishtest();
      } else {
        jQuery('#FinishTest').bind('click');
        return;
      }
    }
  } else {
    alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
  }
});


问:
Eclipse RCP Development - Slowness during debug
I have been using Eclipse (Oxygen or 4.7) to build an Eclipse RCP App in MacOs Sierra.

When I stop the execution with a breakpoint, IDE is really slow. After moments, it logs following statements to error console.

Have you guys seen this? Any workaround to overcome this?

```<code>    2017-09-18 15:39:49.814 java[5621:1677726] IMKClient Stall detected, *please Report* your user scenario attaching a spindump (or sysdiagnose) that captures the problem - (imkxpc_presentFunctionRowItemTextInputViewWithEndpoint:reply:) block performed very slowly (19.02 secs).
    2017-09-18 15:39:49.817 java[5621:1677726] *** Assertion failure in -[NSRemoteView informAuxServiceOfSelf], /Library/Caches/com.apple.xbs/Sources/ViewBridge/ViewBridge-283/NSRemoteView.m:3207
    2017-09-18 15:39:49.827 java[5621:1677726] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x7ff8de18e840 *NO* NSRemoteViewController to client, NSError=Error Domain=com.apple.ViewBridge Code=8 "(null)" UserInfo={com.apple.ViewBridge.error.hint=__38-[NSRemoteView _advanceToConfigPhase:]_block_invoke.2466 caught NSInternalInconsistencyException '<NSRemoteView: 0x7ff8ddebe6f0> failed to rendezvous via aux service' with backtrace (
        0   CoreFoundation                      0x00007fff9ebc92cb __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x00007fffb39d448d objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff9ebce042 +[NSException raise:format:arguments:] + 98
        3   Foundation                          0x00007fffa0616c80 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
        4   ViewBridge                          0x00007fffb242ab34 -[NSRemoteView informAuxServiceOfSelf] + 345
        5   ViewBridge                          0x00007fffb242b47e -[NSRemoteView _finishAdvanceToConfigPhaseWithContextID:andServiceViewSize:andOffset:] + 685
</code>```

答: I had the same issue, then I have bumped up to 10.13.1 (17B48), MacOS High Sierra. Now the performance is smooth as before. I hope this solves your problem too.</p>

Body:
I have been using Eclipse (Oxygen or 4.7) to build an Eclipse RCP App in MacOs Sierra.

When I stop the execution with a breakpoint, IDE is really slow. After moments, it logs following statements to error console.

Have you guys seen this? Any workaround to overcome this?

    2017-09-18 15:39:49.814 java[5621:1677726] IMKClient Stall detected, *please Report* your user scenario attaching a spindump (or sysdiagnose) that captures the problem - (imkxpc_presentFunctionRowItemTextInputViewWithEndpoint:reply:) block performed very slowly (19.02 secs).
    2017-09-18 15:39:49.817 java[5621:1677726] *** Assertion failure in -[NSRemoteView informAuxServiceOfSelf], /Library/Caches/com.apple.xbs/Sources/ViewBridge/ViewBridge-283/NSRemoteView.m:3207
    2017-09-18 15:39:49.827 java[5621:1677726] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x7ff8de18e840 *NO* NSRemoteViewController to client, NSError=Error Domain=com.apple.ViewBridge Code=8 "(null)" UserInfo={com.apple.ViewBridge.error.hint=__38-[NSRemoteView _advanceToConfigPhase:]_block_invoke.2466 caught NSInternalInconsistencyException '<NSRemoteView: 0x7ff8ddebe6f0> failed to rendezvous via aux service' with backtrace (
        0   CoreFoundation                      0x00007fff9ebc92cb __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x00007fffb39d448d objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff9ebce042 +[NSException raise:format:arguments:] + 98
        3   Foundation                          0x00007fffa0616c80 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
        4   ViewBridge                          0x00007fffb242ab34 -[NSRemoteView informAuxServiceOfSelf] + 345
        5   ViewBridge                          0x00007fffb242b47e -[NSRemoteView _finishAdvanceToConfigPhaseWithContextID:andServiceViewSize:andOffset:] + 685


问:
SQL Divide Multiply Execution Order
```<code>select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2
</code>```

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

答:
Exactly what You need - is next query

```<code>select result1 = convert(float,3900.0) * 30097 / 30097

select convert(float,3900.0)/ 30097 * 30097enter as result2
</code>```

i.e. You have to convert one number explicitly to float. That's all

Title: SQL Divide Multiply Execution Order

Body:
select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

Body:
Exactly what You need - is next query

select result1 = convert(float,3900.0) * 30097 / 30097

select convert(float,3900.0)/ 30097 * 30097enter as result2

i.e. You have to convert one number explicitly to float. That's all


问:
Prometheus custom collector just hangs when exporting
I am trying to create a custom collector that collects a routers memory stats and export to prometheus, I am using the python prometheus-client, and have the following code:

```<code>from prometheus_client import start_http_server
from prometheus_client.core import CounterMetricFamily, REGISTRY
import requests
import json

class MemoryCollector(object):
    def collect(self):
        c = CounterMetricFamily('ODL_memory_monitoring', 'Memory for each process on box', labels=['node', 'process'])
        url = "http://<ip>:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/IDC_R-Leaf3/yang-ext:mount/Cisco-IOS-XR-procmem-oper:processes-memory/no\
des"
        headers = {
                'authorization': "<token>",
                'cache-control': "no-cache",
                'postman-token': "<token>"
        }
        response = requests.request("GET", url, headers=headers)
        reply = json.loads(response.text)
        for node in reply['nodes']['node']:
            for process in node['process-ids']['process-id']:
                if process['name'] == 'tcp':
                    c.add_metric([node['node-name'], process['name']], process['malloc-size'])
                    print("Adding metric {} {}".format(node['node-name'], process['name']))
        yield c

def main():
    start_http_server(8000)
    REGISTRY.register(MemoryCollector())

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

When I navigate to the webpage (<ip>:8000), it just hangs and doesn't get updated with the metrics.  Is there any performance issues?  Is this the correct way of creating a custom collector?

答: You've an infinite loop, try removing the while True:.

Body:
I am trying to create a custom collector that collects a routers memory stats and export to prometheus, I am using the python prometheus-client, and have the following code:

from prometheus_client import start_http_server
from prometheus_client.core import CounterMetricFamily, REGISTRY
import requests
import json

class MemoryCollector(object):
    def collect(self):
        c = CounterMetricFamily('ODL_memory_monitoring', 'Memory for each process on box', labels=['node', 'process'])
        url = "http://<ip>:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/IDC_R-Leaf3/yang-ext:mount/Cisco-IOS-XR-procmem-oper:processes-memory/no\
des"
        headers = {
                'authorization': "<token>",
                'cache-control': "no-cache",
                'postman-token': "<token>"
        }
        response = requests.request("GET", url, headers=headers)
        reply = json.loads(response.text)
        for node in reply['nodes']['node']:
            for process in node['process-ids']['process-id']:
                if process['name'] == 'tcp':
                    c.add_metric([node['node-name'], process['name']], process['malloc-size'])
                    print("Adding metric {} {}".format(node['node-name'], process['name']))
        yield c

def main():
    start_http_server(8000)
    REGISTRY.register(MemoryCollector())

if __name__ == '__main__':
    main()

When I navigate to the webpage (<ip>:8000), it just hangs and doesn't get updated with the metrics.  Is there any performance issues?  Is this the correct way of creating a custom collector?