问:
How can I do automatic link and htmlspecialchars conversion at the same time?
I want to create code that meets both of the following two things at the same time.

If text contains any url, the part is automatically converted to a  link.

Apply the func1() to html entity characters on the text, except some  parts generated by the above function. (this is to prevent attack by malicious script.)

So I wrote the following code:

```<code><?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&", $text);
        $text = str_replace("\"", """, $text);
        $text = str_replace("'", "'", $text);
        $text = str_replace("<", "<", $text);
        $text = str_replace(">", ">", $text);
        $text = str_replace(" ", " ", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/([a-zA-Z0-9.\/?&=%_+-@~:#$]+)";
        $text = preg_replace("/(".$url_pattern.")/i", "<a href='\\1' target='_blank' class='temp_class'>\\1</a>", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test     <iframe src='https://youtube.com/watch?v=good'></iframe> hello world.";
    echo func2($test_string);
?>
</code>```

However, when I run the above code,  is applied 'too widely'. In other words, 'https: //www.~' (...) '~ hello world' is treated as 'a single link'.

What I wanted was three things:

 applies to href="https://www.youtube.com/watch?v=test" rel="nofollow noreferrer">https://www.youtube.com/watch?v=test

href ~ class='temp_class'> applies to href="https://youtube.com/watch?v=good" rel="nofollow noreferrer">https://youtube.com/watch?v=good

<, >, ', etc. in this text are appropriately converted by func1(). So  tag does not work.

1 and 2 are not operating normally.

I can guess why this is happening. Perhaps, func1() transforms <, >, etc. into <, >, etc., so regexp in func2() interprets them as part of url.

I can guess why, but I do not know what to do now.

I'm considering adding some words to $url_pattern in func2() to exclude characters like %nbsp; or < from being interpreted. However, how to express this with regexp is also a big hurdle to me.

I have spent a long time on this problem but it is very difficult. Please help me.

Please leave a comment if there is anything you cannot understand.

答:
I guess you could try this. Guards against entities within the url.

Formatted regex

```<code> ( https? )                    # (1)
 : //
 (                             # (2 start)
      (?:
           (?!
                (?i)
                (?:
                     &
                     (?:
                          [a-z_:] [a-z\d_:.-]*
                       |  (?:
                               \#
                               (?: [0-9]+ | x [0-9a-f]+ )
                          )
                     )
                  |  % [a-z_:] [a-z\d_:.-]*
                )
                ;
           )
           [a-zA-Z0-9./?&=%_+-@~:#$]
      )+
 )                             # (2 end)
</code>```

Php

http://sandbox.onlinephpfunctions.com/code/0bba1854a960c00d4946b9cdaa9cca2ca2e447fc

```<code><?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&", $text);
        $text = str_replace("\"", """, $text);
        $text = str_replace("'", "'", $text);
        $text = str_replace("<", "<", $text);
        $text = str_replace(">", ">", $text);
        $text = str_replace(" ", " ", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/((?:(?!(?i)(?:&(?:[a-z_:][a-z\d_:.-]*|(?:\#(?:[0-9]+|x[0-9a-f]+)))|%[a-z_:][a-z\d_:.-]*);)[a-zA-Z0-9.\/?&=%_+-@~:#$])+)";
        $text = preg_replace("/(".$url_pattern.")/i", "<a href='\\1' target='_blank' class='temp_class'>\\1</a>", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test     <iframe src='https://youtube.com/watch?v=good'></iframe> hello world.";
    echo func2($test_string);
</code>```

Output (with extra newline spacing)

```<code>hello universe!

<a href='https://www.youtube.com/watch?v=test' target='_blank' class='temp_class'>
https://www.youtube.com/watch?v=test
</a>

     <iframe src='

<a href='https://youtube.com/watch?v=good' target='_blank' class='temp_class'>
https://youtube.com/watch?v=good
</a>

'></iframe> hello world.
</code>```

Body:
I want to create code that meets both of the following two things at the same time.

If text contains any url, the part is automatically converted to a  link.

Apply the func1() to html entity characters on the text, except some  parts generated by the above function. (this is to prevent attack by malicious script.)

So I wrote the following code:

<?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&", $text);
        $text = str_replace("\"", """, $text);
        $text = str_replace("'", "'", $text);
        $text = str_replace("<", "<", $text);
        $text = str_replace(">", ">", $text);
        $text = str_replace(" ", " ", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/([a-zA-Z0-9.\/?&=%_+-@~:#$]+)";
        $text = preg_replace("/(".$url_pattern.")/i", "\\1", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test      hello world.";
    echo func2($test_string);
?>

However, when I run the above code,  is applied 'too widely'. In other words, 'https: //www.~' (...) '~ hello world' is treated as 'a single link'.

What I wanted was three things:

 applies to https://www.youtube.com/watch?v=test

 applies to https://youtube.com/watch?v=good

<, >, ', etc. in this text are appropriately converted by func1(). So  tag does not work.

1 and 2 are not operating normally.

I can guess why this is happening. Perhaps, func1() transforms <, >, etc. into <, >, etc., so regexp in func2() interprets them as part of url.

I can guess why, but I do not know what to do now.

I'm considering adding some words to $url_pattern in func2() to exclude characters like %nbsp; or < from being interpreted. However, how to express this with regexp is also a big hurdle to me.

I have spent a long time on this problem but it is very difficult. Please help me.

Please leave a comment if there is anything you cannot understand.

Body:
I guess you could try this. Guards against entities within the url.

Formatted regex

 ( https? )                    # (1)
 : //
 (                             # (2 start)
      (?:
           (?!
                (?i)
                (?:
                     &
                     (?:
                          [a-z_:] [a-z\d_:.-]*
                       |  (?:
                               \#
                               (?: [0-9]+ | x [0-9a-f]+ )
                          )
                     )
                  |  % [a-z_:] [a-z\d_:.-]*
                )
                ;
           )
           [a-zA-Z0-9./?&=%_+-@~:#$]
      )+
 )                             # (2 end)

Php

http://sandbox.onlinephpfunctions.com/code/0bba1854a960c00d4946b9cdaa9cca2ca2e447fc

<?php
    function func1($text) //function like htmlspecialchars
    {
        $text = str_replace("&", "&#38;", $text);
        $text = str_replace("\"", "&#34;", $text);
        $text = str_replace("'", "&#39;", $text);
        $text = str_replace("<", "&#60;", $text);
        $text = str_replace(">", "&#62;", $text);
        $text = str_replace(" ", "&nbsp;", $text);
        return $text;
    }
    function func2($text)
    {
        $text = func1($text);
        $url_pattern = "(http|https):\/\/((?:(?!(?i)(?:&(?:[a-z_:][a-z\d_:.-]*|(?:\#(?:[0-9]+|x[0-9a-f]+)))|%[a-z_:][a-z\d_:.-]*);)[a-zA-Z0-9.\/?&=%_+-@~:#$])+)";
        $text = preg_replace("/(".$url_pattern.")/i", "<a href='\\1' target='_blank' class='temp_class'>\\1</a>", $text);
        return $text;
    }
    $test_string ="hello universe! https://www.youtube.com/watch?v=test     <iframe src='https://youtube.com/watch?v=good'></iframe> hello world.";
    echo func2($test_string);

Output (with extra newline spacing)

hello&nbsp;universe!&nbsp;

<a href='https://www.youtube.com/watch?v=test' target='_blank' class='temp_class'>
https://www.youtube.com/watch?v=test
</a>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#60;iframe&nbsp;src=&#39;

<a href='https://youtube.com/watch?v=good' target='_blank' class='temp_class'>
https://youtube.com/watch?v=good
</a>

&#39;&#62;&#60;/iframe&#62;&nbsp;hello&nbsp;world.


来源: stackexchange

问:
Java - Is it possible to call an interface method on a any object?
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

```<code>public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}
</code>```

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

答:
If you look at the end of this documentation, it tells you about casting. Casting allows the program to assume the object is of a type and attempt to call a method within it.</p>

```<code>public void anyMethod() {
     ((MethodParentObject) this.x).runMyMethod();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

Body:
If you look at the end of this documentation, it tells you about casting. Casting allows the program to assume the object is of a type and attempt to call a method within it.

public void anyMethod() {
     ((MethodParentObject) this.x).runMyMethod();
}


问:
Nested hyperlinked areas without nested link elements in HTML source
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

```
|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|
```

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

```<code><a href="xxx" style="display: block">
  Some text
  <a href="yyy">link</a>
</a>
</code>```

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

```<code><a href="xxx" ...>Some text</a>
<a href="yyy" ...>Link</a>
<a href="xxx" ...>& nbsp;</a>
...
</code>```

答:
You could try something like this:

div.a {
  position: relative;
  background-color: #F88;
  z-index: 0;
}
a.b {
  position: relative;
  z-index: 2;
}
a.b:hover {
  background-color: #8F8;
}
a.c {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
a.c:hover {
  background-color: #88F;
}
a.c span {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  foo
  bar
  <span>baz</span>
</div></code>```

OwnerDisplayName: Jakub Narębski

ContentLicense: CC BY-SA 2.5

Body:
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

  Some text
  link

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

Some text
Link
& nbsp;
...

LastEditorDisplayName: Jakub Narębski

Body:
You could try something like this:

div.a {
  position: relative;
  background-color: #F88;
  z-index: 0;
}
a.b {
  position: relative;
  z-index: 2;
}
a.b:hover {
  background-color: #8F8;
}
a.c {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
a.c:hover {
  background-color: #88F;
}
a.c span {
  display: none;
}

<div class="a">
  foo
  <a href="bar" class="b">bar</a>
  <a href="foo" class="c"><span>baz</span></a>
</div>

OwnerDisplayName: Gumbo


问:
Slim 3 Http Delete method not working
I am trying to implement http DELETE. The app is written with php and slim3 framework. The frontend is angular 2.

If the pattern looks like:$slimApp->delete('/delete', ...) everything is fine.

As soon as I introduce params like: $slimApp->delete('/delete/{id}', ...) I get the following error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already read the docs https://www.slimframework.com/docs/cookbook/enable-cors.html but however I cannot get it work.

Here is my middleware:

```<code><?php

class MyMiddleware {

    public function __invoke(Request $req, Response $res, $next) {
        $res->withHeader('Access-Control-Allow-Origin', 'http://localhost:8100')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

        return $next($req, $res);
    }

}

$app = new \Slim\App([
    "settings"  => [
        "determineRouteBeforeAppMiddleware" => true
    ]
]);

$app->add(new MyMiddleware());
</code>```

Any ideas what could be the problem?

答: OK solved the problem. The .htaccess just did not let the request "reach" the code. So I just needed to optimize the rules.</p>

Title: Slim 3 Http Delete method not working

Body:
I am trying to implement http DELETE. The app is written with php and slim3 framework. The frontend is angular 2.

If the pattern looks like:$slimApp->delete('/delete', ...) everything is fine.

As soon as I introduce params like: $slimApp->delete('/delete/{id}', ...) I get the following error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already read the docs https://www.slimframework.com/docs/cookbook/enable-cors.html but however I cannot get it work.

Here is my middleware:

<?php

class MyMiddleware {

    public function __invoke(Request $req, Response $res, $next) {
        $res->withHeader('Access-Control-Allow-Origin', 'http://localhost:8100')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

        return $next($req, $res);
    }

}

$app = new \Slim\App([
    "settings"  => [
        "determineRouteBeforeAppMiddleware" => true
    ]
]);

$app->add(new MyMiddleware());

Any ideas what could be the problem?


问:
Cannot read property 'top' of undefined jQuery
Can someone help me to fix the code so that this script would work?

This is my html:

```<code>        <div class="img-wrapper item">
            <a href="/product/{{$product->id}}/{{$product->slug}}">
                <a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                <img class="media-object indexImg" src="{{$product->image}}">
                </a>
            </a>
            <div class="tags">
            @if($product->discount > 0)
                <span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
            @endif
                <span class="label-tags"><span class="label label-info">Nauja</span></span>
            </div>
            <div class="option">
                <button class="add-to-cart" type="button">Add to cart</button>
            </div>
        </div>
</code>```

This is script:

```<code>$('.add-to-cart').on('click', function () {
        var cart = $('.shopping-cart');
        var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                .offset({
                top: imgtodrag.offset().top,
                left: imgtodrag.offset().left
            })
                .css({
                'opacity': '0.5',
                    'position': 'absolute',
                    'height': '150px',
                    'width': '150px',
                    'z-index': '100'
            })
                .appendTo($('body'))
                .animate({
                'top': cart.offset().top + 10,
                    'left': cart.offset().left + 10,
                    'width': 75,
                    'height': 75
            }, 1000, 'easeInOutExpo');
    });
</code>```

It works with the example so the script is good. I just need correctly fill this line:

```<code>var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);
</code>```

答:
Your problem is because .img-wrapper is not a direct parent, but a "grandfather". With closest, you get the closest ascendent, which is the element you want in this case. Try this:

```<code>var imgtodrag = $(this).closest('.img-wrapper').find("img").first();
</code>```

Body:
Can someone help me to fix the code so that this script would work?

This is my html:

            id}}/{{$product->slug}}">
                id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                image}}">

            @if($product->discount > 0)
                Išpardavimas
            @endif
                Nauja

                <button class="add-to-cart" type="button">Add to cart</button>

This is script:

$('.add-to-cart').on('click', function () {
        var cart = $('.shopping-cart');
        var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                .offset({
                top: imgtodrag.offset().top,
                left: imgtodrag.offset().left
            })
                .css({
                'opacity': '0.5',
                    'position': 'absolute',
                    'height': '150px',
                    'width': '150px',
                    'z-index': '100'
            })
                .appendTo($('body'))
                .animate({
                'top': cart.offset().top + 10,
                    'left': cart.offset().left + 10,
                    'width': 75,
                    'height': 75
            }, 1000, 'easeInOutExpo');
    });

It works with the example so the script is good. I just need correctly fill this line:

var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);

Body:
Your problem is because .img-wrapper is not a direct parent, but a "grandfather". With closest, you get the closest ascendent, which is the element you want in this case. Try this:

var imgtodrag = $(this).closest('.img-wrapper').find("img").first();


问:
import asgi_redis: ImportError: No module named _compat
I can import asgi_redis on my local server fine but I get the error in the title when i try to import asgi_redis on my production server (heroku, using heroku run bash). Both have the same version of asgi_redis.

Here is the full traceback:

```<code>>>> import asgi_redis
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/__init__.py", line 1
, in <module>
    from .core import RedisChannelLayer
  File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/core.py", line 10, i
n <module>
    from redis._compat import b
ImportError: No module named _compat
</code>```

Does anyone know what is going on here? Thanks in advance.
I also have redis installed, redis 2.6.0, FWIW

答: local server had latest redis, production did not. upgraded redis on production and error is gone</p>

Body:
I can import asgi_redis on my local server fine but I get the error in the title when i try to import asgi_redis on my production server (heroku, using heroku run bash). Both have the same version of asgi_redis.

Here is the full traceback:

>>> import asgi_redis
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/__init__.py", line 1
, in <module>
    from .core import RedisChannelLayer
  File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/core.py", line 10, i
n <module>
    from redis._compat import b
ImportError: No module named _compat

Does anyone know what is going on here? Thanks in advance.
I also have redis installed, redis 2.6.0, FWIW


问:
Error message while developing Android Studio VPN Application
The Following message appear While developing an Open VPN application :
07-04 21:33:34.998 20337-21875/pioneers.safwat.myvpn6 E/AndroidRuntime: FATAL EXCEPTION: OpenVPNManagementThread
                                                                        java.lang.UnsatisfiedLinkError: Native method not found: pioneers.safwat.myvpn6.NativeUtils.jniclose:(I)V
                                                                            at pioneers.safwat.myvpn6.NativeUtils.jniclose(Native Method)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.protectFileDescriptor(OpenVpnManagementThread.java:175)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processNeedCommand(OpenVpnManagementThread.java:387)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processCommand(OpenVpnManagementThread.java:227)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processInput(OpenVpnManagementThread.java:198)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.run(OpenVpnManagementThread.java:146)
                                                                            at java.lang.Thread.run(Thread.java:841)
07-04 21:33:35.288 20337-20337/pioneers.safwat.myvpn6 E/ActivityThread: Activity pioneers.safwat.myvpn6.MainActivity_vpn has leaked ServiceConnection pioneers.safwat.myvpn6.MainActivity_vpn$1@42537e00 that was originally bound here
                                                                        android.app.ServiceConnectionLeaked: Activity pioneers.safwat.myvpn6.MainActivity_vpn has leaked ServiceConnection pioneers.safwat.myvpn6.MainActivity_vpn$1@42537e00 that was originally bound here
                                                                            at android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:979)
                                                                            at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:873)
                                                                            at android.app.ContextImpl.bindServiceAsUser(ContextImpl.java:1850)
                                                                            at android.app.ContextImpl.bindService(ContextImpl.java:1838)
                                                                            at android.content.ContextWrapper.bindService(ContextWrapper.java:503)
                                                                            at pioneers.safwat.myvpn6.MainActivity_vpn.onCreate(MainActivity_vpn.java:53)
                                                                            at android.app.Activity.performCreate(Activity.java:5372)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)

Nativeutilis Class:

```<code>public class NativeUtils {
    public static native byte[] rsasign(byte[] input,int pkey) throws InvalidKeyException;
    public static native String[] getIfconfig() throws  IllegalArgumentException;
    static native void jniclose(int fdint);

    static {
    //  System.loadLibrary("opencv_java");
        System.loadLibrary("stlport_shared");
        System.loadLibrary("opvpnutil");
        System.loadLibrary("openvpn");
        System.loadLibrary("ssl");
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN)
        System.loadLibrary("crypto");
    }
}
</code>```

The OpenVpnManagementThread Class:

```<code>   public class OpenVpnManagementThread implements Runnable, OpenVPNManagement {

    private static final String TAG = "Durai";
    private LocalSocket mSocket;
    private VpnProfile mProfile;
    private OpenVPNService mOpenVPNService;
    private LinkedList<FileDescriptor> mFDList = new LinkedList<FileDescriptor>();
    private LocalServerSocket mServerSocket;
    private boolean mReleaseHold = true;
    private boolean mWaitingForRelease = false;
    private long mLastHoldRelease = 0;

    private static final Vector<OpenVpnManagementThread> active = new Vector<OpenVpnManagementThread>();
    private LocalSocket mServerSocketLocal;

    private pauseReason lastPauseReason = pauseReason.noNetwork;

    public OpenVpnManagementThread(VpnProfile profile, OpenVPNService openVpnService) {
        mProfile = profile;
        mOpenVPNService = openVpnService;

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(openVpnService);
        boolean managemeNetworkState = prefs.getBoolean("netchangereconnect", true);
        if (managemeNetworkState)
            mReleaseHold = false;

    }

    public boolean openManagementInterface(@NotNull Context c) {
        // Could take a while to open connection
        int tries = 8;

        String socketName = (c.getCacheDir().getAbsolutePath() + "/" + "mgmtsocket");
        // The mServerSocketLocal is transferred to the LocalServerSocket, ignore warning

        mServerSocketLocal = new LocalSocket();

        while (tries > 0 && !mServerSocketLocal.isConnected()) {
            try {
                mServerSocketLocal.bind(new LocalSocketAddress(socketName,
                        LocalSocketAddress.Namespace.FILESYSTEM));
            } catch (IOException e) {
                // wait 300 ms before retrying
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e1) {
                }

            }
            tries--;
        }

        try {

            mServerSocket = new LocalServerSocket(mServerSocketLocal.getFileDescriptor());
            return true;
        } catch (IOException e) {
            VpnStatus.logException(e);
        }
        return false;

    }

    public void managmentCommand(String cmd) {
        try {
            if (mSocket != null && mSocket.getOutputStream() != null) {
                mSocket.getOutputStream().write(cmd.getBytes());
                mSocket.getOutputStream().flush();
            }
        } catch (IOException e) {
            // Ignore socket stack traces
        }
    }

    @Override
    public void run() {
        byte[] buffer = new byte[2048];
        //  mSocket.setSoTimeout(5); // Setting a timeout cannot be that bad

        String pendingInput = "";
        synchronized (active) {
            active.add(this);
        }

        try {
            // Wait for a client to connect
            mSocket = mServerSocket.accept();
            InputStream instream = mSocket.getInputStream();
            // Close the management socket after client connected

            mServerSocket.close();
            // Closing one of the two sockets also closes the other
            //mServerSocketLocal.close();

            while (true) {
                int numbytesread = instream.read(buffer);
                if (numbytesread == -1)
                    return;

                FileDescriptor[] fds = null;
                try {
                    fds = mSocket.getAncillaryFileDescriptors();
                } catch (IOException e) {
                    VpnStatus.logException("Error reading fds from socket", e);
                }
                if (fds != null) {
                    Collections.addAll(mFDList, fds);
                }

                String input = new String(buffer, 0, numbytesread, "UTF-8");

                pendingInput += input;

                pendingInput = processInput(pendingInput);

            }
        } catch (IOException e) {
            if (!e.getMessage().equals("socket closed") && !e.getMessage().equals("Connection reset by peer"))
                VpnStatus.logException(e);
        }
        synchronized (active) {
            active.remove(this);
        }
    }

    //! Hack O Rama 2000!
    private void protectFileDescriptor(FileDescriptor fd) {
        Exception exp;
        try {
            Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
            int fdint = (Integer) getInt.invoke(fd);
            boolean result = mOpenVPNService.protect(fdint);
            if (!result)
                VpnStatus.logWarning("Could not protect VPN socket");
            NativeUtils.jniclose(fdint);
            return;
        } catch (NoSuchMethodException e) {
            exp = e;
        } catch (IllegalArgumentException e) {
            exp = e;
        } catch (IllegalAccessException e) {
            exp = e;
        } catch (InvocationTargetException e) {
            exp = e;
        } catch (NullPointerException e) {
            exp = e;
        }

        Log.d("Openvpn", "Failed to retrieve fd from socket: " + fd);
        VpnStatus.logException("Failed to retrieve fd from socket (" + fd + ")", exp);
    }

    private String processInput(String pendingInput) {

        while (pendingInput.contains("\n")) {
            String[] tokens = pendingInput.split("\\r?\\n", 2);
            processCommand(tokens[0]);
            if (tokens.length == 1)
                // No second part, newline was at the end
                pendingInput = "";
            else
                pendingInput = tokens[1];
        }
        return pendingInput;
    }

    private void processCommand(String command) {
        //Log.i(TAG, "Line from managment" + command);

        if (command.startsWith(">") && command.contains(":")) {
            String[] parts = command.split(":", 2);
            String cmd = parts[0].substring(1);
            String argument = parts[1];

            if (cmd.equals("INFO")) {
                /* Ignore greeting from management */
                return;
            } else if (cmd.equals("PASSWORD")) {
                processPWCommand(argument);
            } else if (cmd.equals("HOLD")) {
                handleHold();
            } else if (cmd.equals("NEED-OK")) {
                processNeedCommand(argument);
            } else if (cmd.equals("BYTECOUNT")) {
                processByteCount(argument);
            } else if (cmd.equals("STATE")) {
                processState(argument);
            } else if (cmd.equals("PROXY")) {
                processProxyCMD(argument);
            } else if (cmd.equals("LOG")) {
                processLogMessage(argument);
            } else if (cmd.equals("RSA_SIGN")) {
                processSignCommand(argument);
            } else {
                VpnStatus.logWarning("MGMT: Got unrecognized command" + command);
                Log.i(TAG, "Got unrecognized command" + command);
            }
        } else if (command.startsWith("SUCCESS:")) {
            /* Ignore this kind of message too */
            return;
        } else if (command.startsWith("PROTECTFD: ")) {
            FileDescriptor fdtoprotect = mFDList.pollFirst();
            if (fdtoprotect != null)
                protectFileDescriptor(fdtoprotect);
        } else {
            Log.i(TAG, "Got unrecognized line from managment" + command);
            VpnStatus.logWarning("MGMT: Got unrecognized line from management:" + command);
        }
    }

    private void processLogMessage(String argument) {
        String[] args = argument.split(",", 4);
        Log.d("OpenVPN", argument);

        VpnStatus.LogLevel level;
        if (args[1].equals("I")) {
            level = VpnStatus.LogLevel.INFO;
        } else if (args[1].equals("W")) {
            level = VpnStatus.LogLevel.WARNING;
        } else if (args[1].equals("D")) {
            level = VpnStatus.LogLevel.VERBOSE;
        } else if (args[1].equals("F")) {
            level = VpnStatus.LogLevel.ERROR;
        } else {
            level = VpnStatus.LogLevel.INFO;
        }

        int ovpnlevel = Integer.parseInt(args[2]) & 0x0F;
        String msg = args[3];

        if (msg.startsWith("MANAGEMENT: CMD"))
            ovpnlevel = Math.max(4, ovpnlevel);

        VpnStatus.logMessageOpenVPN(level, ovpnlevel, msg);
    }

    private void handleHold() {
        if (mReleaseHold) {
            releaseHoldCmd();
        } else {
            mWaitingForRelease = true;
            VpnStatus.updateStatePause(lastPauseReason);

        }
    }

    private void releaseHoldCmd() {
        if ((System.currentTimeMillis() - mLastHoldRelease) < 5000) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ignored) {
            }

        }
        mWaitingForRelease = false;
        mLastHoldRelease = System.currentTimeMillis();
        managmentCommand("hold release\n");
        managmentCommand("bytecount " + mBytecountInterval + "\n");
        managmentCommand("state on\n");
    }

    public void releaseHold() {
        mReleaseHold = true;
        if (mWaitingForRelease)
            releaseHoldCmd();

    }

    private void processProxyCMD(String argument) {
        String[] args = argument.split(",", 3);
        SocketAddress proxyaddr = ProxyDetection.detectProxy(mProfile);

        if (args.length >= 2) {
            String proto = args[1];
            if (proto.equals("UDP")) {
                proxyaddr = null;
            }
        }

        if (proxyaddr instanceof InetSocketAddress) {
            InetSocketAddress isa = (InetSocketAddress) proxyaddr;

            VpnStatus.logInfo(R.string.using_proxy, isa.getHostName(), isa.getPort());

            String proxycmd = String.format(Locale.ENGLISH, "proxy HTTP %s %d\n", isa.getHostName(), isa.getPort());
            managmentCommand(proxycmd);
        } else {
            managmentCommand("proxy NONE\n");
        }

    }

    private void processState(String argument) {
        String[] args = argument.split(",", 3);
        String currentstate = args[1];

        if (args[2].equals(",,"))
            VpnStatus.updateStateString(currentstate, "");
        else
            VpnStatus.updateStateString(currentstate, args[2]);
    }

    private void processByteCount(String argument) {
        //   >BYTECOUNT:{BYTES_IN},{BYTES_OUT}
        int comma = argument.indexOf(',');
        long in = Long.parseLong(argument.substring(0, comma));
        long out = Long.parseLong(argument.substring(comma + 1));
        VpnStatus.updateByteCount(in, out);
    }
    private void processNeedCommand(String argument) {
        int p1 = argument.indexOf('\'');
        int p2 = argument.indexOf('\'', p1 + 1);
        String needed = argument.substring(p1 + 1, p2);
        String extra = argument.split(":", 2)[1];
        String status = "ok";
        if (needed.equals("PROTECTFD")) {
            FileDescriptor fdtoprotect = mFDList.pollFirst();
            protectFileDescriptor(fdtoprotect);
        } else if (needed.equals("DNSSERVER")) {
            mOpenVPNService.addDNS(extra);
        } else if (needed.equals("DNSDOMAIN")) {
            mOpenVPNService.setDomain(extra);
        } else if (needed.equals("ROUTE")) {
            String[] routeparts = extra.split(" ");

            if (routeparts.length == 5) {
                if (BuildConfig.DEBUG) Assert.assertEquals("dev", routeparts[3]);
                mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]);
            } else if (routeparts.length >= 3) {
                mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null);
            } else {
                VpnStatus.logError("Unrecognized ROUTE cmd:" + Arrays.toString(routeparts) + " | " + argument);
            }

        } else if (needed.equals("ROUTE6")) {
            String[] routeparts = extra.split(" ");
            mOpenVPNService.addRoutev6(routeparts[0], routeparts[1]);
        } else if (needed.equals("IFCONFIG")) {
            String[] ifconfigparts = extra.split(" ");
            int mtu = Integer.parseInt(ifconfigparts[2]);
            mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1], mtu, ifconfigparts[3]);
        } else if (needed.equals("IFCONFIG6")) {
            mOpenVPNService.setLocalIPv6(extra);

        } else if (needed.equals("PERSIST_TUN_ACTION")) {
            // check if tun cfg stayed the same
            status = mOpenVPNService.getTunReopenStatus();
        } else if (needed.equals("OPENTUN")) {
            if (sendTunFD(needed, extra))
                return;
            else
                status = "cancel";
        } else {
            Log.e(TAG, "Unkown needok command " + argument);
            return;
        }
        String cmd = String.format("needok '%s' %s\n", needed, status);
        managmentCommand(cmd);
    }
    private boolean sendTunFD(String needed, String extra) {
        Exception exp;
        if (!extra.equals("tun")) {
            VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!", extra));
            return false;
        }
        ParcelFileDescriptor pfd = mOpenVPNService.openTun();
        if (pfd == null)
            return false;

        Method setInt;
        int fdint = pfd.getFd();
        try {
            setInt = FileDescriptor.class.getDeclaredMethod("setInt$", int.class);
            FileDescriptor fdtosend = new FileDescriptor();
            setInt.invoke(fdtosend, fdint);
            FileDescriptor[] fds = {fdtosend};
            mSocket.setFileDescriptorsForSend(fds);
            String cmd = String.format("needok '%s' %s\n", needed, "ok");
            managmentCommand(cmd);
            mSocket.setFileDescriptorsForSend(null);
            pfd.close();
            return true;
        } catch (NoSuchMethodException e) {
            exp = e;
        } catch (IllegalArgumentException e) {
            exp = e;
        } catch (IllegalAccessException e) {
            exp = e;
        } catch (InvocationTargetException e) {
            exp = e;
        } catch (IOException e) {
            exp = e;
        }
        VpnStatus.logException("Could not send fd over socket", exp);
        return false;
    }

    private void processPWCommand(String argument) {
        String needed;
        try {

            int p1 = argument.indexOf('\'');
            int p2 = argument.indexOf('\'', p1 + 1);
            needed = argument.substring(p1 + 1, p2);
            if (argument.startsWith("Verification Failed")) {
                proccessPWFailed(needed, argument.substring(p2 + 1));
                return;
            }
        } catch (StringIndexOutOfBoundsException sioob) {
            VpnStatus.logError("Could not parse management Password command: " + argument);
            return;
        }
        String pw = null;

        if (needed.equals("Private Key")) {
            pw = mProfile.getPasswordPrivateKey();
        } else if (needed.equals("Auth")) {
            String usercmd = String.format("username '%s' %s\n",
                    needed, VpnProfile.openVpnEscape(mProfile.mUsername));
            managmentCommand(usercmd);
            pw = mProfile.getPasswordAuth();
        }
        if (pw != null) {
            String cmd = String.format("password '%s' %s\n", needed, VpnProfile.openVpnEscape(pw));
            managmentCommand(cmd);
        } else {
            VpnStatus.logError(String.format("Openvpn requires Authentication type '%s' but no password/key information available", needed));
        }
    }

    private void proccessPWFailed(String needed, String args) {
        VpnStatus.updateStateString("AUTH_FAILED", needed + args,R.string.state_auth_failed, VpnStatus.ConnectionStatus.LEVEL_AUTH_FAILED);
    }
    private static boolean stopOpenVPN() {
        synchronized (active) {
            boolean sendCMD = false;
            for (OpenVpnManagementThread mt : active) {
                mt.managmentCommand("signal SIGINT\n");
                sendCMD = true;
                try {
                    if (mt.mSocket != null)
                        mt.mSocket.close();
                } catch (IOException e) {
                }
            }
            return sendCMD;
        }
    }

    @Override
    public void networkChange() {
        if (!mWaitingForRelease)
            managmentCommand("network-change\n");
    }

    public void signalusr1() {
        mReleaseHold = false;

        if (!mWaitingForRelease)
            managmentCommand("signal SIGUSR1\n");
        else
            VpnStatus.updateStatePause(lastPauseReason);
    }

    public void reconnect() {
        signalusr1();
        releaseHold();
    }
    private void processSignCommand(String b64data) {
        String signed_string = mProfile.getSignedData(b64data);
        if (signed_string == null) {
            managmentCommand("rsa-sig\n");
            managmentCommand("\nEND\n");
            stopOpenVPN();
            return;
        }
        managmentCommand("rsa-sig\n");
        managmentCommand(signed_string);
        managmentCommand("\nEND\n");
    }
    @Override
    public void pause(pauseReason reason) {
        lastPauseReason = reason;
        signalusr1();
    }

    @Override
    public void resume() {
        releaseHold();
        /* Reset the reason why we are disconnected */
        lastPauseReason = pauseReason.noNetwork;
    }
    @Override
    public boolean stopVPN() {
        return stopOpenVPN();
    }
}
</code>```

The MainActivity_vpn Class:

```<code>public class MainActivity_vpn extends Activity {
protected OpenVPNService mService;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        OpenVPNService.LocalBinder binder = (OpenVPNService.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mService =null;
        mBound = false;
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_vpn);
    Intent intent = new Intent(getBaseContext(), OpenVPNService.class);
    intent.setAction(OpenVPNService.START_SERVICE);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    registerReceiver(broadcastReceiver, new IntentFilter("CONNECTION_CHANGE"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.settingsmenu, menu);
    return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (Constants.isVPNConnected){
        // disable connect button if VPN is connected
        menu.getItem(0).setEnabled(false);
        // enable disconnect button if VPN is connected
        menu.getItem(1).setEnabled(true);
    } else{
        // enable connect button if VPN is disconnected
        menu.getItem(0).setEnabled(true);
        // disable disconnect button if VPN is disconnected
        menu.getItem(1).setEnabled(false);
    }
    return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_startvpn:
            configureAndStartVpn() ;
            return true ;
        case R.id.action_stopvpn:
            stopVPN() ;
            return true ;
        case R.id.action_removeProfile:
            removeProfile();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
private void removeProfile() {

    final ProfileManager pm = ProfileManager.getInstance(MainActivity_vpn.this) ;
    final VpnProfile profile = pm.getProfileByName(Constants.VPN_PROFILE_NAME) ;

    if (profile != null) {
                        stopVPN() ;
                        pm.removeProfile(getApplicationContext(),profile);
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(MainActivity_vpn.this,"The VPN Configuration is deleted", duration);
                        toast.show();
    } else {
                int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(MainActivity_vpn.this,"There are no VPN Configurations to delete", duration);toast.show();
    }
}
private void stopVPN() {
    try{
        ProfileManager.setConntectedVpnProfileDisconnected(MainActivity_vpn.this);
        if(mService.getManagement()!=null)
            mService.getManagement().stopVPN();
    }
    catch (Exception ex){
    }
}
private void configureAndStartVpn() {
    try {
                EditText Et_Ovpn = (EditText) findViewById(R.id.et_ovpn);

                String retVal = Et_Ovpn.getText().toString();

                if (retVal != null && retVal.trim().length()>0) {

                    byte[] buffer = retVal.getBytes() ;

                    VpnProfile vp = saveProfile(buffer) ;

                    if (vp != null) {
                        startVPN(vp) ;
                    }
                }
                else {
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(MainActivity_vpn.this,"Connecting using the last vpn configuration", duration);
                    toast.show();
                    startVPN();
                }
    } catch (Exception e) {
        e.printStackTrace() ;
    }
}
private VpnProfile saveProfile(byte [] data) {

    ConfigParser cp = new ConfigParser();
    try {
        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(data));
        cp.parseConfig(isr);
        VpnProfile vp = cp.convertProfile();
        ProfileManager vpl = ProfileManager.getInstance(this);
        vp.mName = Constants.VPN_PROFILE_NAME ;
        vpl.addProfile(vp);
        vpl.saveProfile(this, vp);
        vpl.saveProfileList(this);
        return vp ;
    } catch(Exception e) {
        return null ;
    }
}
public void startVPN(VpnProfile vp) {
    Intent intent = new Intent(getApplicationContext(),LaunchVPN.class);
    intent.putExtra(LaunchVPN.EXTRA_KEY, vp.getUUID().toString());
    intent.setAction(Intent.ACTION_MAIN);
    startActivity(intent);
}
private void startVPN() {

    ProfileManager pm = ProfileManager.getInstance(this) ;
    VpnProfile profile = pm.getProfileByName(Constants.VPN_PROFILE_NAME) ;

    if (profile == null) {
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(MainActivity_vpn.this,"There are no VPN Configurations.So paste the .OVPN and try", duration);
        toast.show();
        return ;
    }

    Intent intent = new Intent(this,LaunchVPN.class);
    intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUID().toString());
    intent.setAction(Intent.ACTION_MAIN);
    startActivity(intent);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        stopVPN();
        startVPN();
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}
</code>```

}

答:
From your log i saw this line:

```<code>MainActivity_vpn has leaked ServiceConnection
</code>```

In your activity OnCreate you're binding to service but you never unbind.
Add this to you're onDestroy method in your MainActivity:

```<code>    if (mServiceConn != null) {
      unbindService(mServiceConn);
    }
</code>```

Also, see this:
JNI- java.lang.UnsatisfiedLinkError: Native method not found

I think that you should remove the static from your methods signature

Body:
The Following message appear While developing an Open VPN application :
07-04 21:33:34.998 20337-21875/pioneers.safwat.myvpn6 E/AndroidRuntime: FATAL EXCEPTION: OpenVPNManagementThread
                                                                        java.lang.UnsatisfiedLinkError: Native method not found: pioneers.safwat.myvpn6.NativeUtils.jniclose:(I)V
                                                                            at pioneers.safwat.myvpn6.NativeUtils.jniclose(Native Method)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.protectFileDescriptor(OpenVpnManagementThread.java:175)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processNeedCommand(OpenVpnManagementThread.java:387)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processCommand(OpenVpnManagementThread.java:227)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.processInput(OpenVpnManagementThread.java:198)
                                                                            at pioneers.safwat.myvpn6.OpenVpnManagementThread.run(OpenVpnManagementThread.java:146)
                                                                            at java.lang.Thread.run(Thread.java:841)
07-04 21:33:35.288 20337-20337/pioneers.safwat.myvpn6 E/ActivityThread: Activity pioneers.safwat.myvpn6.MainActivity_vpn has leaked ServiceConnection pioneers.safwat.myvpn6.MainActivity_vpn$1@42537e00 that was originally bound here
                                                                        android.app.ServiceConnectionLeaked: Activity pioneers.safwat.myvpn6.MainActivity_vpn has leaked ServiceConnection pioneers.safwat.myvpn6.MainActivity_vpn$1@42537e00 that was originally bound here
                                                                            at android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:979)
                                                                            at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:873)
                                                                            at android.app.ContextImpl.bindServiceAsUser(ContextImpl.java:1850)
                                                                            at android.app.ContextImpl.bindService(ContextImpl.java:1838)
                                                                            at android.content.ContextWrapper.bindService(ContextWrapper.java:503)
                                                                            at pioneers.safwat.myvpn6.MainActivity_vpn.onCreate(MainActivity_vpn.java:53)
                                                                            at android.app.Activity.performCreate(Activity.java:5372)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)

Nativeutilis Class:

public class NativeUtils {
    public static native byte[] rsasign(byte[] input,int pkey) throws InvalidKeyException;
    public static native String[] getIfconfig() throws  IllegalArgumentException;
    static native void jniclose(int fdint);

    static {
    //  System.loadLibrary("opencv_java");
        System.loadLibrary("stlport_shared");
        System.loadLibrary("opvpnutil");
        System.loadLibrary("openvpn");
        System.loadLibrary("ssl");
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN)
        System.loadLibrary("crypto");
    }
}

The OpenVpnManagementThread Class:

   public class OpenVpnManagementThread implements Runnable, OpenVPNManagement {

    private static final String TAG = "Durai";
    private LocalSocket mSocket;
    private VpnProfile mProfile;
    private OpenVPNService mOpenVPNService;
    private LinkedList<FileDescriptor> mFDList = new LinkedList<FileDescriptor>();
    private LocalServerSocket mServerSocket;
    private boolean mReleaseHold = true;
    private boolean mWaitingForRelease = false;
    private long mLastHoldRelease = 0;

    private static final Vector<OpenVpnManagementThread> active = new Vector<OpenVpnManagementThread>();
    private LocalSocket mServerSocketLocal;

    private pauseReason lastPauseReason = pauseReason.noNetwork;

    public OpenVpnManagementThread(VpnProfile profile, OpenVPNService openVpnService) {
        mProfile = profile;
        mOpenVPNService = openVpnService;

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(openVpnService);
        boolean managemeNetworkState = prefs.getBoolean("netchangereconnect", true);
        if (managemeNetworkState)
            mReleaseHold = false;

    }

    public boolean openManagementInterface(@NotNull Context c) {
        // Could take a while to open connection
        int tries = 8;

        String socketName = (c.getCacheDir().getAbsolutePath() + "/" + "mgmtsocket");
        // The mServerSocketLocal is transferred to the LocalServerSocket, ignore warning

        mServerSocketLocal = new LocalSocket();

        while (tries > 0 && !mServerSocketLocal.isConnected()) {
            try {
                mServerSocketLocal.bind(new LocalSocketAddress(socketName,
                        LocalSocketAddress.Namespace.FILESYSTEM));
            } catch (IOException e) {
                // wait 300 ms before retrying
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e1) {
                }

            }
            tries--;
        }

        try {

            mServerSocket = new LocalServerSocket(mServerSocketLocal.getFileDescriptor());
            return true;
        } catch (IOException e) {
            VpnStatus.logException(e);
        }
        return false;

    }

    public void managmentCommand(String cmd) {
        try {
            if (mSocket != null && mSocket.getOutputStream() != null) {
                mSocket.getOutputStream().write(cmd.getBytes());
                mSocket.getOutputStream().flush();
            }
        } catch (IOException e) {
            // Ignore socket stack traces
        }
    }

    @Override
    public void run() {
        byte[] buffer = new byte[2048];
        //  mSocket.setSoTimeout(5); // Setting a timeout cannot be that bad

        String pendingInput = "";
        synchronized (active) {
            active.add(this);
        }

        try {
            // Wait for a client to connect
            mSocket = mServerSocket.accept();
            InputStream instream = mSocket.getInputStream();
            // Close the management socket after client connected

            mServerSocket.close();
            // Closing one of the two sockets also closes the other
            //mServerSocketLocal.close();

            while (true) {
                int numbytesread = instream.read(buffer);
                if (numbytesread == -1)
                    return;

                FileDescriptor[] fds = null;
                try {
                    fds = mSocket.getAncillaryFileDescriptors();
                } catch (IOException e) {
                    VpnStatus.logException("Error reading fds from socket", e);
                }
                if (fds != null) {
                    Collections.addAll(mFDList, fds);
                }

                String input = new String(buffer, 0, numbytesread, "UTF-8");

                pendingInput += input;

                pendingInput = processInput(pendingInput);

            }
        } catch (IOException e) {
            if (!e.getMessage().equals("socket closed") && !e.getMessage().equals("Connection reset by peer"))
                VpnStatus.logException(e);
        }
        synchronized (active) {
            active.remove(this);
        }
    }

    //! Hack O Rama 2000!
    private void protectFileDescriptor(FileDescriptor fd) {
        Exception exp;
        try {
            Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
            int fdint = (Integer) getInt.invoke(fd);
            boolean result = mOpenVPNService.protect(fdint);
            if (!result)
                VpnStatus.logWarning("Could not protect VPN socket");
            NativeUtils.jniclose(fdint);
            return;
        } catch (NoSuchMethodException e) {
            exp = e;
        } catch (IllegalArgumentException e) {
            exp = e;
        } catch (IllegalAccessException e) {
            exp = e;
        } catch (InvocationTargetException e) {
            exp = e;
        } catch (NullPointerException e) {
            exp = e;
        }

        Log.d("Openvpn", "Failed to retrieve fd from socket: " + fd);
        VpnStatus.logException("Failed to retrieve fd from socket (" + fd + ")", exp);
    }

    private String processInput(String pendingInput) {

        while (pendingInput.contains("\n")) {
            String[] tokens = pendingInput.split("\\r?\\n", 2);
            processCommand(tokens[0]);
            if (tokens.length == 1)
                // No second part, newline was at the end
                pendingInput = "";
            else
                pendingInput = tokens[1];
        }
        return pendingInput;
    }

    private void processCommand(String command) {
        //Log.i(TAG, "Line from managment" + command);

        if (command.startsWith(">") && command.contains(":")) {
            String[] parts = command.split(":", 2);
            String cmd = parts[0].substring(1);
            String argument = parts[1];

            if (cmd.equals("INFO")) {
                /* Ignore greeting from management */
                return;
            } else if (cmd.equals("PASSWORD")) {
                processPWCommand(argument);
            } else if (cmd.equals("HOLD")) {
                handleHold();
            } else if (cmd.equals("NEED-OK")) {
                processNeedCommand(argument);
            } else if (cmd.equals("BYTECOUNT")) {
                processByteCount(argument);
            } else if (cmd.equals("STATE")) {
                processState(argument);
            } else if (cmd.equals("PROXY")) {
                processProxyCMD(argument);
            } else if (cmd.equals("LOG")) {
                processLogMessage(argument);
            } else if (cmd.equals("RSA_SIGN")) {
                processSignCommand(argument);
            } else {
                VpnStatus.logWarning("MGMT: Got unrecognized command" + command);
                Log.i(TAG, "Got unrecognized command" + command);
            }
        } else if (command.startsWith("SUCCESS:")) {
            /* Ignore this kind of message too */
            return;
        } else if (command.startsWith("PROTECTFD: ")) {
            FileDescriptor fdtoprotect = mFDList.pollFirst();
            if (fdtoprotect != null)
                protectFileDescriptor(fdtoprotect);
        } else {
            Log.i(TAG, "Got unrecognized line from managment" + command);
            VpnStatus.logWarning("MGMT: Got unrecognized line from management:" + command);
        }
    }

    private void processLogMessage(String argument) {
        String[] args = argument.split(",", 4);
        Log.d("OpenVPN", argument);

        VpnStatus.LogLevel level;
        if (args[1].equals("I")) {
            level = VpnStatus.LogLevel.INFO;
        } else if (args[1].equals("W")) {
            level = VpnStatus.LogLevel.WARNING;
        } else if (args[1].equals("D")) {
            level = VpnStatus.LogLevel.VERBOSE;
        } else if (args[1].equals("F")) {
            level = VpnStatus.LogLevel.ERROR;
        } else {
            level = VpnStatus.LogLevel.INFO;
        }

        int ovpnlevel = Integer.parseInt(args[2]) & 0x0F;
        String msg = args[3];

        if (msg.startsWith("MANAGEMENT: CMD"))
            ovpnlevel = Math.max(4, ovpnlevel);

        VpnStatus.logMessageOpenVPN(level, ovpnlevel, msg);
    }

    private void handleHold() {
        if (mReleaseHold) {
            releaseHoldCmd();
        } else {
            mWaitingForRelease = true;
            VpnStatus.updateStatePause(lastPauseReason);

        }
    }

    private void releaseHoldCmd() {
        if ((System.currentTimeMillis() - mLastHoldRelease) < 5000) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ignored) {
            }

        }
        mWaitingForRelease = false;
        mLastHoldRelease = System.currentTimeMillis();
        managmentCommand("hold release\n");
        managmentCommand("bytecount " + mBytecountInterval + "\n");
        managmentCommand("state on\n");
    }

    public void releaseHold() {
        mReleaseHold = true;
        if (mWaitingForRelease)
            releaseHoldCmd();

    }

    private void processProxyCMD(String argument) {
        String[] args = argument.split(",", 3);
        SocketAddress proxyaddr = ProxyDetection.detectProxy(mProfile);

        if (args.length >= 2) {
            String proto = args[1];
            if (proto.equals("UDP")) {
                proxyaddr = null;
            }
        }

        if (proxyaddr instanceof InetSocketAddress) {
            InetSocketAddress isa = (InetSocketAddress) proxyaddr;

            VpnStatus.logInfo(R.string.using_proxy, isa.getHostName(), isa.getPort());

            String proxycmd = String.format(Locale.ENGLISH, "proxy HTTP %s %d\n", isa.getHostName(), isa.getPort());
            managmentCommand(proxycmd);
        } else {
            managmentCommand("proxy NONE\n");
        }

    }

    private void processState(String argument) {
        String[] args = argument.split(",", 3);
        String currentstate = args[1];

        if (args[2].equals(",,"))
            VpnStatus.updateStateString(currentstate, "");
        else
            VpnStatus.updateStateString(currentstate, args[2]);
    }

    private void processByteCount(String argument) {
        //   >BYTECOUNT:{BYTES_IN},{BYTES_OUT}
        int comma = argument.indexOf(',');
        long in = Long.parseLong(argument.substring(0, comma));
        long out = Long.parseLong(argument.substring(comma + 1));
        VpnStatus.updateByteCount(in, out);
    }
    private void processNeedCommand(String argument) {
        int p1 = argument.indexOf('\'');
        int p2 = argument.indexOf('\'', p1 + 1);
        String needed = argument.substring(p1 + 1, p2);
        String extra = argument.split(":", 2)[1];
        String status = "ok";
        if (needed.equals("PROTECTFD")) {
            FileDescriptor fdtoprotect = mFDList.pollFirst();
            protectFileDescriptor(fdtoprotect);
        } else if (needed.equals("DNSSERVER")) {
            mOpenVPNService.addDNS(extra);
        } else if (needed.equals("DNSDOMAIN")) {
            mOpenVPNService.setDomain(extra);
        } else if (needed.equals("ROUTE")) {
            String[] routeparts = extra.split(" ");

            if (routeparts.length == 5) {
                if (BuildConfig.DEBUG) Assert.assertEquals("dev", routeparts[3]);
                mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]);
            } else if (routeparts.length >= 3) {
                mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null);
            } else {
                VpnStatus.logError("Unrecognized ROUTE cmd:" + Arrays.toString(routeparts) + " | " + argument);
            }

        } else if (needed.equals("ROUTE6")) {
            String[] routeparts = extra.split(" ");
            mOpenVPNService.addRoutev6(routeparts[0], routeparts[1]);
        } else if (needed.equals("IFCONFIG")) {
            String[] ifconfigparts = extra.split(" ");
            int mtu = Integer.parseInt(ifconfigparts[2]);
            mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1], mtu, ifconfigparts[3]);
        } else if (needed.equals("IFCONFIG6")) {
            mOpenVPNService.setLocalIPv6(extra);

        } else if (needed.equals("PERSIST_TUN_ACTION")) {
            // check if tun cfg stayed the same
            status = mOpenVPNService.getTunReopenStatus();
        } else if (needed.equals("OPENTUN")) {
            if (sendTunFD(needed, extra))
                return;
            else
                status = "cancel";
        } else {
            Log.e(TAG, "Unkown needok command " + argument);
            return;
        }
        String cmd = String.format("needok '%s' %s\n", needed, status);
        managmentCommand(cmd);
    }
    private boolean sendTunFD(String needed, String extra) {
        Exception exp;
        if (!extra.equals("tun")) {
            VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!", extra));
            return false;
        }
        ParcelFileDescriptor pfd = mOpenVPNService.openTun();
        if (pfd == null)
            return false;

        Method setInt;
        int fdint = pfd.getFd();
        try {
            setInt = FileDescriptor.class.getDeclaredMethod("setInt$", int.class);
            FileDescriptor fdtosend = new FileDescriptor();
            setInt.invoke(fdtosend, fdint);
            FileDescriptor[] fds = {fdtosend};
            mSocket.setFileDescriptorsForSend(fds);
            String cmd = String.format("needok '%s' %s\n", needed, "ok");
            managmentCommand(cmd);
            mSocket.setFileDescriptorsForSend(null);
            pfd.close();
            return true;
        } catch (NoSuchMethodException e) {
            exp = e;
        } catch (IllegalArgumentException e) {
            exp = e;
        } catch (IllegalAccessException e) {
            exp = e;
        } catch (InvocationTargetException e) {
            exp = e;
        } catch (IOException e) {
            exp = e;
        }
        VpnStatus.logException("Could not send fd over socket", exp);
        return false;
    }

    private void processPWCommand(String argument) {
        String needed;
        try {

            int p1 = argument.indexOf('\'');
            int p2 = argument.indexOf('\'', p1 + 1);
            needed = argument.substring(p1 + 1, p2);
            if (argument.startsWith("Verification Failed")) {
                proccessPWFailed(needed, argument.substring(p2 + 1));
                return;
            }
        } catch (StringIndexOutOfBoundsException sioob) {
            VpnStatus.logError("Could not parse management Password command: " + argument);
            return;
        }
        String pw = null;

        if (needed.equals("Private Key")) {
            pw = mProfile.getPasswordPrivateKey();
        } else if (needed.equals("Auth")) {
            String usercmd = String.format("username '%s' %s\n",
                    needed, VpnProfile.openVpnEscape(mProfile.mUsername));
            managmentCommand(usercmd);
            pw = mProfile.getPasswordAuth();
        }
        if (pw != null) {
            String cmd = String.format("password '%s' %s\n", needed, VpnProfile.openVpnEscape(pw));
            managmentCommand(cmd);
        } else {
            VpnStatus.logError(String.format("Openvpn requires Authentication type '%s' but no password/key information available", needed));
        }
    }

    private void proccessPWFailed(String needed, String args) {
        VpnStatus.updateStateString("AUTH_FAILED", needed + args,R.string.state_auth_failed, VpnStatus.ConnectionStatus.LEVEL_AUTH_FAILED);
    }
    private static boolean stopOpenVPN() {
        synchronized (active) {
            boolean sendCMD = false;
            for (OpenVpnManagementThread mt : active) {
                mt.managmentCommand("signal SIGINT\n");
                sendCMD = true;
                try {
                    if (mt.mSocket != null)
                        mt.mSocket.close();
                } catch (IOException e) {
                }
            }
            return sendCMD;
        }
    }

    @Override
    public void networkChange() {
        if (!mWaitingForRelease)
            managmentCommand("network-change\n");
    }

    public void signalusr1() {
        mReleaseHold = false;

        if (!mWaitingForRelease)
            managmentCommand("signal SIGUSR1\n");
        else
            VpnStatus.updateStatePause(lastPauseReason);
    }

    public void reconnect() {
        signalusr1();
        releaseHold();
    }
    private void processSignCommand(String b64data) {
        String signed_string = mProfile.getSignedData(b64data);
        if (signed_string == null) {
            managmentCommand("rsa-sig\n");
            managmentCommand("\nEND\n");
            stopOpenVPN();
            return;
        }
        managmentCommand("rsa-sig\n");
        managmentCommand(signed_string);
        managmentCommand("\nEND\n");
    }
    @Override
    public void pause(pauseReason reason) {
        lastPauseReason = reason;
        signalusr1();
    }

    @Override
    public void resume() {
        releaseHold();
        /* Reset the reason why we are disconnected */
        lastPauseReason = pauseReason.noNetwork;
    }
    @Override
    public boolean stopVPN() {
        return stopOpenVPN();
    }
}

The MainActivity_vpn Class:

public class MainActivity_vpn extends Activity {
protected OpenVPNService mService;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        OpenVPNService.LocalBinder binder = (OpenVPNService.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mService =null;
        mBound = false;
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_vpn);
    Intent intent = new Intent(getBaseContext(), OpenVPNService.class);
    intent.setAction(OpenVPNService.START_SERVICE);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    registerReceiver(broadcastReceiver, new IntentFilter("CONNECTION_CHANGE"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.settingsmenu, menu);
    return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (Constants.isVPNConnected){
        // disable connect button if VPN is connected
        menu.getItem(0).setEnabled(false);
        // enable disconnect button if VPN is connected
        menu.getItem(1).setEnabled(true);
    } else{
        // enable connect button if VPN is disconnected
        menu.getItem(0).setEnabled(true);
        // disable disconnect button if VPN is disconnected
        menu.getItem(1).setEnabled(false);
    }
    return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_startvpn:
            configureAndStartVpn() ;
            return true ;
        case R.id.action_stopvpn:
            stopVPN() ;
            return true ;
        case R.id.action_removeProfile:
            removeProfile();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
private void removeProfile() {

    final ProfileManager pm = ProfileManager.getInstance(MainActivity_vpn.this) ;
    final VpnProfile profile = pm.getProfileByName(Constants.VPN_PROFILE_NAME) ;

    if (profile != null) {
                        stopVPN() ;
                        pm.removeProfile(getApplicationContext(),profile);
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(MainActivity_vpn.this,"The VPN Configuration is deleted", duration);
                        toast.show();
    } else {
                int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(MainActivity_vpn.this,"There are no VPN Configurations to delete", duration);toast.show();
    }
}
private void stopVPN() {
    try{
        ProfileManager.setConntectedVpnProfileDisconnected(MainActivity_vpn.this);
        if(mService.getManagement()!=null)
            mService.getManagement().stopVPN();
    }
    catch (Exception ex){
    }
}
private void configureAndStartVpn() {
    try {
                EditText Et_Ovpn = (EditText) findViewById(R.id.et_ovpn);

                String retVal = Et_Ovpn.getText().toString();

                if (retVal != null && retVal.trim().length()>0) {

                    byte[] buffer = retVal.getBytes() ;

                    VpnProfile vp = saveProfile(buffer) ;

                    if (vp != null) {
                        startVPN(vp) ;
                    }
                }
                else {
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(MainActivity_vpn.this,"Connecting using the last vpn configuration", duration);
                    toast.show();
                    startVPN();
                }
    } catch (Exception e) {
        e.printStackTrace() ;
    }
}
private VpnProfile saveProfile(byte [] data) {

    ConfigParser cp = new ConfigParser();
    try {
        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(data));
        cp.parseConfig(isr);
        VpnProfile vp = cp.convertProfile();
        ProfileManager vpl = ProfileManager.getInstance(this);
        vp.mName = Constants.VPN_PROFILE_NAME ;
        vpl.addProfile(vp);
        vpl.saveProfile(this, vp);
        vpl.saveProfileList(this);
        return vp ;
    } catch(Exception e) {
        return null ;
    }
}
public void startVPN(VpnProfile vp) {
    Intent intent = new Intent(getApplicationContext(),LaunchVPN.class);
    intent.putExtra(LaunchVPN.EXTRA_KEY, vp.getUUID().toString());
    intent.setAction(Intent.ACTION_MAIN);
    startActivity(intent);
}
private void startVPN() {

    ProfileManager pm = ProfileManager.getInstance(this) ;
    VpnProfile profile = pm.getProfileByName(Constants.VPN_PROFILE_NAME) ;

    if (profile == null) {
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(MainActivity_vpn.this,"There are no VPN Configurations.So paste the .OVPN and try", duration);
        toast.show();
        return ;
    }

    Intent intent = new Intent(this,LaunchVPN.class);
    intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUID().toString());
    intent.setAction(Intent.ACTION_MAIN);
    startActivity(intent);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        stopVPN();
        startVPN();
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}

}

Body:
From your log i saw this line:

MainActivity_vpn has leaked ServiceConnection

In your activity OnCreate you're binding to service but you never unbind.
Add this to you're onDestroy method in your MainActivity:

    if (mServiceConn != null) {
      unbindService(mServiceConn);
    }

Also, see this:
JNI- java.lang.UnsatisfiedLinkError: Native method not found

I think that you should remove the static from your methods signature


问:
Getting specific fields' values of a text using awk, sed, and grep
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

```<code>{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}
</code>```

答:
try with another following awk solutions too here.

1st approach: IN case you need to have double course around the and name values.

```<code>awk -F'[:,]' '/name/{sub(/^ +/,"",$2);print $2}'   Input_file
</code>```

2nd approach: In case if you need only the name's values then following may help you in same.

```<code>awk -F'[":,]' '/name/{print $5}'   Input_file
</code>```

Explanation of 1st approach: Simply making (:  and ,) as field separators and then looking for string name in a line if it contains then substituting the initial space of 2nd field with NULL and then printing the 2nd field's value.

Explanation of 2nd approach: Making (" : and ,) as field separators. Then searching for string name in a line, if it has it then printing the 5th field of that line.

Body:
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}

Body:
try with another following awk solutions too here.

1st approach: IN case you need to have double course around the and name values.

awk -F'[:,]' '/name/{sub(/^ +/,"",$2);print $2}'   Input_file

2nd approach: In case if you need only the name's values then following may help you in same.

awk -F'[":,]' '/name/{print $5}'   Input_file

Explanation of 1st approach: Simply making (:  and ,) as field separators and then looking for string name in a line if it contains then substituting the initial space of 2nd field with NULL and then printing the 2nd field's value.

Explanation of 2nd approach: Making (" : and ,) as field separators. Then searching for string name in a line, if it has it then printing the 5th field of that line.


问:
How to make an object slide left and right automaticly in Unity 5.6?
I'm currently developing a game in Unity 3D with c#. I developed some levels, and now I want to make some levels with auto moving cubes(the thematic of the game is cubes). I searched a lot on the internet but I don't find nothing wich satisfy me. Can someone help me? I really need help. Sorry if there are some grammare errors.</p>

答:
Create a new Script an name it SimpleTranslator.cs then copy and paste the below code.</p>

```<code>using UnityEngine;

namespace TransformUtility
{
    public class SimpleTranslator : MonoBehaviour
    {
        [Tooltip("The local target position towards we translate this gameObject. A red line is drawn.")]
        public Vector3 m_localTargetPosition = new Vector3(0, 0, 5);
        public float speed = 1;
        public bool pingPong;
        public bool translateOnAwake = true;
        public new AudioSource audio;

        Vector3 m_initialPosition, m_targetPosition;
        Transform m_transform;

        void Awake()
        {
            m_transform = transform;
            m_initialPosition = m_transform.position;

            SetTargetPosition(m_localTargetPosition);
            enabled = translateOnAwake;
        }

        void FixedUpdate()
        {
            if (audio && !audio.isPlaying)
                audio.Play();

            m_transform.position = Vector3.MoveTowards(m_transform.position, m_targetPosition, speed * Time.deltaTime);

            if (m_transform.position == m_targetPosition)
            {
                if (pingPong)
                {
                    SwitchDirection();
                }
                else
                {
                    enabled = false;

                    if (audio)
                        audio.Stop();
                }
            }
        }

        public bool isTranslating
        {
            get
            {
                return enabled;
            }
        }

        public void SwitchDirection()
        {
            enabled = true;

            if (m_transform.position == m_initialPosition)
            {
                SetTargetPosition(m_localTargetPosition);
            }
            else
            {
                m_targetPosition = m_initialPosition;
            }
        }

        public void MoveToTargetPosition()
        {
            enabled = true;
            SetTargetPosition(m_localTargetPosition);
        }

        public void MoveToInitialPosition()
        {
            m_targetPosition = m_initialPosition;
            enabled = true;
        }

        public bool isInInitialPosition
        {
            get
            {
                return m_transform.position == m_initialPosition;
            }
        }

        public bool isInTargetPosition
        {
            get
            {
                return m_transform.position == m_initialPosition + m_transform.TransformDirection(m_localTargetPosition);
            }
        }

        private void SetTargetPosition(Vector3 localPosition)
        {
            m_targetPosition = m_initialPosition + transform.TransformDirection(localPosition);

#if UNITY_EDITOR
            m_endPositionDebug = m_targetPosition;
#endif
        }

#if UNITY_EDITOR
        Vector3 m_endPositionDebug;

        void OnDrawGizmos()
        {
            if (!Application.isPlaying)
            {
                Debug.DrawRay(transform.position, transform.TransformDirection(m_localTargetPosition), Color.red);
            }
            else
            {
                Debug.DrawLine(m_initialPosition, m_endPositionDebug, Color.red);
            }
        }
#endif
    }
}
</code>```

Body:
Create a new Script an name it SimpleTranslator.cs then copy and paste the below code.

using UnityEngine;

namespace TransformUtility
{
    public class SimpleTranslator : MonoBehaviour
    {
        [Tooltip("The local target position towards we translate this gameObject. A red line is drawn.")]
        public Vector3 m_localTargetPosition = new Vector3(0, 0, 5);
        public float speed = 1;
        public bool pingPong;
        public bool translateOnAwake = true;
        public new AudioSource audio;

        Vector3 m_initialPosition, m_targetPosition;
        Transform m_transform;

        void Awake()
        {
            m_transform = transform;
            m_initialPosition = m_transform.position;

            SetTargetPosition(m_localTargetPosition);
            enabled = translateOnAwake;
        }

        void FixedUpdate()
        {
            if (audio && !audio.isPlaying)
                audio.Play();

            m_transform.position = Vector3.MoveTowards(m_transform.position, m_targetPosition, speed * Time.deltaTime);

            if (m_transform.position == m_targetPosition)
            {
                if (pingPong)
                {
                    SwitchDirection();
                }
                else
                {
                    enabled = false;

                    if (audio)
                        audio.Stop();
                }
            }
        }

        public bool isTranslating
        {
            get
            {
                return enabled;
            }
        }

        public void SwitchDirection()
        {
            enabled = true;

            if (m_transform.position == m_initialPosition)
            {
                SetTargetPosition(m_localTargetPosition);
            }
            else
            {
                m_targetPosition = m_initialPosition;
            }
        }

        public void MoveToTargetPosition()
        {
            enabled = true;
            SetTargetPosition(m_localTargetPosition);
        }

        public void MoveToInitialPosition()
        {
            m_targetPosition = m_initialPosition;
            enabled = true;
        }

        public bool isInInitialPosition
        {
            get
            {
                return m_transform.position == m_initialPosition;
            }
        }

        public bool isInTargetPosition
        {
            get
            {
                return m_transform.position == m_initialPosition + m_transform.TransformDirection(m_localTargetPosition);
            }
        }

        private void SetTargetPosition(Vector3 localPosition)
        {
            m_targetPosition = m_initialPosition + transform.TransformDirection(localPosition);

#if UNITY_EDITOR
            m_endPositionDebug = m_targetPosition;
#endif
        }

#if UNITY_EDITOR
        Vector3 m_endPositionDebug;

        void OnDrawGizmos()
        {
            if (!Application.isPlaying)
            {
                Debug.DrawRay(transform.position, transform.TransformDirection(m_localTargetPosition), Color.red);
            }
            else
            {
                Debug.DrawLine(m_initialPosition, m_endPositionDebug, Color.red);
            }
        }
#endif
    }
}


问:
Typescript type requiring any one attribute of an object to be defined: how?
I have the following TypeScript code:

```<code>interface qux {
    foo?: string;
    bar?: number | string;
}

function foobar(x: qux) { ...; something_frobz(x); ...; }
</code>```

Problem: I can call foobar("hello, world"), even though this causes something_frobz to misbehave. I would like to catch and reject calls to foobar with string argument at compile time, while altering the structure of qux as little as possible. What's the best way of going about this?

My own solution is to make one field required; that field has a sensible default value, and AFAIK string doesn't have any fields with the same name. That's a bit of a hack, but it works.

Another approach might be to have foobar take a union type of first-field-is-required | second-field-is-required | ... | hundredth-field-is-required, but then I have to maintain N almost-identical copies of qux (for N > 1) and that never goes well.

Is there anything better?

答:
I would like to add that Typescript 2.4 addresses this problem.

TypeScript 2.4 introduces the concept of “weak types”. A weak type is any type that contains nothing but all-optional properties. [...] In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties. That includes primitives like number, string, and boolean.

https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/#stricter-checks-on-weak-types

Body:
I have the following TypeScript code:

interface qux {
    foo?: string;
    bar?: number | string;
}

function foobar(x: qux) { ...; something_frobz(x); ...; }

Problem: I can call foobar("hello, world"), even though this causes something_frobz to misbehave. I would like to catch and reject calls to foobar with string argument at compile time, while altering the structure of qux as little as possible. What's the best way of going about this?

My own solution is to make one field required; that field has a sensible default value, and AFAIK string doesn't have any fields with the same name. That's a bit of a hack, but it works.

Another approach might be to have foobar take a union type of first-field-is-required | second-field-is-required | ... | hundredth-field-is-required, but then I have to maintain N almost-identical copies of qux (for N > 1) and that never goes well.

Is there anything better?