问:
Safari - CSS transform 3d rotation glitch
I have a div inside a a container div. The inner div html consists of a single character and I am trying to make the div flip with a 180 degrees 3d rotation. The effect works fine in all browsers but Safari.
On Safari when the inner div gets rotated only half character gets rendered like it's split in a half. It's not quite a flicker, it's just like half of the character disappears behind a plane that's not really there.
As per other answers on the same topic I applyed the backface-visibilty:hidden and transform-style:preserve-3d rules to my code, but to no avail.

```<code>.inner{
    height: 80%;
    width: 80%;
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    justify-content: center;
    font-family: Arial;
    font-size: 5em;
    font-weight: bolder;
    color: #7CC7EE;
    -ms-perspective: 800px;
    -webkit-perspective: 800px;
    perspective: 800px;
    -ms-transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -ms-backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-transition: all .5s linear;
    transition: all .5s linear;
}

.flip{
    -ms-transform: rotateY(180deg);
    -webkit-transform: rotateY(180deg);
    -transform: rotateY(180deg);
}
</code>```

I add and remove the .flip class via js to trigger the transition.
Here's a slightly simplified situation of what I'm currently dealing with:
https://jsfiddle.net/sb4usrs1/5/

If you click a div you can see its transition would be rendered fine but the below div would flicker -maybe that's a clue pointing to the cause?- In my actual scenario I have several of those divs flipping at the same time so it's a little more evident and confusing than this.

答: Apparently there's a problem with the rotating div intersecting the plane of the parent div. This answer: Bug in CSS3 rotateY transition on Safari? shed some light on the issue. I solved by setting the z-index=1 to the flipping div.</p>

Body:
I have a div inside a a container div. The inner div html consists of a single character and I am trying to make the div flip with a 180 degrees 3d rotation. The effect works fine in all browsers but Safari.
On Safari when the inner div gets rotated only half character gets rendered like it's split in a half. It's not quite a flicker, it's just like half of the character disappears behind a plane that's not really there.
As per other answers on the same topic I applyed the backface-visibilty:hidden and transform-style:preserve-3d rules to my code, but to no avail.

.inner{
    height: 80%;
    width: 80%;
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    justify-content: center;
    font-family: Arial;
    font-size: 5em;
    font-weight: bolder;
    color: #7CC7EE;
    -ms-perspective: 800px;
    -webkit-perspective: 800px;
    perspective: 800px;
    -ms-transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -ms-backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-transition: all .5s linear;
    transition: all .5s linear;
}

.flip{
    -ms-transform: rotateY(180deg);
    -webkit-transform: rotateY(180deg);
    -transform: rotateY(180deg);
}

I add and remove the .flip class via js to trigger the transition.
Here's a slightly simplified situation of what I'm currently dealing with:
https://jsfiddle.net/sb4usrs1/5/

If you click a div you can see its transition would be rendered fine but the below div would flicker -maybe that's a clue pointing to the cause?- In my actual scenario I have several of those divs flipping at the same time so it's a little more evident and confusing than this.


来源: stackexchange

问:
My show segue not using NavigationController

I am having problems segueing to my detail view, using Navigation Controller.

I was using a tableview, to display some exercises, and when you clicked the exercise you would seque into the detail view, embedded in nav controller
I have removed the Tableview, and added 3 buttons, each with its' own "show" segue to the detail view. It almost works, but it is now not using my Navigation controller, meaning that the view is just presented kind of like a modal presentation.
I have tried removing the segue on one button and replace with this action:

```<code>@IBAction func strengthButton(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destination = storyboard.instantiateViewController(withIdentifier: "ExerciseViewController") as! ExerciseViewController
    destination.componentaccessid = -1;
    destination.openedFromUrl = false;
    destination.exercise = self.strengthexercise
    destination.exercisetype = .strength
    self.navigationController?.present(destination, animated: true, completion: nil)
}
</code>```

But that does exactly the same.

I have a prepare function:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier,
        let destination = segue.destination as? ExerciseViewController{
        destination.componentaccessid = -1;
        destination.openedFromUrl = false;
        switch identifier{
        case "strengthsegue":
            destination.exercise = self.strengthexercise
            destination.exercisetype = .strength
        case "rangesegue":
            destination.exercise = self.rangeexercise
            destination.exercisetype = .range
        case "combinedsegue":
            destination.exercise = self.combinedexercise
            destination.exercisetype = .combined
        default:
            print("Nothing")
        }

    }
}
</code>```

答:
Try this    </p>

```<code>self.navigationController?.pushViewController(destination, animated: true)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having problems segueing to my detail view, using Navigation Controller.

I was using a tableview, to display some exercises, and when you clicked the exercise you would seque into the detail view, embedded in nav controller
I have removed the Tableview, and added 3 buttons, each with its' own "show" segue to the detail view. It almost works, but it is now not using my Navigation controller, meaning that the view is just presented kind of like a modal presentation.
I have tried removing the segue on one button and replace with this action:

@IBAction func strengthButton(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destination = storyboard.instantiateViewController(withIdentifier: "ExerciseViewController") as! ExerciseViewController
    destination.componentaccessid = -1;
    destination.openedFromUrl = false;
    destination.exercise = self.strengthexercise
    destination.exercisetype = .strength
    self.navigationController?.present(destination, animated: true, completion: nil)
}

But that does exactly the same.

I have a prepare function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier,
        let destination = segue.destination as? ExerciseViewController{
        destination.componentaccessid = -1;
        destination.openedFromUrl = false;
        switch identifier{
        case "strengthsegue":
            destination.exercise = self.strengthexercise
            destination.exercisetype = .strength
        case "rangesegue":
            destination.exercise = self.rangeexercise
            destination.exercisetype = .range
        case "combinedsegue":
            destination.exercise = self.combinedexercise
            destination.exercisetype = .combined
        default:
            print("Nothing")
        }

    }
}

Body:
Try this

self.navigationController?.pushViewController(destination, animated: true)


问:
Calendar not showing up in Bootstrap datetimepicker
I am implementing bootstrap datetimepicker with below code:

```<code><div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                <div class="input-group date" id="datetimepicker1">
                    <input type="text" class="form-control" />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

I have included below scripts and styles:

And my output is looking like below:

Order of including files is:

```<code>@Styles.Render("~/Content/css")
@Styles.Render("~/Content/Styles/PreLayout.css")

@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/moment")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/Scripts/JavaScripts/PreLayout.js")
</code>```

When I click on calendar icon nothing happens. What mistake I am making in implementation?

EDIT:

Added fiddler: http://jsfiddle.net/1c1nr9sp/4/

答:
You might also want to check what icon-set are you using.
There are multiple font icon sets like Font Awesome, Material Design, Bootstrap glyphicons, etc.

By default DateTimePicker uses Bootstrap glyphicons but you can specify your custom icons for all other things.

```<code>icons:{
            time: 'glyphicon glyphicon-time',
            date: 'glyphicon glyphicon-calendar',
            up: 'glyphicon glyphicon-chevron-up',
            down: 'glyphicon glyphicon-chevron-down',
            previous: 'glyphicon glyphicon-chevron-left',
            next: 'glyphicon glyphicon-chevron-right',
            today: 'glyphicon glyphicon-screenshot',
            clear: 'glyphicon glyphicon-trash',
            close: 'glyphicon glyphicon-remove'
        }
</code>```

Ref- http://eonasdan.github.io/bootstrap-datetimepicker/Options/#icons

Body:
I am implementing bootstrap datetimepicker with below code:

                    <input type="text" class="form-control" />

I have included below scripts and styles:

And my output is looking like below:

Order of including files is:

@Styles.Render("~/Content/css")
@Styles.Render("~/Content/Styles/PreLayout.css")

@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/moment")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/Scripts/JavaScripts/PreLayout.js")

When I click on calendar icon nothing happens. What mistake I am making in implementation?

EDIT:

Added fiddler: http://jsfiddle.net/1c1nr9sp/4/

Body:
You might also want to check what icon-set are you using.
There are multiple font icon sets like Font Awesome, Material Design, Bootstrap glyphicons, etc.

By default DateTimePicker uses Bootstrap glyphicons but you can specify your custom icons for all other things.

icons:{
            time: 'glyphicon glyphicon-time',
            date: 'glyphicon glyphicon-calendar',
            up: 'glyphicon glyphicon-chevron-up',
            down: 'glyphicon glyphicon-chevron-down',
            previous: 'glyphicon glyphicon-chevron-left',
            next: 'glyphicon glyphicon-chevron-right',
            today: 'glyphicon glyphicon-screenshot',
            clear: 'glyphicon glyphicon-trash',
            close: 'glyphicon glyphicon-remove'
        }

Ref- http://eonasdan.github.io/bootstrap-datetimepicker/Options/#icons


Title: How to count values in pandas group

Body:
Sorry for being so stupid... I am trying to aggregate and count data in a pandas dataframe

m_supplier_name            m_eshop_order_number
1   Axxxx                  202-0147880-7096352
2   Bxxxx                  304-3926447-6272314
3   Bxxxx                  306-6312344-4699555
4   Cxxxx                  305-0612485-9987518
5   Cxxxx                  306-6591383-8935534
6   Cxxxx                  261620209654-1987667522016
7   Bxxxx                  306-3078039-1083529
8   Bxxxx                  305-6383385-7949949
9   Dxxxx                  P1824098
    …   …

This is my pandas query:

print mdata.groupby(['m_supplier_name','m_order_number']).size()

this gives me:

m_supplier_name       m_order_number
Axxxx                 028-8286652-7920300           1
                      303-2594460-9759543           1
                      303-8120802-8687554           1
Bxxxx                 302-0806465-2917902           1
Cxxxx                 252589706005-2022820755015    1
                      302-1196139-4993924           1
                      303-5646700-0910740           1
                      304-1917413-4299541           1
                      305-6425830-6893162           1
                      306-6204117-1493102           1
Dxxxx                 028-7321508-2210762           1

But I am actually looking for this per supplier.

m_supplier_name       m_order_number
Axxxx                 028-8286652-7920300           3
                      303-2594460-9759543
                      303-8120802-8687554
Bxxxx                 302-0806465-2917902           1
Cxxxx                 252589706005-2022820755015    6
                      302-1196139-4993924
                      303-5646700-0910740
                      304-1917413-4299541
                      305-6425830-6893162
                      306-6204117-1493102
Dxxxx                 028-7321508-2210762           1

The goal is to store the count of m_order_numbers in a new column per row in the orginal dataframe.

m_supplier_name         m_eshop_order_number        m_orders_per_supplier
1   Axxxx               202-0147880-7096352         1
2   Bxxxx               304-3926447-6272314         4
3   Bxxxx               306-6312344-4699555         4
4   Cxxxx               305-0612485-9987518         3
5   Cxxxx               306-6591383-8935534         3
6   Cxxxx               261620209654-1987667522016  3
7   Bxxxx               306-3078039-1083529         4
8   Bxxxx               305-6383385-7949949         4
9   Dxxxx               P1824098                    1
    …   …

Body:
You can use transform:

mdata['m_orders_per_supplier'] = mdata.groupby('m_supplier_name')['m_supplier_name']
                                      .transform('size')
print (mdata)
  m_supplier_name        m_eshop_order_number  m_orders_per_supplier
1           Axxxx         202-0147880-7096352                      1
2           Bxxxx         304-3926447-6272314                      4
3           Bxxxx         306-6312344-4699555                      4
4           Cxxxx         305-0612485-9987518                      3
5           Cxxxx         306-6591383-8935534                      3
6           Cxxxx  261620209654-1987667522016                      3
7           Bxxxx         306-3078039-1083529                      4
8           Bxxxx         305-6383385-7949949                      4
9           Dxxxx                    P1824098                      1


问:
css show hide jump issue
I want to implement "show/hide" text using css only. I tried following code in fiddle.

https://jsfiddle.net/phvt8g5w/

```<code>.show-hide-text {
  display: flex;
  flex-wrap: wrap;
}

.show-hide-text a {
  order: 2;
}

.show-hide-text p {
  position: relative;
  overflow: hidden;
  max-height: 60px; // The Height of 3 rows
}

.show-hide-text p {
  display: -webkit-box;
  -webkit-line-clamp: 3; // 3 Rows of text
  -webkit-box-orient: vertical;
}

.show-less {
  display: none;
}

.show-less:target {
  display: block;
}

.show-less:target ~ p {
  display: block;
  max-height: 100%;
}

.show-less:target + a {
  display: none;
}
</code>```

Effects are good. But I faced one problem. If I click "show more" link, it will scroll to bottom of the page. Again I go to the top of the page and click the show less link. How can I fix this problem?

答:
It scrolls to the position of .show-less and is the standard behavior when using :target.

You can avoid this by using a ghost element at the to of the page, which has the advantage of target any element on the page.

html, body {
  margin: 0;
}
.show-hide-text {
  display: flex;
  flex-wrap: wrap;
}
.show-hide-text a {
  order: 2;
}
.show-hide-text p {
  position: relative;
  overflow: hidden;
  max-height: 60px; /* The Height of 3 rows */
}
.show-less {
  display: none;
}

#show-more:target ~ .show-hide-text p {
  max-height: 100%;
}
#show-more:target ~ .show-hide-text a.show-less {
  display: block;
}
#show-more:target ~ .show-hide-text a.show-more {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="show-more" class="ghost"></div>

<div class="show-hide-text">
  Show less
  Show more
  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>
<p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>

  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>

  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
  </code>```

Title: css show hide jump issue

Body:
I want to implement "show/hide" text using css only. I tried following code in fiddle.

https://jsfiddle.net/phvt8g5w/

.show-hide-text {
  display: flex;
  flex-wrap: wrap;
}

.show-hide-text a {
  order: 2;
}

.show-hide-text p {
  position: relative;
  overflow: hidden;
  max-height: 60px; // The Height of 3 rows
}

.show-hide-text p {
  display: -webkit-box;
  -webkit-line-clamp: 3; // 3 Rows of text
  -webkit-box-orient: vertical;
}

.show-less {
  display: none;
}

.show-less:target {
  display: block;
}

.show-less:target ~ p {
  display: block;
  max-height: 100%;
}

.show-less:target + a {
  display: none;
}

Effects are good. But I faced one problem. If I click "show more" link, it will scroll to bottom of the page. Again I go to the top of the page and click the show less link. How can I fix this problem?

Body:
It scrolls to the position of .show-less and is the standard behavior when using :target.

You can avoid this by using a ghost element at the to of the page, which has the advantage of target any element on the page.

html, body {
  margin: 0;
}
.show-hide-text {
  display: flex;
  flex-wrap: wrap;
}
.show-hide-text a {
  order: 2;
}
.show-hide-text p {
  position: relative;
  overflow: hidden;
  max-height: 60px; /* The Height of 3 rows */
}
.show-less {
  display: none;
}

#show-more:target ~ .show-hide-text p {
  max-height: 100%;
}
#show-more:target ~ .show-hide-text a.show-less {
  display: block;
}
#show-more:target ~ .show-hide-text a.show-more {
  display: none;
}

<div id="show-more" class="ghost"></div>

<div class="show-hide-text">
  <a class="show-less" href="#show-less">Show less</a>
  <a class="show-more" href="#show-more">Show more</a>
  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>
<p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>

  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>

  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
  <p>
   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>


问:
Sequential Search Java
I have a problem with sequentially searching, this is the exercise:

You are testing the physical endurance of a type of brick. The test is made to find the max height the brick can fall without breaking from and N stories building. You have k bricks and two cases:

Case 1. When k = 1 the tries begin from the current floor upwards, sequentially, until the brick breaks.

Case 2. For k > 1 one brick is dropped from floor N/2. If it breaks, case 2 is applied again between floors 1 and N/2 -1. If the brick does not break, case 2 is applied again between floors N/2 + 1 and N.

I have a problem with the CASE 1 cause as I don't know how to approach it:

Initially you call dropBricks(k,1,N); Being k, and N introduced by the User(Keyboard).

```<code>public static boolean breakingFloor(int floor){
    boolean breaks;
    Random r =new Random();
    int breakingFloor= r.nextInt(floor)+1;

    if(floor>=breakingFloor){
        breaks=true;
    }else{
        breaks=false;
    }

  return breaks;
}
</code>```

dropBricks receives k(number of remaining bricks, first (first floor),last (last floor = N)) and the output would be the breakingFloor

```<code>public static int dropBricks(int k,int first,int last){
    int result=0;

    if (k==1){//CASE 1
        //I KNOW THIS CODE IS WRONG, IS JUST O NOT LEAVE IT IN EMPTY
         do{
             dropBricks(k,first,last);
             first++;
         }while(breakingFloor(first));
         System.out.println("Floor brick broke "+floor);

    }else{//CASE 2
        if(last-first<=1){
            if(last==first){
                result=first;
                System.out.println("Floor brick broke "+result);
            }else{
                if(breakingFloor(first)){
                    result=first;
                    k--;
                    System.out.println("Floor brick broke "+result);
                }else{
                    result=last;
                    k--;
                    System.out.println("Floor brick broke "+result);
                }
            }
        }else{
            int mid=((first+last)/2);
            if(breakingFloor(mid)){
                result=dropBricks(k-1,first,mid);
                System.out.println("Floor brick broke "+result);
            }else{
                result=dropBricks(k,mid,last);
                System.out.println("Floor brick broke "+result);
            }
        }
    }
    return result;
}
</code>```

答:
Your first issue is here:

```<code>int breakingFloor= r.nextInt(floor)+1;
</code>```

That simply doesn't make sense. The floor number on which a brick will break is not random.

In other words: you want to assign a random number once for that brick. And then your algorithm has to find that number! Your code changes that "breaking floor number" while your algorithm tries to find that number. This makes the whole process useless (and of course; "random"; as all kinds of things can happen).

So the first step on your side: step back, and re-think the problem, and what "solving" the problem really asks you to do.

Title: Sequential Search Java

Body:
I have a problem with sequentially searching, this is the exercise:

You are testing the physical endurance of a type of brick. The test is made to find the max height the brick can fall without breaking from and N stories building. You have k bricks and two cases:

Case 1. When k = 1 the tries begin from the current floor upwards, sequentially, until the brick breaks.

Case 2. For k > 1 one brick is dropped from floor N/2. If it breaks, case 2 is applied again between floors 1 and N/2 -1. If the brick does not break, case 2 is applied again between floors N/2 + 1 and N.

I have a problem with the CASE 1 cause as I don't know how to approach it:

Initially you call dropBricks(k,1,N); Being k, and N introduced by the User(Keyboard).

public static boolean breakingFloor(int floor){
    boolean breaks;
    Random r =new Random();
    int breakingFloor= r.nextInt(floor)+1;

    if(floor>=breakingFloor){
        breaks=true;
    }else{
        breaks=false;
    }

  return breaks;
}

dropBricks receives k(number of remaining bricks, first (first floor),last (last floor = N)) and the output would be the breakingFloor

public static int dropBricks(int k,int first,int last){
    int result=0;

    if (k==1){//CASE 1
        //I KNOW THIS CODE IS WRONG, IS JUST O NOT LEAVE IT IN EMPTY
         do{
             dropBricks(k,first,last);
             first++;
         }while(breakingFloor(first));
         System.out.println("Floor brick broke "+floor);

    }else{//CASE 2
        if(last-first<=1){
            if(last==first){
                result=first;
                System.out.println("Floor brick broke "+result);
            }else{
                if(breakingFloor(first)){
                    result=first;
                    k--;
                    System.out.println("Floor brick broke "+result);
                }else{
                    result=last;
                    k--;
                    System.out.println("Floor brick broke "+result);
                }
            }
        }else{
            int mid=((first+last)/2);
            if(breakingFloor(mid)){
                result=dropBricks(k-1,first,mid);
                System.out.println("Floor brick broke "+result);
            }else{
                result=dropBricks(k,mid,last);
                System.out.println("Floor brick broke "+result);
            }
        }
    }
    return result;
}

Body:
Your first issue is here:

int breakingFloor= r.nextInt(floor)+1;

That simply doesn't make sense. The floor number on which a brick will break is not random.

In other words: you want to assign a random number once for that brick. And then your algorithm has to find that number! Your code changes that "breaking floor number" while your algorithm tries to find that number. This makes the whole process useless (and of course; "random"; as all kinds of things can happen).

So the first step on your side: step back, and re-think the problem, and what "solving" the problem really asks you to do.


问:
AWS Lambda Performance issues
I use aws api gateway integrated with aws lambda(java), but I'm seeing some serious problems in this approach. The concept of removing the server and having your app scaled out of the box is really nice but here are the problem I'm facing. My lambda is doing 2 simple things- validate the payload received from the client and then send it to a kinesis stream for further processing from another lambda(you will ask why I don't send directly to the stream and only use 1 lambda for all of the operations. Let's just say that I want to separate the logic and have a layer of abstraction and also be able to tell the client that he's sending invalid data.).

In the implementation of the lambda I integrated the spring DI. So far so good. I started making performance testing. I simulated 50 concurrent users making 4 requests each with 5 seconds between the requests. So what happened- In the lambda's coldstart I initialize the spring's application context but it seems that having so many simultaneous requests when the lambda was not started is doing some strange things. Here's a screenshot of the times the context was initialized for.

What we can see from the screenshot is that the times for initializing the context have big difference. My assumption of what happening is that when so many requests are received and there's no "active" lambda it initializes a lambda container for every one of them and in the same time it "blocks" some of them(the ones with the big times of 18s) until the others already started are ready. So maybe it has some internal limit of the containers it can start at the same time. The problem is that if you don't have equally distributed traffic this will happen from time to time and some of the requests will timeout. We don't want this to happen.

So next thing was to do some tests without spring container as my thought was "ok, the initialization is heavy, let's just make plain old java objects initialization". And unfortunatelly the same thing happened(maybe just reduced the 3s container initialization for some of the requests). Here is a more detailed screenshot of the test data:

So I logged the whole lambda execution time(from construction to the end), the kinesis client initialization and the actual sending of the data to the stream as these are the heaviest operations in the lambda. We still have these big times of 18s or something but the interesting thing is that the times are somehow proportional. So if the whole lambda takes 18s, around 7-8s is the client initialization and 6-7 for sending the data to the stream and 4-5 seconds left for the other operations in the lambda which for the moment is only validation. On the other hand if we take one of the small times(which means that it reuses an already started lambda),i.e. 820ms, it takes 100ms for the kinesis client initialization and 340 for the data sending and 400ms for the validation. So this pushes me again to the thoughts that internally it makes some sleeps because of some limits. The next screenshot is showing what is happening on the next round of requests when the lamda is already started:

So we don't have this big times, yes we still have some relatively big delta in some of the request(which for me is also strange), but the things looks much better.

So I'm looking for a clarification from someone who knows actually what is happening under the hood, because this is not a good behavior for a serious application which is using the cloud because of it's "unlimited" possibilities.

And another question is related to another limit of the lambda-200 concurrent invocations in all lambdas within an account in a region. For me this is also a big limitation for a big application with lots of traffic. So as my business case in the moment(I don't know for the future) is more or less fire and forget the request. And I'm starting to think of changing the logic in the way that the gateway sends the data directly to the stream and the other lambda is taking care of the validation and the further processing. Yes, I'm loosing the current abstraction(which I don't need at the moment) but I'm increasing the application availability many times. What do you think?

答:
The lambda execution time spikes to 18s because AWS launches new containers w/ your code to handle the incoming requests. The bootstrap time is ~18s.

Assigning more RAM  can significantly improve the performance of your lambda function, because you have more RAM, CPU and networking throughput!

And another question is related to another limit of the lambda-200 concurrent invocations in all lambdas within an account in a region.

You can ask to the AWS Support to increase that limit. I asked to increase that limit to 10,000 invocation/second and the AWS Support did it quickly!

Title: AWS Lambda Performance issues


问:
Inno Setup - How to add cancel button to decompressing page?
I am using this code: How to add .arc decompression to Inno Setup? (answer of Martin Prikryl). I want to add a cancel button at decompressing page and active this page for others functions (when the decompression is active, this page is inactive and, for example, i can not press on/off button of my music implementation).

How to add a cancel button to decompression page? and how to active this page for others functions?

答:
All you need is this
http://fileforums.com/showthread.php?t=96619

This program have the latest compatibility with inno setup and also supports Password based file with multiple extensions.


问:
How to archive files older than 7 days with 7-ZIP by creating one archive for all files with same date
There is a CLOSE solution to my problem, and everything is described in this question:
How to archive files older than 7 days with creating one archive for all files with same date?

The thing is, i need another solution similar to this but working for 7-Zip, this has to be coded in the bat file i believe since there is no -to7d switch in 7-Zip like there is in Winrar.

The Code right now ( Credit goes to @Mofi for creating this ):

```<code>@echo off

setlocal EnableExtensions EnableDelayedExpansion
rem Define the directories to use for backup task.
set "LogDirectory=D:\tet\Web3811\Web3811\log"
set "BakDirectory=D:\tet\Web3811\Web3811\LogsBackup"

rem Get all file names in log directory into a list file sorted by last
rem modification date with oldest file at top and newest at bottom.
rem Note: /S is important to get the file names with complete path.
dir "%LogDirectory%\*" /A-D /B /OD /S /TW 1>"%BakDirectory%\LogFiles.lst" 2>nul
rem Jump to clean up stage if no file found in the log directory.
if errorlevel 1 goto :CleanUp

rem Delete list file for all files with same day if file exists
rem for example from a previous execution of this batch file
rem which was terminated manually by a user during execution.
if exist "%BakDirectory%\DayFiles.lst" del "%BakDirectory%\DayFiles.lst"

set LastDate=none
for /F "usebackq delims=" %%F in ( "%BakDirectory%\LogFiles.lst" ) do (

   set FileTime=%%~tF

   rem Get just file date from file time in format DD-MM-YYYY.
   rem The file time string format depends on date and time
   rem format definition in Windows language settings.
   rem Therefore the line below must be adapted if date format
   rem is whether DD.MM.YYYY nor DD-MM-YYYY nor DD/MM/YYYY.
   set FileDate=!FileTime:~6,4!-!FileTime:~3,2!-!FileTime:~0,2!

   rem Is the last modification date of this file different
   rem to last modification date of the previous file?
   if not "!FileDate!"=="!LastDate!" (
      rem Nothing to archive on first difference.
      if not "!LastDate!"=="none" call :ArchiveLogs
      rem Exit loop if RAR has not archived any file which means
      rem all other files are modified within the last 7 days.
      if "!LastDate!"=="ExitLoop" goto CleanUp
      rem Start creating a new list.
      set LastDate=!FileDate!
   )
   rem Append name of this file with path to current day list.
   echo %%F>>"%BakDirectory%\DayFiles.lst"
)

rem Jump to clean up stage if no list file with files to archive.
if not exist "%BakDirectory%\DayFiles.lst" goto CleanUp

rem Otherwise with no log file created or modified within
rem the last 7 days, but at least one older file exists
rem nevertheless, archive all those files in list file.
call :ArchiveLogs

:CleanUp
del "%BakDirectory%\LogFiles.lst"
endlocal
goto :EOF

:ArchiveLogs
"C:\Program Files (x86)\7-Zip\7z" -sdel a -mmt -mx3 -tzip "%BakDirectory%\!LastDate!_Logs.zip" "@%BakDirectory%\DayFiles.lst"

if errorlevel 10 set LastDate=ExitLoop
del "%BakDirectory%\DayFiles.lst"
</code>```

Basically there just needs to be added a check that check if Modified date = older than 7 days.
i'm not sure how to implement this, since once you run the :ArchiveLogs 7-Zip will just take EVERYTHING in that folder and as far as i can see there are no switches to check for that.

I believe we have to do something like this:

Code to check if file has a modification date older than 7 days & save that file name in a value.

:ZipOnlyafter7days

      For:

      "C:\Program Files (x86)\7-Zip\7z" -sdel a -mmt -mx3 -tzip "%BakDirectory%!LastDate!_Logs.zip" "@%BakDirectory%\ Filename_Value "

答:
The below works for files with a number of days old from a batch file

```<code>forfiles /P (SOURCE_folder) /S /M *.* /D -(number of date old) /C "cmd /C 7Z.exe a "Archive.ZIP @file"
</code>```

I am just working to try and get the date correct.

Body:
There is a CLOSE solution to my problem, and everything is described in this question:
How to archive files older than 7 days with creating one archive for all files with same date?

The thing is, i need another solution similar to this but working for 7-Zip, this has to be coded in the bat file i believe since there is no -to7d switch in 7-Zip like there is in Winrar.

The Code right now ( Credit goes to @Mofi for creating this ):

@echo off

setlocal EnableExtensions EnableDelayedExpansion
rem Define the directories to use for backup task.
set "LogDirectory=D:\tet\Web3811\Web3811\log"
set "BakDirectory=D:\tet\Web3811\Web3811\LogsBackup"

rem Get all file names in log directory into a list file sorted by last
rem modification date with oldest file at top and newest at bottom.
rem Note: /S is important to get the file names with complete path.
dir "%LogDirectory%\*" /A-D /B /OD /S /TW 1>"%BakDirectory%\LogFiles.lst" 2>nul
rem Jump to clean up stage if no file found in the log directory.
if errorlevel 1 goto :CleanUp

rem Delete list file for all files with same day if file exists
rem for example from a previous execution of this batch file
rem which was terminated manually by a user during execution.
if exist "%BakDirectory%\DayFiles.lst" del "%BakDirectory%\DayFiles.lst"

set LastDate=none
for /F "usebackq delims=" %%F in ( "%BakDirectory%\LogFiles.lst" ) do (

   set FileTime=%%~tF

   rem Get just file date from file time in format DD-MM-YYYY.
   rem The file time string format depends on date and time
   rem format definition in Windows language settings.
   rem Therefore the line below must be adapted if date format
   rem is whether DD.MM.YYYY nor DD-MM-YYYY nor DD/MM/YYYY.
   set FileDate=!FileTime:~6,4!-!FileTime:~3,2!-!FileTime:~0,2!

   rem Is the last modification date of this file different
   rem to last modification date of the previous file?
   if not "!FileDate!"=="!LastDate!" (
      rem Nothing to archive on first difference.
      if not "!LastDate!"=="none" call :ArchiveLogs
      rem Exit loop if RAR has not archived any file which means
      rem all other files are modified within the last 7 days.
      if "!LastDate!"=="ExitLoop" goto CleanUp
      rem Start creating a new list.
      set LastDate=!FileDate!
   )
   rem Append name of this file with path to current day list.
   echo %%F>>"%BakDirectory%\DayFiles.lst"
)

rem Jump to clean up stage if no list file with files to archive.
if not exist "%BakDirectory%\DayFiles.lst" goto CleanUp

rem Otherwise with no log file created or modified within
rem the last 7 days, but at least one older file exists
rem nevertheless, archive all those files in list file.
call :ArchiveLogs

:CleanUp
del "%BakDirectory%\LogFiles.lst"
endlocal
goto :EOF

:ArchiveLogs
"C:\Program Files (x86)\7-Zip\7z" -sdel a -mmt -mx3 -tzip "%BakDirectory%\!LastDate!_Logs.zip" "@%BakDirectory%\DayFiles.lst"

if errorlevel 10 set LastDate=ExitLoop
del "%BakDirectory%\DayFiles.lst"

Basically there just needs to be added a check that check if Modified date = older than 7 days.
i'm not sure how to implement this, since once you run the :ArchiveLogs 7-Zip will just take EVERYTHING in that folder and as far as i can see there are no switches to check for that.

I believe we have to do something like this:

Code to check if file has a modification date older than 7 days & save that file name in a value.

:ZipOnlyafter7days

      For:

      "C:\Program Files (x86)\7-Zip\7z" -sdel a -mmt -mx3 -tzip "%BakDirectory%!LastDate!_Logs.zip" "@%BakDirectory%\ Filename_Value "

Body:
The below works for files with a number of days old from a batch file

forfiles /P (SOURCE_folder) /S /M *.* /D -(number of date old) /C "cmd /C 7Z.exe a "Archive.ZIP @file"

I am just working to try and get the date correct.


问:
What's the best way to manage dates across PHP, MySQL, etc?
My server is in Dallas.  I'm in New York City.. and both PHP and MySQL have configuration variables for setting the timezone.

How do I get them all to work together?  What dates should I store in MySQL?  How do I get PHP to handle changing the date based on the user's preference?

Bear in mind:  I don't think I'm ever having PHP explicitly set the date, it's always using "NOW()" in queries.. however I foresee the need to do this.  How would this be done?

I'm hoping SO's experience can help me out here.

答:
The mysql-server stores dates in a timezone independent format (UTC).

But before it stores the date it will be converted using its timezone.

U can change the mysql timezone per connection *1:

```<code>mysql_query('SET time_zone = "'.$timezone.'"');
</code>```

You can also change the timezone per script.

```<code>date_default_timezone_set($timezone);
</code>```

If you set them to the same timezone "2009-01-10 13:30:00" will mean the same thing to both mysql and php.

But keep in mind that the 2 servers have different internal clock values, so if you want to generate timestamps based on current time. Do that in mysql OR php.

*1)
MySQL timezone support may require additional configuration. check the manual

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

Body:
The mysql-server stores dates in a timezone independent format (UTC).

But before it stores the date it will be converted using its timezone.

U can change the mysql timezone per connection *1:

mysql_query('SET time_zone = "'.$timezone.'"');

You can also change the timezone per script.

date_default_timezone_set($timezone);

If you set them to the same timezone "2009-01-10 13:30:00" will mean the same thing to both mysql and php.

But keep in mind that the 2 servers have different internal clock values, so if you want to generate timestamps based on current time. Do that in mysql OR php.

*1)
MySQL timezone support may require additional configuration. check the manual

OwnerDisplayName: NebyGemini

LastEditorDisplayName: NebyGemini


问:
need help writing a function candidates in Haskell
Hi take a look at  this thread already processing this subject
And also this thread might be of intrest.

Im trying to write a function

```<code>candidates :: Sudoku -> Pos -> [Int]
</code>```

that given a Sudoku

```<code>data Sudoku = Sudoku { rows :: [[Maybe Int]] }
 deriving ( Show, Eq )
</code>```

and a position (type Pos = (Int, Int))
determines what numbers that you can write there, for example in a sudoku row that already contains (1,2,4,7,9,x,x) you cant write any of the already existing numbers in the last row. Also the other problem is to check the hight as well as the width so no numbers occur more than once (ordinary sudoku rules). So any suggestions on how to start?

Example:
  Sudoku> candidates example (0,2)
[4,8]

答:
Here is a solution using Data.Set. You can use S.elems to get the list, but if you are making a sudoku solver, you might be looking for S.size.

```<code>import qualified Data.Set as S
import Data.Maybe(catMaybes)

fullSet = S.fromAscList [1..9]

fromJustL = S.fromList . concatMaybes

candidates s x =
  rowSet s x `S.intersection` colSet s x `S.intersection` cellSet s x

rowSet s (i,_) = fullSet `S.difference` fromJustL (s !! i)
colSet s (_,i) = fullSet `S.difference` fromJustL (map (!!i) s)
cellSet s (i,j) = fullSet `S.difference` fromJustL (concatMap (g j) (g i s))
  where
  g i | i < 3     = take 3
      | i < 6     = take 3 . drop 3
      | otherwise = take 3 . drop 6
</code>```

Body:
Hi take a look at  this thread already processing this subject
And also this thread might be of intrest.

Im trying to write a function

candidates :: Sudoku -> Pos -> [Int]

that given a Sudoku

data Sudoku = Sudoku { rows :: [[Maybe Int]] }
 deriving ( Show, Eq )

and a position (type Pos = (Int, Int))
determines what numbers that you can write there, for example in a sudoku row that already contains (1,2,4,7,9,x,x) you cant write any of the already existing numbers in the last row. Also the other problem is to check the hight as well as the width so no numbers occur more than once (ordinary sudoku rules). So any suggestions on how to start?

Example:
  Sudoku> candidates example (0,2)
[4,8]

Body:
Here is a solution using Data.Set. You can use S.elems to get the list, but if you are making a sudoku solver, you might be looking for S.size.

import qualified Data.Set as S
import Data.Maybe(catMaybes)

fullSet = S.fromAscList [1..9]

fromJustL = S.fromList . concatMaybes

candidates s x =
  rowSet s x `S.intersection` colSet s x `S.intersection` cellSet s x

rowSet s (i,_) = fullSet `S.difference` fromJustL (s !! i)
colSet s (_,i) = fullSet `S.difference` fromJustL (map (!!i) s)
cellSet s (i,j) = fullSet `S.difference` fromJustL (concatMap (g j) (g i s))
  where
  g i | i < 3     = take 3
      | i < 6     = take 3 . drop 3
      | otherwise = take 3 . drop 6


问:
Downloading of zip file through ASP.NET MVC using DotNetZip
I have created a text file in a folder and zipped that folder and saved @same location for test purpose. I wanted to download that zip file directly on user machine after it is created. I am using dotnetzip library and have done following:

```<code>Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + "sample.zip");
using (ZipFile zip = new ZipFile())
{
    zip.AddDirectory(Server.MapPath("~/Directories/hello"));
    zip.Save(Server.MapPath("~/Directories/hello/sample.zip"));
}
</code>```

Can someone please suggest how the zip file can be downloaded at user's end.?

答:
just a fix to Klaus solution: (as I can not add comment I have to add another answer!)

The solution is great but for me it gave corrupted zip file and I realized that it is because of return is before finalizing zip object so it did not close zip and result in a corrupted zip.

so to fix we need to just move return line after using zip block so it works.
the final result is :

```<code>/// <summary>
///     Zip a file stream
/// </summary>
/// <param name="originalFileStream"> MemoryStream with original file </param>
/// <param name="fileName"> Name of the file in the ZIP container </param>
/// <returns> Return byte array of zipped file </returns>
private byte[] GetZippedFiles(MemoryStream originalFileStream, string fileName)
{
    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            var zipEntry = zip.CreateEntry(fileName);
            using (var writer = new StreamWriter(zipEntry.Open()))
            {
                originalFileStream.WriteTo(writer.BaseStream);
            }
        }
        return zipStream.ToArray();
    }
}

/// <summary>
///     Download zipped file
/// </summary>
[HttpGet]
public FileContentResult Download()
{
    var zippedFile = GetZippedFiles(/* your stream of original file */, "hello");
    return File(zippedFile, // We could use just Stream, but the compiler gets a warning: "ObjectDisposedException: Cannot access a closed Stream" then.
                "application/zip",
                "sample.zip");
}
</code>```

Body:
I have created a text file in a folder and zipped that folder and saved @same location for test purpose. I wanted to download that zip file directly on user machine after it is created. I am using dotnetzip library and have done following:

Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + "sample.zip");
using (ZipFile zip = new ZipFile())
{
    zip.AddDirectory(Server.MapPath("~/Directories/hello"));
    zip.Save(Server.MapPath("~/Directories/hello/sample.zip"));
}

Can someone please suggest how the zip file can be downloaded at user's end.?

Body:
just a fix to Klaus solution: (as I can not add comment I have to add another answer!)

The solution is great but for me it gave corrupted zip file and I realized that it is because of return is before finalizing zip object so it did not close zip and result in a corrupted zip.

so to fix we need to just move return line after using zip block so it works.
the final result is :

/// <summary>
///     Zip a file stream
/// </summary>
/// <param name="originalFileStream"> MemoryStream with original file </param>
/// <param name="fileName"> Name of the file in the ZIP container </param>
/// <returns> Return byte array of zipped file </returns>
private byte[] GetZippedFiles(MemoryStream originalFileStream, string fileName)
{
    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            var zipEntry = zip.CreateEntry(fileName);
            using (var writer = new StreamWriter(zipEntry.Open()))
            {
                originalFileStream.WriteTo(writer.BaseStream);
            }
        }
        return zipStream.ToArray();
    }
}

/// <summary>
///     Download zipped file
/// </summary>
[HttpGet]
public FileContentResult Download()
{
    var zippedFile = GetZippedFiles(/* your stream of original file */, "hello");
    return File(zippedFile, // We could use just Stream, but the compiler gets a warning: "ObjectDisposedException: Cannot access a closed Stream" then.
                "application/zip",
                "sample.zip");
}


问:
Improve Tesseract OCR results with blurred text
I am working on OCR recognition of printed text. In particular I am focusing on the preprocessing step to improve the results of the Tesseract engine.
I have already obtained good results with adaptive thresholding, noise removal, text deskew, etc... But still Tesseract seems to fail when other commercial product return decent results.

I used the following test image and here are the results obtained with Tesseract 3.04 compared to two commercial OCR apis. All the 3 services were provided with the same binary image that contains some slightly blurred text.

Tesseract

```<code>Careers in Technology Consulting

Networking Lunch
21 m 2014, 11:00 - 14:30

Definingthecorporatellstmtegy, Wammmwdngdeal, creating
uniquebwinessisighnwilgbigdam-doesﬂismﬂxemmyouaﬁoy?

Findoutmoreabanhowitfeektomkasatedlﬂogymbyjoiningour

for further mm please visit mAeloittexom/weers
</code>```

ABBYY Fine Reader Online

```<code>Careers in Technology Consulting
Networking Lunch
21 November 2014,1140-14:30
Defining the corporate IT strategy, planning a multHnKon <Mar outsourcing deal, creating unique business insights using big data-doesthis sound Ifce something you enjoy?
Find out more about hour it feels to work as a technology consultant by joining our exclusive networking lunch,
For further information please visit wrwMuleloittexom/carcert
</code>```

Online OCR

```<code>Careers in Technology Consulting Networking Lunch 21 November 2014, 11;00 —14:30
Defining the corporate IT strategy, planning a muiti-indlimi dollar outsourcing deal, creating unique business insights using big data—does this sound like something you enjoy?
Find out more about how it feels to work as a tedmology consultant by joining our exclusive networking lunch,
For further information' please visit wwwdeloitte,com/careers
</code>```

Now I wonder whether the big gap between Tesseract and the other two products is due to a different engine (for sure ABBYY uses its own engine, not sure about OCR Web Service) or there are some other preprocessing steps that can be done before running Tesseract. Do you have any suggestions?

答:
Here a suggestion for "magic" OCR preprocessing.
In order to explain the principle of the proposed preprocessing idea, let's consider an excerpt from the provided text image on which all of the tested OCRs failed :

and apply to it some "preprocessing-wisdom". First the usual thresholding:

and then some "magic" by shooting vertical lines through word-elements, detecting max. 2 pixel high "bars" and cutting them at their edges along with cutting the word-element down to its bottom line:

Now switching from shooting lines through the word-elements in this image from vertical to horizontal ones in order to detect very wide "bars" and cut them vertical in the middle of their width:

This should help any OCR-engine to provide better results on this particular image. I can imagine that some of the commercial OCR-engines use this approach already being able to provide a better recognition than this ones tested.

In this context let me mention another free OCR-engines available in the Ubuntu repositories (comparable with tesseract). Testing them against each other you can wonder even more how it comes that they provide different results and then look into their source code to know :) and infer from this experience something about the commercial ones.

```<code>sudo apt-get install cuneiform gocr ocrad
</code>```

Body:
I am working on OCR recognition of printed text. In particular I am focusing on the preprocessing step to improve the results of the Tesseract engine.
I have already obtained good results with adaptive thresholding, noise removal, text deskew, etc... But still Tesseract seems to fail when other commercial product return decent results.

I used the following test image and here are the results obtained with Tesseract 3.04 compared to two commercial OCR apis. All the 3 services were provided with the same binary image that contains some slightly blurred text.

Tesseract

Careers in Technology Consulting

Networking Lunch
21 m 2014, 11:00 - 14:30

Definingthecorporatellstmtegy, Wammmwdngdeal, creating
uniquebwinessisighnwilgbigdam-doesﬂismﬂxemmyouaﬁoy?

Findoutmoreabanhowitfeektomkasatedlﬂogymbyjoiningour

for further mm please visit mAeloittexom/weers

ABBYY Fine Reader Online

Careers in Technology Consulting
Networking Lunch
21 November 2014,1140-14:30
Defining the corporate IT strategy, planning a multHnKon <Mar outsourcing deal, creating unique business insights using big data-doesthis sound Ifce something you enjoy?
Find out more about hour it feels to work as a technology consultant by joining our exclusive networking lunch,
For further information please visit wrwMuleloittexom/carcert

Online OCR

Careers in Technology Consulting Networking Lunch 21 November 2014, 11;00 —14:30
Defining the corporate IT strategy, planning a muiti-indlimi dollar outsourcing deal, creating unique business insights using big data—does this sound like something you enjoy?
Find out more about how it feels to work as a tedmology consultant by joining our exclusive networking lunch,
For further information' please visit wwwdeloitte,com/careers

Now I wonder whether the big gap between Tesseract and the other two products is due to a different engine (for sure ABBYY uses its own engine, not sure about OCR Web Service) or there are some other preprocessing steps that can be done before running Tesseract. Do you have any suggestions?

Body:
Here a suggestion for "magic" OCR preprocessing.
In order to explain the principle of the proposed preprocessing idea, let's consider an excerpt from the provided text image on which all of the tested OCRs failed :

and apply to it some "preprocessing-wisdom". First the usual thresholding:

and then some "magic" by shooting vertical lines through word-elements, detecting max. 2 pixel high "bars" and cutting them at their edges along with cutting the word-element down to its bottom line:

Now switching from shooting lines through the word-elements in this image from vertical to horizontal ones in order to detect very wide "bars" and cut them vertical in the middle of their width:

This should help any OCR-engine to provide better results on this particular image. I can imagine that some of the commercial OCR-engines use this approach already being able to provide a better recognition than this ones tested.

In this context let me mention another free OCR-engines available in the Ubuntu repositories (comparable with tesseract). Testing them against each other you can wonder even more how it comes that they provide different results and then look into their source code to know :) and infer from this experience something about the commercial ones.

sudo apt-get install cuneiform gocr ocrad


问:
How to use NgFor in Angular 2 to indicate an active item on another html object?
I am using NgFor to iterate through a collection:

```<code>this.articles = [
    {
        id: 1,
        title: “Tile 1“,
        summary: “First Article“
    },
    {
        id: 2,
        title: “title 2“,
        summary: “Summary 2“
    },
    {
        id: 3,
        title: "Title 3”,
        summary: “Summary 3“
    },
    {
        id: 4,
        title: “Title 4“,
        summary: “Summary 4”
    }
];

<p class="controls">
    «
    <a (click)="showPrevArticle()">Previous article</a>
    —
    <a (click)="showNextArticle()">Next article</a>
    »
</p>
<div class="container">
    <template ngFor let-article [ngForOf]="[ selectedArticle ]" let-i="index">
        <ol class="article-indicators text"  [hidden]="articles.length <= 1">
              <li  *ngFor="let article of articles ; let i = index" [class.active]="selectedBundle === true" (click)="select(article)"><strong>id: </strong>{{i}} </li>
        </ol>

        <div [@articleAnimation]="orientation" class="article">
            <div class="name">
                {{ article.title }}
            </div>
            <div class="avatar">id is: <strong>{{i}}</strong></div>
            <div class="meta">
               {{ article.summary }}
            </div>
        </div>
    </template>
</div>
</code>```

I want a list of items to highlight which article is currently being on display in the "article" div above.

```<code><ol class="article-indicators text"  [hidden]="articles.length <= 1">
                  <li  *ngFor="let article of articles ; let i = index" [class.active]="selectedBundle === true" (click)="select(article)"><strong>id: </strong>{{i}} </li>
            </ol>
</code>```

Because the data is not fed through a router, how can I use an equivalent to [routerLinkActive]="['active']" to show which article has been pushed to the front?

///Edited

Component code:

This will probably explain better:

At the beginning I set up the animation orientation:

```<code>type Orientation = ( "prev" | "next" | "none" );
</code>```

My Component code:

```<code>@Component({
  selector: 'app-article-01',
  animations: [
        trigger(
            "articleAnimation",
            [
                transition(
                    "void => prev", // ---> Entering --->
                    [
                        // Maintain a zIndex of 2 throughout the ENTIRE animation
                        style({
                            left: -100,
                            opacity: 0.0,
                            zIndex: 2
                        }),
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 0,
                                opacity: 1.0,
                                zIndex: 2
                            })
                        )
                    ]
                ),
                transition(
                    "prev => void", // ---> Leaving --->
                    [
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 100,
                                opacity: 0.0
                            })
                        )
                    ]
                ),
                transition(
                    "void => next", // <--- Entering <---
                    [
                        // Maintain a zIndex of 2 throughout the ENTIRE
                        // animation (but not after the animation)
                        style({
                            left: 100,
                            opacity: 0.0,
                            zIndex: 2
                        }),
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 0,
                                opacity: 1.0,
                                zIndex: 2
                            })
                        )
                    ]
                ),
                transition(
                    "next => void", // <--- Leaving <---
                    [
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: -100,
                                opacity: 0.0
                            })
                        )
                    ]
                )
            ]
        )
    ],
  templateUrl: './article-01.component.html',
  styleUrls: ['./article-01.component.scss']
})
</code>```

Export my class and create my article collection:

```<code>export class article01Component implements OnInit {
 //indicator states
  selectedArticleId:number;

  isSelected(article): boolean {
       return article.id === this.selectedArticleId;
   }

  public orientation: Orientation;
  public selectedArticle: article;

  private changeDetectorRef: ChangeDetectorRef;
  private articles: article[];

  constructor(changeDetectorRef: ChangeDetectorRef) {

    this.changeDetectorRef = changeDetectorRef;
    this.orientation = "none";

     // Setup the articles collection.
        this.articles = [
            {
                id: 1,
                title: "Article 1 Heading",
                summary: "Summary for article 1"
            },
            {
                id: 2,
                title: "Article 2 Heading",
                summary: "Summary for article 2"            },
            {
                id: 3,
                title: "Article 3 Heading",
                summary: "Summary for article 3"            },
            {
                id: 4,
                title: "Artcile 4 Heading",
                summary: "Summary for article 4"
            }
        ];

          // Randomly(ish) select the initial article to display.
        this.selectedArticle = this.articles[ Math.floor( Math.random() * this.articles.length ) ];

  }
</code>```

Previous button code with implemented method for indicator:

I cycle to the next article in the collection.

```<code>public showNextArticle() : void {

    // Change the "state" of the animation trigger.
    this.orientation = "next";

    // Force the Template to apply the new animation state before we actually
    // change the rendered element view-model. If we don't force a change-detection,
    // the new [@orientation] state won't be applied prior to the "leave" transition;
    // which means that we won't be leaving from the "expected" state.
    this.changeDetectorRef.detectChanges();

    // Find the currently selected index.
    var index = this.articles.indexOf( this.selectedArticle );
    //THIS IS WRONG:highlight indicator, this is not picking up the correct id
    this.selectedArticleId = index;

    //this.indicatorState(newState)

    // Move the rendered element to the next index - this will cause the current item
    // to enter the ( "next" => "void" ) transition and this new item to enter the
    // ( "void" => "next" ) transition.
    this.selectedArticle = this.articles[ index + 1 ]
        ? this.articles[ index + 1 ]
        : this.articles[ 0 ]
    ;

}
</code>```

My indicators

```<code>    <ol class="article-indicators text"  [hidden]="articles.length <= 1">
          <li  *ngFor="let article of articles ; let i = index" [class.active]="isSelected(article)"  (click)="select(article)"><strong>id: </strong>{{i}} </li>
    </ol>
</code>```

There seems to be a problem with how the active class is applied as it is doing it on a random basis rather than picking up the current selectedArticle index:

// Find the currently selected index.

```<code>    var index = this.articles.indexOf( this.selectedArticle );

    this.selectedArticleId = index;

Select the bundle via the indicator (not working):

  public select(selectedArticle){

       selectedArticle.id = this.article.id //property of article does not exist on type 'ArticleComponent'
   }
</code>```

答:
UPDATE (after HGB added the component code)

You already have a selectedArticle property, so forget what I said about adding the extra selectedArticleId. You should be able to simply change the [class.active] code to this:

```<code><li  *ngFor="let article of articles ; let i = index" [class.active]="article.id === selectedArticle?.Id" (click)="select(article)"><strong>id: </strong>{{i}} </li>
</code>```

Body:
I am using NgFor to iterate through a collection:

this.articles = [
    {
        id: 1,
        title: “Tile 1“,
        summary: “First Article“
    },
    {
        id: 2,
        title: “title 2“,
        summary: “Summary 2“
    },
    {
        id: 3,
        title: "Title 3”,
        summary: “Summary 3“
    },
    {
        id: 4,
        title: “Title 4“,
        summary: “Summary 4”
    }
];

    «
    Previous article
    —
    Next article
    »

    <template ngFor let-article [ngForOf]="[ selectedArticle ]" let-i="index">
        <ol class="article-indicators text"  [hidden]="articles.length <= 1">

id: {{i}}

                {{ article.title }}

id is: {{i}}

               {{ article.summary }}

    </template>

I want a list of items to highlight which article is currently being on display in the "article" div above.

<ol class="article-indicators text"  [hidden]="articles.length <= 1">

id: {{i}}

Because the data is not fed through a router, how can I use an equivalent to [routerLinkActive]="['active']" to show which article has been pushed to the front?

///Edited

Component code:

This will probably explain better:

At the beginning I set up the animation orientation:

type Orientation = ( "prev" | "next" | "none" );

My Component code:

@Component({
  selector: 'app-article-01',
  animations: [
        trigger(
            "articleAnimation",
            [
                transition(
                    "void => prev", // ---> Entering --->
                    [
                        // Maintain a zIndex of 2 throughout the ENTIRE animation
                        style({
                            left: -100,
                            opacity: 0.0,
                            zIndex: 2
                        }),
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 0,
                                opacity: 1.0,
                                zIndex: 2
                            })
                        )
                    ]
                ),
                transition(
                    "prev => void", // ---> Leaving --->
                    [
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 100,
                                opacity: 0.0
                            })
                        )
                    ]
                ),
                transition(
                    "void => next", // <--- Entering <---
                    [
                        // Maintain a zIndex of 2 throughout the ENTIRE
                        // animation (but not after the animation)
                        style({
                            left: 100,
                            opacity: 0.0,
                            zIndex: 2
                        }),
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: 0,
                                opacity: 1.0,
                                zIndex: 2
                            })
                        )
                    ]
                ),
                transition(
                    "next => void", // <--- Leaving <---
                    [
                        animate(
                            "200ms ease-in-out",
                            style({
                                left: -100,
                                opacity: 0.0
                            })
                        )
                    ]
                )
            ]
        )
    ],
  templateUrl: './article-01.component.html',
  styleUrls: ['./article-01.component.scss']
})

Export my class and create my article collection:

export class article01Component implements OnInit {
 //indicator states
  selectedArticleId:number;

  isSelected(article): boolean {
       return article.id === this.selectedArticleId;
   }

  public orientation: Orientation;
  public selectedArticle: article;

  private changeDetectorRef: ChangeDetectorRef;
  private articles: article[];

  constructor(changeDetectorRef: ChangeDetectorRef) {

    this.changeDetectorRef = changeDetectorRef;
    this.orientation = "none";

     // Setup the articles collection.
        this.articles = [
            {
                id: 1,
                title: "Article 1 Heading",
                summary: "Summary for article 1"
            },
            {
                id: 2,
                title: "Article 2 Heading",
                summary: "Summary for article 2"            },
            {
                id: 3,
                title: "Article 3 Heading",
                summary: "Summary for article 3"            },
            {
                id: 4,
                title: "Artcile 4 Heading",
                summary: "Summary for article 4"
            }
        ];

          // Randomly(ish) select the initial article to display.
        this.selectedArticle = this.articles[ Math.floor( Math.random() * this.articles.length ) ];

  }

Previous button code with implemented method for indicator:

I cycle to the next article in the collection.

public showNextArticle() : void {

    // Change the "state" of the animation trigger.
    this.orientation = "next";

    // Force the Template to apply the new animation state before we actually
    // change the rendered element view-model. If we don't force a change-detection,
    // the new [@orientation] state won't be applied prior to the "leave" transition;
    // which means that we won't be leaving from the "expected" state.
    this.changeDetectorRef.detectChanges();

    // Find the currently selected index.
    var index = this.articles.indexOf( this.selectedArticle );
    //THIS IS WRONG:highlight indicator, this is not picking up the correct id
    this.selectedArticleId = index;

    //this.indicatorState(newState)

    // Move the rendered element to the next index - this will cause the current item
    // to enter the ( "next" => "void" ) transition and this new item to enter the
    // ( "void" => "next" ) transition.
    this.selectedArticle = this.articles[ index + 1 ]
        ? this.articles[ index + 1 ]
        : this.articles[ 0 ]
    ;

}

My indicators

    <ol class="article-indicators text"  [hidden]="articles.length <= 1">

id: {{i}}

There seems to be a problem with how the active class is applied as it is doing it on a random basis rather than picking up the current selectedArticle index:

// Find the currently selected index.

    var index = this.articles.indexOf( this.selectedArticle );

    this.selectedArticleId = index;

Select the bundle via the indicator (not working):

  public select(selectedArticle){

       selectedArticle.id = this.article.id //property of article does not exist on type 'ArticleComponent'
   }

Body:
UPDATE (after HGB added the component code)

You already have a selectedArticle property, so forget what I said about adding the extra selectedArticleId. You should be able to simply change the [class.active] code to this:

<li  *ngFor="let article of articles ; let i = index" [class.active]="article.id === selectedArticle?.Id" (click)="select(article)"><strong>id: </strong>{{i}} </li>


问:
F# remove duplicates from a string [] list
I have a program that results in an [] list, and I'm trying to remove near duplicated arrays from the list. An example of the list is...

```<code>[
   [|
      "Jackson";
      "Stentzke";
      "22";
      "001"
    |];
    [|
      "Jackson";
      "Stentzke";
      "22";
      "002"
    |];
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]
</code>```

Basically I'm trying to write a function that would read over the list and remove all examples of near identical data. So the final returned [] list should look like...

```<code>[
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]
</code>```

I've tried a number of functions to try and get this result or something close to it that can work with. My current attempt is this...

```<code>let removeDuplicates (arrayList: string[]list) =
    let list = arrayList|> List.map(fun aL ->
        let a = arrayList|> List.map(fun aL2 ->
                try
                    match (aL.GetValue(0).Equals(aL2.GetValue(0))) && (aL.GetValue(2).Equals(aL2.GetValue(2))) && (aL.GetValue(3).Equals(aL2.GetValue(3))) with
                    | false -> aL2
                    | _ -> [|""|]
                with
                | ex -> [|""|]
            )
        a
                                              )
    list |> List.concat |> List.distinct
</code>```

But all this returns is the a reversed version on the input []list.

Does anyone know how to remove near duplicated arrays from a list?

答:
I believe your code and comments don't match up very well. Considering your comments "the first, second and third values are the same", I believe this can get you in the right track:

```<code>let removeDuplicates (arrayList: string[]list) =
    arrayList |> Seq.distinctBy (fun elem ->  (elem.[0] , elem.[1] , elem.[2]))
</code>```

The result of this against your input data is a two element list containing:

```<code>[
 [|
  "Jackson";
  "Stentzke";
  "22";
  "001"
 |];
 [|
  "Alec";
  "Stentzke";
  "18";
  "003"
 |]
]
</code>```

Body:
I have a program that results in an [] list, and I'm trying to remove near duplicated arrays from the list. An example of the list is...

[
   [|
      "Jackson";
      "Stentzke";
      "22";
      "001"
    |];
    [|
      "Jackson";
      "Stentzke";
      "22";
      "002"
    |];
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]

Basically I'm trying to write a function that would read over the list and remove all examples of near identical data. So the final returned [] list should look like...

[
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]

I've tried a number of functions to try and get this result or something close to it that can work with. My current attempt is this...

let removeDuplicates (arrayList: string[]list) =
    let list = arrayList|> List.map(fun aL ->
        let a = arrayList|> List.map(fun aL2 ->
                try
                    match (aL.GetValue(0).Equals(aL2.GetValue(0))) && (aL.GetValue(2).Equals(aL2.GetValue(2))) && (aL.GetValue(3).Equals(aL2.GetValue(3))) with
                    | false -> aL2
                    | _ -> [|""|]
                with
                | ex -> [|""|]
            )
        a
                                              )
    list |> List.concat |> List.distinct

But all this returns is the a reversed version on the input []list.

Does anyone know how to remove near duplicated arrays from a list?

Body:
I believe your code and comments don't match up very well. Considering your comments "the first, second and third values are the same", I believe this can get you in the right track:

let removeDuplicates (arrayList: string[]list) =
    arrayList |> Seq.distinctBy (fun elem ->  (elem.[0] , elem.[1] , elem.[2]))

The result of this against your input data is a two element list containing:

[
 [|
  "Jackson";
  "Stentzke";
  "22";
  "001"
 |];
 [|
  "Alec";
  "Stentzke";
  "18";
  "003"
 |]
]


问:
Ruby post title to slug
How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).

So basically:

downcase all letters

convert spaces to hyphens

delete extraneous characters

答: I like FriendlyId, the self-professed "Swiss Army Bulldozer" of creating slugs. https://github.com/norman/friendly_id</p>

Title: Ruby post title to slug


问:
Get file from iCloud drive without downloading?
How get file url from UIDocumentPickerController, for later upload to my server? Sending files as implemented Telegram. Now there is only the possibility to download a file from icloud and send later. But I want to learn how to implement in the telegram?

This is my code now:

```<code>func openPicker() {
    let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.data"], inMode: UIDocumentPickerMode.Open)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
    self.presentViewController(documentPicker, animated: true, completion: nil)
}

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    if controller.documentPickerMode == UIDocumentPickerMode.Open {
        let fileManager = NSFileManager.defaultManager()
        print(fileManager.fileExistsAtPath(url.path!))
        let data = NSData(contentsOfFile: url.path!)
        let document = UIDocument(fileURL: url)
    }
}
</code>```

答:
This worked for me, I was able to fetch the url of the file and read contents from it without having to download the file

```<code>let documentPickerController = UIDocumentPickerViewController(documentTypes: [ICLOUD_DOCUMENT_SEARCH_TYPE], inMode: UIDocumentPickerMode.Import)
        documentPickerController.delegate = self
        self.presentViewController(documentPickerController, animated: true, completion: nil)

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    print(url)
}
</code>```

From the url, you can then use NSFileManager to read contents of the file.

Body:
How get file url from UIDocumentPickerController, for later upload to my server? Sending files as implemented Telegram. Now there is only the possibility to download a file from icloud and send later. But I want to learn how to implement in the telegram?

This is my code now:

func openPicker() {
    let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.data"], inMode: UIDocumentPickerMode.Open)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
    self.presentViewController(documentPicker, animated: true, completion: nil)
}

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    if controller.documentPickerMode == UIDocumentPickerMode.Open {
        let fileManager = NSFileManager.defaultManager()
        print(fileManager.fileExistsAtPath(url.path!))
        let data = NSData(contentsOfFile: url.path!)
        let document = UIDocument(fileURL: url)
    }
}

Body:
This worked for me, I was able to fetch the url of the file and read contents from it without having to download the file

let documentPickerController = UIDocumentPickerViewController(documentTypes: [ICLOUD_DOCUMENT_SEARCH_TYPE], inMode: UIDocumentPickerMode.Import)
        documentPickerController.delegate = self
        self.presentViewController(documentPickerController, animated: true, completion: nil)

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    print(url)
}

From the url, you can then use NSFileManager to read contents of the file.


答: Launchers generated by install4j do not contain the JAR files, they use JNI to create the JVM and they include external JAR files into the classpath. You can run the launcher with the /create-i4j-log argument to see what it is doing.

Title: Get Jar/Java from INSTALL4J .exe

Body:
Hi Im new to install4j so forgive my misunderstandings, I have a x64 .exe that was built using INSTALL4J is there any way to get the java/jar out of it? does everything get compiled to PE64? This is the 7zip list of the .exe archive:

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2014-12-03 16:37:21 .....       173056       173056  .text
2014-12-03 16:37:21 .....        40960        40960  .rdata
2014-12-03 16:37:21 .....         9216         9216  .data
2014-12-03 16:37:21 .....         7680         7680  .pdata
                    .....         1612         1612  .rsrc\0\version.txt
                    .....          302          302  .rsrc\1033\DIALOG\101
                    .....         1188         1188  .rsrc\0\MANIFEST\1
2014-12-03 16:37:21 .....         2048         2048  .reloc
2014-12-03 16:37:21 .....         7384         7384  CERTIFICATE
2014-12-03 16:37:21 .....         3072         3072  [0]
------------------- ----- ------------ ------------  ------------------------
2014-12-03 16:37:21             246518       246518  10 files

There is no PK value as per here

And another thing how do you debug such an .exe windbg can makes sense of it and a java debugger cannot see the process?


问:
Using a string to define Numpy array slice
I have an image array that has an X times Y shape of 2048x2088. The x-axis has two 20 pixel regions, one at the start and one at the end, which are used to calibrate the main image area. To access these regions I can slice the array like so:

```<code>prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]
</code>```

My question is how to define these areas in a configuration file in order the generalise this slice for other cameras which may have different prescan and overscan areas and therefore require a different slice.

Ideally, something like the strings below would allow a simple representation in the camera specific configuration file, but I am not sure how to translate these strings into array slices.

```<code>prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"
</code>```

Maybe there is something obvious that I am missing?

Thanks!

答:
Here's an approach using regular expressions.</p>

```<code>import numpy as np
import re

def slice_from_str(img, s):

    REGEX = r'\[(\d*):(\d*), (\d*):(\d*)\]'

    m = re.findall(REGEX,s)
    if m:
        # convert empty strings to None
        groups = [None if x=='' else int(x) for x in m[0]]
        start_x, end_x, start_y, end_y = groups
        x_slice = slice(start_x, end_x)
        y_slice = slice(start_y, end_y)

        return img[x_slice,y_slice]

    return []

img = np.random.rand(2048,2088)

prescan_area_def = '[:, :20]'
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:0]"

slice_from_str(img, prescan_area_def)
slice_from_str(img, image_area_def)
slice_from_str(img, overscan_area_def)
</code>```

Body:
I have an image array that has an X times Y shape of 2048x2088. The x-axis has two 20 pixel regions, one at the start and one at the end, which are used to calibrate the main image area. To access these regions I can slice the array like so:

prescan_area = img[:, :20]
data_area = img[:, 20:2068]
overscan_area = img[:, 2068:]

My question is how to define these areas in a configuration file in order the generalise this slice for other cameras which may have different prescan and overscan areas and therefore require a different slice.

Ideally, something like the strings below would allow a simple representation in the camera specific configuration file, but I am not sure how to translate these strings into array slices.

prescan_area_def = "[:, :20]"
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:]"

Maybe there is something obvious that I am missing?

Thanks!

Body:
Here's an approach using regular expressions.

import numpy as np
import re

def slice_from_str(img, s):

    REGEX = r'\[(\d*):(\d*), (\d*):(\d*)\]'

    m = re.findall(REGEX,s)
    if m:
        # convert empty strings to None
        groups = [None if x=='' else int(x) for x in m[0]]
        start_x, end_x, start_y, end_y = groups
        x_slice = slice(start_x, end_x)
        y_slice = slice(start_y, end_y)

        return img[x_slice,y_slice]

    return []

img = np.random.rand(2048,2088)

prescan_area_def = '[:, :20]'
image_area_def = "[:, 20:2068]"
overscan_area_def = "[:, 2068:0]"

slice_from_str(img, prescan_area_def)
slice_from_str(img, image_area_def)
slice_from_str(img, overscan_area_def)


问:
Call inherited method using some "specialized" fields
For example:

```<code>struct A {
    ~A() {
        cout << me << ": destructor" << endl;
    }
    const string me = "A";
};

struct B : A {
    const string me = "B";
};

int main() {
    {
        A a;
        B b;
    }
    cout << "----\n";
    return 0;
}
</code>```

Sorry for the newbie question, I'm just wondering for the following output:

```<code>A: destructor
A: destructor
----
</code>```

In the second line I was expecting B: destructor. Can you explain why? How can I modify the code without rewriting the destructor in order to see the expected result?

答:
declaration B::me shadows A::me, but A::~A, obviously, uses A::me. (you should read more about ctors and dtors, in particular why virtual functions should not be called in ctors and dtors for deeper understanding). As for how example should be corrected:</p>

```<code>struct A{
  string me;
  A(string str = "A") : me(str){}
  ~A(){cout<<me<<endl;}
}

struct B : A {
  B(string str = "B") : A(str){}
}
</code>```

Body:
For example:

struct A {
    ~A() {
        cout << me << ": destructor" << endl;
    }
    const string me = "A";
};

struct B : A {
    const string me = "B";
};

int main() {
    {
        A a;
        B b;
    }
    cout << "----\n";
    return 0;
}

Sorry for the newbie question, I'm just wondering for the following output:

A: destructor
A: destructor
----

In the second line I was expecting B: destructor. Can you explain why? How can I modify the code without rewriting the destructor in order to see the expected result?

Body:
declaration B::me shadows A::me, but A::~A, obviously, uses A::me. (you should read more about ctors and dtors, in particular why virtual functions should not be called in ctors and dtors for deeper understanding). As for how example should be corrected:

struct A{
  string me;
  A(string str = "A") : me(str){}
  ~A(){cout<<me<<endl;}
}

struct B : A {
  B(string str = "B") : A(str){}
}


问:
Position of Seaborn heatmap annotations in cells
The annotations in a Seaborn heatmap are centered in the middle of each cell by default.
Is it possible to move the annotations to "top left".</p>

答:
You can use annot_kws of seaborn and set vertical (va) and horizontal (ha) alignments like here (sometimes it works bad):

```<code>...
annot_kws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data, annot=True, annot_kws=annot_kws)
...
</code>```

Another way put labels manually like here:

```<code>import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

data = np.random.randint(100, size=(5,5))
ax = sns.heatmap(data)

# put labels manually
for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x, y+1, '%d' % data[data.shape[0] - y - 1, x],
         ha='left',va='top', color='r')
plt.show()
</code>```

For more information and to understand text layout (why 1st example works bad?) in matplotlib read this topic: http://matplotlib.org/users/text_props.html

Body:
You can use annot_kws of seaborn and set vertical (va) and horizontal (ha) alignments like here (sometimes it works bad):

...
annot_kws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data, annot=True, annot_kws=annot_kws)
...

Another way put labels manually like here:

import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

data = np.random.randint(100, size=(5,5))
ax = sns.heatmap(data)

# put labels manually
for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x, y+1, '%d' % data[data.shape[0] - y - 1, x],
         ha='left',va='top', color='r')
plt.show()

For more information and to understand text layout (why 1st example works bad?) in matplotlib read this topic: http://matplotlib.org/users/text_props.html


问:
Google Drive: where are my comments?
The Google API does seem to permit to create comments and replies on any type of files (including binary files)

Also, I can publicly share a link and grant anonymous users having the link the permission to view and comment this file. This is the case of this picture with id=0BxMiPUSrDs2EMWVUQkR3cWsxRWs, yet, browsing this url as an anonymous user, I don't really know where are the comments and how to send a new comment.

Using this Drive API, I successfully created a comment:

```<code>POST https://www.googleapis.com/drive/v3/files/fileId/comments
</code>```

Using this Drive API, I successfully listed the file comments:

```<code>GET https://www.googleapis.com/drive/v3/files/fileId/comments
</code>```

Result is:

```<code>{
 "comments": [
  {
   "kind": "drive#comment",
   "id": "AAAAA-ZIom0",
   "createdTime": "2017-03-28T17:21:18.008Z",
   "modifiedTime": "2017-03-28T17:21:18.008Z",
   "author": {
    "kind": "drive#user",
    "displayName": "Sébastien Lorber",
    "photoLink": "//ssl.gstatic.com/s2/profiles/images/silhouette96.png",
    "me": true
   },
   "htmlContent": "Hello world",
   "content": "Hello world",
   "deleted": false,
   "resolved": false,
   "replies": []
  }
 ]
}
</code>```

So it seems this file does have a comment.

The problem is that, when using both the Drive web UI, and the Drive Android application, I am totally unable to access the content of this comment.

I can only see the comment appears as an entry inside the file activity log, so the Drive UI does know that there is a comment, but I am totally unable to find a way to read the comment content Hello world inside the official UIs.

So: am I missing something, or the Drive comment system is only to be considered as a SaaS backend for comments and the official UIs do not care of the comments we created (unless they are special kind of files, like Google Docs files).

Is there any Drive application out there that actually does show Drive comments for any kind of file?

答:
Google Drive Comments:

View all comments:

Open a document, spreadsheet, or presentation.

In the top right, click Comments.

To close, click Comments again.

This issue is in how Google Drive works.  Google drive only displays comments for the following types of files document, spreadsheet, or presentation.

While the API may allow you to add a comment Drive wont display it.

Title: Google Drive: where are my comments?

Body:
The Google API does seem to permit to create comments and replies on any type of files (including binary files)

Also, I can publicly share a link and grant anonymous users having the link the permission to view and comment this file. This is the case of this picture with id=0BxMiPUSrDs2EMWVUQkR3cWsxRWs, yet, browsing this url as an anonymous user, I don't really know where are the comments and how to send a new comment.

Using this Drive API, I successfully created a comment:

POST https://www.googleapis.com/drive/v3/files/fileId/comments

Using this Drive API, I successfully listed the file comments:

GET https://www.googleapis.com/drive/v3/files/fileId/comments

Result is:

{
 "comments": [
  {
   "kind": "drive#comment",
   "id": "AAAAA-ZIom0",
   "createdTime": "2017-03-28T17:21:18.008Z",
   "modifiedTime": "2017-03-28T17:21:18.008Z",
   "author": {
    "kind": "drive#user",
    "displayName": "Sébastien Lorber",
    "photoLink": "//ssl.gstatic.com/s2/profiles/images/silhouette96.png",
    "me": true
   },
   "htmlContent": "Hello world",
   "content": "Hello world",
   "deleted": false,
   "resolved": false,
   "replies": []
  }
 ]
}

So it seems this file does have a comment.

The problem is that, when using both the Drive web UI, and the Drive Android application, I am totally unable to access the content of this comment.

I can only see the comment appears as an entry inside the file activity log, so the Drive UI does know that there is a comment, but I am totally unable to find a way to read the comment content Hello world inside the official UIs.

So: am I missing something, or the Drive comment system is only to be considered as a SaaS backend for comments and the official UIs do not care of the comments we created (unless they are special kind of files, like Google Docs files).

Is there any Drive application out there that actually does show Drive comments for any kind of file?