问:
How can I monkey-patch an instance method in Perl?
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

答:
```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

You have not 1, but 2 problems here, because this is what you are doing:

```<code>( $agent->get_basic_credentials() ) = _user_agent_get_basic_credentials_patch();
</code>```

on both sides cases, you're calling the subs instead of simply referring to them.

```<code>assign the result of
              '_user_agent_get_basic_credentials_patch'
to the value that was returned from
              'get_basic_credentials';
</code>```

Equivalent logic :

```<code>{
   package FooBar;
   sub foo(){
         return 5;
   }
   1;
}
my $x =  bless( {}, "FooBar" );
sub baz(){
      return 1;
}
$x->foo() = baz();
#   5 = 1;
</code>```

So its no wonder its complaining.

Your "fixed" code in your answer is also wrong, for the same reason, with another problem you may not realise:

```<code> $agent->{get_basic_credentials} = _user_agent_get_basic_credentials_patch;
</code>```

This is rather flawed logic thinking it works like you think it does.

What it is really doing, is:

```<code>1. Dereference $agent, which is a HashRef
2. Set the hash-key 'get_basic_credentials' to the result from _user_agent_get_basic_credentials_patch
</code>```

You didn't assign any function at all.

```<code>{
package FooBar;
sub foo(){
     return 5;
}
1;
}
my $x =  bless( {}, "FooBar" );
sub baz(){
  return 1;
}
$x->{foo} = baz();
#  $x is now  = ( bless{ foo => 1 }, "FooBar" );
#  $x->foo(); # still returns 5
#  $x->{foo}; # returns 1;
</code>```

Monkey patching is rather evil of course, and I have not myself seen how to override a method on a singular instance of something like that.

However, what you can do is this:

```<code>  {
     no strict 'refs';
     *{'LWP::UserAgent::get_basic_credentials'} = sub {
         # code here

     };
  }
</code>```

Which will globally replace the get_basic_credentials code sections behaviour ( I might be wrong somewhat, somebody correct me )

If you really need to do it on a per-instance basis you could probably do a bit of  class inheritance and just build a derived class instead, and/or dynamically create new packages.

OwnerDisplayName: cdleary

Body:
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

LastEditorDisplayName: cdleary

Body:
sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

You have not 1, but 2 problems here, because this is what you are doing:

( $agent->get_basic_credentials() ) = _user_agent_get_basic_credentials_patch();

on both sides cases, you're calling the subs instead of simply referring to them.

assign the result of
              '_user_agent_get_basic_credentials_patch'
to the value that was returned from
              'get_basic_credentials';

Equivalent logic :

{
   package FooBar;
   sub foo(){
         return 5;
   }
   1;
}
my $x =  bless( {}, "FooBar" );
sub baz(){
      return 1;
}
$x->foo() = baz();
#   5 = 1;

So its no wonder its complaining.

Your "fixed" code in your answer is also wrong, for the same reason, with another problem you may not realise:

 $agent->{get_basic_credentials} = _user_agent_get_basic_credentials_patch;

This is rather flawed logic thinking it works like you think it does.

What it is really doing, is:

1. Dereference $agent, which is a HashRef
2. Set the hash-key 'get_basic_credentials' to the result from _user_agent_get_basic_credentials_patch

You didn't assign any function at all.

{
package FooBar;
sub foo(){
     return 5;
}
1;
}
my $x =  bless( {}, "FooBar" );
sub baz(){
  return 1;
}
$x->{foo} = baz();
#  $x is now  = ( bless{ foo => 1 }, "FooBar" );
#  $x->foo(); # still returns 5
#  $x->{foo}; # returns 1;

Monkey patching is rather evil of course, and I have not myself seen how to override a method on a singular instance of something like that.

However, what you can do is this:

  {
     no strict 'refs';
     *{'LWP::UserAgent::get_basic_credentials'} = sub {
         # code here

     };
  }

Which will globally replace the get_basic_credentials code sections behaviour ( I might be wrong somewhat, somebody correct me )

If you really need to do it on a per-instance basis you could probably do a bit of  class inheritance and just build a derived class instead, and/or dynamically create new packages.

OwnerDisplayName: Kent Fredric


来源: stackexchange

问:
Angular Validator.maxlength show message on keypress
I would like to show validation messages on keypress for certain validations such as max length. Currently, they show if you tab out or click out of the field.

Form group:

```<code>this.shortForm = this.fb.group({
  fName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]]
})
</code>```

template:

```<code><md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength') && shortForm.get('fName').touched">
      Maximum of 50 characters
 </md-error>
</md-input-container>
</code>```

Also does not work:

```<code><md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
      Maximum of 50 characters
 </md-error>
</md-input-container>
</code>```

How can I display the error message if the user input hits max-length on keypress instead of waiting for them to tab or click out?

Update:

If I move

```<code><md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
 Maximum of 50 characters
</md-error>
</code>```

to the outside of md-input-container, the error message displayed in keypress. Is this possibly a bug within angular material?

Update #2:
https://github.com/angular/material2/issues/4027

答:
As mentioned, the input gets marked as touched once it is blurred. As a default, md-error is shown when the invalid control is touched. You can change it to show when dirty using a custom errorStateMatcher.

See the input docs.

app.component.html

```<code><md-input-container>
  <input mdInput type="text" formControlName="fName" placeholder="First Name" [errorStateMatcher]="dirtyMatcher">
  <md-error *ngIf="fNameControl.hasError('maxlength')">
    Maximum of 50 characters
   </md-error>
</md-input-container>
</code>```

app.component.ts

```<code>/** Whether the invalid control is dirty or submitted */
dirtyMatcher(control: FormControl, form: FormGroupDirective | NgForm): boolean {
  const isSubmitted = form && form.submitted;
  return !!(control.invalid && (control.dirty || isSubmitted)));
}
</code>```

Also checkout this plunker showing an example.

EDIT: There is also a global option to always show errors on dirty for all inputs (see the input docs). Also, you can make the errorStateMatcher as complicated as you need (you will need to .bind(this) in the template if you wish to use instance properties in your error state calculation).

ContentLicense: CC BY-SA 3.0

Body:
I would like to show validation messages on keypress for certain validations such as max length. Currently, they show if you tab out or click out of the field.

Form group:

this.shortForm = this.fb.group({
  fName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]]
})

template:

<md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength') && shortForm.get('fName').touched">
      Maximum of 50 characters
 </md-error>
</md-input-container>

Also does not work:

<md-input-container>
 <md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
      Maximum of 50 characters
 </md-error>
</md-input-container>

How can I display the error message if the user input hits max-length on keypress instead of waiting for them to tab or click out?

Update:

If I move

<md-error *ngIf="shortForm.get('fName').hasError('maxlength')">
 Maximum of 50 characters
</md-error>

to the outside of md-input-container, the error message displayed in keypress. Is this possibly a bug within angular material?

Update #2:
https://github.com/angular/material2/issues/4027

Body:
As mentioned, the input gets marked as touched once it is blurred. As a default, md-error is shown when the invalid control is touched. You can change it to show when dirty using a custom errorStateMatcher.

See the input docs.

app.component.html

<md-input-container>
  <input mdInput type="text" formControlName="fName" placeholder="First Name" [errorStateMatcher]="dirtyMatcher">
  <md-error *ngIf="fNameControl.hasError('maxlength')">
    Maximum of 50 characters
   </md-error>
</md-input-container>

app.component.ts

/** Whether the invalid control is dirty or submitted */
dirtyMatcher(control: FormControl, form: FormGroupDirective | NgForm): boolean {
  const isSubmitted = form && form.submitted;
  return !!(control.invalid && (control.dirty || isSubmitted)));
}

Also checkout this plunker showing an example.

EDIT: There is also a global option to always show errors on dirty for all inputs (see the input docs). Also, you can make the errorStateMatcher as complicated as you need (you will need to .bind(this) in the template if you wish to use instance properties in your error state calculation).


问:
android.view.InflateException - cannot find reason
This is my fragment inputtext_fragment.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>
</code>```

inputText fragment in java:

```<code>package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}
</code>```

This is the activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>
</code>```

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

```<code>W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more
</code>```

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.

答:
Remove the fragment from inputtext_fragment.xml layout,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

</LinearLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my fragment inputtext_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>

inputText fragment in java:

package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}

This is the activity layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.

Body:
Remove the fragment from inputtext_fragment.xml layout,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

</LinearLayout>


问:
Using Javascript to play an array sequence audio files
I'm a beginner of Javascript. And I'm trying to do a little project that can play array audio files sequently. The code below are inside of annyang API. My idea is to wait for 10 seconds after say some certain words and play the first element in the array, and then wait for 10 seconds, play the second element of the array, and so on so forth. Thus, I use the for loop, but I don't why, it always plays the 'oh_interesting_why' which is the third element. </p>

```<code>var playList = ["tell_me_more", "why", "oh_interesting_why"];

var dir = "sound/";
var extention = ".wav";
var i;
var agent = navigator.userAgent.toLowerCase();

if (agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1) {
  extention = ".wav";
}

//audio = new Audio();

for (i = 0; i < playList.length; i++) {
  audio = new Audio();
  //audio = dir + playList[i] + extention;
  audio.src = dir + playList[i] + extention;
  audio.load();
  setTimeout(function() {
    audio.play();
  }, 10000);
}

audio.loop = false;
</code>```

<p>I have been struggling with is for 2 days. Can't figure out why.
I'm open to use jQuery, Javascript, or HTML5. Please help me!!
Thank you in advance. </p>

答:
I figured it out by using onended function. The below link is the solution.

https://stackoverflow.com/a/27364285/8105243

Body:
I'm a beginner of Javascript. And I'm trying to do a little project that can play array audio files sequently. The code below are inside of annyang API. My idea is to wait for 10 seconds after say some certain words and play the first element in the array, and then wait for 10 seconds, play the second element of the array, and so on so forth. Thus, I use the for loop, but I don't why, it always plays the 'oh_interesting_why' which is the third element.

var playList = ["tell_me_more", "why", "oh_interesting_why"];

var dir = "sound/";
var extention = ".wav";
var i;
var agent = navigator.userAgent.toLowerCase();

if (agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1) {
  extention = ".wav";
}

//audio = new Audio();

for (i = 0; i < playList.length; i++) {
  audio = new Audio();
  //audio = dir + playList[i] + extention;
  audio.src = dir + playList[i] + extention;
  audio.load();
  setTimeout(function() {
    audio.play();
  }, 10000);
}

audio.loop = false;

I have been struggling with is for 2 days. Can't figure out why.
I'm open to use jQuery, Javascript, or HTML5. Please help me!!
Thank you in advance.


问:
Read excel file from AWS S3 Bucket
Currently I have a method to read an excel file that is on my local machine using filename path like this:

```<code>               // Create COM Objects. Create a COM object for everything that is referenced
               Console.WriteLine("Begin reading file...");
               Excel.Application xlApp = new Excel.Application();
               Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\user1\Desktop\file1.xlsx");
               Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
               Excel.Range xlRange = xlWorksheet.UsedRange;
               // Some code here
</code>```

Now I have to read the file from an AWS S3 bucket, and I'm pretty new to the whole AWS environment. From all the sources I read I think the file you get from a S3 bucket only can be returned as "stream" type.

How do I make it work with my current method?

Is there other better way to do this, my goal is just read an excel file from a S3 bucket and do something with the data inside.

答:
There are a couple of things you can do. Here's a couple

You can save the blob as a local file. Docs from AWS

You can use third party to mount your bucket as a virtual Drive. Check here. Keep in mind you're making your operations across the network here.

You may also just skip the COM objects alltogheter and use ClosedXML. This will avoid the speed and memory issues currently available with COM. This will also give you the flexibility to move it to lambda or containerized services since you're already working with AWS.

I'm sure you're aware by now, one thing you'll need to watch out for is the file permission while your process is working with the file.

Title: Read excel file from AWS S3 Bucket

Body:
Currently I have a method to read an excel file that is on my local machine using filename path like this:

               // Create COM Objects. Create a COM object for everything that is referenced
               Console.WriteLine("Begin reading file...");
               Excel.Application xlApp = new Excel.Application();
               Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\user1\Desktop\file1.xlsx");
               Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
               Excel.Range xlRange = xlWorksheet.UsedRange;
               // Some code here

Now I have to read the file from an AWS S3 bucket, and I'm pretty new to the whole AWS environment. From all the sources I read I think the file you get from a S3 bucket only can be returned as "stream" type.

How do I make it work with my current method?

Is there other better way to do this, my goal is just read an excel file from a S3 bucket and do something with the data inside.


问:
java-- Geometric shapes with polymorphism and encapsulation
Just to make sure this is my homework assignment. I need to implement classes to calculate area and perimeter of geometric shapes.

Overview of what I need: I will give something like "java ShapeTest Rectangle 5 5" in command line which should give area and perimeter of that rectangle.

Here is my code:

Shape.java

```<code>public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}
</code>```

Rectangle.java

```<code>public class Rectangle extends Shape {
private double b;
private double a;

public Rectangle(){

}

public Rectangle(double a, double b) {
    this.a = a;
    this.b = b;
}

@Override
public double area(){
    return a *b;
}

@Override
public  double perimeter(){
    return 2*(a+b);
}

@Override
public String toString() {
    return "Rectangle{" +
            "a=" + a +
            " b=" + b +
            '}';
}
}
</code>```

I have similar Circle, Triangle and Sqaure.java.
This is my ShapeTest.java

```<code>public class FormenTest {

public static void set(){
//I want something here

}

public static void main(String[] args) {

    Rectangle rectangle = new Rectangle(Character.getNumericValue((args[1].charAt(0))),Character.getNumericValue((args[2].charAt(0))) );

    if(args[0].equals("Rectangle")){
        System.out.println(rectangle.area());

        }
    }
}
</code>```

Now, this kind of does what is needed but I don't think this is nice way to do it. In the set method inside ShapeTest class I want to generate shape object which I later use in main method. Any help regarding optimizing the code and filling set method will be appreciated.

答:
Your main method can look something like this:

```<code>public static Shape createShape(String[] args) {
    Shape s = null;
    if(args.length > 0) {
        switch(args[0]) {
            case "Rectangle":
                if(args.length > 2) {
                    s = new Rectangle(Double.parseDouble(args[1]), Double.parseDouble(args[2]));
                }
                break;
            case "Circle":
                if(args.length > 1) {
                    s = new Circle(Double.parseDouble(args[1]));
                }
                break;
            case "Triangle":
                //etc...
                break;
        }
    }
    return s;
}

public static void main(String[] args) {
    Shape s = createShape(args);

    if(s != null) {
        System.out.println("Area: " + s.area());
        System.out.println("Perimeter: " + s.perimeter());
    }
}
</code>```

}

You will want to add user-friendly exception handling of course.

Body:
Just to make sure this is my homework assignment. I need to implement classes to calculate area and perimeter of geometric shapes.

Overview of what I need: I will give something like "java ShapeTest Rectangle 5 5" in command line which should give area and perimeter of that rectangle.

Here is my code:

Shape.java

public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

Rectangle.java

public class Rectangle extends Shape {
private double b;
private double a;

public Rectangle(){

}

public Rectangle(double a, double b) {
    this.a = a;
    this.b = b;
}

@Override
public double area(){
    return a *b;
}

@Override
public  double perimeter(){
    return 2*(a+b);
}

@Override
public String toString() {
    return "Rectangle{" +
            "a=" + a +
            " b=" + b +
            '}';
}
}

I have similar Circle, Triangle and Sqaure.java.
This is my ShapeTest.java

public class FormenTest {

public static void set(){
//I want something here

}

public static void main(String[] args) {

    Rectangle rectangle = new Rectangle(Character.getNumericValue((args[1].charAt(0))),Character.getNumericValue((args[2].charAt(0))) );

    if(args[0].equals("Rectangle")){
        System.out.println(rectangle.area());

        }
    }
}

Now, this kind of does what is needed but I don't think this is nice way to do it. In the set method inside ShapeTest class I want to generate shape object which I later use in main method. Any help regarding optimizing the code and filling set method will be appreciated.

Body:
Your main method can look something like this:

public static Shape createShape(String[] args) {
    Shape s = null;
    if(args.length > 0) {
        switch(args[0]) {
            case "Rectangle":
                if(args.length > 2) {
                    s = new Rectangle(Double.parseDouble(args[1]), Double.parseDouble(args[2]));
                }
                break;
            case "Circle":
                if(args.length > 1) {
                    s = new Circle(Double.parseDouble(args[1]));
                }
                break;
            case "Triangle":
                //etc...
                break;
        }
    }
    return s;
}

public static void main(String[] args) {
    Shape s = createShape(args);

    if(s != null) {
        System.out.println("Area: " + s.area());
        System.out.println("Perimeter: " + s.perimeter());
    }
}

}

You will want to add user-friendly exception handling of course.


问:
Which kernel version are stable/recommended for linux mint 18.2?
LSB Version:    core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch

Distributor ID: LinuxMint

Description:    Linux Mint 18.2 Sonya

Release:    18.2

Codename:   sonya

答:
The version they have in their repo?
http://packages.linuxmint.com/search.php?release=any&section=any&keyword=kernel</p>


问:
puppet node hostname
I'm using puppet to configure servers. I want to print current machine (node) name in *.erb template. There is hostname variable, but this holds puppetmaster hostname. Is there any good reference/list regarding to this topic?

答:
Entering the following command into your terminal will return variables available in your erb files:</p>

```<code>facter --puppet
</code>```

ContentLicense: CC BY-SA 2.5

Title: puppet node hostname

Body:
Entering the following command into your terminal will return variables available in your erb files:

facter --puppet


问:
Detect what JS function is creating an element with Firefox tools
I have a page with elements that JavaScript is creating at some point after the page loads and I want to remove them but I cant find the function that creates them.

I wonder if Firefox tools can help me with that? I use Firefox 53.0.3

答: right click inspect element, search code base for the ID or the class name of the div to see what spawns it. Without knowing if this is jquery, angular, or even the type of element I can not assist you more.</p>

OwnerDisplayName: Cain Nuke


问:
How to open private files saved to the internal storage using Intent.ACTION_VIEW?
I am trying a sample program to store a file in the internal storage and the open it using
Intent.ACTION_VIEW.

For storing the file in private mode I followed the steps provided here.

I was able to find the created file in the internal storage at /data/data/com.storeInternal.poc/files .*

But when I tried to open file,it does not open.

Please find below the code I used for it.

```<code>public class InternalStoragePOCActivity extends Activity {
    /** Called when the activity is first created. */
    String FILENAME = "hello_file.txt";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        openFile(FILENAME);
    }

    public FileOutputStream getStream(String path) throws FileNotFoundException {
        return openFileOutput(path, Context.MODE_PRIVATE);
    }

    public void createFile(){

        String string = "hello world!";
        FileOutputStream fout = null;
        try {
            //getting output stream
            fout = getStream(FILENAME);
            //writng data
            fout.write(string.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fout!=null){
                //closing the output stream
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public void openFile(String filePath) {
        try {
            File temp_file = new File(filePath);

            Uri data = Uri.fromFile(temp_file);
            String type = getMimeType(data.toString());

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(data, type);
            startActivity(intent);

        } catch (Exception e) {
            Log.d("Internal Storage POC ", "No Supported Application found to open this file");
            e.printStackTrace();

        }
    }

    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);

        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }

        return type;
    }
}
</code>```

How may I open the file stored using Context.MODE_PRIVATE by any other existing/appropriate app. Eg: file.pdf should be opened by PDF reader,Video by video Players,etc.

答:
If anyone still faces an issue like: the file couldn't be accessed. This might help u. Along with the content provider u have to set the following flag too...

```<code>intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
</code>```

or

```<code>intent.setFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
</code>```

Body:
I am trying a sample program to store a file in the internal storage and the open it using
Intent.ACTION_VIEW.

For storing the file in private mode I followed the steps provided here.

I was able to find the created file in the internal storage at /data/data/com.storeInternal.poc/files .*

But when I tried to open file,it does not open.

Please find below the code I used for it.

public class InternalStoragePOCActivity extends Activity {
    /** Called when the activity is first created. */
    String FILENAME = "hello_file.txt";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        openFile(FILENAME);
    }

    public FileOutputStream getStream(String path) throws FileNotFoundException {
        return openFileOutput(path, Context.MODE_PRIVATE);
    }

    public void createFile(){

        String string = "hello world!";
        FileOutputStream fout = null;
        try {
            //getting output stream
            fout = getStream(FILENAME);
            //writng data
            fout.write(string.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fout!=null){
                //closing the output stream
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public void openFile(String filePath) {
        try {
            File temp_file = new File(filePath);

            Uri data = Uri.fromFile(temp_file);
            String type = getMimeType(data.toString());

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(data, type);
            startActivity(intent);

        } catch (Exception e) {
            Log.d("Internal Storage POC ", "No Supported Application found to open this file");
            e.printStackTrace();

        }
    }

    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);

        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }

        return type;
    }
}

How may I open the file stored using Context.MODE_PRIVATE by any other existing/appropriate app. Eg: file.pdf should be opened by PDF reader,Video by video Players,etc.

Body:
If anyone still faces an issue like: the file couldn't be accessed. This might help u. Along with the content provider u have to set the following flag too...

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

or

intent.setFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);


问:
JTextComponent : how to update an existing StyledDocument elements
I wrote a two panes diff class using two DefaultStyledDocument.

Now I would like to let the user change, in place, the colours (and, say, boldness) used to show the deletions and insertions, without re-diffing nor keeping the intermediate diff results.

The problem I am facing is that insertString copies the attributes, so I can not just update the Style instance afterward.

I tried DefaultStyledDocument.setLogicalStyle(int, Style) but nothing changed visually.

Do you see a (simple/cheap) way to do the style update without recreating the whole document ?

答:
Logical styles apply to whole paragraphs.  From what I can tell, there is no way to apply a Style to characters within a paragraph and have Swing automatically listen to changes in the Style.

What you can do is use the Style as a regular AttributeSet, then use an ElementIterator to scan for the styled elements, since a Style’s name is stored under the AttributeSet.NameAttribute attribute key:

```<code>void updateHighlight(StyledDocument doc,
                     AttributeSet newStyle) {

    Object styleName = newStyle.getAttribute(AttributeSet.NameAttribute);

    ElementIterator i = new ElementIterator(doc);
    for (Element e = i.first(); e != null; e = i.next()) {
        AttributeSet attr = e.getAttributes();
        Object name = attr.getAttribute(AttributeSet.NameAttribute);
        if (styleName.equals(name)) {
            int start = e.getStartOffset();
            int end = e.getEndOffset();
            doc.setCharacterAttributes(start, end - start,
                newStyle, false);
        }
    }
}
</code>```

Whether that qualifies as “simple/cheap” is up to you to decide.

Here’s a demo:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class StyleChanger {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> show());
    }

    private static final String HIGHLIGHT =
        StyleChanger.class.getName() + ".highlight";

    static void show() {
        JTextPane textPane = new JTextPane();

        Style normal = textPane.getStyle(StyleContext.DEFAULT_STYLE);
        Style highlight = textPane.addStyle(HIGHLIGHT, normal);
        StyleConstants.setBackground(highlight, Color.YELLOW);

        class Fragment {
            final AttributeSet style;
            final String text;

            Fragment(AttributeSet style,
                     String text) {
                this.style = style;
                this.text = text;
            }
        }

        Fragment[] fragments = {
            new Fragment(highlight, "Space"),
            new Fragment(normal, ": the final frontier.  These are the "),
            new Fragment(highlight, "voyages"),
            new Fragment(normal, " of the starship "),
            new Fragment(highlight, "Enterprise"),
            new Fragment(normal, ".  Its five-year "),
            new Fragment(highlight, "mission"),
            new Fragment(normal, ": to explore strange "),
            new Fragment(highlight, "new worlds"),
            new Fragment(normal, "; to seek out "),
            new Fragment(highlight, "new life"),
            new Fragment(normal, " and new civilizations; to "),
            new Fragment(highlight, "boldly go"),
            new Fragment(normal, " where no man has gone before!"),
        };

        for (Fragment fragment : fragments) {
            textPane.setCharacterAttributes(fragment.style, true);
            textPane.replaceSelection(fragment.text);
        }

        Action change = new AbstractAction("Change Highlight\u2026") {
            private static final long serialVersionUID = 1;

            @Override
            public void actionPerformed(ActionEvent event) {
                Color color = JColorChooser.showDialog(
                    textPane.getTopLevelAncestor(),
                    "Highlight Color",
                    textPane.getBackground());

                if (color != null) {
                    StyleConstants.setBackground(highlight, color);
                    updateHighlight(textPane.getStyledDocument(), highlight);
                }
            }
        };

        JButton changeButton = new JButton(change);

        JPanel buttonPane = new JPanel();
        buttonPane.add(changeButton);

        JFrame frame = new JFrame("Style Changer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new JScrollPane(textPane));
        frame.getContentPane().add(buttonPane, BorderLayout.PAGE_END);

        frame.setSize(450, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private static void updateHighlight(StyledDocument doc,
                                        AttributeSet newStyle) {

        Object styleName = newStyle.getAttribute(AttributeSet.NameAttribute);

        ElementIterator i = new ElementIterator(doc);
        for (Element e = i.first(); e != null; e = i.next()) {
            AttributeSet attr = e.getAttributes();
            Object name = attr.getAttribute(AttributeSet.NameAttribute);
            if (styleName.equals(name)) {
                int start = e.getStartOffset();
                int end = e.getEndOffset();
                doc.setCharacterAttributes(start, end - start,
                    newStyle, false);
            }
        }
    }
}
</code>```

Body:
Logical styles apply to whole paragraphs.  From what I can tell, there is no way to apply a Style to characters within a paragraph and have Swing automatically listen to changes in the Style.

What you can do is use the Style as a regular AttributeSet, then use an ElementIterator to scan for the styled elements, since a Style’s name is stored under the AttributeSet.NameAttribute attribute key:

void updateHighlight(StyledDocument doc,
                     AttributeSet newStyle) {

    Object styleName = newStyle.getAttribute(AttributeSet.NameAttribute);

    ElementIterator i = new ElementIterator(doc);
    for (Element e = i.first(); e != null; e = i.next()) {
        AttributeSet attr = e.getAttributes();
        Object name = attr.getAttribute(AttributeSet.NameAttribute);
        if (styleName.equals(name)) {
            int start = e.getStartOffset();
            int end = e.getEndOffset();
            doc.setCharacterAttributes(start, end - start,
                newStyle, false);
        }
    }
}

Whether that qualifies as “simple/cheap” is up to you to decide.

Here’s a demo:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class StyleChanger {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> show());
    }

    private static final String HIGHLIGHT =
        StyleChanger.class.getName() + ".highlight";

    static void show() {
        JTextPane textPane = new JTextPane();

        Style normal = textPane.getStyle(StyleContext.DEFAULT_STYLE);
        Style highlight = textPane.addStyle(HIGHLIGHT, normal);
        StyleConstants.setBackground(highlight, Color.YELLOW);

        class Fragment {
            final AttributeSet style;
            final String text;

            Fragment(AttributeSet style,
                     String text) {
                this.style = style;
                this.text = text;
            }
        }

        Fragment[] fragments = {
            new Fragment(highlight, "Space"),
            new Fragment(normal, ": the final frontier.  These are the "),
            new Fragment(highlight, "voyages"),
            new Fragment(normal, " of the starship "),
            new Fragment(highlight, "Enterprise"),
            new Fragment(normal, ".  Its five-year "),
            new Fragment(highlight, "mission"),
            new Fragment(normal, ": to explore strange "),
            new Fragment(highlight, "new worlds"),
            new Fragment(normal, "; to seek out "),
            new Fragment(highlight, "new life"),
            new Fragment(normal, " and new civilizations; to "),
            new Fragment(highlight, "boldly go"),
            new Fragment(normal, " where no man has gone before!"),
        };

        for (Fragment fragment : fragments) {
            textPane.setCharacterAttributes(fragment.style, true);
            textPane.replaceSelection(fragment.text);
        }

        Action change = new AbstractAction("Change Highlight\u2026") {
            private static final long serialVersionUID = 1;

            @Override
            public void actionPerformed(ActionEvent event) {
                Color color = JColorChooser.showDialog(
                    textPane.getTopLevelAncestor(),
                    "Highlight Color",
                    textPane.getBackground());

                if (color != null) {
                    StyleConstants.setBackground(highlight, color);
                    updateHighlight(textPane.getStyledDocument(), highlight);
                }
            }
        };

        JButton changeButton = new JButton(change);

        JPanel buttonPane = new JPanel();
        buttonPane.add(changeButton);

        JFrame frame = new JFrame("Style Changer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new JScrollPane(textPane));
        frame.getContentPane().add(buttonPane, BorderLayout.PAGE_END);

        frame.setSize(450, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private static void updateHighlight(StyledDocument doc,
                                        AttributeSet newStyle) {

        Object styleName = newStyle.getAttribute(AttributeSet.NameAttribute);

        ElementIterator i = new ElementIterator(doc);
        for (Element e = i.first(); e != null; e = i.next()) {
            AttributeSet attr = e.getAttributes();
            Object name = attr.getAttribute(AttributeSet.NameAttribute);
            if (styleName.equals(name)) {
                int start = e.getStartOffset();
                int end = e.getEndOffset();
                doc.setCharacterAttributes(start, end - start,
                    newStyle, false);
            }
        }
    }
}


问:
deleting repetitive columns in unix
I would like to delete multiple repetitive columns from a huge file (about 1 million).
The columns that I want to delete has the same column names: A and others has different unique name. Say:

A B2 A B3

1.1 AA 1.2 AA

2.1 AB 4.3 CT

2.2 AC 6.4 GT

so column headers are A, B2, A, B3,... .
How could I delete the columns named as A's from the data.

答:
Another in awk:</p>

```<code>$ awk '
NR==1 {
    split($0,a)
    for(i in a)
        if(a[i]=="A")
            delete a[i]
}
{
    for(i=1;i<=NF;i++)
        printf "%s",(i in a?$i OFS:"")
    printf ORS
}' file
B2 B3
AA AA
AB CT
AC GT
</code>```

Title: deleting repetitive columns in unix

Body:
Another in awk:

$ awk '
NR==1 {
    split($0,a)
    for(i in a)
        if(a[i]=="A")
            delete a[i]
}
{
    for(i=1;i<=NF;i++)
        printf "%s",(i in a?$i OFS:"")
    printf ORS
}' file
B2 B3
AA AA
AB CT
AC GT


问:
Angular: Dynamically change <ng-outlet> content
I have a component with a ng-outlet. Now I try to set the outlet content dynamically. My first try was it to just set the innerText property of the DOM-Element, but then all other content of the components template get lost. Maybe I use a completely wrong way, I'm very new to Angular.

Here is my component:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'ks4-error-output',
  templateUrl: './error-output.component.html',
  styleUrls: ['./error-output.component.styl']
})
export class ErrorOutputComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
```

<p>And here the template:</p>

<pre class="lang-html prettyprint-override"><code><div [hidden]="content.innerText==''">
  <span>Error:</span>
  <span #content><ng-content></ng-content></span>
</div>
</code>```

I tried to set the content like this (in this case clear the ng-outlet content):

<form (ngSubmit)="error.innerText=''; ...">...</form>
...
<ks4-error-output #error id="errorOutput"></ks4-error-output>
```

But then the complete content is lost. Same thing if I try to set some content this way. I didn't find anything with google, every time I try searching, google only founds router-oulet things.

答:
ngOutlet is a AngularJS directive. If you are using Angular 2 or 4 (Which I assume you are considering you have @Component in your code), you can use router-outlet to set components to show. It allows for static/dynamic templating using static/dynamic routes.

An alternative without routes is to use the dynamic component loader. It also let you have multiple directives with dynamic component on the same page while router-outlet technically doesn't allow this.

Body:
I have a component with a ng-outlet. Now I try to set the outlet content dynamically. My first try was it to just set the innerText property of the DOM-Element, but then all other content of the components template get lost. Maybe I use a completely wrong way, I'm very new to Angular.

Here is my component:

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'ks4-error-output',
  templateUrl: './error-output.component.html',
  styleUrls: ['./error-output.component.styl']
})
export class ErrorOutputComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

And here the template:

  Error:
  <ng-content></ng-content>

I tried to set the content like this (in this case clear the ng-outlet content):

<form (ngSubmit)="error.innerText=''; ...">...</form>
...
<ks4-error-output #error id="errorOutput"></ks4-error-output>

But then the complete content is lost. Same thing if I try to set some content this way. I didn't find anything with google, every time I try searching, google only founds router-oulet things.


问:
Clarification about LE encryption field used in the LL_FEATURE_REQ and LL_FEATURE_RSP
I sniffed with my Ubertooth One, some BLE packets between my Android phone and my BLE device, and I would like clarifications about a particular field and its meaning.

After the connection is established, a LL_FEATURE_REQ is sent with the value of the LE Encryption field set to 0 (false).

According to the offical documentation (BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], 4.6 FEATURE SUPPORT):

"When this information is sent from a Controller to a Host, a bit set to 0 indicates
  that the Link Layer Feature is not supported in this Controller; a bit set to 1
  indicates that the Link Layer Feature is supported in this Controller.

When this information is sent from a Controller to a peer Controller, a bit set to 0
  indicates that the Link Layer Feature shall not be used by the Controllers; a bit
  set to 1 indicates that the Link Layer Feature may be used by the Controllers.
  "

Also in the LL_FEATURE_RSP the LL Encryption field is set to 0 (false).

So, according to this Message Sequence Chart (BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part D]), before sending the LL_FEATURE_REQ, the Master device (my Android phone), first reads the supported features and then sends the request.

Does this mean that my Android device does not support communication encryption?

EDIT:

Below is the Wireshark output (on the left is the the Bluetooth HCI snoop log from my Android phone, and on the right the packtet captured with my Ubertooth):

答:
If the LL_FEATURE_REQ contains a 0 for position of LE Encryption (position 0), then that device's controller does not support encryption. The LL_FEATURE_RSP contains the bitwise AND of the master's and the slave's supported features.

But it sounds strange that an Android device wouldn't support encryption...


问:
is there a similar way to make this excel-vba code to work on access?
How can I add a automatically number depends on my last row?

On Excel I can take as a reference this code:

```<code>Lastentry = Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
Help1 = Replace(Range("B" & Last_entry).Value, "B-AK", "")
Boxnummer.Value = "B-AK" & (CInt(Help1) + 1)
</code>```

But on my Access database I dont know how to take raws as a reference. I looked on the internet after some solutions but I couldnt find usefull information because actually I havent got good access-skills..

答:
It all depends on what you're trying to achieve. There are a number of different ways to get the record count.

1) DCount function:

```<code>Dim count_ As Long
    count_ = DCount("*","TableName")
</code>```

2) Recordset.RecordCount property:

```<code>Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT * FROM TableName")
    rs.MoveLast

count_ = rs.RecordCount
</code>```

3) Control.ControlSource property:

```<code>TextBox.ControlSource = "=Count(*)"
</code>```

Edit:

In this case you need the DLookup function. Have a look at the attached link to understand more about the DLookup function, but in a few words it means:

Give me the last value in "ColumnName" which is located in "TableName".

```<code>Dim ref As String
    ref = "B-AK" & Format(Date, "yy") & _
          DLookup("ColumnName", "TableName", "ID=" & DMax("ID", "TableName"))
         'Change "ColumnName", "TableName" and "ID" to their actual names.
</code>```

Body:
How can I add a automatically number depends on my last row?

On Excel I can take as a reference this code:

Lastentry = Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
Help1 = Replace(Range("B" & Last_entry).Value, "B-AK", "")
Boxnummer.Value = "B-AK" & (CInt(Help1) + 1)

But on my Access database I dont know how to take raws as a reference. I looked on the internet after some solutions but I couldnt find usefull information because actually I havent got good access-skills..

Body:
It all depends on what you're trying to achieve. There are a number of different ways to get the record count.

1) DCount function:

Dim count_ As Long
    count_ = DCount("*","TableName")

2) Recordset.RecordCount property:

Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT * FROM TableName")
    rs.MoveLast

count_ = rs.RecordCount

3) Control.ControlSource property:

TextBox.ControlSource = "=Count(*)"

Edit:

In this case you need the DLookup function. Have a look at the attached link to understand more about the DLookup function, but in a few words it means:

Give me the last value in "ColumnName" which is located in "TableName".

Dim ref As String
    ref = "B-AK" & Format(Date, "yy") & _
          DLookup("ColumnName", "TableName", "ID=" & DMax("ID", "TableName"))
         'Change "ColumnName", "TableName" and "ID" to their actual names.


问:
How to print invalid QTime?
I want to do something like this

```<code>QTime time (25,0,0);
qDebug() << time.toString();
</code>```

But that will be invalid QTime and outputs ""

Can it be done in some way other then converting QTime to seconds, seconds to string?

答: QTime is time of day, and thus 25:0:0 is invalid. What you seem to want is not time-of-day, but a duration. Qt doesn't ship a QDuration class. It's quite simple though to roll your own (durations are much simpler than dates and times, no timezones etc.).</p>

Title: How to print invalid QTime?

Body:
I want to do something like this

QTime time (25,0,0);
qDebug() << time.toString();

But that will be invalid QTime and outputs ""

Can it be done in some way other then converting QTime to seconds, seconds to string?


问:
Dynamically import classes
Now i have script like this:

```<code>class threadEnum():
    pass

class first(threadEnum):
    pass

class second(threadEnum):
    pass

class third(threadEnum):
    pass

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()
</code>```

which classes is very long and takes a lot of lines. I need to move each class to separate file and then import all classes into main script. So i create folder engines and put inside three files with classes first.py, second.py and third.py also file __init__.py

I think must be something like that:

```<code>import importlib

class threadEnum():
    pass

chosenEnums = []
chosenEnums = ['first', 'second', 'third']

# Load classes from engines folder
for enumm in chosenEnums:
    module = 'engines'
    # create a global object containging our module
    mymethod = getattr(importlib.import_module('engines'), enumm)

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()
</code>```

But i get error:

AttributeError: 'module' object has no attribute 'first'

What is wrong? Python 2.7.6

答:
When you import a folder as a module, the files within it are not immediately loaded as attributes.

```<code>>>> import importlib
>>> print(dir(importlib.import_module('engines'))

['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
</code>```

To load them, you must use an import statement. In this case you could use __import__("{0}.{1}".format(module,enumm)).

Title: Dynamically import classes

Body:
Now i have script like this:

class threadEnum():
    pass

class first(threadEnum):
    pass

class second(threadEnum):
    pass

class third(threadEnum):
    pass

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

which classes is very long and takes a lot of lines. I need to move each class to separate file and then import all classes into main script. So i create folder engines and put inside three files with classes first.py, second.py and third.py also file __init__.py

I think must be something like that:

import importlib

class threadEnum():
    pass

chosenEnums = []
chosenEnums = ['first', 'second', 'third']

# Load classes from engines folder
for enumm in chosenEnums:
    module = 'engines'
    # create a global object containging our module
    mymethod = getattr(importlib.import_module('engines'), enumm)

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

But i get error:

AttributeError: 'module' object has no attribute 'first'

What is wrong? Python 2.7.6

Body:
When you import a folder as a module, the files within it are not immediately loaded as attributes.

>>> import importlib
>>> print(dir(importlib.import_module('engines'))

['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

To load them, you must use an import statement. In this case you could use __import__("{0}.{1}".format(module,enumm)).


问:
lambda function capture and modify own reference
Sometimes there is a need to execute a particular function once and than switch to another implementation.

For example, I am really annoyed by the stream output iterator which prints delimiter after the item being printed in conjunction with the copy algorithm:

```<code>> 1,2,3,4,
         ^---- this is what happens in that case
</code>```

The question isn't about nicely printing items, but more about properly concatenating them.

For example Python produces a correct result using string.join function:

```<code>','.join((1,2,3,4))
> 1,2,3,4
</code>```

I also want to avoid if/else statement, because we only need once to make the switch after the first execution. So what I came up with, is:

```<code>std::function<char const*()> get_delim;

get_delim = [&get_delim]()
{
  get_delim = [](){ return ","; };
  return "";
};

for(auto b : some_byte_range)
  std::cout << get_delim() << b;
</code>```

Note: b is just a byte in my case, that's why I did not use auto const&.

Now the questions:

Is there a way to get rid of the prior std::function<char const*()> declaration and somehow declare get_delim with auto which effectively involves self-capturing of lambda?

Is there may be another more expressive (like in Python) way to do that kind of join?

答:
In this case, all you need is:

```<code>auto get_delim = [c=char(0)]() mutable {
    char cur = c;
    c = ',';
    return cur;
};
</code>```

or even:

```<code>auto get_delim = [c=char(0)]() mutable { return std::exchange(c, ','); }
</code>```

Or use "" and "," if you prefer, should be easy to see how to adjust this to suit your needs.

As far as library goes, there is a std::experimental::ostream_joiner.

Body:
Sometimes there is a need to execute a particular function once and than switch to another implementation.

For example, I am really annoyed by the stream output iterator which prints delimiter after the item being printed in conjunction with the copy algorithm:

> 1,2,3,4,
         ^---- this is what happens in that case

The question isn't about nicely printing items, but more about properly concatenating them.

For example Python produces a correct result using string.join function:

','.join((1,2,3,4))
> 1,2,3,4

I also want to avoid if/else statement, because we only need once to make the switch after the first execution. So what I came up with, is:

std::function<char const*()> get_delim;

get_delim = [&get_delim]()
{
  get_delim = [](){ return ","; };
  return "";
};

for(auto b : some_byte_range)
  std::cout << get_delim() << b;

Note: b is just a byte in my case, that's why I did not use auto const&.

Now the questions:

Is there a way to get rid of the prior std::function<char const*()> declaration and somehow declare get_delim with auto which effectively involves self-capturing of lambda?

Is there may be another more expressive (like in Python) way to do that kind of join?

Body:
In this case, all you need is:

auto get_delim = [c=char(0)]() mutable {
    char cur = c;
    c = ',';
    return cur;
};

or even:

auto get_delim = [c=char(0)]() mutable { return std::exchange(c, ','); }

Or use "" and "," if you prefer, should be easy to see how to adjust this to suit your needs.

As far as library goes, there is a std::experimental::ostream_joiner.


问:
What does an overline above a graph mean?
[Specifically in this example]]1

答:
Not sure if this is the correct forum to post this, but an overline on a graph means the complement of the graph.

https://en.wikipedia.org/wiki/Complement_graph

Body: [Specifically in this example]]1


问:
WPF DataGrid Hide RowDetails or Unselect Row
I have a DataGrid who's RowDetails is set to show when selected (RowDetailsVisibilityMode="VisibleWhenSelected").  Now I want to be able to get rid of it!  I put a close button on the row details with this code:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
  {
   e.Handled = true;
   Button button = sender as Button;
   DataGridRow row = button.FindAncestor<DataGridRow>();

   row.DetailsVisibility = Visibility.Collapsed;
  }
</code>```

That code gets me 90% there, but once the row details is collapsed for a given row it will not appear the next time that row is selected.

答:
Make sure your datagrid has a name such as

```<code><DataGrid x:Name="dgPrimary"
          ...>
</code>```

Place a button in the row template such as

```<code><DataGrid.RowDetailsTemplate>
    <DataTemplate>
        <Button Content="X" Click="Button_Click" Width="20"/>
         ....
</code>```

Then in the codebehind simply set the datagrid's selected index to -1

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    dgPrimary.SelectedIndex = -1;
}
</code>```

Body:
I have a DataGrid who's RowDetails is set to show when selected (RowDetailsVisibilityMode="VisibleWhenSelected").  Now I want to be able to get rid of it!  I put a close button on the row details with this code:

private void Button_Click(object sender, RoutedEventArgs e)
  {
   e.Handled = true;
   Button button = sender as Button;
   DataGridRow row = button.FindAncestor<DataGridRow>();

   row.DetailsVisibility = Visibility.Collapsed;
  }

That code gets me 90% there, but once the row details is collapsed for a given row it will not appear the next time that row is selected.

Body:
Make sure your datagrid has a name such as

<DataGrid x:Name="dgPrimary"
          ...>

Place a button in the row template such as

<DataGrid.RowDetailsTemplate>
    <DataTemplate>
        <Button Content="X" Click="Button_Click" Width="20"/>
         ....

Then in the codebehind simply set the datagrid's selected index to -1

private void Button_Click(object sender, RoutedEventArgs e)
{
    dgPrimary.SelectedIndex = -1;
}


问:
Adding Image into Webpage using AngularJS
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}
```

<p>This is my HTML for adding the image</p>

<pre class="lang-html prettyprint-override"><code><img ng-src="{{product.images[0].full}}"/>
</code>```

答:
Your should use absolute or relative path for the image, like

```<code><img src="/images/{{product.images[0].full}}"/>
</code>```

If you use the latest angularjs 4.x with cli, you need to add the images path to "assets" section in angular-cli.json:

"apps": [
    {
      ......

```<code>  "assets": [
    "assets",
    "favicon.ico",
    "images"
  ],
  ........
</code>```

}

Body:
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}

This is my HTML for adding the image

Body:
Your should use absolute or relative path for the image, like

<img src="/images/{{product.images[0].full}}"/>

If you use the latest angularjs 4.x with cli, you need to add the images path to "assets" section in angular-cli.json:

"apps": [
    {
      ......

  "assets": [
    "assets",
    "favicon.ico",
    "images"
  ],
  ........

}


问:
How can I get the maximum or minimum value in a vector?
How can I get the maximum or minimum value in a vector in C++?

And am I wrong in assuming it would be more or less the same with an array?

I need an iterator, right? I tried it with max_element, but I kept getting an error.

```<code>vector<int>::const_iterator it;
it = max_element(cloud.begin(), cloud.end());
</code>```
```<code>error: request for member ‘begin’ in ‘cloud’, which is of non-class type ‘int [10]’
</code>```

答:
Let,

```<code> #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};
</code>```

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

```<code>int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}
</code>```

You can use iterator,

```<code>for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}
</code>```

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

```<code>int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}
</code>```

Also you can get smallest/largest element by built in functions

```<code>#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());
</code>```

You can get smallest/largest element of any range by using this functions. such as,

```<code>vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)
</code>```

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.

Body:
How can I get the maximum or minimum value in a vector in C++?

And am I wrong in assuming it would be more or less the same with an array?

I need an iterator, right? I tried it with max_element, but I kept getting an error.

vector<int>::const_iterator it;
it = max_element(cloud.begin(), cloud.end());

error: request for member ‘begin’ in ‘cloud’, which is of non-class type ‘int [10]’

Body:
Let,

 #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}

You can use iterator,

for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}

Also you can get smallest/largest element by built in functions

#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());

You can get smallest/largest element of any range by using this functions. such as,

vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.


问:
When we speak of RPC, do we refer to a specific technology on Windows?
I hold different views on the term RPC with my colleague.
We both know RPC is remote procedure call. He said RPC refers to a specific term of Windows technology. I thought it's a more general and abstract concept. I think SOAP, DCOM, COBRA, XML-RPC, WCF are one form of RPC, as there're many different languages/platform and may be based on HTTP or TCP. Only if called remotely can be viewed as RPC. Though I'm not very sure or clear about it either.
Could anyone please to clarify this acronym's scope for me?</p>

答:
It's both a generic term, and refers to specific (older) technologies in both Windows and Unix.  You have to infer from the context.

The "remote" part is also somewhat ambiguous.  It can refer to calling from one process to another on the same host, as well as calling to an entirely different host.


问:
Is there a Spark SQL jdbc driver?
I'm looking for a client jdbc driver that supports Spark SQL.

I have been using Jupyter so far to run SQL statements on Spark (running on HDInsight) and I'd like to be able to connect using JDBC so I can use third-party SQL clients (e.g. SQuirreL, SQL Explorer, etc.) instead of the notebook interface.

I found an ODBC driver from Microsoft but this doesn't help me with java-based SQL clients. I also tried downloading the Hive jdbc driver from my cluster, but the Hive JDBC driver does not appear to support more advance SQL features that Spark does. For example, the Hive driver complains about not supporting join statements that are not equajoins, where I know that this is a supported feature of Spark because I've executed the same SQL in Jupyter successfully.

答:
the Hive JDBC driver does not appear to support more advance SQL features that Spark does

Regardless of the support that it provides, the Spark Thrift Server is fully compatible with Hive/Beeline's JDBC connection.

Therefore, that is the JAR you need to use. I have verified this works in DBVisualizer.

The alternative solution would be to run Spark code in your Java clients (non-third party tools) directly and skip the need for the JDBC connection.

Title: Is there a Spark SQL jdbc driver?


问:
Passing a parameter into a an Openquery select statement
I've a query:

```<code>DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;

SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900')
FROM BloodTests
PRINT @maxdate

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, '
    +CAST(@maxdate AS varchar(20))
    +', count(*) AS Count
    FROM blood_tests
    WHERE btestResult = 1 AND
        btestDateResultBack >'''''
            +convert(varchar(30), @maxdate, 121)
        +''''''

SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2
</code>```

that returns the DonorIDs and Count columns correctly, but the column with the variable '+CAST(@maxdate AS varchar(20))+' returns the date as an alias to a column (see image below).

Using @maxdate in the WHERE clause works just fine.

How can I use @maxdate in the body of the SELECT statement?

I've seen plenty of answers on how can I use this variable in a WHERE clause, but I haven't seen one discussing adding it to the SELECT statements select list.

Final Working Solution

```<code>DECLARE @sql nvarchar(max)
        ,@sql2 nvarchar(max)
        , @sql3 nvarchar(max)
        , @counts int
        , @bloodtestdonors int
        , @maxdate date;

--Find and delete bloodtests from today
SELECT @maxdate = isnull(Max(btestDateResultBack),'1900-01-01') FROM BloodTests;

PRINT @maxdate;

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
        '''''+CAST(@maxdate AS varchar(30))+''''' AS Date,
        count(*) AS Count FROM blood_tests
        WHERE btestResult = 1 AND
        btestDateResultBack >'''''+convert(varchar(30), @maxdate, 121)+''''''

SET @sql2 = 'SELECT * From OPENQUERY(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2
</code>```

Thanks @bielawski and @Prdp for the help and clarification. I appreciate it. Thanks @stan-shaw for the code formatting.

答:
I tested this.  It has the correct quoting and it works.  The problem was a combination of the wrong quoting and the unnamed date column.</p>

```<code>DECLARE @maxdate DATE = '2017-6-29';
DECLARE @sql2 NVARCHAR(max) =
    'SELECT * From openquery(MYSQL_donors, ''SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
    '''''+CAST(@maxdate AS varchar(20))+''''' AS DDate, count(*) AS Count
       FROM blood_tests WHERE btestResult = 1
        AND btestDateResultBack >''''' +convert(varchar(30), @maxdate, 121)+''''''')'

EXEC (@sql2);
</code>```

Body:
I've a query:

DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;

SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900')
FROM BloodTests
PRINT @maxdate

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, '
    +CAST(@maxdate AS varchar(20))
    +', count(*) AS Count
    FROM blood_tests
    WHERE btestResult = 1 AND
        btestDateResultBack >'''''
            +convert(varchar(30), @maxdate, 121)
        +''''''

SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2

that returns the DonorIDs and Count columns correctly, but the column with the variable '+CAST(@maxdate AS varchar(20))+' returns the date as an alias to a column (see image below).

Using @maxdate in the WHERE clause works just fine.

How can I use @maxdate in the body of the SELECT statement?

I've seen plenty of answers on how can I use this variable in a WHERE clause, but I haven't seen one discussing adding it to the SELECT statements select list.

Final Working Solution

DECLARE @sql nvarchar(max)
        ,@sql2 nvarchar(max)
        , @sql3 nvarchar(max)
        , @counts int
        , @bloodtestdonors int
        , @maxdate date;

--Find and delete bloodtests from today
SELECT @maxdate = isnull(Max(btestDateResultBack),'1900-01-01') FROM BloodTests;

PRINT @maxdate;

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
        '''''+CAST(@maxdate AS varchar(30))+''''' AS Date,
        count(*) AS Count FROM blood_tests
        WHERE btestResult = 1 AND
        btestDateResultBack >'''''+convert(varchar(30), @maxdate, 121)+''''''

SET @sql2 = 'SELECT * From OPENQUERY(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2

Thanks @bielawski and @Prdp for the help and clarification. I appreciate it. Thanks @stan-shaw for the code formatting.

Body:
I tested this.  It has the correct quoting and it works.  The problem was a combination of the wrong quoting and the unnamed date column.

DECLARE @maxdate DATE = '2017-6-29';
DECLARE @sql2 NVARCHAR(max) =
    'SELECT * From openquery(MYSQL_donors, ''SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
    '''''+CAST(@maxdate AS varchar(20))+''''' AS DDate, count(*) AS Count
       FROM blood_tests WHERE btestResult = 1
        AND btestDateResultBack >''''' +convert(varchar(30), @maxdate, 121)+''''''')'

EXEC (@sql2);


问:
Custom TableViewCell with Appcelerator Hyperloop
Hi would like to create custom tableViewCell with hyperloop. The problem is, I don't figure how to. I've tried implement it with a swift class :

Cell.swift

```<code>import UIKit

public class MyCell: UITableViewCell{//UICollectionViewCell {

    public var imgUser:UIImageView = UIImageView()
    public var labUerName:UILabel = UILabel()
    public var labMessage:UILabel = UILabel()
    public var labTime:UILabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        NSLog("la");
        imgUser.backgroundColor = UIColor.blue

        imgUser.translatesAutoresizingMaskIntoConstraints = false
        labUerName.translatesAutoresizingMaskIntoConstraints = false
        labMessage.translatesAutoresizingMaskIntoConstraints = false
        labTime.translatesAutoresizingMaskIntoConstraints = false

        labUerName.frame = CGRect(x: 5, y: 5, width: 70, height: 30)

        contentView.addSubview(imgUser)
        contentView.addSubview(labUerName)
        contentView.addSubview(labMessage)
        contentView.addSubview(labTime)

    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public func setName(txt: String){
        labUerName.text = txt
    }

}
</code>```

In my tabbleview controller:

```<code>(function (container) {

    var UIScreen = require('UIKit/UIScreen'),
        UIColor = require('UIKit/UIColor'),
        UITableView = require('UIKit/UITableView'),
        UITableViewCell = require('UIKit/UITableViewCell'),
        NSIndexPath = require('Foundation').NSIndexPath,
        UITableViewStyleGrouped = require('UIKit').UITableViewStyleGrouped,
        UITableViewCellStyleSubtitle = require('UIKit').UITableViewCellStyleSubtitle,
        UITableViewCellAccessoryDisclosureIndicator = require('UIKit').UITableViewCellAccessoryDisclosureIndicator;

    // Grabs the JSON-file from app/lib/static/data.json
    var file = Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory() + 'static/data.json');
    var users = JSON.parse(file.read().text).users;
    var Cell = require('MyFramework/MyCell'); // HERE IS MY CUSTOM CELL

    // Subclass delegate + data source
    var TableViewDataSourceAndDelegate = require('subclasses/tableviewdatasourcedelegate');

    // Create + configure tableView
    var tableView = UITableView.alloc().initWithFrameStyle(UIScreen.mainScreen.bounds, UITableViewStyleGrouped);
    var dataSourceDelegate = new TableViewDataSourceAndDelegate();

    dataSourceDelegate.numberOfSections = function(tableView) {
        return 1;
    };
    dataSourceDelegate.numberOfRows = function(tableView, section) {
        return users.length;
    };
    dataSourceDelegate.titleForHeader = function(tableView, section) {
        return 'Available users: ' + users.length;
    };
    dataSourceDelegate.heightForRow = function(tableView, indexPath) {
        return 44;
    };
    dataSourceDelegate.cellForRow = function(tableView, indexPath) {

        var user = users[indexPath.row];

        var cell = tableView.dequeueReusableCellWithIdentifierForIndexPath('hyperloop_cell', indexPath);

        cell.setName('abc');

        return cell;
    };
    dataSourceDelegate.didSelectRowAtIndexPath = function(tableView, indexPath) {
        alert('Call me maybe: ' + users[indexPath.row].phone);
        tableView.deselectRowAtIndexPathAnimated(indexPath, true);
    };

    // Assign delegate + data source
    tableView.registerClassForCellReuseIdentifier(Cell.self, "hyperloop_cell");
    tableView.setDelegate(dataSourceDelegate);
    tableView.setDataSource(dataSourceDelegate);

    container.add(tableView);

})($.tableview_container);
</code>```

i don't know how to use it well. Can someone help me please ?
thanks

答: Not sure why it's not working, however it doesn't seem like you're doing anything that could not be done without hyperloop... Why not just create your own tableview cell/row layout with Appcelerator?</p>

Body:
Hi would like to create custom tableViewCell with hyperloop. The problem is, I don't figure how to. I've tried implement it with a swift class :

Cell.swift

import UIKit

public class MyCell: UITableViewCell{//UICollectionViewCell {

    public var imgUser:UIImageView = UIImageView()
    public var labUerName:UILabel = UILabel()
    public var labMessage:UILabel = UILabel()
    public var labTime:UILabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        NSLog("la");
        imgUser.backgroundColor = UIColor.blue

        imgUser.translatesAutoresizingMaskIntoConstraints = false
        labUerName.translatesAutoresizingMaskIntoConstraints = false
        labMessage.translatesAutoresizingMaskIntoConstraints = false
        labTime.translatesAutoresizingMaskIntoConstraints = false

        labUerName.frame = CGRect(x: 5, y: 5, width: 70, height: 30)

        contentView.addSubview(imgUser)
        contentView.addSubview(labUerName)
        contentView.addSubview(labMessage)
        contentView.addSubview(labTime)

    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public func setName(txt: String){
        labUerName.text = txt
    }

}

In my tabbleview controller:

(function (container) {

    var UIScreen = require('UIKit/UIScreen'),
        UIColor = require('UIKit/UIColor'),
        UITableView = require('UIKit/UITableView'),
        UITableViewCell = require('UIKit/UITableViewCell'),
        NSIndexPath = require('Foundation').NSIndexPath,
        UITableViewStyleGrouped = require('UIKit').UITableViewStyleGrouped,
        UITableViewCellStyleSubtitle = require('UIKit').UITableViewCellStyleSubtitle,
        UITableViewCellAccessoryDisclosureIndicator = require('UIKit').UITableViewCellAccessoryDisclosureIndicator;

    // Grabs the JSON-file from app/lib/static/data.json
    var file = Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory() + 'static/data.json');
    var users = JSON.parse(file.read().text).users;
    var Cell = require('MyFramework/MyCell'); // HERE IS MY CUSTOM CELL

    // Subclass delegate + data source
    var TableViewDataSourceAndDelegate = require('subclasses/tableviewdatasourcedelegate');

    // Create + configure tableView
    var tableView = UITableView.alloc().initWithFrameStyle(UIScreen.mainScreen.bounds, UITableViewStyleGrouped);
    var dataSourceDelegate = new TableViewDataSourceAndDelegate();

    dataSourceDelegate.numberOfSections = function(tableView) {
        return 1;
    };
    dataSourceDelegate.numberOfRows = function(tableView, section) {
        return users.length;
    };
    dataSourceDelegate.titleForHeader = function(tableView, section) {
        return 'Available users: ' + users.length;
    };
    dataSourceDelegate.heightForRow = function(tableView, indexPath) {
        return 44;
    };
    dataSourceDelegate.cellForRow = function(tableView, indexPath) {

        var user = users[indexPath.row];

        var cell = tableView.dequeueReusableCellWithIdentifierForIndexPath('hyperloop_cell', indexPath);

        cell.setName('abc');

        return cell;
    };
    dataSourceDelegate.didSelectRowAtIndexPath = function(tableView, indexPath) {
        alert('Call me maybe: ' + users[indexPath.row].phone);
        tableView.deselectRowAtIndexPathAnimated(indexPath, true);
    };

    // Assign delegate + data source
    tableView.registerClassForCellReuseIdentifier(Cell.self, "hyperloop_cell");
    tableView.setDelegate(dataSourceDelegate);
    tableView.setDataSource(dataSourceDelegate);

    container.add(tableView);

})($.tableview_container);

i don't know how to use it well. Can someone help me please ?
thanks