问:
Storing passwords while keeping the integrity of getch()
Whats an easy way I can store the password the user inputs while still keeping the password hidden?

```<code>  char password[9];
   int i;
   printf("Enter your password: ");
   for (i=0;i<9;i++)
   {
   password[i] = getch();
   printf("*");
   }
   for (i=0;i<9;i++)
   printf("%c",password[i]);
   getch();
   }
</code>```

I wanna store the password so I can do a simple if (password[i] == root_password) so the proper password continues on.

答:
You need to use the console API in Windows. Below is a snippet that disables echoing in the console window. The function SetConsoleMode() is used to control the echoing (among other things). I save the old mode, so that I can restore the console once the password has been retrieved.

Also, the *ConsoleMode() functions need a handle to the console input buffer. How you can get a handle to these buffers is described in the MSDN documentation of CreateFile().

```<code>int main(int argc, char* argv[])
{
    char password[100] = { 0 };
    printf("Enter your password: ");

    HANDLE hConsole = ::CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

    DWORD dwOldMode;
    ::GetConsoleMode(hConsole, &dwOldMode);
    ::SetConsoleMode(hConsole, dwOldMode & ~ENABLE_ECHO_INPUT);

    bool bFinished = false;
    while(!bFinished) {
        if(!fgets(password, sizeof(password) / sizeof(password[0]) - 1, stdin)) {
            printf("\nEOF - exiting\n");
        } else
            bFinished = true;
    }

    ::SetConsoleMode(hConsole, dwOldMode | ENABLE_ECHO_INPUT);
    printf("\nPassword is: %s\n", password);

    return 0;
}
</code>```

Body:
Whats an easy way I can store the password the user inputs while still keeping the password hidden?

  char password[9];
   int i;
   printf("Enter your password: ");
   for (i=0;i<9;i++)
   {
   password[i] = getch();
   printf("*");
   }
   for (i=0;i<9;i++)
   printf("%c",password[i]);
   getch();
   }

I wanna store the password so I can do a simple if (password[i] == root_password) so the proper password continues on.

Body:
You need to use the console API in Windows. Below is a snippet that disables echoing in the console window. The function SetConsoleMode() is used to control the echoing (among other things). I save the old mode, so that I can restore the console once the password has been retrieved.

Also, the *ConsoleMode() functions need a handle to the console input buffer. How you can get a handle to these buffers is described in the MSDN documentation of CreateFile().

int main(int argc, char* argv[])
{
    char password[100] = { 0 };
    printf("Enter your password: ");

    HANDLE hConsole = ::CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

    DWORD dwOldMode;
    ::GetConsoleMode(hConsole, &dwOldMode);
    ::SetConsoleMode(hConsole, dwOldMode & ~ENABLE_ECHO_INPUT);

    bool bFinished = false;
    while(!bFinished) {
        if(!fgets(password, sizeof(password) / sizeof(password[0]) - 1, stdin)) {
            printf("\nEOF - exiting\n");
        } else
            bFinished = true;
    }

    ::SetConsoleMode(hConsole, dwOldMode | ENABLE_ECHO_INPUT);
    printf("\nPassword is: %s\n", password);

    return 0;
}


来源: stackexchange

问:
How to change inject different view in ion-view and change title in title bar based on injected page using ionic and angular js?
I am new to ionic and angular JS. I am trying a simple app in ionic framework. I am trying to inject html template in ion-view tag with the help of ngRoute concept. But my code is not injected html template in ion-view. Also based on injected page, title bar title also be changed automatically.  Also i want to show popover icon with menu item in title bar. How can i achieve this. Find the below index.html, home.html and app.js files. Thanks in advance.

index.html

```<code>  <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->
        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>

        <!-- cordova script (this will be a 404 during development) -->
        <script src="cordova.js"></script>

        <!-- your app's js -->
        <script src="js/app.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

      </head>
      <body ng-app="starter" ng-controller="AppCtrl">
          <ion-nav-bar title="{{message}}" class="bar-positive">
            <button class="button button-icon ion-more" ng-click="popover.show($event)">
            </button>

          </ion-nav-bar>

          <ion-nav-view>

          </ion-nav-view>

          <script id="mypopover.html" type="text/ng-template">
            <ion-popover-view >
              <ion-content class="my-popover">
                <div class="list">
                  <a class="item" nav-transition="android" href="#aboutus">
                   About Us
                  </a>
                  <a nav-transition="none" class="item" href="http://ionicframework.com/docs/" target="_blank">
                    Documentation
                  </a>
                  <a class="item" href="http://showcase.ionicframework.com/" target="_blank">
                    Showcase
                  </a>
                  <a class="item" href="http://ionicframework.com/submit-issue/" target="_blank">
                    Submit an Issue
                  </a>
                  <a class="item" href="https://github.com/driftyco/ionic" target="_blank">
                    Github Repo
                  </a>
                </div>
              </ion-content>
          </ion-popover-view>
        </script>
      </body>
    </html>
</code>```

templates/home.html

```<code><script type="text/ng-template" id="home.html">
    <ion-view title="Movie Review">
        <ion-content>
        <div class="fixed-header my-video">
         <ion-slide-box show-pager="false" auto-play="false" does-continue="true">
            <ion-slide>
                <img  style="max-width:100%" src="img/irumuganmovie.png"/>
            </ion-slide>
            <ion-slide>
                <img  style="max-width:100%" src="img/irumuganmovie.png"/>
            </ion-slide>
            <ion-slide>
                <img  style="max-width:100%" src="img/irumuganmovie.png"/>
            </ion-slide>
            <ion-slide>
                <img  style="max-width:100%" src="img/irumuganmovie.png"/>
            </ion-slide>
            <ion-slide>
                <img  style="max-width:100%" src="img/irumuganmovie.png"/>
            </ion-slide>
        </ion-slide-box>
        </div>
        <div class="ion-content-below-my-video">
            <div class="row center grid-row-height">
                <div class="col width-50 grid-col-size">
                    <ion-card>
                      <img src="img/irumuganmovie.png"/>
                      <ion-card-content>
                        <ion-card-title>
                            Nine Inch Nails Live
                        </ion-card-title>
                      </ion-card-content>
                    </ion-card>
                </div>
                <div class="col width-50 grid-col-size">
                    <ion-card>
                      <img src="img/irumuganmovie.png"/>
                      <ion-card-content>
                        <ion-card-title>
                            Nine Inch Nails Live
                        </ion-card-title>
                      </ion-card-content>
                    </ion-card>
                </div>
            </div>
            <div class="row center grid-row-height">
                <div class="col width-50 grid-col-size">
                    <ion-card>
                      <img src="img/irumuganmovie.png"/>
                      <ion-card-content>
                        <ion-card-title>
                            Nine Inch Nails Live
                        </ion-card-title>
                      </ion-card-content>
                    </ion-card>
                </div>
                <div class="col width-50 grid-col-size">
                    <ion-card>
                      <img src="img/irumuganmovie.png"/>
                      <ion-card-content>
                        <ion-card-title>
                            Nine Inch Nails Live
                        </ion-card-title>
                      </ion-card-content>
                    </ion-card>
                </div>
            </div>
            </div>
        </ion-content>
    </ion-view>

</script>
</code>```

app.js

```<code>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app=angular.module('starter', ['ionic','ngRoute']);

app.controller('AppCtrl',function($scope,$ionicPopover)
  {
    $ionicPopover.fromTemplateUrl('mypopover.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(popover) {

    $scope.popover = popover;
  });

  $scope.openPopover = function($event) {
  alert("opened");
   $scope.popover.show($event);
  };
  $scope.closePopover = function() {
    $scope.popover.hide();
  };
  // Perform Action on destroy
   $scope.$on('$destroy', function() {
    $scope.popover.remove();
  });
  // Perform action on hide popover
  $scope.$on('popover.hidden', function() {
    // Perform action
  });
  // Perform action on remove popover
  $scope.$on('popover.removed', function() {
    // Perform action
  });
});

app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    url: '/home',
    templateUrl : "templates/home.html",
    controller : "homeCtrl"
  });
});

app.controller('homeCtrl',function($scope) {
  // body...
  $scope.message="home controller";
});

app.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
</code>```

答:
after having same problem and searching for an answer i found this:
you can add <ion-nav-title> right after <ion-view>.

Example:

```<code>`<ion-view>
  <ion-nav-title>
    <span style="color: blue">hello</span>world
  </ion-nav-title>
   ....
   ....
</ion-view>`
</code>```

hope it will help someone.... :)

ContentLicense: CC BY-SA 3.0

Body:
I am new to ionic and angular JS. I am trying a simple app in ionic framework. I am trying to inject html template in ion-view tag with the help of ngRoute concept. But my code is not injected html template in ion-view. Also based on injected page, title bar title also be changed automatically.  Also i want to show popover icon with menu item in title bar. How can i achieve this. Find the below index.html, home.html and app.js files. Thanks in advance.

index.html

  <!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

          <ion-nav-bar title="{{message}}" class="bar-positive">
            <button class="button button-icon ion-more" ng-click="popover.show($event)">
            </button>

          </ion-nav-bar>

          <ion-nav-view>

          </ion-nav-view>

templates/home.html

app.js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app=angular.module('starter', ['ionic','ngRoute']);

app.controller('AppCtrl',function($scope,$ionicPopover)
  {
    $ionicPopover.fromTemplateUrl('mypopover.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(popover) {

    $scope.popover = popover;
  });

  $scope.openPopover = function($event) {
  alert("opened");
   $scope.popover.show($event);
  };
  $scope.closePopover = function() {
    $scope.popover.hide();
  };
  // Perform Action on destroy
   $scope.$on('$destroy', function() {
    $scope.popover.remove();
  });
  // Perform action on hide popover
  $scope.$on('popover.hidden', function() {
    // Perform action
  });
  // Perform action on remove popover
  $scope.$on('popover.removed', function() {
    // Perform action
  });
});

app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    url: '/home',
    templateUrl : "templates/home.html",
    controller : "homeCtrl"
  });
});

app.controller('homeCtrl',function($scope) {
  // body...
  $scope.message="home controller";
});

app.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

Body:
after having same problem and searching for an answer i found this:
you can add <ion-nav-title> right after <ion-view>.

Example:

`<ion-view>
  <ion-nav-title>
    <span style="color: blue">hello</span>world
  </ion-nav-title>
   ....
   ....
</ion-view>`

hope it will help someone.... :)


问:
Getting StaleElementReferenceException while trying print the link names
I'm trying to print first 5 pages links displayed in google search.. But getting StateElementReferenceException Not sure which one went wrong.. </p>

```<code>    public class GoogleCoInTest {

    static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();
        List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));

        for(int i=0;i<5;i++){
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();

        }
    }

    public static void printLinksName() throws InterruptedException{

        List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
        System.out.println(allLinks.size());

        //print all list
        for(int i=0;i<allLinks.size();i++){
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

        }
    }
}
</code>```

<p>it prints fine till 2nd page , but there after I am getting </p>

```<code>Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: The element reference of <a class="fl"> stale: either the element is no longer attached to the DOM or the page has been refreshed
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
</code>```

答:
This is due to referencing object after moving to another page. please try to add the following lines inside the for loops at the end. It may resolve stale reference issue.</p>

```<code>    driver.navigate().back();
    fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));
</code>```

Body:
I'm trying to print first 5 pages links displayed in google search.. But getting StateElementReferenceException Not sure which one went wrong..

    public class GoogleCoInTest {

    static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
        //driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
        WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
        search.sendKeys("Banduchode");
        search.sendKeys(Keys.ENTER);
        printLinksName();
        List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));

        for(int i=0;i<5;i++){
            System.out.println(fiveLinks.get(i).getText());
            fiveLinks.get(i).click();
            Thread.sleep(5000);
            printLinksName();

        }
    }

    public static void printLinksName() throws InterruptedException{

        List<WebElement> allLinks=driver.findElements(By.xpath("//*[@id='rso']/div/div/div/div/div/h3/a"));
        System.out.println(allLinks.size());

        //print all list
        for(int i=0;i<allLinks.size();i++){
            System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());

        }
    }
}

it prints fine till 2nd page , but there after I am getting

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: The element reference of  stale: either the element is no longer attached to the DOM or the page has been refreshed
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html

Body:
This is due to referencing object after moving to another page. please try to add the following lines inside the for loops at the end. It may resolve stale reference issue.

    driver.navigate().back();
    fiveLinks=driver.findElements(By.xpath(".//*[@id='nav']/tbody/tr/td/a"));


问:
Set a CSS Property (color) to a VueJS Variable
I want to set the CSS property of a class using rgb(redComp, greenComp, blueComp) format. I want to get these components from Vuejs component code.

```<code>.progress {
    color: rgb(256,0,0);
    border-radius: 0px;
}
</code>```

I want the CSS to be something like :-

```<code>.progress {
    color: rgb(redComp, greenComp, blueComp);
    border-radius: 0px;
}
</code>```

Where redComp, greenComp and blueComp will be variables in the VueJS Component.
How can I implement this?

答:
Update 2022

With Vue 3, you can now directly bind css values to reactive state.

Original answer

You cannot manipulate css with javascript. You can directly manipulate the style attribute of an element, as in throrin19's answer, but you should probalbly try to use css and the class list instead. I've never met a style problem I couldn't fix by combining classes, and the result will be more declarative in style, and likely smoother in effect.

Vue lets you specify an array of reactive classes
 You can put static classes in the same array, use ternary expressions etc.

Why do you want to do this? One reason would be to animate a colour change. If so, the best way to do this is with css transition. Your code stays declarative. See the details here.

Body:
I want to set the CSS property of a class using rgb(redComp, greenComp, blueComp) format. I want to get these components from Vuejs component code.

.progress {
    color: rgb(256,0,0);
    border-radius: 0px;
}

I want the CSS to be something like :-

.progress {
    color: rgb(redComp, greenComp, blueComp);
    border-radius: 0px;
}

Where redComp, greenComp and blueComp will be variables in the VueJS Component.
How can I implement this?

Body:
Update 2022

With Vue 3, you can now directly bind css values to reactive state.

Original answer

You cannot manipulate css with javascript. You can directly manipulate the style attribute of an element, as in throrin19's answer, but you should probalbly try to use css and the class list instead. I've never met a style problem I couldn't fix by combining classes, and the result will be more declarative in style, and likely smoother in effect.

Vue lets you specify an array of reactive classes <div v-bind:class="[activeClass, errorClass]"> You can put static classes in the same array, use ternary expressions etc.

Why do you want to do this? One reason would be to animate a colour change. If so, the best way to do this is with css transition. Your code stays declarative. See the details here.

ContentLicense: CC BY-SA 4.0


问:
How to calculate value from a dynamically generated table and its rows using angular js?
I am trying to find the value for net worth from the table.

Net Worth = Sum(Stock Price * Shares Held)

Below is the table which is created as per user selection.

For ex: from the above table, Net Worth = (842.21*1 + 230.16*2 + 1002.2*2).

I am trying with ng-change as the networth can change every time the user adds or deletes stocks. Besides, I am also facing the css issue as networth goes down when a row is getting added to table.

Here is the plnkr.

```<code>  <section class="pickstocks">
    <label class="basiclabel">Manage Portfolio</label>
    <div class="pickstocks-align">
        <table>
            <thead>
                <tr>
                    <th>STOCK</th>
                    <th>PRICE</th>
                    <th>SHARES</th>
                    <th>WEIGHT</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td class="portfoliovalue">{{"₹" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>
            </tbody>
        </table>
        <div class="networth">
            <h3>Networth</h3>
        </div>
    </div>
</section>
</code>```

答:
Here is the Plunker for reference

The first thing to do is to store the weight field just like another field in the stock object.

```<code>mystock.weight = function(){return this.value*this.shares};
</code>```

Making it into a function of the shares and value field lets us update the other two fields dynamically changing the networth. Also adding shares as a field to the stock object lets us update it easier later, so we only have to increment/decrement the field  like so.

```<code>$scope.stocksArray[$scope.stocksArray.indexOf(stock)].shares++;
</code>```

The biggest part of changing the code was objectifying it. Taking the stocks and representing it with objects allows us to easily modify and access the values later.

Once that was done all you have to do is make a method that returns the sum of all of the weights like so.

```<code>$scope.getNetWorth = function(){
      let total = 0;

      for(let i = 0; i < $scope.stocksArray.length; i++){
        total += $scope.stocksArray[i].weight()
      }

      return total.toFixed(2);
    }
</code>```

And then reference it in the html like so {{"₹" +getNetWorth()}}

In the future try to use OOP practices to simplify your code and turn your data into object representations, it will save you time and headache trying to manipulate and access your data later.

Body:
I am trying to find the value for net worth from the table.

Net Worth = Sum(Stock Price * Shares Held)

Below is the table which is created as per user selection.

For ex: from the above table, Net Worth = (842.21*1 + 230.16*2 + 1002.2*2).

I am trying with ng-change as the networth can change every time the user adds or deletes stocks. Besides, I am also facing the css issue as networth goes down when a row is getting added to table.

Here is the plnkr.

    Manage Portfolio

                    STOCK
                    PRICE
                    SHARES
                    WEIGHT

                    {{stock.key}}
                    {{"₹" + stock.value}}

                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />

                    {{stock.weight}}

Networth

Body:
Here is the Plunker for reference

The first thing to do is to store the weight field just like another field in the stock object.

mystock.weight = function(){return this.value*this.shares};

Making it into a function of the shares and value field lets us update the other two fields dynamically changing the networth. Also adding shares as a field to the stock object lets us update it easier later, so we only have to increment/decrement the field  like so.

$scope.stocksArray[$scope.stocksArray.indexOf(stock)].shares++;

The biggest part of changing the code was objectifying it. Taking the stocks and representing it with objects allows us to easily modify and access the values later.

Once that was done all you have to do is make a method that returns the sum of all of the weights like so.

$scope.getNetWorth = function(){
      let total = 0;

      for(let i = 0; i < $scope.stocksArray.length; i++){
        total += $scope.stocksArray[i].weight()
      }

      return total.toFixed(2);
    }

And then reference it in the html like so {{"&#x20b9;" +getNetWorth()}}

In the future try to use OOP practices to simplify your code and turn your data into object representations, it will save you time and headache trying to manipulate and access your data later.


问:
Axes class - set explicitly size (width/height) of axes in given units
I want to to create a figure using matplotlib where I can explicitly specify the size of the axes, i.e. I want to set the width and height of the axes bbox.

I have looked around all over and I cannot find a solution for this. What I typically find is how to adjust the size of the complete Figure (including ticks and labels), for example using fig, ax = plt.subplots(figsize=(w, h))

This is very important for me as I want to have a 1:1 scale of the axes, i.e. 1 unit in paper is equal to 1 unit in reality. For example, if xrange is 0 to 10 with major tick = 1 and x axis is 10cm, then 1 major tick = 1cm. I will save this figure as pdf to import it to a latex document.

This question brought up a similar topic but the answer does not solve my problem (using plt.gca().set_aspect('equal', adjustable='box') code)

From this other question I see that it is possible to get the axes size, but not how to modify them explicitly.

Any ideas how I can set the axes box size and not just the figure size. The figure size should adapt to the axes size.

Thanks!

For those familiar with pgfplots in latex, it will like to have something similar to the scale only axis option (see here for example).

答:
The axes size is determined by the figure size and the figure spacings, which can be set using figure.subplots_adjust().  In reverse this means that you can set the axes size by setting the figure size taking into acount the figure spacings:

```<code>import matplotlib.pyplot as plt

def set_size(w,h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_size(5,5)

plt.show()
</code>```

Body:
The axes size is determined by the figure size and the figure spacings, which can be set using figure.subplots_adjust().  In reverse this means that you can set the axes size by setting the figure size taking into acount the figure spacings:

import matplotlib.pyplot as plt

def set_size(w,h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_size(5,5)

plt.show()


问:
making a jar file
I have written a code for client/server application. and I go to

properties>packaging

for making a jar file for it. but when I run my server side and then client side ! it doesn't make the jar file for my application! what should I do? please help me thanks

答:
If you are a real beginner I suggest that you follow the
Java Tutorials

Especially the one on Jar files

ContentLicense: CC BY-SA 2.5

Title: making a jar file


问:
Grouping issue with addJSONData
I have some issue with jqGrid paging. I want create own group and add row data to it. While I add data to grid on the first page its Ok, but if add new group on the next page, I can see exception in Firebug and empty page. I use addJSONData method. The problem is that addJSONData iterate through all groups in Grid and look for their length:

```<code>str += "<tr id=\""+hid+"\" role=\"row\" class= \"ui-widget-content jqgroup ui-row-"+$t.p.direction+"\"><td colspan=\""+colspans+"\">"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"</td></tr>";
</code>```

But if I have one group on previous page and only sent data of second group with ajax and call addJSONData it throws exception: length of undefined. How can I solve it?

UPDATE: Here is my code:

```<code>function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });
</code>```

}

And table:

```<code>$(myGrid).jqGrid({
    url: myUrlTable,
    datatype: 'json',
    postData: {},
    mtype: 'GET',
    jsonReader: { repeatitems : false},
    colNames: ['Id', 'Group', 'Bytes'],
    colModel: [{name:'id', index: 'id', hidden: true},
               {name:'group', index: 'group', width: 100},
               {name:'bytes', index: 'bytes', width: 60, classes:'gc column-bytes', sortable: false, sorttype:'int', formatter:'integer'}
               ],
    grouping: true,
    groupingView: {
        groupField : ['group'],
        groupText : ['Group: ({1} items)'],
        groupOrder: 'asc',
        groupDataSorted : true
    },
    sortable: true,
    toppager: true,
    hoverrows: true,
    altrows: false,
});
</code>```

Test data from server:

```<code>{"total":1,"page":1,"records":1,"rows":[{"group":"abc", "bytes":229447,"id":"7124"}]}
</code>```

Another records are similar. I added 20 records and then I added next 5 on another page with group bbb.
Method addToGrid is called from another grid and with ids and entered group name to input dialog. Then I pass it to server and server returns valid data to fulefill grid. Server returns only data for the last page in my case 5 rows.

Server response:

```<code> {"total":2,"page":2,"records":5,"rows":[{"group":"bbb", "bytes":229447,"id":"7155"},
                                         {"group":"bbb", "bytes":229447,"id":"7156"},
                                         {"group":"bbb", "bytes":229447,"id":"7157"},
                                         {"group":"bbb", "bytes":229447,"id":"7158"},
                                         {"group":"bbb", "bytes":229447,"id":"7159"}
                                        ]
 }
</code>```

答:
As  @unknown user mentioned in this case you should call groupingSetup method before to call addJsonData, but this is not enough in case you have  change the grouping and other parameters dynamically.

You will need to set the changed grouped parameters with setGridParam method before to call groupingSetup.

More you can find in our new Guriddo jqGrid documentation

Kind Regards

Title: Grouping issue with addJSONData

Body:
I have some issue with jqGrid paging. I want create own group and add row data to it. While I add data to grid on the first page its Ok, but if add new group on the next page, I can see exception in Firebug and empty page. I use addJSONData method. The problem is that addJSONData iterate through all groups in Grid and look for their length:

str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";

But if I have one group on previous page and only sent data of second group with ajax and call addJSONData it throws exception: length of undefined. How can I solve it?

UPDATE: Here is my code:

function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });

}

And table:

$(myGrid).jqGrid({
    url: myUrlTable,
    datatype: 'json',
    postData: {},
    mtype: 'GET',
    jsonReader: { repeatitems : false},
    colNames: ['Id', 'Group', 'Bytes'],
    colModel: [{name:'id', index: 'id', hidden: true},
               {name:'group', index: 'group', width: 100},
               {name:'bytes', index: 'bytes', width: 60, classes:'gc column-bytes', sortable: false, sorttype:'int', formatter:'integer'}
               ],
    grouping: true,
    groupingView: {
        groupField : ['group'],
        groupText : ['Group: ({1} items)'],
        groupOrder: 'asc',
        groupDataSorted : true
    },
    sortable: true,
    toppager: true,
    hoverrows: true,
    altrows: false,
});

Test data from server:

{"total":1,"page":1,"records":1,"rows":[{"group":"abc", "bytes":229447,"id":"7124"}]}

Another records are similar. I added 20 records and then I added next 5 on another page with group bbb.
Method addToGrid is called from another grid and with ids and entered group name to input dialog. Then I pass it to server and server returns valid data to fulefill grid. Server returns only data for the last page in my case 5 rows.

Server response:

 {"total":2,"page":2,"records":5,"rows":[{"group":"bbb", "bytes":229447,"id":"7155"},
                                         {"group":"bbb", "bytes":229447,"id":"7156"},
                                         {"group":"bbb", "bytes":229447,"id":"7157"},
                                         {"group":"bbb", "bytes":229447,"id":"7158"},
                                         {"group":"bbb", "bytes":229447,"id":"7159"}
                                        ]
 }


问:
Dagger2 Why can't one type is injected into more than one component?
In Dagger2 is it possible to request same class for injection from more than one component. Sample code below

```<code>@Component(modules = classA.class)
interface compA
{
void inject(MyActivity target);
}

@Component(modules = classB.class)
interface compB
{
void inject(MyActivity target);
}
</code>```

If possible please explain with reason and any doc reference.

Thanks

答: Not at the same time.  You can call either inject function you wish on it, but you can't inject it with compA then compB.  You could however make a componentC that builds off of subcomponents A and B and inject it with that.</p>

Body:
In Dagger2 is it possible to request same class for injection from more than one component. Sample code below

@Component(modules = classA.class)
interface compA
{
void inject(MyActivity target);
}

@Component(modules = classB.class)
interface compB
{
void inject(MyActivity target);
}

If possible please explain with reason and any doc reference.

Thanks


问:
AES use same IV for encryption and decryption
I'm having some issues with my code whereby I am not using the same IV for encryption and decryption. I know in order to do this correctly I have to write the IV to my output file before the data however I am struggling implementing this. Could anyone help me with this issue?

Edited code code again to show full scope

```<code>public class TestFileEncryption {
    private static void mainCrypto(int cipherMode, File inputFile, File outputFile) throws Exception{
        //Let the user enter the key they wish to use
        Key secretKey = new SecretKeySpec(UITest.getStoreKey().getBytes(), UITest.getSendAlg()); //Generates a key based on the default keysize for the specified algorithm

        //Generate an Initialization Vector (IV)
        final int ALG_KEYLENGTH = UITest.getStoreKey().length(); //Change this as desired for the security level you want
        byte[] iv = new byte[ALG_KEYLENGTH]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
        SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
        prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

        //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
        Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

        //Initialize the Cipher for Encryption
        cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

        //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length() - ALG_KEYLENGTH];
        inputStream.read(iv);
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        inputStream.close();
        outputStream.close();
    }

    public static void encrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void decrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void main(String[] args) {}
}
</code>```

答:
You just have to write the IV before the ciphertext:

```<code>outputStream.write(iv);
outputStream.write(outputBytes);
</code>```

Then, when decrypting, read the IV and the ciphertext:

```<code>byte[] iv = new byte[ALG_BLOCKSIZE];
byte[] inputBytes = new byte[(int) inputFile.length() - ALG_BLOCKSIZE];
inputStream.read(iv);
inputStream.read(inputBytes);
</code>```

Here ALG_BLOCKSIZE needs to be 16 for AES-CBC.

Body:
I'm having some issues with my code whereby I am not using the same IV for encryption and decryption. I know in order to do this correctly I have to write the IV to my output file before the data however I am struggling implementing this. Could anyone help me with this issue?

Edited code code again to show full scope

public class TestFileEncryption {
    private static void mainCrypto(int cipherMode, File inputFile, File outputFile) throws Exception{
        //Let the user enter the key they wish to use
        Key secretKey = new SecretKeySpec(UITest.getStoreKey().getBytes(), UITest.getSendAlg()); //Generates a key based on the default keysize for the specified algorithm

        //Generate an Initialization Vector (IV)
        final int ALG_KEYLENGTH = UITest.getStoreKey().length(); //Change this as desired for the security level you want
        byte[] iv = new byte[ALG_KEYLENGTH]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
        SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
        prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

        //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
        Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

        //Initialize the Cipher for Encryption
        cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

        //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length() - ALG_KEYLENGTH];
        inputStream.read(iv);
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        inputStream.close();
        outputStream.close();
    }

    public static void encrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void decrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void main(String[] args) {}
}

Body:
You just have to write the IV before the ciphertext:

outputStream.write(iv);
outputStream.write(outputBytes);

Then, when decrypting, read the IV and the ciphertext:

byte[] iv = new byte[ALG_BLOCKSIZE];
byte[] inputBytes = new byte[(int) inputFile.length() - ALG_BLOCKSIZE];
inputStream.read(iv);
inputStream.read(inputBytes);

Here ALG_BLOCKSIZE needs to be 16 for AES-CBC.


问:
c# base64 encoding. Invalid length error on decrpytion
I'm trying to decrypt a string which is also base64 encoded, but I am receiving an when I try to decrypt the string.

The error I am receiving is:

{System.FormatException: Invalid length for a Base-64 char array or string.

at this line in the decrypt function below:

MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));

Encrpyt/Decrypt functions:

```<code>//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
    try
    {
        if(String.IsNullOrEmpty(inString)){return false;}

        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
        StreamWriter sw = new StreamWriter(cs);

        sw.Write(inString);
        sw.Flush();
        cs.FlushFinalBlock();
        sw.Flush();

        outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);

        return true;
    }
    catch(Exception ex)
    {
        clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
        return false;
    }
}

//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
    try
    {
        if(String.IsNullOrEmpty(inString)){return false;};

        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
        CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
        StreamReader sr = new StreamReader(cs);

        outstring = sr.ReadToEnd();

        return true;
    }
    catch(Exception ex)
    {
        clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
        return false;
    }
}
</code>```

答:
Solved using the simple solution in the following link
How do I encode and decode a base64 string?

Also added some code in the encoding function to ensure the plain text string will be converted to a valid length base64 string.

Code:

```<code>public static string Base64Encode(string plainText)
{

            //check plain text string and pad if needed
            int mod4 = plainText.Length % 4;
            if (mod4 > 0)
            {
                plainText += new string('=', 4 - mod4);
            }

            //convert to base64 and return
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(string base64EncodedData)
        {
            //decode base64 and return as string
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
</code>```

Body:
I'm trying to decrypt a string which is also base64 encoded, but I am receiving an when I try to decrypt the string.

The error I am receiving is:

{System.FormatException: Invalid length for a Base-64 char array or string.

at this line in the decrypt function below:

MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));

Encrpyt/Decrypt functions:

//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
    try
    {
        if(String.IsNullOrEmpty(inString)){return false;}

        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
        StreamWriter sw = new StreamWriter(cs);

        sw.Write(inString);
        sw.Flush();
        cs.FlushFinalBlock();
        sw.Flush();

        outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);

        return true;
    }
    catch(Exception ex)
    {
        clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
        return false;
    }
}

//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
    try
    {
        if(String.IsNullOrEmpty(inString)){return false;};

        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
        CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
        StreamReader sr = new StreamReader(cs);

        outstring = sr.ReadToEnd();

        return true;
    }
    catch(Exception ex)
    {
        clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
        return false;
    }
}

Body:
Solved using the simple solution in the following link
How do I encode and decode a base64 string?

Also added some code in the encoding function to ensure the plain text string will be converted to a valid length base64 string.

Code:

public static string Base64Encode(string plainText)
{

            //check plain text string and pad if needed
            int mod4 = plainText.Length % 4;
            if (mod4 > 0)
            {
                plainText += new string('=', 4 - mod4);
            }

            //convert to base64 and return
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(string base64EncodedData)
        {
            //decode base64 and return as string
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }


问:
CPU Utilisation 100% while using OpenOffice4
I'm trying to convert documents(.docx/.xlsx/.pptx) to PDF using JOD Converter. I'm using OpenOffice 4.1.2 on Centos 7. My problem is, I'm getting constant CPU usage of 100% while i'm converting the file, and this is impacting the performance of overall machine. I have tried every possible option in the command line options, but ,unfortunately, haven't been able to mitigate this issue. I have searched on a lot of forums, and found that lot of other people are also facing the same problem, however, there is no solution out there. Through my readings, I realize this could be because memory leak problems in OpenOffice. Can someone please help me resolve or at-least mitigate this?

Below is the command that I use to spawn the OpenOffice instance.

```<code>/opt/openoffice4/program/soffice.bin -accept=socket,host=127.0.0.1,port=8016;urp; -env:UserInstallation=file:///tmp/.jodconverter_socket_host-127.0.0.1_port-8016 -headless -nocrashreport -nodefault -nofirststartwizard -nolockcheck -nologo -norestore
</code>```

The code I'm using to convert the files is as follows:
package org.samples.docxconverters.jodconverter.pdf;

```<code>import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

public class Word2PdfJod {

    public static void main(String[] args) {

        // 1) Start LibreOffice in headless mode.
        OfficeManager officeManager = null;
        try {
            officeManager = new DefaultOfficeManagerConfiguration()
                .setOfficeHome(new File("/Applications/OpenOffice.app/Contents/")).buildOfficeManager();
            officeManager.start();

            // 2) Create JODConverter converter
            OfficeDocumentConverter converter = new OfficeDocumentConverter(
                    officeManager);

            // 3) Create PDF
            createPDF(converter);

        } finally {
            // 4) Stop OpenOffice in headless mode.
            if (officeManager != null) {
                officeManager.stop();
            }
        }
    }

    private static void createPDF(OfficeDocumentConverter converter) {
        try {
            long start = System.currentTimeMillis();
            String src_file = "/Users/Aman/Documents/WindowsData/DocumentConversionPoc/Powerpoint2Pdf/JODConverterV3/Sample_pptx_files/AdeemSample2.pptx";

            System.out.println(src_file.substring(0, src_file.lastIndexOf(".")) + "_" + FilenameUtils.getExtension(src_file) );
            //Actual Conversion

            converter.convert( new File(src_file), new File( src_file.substring(0, src_file.lastIndexOf(".")) + "_"
                        + FilenameUtils.getExtension(src_file) +"_Jod.pdf") );
            System.out.println("Time Taken in conversion -  "+ (System.currentTimeMillis() - start) + "ms");

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
</code>```

And the relevant jars can be downloaded from :
https://drive.google.com/file/d/0B4hS5IGxGOh9OE5Ca0RlbTdVclU/view?usp=sharing

答:
If CPU is idle, a process will take 100% CPU time by default. It's normal. If this is causing hinderance in executing other processes (highly unlikely), you can set up priorities using nice.

```<code>nice <your command>
</code>```

Or, you can install cpulimit, which makes your program sleep if it reaches a predefined CPU usage. Read about it here.

Body:
I'm trying to convert documents(.docx/.xlsx/.pptx) to PDF using JOD Converter. I'm using OpenOffice 4.1.2 on Centos 7. My problem is, I'm getting constant CPU usage of 100% while i'm converting the file, and this is impacting the performance of overall machine. I have tried every possible option in the command line options, but ,unfortunately, haven't been able to mitigate this issue. I have searched on a lot of forums, and found that lot of other people are also facing the same problem, however, there is no solution out there. Through my readings, I realize this could be because memory leak problems in OpenOffice. Can someone please help me resolve or at-least mitigate this?

Below is the command that I use to spawn the OpenOffice instance.

/opt/openoffice4/program/soffice.bin -accept=socket,host=127.0.0.1,port=8016;urp; -env:UserInstallation=file:///tmp/.jodconverter_socket_host-127.0.0.1_port-8016 -headless -nocrashreport -nodefault -nofirststartwizard -nolockcheck -nologo -norestore

The code I'm using to convert the files is as follows:
package org.samples.docxconverters.jodconverter.pdf;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

public class Word2PdfJod {

    public static void main(String[] args) {

        // 1) Start LibreOffice in headless mode.
        OfficeManager officeManager = null;
        try {
            officeManager = new DefaultOfficeManagerConfiguration()
                .setOfficeHome(new File("/Applications/OpenOffice.app/Contents/")).buildOfficeManager();
            officeManager.start();

            // 2) Create JODConverter converter
            OfficeDocumentConverter converter = new OfficeDocumentConverter(
                    officeManager);

            // 3) Create PDF
            createPDF(converter);

        } finally {
            // 4) Stop OpenOffice in headless mode.
            if (officeManager != null) {
                officeManager.stop();
            }
        }
    }

    private static void createPDF(OfficeDocumentConverter converter) {
        try {
            long start = System.currentTimeMillis();
            String src_file = "/Users/Aman/Documents/WindowsData/DocumentConversionPoc/Powerpoint2Pdf/JODConverterV3/Sample_pptx_files/AdeemSample2.pptx";

            System.out.println(src_file.substring(0, src_file.lastIndexOf(".")) + "_" + FilenameUtils.getExtension(src_file) );
            //Actual Conversion

            converter.convert( new File(src_file), new File( src_file.substring(0, src_file.lastIndexOf(".")) + "_"
                        + FilenameUtils.getExtension(src_file) +"_Jod.pdf") );
            System.out.println("Time Taken in conversion -  "+ (System.currentTimeMillis() - start) + "ms");

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

And the relevant jars can be downloaded from :
https://drive.google.com/file/d/0B4hS5IGxGOh9OE5Ca0RlbTdVclU/view?usp=sharing

Body:
If CPU is idle, a process will take 100% CPU time by default. It's normal. If this is causing hinderance in executing other processes (highly unlikely), you can set up priorities using nice.

nice <your command>

Or, you can install cpulimit, which makes your program sleep if it reaches a predefined CPU usage. Read about it here.


问:
Protobuf with GZIP compression
I am having a problem in trying to serialize an array of unsigned char into file with GZIP compression using protobuf while playing with the library.

I think the problem might have to do with some of my syntax or misuse of API.
I have also tried std::fstream.
FYI, Windows 8.1 & VS2013 is the building environment.

scene.proto

```<code>syntax = "proto3";

package Recipe;

message Scene
{
    repeated int32 imageData = 1 [packed=true];
}
</code>```

source.cpp

```<code>#include <iostream>
#include <fstream>
#include <ostream>
#include <istream>
#include <string>
#include <cstdint>
#include "Scene.pb.h"
#include <google\protobuf\io\zero_copy_stream_impl.h>
#include <google\protobuf\io\gzip_stream.h>

int const _MIN = 0;
int const _MAX = 255;
unsigned int const _SIZE = 65200000;
unsigned int const _COMPRESSION_LEVEL = 10;

void randWithinUnsignedCharSize(uint8_t * buffer, unsigned int size)
{
    for (size_t i = 0; i < size; ++i)
    {
        buffer[i] = _MIN + (rand() % static_cast<int>(_MAX - _MIN + 1));
    }
}

using namespace google::protobuf::io;

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    Recipe::Scene * scene = new Recipe::Scene();
    uint8_t * imageData = new uint8_t[_SIZE];
    randWithinUnsignedCharSize(imageData, _SIZE);

    for (size_t i = 0; i < _SIZE; i++)
    {
        scene->add_imagedata(imageData[i]);
    }
    std::cout << "scene->imagedata_size() " << scene->imagedata_size() << std::endl;
    {
        std::ofstream output("scene.art", std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
        OstreamOutputStream outputFileStream(&output);
        GzipOutputStream::Options options;
        options.format = GzipOutputStream::GZIP;
        options.compression_level = _COMPRESSION_LEVEL;

        GzipOutputStream gzipOutputStream(&outputFileStream, options);

        if (!scene->SerializeToZeroCopyStream(&gzipOutputStream)) {
            std::cerr << "Failed to write scene." << std::endl;
            return -1;
        }
    }
    Recipe::Scene * scene1 = new Recipe::Scene();
    {
        std::ifstream input("scene.art", std::ifstream::in | std::ifstream::binary);
        IstreamInputStream inputFileStream(&input);
        GzipInputStream gzipInputStream(&inputFileStream);

        if (!scene1->ParseFromZeroCopyStream(&gzipInputStream)) {
            std::cerr << "Failed to parse scene." << std::endl;
            return -1;
        }
    }
    std::cout << "scene1->imagedata_size() " << scene1->imagedata_size() <<std::endl;
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}
</code>```

答:
You seem to have a typo in your code. Compression level is according to documentation in range 0-9. You set incorrectly compression level to 10.

Your example is working for me when corrected to:

```<code>unsigned int const _COMPRESSION_LEVEL = 9;
</code>```

Title: Protobuf with GZIP compression

Body:
I am having a problem in trying to serialize an array of unsigned char into file with GZIP compression using protobuf while playing with the library.

I think the problem might have to do with some of my syntax or misuse of API.
I have also tried std::fstream.
FYI, Windows 8.1 & VS2013 is the building environment.

scene.proto

syntax = "proto3";

package Recipe;

message Scene
{
    repeated int32 imageData = 1 [packed=true];
}

source.cpp

#include <iostream>
#include <fstream>
#include <ostream>
#include <istream>
#include <string>
#include <cstdint>
#include "Scene.pb.h"
#include <google\protobuf\io\zero_copy_stream_impl.h>
#include <google\protobuf\io\gzip_stream.h>

int const _MIN = 0;
int const _MAX = 255;
unsigned int const _SIZE = 65200000;
unsigned int const _COMPRESSION_LEVEL = 10;

void randWithinUnsignedCharSize(uint8_t * buffer, unsigned int size)
{
    for (size_t i = 0; i < size; ++i)
    {
        buffer[i] = _MIN + (rand() % static_cast<int>(_MAX - _MIN + 1));
    }
}

using namespace google::protobuf::io;

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    Recipe::Scene * scene = new Recipe::Scene();
    uint8_t * imageData = new uint8_t[_SIZE];
    randWithinUnsignedCharSize(imageData, _SIZE);

    for (size_t i = 0; i < _SIZE; i++)
    {
        scene->add_imagedata(imageData[i]);
    }
    std::cout << "scene->imagedata_size() " << scene->imagedata_size() << std::endl;
    {
        std::ofstream output("scene.art", std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
        OstreamOutputStream outputFileStream(&output);
        GzipOutputStream::Options options;
        options.format = GzipOutputStream::GZIP;
        options.compression_level = _COMPRESSION_LEVEL;

        GzipOutputStream gzipOutputStream(&outputFileStream, options);

        if (!scene->SerializeToZeroCopyStream(&gzipOutputStream)) {
            std::cerr << "Failed to write scene." << std::endl;
            return -1;
        }
    }
    Recipe::Scene * scene1 = new Recipe::Scene();
    {
        std::ifstream input("scene.art", std::ifstream::in | std::ifstream::binary);
        IstreamInputStream inputFileStream(&input);
        GzipInputStream gzipInputStream(&inputFileStream);

        if (!scene1->ParseFromZeroCopyStream(&gzipInputStream)) {
            std::cerr << "Failed to parse scene." << std::endl;
            return -1;
        }
    }
    std::cout << "scene1->imagedata_size() " << scene1->imagedata_size() <<std::endl;
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}

Body:
You seem to have a typo in your code. Compression level is according to documentation in range 0-9. You set incorrectly compression level to 10.

Your example is working for me when corrected to:

unsigned int const _COMPRESSION_LEVEL = 9;


问:
Enable the display of line numbers in Visual Studio
Why doesn't Visual Studio have any way of showing line numbers in a source file? Is there any way to enable it, or a plugin for it? I know that the number of lines of code in a program doesn't matter, but sometimes it is nice to know how long a program is or the number of a particular line for reference.

Though I tried, I can't seem to find a way to enable line numbering and I find that surprising.

This is Visual Studio 2010 Ultimate. (If you have read my older questions, I've been using 2008 Express until now.)

答:
You should edit "settings.json". In that add, "editor.lineNumbers":"on", . You can check comments for various options you have.

In Visual Studio Code - 2017, you can also directly go to a given line number. There are following three ways to do that.

Directly use keyboard shortcut - Ctrl + G.

Under menu Go, use Go to Line - Go > Go to Line

Search for Go to Line in Command Pallete (Cmd + Shift + P).


问:
signin user upon clicking the link in email automatically in rails application?
I have a User model in my rails application. which is a "devise" model. i have one form called "user-info" form this form can be available once the user logs into the system.

i have one admin login in which an admin can send the link to the user email like fill the "user info" by clicking a button. once the user clicks the button i want the user to login into the system automatically without redirecting to the login page. and should be navigated to the user-info form.

i have an idea of sending query string parameters in the url like email = "x@gmail.com "&& form = "user_info". but once the user clicks on this what needs to be implemented to achieve my requirement.

答:
My understanding is that you can use the tokens to log in or to hit arbitrary pages that need authentication, even with cURL. If you look in config/initializers/devise.rb, there should be a line that says something like:

```<code>config.token_authentication_key = :auth_token
</code>```

Whatever the name of the token_authentication_key is should match what you put as the query or form parameter in your request. You used authentication_token in your example, not sure if you changed devise.rb to match that or not.

If you want to figure out how things are working internally, I would try git clone git://github.com/plataformatec/devise.git and search for the methods you need clarification of.

Here are some sample cURL requests (I made a custom Users::SessionsController that extends Devise::SessionsController and overrides the create method to handle JSON.)

```<code>class Users::SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html do
        respond_with resource, :location => redirect_location(resource_name, resource)
      end
      format.json do
        render :json => { :response => 'ok', :auth_token => current_user.authentication_token }.to_json, :status => :ok
      end
    end
  end
end
</code>```

And then the cURL requests I gave:

```<code>curl -X POST 'http://localhost:3000/users/sign_in.json' -d 'user[email]=example@example.com&user[password]=password'
-> {"response":"ok","auth_token":"ABCDE0123456789"}

curl -L 'http://localhost:3000/profile?auth_token=ABCDE0123456789'
-> got page that I wanted that needs authentication
</code>```

Body:
My understanding is that you can use the tokens to log in or to hit arbitrary pages that need authentication, even with cURL. If you look in config/initializers/devise.rb, there should be a line that says something like:

config.token_authentication_key = :auth_token

Whatever the name of the token_authentication_key is should match what you put as the query or form parameter in your request. You used authentication_token in your example, not sure if you changed devise.rb to match that or not.

If you want to figure out how things are working internally, I would try git clone git://github.com/plataformatec/devise.git and search for the methods you need clarification of.

Here are some sample cURL requests (I made a custom Users::SessionsController that extends Devise::SessionsController and overrides the create method to handle JSON.)

class Users::SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html do
        respond_with resource, :location => redirect_location(resource_name, resource)
      end
      format.json do
        render :json => { :response => 'ok', :auth_token => current_user.authentication_token }.to_json, :status => :ok
      end
    end
  end
end

And then the cURL requests I gave:

curl -X POST 'http://localhost:3000/users/sign_in.json' -d 'user[email]=example@example.com&user[password]=password'
-> {"response":"ok","auth_token":"ABCDE0123456789"}

curl -L 'http://localhost:3000/profile?auth_token=ABCDE0123456789'
-> got page that I wanted that needs authentication


问:
How to select rows where date is greater than the date in another row?
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

```<code>card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17
</code>```

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?

答:
Can you try something like this?</p>

```<code>SELECT A.card_id, A.customer_id, A.card_type, A.last_used
FROM CUSTOMER_CARDS A
INNER JOIN CUSTOMER_CARDS B ON A.customer_id=B.customer_id
WHERE A.card_type='B'
    AND B.card_type='A' AND A.last_user > B.last_used
    ;
</code>```

Body:
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?

Body:
Can you try something like this?

SELECT A.card_id, A.customer_id, A.card_type, A.last_used
FROM CUSTOMER_CARDS A
INNER JOIN CUSTOMER_CARDS B ON A.customer_id=B.customer_id
WHERE A.card_type='B'
    AND B.card_type='A' AND A.last_user > B.last_used
    ;


问:
Making preview in writing page using AngularJS
I want have a preview in my writing page just like here in StackOverFlow question writing.

Everytime i press enterkey in the textarea, it doesn't make new line but just a space.

Instead of typing >br< tag in the textarea, I want pressing enterkey as really making a new line in the preview area.

Please help me and Thank you.

here's my code

  <textarea ng-model="myText"></textarea>

```

答:
Can be done with css

```<code>#contentsPreview {
  white-space: pre;// or pre-line
}
</code>```

Otherwise use a function or filter to replace \n with

```<code>$scope.n2br = function(str){
   return str.replace(/\\n/g, '<br>')
}
</code>```

Body:
Can be done with css

#contentsPreview {
  white-space: pre;// or pre-line
}

Otherwise use a function or filter to replace \n with <br>

$scope.n2br = function(str){
   return str.replace(/\\n/g, '<br>')
}


问:
Ordering for key value pairs
I have the following two classes:

```<code>class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}
</code>```

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?

答:
I recommend you do the following:

Change your com.google.common.collect.Ordering<ValueClass> to com.google.common.collect.Ordering<Map.Entry<KeyClass, ValueClass>> and modify the multiple Comparator<ValueClass> that are used to use Map.Entry#getValue instead.

Thus, the maximum ValueClass will be equivalent to the maximum Map.Entry<KeyClass, ValueClass>.

I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

Now, you can simply use Map.Entry#getKey to grab the key of the maximum value/entry.

Title: Ordering for key value pairs

Body:
I have the following two classes:

class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?


问:
why my onclick function didn't work in react
Hi i didn't understand why my onclick function didn't work. my function create run herself 2 time at the loading of the page but not when i click on the button

   import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Topics } from '../api/topic.js';
import Topic from './Topic.jsx';

class AppCreate extends Component {

render(){

  return(

      <form>
        <input type="text" placeholder="donnez un nom a votre Topic" className="topic"></input>
        <input type="button" value="Créer" onClick={this.create()}></input>
      </form>

  );

  }
  create(e){
   {var test = document.getElementsByClassName("topic").value;
   console.log(test);}
  }
}

AppCreate.propTypes = {
topics: PropTypes.array.isRequired
};

export default createContainer(() => {
return {
  topics: Topics.find({}).fetch(),
};
}, AppCreate);```

答:
Why it doesn't work

When you're passing onClick={this.create()} you're actually passing the return value of the function, and not the function it self. As a side effect, this will also cause that function to be called when a render occurs, not only when a user actually clicks.

Solution

You want to pass the function itself to be called, notice there are no parentheses ():

onClick={this.create}

If you need to access the component instance in the click handle

You'll also want to bind this (the instance of your component) inside your method, e.g. to access this.state you'll have to bind that value

onClick={this.create.bind(this)}

With this the execution inside create() will have a this value equal to the instance of your component, allowing you to access its attributes and methods like this.props, this.state and other methods you have defined on the component.


问:
Table is specified twice, both as a target for 'UPDATE' and as a separate source for data in mysql
I have below query in mysql where I want to check if branch id and year of finance type from branch_master are equal with branch id and year of manager then update status in manager table against branch id in manager

```<code>UPDATE manager as m1
  SET m1.status = 'Y'
  WHERE m1.branch_id IN (
    SELECT m2.branch_id FROM manager as m2
     WHERE (m2.branch_id,m2.year) IN (
        (
          SELECT DISTINCT branch_id,year
            FROM `branch_master`
           WHERE type = 'finance'
        )
     )
  )
</code>```

but getting error

Table 'm1' is specified twice, both as a target for 'UPDATE' and as a
  separate source for data

答:
This is a typical MySQL thing and can usually be circumvented by selecting from the table derived, i.e. instead of

```<code>FROM manager AS m2
</code>```

use

```<code>FROM (select * from manager) AS m2
</code>```

The complete statement:

```<code>UPDATE manager
SET status = 'Y'
WHERE branch_id IN
(
  select branch_id
  FROM (select * from manager) AS m2
  WHERE (branch_id, year) IN
  (
    SELECT branch_id, year
    FROM branch_master
    WHERE type = 'finance'
  )
);
</code>```

Body:
I have below query in mysql where I want to check if branch id and year of finance type from branch_master are equal with branch id and year of manager then update status in manager table against branch id in manager

UPDATE manager as m1
  SET m1.status = 'Y'
  WHERE m1.branch_id IN (
    SELECT m2.branch_id FROM manager as m2
     WHERE (m2.branch_id,m2.year) IN (
        (
          SELECT DISTINCT branch_id,year
            FROM `branch_master`
           WHERE type = 'finance'
        )
     )
  )

but getting error

Table 'm1' is specified twice, both as a target for 'UPDATE' and as a
  separate source for data

Body:
This is a typical MySQL thing and can usually be circumvented by selecting from the table derived, i.e. instead of

FROM manager AS m2

use

FROM (select * from manager) AS m2

The complete statement:

UPDATE manager
SET status = 'Y'
WHERE branch_id IN
(
  select branch_id
  FROM (select * from manager) AS m2
  WHERE (branch_id, year) IN
  (
    SELECT branch_id, year
    FROM branch_master
    WHERE type = 'finance'
  )
);


问:
Android layouts for different screen sizes
I am struggling for layouts for an Android app. I have defined different layouts for different screen sizes and the current layout directory structure is something like this:

layout

layout-land

layout-small

layout-xlarge

layout-xlarge-land

Problem

The main layout directory files are being displayed for 3.7 to 7.0 which is a very broad range. And text overlap on small screens and if I adjust on small; it becomes very tiny on the large screen.

According to me, the layout small files should be rendered for smaller screens but those files are only rendered for android wear devices.

layout-xlarge seems to work for Nexus 9 to Nexus 10

I want to know, how can I define the different layout for 3.7-5.0 and 5.0-7.0 screen sizes.

答:
The answer is already given by user5594218 but looks like you are still unclear. (maybe you are beginner)

So, here is the step by step guideline

Solution 1: (short and simple)

Navigate to app > src > main > res

Duplicate layout directory by copying and pasting

Rename duplicated Directories e.g layout-sw300dp

Solution 2: (bit lengthy)

Create new resource directory: res > New > Android resource directory

Select Resource Type as layout

Add sw<N>dp in Directory name e.g layout-sw300dp and Hit OK

Navigate to app > src > main > res

Copy layouts XML file inside new directory

```<code>//repeat process for other qualifiers
</code>```

List of Qualifiers to support all screens:

layout-sw300dp

layout-sw330dp

layout-sw480dp

layout-sw600dp

layout-sw720dp

Testing:

This is how it gonna look like, if you did it right.

For more detail and examples, check: Android Application Development All-in-One For Dummies

Body:
The answer is already given by user5594218 but looks like you are still unclear. (maybe you are beginner)

So, here is the step by step guideline

Solution 1: (short and simple)

Navigate to app > src > main > res

Duplicate layout directory by copying and pasting

Rename duplicated Directories e.g layout-sw300dp

Solution 2: (bit lengthy)

Create new resource directory: res > New > Android resource directory

Select Resource Type as layout

Add sw<N>dp in Directory name e.g layout-sw300dp and Hit OK

Navigate to app > src > main > res

Copy layouts XML file inside new directory

//repeat process for other qualifiers

List of Qualifiers to support all screens:

layout-sw300dp

layout-sw330dp

layout-sw480dp

layout-sw600dp

layout-sw720dp

Testing:

This is how it gonna look like, if you did it right.

For more detail and examples, check: Android Application Development All-in-One For Dummies


问:
Attached iOS 11-style UISearchBar background image
I'd like to migrate my tableHeaderView based search bar to the new seamless search bar approach in iOS 11 by configuring navigationItem.searchController.

Since my navigation bar uses a custom background image, I'm wondering how to apply the same background image to the search bar as well. I tried

```<code>[navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarPromptBackground"] forBarMetrics:UIBarMetricsDefaultPrompt];
[searchBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
</code>```

to no avail. The search bar keeps the standard navigation bar background (with a barTintColor applied) but doesn't show the custom background image.

答:
I do a very similar thing in my application and discovered on IOS11 it's now broken. This is the code I had which sets my image across the Search and Scope bars, works fine up to IOS10:

```<code>[searchBarSearch setBackgroundImage:image];
[searchBarSearch setScopeBarBackgroundImage:image];
</code>```

I fixed it by adding this to the .plist

```<code>View controller-based status bar appearance = NO
</code>```

Now my bar is coloured and changes as I select different options as it did before IOS11.

Hope this helps you!

Plasma

Body:
I'd like to migrate my tableHeaderView based search bar to the new seamless search bar approach in iOS 11 by configuring navigationItem.searchController.

Since my navigation bar uses a custom background image, I'm wondering how to apply the same background image to the search bar as well. I tried

[navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarPromptBackground"] forBarMetrics:UIBarMetricsDefaultPrompt];
[searchBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];

to no avail. The search bar keeps the standard navigation bar background (with a barTintColor applied) but doesn't show the custom background image.

Body:
I do a very similar thing in my application and discovered on IOS11 it's now broken. This is the code I had which sets my image across the Search and Scope bars, works fine up to IOS10:

[searchBarSearch setBackgroundImage:image];
[searchBarSearch setScopeBarBackgroundImage:image];

I fixed it by adding this to the .plist

View controller-based status bar appearance = NO

Now my bar is coloured and changes as I select different options as it did before IOS11.

Hope this helps you!

Plasma


问:
Linux bash regex global flag
I want to match string with regex and echo matches.

```<code>if [[ "${PLUGS}"  =~  \"[a-zA-Z0-9.-]+ ]]; then
    echo ${BASH_REMATCH[*]}
else
    echo "nothing"
fi
</code>```

But i don't know how to add global flag. If i write regex like /\"[a-zA-Z0-9.-]+/g i get only first match. What i am doing wrong?

EDIT:
Samples data is mysql return of wordpress active plugins SELECT * FROM wp_options WHERE option_name = 'active_plugins';

```<code>a:31:{i:0;s:13:"AddMySite.php";i:1;s:19:"akismet/akismet.php";i:2;s:23:"all_in_one_seo_pack.php";i:3;s:16:"authenticate.php";i:4;s:28:"breadcrumb-navigation-xt.php";i:5;s:18:"codeautoescape.php";i:6;s:37:"contact-coldform/contact_coldform.php";i:7;s:32:"custom-query-string-reloaded.php";i:8;s:30:"customizable-post-listings.php";i:9;s:33:"dd-sitemap-gen/dd-sitemap-gen.php";i:10;s:20:"download-counter.php";i:11;s:13:"feedcount.php";i:12;s:13:"full_feed.php";i:13;s:15:"get-weather.php";i:14;s:36:"google-sitemap-generator/sitemap.php";i:15;s:13:"gravatars.php";i:16;s:19:"kill-admin-nags.php";i:17;s:18:"landingsites13.php";i:18;s:30:"nofollow-free/nofollowfree.php";i:19;s:17:"ol_feedburner.php";i:20;s:16:"plugins-used.php";i:21;s:22:"popularity-contest.php";i:22;s:39:"search-everything/search_everything.php";i:23;s:27:"simple-tags/simple-tags.php";i:24;s:26:"simple_recent_comments.php";i:25;s:18:"simple_twitter.php";i:26;s:25:"subscribe-to-comments.php";i:27;s:24:"the-excerpt-reloaded.php";i:28;s:18:"theme-switcher.php";i:29;s:9:"top10.php";i:30;s:16:"wp-db-backup.php";}
</code>```

答:
If all you want to do is extract all matches and echo them, consider using grep with -o/--only-matching flag:

```<code>$ grep -oE '("[a-zA-Z0-9.-]+")' <<<"${PLUGS}"
"AddMySite.php"
"authenticate.php"
"breadcrumb-navigation-xt.php"
"codeautoescape.php"
"custom-query-string-reloaded.php"
"customizable-post-listings.php"
"download-counter.php"
"feedcount.php"
"get-weather.php"
"gravatars.php"
"kill-admin-nags.php"
"landingsites13.php"
"plugins-used.php"
"popularity-contest.php"
"subscribe-to-comments.php"
"the-excerpt-reloaded.php"
"theme-switcher.php"
"top10.php"
"wp-db-backup.php"
</code>```

We also need to use -E/--extended-regexp, since your regex is POSIX ERE.

Or, to also handle the non-matching case (like in your question):

```<code>if ! grep -o -E '"([a-zA-Z0-9.-]+)"' <<<"${PLUGS}"; then
    echo "nothing"
fi
</code>```

Title: Linux bash regex global flag

Body:
I want to match string with regex and echo matches.

if [[ "${PLUGS}"  =~  \"[a-zA-Z0-9.-]+ ]]; then
    echo ${BASH_REMATCH[*]}
else
    echo "nothing"
fi

But i don't know how to add global flag. If i write regex like /\"[a-zA-Z0-9.-]+/g i get only first match. What i am doing wrong?

EDIT:
Samples data is mysql return of wordpress active plugins SELECT * FROM wp_options WHERE option_name = 'active_plugins';

a:31:{i:0;s:13:"AddMySite.php";i:1;s:19:"akismet/akismet.php";i:2;s:23:"all_in_one_seo_pack.php";i:3;s:16:"authenticate.php";i:4;s:28:"breadcrumb-navigation-xt.php";i:5;s:18:"codeautoescape.php";i:6;s:37:"contact-coldform/contact_coldform.php";i:7;s:32:"custom-query-string-reloaded.php";i:8;s:30:"customizable-post-listings.php";i:9;s:33:"dd-sitemap-gen/dd-sitemap-gen.php";i:10;s:20:"download-counter.php";i:11;s:13:"feedcount.php";i:12;s:13:"full_feed.php";i:13;s:15:"get-weather.php";i:14;s:36:"google-sitemap-generator/sitemap.php";i:15;s:13:"gravatars.php";i:16;s:19:"kill-admin-nags.php";i:17;s:18:"landingsites13.php";i:18;s:30:"nofollow-free/nofollowfree.php";i:19;s:17:"ol_feedburner.php";i:20;s:16:"plugins-used.php";i:21;s:22:"popularity-contest.php";i:22;s:39:"search-everything/search_everything.php";i:23;s:27:"simple-tags/simple-tags.php";i:24;s:26:"simple_recent_comments.php";i:25;s:18:"simple_twitter.php";i:26;s:25:"subscribe-to-comments.php";i:27;s:24:"the-excerpt-reloaded.php";i:28;s:18:"theme-switcher.php";i:29;s:9:"top10.php";i:30;s:16:"wp-db-backup.php";}

Body:
If all you want to do is extract all matches and echo them, consider using grep with -o/--only-matching flag:

$ grep -oE '("[a-zA-Z0-9.-]+")' <<<"${PLUGS}"
"AddMySite.php"
"authenticate.php"
"breadcrumb-navigation-xt.php"
"codeautoescape.php"
"custom-query-string-reloaded.php"
"customizable-post-listings.php"
"download-counter.php"
"feedcount.php"
"get-weather.php"
"gravatars.php"
"kill-admin-nags.php"
"landingsites13.php"
"plugins-used.php"
"popularity-contest.php"
"subscribe-to-comments.php"
"the-excerpt-reloaded.php"
"theme-switcher.php"
"top10.php"
"wp-db-backup.php"

We also need to use -E/--extended-regexp, since your regex is POSIX ERE.

Or, to also handle the non-matching case (like in your question):

if ! grep -o -E '"([a-zA-Z0-9.-]+)"' <<<"${PLUGS}"; then
    echo "nothing"
fi


问:
Which data type should I use for declaring number equal to 12000000000 in JAVA(JDK1.7)?
After using class BigInteger my program on platform showed Memory Limit Exceeded. </p>

答:
Long can handle that value. You should remember to type an L after the value. For example:

```<code>long value = 12000000000L;
</code>```

In the other hand, there is no limit for the BigInteger in theory due to it allocates the memory amount it needs, the limit is the available memory. You need to keep in mind BigInteger class is inmutable, so if you call add, multiply, divide or whatever it will return a new BigInteger instead of modifying the current one.
You may consider to implement your own data structure according to your needs. And also you may consider to post your code.

Body:
Long can handle that value. You should remember to type an L after the value. For example:

long value = 12000000000L;

In the other hand, there is no limit for the BigInteger in theory due to it allocates the memory amount it needs, the limit is the available memory. You need to keep in mind BigInteger class is inmutable, so if you call add, multiply, divide or whatever it will return a new BigInteger instead of modifying the current one.
You may consider to implement your own data structure according to your needs. And also you may consider to post your code.


问:
How to lower case entire column data in Google Cloud BigQuery
I am trying to find a "quick" way to lower case all the data (strings) in a table's column inside Google Cloud BigQuery.

Before going into building a script, I'm looking for more shorter way like Query.

How can I query BigQuery to lower case entire column?

答:
You can use an UPDATE statement:

```<code>UPDATE YourTable
SET string_column = LOWER(string_column)
WHERE true;
</code>```

Body:
You can use an UPDATE statement:

UPDATE YourTable
SET string_column = LOWER(string_column)
WHERE true;


问:
How to access View-Propperties in the ViewModel, using Caliburn.Micro
Until now I only used the basic features of the Caliburn.Micro Framework. But now I want and need to to get deeper into it.

Now I have the case that I need to access properties of the view (a Window) inside its view model.

The details are the following:
I customize the shell-window, using Microsoft's Window-Chrome (NuGet-Package: Microsoft.Windows.Chrome).
Now I need to check the value of the window's WindowState-Property, to set the property bound to its ResizeBorderThickness-property correctly.

How can I do that with the Caliburn.Micro Framework?

Additional infos:
.NET Framework: 4.5;
Caliburn.Micro: 3.1.0

答:
You don't directly access view properties in a view model. This effectively breaks the MVVM pattern and what it is all about. A view model shouldn't have any dependency upon the view.

What you could do is to bind the WindowState property of the window to a bool? source property of your view model and then perform any logic in the setter of the latter.


问:
Angular 2 : System.import() : Not working with full path
I am using below two different code to import a file runtime, one of them is working fine while other one throw error.

Working:

```<code> System.import('../../FileName.ts').then(classObj => {
        console.log(classObj);
 });
</code>```

Not Working:

```<code> System.import('App/Models/FileName.ts').then(classObj => {
        console.log(classObj);
 });
</code>```

It throw below error :

Can not find module 'App/Models/FileName.ts'

File Structure in which code is written and i also trying to import file from same structure:

(1) Code : ActivityModel.ts
(2) Importing : ApplicationModel.ts

Any one can help me to resolve above full path consideration issue.

答:
First of all, make sure you have latest version of webpack installed.Then you can try with following changes :

In webpack.config.js file change the following piece of code,

```<code>resolve: {
        extensions: ['.ts', '.js', 'css'],
        "modules": [
            "./node_modules",
            "content"
        ]
    },
</code>```

And

```<code> output: {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name].js',
            publicPath: 'dist/',
        }
</code>```

In .ts file change,

```<code>System.import('horizontal/models/FileName.ts').then(classObj => {
        console.log(classObj);
 });
</code>```

The resolver is used to load files relative to the app root and by
resolving content folder in webpack.config.js, file within that
folder can be accessed by absolute path as shown above.

(Now,path like content/horizontal/models/FileName.ts won't work)

The bundle file of FileName.ts will be created in dist folder and
will be loaded in the browser dynamically.Webpack will throw an error
in the browser, that it cannot load chunk 0 or something. This is
because, it tries to load the other files relative to the your HTML
file and not relative to the first JavaScript file you loaded via the
script tag.

To migrate this, you have to add a publicPath to your Webpack
config.

Hope,It wil help!

Body:
I am using below two different code to import a file runtime, one of them is working fine while other one throw error.

Working:

 System.import('../../FileName.ts').then(classObj => {
        console.log(classObj);
 });

Not Working:

 System.import('App/Models/FileName.ts').then(classObj => {
        console.log(classObj);
 });

It throw below error :

Can not find module 'App/Models/FileName.ts'

File Structure in which code is written and i also trying to import file from same structure:

(1) Code : ActivityModel.ts
(2) Importing : ApplicationModel.ts

Any one can help me to resolve above full path consideration issue.

Body:
First of all, make sure you have latest version of webpack installed.Then you can try with following changes :

In webpack.config.js file change the following piece of code,

resolve: {
        extensions: ['.ts', '.js', 'css'],
        "modules": [
            "./node_modules",
            "content"
        ]
    },

And

 output: {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name].js',
            publicPath: 'dist/',
        }

In .ts file change,

System.import('horizontal/models/FileName.ts').then(classObj => {
        console.log(classObj);
 });

The resolver is used to load files relative to the app root and by
resolving content folder in webpack.config.js, file within that
folder can be accessed by absolute path as shown above.

(Now,path like content/horizontal/models/FileName.ts won't work)

The bundle file of FileName.ts will be created in dist folder and
will be loaded in the browser dynamically.Webpack will throw an error
in the browser, that it cannot load chunk 0 or something. This is
because, it tries to load the other files relative to the your HTML
file and not relative to the first JavaScript file you loaded via the
script tag.

To migrate this, you have to add a publicPath to your Webpack
config.

Hope,It wil help!