问:
Jenkins version doesn't match
I have jenkins installed on an Ubuntu VM.

In the web interface I can see the version is

```<code>2.32.3.
</code>```

However, if I go to /home/bitnami/.jenkins/config.xml I see the version is 1.0 (there is this tag: <version>1.0</version>)

How can it be? am I looking in the wrong place?

Thanks

答:
You may have two versions installed, one in your system and one in your user account.
Did you installed by apt-get or wget?

When you execute the app, you may be running the Jenkins installed in your system and you are looking in your user HOME directory
Try (whereis jenkins and which jenkins) and execute this jenkins in your terminal to see if the version match.

Title: Jenkins version doesn't match

Body:
I have jenkins installed on an Ubuntu VM.

In the web interface I can see the version is

2.32.3.

However, if I go to /home/bitnami/.jenkins/config.xml I see the version is 1.0 (there is this tag: <version>1.0</version>)

How can it be? am I looking in the wrong place?

Thanks


来源: stackexchange

问:
Objective C editor for windows
I need to review the iphone application code written by my colleague, but unfortunately I have only a windows PC at present.

It would be nice if some one suggest a tool like 'source insight' which can be used to navigate through the obj-c code in a windows environment.

Regards,
Dhanesh

答: Try Notepad++, it seems to recognize Objective-C syntax.</p>

ContentLicense: CC BY-SA 2.5

Title: Objective C editor for windows


问:
Simple way to find if two different lists contain exactly the same elements?
What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.

e.g.

```<code>List list1
List<String> list2;
// ... construct etc

list1.add("A");
list2.add("A");
// the function, given these two lists, should return true
</code>```

There's probably something staring me in the face I know :-)

EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.

答:
In addition to Laurence's answer, if you also want to make it null-safe:</p>

```<code>private static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    if (list1 == null)
        return list2==null;
    if (list2 == null)
        return list1 == null;
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.

e.g.

List list1
List<String> list2;
// ... construct etc

list1.add("A");
list2.add("A");
// the function, given these two lists, should return true

There's probably something staring me in the face I know :-)

EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.

Body:
In addition to Laurence's answer, if you also want to make it null-safe:

private static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    if (list1 == null)
        return list2==null;
    if (list2 == null)
        return list1 == null;
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

ContentLicense: CC BY-SA 3.0


问:
SQL query to check all records of employee
I wanted to check all employees and location. One location is having multiple employees. So my condition is i want all locations where all employee status is inactive.

Like eg emp table is

```<code>EmpId loc status
123  ABC active
124 ABC active
125  ABC inactive
234  PQR inactive
</code>```

Result should be

```<code>Empid loc status
234 PQR inactive
</code>```

答:
If you want the location where all statuses are inactive, I would recommend group by:

```<code>select loc
from t
group by loc
having min(status) = max(status) and min(status) = 'inactive';
</code>```

Body:
I wanted to check all employees and location. One location is having multiple employees. So my condition is i want all locations where all employee status is inactive.

Like eg emp table is

EmpId loc status
123  ABC active
124 ABC active
125  ABC inactive
234  PQR inactive

Result should be

Empid loc status
234 PQR inactive

Body:
If you want the location where all statuses are inactive, I would recommend group by:

select loc
from t
group by loc
having min(status) = max(status) and min(status) = 'inactive';


问:
laravel throwing MethodNotAllowedHttpException
I am trying to get something very basic running. I am used to CI and now learning Laravel 4, and their docs are not making it easy! Anyways, I am trying to create a login form and just make sure that data is posted successfully by printing it in the next form. I am getting this exception:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException

and my MemberController.php:

```<code>    public function index()
    {
        if (Session::has('userToken'))
        {
            /*Retrieve data of user from DB using token & Load view*/
            return View::make('members/profile');
        }else{
            return View::make('members/login');
        }
    }

    public function validateCredentials()
    {
        if(Input::post())
        {
            $email = Input::post('email');
            $password = Input::post('password');
            return "Email: " . $email . " and Password: " . $password;
        }else{
            return View::make('members/login');
        }
    }
</code>```

and routes has:

```<code>Route::get('/', function()
{
    return View::make('hello');
});

Route::get('/members', 'MemberController@index');
Route::get('/validate', 'MemberController@validateCredentials');
</code>```

and finally my view login.php has this form direction:

```<code><?php echo Form::open(array('action' => 'MemberController@validateCredentials')); ?>
</code>```

Any help will be greatly appreciated.

答:
well when i had these problem i faced 2 code errors

```<code>{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}
</code>```

i corrected it by doing this

```<code>{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}
</code>```

so just to expatiate i changed the form model to open and also the route where wrongly placed in square braces.

Body:
I am trying to get something very basic running. I am used to CI and now learning Laravel 4, and their docs are not making it easy! Anyways, I am trying to create a login form and just make sure that data is posted successfully by printing it in the next form. I am getting this exception:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException

and my MemberController.php:

    public function index()
    {
        if (Session::has('userToken'))
        {
            /*Retrieve data of user from DB using token & Load view*/
            return View::make('members/profile');
        }else{
            return View::make('members/login');
        }
    }

    public function validateCredentials()
    {
        if(Input::post())
        {
            $email = Input::post('email');
            $password = Input::post('password');
            return "Email: " . $email . " and Password: " . $password;
        }else{
            return View::make('members/login');
        }
    }

and routes has:

Route::get('/', function()
{
    return View::make('hello');
});

Route::get('/members', 'MemberController@index');
Route::get('/validate', 'MemberController@validateCredentials');

and finally my view login.php has this form direction:

<?php echo Form::open(array('action' => 'MemberController@validateCredentials')); ?>

Any help will be greatly appreciated.

Body:
well when i had these problem i faced 2 code errors

{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}

i corrected it by doing this

{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}

so just to expatiate i changed the form model to open and also the route where wrongly placed in square braces.


问:
CSS padding overlapping parent element
My HTML:

```<code><table style="width:100%;">
    <tbody>
        <tr style="cursor:pointer; border-bottom:1px solid #ACACAC; height:60px;">
            <td style="text-align:right; vertical-align:middle; padding:10px 10px 10px 0px;">
                <span style="color:#F87E20;">Copy</span>
                <div style="display:inline; color:#ACACAC;"> | </div>
                <span style="color:#F87E20;">Export</span>
                <div style="display:inline; color:#ACACAC;"> | </div>
                <span style="color:#F87E20;">Delete</span>
            </td>
        </tr>
    </tbody>
</table>
</code>```

The result:

This is all fine, and is working wonderfully. I want to make some QOL changes, though, and while looking into some of the changes I wanted to make, ran into something that is confusing me quite a bit.

The entire row is clickable, as well as the Copy, Export and Delete spans. This becomes a problem when I try to click on Export, but miss by 2 or 3 pixels, and instead navigate away from this area. I wanted to make the clickable area for the spans bigger, so I gave the a style property like so: padding:10px 0px 10px 0px;

The padding works as intended, enlarging the clickable area around the spans, making it easier to click on them. However, I was expecting the padding to also make the entire row taller, but instead it's as if the spans' padding is just flowing over the padding on the parent.

Here are some images to help explain the situation:
Parent:

And Child:

I don't understand why the child's padding is flowing outside it's container, and I don't want to go on in this direction without understanding what's going on. I was wondering if anyone could please help me understand what's happening here?

答:
Your spans are inline elements. Top and bottom padding is ignored in case of inline elements.
By default, spans are inline, and divs are block. However, you can always override these with display: block; or display: inline;. Block elements (also inline-blocks) have full padding support.
See:

table {
  width: 100%;
  border-bottom: 1px solid #ACACAC;
}

tr {
  cursor: pointer;
  height: 60px;
}

td {
  text-align: right;
  vertical-align: middle;
  padding: 10px 10px 10px 0px;
  background-color: #e0c000;
}

span {
  display: inline-block;
  color: #F87E20;
  background-color: #f0e000;
}

.padded {
  padding: 10px 0 10px;
}

div {
  display: inline;
  color: #ACACAC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>
        <span>Copy</span>
        <div> | </div>
        <span class="padded">Export</span>
        <div> | </div>
        <span>Delete</span>
      </td>
    </tr>
  </tbody>
</table></code>```

See also this article for more on this.

Title: CSS padding overlapping parent element

Body:
My HTML:

                Copy

 |

                Export

 |

                Delete

The result:

This is all fine, and is working wonderfully. I want to make some QOL changes, though, and while looking into some of the changes I wanted to make, ran into something that is confusing me quite a bit.

The entire row is clickable, as well as the Copy, Export and Delete spans. This becomes a problem when I try to click on Export, but miss by 2 or 3 pixels, and instead navigate away from this area. I wanted to make the clickable area for the spans bigger, so I gave the a style property like so: padding:10px 0px 10px 0px;

The padding works as intended, enlarging the clickable area around the spans, making it easier to click on them. However, I was expecting the padding to also make the entire row taller, but instead it's as if the spans' padding is just flowing over the padding on the parent.

Here are some images to help explain the situation:
Parent:

And Child:

I don't understand why the child's padding is flowing outside it's container, and I don't want to go on in this direction without understanding what's going on. I was wondering if anyone could please help me understand what's happening here?

Body:
Your spans are inline elements. Top and bottom padding is ignored in case of inline elements.
By default, spans are inline, and divs are block. However, you can always override these with display: block; or display: inline;. Block elements (also inline-blocks) have full padding support.
See:

table {
  width: 100%;
  border-bottom: 1px solid #ACACAC;
}

tr {
  cursor: pointer;
  height: 60px;
}

td {
  text-align: right;
  vertical-align: middle;
  padding: 10px 10px 10px 0px;
  background-color: #e0c000;
}

span {
  display: inline-block;
  color: #F87E20;
  background-color: #f0e000;
}

.padded {
  padding: 10px 0 10px;
}

div {
  display: inline;
  color: #ACACAC;
}

<table>
  <tbody>
    <tr>
      <td>
        <span>Copy</span>
        <div>&nbsp;|&nbsp;</div>
        <span class="padded">Export</span>
        <div>&nbsp;|&nbsp;</div>
        <span>Delete</span>
      </td>
    </tr>
  </tbody>
</table>

See also this article for more on this.


问:
Thymeleaf nested list not working
I'm trying to get the nested list working in Thymeleaf. I have tried not nesting the list and the entry.value works. However when I start nesting it, it doesnt show up in the webpage. Students is a Map<String, ArrayList<String>>.

```<code><ul th:each="entry : ${students}">
    <li th:text="${entry.key}">
        <ul>
            <li th:text="${entry.value[0]}"></li>
            <li th:text="${entry.value[1]}"></li>
            <li th:text="${entry.value[2]}"></li>
        </ul>
    </li>
</ul>
</code>```

Currently it looks like this.

答:
th:text attributes replace all any child html elements with the contents of the th:text expression.  You have to move the th:text into it's own tag, something like this:

```

Title: Thymeleaf nested list not working

Body:
I'm trying to get the nested list working in Thymeleaf. I have tried not nesting the list and the entry.value works. However when I start nesting it, it doesnt show up in the webpage. Students is a Map<String, ArrayList<String>>.

Currently it looks like this.

Body:
th:text attributes replace all any child html elements with the contents of the th:text expression.  You have to move the th:text into it's own tag, something like this:

<ul th:each="entry: ${students}">
    <li>
        <span th:text="${entry.key}" />

        <ul>
            <li th:text="${entry.value[0]}" />
            <li th:text="${entry.value[1]}" />
            <li th:text="${entry.value[2]}" />
        </ul>
    </li>
</ul>


问:
Reading values from application.properties Spring Boot
My Spring boot app has this application structure:

src

main

java

resources

application.properties

This is my application.properties file:

```<code>logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java
</code>```

I have a class which requires the use of that language=java property. This is how I am trying to use it:

```<code>public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}
</code>```

That printed value is always "null" for some reason! I have also tried putting this on top of the class declaration:

```<code>@PropertySource(value = "classpath:application.properties")
</code>```

答:
create you beans

```<code>@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationBeansConfig {

    @Autowired
    Environment env;

    @Bean
    public IApplicationBeanService getService(){
        return new ApplicationBeansService(env);
    }
}
</code>```

and then in service costructor

```<code>@Service
public class ApplicationBeansService implements IApplicationBeanService {
...
   public ApplicationBeansService(Environment env){
      ...
      String value = env.getProperty("your.value")
      ...
   }
...
}
</code>```

don't forget fill your application.properties:

```<code>your.value = some-string-value
</code>```

Body:
My Spring boot app has this application structure:

src

main

java

resources

application.properties

This is my application.properties file:

logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java

I have a class which requires the use of that language=java property. This is how I am trying to use it:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

That printed value is always "null" for some reason! I have also tried putting this on top of the class declaration:

@PropertySource(value = "classpath:application.properties")

Body:
create you beans

@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationBeansConfig {

    @Autowired
    Environment env;

    @Bean
    public IApplicationBeanService getService(){
        return new ApplicationBeansService(env);
    }
}

and then in service costructor

@Service
public class ApplicationBeansService implements IApplicationBeanService {
...
   public ApplicationBeansService(Environment env){
      ...
      String value = env.getProperty("your.value")
      ...
   }
...
}

don't forget fill your application.properties:

your.value = some-string-value


问:
Angular response is undefined
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

```<code><html ng-app="myViewer">
<head>
<script data-require="angular.js@*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>

<body ng-controller="MyController">
    {{ result.id }}
    {{ err }}
</body>

<script type="text/javascript">
(function() {

    var app = angular.module("myViewer", []);

    var MyController = function($scope, $http)
    {
        $http.get("https://api.github.com/users/angular")
        .then(function1, onerr);

        var function1 = function(response)
        {
            $scope.result = response.data;
        }
        var onerr = function(reason)
        {
            $scope.err = "nightmare";
        }

    }

    app.controller("MyController", ["$scope", "$http", MyController]);
}());

</script>
</html>
</code>```

I expect the result to be the id that you can see by copying that link in your browser.

答:
I think your promise is wrong.

```<code>  $http.get('https://api.github.com/users/angular').then(function(response){
    $scope.result = response.data;
  })
</code>```

See same HTTP call working below:

https://plnkr.co/edit/8JqZ5NukHnHWGPxZ0GRr

Title: Angular response is undefined

Body:
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

    {{ result.id }}
    {{ err }}

I expect the result to be the id that you can see by copying that link in your browser.

Body:
I think your promise is wrong.

  $http.get('https://api.github.com/users/angular').then(function(response){
    $scope.result = response.data;
  })

See same HTTP call working below:

https://plnkr.co/edit/8JqZ5NukHnHWGPxZ0GRr


问:
How do I pass gson JsonObject between fragments in the same activity
I'm refactoring my app and currently rewriting two activities as two fragments in the same activity. This was how I used to send gson JsonObject from the first activity to the second activity:

Activity1:

```<code>Intent intent = new Intent(this, Activity2.class);
intent.putExtra("form", gson.toJson(form));
startActivity(intent);
</code>```

Activity2:

```<code>intent = getIntent();
form = gson.fromJson(intent.getStringExtra("form"), JsonObject.class);
</code>```

Now that I've rewritten Activity1 and Activity2 as fragments in the same activity, is there a similar approach that I can use to send and retrieve data in the fragments? I just find using intents very intuitive, but I figured fragments use a different way of communicating with one another.

答:
```<code>Bundle args = new Bundle();
args.putString("form", gson.toJson(form));
secondFragment.setArguments(args);
</code>```

and in your targeted Fragment :

```<code>getArguments().getString("form");
</code>```

Body:
I'm refactoring my app and currently rewriting two activities as two fragments in the same activity. This was how I used to send gson JsonObject from the first activity to the second activity:

Activity1:

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("form", gson.toJson(form));
startActivity(intent);

Activity2:

intent = getIntent();
form = gson.fromJson(intent.getStringExtra("form"), JsonObject.class);

Now that I've rewritten Activity1 and Activity2 as fragments in the same activity, is there a similar approach that I can use to send and retrieve data in the fragments? I just find using intents very intuitive, but I figured fragments use a different way of communicating with one another.

Body:
Bundle args = new Bundle();
args.putString("form", gson.toJson(form));
secondFragment.setArguments(args);

and in your targeted Fragment :

getArguments().getString("form");


问:
Which benefits Smarty gives when using with PHP or better to use pure PHP?
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

```<code>// adding a guestbook entry
$guestbook->displayForm();
</code>```

to

```<code>// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));
</code>```

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

答:
I agree that it causes overhead, I worked in a project that used Smarty and it was a nightmare. The two benefits you can get are

1: designers that are not familiar with PHP can work out with your HTML without coding skills required. But doesn't that mean they will eventually need to study Smarty first? I really don't see any point.

2: For template separation: you can use PHP alternative syntax the same way you would use Smarty, without losing the power of that giant programming language. Example of alternative syntax:

```<code><div>Product list</div>
<?php foreach($products as $product): ?>

<div>Product: <?php echo $product->name; ?> </div>
<div>Price: <?php echo $product->price; ?> </div>
<?php if($product->discountPercentage): ?>
<div>
Discount: <?php echo $product->price * $product->discountPercentage / 100; ?> off! </div>
<?php endif; ?>

<?php endforeach; ?>
</code>```

Body:
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

// adding a guestbook entry
$guestbook->displayForm();

to

// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

Body:
I agree that it causes overhead, I worked in a project that used Smarty and it was a nightmare. The two benefits you can get are

1: designers that are not familiar with PHP can work out with your HTML without coding skills required. But doesn't that mean they will eventually need to study Smarty first? I really don't see any point.

2: For template separation: you can use PHP alternative syntax the same way you would use Smarty, without losing the power of that giant programming language. Example of alternative syntax:

<div>Product list</div>
<?php foreach($products as $product): ?>

<div>Product: <?php echo $product->name; ?> </div>
<div>Price: <?php echo $product->price; ?> </div>
<?php if($product->discountPercentage): ?>
<div>
Discount: <?php echo $product->price * $product->discountPercentage / 100; ?> off! </div>
<?php endif; ?>

<?php endforeach; ?>


问:
Instagram relationship endpoint that modify the relationship with target user
I'm developing an app that uses instagram API, when I'm trying to follow or doing other action to another user programmatically with POST method

```<code>https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN
</code>```

the response is

```<code>This action is invalid. Please supply a valid action from the following: follow, unfollow, approve, ignore, block, unblock
</code>```

P.S:

the other user already added in sandbox mode

scope used are : [.basic,.followerList,.publicContent,.relationships] and access tocken and user id are tested and valid

I'm using this library https://github.com/AnderGoig/SwiftInstagram to avoid handling http requests and this library added the action parameter with 'follow' correctly with post method

答: If anybody face the problem, the solution is to send the action parameter in the body not in url, I'm using the library like I said so I thought it's ok but when testing it with postman and send the parameter in body it returns the result as expected</p>

Body:
I'm developing an app that uses instagram API, when I'm trying to follow or doing other action to another user programmatically with POST method

https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN

the response is

This action is invalid. Please supply a valid action from the following: follow, unfollow, approve, ignore, block, unblock

P.S:

the other user already added in sandbox mode

scope used are : [.basic,.followerList,.publicContent,.relationships] and access tocken and user id are tested and valid

I'm using this library https://github.com/AnderGoig/SwiftInstagram to avoid handling http requests and this library added the action parameter with 'follow' correctly with post method


问:
Error Parsing the JSON output of Google places API
I am trying to parse the JSON output after a successful JSON fetch using the google places API, though the code shows no error and I don't even get the parsed response.
  Here is the JSON parsing code to show it on a listview.

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DisplayListView extends AppCompatActivity {

JSONObject jsonObject;
JSONArray jsonArray;
HotelAdapter hotelAdapter;
ListView listView;

String JSONSTR;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_list_view);

   this.JSONSTR=getIntent().getStringExtra("JSONmsg");
    Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();

    listView=(ListView)findViewById(R.id.HotelListView);

    hotelAdapter=new HotelAdapter(this,R.layout.row_layout);

    listView.setAdapter(hotelAdapter);

    try {
        jsonObject=new JSONObject(JSONSTR);
        jsonArray=jsonObject.getJSONArray("results");
        int count=0;

        String name,rating,types,vicinity;

        while (count<jsonArray.length()){
            JSONObject jo=jsonArray.getJSONObject(count);
            name=jo.getString("name");
            rating=jo.getString("rating");
            types=jo.getJSONArray("types").toString();
            vicinity=jo.getString("vicinity");

            Hotels hotels=new Hotels(name,rating,types,vicinity);
            hotelAdapter.add(hotels);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
</code>```

}

and the corresponding JSON fetching code is ->

```<code>import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Hotel_lists extends AppCompatActivity {
    String jsonStr,JSONSTR;
    JSONObject jsonObject;
    JSONArray jsonArray;
    HotelAdapter hotelAdapter;
    ListView listView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hotel_lists);

}

public void getJson(View view){
    new BackTask().execute();

}

class BackTask extends AsyncTask<Void,Void,String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
       jsonStr="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=20.296059,85.824540&radius=500&type=hotel&key=mykey";

    }
    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url=new URL(jsonStr);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader((new InputStreamReader(inputStream)));

            StringBuilder stringBuilder=new StringBuilder();
            while((jsonStr = bufferedReader.readLine())!=null){
                stringBuilder.append(jsonStr);

            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView textView=(TextView)findViewById(R.id.locText);
        textView.setText(result);
        JSONSTR=result;
        Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();
    }
}

public void parseJson(View view){
    if(JSONSTR==null){
        Toast.makeText(getApplicationContext(),"error gettingg result",Toast.LENGTH_SHORT).show();

    }
    else{
        Toast.makeText(getApplicationContext()," gettingg result",Toast.LENGTH_SHORT).show();
       Intent intent=new Intent(this,DisplayListView.class);

       intent.putExtra("JSONmsg",JSONSTR.trim());
       startActivity(intent);

    }
}
</code>```

}

Here is the json response..

```<code>{
   "html_attributions" : [],
   "next_page_token" : "CqQCGwEAAHzgWjXXoyd7FnMd3tjkgYMbo4quo3d4CZlw_HLR6yLWPbo929niHRbwAW-Ma-DaB-iqsTydif_5ggetITyGHy1jvP3r1zwD4RHdKQRYDdh8lk7wU0kiCTxp_xo9vnnrhD-Ku0LJ3ljI9Q89yvJRmFwG53opXjD1JIXd3QhWA69zUw_Dp8CvF4YJbmijDL3CKDpWRSFYRHYsOxVo8wX5ZNDBA-0JZMEeJiS77a3KsH-5miVgyHzfdbovhEctP9Yv8fvdOW1ugBWTyCpE8tdXIAIGsVpUhYmf0FE-A99LlblrttGSiVkrWCw0bXO_tyY0O_KDA-mBavlNJnDexOH3atvQz6xaMJixjwLfrzLkSA1LPc2A8EN0Q6eTB-PjOoRgRxIQqNzXJZnQ13QQebkTSF1GiBoUusO5z_TqyZlClWBh71nydS6A2gA",
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 22.572646,
               "lng" : 88.36389500000001
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 22.5739949802915,
                  "lng" : 88.36524398029151
               },
               "southwest" : {
                  "lat" : 22.5712970197085,
                  "lng" : 88.3625460197085
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "ab3c682ca2e068c91d806c8a443b5f7bd45145aa",
         "name" : "Sugar & Spice",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 480,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/104833748119464497887/photos\"\u003eSugar & Spice\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAa7VFOzF-sjipV8a4qyD8B6v31XOwgT91SLLOmGLNVRHcWNhkhPNeOp1fTdH8yWUjhtaNEcAmnYg3G7LBI_BGeb2sVLMqNc4JH1xolP7_x8oLKkmo5XKJBtQ3-2kc7-ZIEhBUdWsuWoprBvTAfkL1_cj_GhRknB1JQe1eCTZjUNOpPdde_AV1EA",
               "width" : 640
            }
         ],
         "place_id" : "ChIJe6yzIVN2AjoRpnq6Ojv2HoM",
         "rating" : 3.2,
         "reference" : "CmRSAAAA8t4Ry-gd5HGWXZ7tN9wQNGC09gB4izm0nP1s-EGIdrbcAjCXQ7WTNzdbP2mC-x56ns8P0_19u0dIbNqk_-hCB0yYvjBL6OMx2HHAmejK8KbGDs3MGa1wiG_f6TiKAKs4EhD07l9cCpEERshxnRZGzaeqGhRDo92OY4kXdzuKRR-vMgaKjxBU7g",
         "scope" : "GOOGLE",
         "types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
         "vicinity" : "78/B, Acharya Prafulla Chandra Road, Sealdah, Baithakkhana, Kolkata"
      },
</code>```

so please help me to find out the error as android studio shows nothing though I can assure that I am having successful JSON fetch, but ultimately I am not able to show the final result..

答:
So you didn't called notifyDatasetChanged() after adding data to your dataset?
Do that and see it works or not please.</p>

Body:
I am trying to parse the JSON output after a successful JSON fetch using the google places API, though the code shows no error and I don't even get the parsed response.
  Here is the JSON parsing code to show it on a listview.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DisplayListView extends AppCompatActivity {

JSONObject jsonObject;
JSONArray jsonArray;
HotelAdapter hotelAdapter;
ListView listView;

String JSONSTR;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_list_view);

   this.JSONSTR=getIntent().getStringExtra("JSONmsg");
    Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();

    listView=(ListView)findViewById(R.id.HotelListView);

    hotelAdapter=new HotelAdapter(this,R.layout.row_layout);

    listView.setAdapter(hotelAdapter);

    try {
        jsonObject=new JSONObject(JSONSTR);
        jsonArray=jsonObject.getJSONArray("results");
        int count=0;

        String name,rating,types,vicinity;

        while (count<jsonArray.length()){
            JSONObject jo=jsonArray.getJSONObject(count);
            name=jo.getString("name");
            rating=jo.getString("rating");
            types=jo.getJSONArray("types").toString();
            vicinity=jo.getString("vicinity");

            Hotels hotels=new Hotels(name,rating,types,vicinity);
            hotelAdapter.add(hotels);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

}

and the corresponding JSON fetching code is ->

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Hotel_lists extends AppCompatActivity {
    String jsonStr,JSONSTR;
    JSONObject jsonObject;
    JSONArray jsonArray;
    HotelAdapter hotelAdapter;
    ListView listView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hotel_lists);

}

public void getJson(View view){
    new BackTask().execute();

}

class BackTask extends AsyncTask<Void,Void,String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
       jsonStr="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=20.296059,85.824540&radius=500&type=hotel&key=mykey";

    }
    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url=new URL(jsonStr);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader((new InputStreamReader(inputStream)));

            StringBuilder stringBuilder=new StringBuilder();
            while((jsonStr = bufferedReader.readLine())!=null){
                stringBuilder.append(jsonStr);

            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView textView=(TextView)findViewById(R.id.locText);
        textView.setText(result);
        JSONSTR=result;
        Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();
    }
}

public void parseJson(View view){
    if(JSONSTR==null){
        Toast.makeText(getApplicationContext(),"error gettingg result",Toast.LENGTH_SHORT).show();

    }
    else{
        Toast.makeText(getApplicationContext()," gettingg result",Toast.LENGTH_SHORT).show();
       Intent intent=new Intent(this,DisplayListView.class);

       intent.putExtra("JSONmsg",JSONSTR.trim());
       startActivity(intent);

    }
}

}

Here is the json response..

{
   "html_attributions" : [],
   "next_page_token" : "CqQCGwEAAHzgWjXXoyd7FnMd3tjkgYMbo4quo3d4CZlw_HLR6yLWPbo929niHRbwAW-Ma-DaB-iqsTydif_5ggetITyGHy1jvP3r1zwD4RHdKQRYDdh8lk7wU0kiCTxp_xo9vnnrhD-Ku0LJ3ljI9Q89yvJRmFwG53opXjD1JIXd3QhWA69zUw_Dp8CvF4YJbmijDL3CKDpWRSFYRHYsOxVo8wX5ZNDBA-0JZMEeJiS77a3KsH-5miVgyHzfdbovhEctP9Yv8fvdOW1ugBWTyCpE8tdXIAIGsVpUhYmf0FE-A99LlblrttGSiVkrWCw0bXO_tyY0O_KDA-mBavlNJnDexOH3atvQz6xaMJixjwLfrzLkSA1LPc2A8EN0Q6eTB-PjOoRgRxIQqNzXJZnQ13QQebkTSF1GiBoUusO5z_TqyZlClWBh71nydS6A2gA",
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 22.572646,
               "lng" : 88.36389500000001
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 22.5739949802915,
                  "lng" : 88.36524398029151
               },
               "southwest" : {
                  "lat" : 22.5712970197085,
                  "lng" : 88.3625460197085
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "ab3c682ca2e068c91d806c8a443b5f7bd45145aa",
         "name" : "Sugar & Spice",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 480,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/104833748119464497887/photos\"\u003eSugar & Spice\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAa7VFOzF-sjipV8a4qyD8B6v31XOwgT91SLLOmGLNVRHcWNhkhPNeOp1fTdH8yWUjhtaNEcAmnYg3G7LBI_BGeb2sVLMqNc4JH1xolP7_x8oLKkmo5XKJBtQ3-2kc7-ZIEhBUdWsuWoprBvTAfkL1_cj_GhRknB1JQe1eCTZjUNOpPdde_AV1EA",
               "width" : 640
            }
         ],
         "place_id" : "ChIJe6yzIVN2AjoRpnq6Ojv2HoM",
         "rating" : 3.2,
         "reference" : "CmRSAAAA8t4Ry-gd5HGWXZ7tN9wQNGC09gB4izm0nP1s-EGIdrbcAjCXQ7WTNzdbP2mC-x56ns8P0_19u0dIbNqk_-hCB0yYvjBL6OMx2HHAmejK8KbGDs3MGa1wiG_f6TiKAKs4EhD07l9cCpEERshxnRZGzaeqGhRDo92OY4kXdzuKRR-vMgaKjxBU7g",
         "scope" : "GOOGLE",
         "types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
         "vicinity" : "78/B, Acharya Prafulla Chandra Road, Sealdah, Baithakkhana, Kolkata"
      },

so please help me to find out the error as android studio shows nothing though I can assure that I am having successful JSON fetch, but ultimately I am not able to show the final result..


问:
Angular2 ContentChild with multiple selectors
Is this possible to set multiple selectors in ContentChild?

For example, I'm looking for a solution similar to it:

```<code>@ContentChild(Case1 | Case2)
</code>```

To be able to get Case2 values if Case1 aren't available.

Without this solution I must create two seperate ContentChild's.

```<code>@ContentChild(Case1)
@ContentChild(Case2)
</code>```

答: As far as I know you can simply use @ContentChildren which is some kind of array. Here take a look at docs. It has QueryList type which can be easly converted to array by using map or toArray function, and then all you need to do is what element is exists, also you can subscribe for it's changes via changes property which is Observable.

Body:
Is this possible to set multiple selectors in ContentChild?

For example, I'm looking for a solution similar to it:

@ContentChild(Case1 | Case2)

To be able to get Case2 values if Case1 aren't available.

Without this solution I must create two seperate ContentChild's.

@ContentChild(Case1)
@ContentChild(Case2)


问:
Azure - Storage queue message renewal
We are using azure web job for processing the messages in azure storage queue. After the 5 unsuccessful attempts messages are moved to the Poisson queue. Instead of that i want to process the message further more until the message have been processed successfully.

kindly assist me on the same.

答:
You can configure the maximum number of retries (default is 5) before a message is sent to the poison queue. You can add an 'int dequeCount' parameter to your method to check the number of times it has been called and base your decisions on that.

Having said that you should definitely have some error handling strategy in place. Just trying indefinitely till you succeed is a recipe for failure.

Title: Azure - Storage queue message renewal


问:
Code runs but Tkinter window stays blank
The problem i'm having is that it even though it executes, the tkinter window remains blank. and as a side issue the window doesn't refresh to update the Actions checkbutton.

```<code>from tkinter import *
Pieces = {}
Actions =[]
class GameCreation(Frame):
    def __init(self,master):
        super(GameCreation,self).__init__(master)
        self.grid()
        self.CreatePiece()
   #Creating pieces function
    def CreatePiece(self):
        Label(self,text ="What piece are we working with?").grid(row =0,
                                                             column = 0,
                                                             sticky = W)
        self.piece_entry = Entry(self)
        self.piece_entry.grid(row =0,
                          column = 1,
                          sticky = W)

        Label (self, text = "Tick all the actions which the piece has").grid (row =1,
                                                                          column = 0,
                                                                          sticky = W)
        self.Actions = BooleanVar()
        self.Actions.set(None)

    column = 0
    row = 4
        for action in Actions:
            Checkbutton(self,text = action, variable = self.checkButton, value = action).grid( row = row,
                                                                                column = column,
                                                                                sticky = W)
            if column == 5:
                row +=1
                column = 0
            else:
                column +=1
        Button(self,text = "Add action", command = self.AddAction).grid(row = 1,
                                                                    column = 0,
                                                                    sticky = W)
        self.action_entry = Entry(self)
        self.action_entry.grid(row = 1, column = 1, sticky = W)

        Button (self, text = "Create piece and it's actions", command = Add_to_dict).grid(row =2,
                                                                                column = 0,
                                                                                sticky = W)
        self.Add_dict = Text(self, width =10, height = 2, wrap = WORD)
        self.Add_dict.grid( row = 3, column = 0, columnspan = 4)
</code>```

This function should add to the Actions list

```<code>    def addAction(self):
        action = self.action_entry.get()
        Actions.append(action)
</code>```

This function should just print the name of the piece and the actions chosen for it

```<code>    def Add_to_dict(self):
        actions = Actions.get()
        piece = piece_entry.get()
        rules = piece, ":", actions
        self.Add_dict.delete(0.0,END)
        self.Add_dict.insert(0.0,rules)
</code>```

答:
You need to use __init__, not __init

Also, if you're using BooleanVar, you must set it to True or False, not None:

```<code>self.Actions.set(False)
</code>```

Also, you have a method named addAction but you are calling it like self.AddAction, and you have a method named Add_to_dict that you are calling like Add_to_dict rather than self.Add_to_dict.

And finally, you don't appear to be creating an instance of GameCreation anywhere.

Body:
The problem i'm having is that it even though it executes, the tkinter window remains blank. and as a side issue the window doesn't refresh to update the Actions checkbutton.

from tkinter import *
Pieces = {}
Actions =[]
class GameCreation(Frame):
    def __init(self,master):
        super(GameCreation,self).__init__(master)
        self.grid()
        self.CreatePiece()
   #Creating pieces function
    def CreatePiece(self):
        Label(self,text ="What piece are we working with?").grid(row =0,
                                                             column = 0,
                                                             sticky = W)
        self.piece_entry = Entry(self)
        self.piece_entry.grid(row =0,
                          column = 1,
                          sticky = W)

        Label (self, text = "Tick all the actions which the piece has").grid (row =1,
                                                                          column = 0,
                                                                          sticky = W)
        self.Actions = BooleanVar()
        self.Actions.set(None)

    column = 0
    row = 4
        for action in Actions:
            Checkbutton(self,text = action, variable = self.checkButton, value = action).grid( row = row,
                                                                                column = column,
                                                                                sticky = W)
            if column == 5:
                row +=1
                column = 0
            else:
                column +=1
        Button(self,text = "Add action", command = self.AddAction).grid(row = 1,
                                                                    column = 0,
                                                                    sticky = W)
        self.action_entry = Entry(self)
        self.action_entry.grid(row = 1, column = 1, sticky = W)

        Button (self, text = "Create piece and it's actions", command = Add_to_dict).grid(row =2,
                                                                                column = 0,
                                                                                sticky = W)
        self.Add_dict = Text(self, width =10, height = 2, wrap = WORD)
        self.Add_dict.grid( row = 3, column = 0, columnspan = 4)

This function should add to the Actions list

    def addAction(self):
        action = self.action_entry.get()
        Actions.append(action)

This function should just print the name of the piece and the actions chosen for it

    def Add_to_dict(self):
        actions = Actions.get()
        piece = piece_entry.get()
        rules = piece, ":", actions
        self.Add_dict.delete(0.0,END)
        self.Add_dict.insert(0.0,rules)

Body:
You need to use __init__, not __init

Also, if you're using BooleanVar, you must set it to True or False, not None:

self.Actions.set(False)

Also, you have a method named addAction but you are calling it like self.AddAction, and you have a method named Add_to_dict that you are calling like Add_to_dict rather than self.Add_to_dict.

And finally, you don't appear to be creating an instance of GameCreation anywhere.


问:
Fault in memory management by test in valgrind?
I've written a C programm to compare the runtime of insertion sort and count sort, but it can't pass the valgrind test because this programm will read from non-initialized memory.
Here is my code, which could probably be false, and I want to know why I have this problem:

```<code>void count_sort_write_output_array(int output_array[], int len, int count_array[], int* befehle) {
    int k=0;
    //use count array to output result
    for (int j=0;j<=MAX_VALUE;j++) {
        //add befehle
        //(j++)
        (*befehle)++;
        for (int i=0; i<count_array[j]; i++) {
            output_array[k] = j;
            k++;
            //add befehle
            //(i++, output_array[k] = j, k++)
            (*befehle)+=3;
        }
    }
}

void count_sort(int array[], int len, int* befehle) {
    int* count_array = malloc(sizeof(int) * MAX_VALUE);

    //fill count_array with 0
    for(int i=0;i<MAX_VALUE;i++){
        count_array[i] = 0;
    }

    count_sort_calculate_counts(array, len, count_array, befehle);

    //use output array to save result
    count_sort_write_output_array(array, len, count_array, befehle);

    free(count_array);

}
</code>```

and here is the result of valgrind:

```<code>==6694== Memcheck, a memory error detector
==6694== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6694== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==6694== Command: ./aaaad
==6694==
==6694== Invalid read of size 4
==6694==    at 0x4009ED: count_sort_write_output_array (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400A8D: count_sort (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400FD5: main (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==  Address 0x6916d40 is 0 bytes after a block of size 20,000,000 alloc'd
==6694==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6694==    by 0x400A2A: count_sort (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400FD5: main (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==
Parameter MAX_VALUE hat den Wert 5000000
                                Countsort                              Insertionsort
       n                  Befehle         Laufzeit                Befehle         Laufzeit
   10000                  5050001         425.5080               50215642        1929.5740
   20000                  5100001         423.1040              200387176        7655.5280
   30000                  5150001         427.7080              453403054       16763.7200
   40000                  5200001         363.3830              797737482       28034.7020
   50000                  5250001         392.9350             1245274822       44438.0240
==6694==
==6694== HEAP SUMMARY:
==6694==     in use at exit: 0 bytes in 0 blocks
==6694==   total heap usage: 26 allocs, 26 frees, 101,224,264 bytes allocated
==6694==
==6694== All heap blocks were freed -- no leaks are possible
==6694==
==6694== For counts of detected and suppressed errors, rerun with: -v
==6694== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)
</code>```

答:
Here's your problem:

```<code>for (int j=0;j<=MAX_VALUE;j++) {
</code>```

You allocate space for an array of MAX_VALUE int's.  So the indexes of this array range from 0 to MAX_VALUE - 1.  Your loop however allows j to range up to MAX_VALUE, so when that happens count_array[j] is reading one element past the end of the array.

Fix your loop condition to not include MAX_VALUE:

```<code>for (int j=0;j<MAX_VALUE;j++) {
</code>```

Body:
I've written a C programm to compare the runtime of insertion sort and count sort, but it can't pass the valgrind test because this programm will read from non-initialized memory.
Here is my code, which could probably be false, and I want to know why I have this problem:

void count_sort_write_output_array(int output_array[], int len, int count_array[], int* befehle) {
    int k=0;
    //use count array to output result
    for (int j=0;j<=MAX_VALUE;j++) {
        //add befehle
        //(j++)
        (*befehle)++;
        for (int i=0; i<count_array[j]; i++) {
            output_array[k] = j;
            k++;
            //add befehle
            //(i++, output_array[k] = j, k++)
            (*befehle)+=3;
        }
    }
}

void count_sort(int array[], int len, int* befehle) {
    int* count_array = malloc(sizeof(int) * MAX_VALUE);

    //fill count_array with 0
    for(int i=0;i<MAX_VALUE;i++){
        count_array[i] = 0;
    }

    count_sort_calculate_counts(array, len, count_array, befehle);

    //use output array to save result
    count_sort_write_output_array(array, len, count_array, befehle);

    free(count_array);

}

and here is the result of valgrind:

==6694== Memcheck, a memory error detector
==6694== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6694== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==6694== Command: ./aaaad
==6694==
==6694== Invalid read of size 4
==6694==    at 0x4009ED: count_sort_write_output_array (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400A8D: count_sort (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400FD5: main (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==  Address 0x6916d40 is 0 bytes after a block of size 20,000,000 alloc'd
==6694==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6694==    by 0x400A2A: count_sort (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==    by 0x400FD5: main (in /afs/tu-berlin.de/home/r/ryoine/irb-ubuntu/introprog-wise1718/Tutorien/t24/Studierende/ryoine/Abgaben/Blatt03/aaaad)
==6694==
Parameter MAX_VALUE hat den Wert 5000000
                                Countsort                              Insertionsort
       n                  Befehle         Laufzeit                Befehle         Laufzeit
   10000                  5050001         425.5080               50215642        1929.5740
   20000                  5100001         423.1040              200387176        7655.5280
   30000                  5150001         427.7080              453403054       16763.7200
   40000                  5200001         363.3830              797737482       28034.7020
   50000                  5250001         392.9350             1245274822       44438.0240
==6694==
==6694== HEAP SUMMARY:
==6694==     in use at exit: 0 bytes in 0 blocks
==6694==   total heap usage: 26 allocs, 26 frees, 101,224,264 bytes allocated
==6694==
==6694== All heap blocks were freed -- no leaks are possible
==6694==
==6694== For counts of detected and suppressed errors, rerun with: -v
==6694== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)

Body:
Here's your problem:

for (int j=0;j<=MAX_VALUE;j++) {

You allocate space for an array of MAX_VALUE int's.  So the indexes of this array range from 0 to MAX_VALUE - 1.  Your loop however allows j to range up to MAX_VALUE, so when that happens count_array[j] is reading one element past the end of the array.

Fix your loop condition to not include MAX_VALUE:

for (int j=0;j<MAX_VALUE;j++) {


问:
Issue centering images in WInForms App
I am having trouble with making my game centered and also a bit bigger on the screen when I go into full screen mode.

Is there any property or code that helps me?

Here's what it looks like right now:

All of my elements go to the left when they are on a little screen (800x600) (the normal screen the game is played on), the ones that seem to be on the right, go to the center and a bit off of that and the ones on the left seem to be almost centered.

答:
System.Windows.Forms.Screen contains properties that may be helpful.

The following code will get you the dimensions of the primary screen:

```<code>System.Windows.Forms.Screen _primaryScreen = System.Windows.Forms.Screen.PrimaryScreen;
double _screenWidth = _primaryScreen.Bounds.Width;
double _screenHeight = _primaryScreen.Bounds.Height;
</code>```

You can use calculated offsets/scales based on the size of the display.

Title: Issue centering images in WInForms App

Body:
System.Windows.Forms.Screen contains properties that may be helpful.

The following code will get you the dimensions of the primary screen:

System.Windows.Forms.Screen _primaryScreen = System.Windows.Forms.Screen.PrimaryScreen;
double _screenWidth = _primaryScreen.Bounds.Width;
double _screenHeight = _primaryScreen.Bounds.Height;

You can use calculated offsets/scales based on the size of the display.


问:
how can I create executable file for the program written on Java?
everyone, how can I create executable file for the program written on Java in Eclipse Helios? I mean to create small icon to be able start program only by double-clicking on its icon, thanks in advance
edited
I mean executable for Windows

答:
Create a 1-line metafile to specify which class the JVM should look for to start with the main(String[]) method.

Run the command jar cmf [metafileName] [jarfileName] [classfiles] [img/txtDirectories]

You have an executable jar file - type in "java -jar jarfileName" or, directly "jarfileName" at your prompt. On windows, you can also double click on the jar file logo/name to get it started.

Good wishes, - M.S.

PS: Here is the link to a more detailed tutorial:
http://csdl.ics.hawaii.edu/~johnson/613f99/modules/04/jar-files.html


问:
C# How to get properties value of generic class at runtime
How to get value and type of "strx" at runtime? Cant get value of cell (properties) at runtime when using generics (as result of under code is "null").

Example

```<code>   public class Foo
    {
        public int x, y;
        public string strx, stry;
    }

    public void GetCellValueByName<T>(GridView gridview, string name/)
    {
        T = (T)Activator.CreateInstance(typeof(T));

        object row = gridview.GetRow(gridview.GetSelectedRows()[0]);

        if (row != null && row is T)
        {
            columnType = (T)gridview.GetRow(gridview.GetSelectedRows()[0]);
            PropertyInfo info = columnType.GetType().GetProperty(name);
            if (info != null)
            {  // Here I got always null
                info.GetValue(columnType, null);
            }
        }
    }

string valueOfStrx = GetCellValueByName<Foo>(grid, "strx");
</code>```

答:
The problem is that in class Foo, strx is a field (member variable):

```<code>public string strx, stry;
</code>```

In your method, you try to use GetProperty, but this will not find the field:

```<code>PropertyInfo info = columnType.GetType().GetProperty(name);
</code>```

So either change the member to a property

```<code>public string strx { get; set; }
public string stry { get; set; }
</code>```

or use GetField instead:

```<code>FieldInfo info = columnType.GetType().GetField(name);
// ...
info.GetValue(columnType); // Note that GetValue for a field does not take a second parameter
</code>```

Body:
How to get value and type of "strx" at runtime? Cant get value of cell (properties) at runtime when using generics (as result of under code is "null").

Example

   public class Foo
    {
        public int x, y;
        public string strx, stry;
    }

    public void GetCellValueByName<T>(GridView gridview, string name/)
    {
        T = (T)Activator.CreateInstance(typeof(T));

        object row = gridview.GetRow(gridview.GetSelectedRows()[0]);

        if (row != null && row is T)
        {
            columnType = (T)gridview.GetRow(gridview.GetSelectedRows()[0]);
            PropertyInfo info = columnType.GetType().GetProperty(name);
            if (info != null)
            {  // Here I got always null
                info.GetValue(columnType, null);
            }
        }
    }

string valueOfStrx = GetCellValueByName<Foo>(grid, "strx");

Body:
The problem is that in class Foo, strx is a field (member variable):

public string strx, stry;

In your method, you try to use GetProperty, but this will not find the field:

PropertyInfo info = columnType.GetType().GetProperty(name);

So either change the member to a property

public string strx { get; set; }
public string stry { get; set; }

or use GetField instead:

FieldInfo info = columnType.GetType().GetField(name);
// ...
info.GetValue(columnType); // Note that GetValue for a field does not take a second parameter


问:
Sass pre-processing using Webpack Encore: how to add sass options?
I'm trying to configure Webpack Encore to integrate Foundation into our project. At this page, it is said that Sass options can be passed into Encore using something like:

```<code>Encore
    // ...
    .enableSassLoader(function(sassOptions) {
        // https://github.com/sass/node-sass#options
        // options.includePaths = [...]
    });
;
</code>```

How to pass Sass options such as the following (ie, the path to the scss folder of Foundation) in my config?

```<code>var sassOptions = {
    includePaths: 'node_modules/foundation-sites/scss'
};
</code>```

I'm new to Sass & Webpack. I'm probably missing smthg obvious.

答:
Have you tried this already?

```<code>.enableSassLoader(function(sassOptions) {
    options.includePaths = ['node_modules/foundation-sites/scss'];
});
</code>```

OR

```<code>.enableSassLoader(function(sassOptions) {
   sassOptions.includePaths = ['node_modules/foundation-sites/scss'];
});
</code>```

Body:
I'm trying to configure Webpack Encore to integrate Foundation into our project. At this page, it is said that Sass options can be passed into Encore using something like:

Encore
    // ...
    .enableSassLoader(function(sassOptions) {
        // https://github.com/sass/node-sass#options
        // options.includePaths = [...]
    });
;

How to pass Sass options such as the following (ie, the path to the scss folder of Foundation) in my config?

var sassOptions = {
    includePaths: 'node_modules/foundation-sites/scss'
};

I'm new to Sass & Webpack. I'm probably missing smthg obvious.

Body:
Have you tried this already?

.enableSassLoader(function(sassOptions) {
    options.includePaths = ['node_modules/foundation-sites/scss'];
});

OR

.enableSassLoader(function(sassOptions) {
   sassOptions.includePaths = ['node_modules/foundation-sites/scss'];
});


问:
Unable to deploy maven artifact to maven central repository using travis
I am trying to deploy maven artifact to central repository through Travis but I am facing below error:

```<code>[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:1.6.7:deploy (injected-nexus-deploy) on project Test-plugin: Execution injected-nexus-deploy of goal org.sonatype.plugins:nexus-staging-maven-plugin:1.6.7:deploy failed: Nexus connection problem to URL [https://oss.sonatype.org/ ]: 401 - Unauthorized -> [Help 1]
</code>```

I have set correct username and password for sonatype account, still I am getting the same error.
Below are the files uploaded:
.travis.yml
settings.xml

答:
Looks like your settings.xml in the .m2 folder in your home directory is not having proper authorization properties set for maven to look

I am enclosing a sample XML for your reference ..

https://maven.apache.org/settings.html

```<code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd">   ...   <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>   </servers>   ... </settings>
</code>```

Here is the troubleshooting guide if you are getting 404

https://support.sonatype.com/hc/en-us/articles/213464518-Troubleshooting-Artifact-Download-Failures

From the docs

SNAPSHOT look-ups, or version ranges, or unversioned dependencies (typically  plugins) will trigger metadata look-up. If the version referenced by the maven-metadata.xml is not there you will get a 404.

This can usually be fixed by running rebuild metadata on the affected artifact.

Body:
I am trying to deploy maven artifact to central repository through Travis but I am facing below error:

[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:1.6.7:deploy (injected-nexus-deploy) on project Test-plugin: Execution injected-nexus-deploy of goal org.sonatype.plugins:nexus-staging-maven-plugin:1.6.7:deploy failed: Nexus connection problem to URL [https://oss.sonatype.org/ ]: 401 - Unauthorized -> [Help 1]

I have set correct username and password for sonatype account, still I am getting the same error.
Below are the files uploaded:
.travis.yml
settings.xml

Body:
Looks like your settings.xml in the .m2 folder in your home directory is not having proper authorization properties set for maven to look

I am enclosing a sample XML for your reference ..

https://maven.apache.org/settings.html

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd">   ...   <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>   </servers>   ... </settings>

Here is the troubleshooting guide if you are getting 404

https://support.sonatype.com/hc/en-us/articles/213464518-Troubleshooting-Artifact-Download-Failures

From the docs

SNAPSHOT look-ups, or version ranges, or unversioned dependencies (typically  plugins) will trigger metadata look-up. If the version referenced by the maven-metadata.xml is not there you will get a 404.

This can usually be fixed by running rebuild metadata on the affected artifact.


问:
What is a good way to find gaps in a set of datespans?
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

```<code>1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11
</code>```

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

答:
I want to be able to tell that between
  1/10/11 and 1/13/11 there is a gap so
  the start and end date is not
  possible.

I think you're asking this question: does the data in your table have a gap between the start date and the end date?

I created a one-column table, date_span, and inserted your date spans into it.

You can identify a gap by counting the number of days between start date and end date, and comparing that the the number of rows in date_span for the same range.

```<code>select
  date '2011-01-14' - date '2011-01-07' + 1 as elapsed_days,
  count(*) from date_span
where cal_date between '2011-01-07' and '2011-01-14';
</code>```

returns

```<code>elapsed_days count
--           --
8            6
</code>```

Since they're not equal, there's a gap in the table "date_span" between 2011-01-07 and 2011-01-14. I'll stop there for now, because I'm really not certain what you're trying to do.

Body:
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

Body:
I want to be able to tell that between
  1/10/11 and 1/13/11 there is a gap so
  the start and end date is not
  possible.

I think you're asking this question: does the data in your table have a gap between the start date and the end date?

I created a one-column table, date_span, and inserted your date spans into it.

You can identify a gap by counting the number of days between start date and end date, and comparing that the the number of rows in date_span for the same range.

select
  date '2011-01-14' - date '2011-01-07' + 1 as elapsed_days,
  count(*) from date_span
where cal_date between '2011-01-07' and '2011-01-14';

returns

elapsed_days count
--           --
8            6

Since they're not equal, there's a gap in the table "date_span" between 2011-01-07 and 2011-01-14. I'll stop there for now, because I'm really not certain what you're trying to do.


问:
AJAX appended content does not execute Javascript
I've seen this problem posted on Stack Overflow couple of times, but the solution I found is usually very old and talks about delegate method which is deprecated.

I am looking for a solution for jQuery 3.x. This is my AJAX call:

```<code>$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
  }
});
</code>```

Here I am appending the success data to a div called appendsection
This appendsection div does not execute any javascript, it executes CSS, but no javascript and no jquery. I see this problem most of the time, any data I get from ajax call does not want to execute javascript.

This is the appended content

```<code><div class="sortingbuttons">
        <select id="sort">
        Sort By
          <option value="name">Relevance</option>
          <option value="price">Cheapest</option>
          <option value="recommend">Recommended</option>
        </select>
</div>
</code>```

The #sort id is executed on app.js

```<code>$('#sort').change(function(){
            $('.section').hide();
            $('#' + $(this).val()).show();
        });
</code>```

So, the sorting does not work on the appended content, so the javascript is not working on the appended content.

答:
the solution to your problem is still delegation but not the method delegate.

here is the structure for event delegation in jQuery 1.7+

```<code>$( elements ).on( events, selector, data, handler );
</code>```

try this I hope it will work

```<code>$('body').on('change', '#sort', function(){
    $('.section').hide();
    $('#' + $(this).val()).show(); //do anything
})
</code>```

Body:
I've seen this problem posted on Stack Overflow couple of times, but the solution I found is usually very old and talks about delegate method which is deprecated.

I am looking for a solution for jQuery 3.x. This is my AJAX call:

$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
  }
});

Here I am appending the success data to a div called appendsection
This appendsection div does not execute any javascript, it executes CSS, but no javascript and no jquery. I see this problem most of the time, any data I get from ajax call does not want to execute javascript.

This is the appended content

        <select id="sort">
        Sort By
          <option value="name">Relevance</option>
          <option value="price">Cheapest</option>
          <option value="recommend">Recommended</option>
        </select>

The #sort id is executed on app.js

$('#sort').change(function(){
            $('.section').hide();
            $('#' + $(this).val()).show();
        });

So, the sorting does not work on the appended content, so the javascript is not working on the appended content.

Body:
the solution to your problem is still delegation but not the method delegate.

here is the structure for event delegation in jQuery 1.7+

$( elements ).on( events, selector, data, handler );

try this I hope it will work

$('body').on('change', '#sort', function(){
    $('.section').hide();
    $('#' + $(this).val()).show(); //do anything
})


问:
Amazon ssh_exchange_identification: read: Connection reset by peer: when changing permissions
I went on to my amazon ec2 successfully and I have been experimenting around. I found it annoying that I needed to always run sudo on everything so what I decided to do was to go to the route directory and change the permissions of everything to write, write, and execute.

I did so doing the following

```<code>chmod -R 777 .
</code>```

I then exited out of the server.

The next time I tried to logon I got

```<code>"ssh_exchange_identification: read: Connection reset by peer"
</code>```

How can I fix this?

Thank you

答:
In my case instance stop and start worked.

I simply rebooted my EC2 instance in the browser (AWS -> EC2 Dashboard -> instances -> (select your instance) -> (click the action dropdown) -> Instance State -> Stop

then

I simply rebooted my EC2 instance in the browser (AWS -> EC2 Dashboard -> instances -> (select your instance) -> (click the action dropdown) -> Instance State -> Start

Note:- It takes a while for stop and start, have some patience.

thanks
Pranav

Body:
I went on to my amazon ec2 successfully and I have been experimenting around. I found it annoying that I needed to always run sudo on everything so what I decided to do was to go to the route directory and change the permissions of everything to write, write, and execute.

I did so doing the following

chmod -R 777 .

I then exited out of the server.

The next time I tried to logon I got

"ssh_exchange_identification: read: Connection reset by peer"

How can I fix this?

Thank you


问:
jspdf - specialElementHandlers to alter element
I want to generate a PDF from HTML, but the PDF sometimes contains different text.
So I am trying to use the "specialElementHandlers" to alter some elements, before adding them to the PDF.

```<code>htmlToPDF(){
    var pdf = new jsPDF('p', 'pt', 'letter');
    var source = $('#HTMLtoPDF')[0];
    var specialElementHandlers = {
        '#bypassme': function(element, renderer) {
            return true
        },
        '#changeme': function (element, renderer) {
            return <h2>different text</h2>
        }
    };
</code>```

Right now, I am trying to do something like this, but it won't work (at least the "changeme" part, the "bypassme" works flawlessly).

I'd highly appreciate any kind of help.

答:
If you want to alter before adding it to the id, you have to return "false" in the specialElementHandler and change the element itself.
E.G.:

```<code>'#changeme': function (element, renderer) {
            element.innerHTML = "<div>New Text</div>";
            return false;
</code>```

Notice that you have to copy the elemnts for your pdf before. Otherwise you will also change the element on the website itself.

```<code>const html = source.outerHTML;

    pdf.fromHTML (
        html // HTML string or DOM elem ref.
        , margins.left // x coord
        , margins.top // y coord
        , {
            'width': margins.width // max width of content on PDF
            , 'elementHandlers': specialElementHandlers
        },
...
</code>```

Body:
I want to generate a PDF from HTML, but the PDF sometimes contains different text.
So I am trying to use the "specialElementHandlers" to alter some elements, before adding them to the PDF.

htmlToPDF(){
    var pdf = new jsPDF('p', 'pt', 'letter');
    var source = $('#HTMLtoPDF')[0];
    var specialElementHandlers = {
        '#bypassme': function(element, renderer) {
            return true
        },
        '#changeme': function (element, renderer) {
            return
different text

        }
    };

Right now, I am trying to do something like this, but it won't work (at least the "changeme" part, the "bypassme" works flawlessly).

I'd highly appreciate any kind of help.

Body:
If you want to alter before adding it to the id, you have to return "false" in the specialElementHandler and change the element itself.
E.G.:

'#changeme': function (element, renderer) {
            element.innerHTML = "<div>New Text</div>";
            return false;

Notice that you have to copy the elemnts for your pdf before. Otherwise you will also change the element on the website itself.

const html = source.outerHTML;

    pdf.fromHTML (
        html // HTML string or DOM elem ref.
        , margins.left // x coord
        , margins.top // y coord
        , {
            'width': margins.width // max width of content on PDF
            , 'elementHandlers': specialElementHandlers
        },
...


问:
Swagger/OpenAPI: How to integrate generation of typescript/angular client in build process?
Java/Spring Server-Stubs Generation with swagger-codegen-maven-plugin

In my Spring Boot Java project I am using swagger-codegen-maven-plugin to generate the Spring MVC controller interfaces (server stubs) from my Swagger 2.0 api.yml. The integration in the maven build process is quite simple. It works simliar as I used to do it with the jaxws-maven-plugin for WSDLs. This is the example configuration from the pom.xml with swagger-codegen. It generates the server side model and mvc interfaces:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>/api/api-v2.yml</inputSpec>
                <language>spring</language>
                <apiPackage>io.fischermatte.test.api</apiPackage>
                <modelPackage>io.fischermatte.test.api.model</modelPackage>
                <output>${project.build.directory}/generated</output>
                <configOptions>
                    <interfaceOnly>true</interfaceOnly>
                    <sourceFolder>/src/main/java</sourceFolder>
                    <library>spring-mvc</library>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>
```

But how to integrate the same thing in a npm build process of a client angular app ?

Now I am trying to integrate the generation of the client code in the npm build process of my angular app. I have an api.yml defining my rest endpoints based on Swagger 2.0. I want the npm build to generate the api module similar to this typescript-angular-v4.3 sample. As much as I have seen, there is no official package for npm that does this like swagger-codegen-maven-plugin is doing it when you are using maven.

Did I misunderstand something here? The sample mentioned above is already the outcome, but what is the recommended approach to get there? Is such an integration in a npm based project not the way to go? Should one do it manually and check the generated typescript files into the sources directory?

答:
Briefly:

Use maven "swagger-codegen-maven-plugin" to generate server/client code out of Swagger yaml/json, use "exec-maven-plugin" to install node dependencies (npm install) and client compilation (ng build).

Details:

Recently had similar question, not found anything in Internet, implemented it in the following way (please do not judge strictly if it's not ideal).

Build pipeline:

"swagger-codegen-maven-plugin" generates model and API code for
Spring MVC server

Maven builds and installs generated server code
and installs to local repository as artifact

Spring Boot application includes dependency of generated server
artifact, and has additional configuration, properties and real
implementation of controllers

"swagger-codegen-maven-plugin" generates model and API code for
Angular Client. The output directory is under "mem-client" angular
project.

"exec-maven-plugin" installs client dependencies (npm install)
"exec-maven-plugin" builds application (ng build --env=prod …) the
output of build stored in Spring Boot application resources

Once Angular client compiled and added to static server resources, we could
create standalone JAR with spring server and client
("spring-boot-maven-plugin" can do it)

NOTE: Please note that generated server and client codes are read-only and included only as dependencies/imports. Real implementation of controllers in separate project. To start server/client coding, execute "mvn generate-sources". To create server+client as standalone web application, just execute "mvn install" in parent "mem" project. This will create jar with all necessary stuff included in it.

Example:

Here is a working example (created simple "Memory Quiz" game. NOTE: not merged to master branch yet, see in "quiz" branch on GitHub): https://github.com/makimenko/mem/tree/quiz

Projects overview:

Parent maven pom "mem" project which includes all child modules

Maven "mem-design" project includes only Swagger 2.0 yaml file in
resources.

Maven "mem-server" project includes Spring Boot configuration,
properties and real controllers

Angular 5 client project "mem-client"

Auto generated code (not touched, just used in read-only mode as
import. Ignored in source control)

Hope this info could help you.

Body:
Java/Spring Server-Stubs Generation with swagger-codegen-maven-plugin

In my Spring Boot Java project I am using swagger-codegen-maven-plugin to generate the Spring MVC controller interfaces (server stubs) from my Swagger 2.0 api.yml. The integration in the maven build process is quite simple. It works simliar as I used to do it with the jaxws-maven-plugin for WSDLs. This is the example configuration from the pom.xml with swagger-codegen. It generates the server side model and mvc interfaces:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>/api/api-v2.yml</inputSpec>
                <language>spring</language>
                <apiPackage>io.fischermatte.test.api</apiPackage>
                <modelPackage>io.fischermatte.test.api.model</modelPackage>
                <output>${project.build.directory}/generated</output>
                <configOptions>
                    <interfaceOnly>true</interfaceOnly>
                    <sourceFolder>/src/main/java</sourceFolder>
                    <library>spring-mvc</library>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

But how to integrate the same thing in a npm build process of a client angular app ?

Now I am trying to integrate the generation of the client code in the npm build process of my angular app. I have an api.yml defining my rest endpoints based on Swagger 2.0. I want the npm build to generate the api module similar to this typescript-angular-v4.3 sample. As much as I have seen, there is no official package for npm that does this like swagger-codegen-maven-plugin is doing it when you are using maven.

Did I misunderstand something here? The sample mentioned above is already the outcome, but what is the recommended approach to get there? Is such an integration in a npm based project not the way to go? Should one do it manually and check the generated typescript files into the sources directory?


问:
CTA Button design with HTML
I'm hoping you can help me. The CTA Button I use for my emails is currently clickable only if you click on the text. I' m trying to make the whole box clickable.

The current HTML Code for my CTA Button is:

```<code><table border="0" cellpadding="0" cellspacing="0" class="button" style="border-collapse: collapse; mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%">
    <tbody class="button">
        <tr>
            <td align="center" class="button" style="padding:10px 50px; mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" valign="top">
            <table border="0" cellpadding="0" cellspacing="0" class="button" style="border-collapse: separate !important;border: 0px none;border-radius: 7px;background-color: #cb673d;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%">
                <tbody>
                    <tr>
                        <td align="center" class="button" style="font-family: verdana;font-size: 12px;padding: 15px;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" valign="middle"><a class="button" href="*http://www.mywebsite.com*" style="font-weight: bold;letter-spacing: .5px;line-height: 100%;text-align: center;word-wrap: break-word;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;text-decoration:none;color: #EFEFEF;" target="_blank">Submit your application</a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
</code>```

What should I change in order to have the whole CTA Button clickable?
Thank you very much in advance for your help.

Lucile

答:
You should do something like this:

                            Submit your application

```

Title: CTA Button design with HTML

Body:
I'm hoping you can help me. The CTA Button I use for my emails is currently clickable only if you click on the text. I' m trying to make the whole box clickable.

The current HTML Code for my CTA Button is:

                        Submit your application

What should I change in order to have the whole CTA Button clickable?
Thank you very much in advance for your help.

Lucile

Body:
You should do something like this:

<table border="0" cellpadding="0" cellspacing="0" class="button" style="border-collapse: collapse; mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%">
    <tbody class="button">
        <tr>
            <td align="center" class="button" style="padding:10px 50px; mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" valign="top">
                <table border="0" cellpadding="0" cellspacing="0" class="button" style="border-collapse: separate !important;border: 0px none;border-radius: 7px;background-color: #cb673d;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%">
                    <tbody>
                        <tr>
                            <td align="center" class="button" style="font-family: verdana;font-size: 12px;padding: 15px;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;padding: 0;" valign="middle"><a class="button" href="*http://www.mywebsite.com*" style="font-weight: bold;letter-spacing: .5px;line-height: 100%;text-align: center;word-wrap: break-word;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;text-decoration:none;color: #EFEFEF;display: block;width: 100%;height: 100%;padding: 15px;text-align:center;" target="_blank">Submit your application</a></td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>


问:
awk : extracting a data which is on several lines
so I have a file that looks like this :

```<code>/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"
</code>```

I need to extract the text that is between quotes after a "/product=", so I need this :

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

I have to use awk, so I wrote this :

```<code>awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'
</code>```

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

答:
assuming file name is file.txt

```<code>echo $(cat file.txt ) | sed 's/\//\n/g' | grep product | sed 's/product="//g;s/".*//'
</code>```

Explanation :

merge all line into  one line

echo $(cat file.txt )

replace "/"  as new line

echo $(cat file.txt ) | sed 's///\n/g'

grep line which having line Product

echo $(cat file.txt ) | sed 's///\n/g' | grep product

replace "product=" and all acaracter after double quote

echo $(cat file.txt ) | sed 's///\n/g' | grep product | sed 's/product="//g;s/".*//'

Body:
so I have a file that looks like this :

/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"

I need to extract the text that is between quotes after a "/product=", so I need this :

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

I have to use awk, so I wrote this :

awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

Body:
assuming file name is file.txt

echo $(cat file.txt ) | sed 's/\//\n/g' | grep product | sed 's/product="//g;s/".*//'

Explanation :

merge all line into  one line

echo $(cat file.txt )

replace "/"  as new line

echo $(cat file.txt ) | sed 's///\n/g'

grep line which having line Product

echo $(cat file.txt ) | sed 's///\n/g' | grep product

replace "product=" and all acaracter after double quote

echo $(cat file.txt ) | sed 's///\n/g' | grep product | sed 's/product="//g;s/".*//'