问:
how to fetch a variable outside of the observable in Angular
I have an Observable which has an array. I want to fetch that array outside of the Observable so that I can merge it with another array.

```<code>    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);

       console.log(this.commercialDetailsArray);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );
</code>```

I want to fetch newcommercialDetailsArray

答:
You cannot access the array outside of the subscribe with the actual data as beacause it is a
  async callback and you want to access it in a synchronous way . you
  can merge the array inside of the subscribe using the following

```<code>    myArray = [];

    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];

       // do the merge here ;
       let myNewArray =
       this.newcommercialDetailsArray.concat(this.myArray)   ;
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );
</code>```

Update

If there are two observables that you need to run in order to generate the data you might need to look at observables.forkJoin()

Fork Join The forkJoin() operator allows us take a list of Observables
  and execute them in parallel. Once every Observable in the list emits
  a value the forkJoin with emit a single Observable value containing a
  list of all the resolved values from the Observables in the list.

More on fork join with example.

Body:
I have an Observable which has an array. I want to fetch that array outside of the Observable so that I can merge it with another array.

    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);

       console.log(this.commercialDetailsArray);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );

I want to fetch newcommercialDetailsArray

Body:
You cannot access the array outside of the subscribe with the actual data as beacause it is a
  async callback and you want to access it in a synchronous way . you
  can merge the array inside of the subscribe using the following

    myArray = [];

    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];

       // do the merge here ;
       let myNewArray =
       this.newcommercialDetailsArray.concat(this.myArray)   ;
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );

Update

If there are two observables that you need to run in order to generate the data you might need to look at observables.forkJoin()

Fork Join The forkJoin() operator allows us take a list of Observables
  and execute them in parallel. Once every Observable in the list emits
  a value the forkJoin with emit a single Observable value containing a
  list of all the resolved values from the Observables in the list.

More on fork join with example.


来源: stackexchange

问:
iOS 11 Layout guidance about safe Area for iPhone x
My application already in app store, yesterday i have updated my Xcode version to 9 and works fine except iPhone x. UI got collapsed.

1.Here I have Created Two UIView(both are fixed height) named as Header and Tab bar and I have hidden my NavigationBar entire app.

2.Added extension to UIViewController for making Header and Tab bar

```<code>func addHeaderTab(currentViewController:UIViewController,content:String, isMenu:Bool){
        let noView = TopHeaderView()
        noView.tag = 12345
        noView.isMenu = isMenu
        noView.translatesAutoresizingMaskIntoConstraints = false
        currentViewController.view .addSubview(noView)
        if isMenu{
            noView.menuBtn .setImage(UIImage(named: "Small"), for: .normal)
            noView.logoImg.isHidden = false

        }else{
            noView.menuBtn .setImage(UIImage(named: "arrow_small"), for: .normal)
            noView.logoImg.isHidden = true
        }
        noView.titleLbl.text = content
        noView.delegate = (currentViewController as! menuOpen)

        NSLayoutConstraint(item: noView, attribute: .leading, relatedBy: .equal, toItem: currentViewController.view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .trailing, relatedBy: .equal, toItem: currentViewController.view, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .top, relatedBy: .equal, toItem: currentViewController.view, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 64).isActive = true

    }
</code>```

and calling this every Viewcontroller like below :

```<code>self.addHeaderTab(currentViewController: self, content:"நிகழ்ச்சி நிரல்" , isMenu: true)
</code>```

Like that Tab bar also i have done but all the device working expect iPhone x.

See My screen shot :

i have studied about https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/

but am not clear with their document.

Help would be appreciated, Thanks in advance.

答:
If you don't want to use a UINavigationController but you want to have a navigation bar, you can do this way (using a UIImageView):

https://medium.com/@kahseng.lee123/creating-custom-navigation-bar-tab-bar-for-iphone-x-f03b1e1827d3

Or you can create a view and set its top constraint to the top of the superview and its bottom contraint to the top of the navigation bar. Don't forget to make it red.  :-)

ContentLicense: CC BY-SA 3.0

Body:
My application already in app store, yesterday i have updated my Xcode version to 9 and works fine except iPhone x. UI got collapsed.

1.Here I have Created Two UIView(both are fixed height) named as Header and Tab bar and I have hidden my NavigationBar entire app.

2.Added extension to UIViewController for making Header and Tab bar

func addHeaderTab(currentViewController:UIViewController,content:String, isMenu:Bool){
        let noView = TopHeaderView()
        noView.tag = 12345
        noView.isMenu = isMenu
        noView.translatesAutoresizingMaskIntoConstraints = false
        currentViewController.view .addSubview(noView)
        if isMenu{
            noView.menuBtn .setImage(UIImage(named: "Small"), for: .normal)
            noView.logoImg.isHidden = false

        }else{
            noView.menuBtn .setImage(UIImage(named: "arrow_small"), for: .normal)
            noView.logoImg.isHidden = true
        }
        noView.titleLbl.text = content
        noView.delegate = (currentViewController as! menuOpen)

        NSLayoutConstraint(item: noView, attribute: .leading, relatedBy: .equal, toItem: currentViewController.view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .trailing, relatedBy: .equal, toItem: currentViewController.view, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .top, relatedBy: .equal, toItem: currentViewController.view, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true

        NSLayoutConstraint(item: noView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 64).isActive = true

    }

and calling this every Viewcontroller like below :

self.addHeaderTab(currentViewController: self, content:"நிகழ்ச்சி நிரல்" , isMenu: true)

Like that Tab bar also i have done but all the device working expect iPhone x.

See My screen shot :

i have studied about https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/

but am not clear with their document.

Help would be appreciated, Thanks in advance.


问:
Can you only write operating systems in C?
I get that C and its super sets allow you to have low level access, but could you use a different language. For example Visual Basic, C# or even Java? I was just curious because it seems like something better should have come along since C's inception.</p>

答:
Cosmos - C# Open Source Managed Operating System

http://www.codeproject.com/KB/system/CosmosIntro.aspx

ContentLicense: CC BY-SA 2.5


问:
AWK Command print size in mb,kb or gb by finding a file using ls -l
I want to get a file size using find command along with size in kb, mb or gb with decimal point of two only.

Desired output:

```<code>15.04 MB
10MB
10GB
</code>```

I have tried below command but getting error:

```<code>find /orabackup/EXPDP/ATRUS001 -name "expdp_ATRUS001_04122017_0500.dmp" -exec ls -ltr  {} \;  | awk ' {s+=$5}' '{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }'
</code>```

Output:

```<code>awk: cmd. line:1: fatal: cannot open file `{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }' for reading (No such file or directory
</code>```

even though file is present in directory giving me above error. Thank you for your help.

答:
Short and optimized find + numfmt solution:

```<code>find /your_dirpath -type f -name "filepath" -printf "%s\n" | numfmt --to=iec --format='%.2fB'
</code>```

-printf "%s\n" - print file size

numfmt ... - convert numbers from/to human-readable strings

Example output:

```<code>3.70MB
24.27MB
38.16MB
1.76MB
</code>```

Body:
I want to get a file size using find command along with size in kb, mb or gb with decimal point of two only.

Desired output:

15.04 MB
10MB
10GB

I have tried below command but getting error:

find /orabackup/EXPDP/ATRUS001 -name "expdp_ATRUS001_04122017_0500.dmp" -exec ls -ltr  {} \;  | awk ' {s+=$5}' '{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }'

Output:

awk: cmd. line:1: fatal: cannot open file `{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }' for reading (No such file or directory

even though file is present in directory giving me above error. Thank you for your help.

Body:
Short and optimized find + numfmt solution:

find /your_dirpath -type f -name "filepath" -printf "%s\n" | numfmt --to=iec --format='%.2fB'

-printf "%s\n" - print file size

numfmt ... - convert numbers from/to human-readable strings

Example output:

3.70MB
24.27MB
38.16MB
1.76MB


问:
Effective way of pattern matching on multiple Options Scala
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

```<code>def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}
</code>```

答:
In functional programming, it is better to have small functions instead of large one. I would prefer doing something as below:</p>

```<code>  def screenStudent(income:Double):String = {
    if (income <= 18000) "P" else "F"
  }
  def screenUnemployment(income:Double):String = {
    if (income <= 7000) "P" else "F"
  }
  def screenOthers(income:Double, score:Int):String = {
    (income, score) match {
      case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
      case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
      case _ => "F"
    }
  }
  def incomeScreenStatus(
    status_cd: Option[String],
    score: Option[Int],
    income: Option[Double]
  ) : String  =
  (status_cd , score, income) match {
    case (Some("STUDENT"), Some(_), Some(i)) => screenStudent(i)
    case (Some("UNEMPLOYMENT"), Some(_), Some(i)) => screenUnemployment(i)
    case (Some(_), Some(s), Some(i)) => screenOthers(i, s)
    case _ => "F"
  }
</code>```

Body:
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}

Body:
In functional programming, it is better to have small functions instead of large one. I would prefer doing something as below:

  def screenStudent(income:Double):String = {
    if (income <= 18000) "P" else "F"
  }
  def screenUnemployment(income:Double):String = {
    if (income <= 7000) "P" else "F"
  }
  def screenOthers(income:Double, score:Int):String = {
    (income, score) match {
      case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
      case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
      case _ => "F"
    }
  }
  def incomeScreenStatus(
    status_cd: Option[String],
    score: Option[Int],
    income: Option[Double]
  ) : String  =
  (status_cd , score, income) match {
    case (Some("STUDENT"), Some(_), Some(i)) => screenStudent(i)
    case (Some("UNEMPLOYMENT"), Some(_), Some(i)) => screenUnemployment(i)
    case (Some(_), Some(s), Some(i)) => screenOthers(i, s)
    case _ => "F"
  }


问:
iOS share extension hiding on number of items selected
I see that app like twitter has the feature to automatically hide the share extension depending on number of items selected, .ie in Photo app like:

Anybody has any idea on how to obtain something like twitter share extension

Thanks

答:
Use: Declaring Supported Data Types for a Share or Action Extension

https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW8

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/AppExtensionKeys.html


问:
Has no exported member 'toPromise' rxjs- 5.5.2
Using toPromise throws an error

Old method:

```<code>import 'rxjs/add/operator/toPromise';
</code>```

Latest way:

```<code>import { toPromise } from 'rxjs/operators';
</code>```

The latest way shows the following errors:

[ts] Module '"d:/.../node_modules/rxjs/operators/index"' has no
  exported member 'toPromise'.

Versions:

```<code> "typescript": "2.4.2"
 "rxjs": "5.5.2",
</code>```

答:
As of rxjs 5.5.0-beta.5, the toPromise method is now a permanent method of Observable.

There is no need to import this method anymore; in fact, trying to do so will throw an error.

toPromise: now exists as a permanent method on Observable

Change Log    |      Github Reference

Body:
Using toPromise throws an error

Old method:

import 'rxjs/add/operator/toPromise';

Latest way:

import { toPromise } from 'rxjs/operators';

The latest way shows the following errors:

[ts] Module '"d:/.../node_modules/rxjs/operators/index"' has no
  exported member 'toPromise'.

Versions:

 "typescript": "2.4.2"
 "rxjs": "5.5.2",


问:
Cannot connect bluetooth remote control to SBC running linux
I am running a buildroot-generated linux image (kernel 4.11.2) on a nanopi NEO air board, and I struggle to connect to my ruwido remote control.

I can see it when I scan the devices using hcitool :

```<code># hcitool lescan
LE Scan ...
<snip>
5C:F8:21:85:8E:67 ruwido
<snip>
</code>```

But I cannot get a connection (it acts like the remote is not here) :

```<code># hcitool cc 5C:F8:21:85:8E:67
Can't create connection: Input/output error
</code>```

The only thing I can do is get some information about it :

```<code># hcitool leinfo 5C:F8:21:85:8E:67
Requesting information ...
        Handle: 64 (0x0040)
        LMP Version: 4.0 (0x6) LMP Subversion: 0x140
        Manufacturer: Texas Instruments Inc. (13)
        Features: 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00
</code>```

I also cannot use bluetoothctl since it doesn't detect my interface, even though it's initialized, bluetoothd is running and the modules are loaded :

```<code># lsmod
Module                  Size  Used by
bnep                   20480  2
hci_uart               61440  1
btbcm                  16384  1 hci_uart
btqca                  16384  1 hci_uart
btintel                16384  1 hci_uart
bluetooth             348160  12 hci_uart,btintel,btqca,bnep,btbcm
brcmfmac              245760  0
brcmutil               16384  1 brcmfmac
sunxi_cir              16384  0
# ps -e | grep bluetooth
  553 root     /usr/sbin/bluetoothd
  731 root     grep bluetooth
# sudo hciconfig -a
hci0:   Type: Primary  Bus: UART
        BD Address: F7:93:3E:74:CF:62  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:12593 acl:7 sco:0 events:292 errors:0
        TX bytes:2050 acl:4 sco:0 commands:155 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'NanoPi-NEO-Air'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x0
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

# bluetoothctl
Agent registered
[bluetooth]# power on
No default controller available
</code>```

My question is, how do I get the remote paired and connected to the board ? It doesn't matter if it's through hcitool, bluetoothctl or another tool.

Update

Thanks to Prabhakar Lad's comment, bluetoothctl is now detecting the interface, however the problem still remains and the problem seems to have narrowed :

```<code># rfkill unblock all
# hciconfig hci0 up
# hciconfig -a
hci0:   Type: Primary  Bus: UART
        BD Address: AA:AA:AA:AA:AA:AA  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING PSCAN
        RX bytes:1930 acl:0 sco:0 events:101 errors:0
        TX bytes:1587 acl:0 sco:0 commands:103 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'BlueZ 5.47'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x0
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

# bluetoothctl
[NEW] Controller F7:93:3E:74:CF:62 BlueZ 5.47 [default]
[NEW] Device 5C:F8:21:85:8E:67 ruwido
Agent registered
[bluetooth]# agent on
Agent is already registered
[bluetooth]# power on
Changing power on succeeded
[bluetooth]# scan on
Discovery started
[CHG] Controller F7:93:3E:74:CF:62 Discovering: yes
<snip>
[NEW] Device 5C:F8:21:85:8E:67 ruwido
<snip>
[bluetooth]# scan off
<snip>
[CHG] Device 5C:F8:21:85:8E:67 RSSI is nil
<snip>
[CHG] Controller F7:93:3E:74:CF:62 Discovering: no
Discovery stopped
[bluetooth]# pair 5C:F8:21:85:8E:67
Attempting to pair with 5C:F8:21:85:8E:67
[CHG] Device 5C:F8:21:85:8E:67 Connected: yes
[ruwido]# [  501.424858] Bluetooth: hci0 unexpected SMP command 0x0b from 5c:f8:21:85:8e:67
[CHG] Device 5C:F8:21:85:8E:67 Connected: no
[bluetooth]# pair 5C:F8:21:85:8E:67
Attempting to pair with 5C:F8:21:85:8E:67
Failed to pair: org.bluez.Error.ConnectionAttemptFailed
</code>```

The SMP error seems to be related to bluetooth low-energy security, so am I supposed to use a different tool for pairing ?

Additional information

I actually use the busybox init system with bluetooth init scripts I found in the manufacturer's image (which is nanopi-neo-air_FriendlyCore-Xenial_4.11.2_20171113.img) and adapted so that they could be used with busybox init (the init system on the image is systemd/upstart).

So I have two files :

/etc/init.d/S35brcm_patchram_plus : patches firmware (the card uses an AMPAK ap6212 bluetooth/wifi combo module)

/etc/init.d/S38bluetooth : starts bluetoothd

I use bluez 5.47 with the following options in buildroot 2017.08.1 :

```<code>BR2_PACKAGE_BLUEZ_TOOLS=y
# BR2_PACKAGE_BLUEZ_UTILS is not set
BR2_PACKAGE_BLUEZ5_UTILS=y
BR2_PACKAGE_BLUEZ5_UTILS_OBEX=y
BR2_PACKAGE_BLUEZ5_UTILS_CLIENT=y
BR2_PACKAGE_BLUEZ5_UTILS_DEPRECATED=y
# BR2_PACKAGE_BLUEZ5_UTILS_EXPERIMENTAL is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_HEALTH is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_MIDI is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_NFC is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_SAP is not set
BR2_PACKAGE_BLUEZ5_UTILS_TEST=y
# BR2_PACKAGE_BLUEZ5_UTILS_GATTTOOL is not set
</code>```

答:
You didnt go through my complete post, you need to perform following
 steps after you have done with rfkill and service restart:

a] bluetoothctl

```<code>Start the tool, this should detect the controller
</code>```

b] [bluetooth]# agent on

```<code>Turn on the pairing agent
</code>```

c] [bluetooth]# scan on

```<code>Let bluez detect your device, look in my post it should print you baddr (5C:F8:21:85:8E:67)
</code>```

d] [bluetooth]# scan off

```<code>Turn off scanning once your device is discovered
</code>```

e] [bluetooth]# pair 5C:F8:21:85:8E:67

```<code>Now pair to the device
</code>```

It should now be paired.
Note: you cannot pair a device until the bluez has scanned it.

Body:
I am running a buildroot-generated linux image (kernel 4.11.2) on a nanopi NEO air board, and I struggle to connect to my ruwido remote control.

I can see it when I scan the devices using hcitool :

# hcitool lescan
LE Scan ...
<snip>
5C:F8:21:85:8E:67 ruwido
<snip>

But I cannot get a connection (it acts like the remote is not here) :

# hcitool cc 5C:F8:21:85:8E:67
Can't create connection: Input/output error

The only thing I can do is get some information about it :

# hcitool leinfo 5C:F8:21:85:8E:67
Requesting information ...
        Handle: 64 (0x0040)
        LMP Version: 4.0 (0x6) LMP Subversion: 0x140
        Manufacturer: Texas Instruments Inc. (13)
        Features: 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00

I also cannot use bluetoothctl since it doesn't detect my interface, even though it's initialized, bluetoothd is running and the modules are loaded :

# lsmod
Module                  Size  Used by
bnep                   20480  2
hci_uart               61440  1
btbcm                  16384  1 hci_uart
btqca                  16384  1 hci_uart
btintel                16384  1 hci_uart
bluetooth             348160  12 hci_uart,btintel,btqca,bnep,btbcm
brcmfmac              245760  0
brcmutil               16384  1 brcmfmac
sunxi_cir              16384  0
# ps -e | grep bluetooth
  553 root     /usr/sbin/bluetoothd
  731 root     grep bluetooth
# sudo hciconfig -a
hci0:   Type: Primary  Bus: UART
        BD Address: F7:93:3E:74:CF:62  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:12593 acl:7 sco:0 events:292 errors:0
        TX bytes:2050 acl:4 sco:0 commands:155 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'NanoPi-NEO-Air'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x0
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

# bluetoothctl
Agent registered
[bluetooth]# power on
No default controller available

My question is, how do I get the remote paired and connected to the board ? It doesn't matter if it's through hcitool, bluetoothctl or another tool.

Update

Thanks to Prabhakar Lad's comment, bluetoothctl is now detecting the interface, however the problem still remains and the problem seems to have narrowed :

# rfkill unblock all
# hciconfig hci0 up
# hciconfig -a
hci0:   Type: Primary  Bus: UART
        BD Address: AA:AA:AA:AA:AA:AA  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING PSCAN
        RX bytes:1930 acl:0 sco:0 events:101 errors:0
        TX bytes:1587 acl:0 sco:0 commands:103 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'BlueZ 5.47'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x0
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

# bluetoothctl
[NEW] Controller F7:93:3E:74:CF:62 BlueZ 5.47 [default]
[NEW] Device 5C:F8:21:85:8E:67 ruwido
Agent registered
[bluetooth]# agent on
Agent is already registered
[bluetooth]# power on
Changing power on succeeded
[bluetooth]# scan on
Discovery started
[CHG] Controller F7:93:3E:74:CF:62 Discovering: yes
<snip>
[NEW] Device 5C:F8:21:85:8E:67 ruwido
<snip>
[bluetooth]# scan off
<snip>
[CHG] Device 5C:F8:21:85:8E:67 RSSI is nil
<snip>
[CHG] Controller F7:93:3E:74:CF:62 Discovering: no
Discovery stopped
[bluetooth]# pair 5C:F8:21:85:8E:67
Attempting to pair with 5C:F8:21:85:8E:67
[CHG] Device 5C:F8:21:85:8E:67 Connected: yes
[ruwido]# [  501.424858] Bluetooth: hci0 unexpected SMP command 0x0b from 5c:f8:21:85:8e:67
[CHG] Device 5C:F8:21:85:8E:67 Connected: no
[bluetooth]# pair 5C:F8:21:85:8E:67
Attempting to pair with 5C:F8:21:85:8E:67
Failed to pair: org.bluez.Error.ConnectionAttemptFailed

The SMP error seems to be related to bluetooth low-energy security, so am I supposed to use a different tool for pairing ?

Additional information

I actually use the busybox init system with bluetooth init scripts I found in the manufacturer's image (which is nanopi-neo-air_FriendlyCore-Xenial_4.11.2_20171113.img) and adapted so that they could be used with busybox init (the init system on the image is systemd/upstart).

So I have two files :

/etc/init.d/S35brcm_patchram_plus : patches firmware (the card uses an AMPAK ap6212 bluetooth/wifi combo module)

/etc/init.d/S38bluetooth : starts bluetoothd

I use bluez 5.47 with the following options in buildroot 2017.08.1 :

BR2_PACKAGE_BLUEZ_TOOLS=y
# BR2_PACKAGE_BLUEZ_UTILS is not set
BR2_PACKAGE_BLUEZ5_UTILS=y
BR2_PACKAGE_BLUEZ5_UTILS_OBEX=y
BR2_PACKAGE_BLUEZ5_UTILS_CLIENT=y
BR2_PACKAGE_BLUEZ5_UTILS_DEPRECATED=y
# BR2_PACKAGE_BLUEZ5_UTILS_EXPERIMENTAL is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_HEALTH is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_MIDI is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_NFC is not set
# BR2_PACKAGE_BLUEZ5_PLUGINS_SAP is not set
BR2_PACKAGE_BLUEZ5_UTILS_TEST=y
# BR2_PACKAGE_BLUEZ5_UTILS_GATTTOOL is not set

Body:
You didnt go through my complete post, you need to perform following
 steps after you have done with rfkill and service restart:

a] bluetoothctl

Start the tool, this should detect the controller

b] [bluetooth]# agent on

Turn on the pairing agent

c] [bluetooth]# scan on

Let bluez detect your device, look in my post it should print you baddr (5C:F8:21:85:8E:67)

d] [bluetooth]# scan off

Turn off scanning once your device is discovered

e] [bluetooth]# pair 5C:F8:21:85:8E:67

Now pair to the device

It should now be paired.
Note: you cannot pair a device until the bluez has scanned it.


问:
Validators min and maximum number angular 4
is there any option to make validator min and maximum number, i.e number between 0 to 200?

dialog-result-component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { FormGroup,FormControl,Validators,FormBuilder,  } from '@angular/forms';

@Component({
  selector: 'app-dialog-result',
  templateUrl: './dialog-result.component.html',
})

export class DialogResultComponent {

  form: FormGroup;
  name = new FormControl('',Validators.required);
  width = new FormControl('',Validators.required);
  height = new FormControl('',Validators.required);
  constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {

  }

  ngOnInit() {
  this.form = this.fb.group({
      'name':    this.name,
      'width':   this.width,
      'height':  this.height,
    });
}

  saveData(){
    this.dialogRef.close({name:this.name,width:this.width,height:this.height});
  }
}
</code>```

dialog-result.component.html

```<code>       <form [formGroup]="form">
     <h3>MineSweeperwix</h3>
      <div class="mdl-dialog__content">
                <p><mdl-textfield type="text" label="name" formControlName="name" floating-label autofocus></mdl-textfield></p>
                <mdl-textfield type="number" formControlName="width" min="0" max="350" label="width"   floating-label autofocus></mdl-textfield>
               <mdl-textfield type="number" formControlName="height" label="height" min="0" max="350" floating-label autofocus  error-msg="'Please provide a correct email!'"></mdl-textfield>
      </div>
      <div class="mdl-dialog__actions">
        <button mdl-button (click)="saveData()" mdl-button-type="raised" mdl-colored="primary" mdl-ripple [disabled]="!form.valid">Save</button>
        <button mdl-button (click)="dialogRef.close(dd)" mdl-button-type="raised" mdl-ripple>Cancel</button>
      </div>
   </form>
</code>```

the min and maximum into the the mdl-text-field

```<code>min="0" max="200" floating-label autofocus
</code>```

limit the user to write number between the range but it let to press the save button and that's not what i want to do. i want the user can press save button just if all the form is valid.

what I tried to do is

dialog.result.component.ts

```<code>    import { Component, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { FormGroup,FormControl,Validators,FormBuilder,ValidatorFn,AbstractControl  } from '@angular/forms';
import { NumberValidators } from '../validators/NumberValidators.module';

@Component({
  selector: 'app-dialog-result',
  templateUrl: './dialog-result.component.html',
})

export class DialogResultComponent {

  form: FormGroup;
  name = new FormControl('',Validators.required);
  width = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
  height = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
  constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {

  }

  ngOnInit() {
  this.form = this.fb.group({
      'name' :this.name,
      'width': this.width,
      'height':  this.height
    });
}

  saveData(){
    console.log(this.name.value);
    this.dialogRef.close({name:this.name.value,width:this.width.value,height:this.height.value});
  }

}
</code>```

NumberValidators.module.ts

```<code>import { AbstractControl, ValidatorFn } from '@angular/forms';

export class NumberValidators {

    static range(min: number, max: number): ValidatorFn {
        console.log(min+max);
        return (c: AbstractControl): { [key: string]: boolean } | null => {
            if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
                return { 'range': true };
            }
            return null;
        };
    }
</code>```

}

but it's not works fine, anyone have any suggestion?

答:
Easiest way I found is with validators. Check this reference link:

https://angular.io/api/forms/Validators

```<code>static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
</code>```

Complete code example which I have implemented is as following:

For the reference component.ts

```<code>this.form = this.fb.group({
  'name' :new FormControl(null, Validators.compose([Validators.required])),
  'width':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)])),
  'height':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)]))
});
</code>```

component.html

```<code><div *ngIf="width.errors?.min || width.errors?.max" class="error">Width is not valid.</div>
<div *ngIf="height.errors?.min || height.errors?.max" class="error">Height is not valid.</div>
</code>```

Body:
is there any option to make validator min and maximum number, i.e number between 0 to 200?

dialog-result-component.ts

import { Component, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { FormGroup,FormControl,Validators,FormBuilder,  } from '@angular/forms';

@Component({
  selector: 'app-dialog-result',
  templateUrl: './dialog-result.component.html',
})

export class DialogResultComponent {

  form: FormGroup;
  name = new FormControl('',Validators.required);
  width = new FormControl('',Validators.required);
  height = new FormControl('',Validators.required);
  constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {

  }

  ngOnInit() {
  this.form = this.fb.group({
      'name':    this.name,
      'width':   this.width,
      'height':  this.height,
    });
}

  saveData(){
    this.dialogRef.close({name:this.name,width:this.width,height:this.height});
  }
}

dialog-result.component.html

       <form [formGroup]="form">

MineSweeperwix

<mdl-textfield type="text" label="name" formControlName="name" floating-label autofocus></mdl-textfield>

                <mdl-textfield type="number" formControlName="width" min="0" max="350" label="width"   floating-label autofocus></mdl-textfield>
               <mdl-textfield type="number" formControlName="height" label="height" min="0" max="350" floating-label autofocus  error-msg="'Please provide a correct email!'"></mdl-textfield>

        <button mdl-button (click)="saveData()" mdl-button-type="raised" mdl-colored="primary" mdl-ripple [disabled]="!form.valid">Save</button>
        <button mdl-button (click)="dialogRef.close(dd)" mdl-button-type="raised" mdl-ripple>Cancel</button>

   </form>

the min and maximum into the the mdl-text-field

min="0" max="200" floating-label autofocus

limit the user to write number between the range but it let to press the save button and that's not what i want to do. i want the user can press save button just if all the form is valid.

what I tried to do is

dialog.result.component.ts

    import { Component, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { FormGroup,FormControl,Validators,FormBuilder,ValidatorFn,AbstractControl  } from '@angular/forms';
import { NumberValidators } from '../validators/NumberValidators.module';

@Component({
  selector: 'app-dialog-result',
  templateUrl: './dialog-result.component.html',
})

export class DialogResultComponent {

  form: FormGroup;
  name = new FormControl('',Validators.required);
  width = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
  height = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
  constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {

  }

  ngOnInit() {
  this.form = this.fb.group({
      'name' :this.name,
      'width': this.width,
      'height':  this.height
    });
}

  saveData(){
    console.log(this.name.value);
    this.dialogRef.close({name:this.name.value,width:this.width.value,height:this.height.value});
  }

}

NumberValidators.module.ts

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class NumberValidators {

    static range(min: number, max: number): ValidatorFn {
        console.log(min+max);
        return (c: AbstractControl): { [key: string]: boolean } | null => {
            if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
                return { 'range': true };
            }
            return null;
        };
    }

}

but it's not works fine, anyone have any suggestion?

Body:
Easiest way I found is with validators. Check this reference link:

https://angular.io/api/forms/Validators

static min(min: number): ValidatorFn
static max(max: number): ValidatorFn

Complete code example which I have implemented is as following:

For the reference component.ts

this.form = this.fb.group({
  'name' :new FormControl(null, Validators.compose([Validators.required])),
  'width':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)])),
  'height':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)]))
});

component.html

<div *ngIf="width.errors?.min || width.errors?.max" class="error">Width is not valid.</div>
<div *ngIf="height.errors?.min || height.errors?.max" class="error">Height is not valid.</div>


问:
Index find position for matching string
Consider following example

```<code>index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index
</code>```

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

```<code>index_id.index('a')
</code>```

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

答:
Try this:</p>

```<code>index = pd.Index(list(df))
print index.get_loc('a')
</code>```

Title: Index find position for matching string

Body:
Consider following example

index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

index_id.index('a')

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

Body:
Try this:

index = pd.Index(list(df))
print index.get_loc('a')


问:
Allow anonymous users to create unpublished nodes in Drupal?
I'm creating a site for a client based on drupal, and the client wants an anonymous user (not logged in) to be able to create a new node, but only an unpublished one. Then an admin can review the node and alter it before publishing himself.

I have looked at using triggers and actions, but writing a custom trigger module seems a bit daunting, as I'm not very fluent with the Drupal API currently. Any ideas are appreciated.

答:
You can set the default publish status to unpublished - and hide that field from anonymous users.

Then you can create a view - or just use the Content link in the admin section to view the pages that have Anonymous for an author, and are unpublished - then you can review nodes from there.


问:
Total all matching integer elements in an array
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

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

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}
</code>```

But, if the array was for example...

```<code>int arr[] = {6,1,1,6,6,6};
</code>```

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?

答:
Interpreting the question as "provide the total number of values that occur more than once and their sum", and taking into account that nothing "fancy" (sic) such as a map can be used:

```<code>int[] array = {6, 1, 1, 6, 6, 6};
int sum = 0;
int matches = 0;

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        if (i != j && array[i] == array[j]) {
            sum += array[i];
            matches++;

            break;
        }
    }
}

System.out.println(matches); // 6
System.out.println(sum); // 26
</code>```

Body:
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

public static void main(String[] args) {

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}

But, if the array was for example...

int arr[] = {6,1,1,6,6,6};

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?

Body:
Interpreting the question as "provide the total number of values that occur more than once and their sum", and taking into account that nothing "fancy" (sic) such as a map can be used:

int[] array = {6, 1, 1, 6, 6, 6};
int sum = 0;
int matches = 0;

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        if (i != j && array[i] == array[j]) {
            sum += array[i];
            matches++;

            break;
        }
    }
}

System.out.println(matches); // 6
System.out.println(sum); // 26


问:
Create a class for reading in files: creating an SQL api with distinct methods
This question is more about how one uses OOP to read in databases. SQLite and sqlite3 are simply examples to work with, and are not the main thrust of the question:

I am creating a software package which allows users to query SQLite index files which have already been generated. It's basically syntactic to make it super user-friendly to query SQLite files indexed in a certain way, for a very particular case This should be quite straightforward, but I am somewhat confused how to "automatically" read in the SQLite

Here's an example (with pseudo-code):

```<code>import sqlite3

Class EasySQL:
    def __init__(self, filepath):
        self.filepath = filepath

    def connect(self, filepath):  ## perhaps this should be above in init?
        return sqlite3.connect(self.filepath)

    def query_indexA(self):
        ## query index A on SQLite3 connection
</code>```

I would prefer the connection to the SQLite database to be "automatic" upon instantiation of the class:

```<code>### instantiate class
my_table1 = EasySQL("path/to/file")
</code>```

At the moment, users one need to call the function .connect() after instantiation.

```<code>my_table = EasySQL("path/to/file")
the_object_to_do_queries = my_table.connect()

## now users can actually use this
the_object_to_do_queries.query_indexA()
</code>```

This seems like bad form, and unnecessarily complicated.

How does one write the the initialization method to immediately create the SQLite3 connection?

Hopefully this question is clear. I am happy to edit if not.

答:
The main point here is that EasySQL should not return the connection (which makes it mostly useless) but use it internally by keeping a reference to it:

```<code>class EasySQL(object):
    def __init__(self, filepath):
        self._filepath = filepath
        self._db = sqlite3.connect(self.filepath)

    def close(self):
        if self._db:
            self._db.close()
            self._db = None

    def query_indexA(self):
        # XXX example implementation
        cursor = self._db.cursor()
        cursor.execute("some query here")
        return cursor.fetchall()
</code>```

Body:
This question is more about how one uses OOP to read in databases. SQLite and sqlite3 are simply examples to work with, and are not the main thrust of the question:

I am creating a software package which allows users to query SQLite index files which have already been generated. It's basically syntactic to make it super user-friendly to query SQLite files indexed in a certain way, for a very particular case This should be quite straightforward, but I am somewhat confused how to "automatically" read in the SQLite

Here's an example (with pseudo-code):

import sqlite3

Class EasySQL:
    def __init__(self, filepath):
        self.filepath = filepath

    def connect(self, filepath):  ## perhaps this should be above in init?
        return sqlite3.connect(self.filepath)

    def query_indexA(self):
        ## query index A on SQLite3 connection

I would prefer the connection to the SQLite database to be "automatic" upon instantiation of the class:

### instantiate class
my_table1 = EasySQL("path/to/file")

At the moment, users one need to call the function .connect() after instantiation.

my_table = EasySQL("path/to/file")
the_object_to_do_queries = my_table.connect()

## now users can actually use this
the_object_to_do_queries.query_indexA()

This seems like bad form, and unnecessarily complicated.

How does one write the the initialization method to immediately create the SQLite3 connection?

Hopefully this question is clear. I am happy to edit if not.

Body:
The main point here is that EasySQL should not return the connection (which makes it mostly useless) but use it internally by keeping a reference to it:

class EasySQL(object):
    def __init__(self, filepath):
        self._filepath = filepath
        self._db = sqlite3.connect(self.filepath)

    def close(self):
        if self._db:
            self._db.close()
            self._db = None

    def query_indexA(self):
        # XXX example implementation
        cursor = self._db.cursor()
        cursor.execute("some query here")
        return cursor.fetchall()


问:
Is it safe to define my io as global.io
I am new to nodejs and socket. What I would like to know is how I should able to access my io variable in different controllers or files. Is it safe to declare my io variable as:

```<code>global.io = require('socket.io').listen(server);
</code>```

so now my io is accessible in any of my controller?

I got this idea from this link:

https://blog.sylo.space/use-global-variable-for-socket-io/

答:
In most cases, global variables are an indication of poor software design. A better approach would be containing all your IO code in a distinct class/module. Here's a short code piece to illustrate what I mean:

```<code>const socketIO = require('socket.io');
class myIO {
    construct(server) {
        this.io = socketIO.listen(server)
    }

    doStuff() {
        // do stuff with your io socket
    }
}

module.exports = myIO;
</code>```

Now you need to provide an instance of myIO to your controllers, but I'm not sure what constitutes a controller in your case. And do you need to reconnect socket each time, or reuse same socket?

Either way you might want to look into Dependency Injection pattern OR use a Singleton:

```<code>module.exports = new myIO();
</code>```

in this case require("myio") would always return same socket. Or if your framework has a registry, you could use that.

ContentLicense: CC BY-SA 4.0

Title: Is it safe to define my io as global.io

Body:
I am new to nodejs and socket. What I would like to know is how I should able to access my io variable in different controllers or files. Is it safe to declare my io variable as:

global.io = require('socket.io').listen(server);

so now my io is accessible in any of my controller?

I got this idea from this link:

https://blog.sylo.space/use-global-variable-for-socket-io/

Body:
In most cases, global variables are an indication of poor software design. A better approach would be containing all your IO code in a distinct class/module. Here's a short code piece to illustrate what I mean:

const socketIO = require('socket.io');
class myIO {
    construct(server) {
        this.io = socketIO.listen(server)
    }

    doStuff() {
        // do stuff with your io socket
    }
}

module.exports = myIO;

Now you need to provide an instance of myIO to your controllers, but I'm not sure what constitutes a controller in your case. And do you need to reconnect socket each time, or reuse same socket?

Either way you might want to look into Dependency Injection pattern OR use a Singleton:

module.exports = new myIO();

in this case require("myio") would always return same socket. Or if your framework has a registry, you could use that.


问:
Neo4j Procedure with static variables in a cluster
Let's say I have a Neo4j Database with a custom Procedure, I've written.
The procedure uses a static variable as some kind of some short term memory, like the apoc.search procedure does for example.
I now want to cluster my Neo4j which would mean I have multiple instances running on different VMs.
I now have the problem, that the clustered instances can't share the content of the static variable, right?
Is there some way to share this?

For better understanding lets say I re-implemented the apoc.create.vNode procedure by creating a node and saving it inside a public static Node node;, not in the Database. I've deployed the plugin into each instance of my cluster. When I now save a Node like that, it will just be known to one Neo4j instance, right?
When my instance dies, the node is forgotten.

Is this correct?

答:
Yes. State held in procedures, even static state, is not shared across the cluster.

I think the only way to share it would be to save it into the graph itself.


问:
Knockout where clause in foreach
I would like to replicate this logic in knockout foreach.. any suggestions please? The current code is in razor and I am converting this to use knockoutJS

Where ItemStatus.Active is 0 in an enum in c# (backend)

```<code>    @foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{
      <div class="someclass”>
      <span class="label">Name:</span>
      <span class="value">@employee.Name</span>
    </div>
    }
</code>```

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

thank you

答:
I would go for an array filter in my view model to solve that one, something along the lines of:

```<code>var self = this;

self.Employees = ko.observableArray();
ko.uitls.arrayfilter(self.Employees(), function(e) { return e.Status == 'Active' });
</code>```

Make it really swish by working the array filter into a computed function and binding that to your div, there are plenty of documentation/tutorials on knockouts website to help you with this.

Knockout Tutorial Website

Title: Knockout where clause in foreach

Body:
I would like to replicate this logic in knockout foreach.. any suggestions please? The current code is in razor and I am converting this to use knockoutJS

Where ItemStatus.Active is 0 in an enum in c# (backend)

    @foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{

      Name:
      @employee.Name

    }

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

thank you

Body:
I would go for an array filter in my view model to solve that one, something along the lines of:

var self = this;

self.Employees = ko.observableArray();
ko.uitls.arrayfilter(self.Employees(), function(e) { return e.Status == 'Active' });

Make it really swish by working the array filter into a computed function and binding that to your div, there are plenty of documentation/tutorials on knockouts website to help you with this.

Knockout Tutorial Website


问:
Extension method for classes implementing an interface
I am trying to create an extension method for all classes that implement an interface Iinterface which will return a list of T where T is the original class. So basically something like:

```<code>public static List<T> Funct<T>(this T obj)
where T : Iinterface, new()
</code>```

However this applies to every object, not just to Iinterface classes. So, I am trying to make something like this Iinterface obj, which would work but only if I use it as myObj.Funct<MyObjType>() I can not directly use it as List<MyObjType> list = myObj.Funct(), but not  . Is there any way I could have such a usage of an extension?

I am considering using a utility function or extending Iinterface to create something like this:

```<code>interface IExtend<T> : Iinterface
where T : IExtend<T> {}
</code>```

Then I can make an extension function like this:

```<code>public static List<T> Funct<T>(this IExtend<T> obj)
where T : IExtend<T> {}
</code>```

However before I do this, is there a way I could implement the function directly to Iinterface objects?

Update
Usage example:

```<code>public interface Iinterface { }
public interface Iinterface2 { }

public class MyObjType : Iinterface { }

public class SomeOtherClass : Iinterface2 { }

public static class Mine {

    public static List<T> Funct<T>(this T obj)
    where T : Iinterface, new() => null;

    public static void Funct(this Iinterface2 obj)
    {  }

    public static void Main()
    {
        MyObjType obj = new MyObjType();
        List<MyObjType> list = obj.Funct(); // the above mentioned function works in this case

        SomeOtherClass obj2 = new SomeOtherClass();
        obj2.Funct(); // uses the wrong extension function
    }

}
</code>```

Update 2

I have noticed some answers and suggestions where the usage is different. So just to clarify:

I do understand that using a different structure can get the output. I also already have. However I was looking if there is a way to have a structure that can work for this specific usage. Main reason being this is the simplest usage I found and my main aim is to implement this functionality in the simplest way.
So basically I am looking for the exact usage as obj.Funct() and obj2.Funct() without generics or parameters required to be passed.

答:
Not the best thing, but you could do something like this:

```<code>public static List<T> Funct<T>(this T obj, Iinterface type)
    where T : Iinterface, new()

public static void Funct(this Iinterface2 obj, Iinterface2 type)
</code>```

These second parameters are just here to help your compiler.
But, you will have to pass twice your object as parameters which is cumbersome.

```<code>public static void Main()
{
    MyObjType obj = new MyObjType();
    List<MyObjType> list = obj.Funct(obj); // still works as expected

    SomeOtherClass obj2 = new SomeOtherClass();
    obj2.Funct(obj2); // uses the correct one, now
}
</code>```

But, the best solution IMHO, would be to change your extension's names.

A method that returns a list and the other that doesn't. They don't do the same job, obviously.

So, why are they named exactly the same ?

Body:
I am trying to create an extension method for all classes that implement an interface Iinterface which will return a list of T where T is the original class. So basically something like:

public static List<T> Funct<T>(this T obj)
where T : Iinterface, new()

However this applies to every object, not just to Iinterface classes. So, I am trying to make something like this Iinterface obj, which would work but only if I use it as myObj.Funct<MyObjType>() I can not directly use it as List<MyObjType> list = myObj.Funct(), but not  . Is there any way I could have such a usage of an extension?

I am considering using a utility function or extending Iinterface to create something like this:

interface IExtend<T> : Iinterface
where T : IExtend<T> {}

Then I can make an extension function like this:

public static List<T> Funct<T>(this IExtend<T> obj)
where T : IExtend<T> {}

However before I do this, is there a way I could implement the function directly to Iinterface objects?

Update
Usage example:

public interface Iinterface { }
public interface Iinterface2 { }

public class MyObjType : Iinterface { }

public class SomeOtherClass : Iinterface2 { }

public static class Mine {

    public static List<T> Funct<T>(this T obj)
    where T : Iinterface, new() => null;

    public static void Funct(this Iinterface2 obj)
    {  }

    public static void Main()
    {
        MyObjType obj = new MyObjType();
        List<MyObjType> list = obj.Funct(); // the above mentioned function works in this case

        SomeOtherClass obj2 = new SomeOtherClass();
        obj2.Funct(); // uses the wrong extension function
    }

}

Update 2

I have noticed some answers and suggestions where the usage is different. So just to clarify:

I do understand that using a different structure can get the output. I also already have. However I was looking if there is a way to have a structure that can work for this specific usage. Main reason being this is the simplest usage I found and my main aim is to implement this functionality in the simplest way.
So basically I am looking for the exact usage as obj.Funct() and obj2.Funct() without generics or parameters required to be passed.

Body:
Not the best thing, but you could do something like this:

public static List<T> Funct<T>(this T obj, Iinterface type)
    where T : Iinterface, new()

public static void Funct(this Iinterface2 obj, Iinterface2 type)

These second parameters are just here to help your compiler.
But, you will have to pass twice your object as parameters which is cumbersome.

public static void Main()
{
    MyObjType obj = new MyObjType();
    List<MyObjType> list = obj.Funct(obj); // still works as expected

    SomeOtherClass obj2 = new SomeOtherClass();
    obj2.Funct(obj2); // uses the correct one, now
}

But, the best solution IMHO, would be to change your extension's names.

A method that returns a list and the other that doesn't. They don't do the same job, obviously.

So, why are they named exactly the same ?


问:
Where is Url.Action getting these values from?
I'm trying to create a link to the following GET action with Url.Action:

```<code>public class FooController : Controller
{
    [HttpGet]
    [Route("Foo/Apply/BarDetails/Part/{id}")]
    public IActionResult BarDetails(int id)
    {
    }
}
</code>```

And in my view I'm creating a URL with

```<code>Url.Action("BarDetails", "Foo", new {id = 1})
</code>```

However this generates the URL Foo/Apply/BarDetails/Part/10?id=1 which is definitely not what I want! Removing the values parameter simply removes the query string part of the URL. The only route I have registered at startup is

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

I've had a look at the ASP.NET Core source and I suspect that the "10" part of the URL is coming from a "1" + "0" operation somewhere as the routing code is split across 2+ repos it's hard to follow. Does anyone know how the last part of this URL is being generated and how I can fix it to match the id provided in the route values?

答: It turns out that routing has changed between MVC5 (where this controller was written) and ASP.NET Core 2. It's also related to the way I've structured my controller. Basically at some point the list of possible routes gets sorted by the URL so Foo/Apply/BarDetails/Part/10 gets sorted to the top of the list and as this matches the requested URL, it gets returned. For the full details, see this GitHub issue.

Body:
I'm trying to create a link to the following GET action with Url.Action:

public class FooController : Controller
{
    [HttpGet]
    [Route("Foo/Apply/BarDetails/Part/{id}")]
    public IActionResult BarDetails(int id)
    {
    }
}

And in my view I'm creating a URL with

Url.Action("BarDetails", "Foo", new {id = 1})

However this generates the URL Foo/Apply/BarDetails/Part/10?id=1 which is definitely not what I want! Removing the values parameter simply removes the query string part of the URL. The only route I have registered at startup is

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I've had a look at the ASP.NET Core source and I suspect that the "10" part of the URL is coming from a "1" + "0" operation somewhere as the routing code is split across 2+ repos it's hard to follow. Does anyone know how the last part of this URL is being generated and how I can fix it to match the id provided in the route values?


问:
mysql SQL: specific item to be first and then to sort the rest of the items
Lets say I have the table below.

I want to get all the friends, but I want the id 5 to be the first item in the list. I don't care about the order that I receive the rest of the items.

The desired query result will be:

```<code>friends
-------

id    name

5     nahum
1     moshe
2     haim
3     yusuf
4     gedalia
6     dana
</code>```

How can I do this?

using Mysql 5.1.x.

Thanks!

答:
If you want to do the same for UNION query, for example if you have:

```<code>select id,name
from friends
UNION
select id,name
from friends
order by id=5 desc
</code>```

... you would get an exception in PostgreSQL:

Only result column names can be used, not expressions or functions. HINT: Add the expression/function to every SELECT, or move the UNION into a from clause

To get around this, you would use the following:

```<code>select id,name, (id=5) AS is_five
from friends
UNION
select id,name, (id=5) AS is_five
from friends
order by is_five DESC, id DESC
</code>```

The expression (id=5) would return 't' OR 'f', depending on whether your column value is equal or not to the expected value (5), so the order by would first order the 't' columns, then the rest.

Body:
Lets say I have the table below.

I want to get all the friends, but I want the id 5 to be the first item in the list. I don't care about the order that I receive the rest of the items.

The desired query result will be:

friends
-------

id    name

5     nahum
1     moshe
2     haim
3     yusuf
4     gedalia
6     dana

How can I do this?

using Mysql 5.1.x.

Thanks!

Body:
If you want to do the same for UNION query, for example if you have:

select id,name
from friends
UNION
select id,name
from friends
order by id=5 desc

... you would get an exception in PostgreSQL:

Only result column names can be used, not expressions or functions. HINT: Add the expression/function to every SELECT, or move the UNION into a from clause

To get around this, you would use the following:

select id,name, (id=5) AS is_five
from friends
UNION
select id,name, (id=5) AS is_five
from friends
order by is_five DESC, id DESC

The expression (id=5) would return 't' OR 'f', depending on whether your column value is equal or not to the expected value (5), so the order by would first order the 't' columns, then the rest.


问:
Adding the same image every time a button is clicked
I making a drawing pad for teachers, i want to include geometrical shapes in it, there is a button on click of which a shape is displayed.
What i am doing now is i created an image view already and set its visibility to gone, on button i am making it visible.

```<code><ImageView
        android:id="@+id/ivReact"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/rectangle"
        android:visibility="gone"
        android:layout_centerInParent="true"

        />
</code>```

i want the previous image to be there, when a button is clicked the same image should be added twice in the layout and if the button clicked again it should be added again and go on.

is it possible to do that?

答:
You have to update image programmatically when button is clicked:

```<code>imageView.setImageResource(R.drawable.your_image);
</code>```

EDIT:

If you have ImageViews in LinearLayout, you can simply create new and add to layout:

```<code>ImageView imageView = (ImageView) LayoutInflater.from(context).inflate(R.layout.image_view_layout_name, null);
linearLayout.addView(imageView);
</code>```

Body:
I making a drawing pad for teachers, i want to include geometrical shapes in it, there is a button on click of which a shape is displayed.
What i am doing now is i created an image view already and set its visibility to gone, on button i am making it visible.

<ImageView
        android:id="@+id/ivReact"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/rectangle"
        android:visibility="gone"
        android:layout_centerInParent="true"

        />

i want the previous image to be there, when a button is clicked the same image should be added twice in the layout and if the button clicked again it should be added again and go on.

is it possible to do that?

Body:
You have to update image programmatically when button is clicked:

imageView.setImageResource(R.drawable.your_image);

EDIT:

If you have ImageViews in LinearLayout, you can simply create new and add to layout:

ImageView imageView = (ImageView) LayoutInflater.from(context).inflate(R.layout.image_view_layout_name, null);
linearLayout.addView(imageView);


问:
Java generics code compilation issues when building outside of Eclipse
I have configured a Maven build for a very small GWT project I'm having. Compiling/running from Eclipse causes no problem, but when I execute Maven build, I've got compilation issues in one single place (this is GWT 'client-side' code, but I'm not sure if that's the case). Maven/compile output:

```<code>[..]SmartTable.java:[63,52] ')' expected
[..]SmartTable.java:[63,53] ')' expected
[..]SmartTable.java:[63,69] ';' expected
[..]SmartTable.java:[63,71] not a statement
[..]SmartTable.java:[63,77] ';' expected
[..]SmartTable.java:[63,79] not a statement
</code>```

.. where this specific line defined as following:

```<code>final Comparator<T> comparator = ((SmartTable<T>.ComparableColumn) column).comparator;
</code>```

As you have guessed, I'm iterating over all columns defined for this generics-class (which I call 'SmartTable'), and getting a comparator (of course, if column instanceof SmartTable.ComparableColumn) for further operations.
Classes 'Column' and 'ComparableColumn' are nested in SmartTable, and their headers looks as following:

```<code>public abstract class Column {
    // private String id;
    private String caption;
    private int width;
    private Filter<T> filter;
...
public class ComparableColumn extends Column {
    private Comparator<T> comparator;
...
</code>```

When it gets compiled from Eclipse, I have no problems in packaging WAR (without 'clean' - simply package which will work since Eclipse configured to place .class files in the same target directory used by Maven) and deploying/running it correctly.

I've already tried changing maven-compiler-plugin  and  configuration (setting values 1.5, 1.6; and 1.4 - for sake of experiment to see if it will start complain on generics in general), but that wasn't of help. Eclipse project compiler compliance is default (1.6). It seems that I have no other compilation issues with the other generics code.

Tried to make it as short as possible, but not sure if I managed to do it well :)

EDIT: More of code by demand

```<code>public class SmartTable<T> extends FlexTable {
    private List<Column> columns = new ArrayList<Column>();
    ...
    private Comparator<T> currentComparator;
...

    public void init(Comparator<T> defaultComparator) {
        this.currentComparator = defaultComparator;
        ...
        int index = 0;
        for (Column column : columns) {
            ...
            if (column instanceof SmartTable.ComparableColumn) {
                @SuppressWarnings("unchecked")
                final Comparator<T> comparator = ((SmartTable<T>.ComparableColumn) column).comparator;
            ...
    }
...

    public abstract class Column {
        // private String id;
        private String caption;
        private int width;
        private Filter<T> filter;
        private List<WidgetCreator<T>> widgetCreators;

        public Column(/* String id, */String caption, int width, Filter<T> filter, List<WidgetCreator<T>> widgetCreators) {

...

    public class SimpleColumn extends Column {
        public SimpleColumn(/* String id, */String caption, int width, Filter<T> filter, List<WidgetCreator<T>> widgetCreators) {
            super(/* id, */caption, width, filter, widgetCreators);
        }

...

    public class ComparableColumn extends Column {
        private Comparator<T> comparator;

        public ComparableColumn(/* String id, */String caption, int width, Filter<T> filter,
                List<WidgetCreator<T>> widgetCreators, Comparator<T> comparator) {
            super(/* id, */caption, width, filter, widgetCreators);
            this.comparator = comparator;
        }

...

}
</code>```

EDIT2: Actual problem seems to be very concentrated :)

```<code>public class SmartTable2<T> {
    public void init() {
        Column c = new ComparableColumn();

        final Comparator<T> comparator = ((SmartTable2<T>.ComparableColumn) c).comparator;
    }

    class Column {

    }

    class ComparableColumn extends Column {
        Comparator<T> comparator;
    }
}
</code>```

EDIT3: Some thoughts, hopefully closer to the solution
.. so this doesn't compile simply with javac, throwing exactly same compilation errors. So what I've learned just now: Eclipse uses it's own internal Java compiler - which is part of JDT Core (hope I have not misunderstood it); so might it be the case that JDT Compiler is able to compile such a syntax, while Sun's JDK javac is not??? (oops, Oracle not Sun)

答:
Try this syntax:

```<code>Comparator<T> comparator = (Comparator<T>) ((SmartTable.ComparableColumn) column).comparator;
</code>```

EDIT:
The cast is useless:

```<code>Comparator<T> comparator = ((SmartTable.ComparableColumn) column).comparator;
</code>```

Does this resemble your scenario ?

```<code>public class Main {

    public static <T> void main(String[] args) throws Exception {
        SmartTable<T>.Column column = new SmartTable<T>().new Column();
        Comparator<T> comparator = ((SmartTable.ComparableColumn) column).comparator;

    }

    static class SmartTable<T> {
        class Column {

        }
        class ComparableColumn extends Column {
            Comparator<T> comparator;
        }
    }

}
</code>```

This compiles fine with javac (with unchecked warnings, of course), while trying to compile the cast to (SmartTable.ComparableColumn) results in exactly the errors in your post.

EDIT (of all edits):
Your question seems to have been asked before: Casting to an inner class with generics and the answer seems to be a compiler bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6665356

Body:
I have configured a Maven build for a very small GWT project I'm having. Compiling/running from Eclipse causes no problem, but when I execute Maven build, I've got compilation issues in one single place (this is GWT 'client-side' code, but I'm not sure if that's the case). Maven/compile output:

[..]SmartTable.java:[63,52] ')' expected
[..]SmartTable.java:[63,53] ')' expected
[..]SmartTable.java:[63,69] ';' expected
[..]SmartTable.java:[63,71] not a statement
[..]SmartTable.java:[63,77] ';' expected
[..]SmartTable.java:[63,79] not a statement

.. where this specific line defined as following:

final Comparator<T> comparator = ((SmartTable<T>.ComparableColumn) column).comparator;

As you have guessed, I'm iterating over all columns defined for this generics-class (which I call 'SmartTable'), and getting a comparator (of course, if column instanceof SmartTable.ComparableColumn) for further operations.
Classes 'Column' and 'ComparableColumn' are nested in SmartTable, and their headers looks as following:

public abstract class Column {
    // private String id;
    private String caption;
    private int width;
    private Filter<T> filter;
...
public class ComparableColumn extends Column {
    private Comparator<T> comparator;
...

When it gets compiled from Eclipse, I have no problems in packaging WAR (without 'clean' - simply package which will work since Eclipse configured to place .class files in the same target directory used by Maven) and deploying/running it correctly.

I've already tried changing maven-compiler-plugin  and  configuration (setting values 1.5, 1.6; and 1.4 - for sake of experiment to see if it will start complain on generics in general), but that wasn't of help. Eclipse project compiler compliance is default (1.6). It seems that I have no other compilation issues with the other generics code.

Tried to make it as short as possible, but not sure if I managed to do it well :)

EDIT: More of code by demand

public class SmartTable<T> extends FlexTable {
    private List<Column> columns = new ArrayList<Column>();
    ...
    private Comparator<T> currentComparator;
...

    public void init(Comparator<T> defaultComparator) {
        this.currentComparator = defaultComparator;
        ...
        int index = 0;
        for (Column column : columns) {
            ...
            if (column instanceof SmartTable.ComparableColumn) {
                @SuppressWarnings("unchecked")
                final Comparator<T> comparator = ((SmartTable<T>.ComparableColumn) column).comparator;
            ...
    }
...

    public abstract class Column {
        // private String id;
        private String caption;
        private int width;
        private Filter<T> filter;
        private List<WidgetCreator<T>> widgetCreators;

        public Column(/* String id, */String caption, int width, Filter<T> filter, List<WidgetCreator<T>> widgetCreators) {

...

    public class SimpleColumn extends Column {
        public SimpleColumn(/* String id, */String caption, int width, Filter<T> filter, List<WidgetCreator<T>> widgetCreators) {
            super(/* id, */caption, width, filter, widgetCreators);
        }

...

    public class ComparableColumn extends Column {
        private Comparator<T> comparator;

        public ComparableColumn(/* String id, */String caption, int width, Filter<T> filter,
                List<WidgetCreator<T>> widgetCreators, Comparator<T> comparator) {
            super(/* id, */caption, width, filter, widgetCreators);
            this.comparator = comparator;
        }

...

}

EDIT2: Actual problem seems to be very concentrated :)

public class SmartTable2<T> {
    public void init() {
        Column c = new ComparableColumn();

        final Comparator<T> comparator = ((SmartTable2<T>.ComparableColumn) c).comparator;
    }

    class Column {

    }

    class ComparableColumn extends Column {
        Comparator<T> comparator;
    }
}

EDIT3: Some thoughts, hopefully closer to the solution
.. so this doesn't compile simply with javac, throwing exactly same compilation errors. So what I've learned just now: Eclipse uses it's own internal Java compiler - which is part of JDT Core (hope I have not misunderstood it); so might it be the case that JDT Compiler is able to compile such a syntax, while Sun's JDK javac is not??? (oops, Oracle not Sun)

Body:
Try this syntax:

Comparator<T> comparator = (Comparator<T>) ((SmartTable.ComparableColumn) column).comparator;

EDIT:
The cast is useless:

Comparator<T> comparator = ((SmartTable.ComparableColumn) column).comparator;

Does this resemble your scenario ?

public class Main {

    public static <T> void main(String[] args) throws Exception {
        SmartTable<T>.Column column = new SmartTable<T>().new Column();
        Comparator<T> comparator = ((SmartTable.ComparableColumn) column).comparator;

    }

    static class SmartTable<T> {
        class Column {

        }
        class ComparableColumn extends Column {
            Comparator<T> comparator;
        }
    }

}

This compiles fine with javac (with unchecked warnings, of course), while trying to compile the cast to (SmartTable.ComparableColumn) results in exactly the errors in your post.

EDIT (of all edits):
Your question seems to have been asked before: Casting to an inner class with generics and the answer seems to be a compiler bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6665356


问:
Why does strtok return the wrong number of tokens?
I've been solving an Advent of Code problem in C, and I've hit something I don't understand. My C is very rusty, and I know this isn't a great example of C code. I have stripped the program down to the smallest section that demonstrates the behaviour that confuses me.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ae_load_file_to_memory(const char *filename, char **result)
{
    int size = 0;
    FILE *f = fopen(filename, "rb");
    if (f == NULL)
    {
        *result = NULL;
        return -1;
    }
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    fseek(f, 0, SEEK_SET);
    *result = (char *)malloc(sizeof(char) * (size + 1));
    if (size != fread(*result, sizeof(char), size, f))
    {
        free(*result);
        return -2;
    }
    fclose(f);
    (*result)[size] = 0;
    return size;
}

int main(void)
{
    const char delim = '\n';
    int fill_index = 0;
    char *token = NULL;
    char *content = NULL;

    ae_load_file_to_memory("input.txt", &content);

    token = strtok(content, &delim);

    while (token != NULL)
    {
        fill_index++;
        token = strtok(NULL, &delim);
    }
    printf("Fill index %d\n", fill_index);
}
</code>```

This code reads a file from disk, and then splits it into tokens using the newline as the delimiter. The final printf returns the correct number of tokens, 1044.

However, if I change the start of the main method to move the declaration of fill_index:

```<code>int main(void)
{
    int fill_index = 0;
    const char delim = '\n';
</code>```

...now strtok returns 1050 tokens, which is wrong. That's the only difference between the two files. I'm running on Mac OS X Sierra, gcc --version reports that its Apple LLVM version 9.0.0 (clang-900.0.38).

I'm sure I'm stomping on memory somewhere, and the first version only works by coincidence. However, I've got no idea why moving that declaration makes such a difference. Can anyone explain what's going on?

答:
You didn't use the delim properly. It would be  const char delim[] = "\n"; (Null terminated char array not a single character).

Earlier you were invoking undefined behavior by passing the wrong parameter.

From standard  §7.24.5.8

```<code>char *strtok(char * restrict s1,const char * restrict s2);
</code>```

And some example

```<code>static char str[] = "?a???b,,,#c";
         char *t;
         t   =   strtok(str, "?");         //   t   points to the token "a"
         t   =   strtok(NULL, ",");        //   t   points to the token "??b"
         t   =   strtok(NULL, "#,");       //   t   points to the token "c"
         t   =   strtok(NULL, "?");        //   t   is a null pointer
</code>```

Body:
I've been solving an Advent of Code problem in C, and I've hit something I don't understand. My C is very rusty, and I know this isn't a great example of C code. I have stripped the program down to the smallest section that demonstrates the behaviour that confuses me.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ae_load_file_to_memory(const char *filename, char **result)
{
    int size = 0;
    FILE *f = fopen(filename, "rb");
    if (f == NULL)
    {
        *result = NULL;
        return -1;
    }
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    fseek(f, 0, SEEK_SET);
    *result = (char *)malloc(sizeof(char) * (size + 1));
    if (size != fread(*result, sizeof(char), size, f))
    {
        free(*result);
        return -2;
    }
    fclose(f);
    (*result)[size] = 0;
    return size;
}

int main(void)
{
    const char delim = '\n';
    int fill_index = 0;
    char *token = NULL;
    char *content = NULL;

    ae_load_file_to_memory("input.txt", &content);

    token = strtok(content, &delim);

    while (token != NULL)
    {
        fill_index++;
        token = strtok(NULL, &delim);
    }
    printf("Fill index %d\n", fill_index);
}

This code reads a file from disk, and then splits it into tokens using the newline as the delimiter. The final printf returns the correct number of tokens, 1044.

However, if I change the start of the main method to move the declaration of fill_index:

int main(void)
{
    int fill_index = 0;
    const char delim = '\n';

...now strtok returns 1050 tokens, which is wrong. That's the only difference between the two files. I'm running on Mac OS X Sierra, gcc --version reports that its Apple LLVM version 9.0.0 (clang-900.0.38).

I'm sure I'm stomping on memory somewhere, and the first version only works by coincidence. However, I've got no idea why moving that declaration makes such a difference. Can anyone explain what's going on?

Body:
You didn't use the delim properly. It would be  const char delim[] = "\n"; (Null terminated char array not a single character).

Earlier you were invoking undefined behavior by passing the wrong parameter.

From standard  §7.24.5.8

char *strtok(char * restrict s1,const char * restrict s2);

And some example

static char str[] = "?a???b,,,#c";
         char *t;
         t   =   strtok(str, "?");         //   t   points to the token "a"
         t   =   strtok(NULL, ",");        //   t   points to the token "??b"
         t   =   strtok(NULL, "#,");       //   t   points to the token "c"
         t   =   strtok(NULL, "?");        //   t   is a null pointer


问:
missing jquery even though it is inside file laravel
I need help with this problem, it keeps giving me this error in the developer tool even though the file is already in place.

It keep giving me this error:

Failed to load resource: the server responded with a status of 404
  (Not Found)

Which I know that it is because it is not at the correct location but I have put it there correctly. Why do I keep getting this? Just now it was working fine but not sure what happen

Here is the location where I keep all the js file:

C:\xampp\htdocs\Evaluation\public\js

test.blade.php

```<code><a class="word-export" href="javascript:void(0)">Export to Word (.doc)</a>

    <div class="word-content">
        <title>Test</title>
        <p>test somehting</p>
        <p>jadanjdwlb</p>
    </div>

<script src="js/signature_pad.js"></script>
<script src="js/test2.js"></script>

<script src="js/jquery.min.js"></script>
<script src="js/FileSaver.js"></script>
<script src="js/jquery.wordexport.js"></script>
<script>
    $('.word-export').click(function(events){
        $('.word-content').wordExport();
    });
</script>
</code>```

It also gave me this error at my script and I know there shouldn't be anything wrong with it.

Uncaught ReferenceError: $ is not defined

答:
Try like this:

```<code><script type="text/javascript" src="{{ URL::asset('js/test2.js') }}"></script>
</code>```

{{ URL::asset() }} is take path from your public directory!

If you created directory in assets in public then take {{ URL::asset('assets/') }}

Hope this helps you!

Body:
I need help with this problem, it keeps giving me this error in the developer tool even though the file is already in place.

It keep giving me this error:

Failed to load resource: the server responded with a status of 404
  (Not Found)

Which I know that it is because it is not at the correct location but I have put it there correctly. Why do I keep getting this? Just now it was working fine but not sure what happen

Here is the location where I keep all the js file:

C:\xampp\htdocs\Evaluation\public\js

test.blade.php

Export to Word (.doc)

        <title>Test</title>

test somehting

jadanjdwlb

It also gave me this error at my script and I know there shouldn't be anything wrong with it.

Uncaught ReferenceError: $ is not defined

Body:
Try like this:

<script type="text/javascript" src="{{ URL::asset('js/test2.js') }}"></script>

{{ URL::asset() }} is take path from your public directory!

If you created directory in assets in public then take {{ URL::asset('assets/') }}

Hope this helps you!


问:
Javascript convert objects to array
I have an array of arrays of objects like this:

```<code>var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]
</code>```

And I want to convert it to this:

```<code>[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]
</code>```

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...

答:
You could use a destruction assignment for the inner array.

var array = [[{ name: 'a', value: 1, where: '1st array' }, { name: 'b', value: 2, where: '1st array' }], [{ name: 'a', value: 1, where: '2nd array' }, { name: 'b', value: 2, where: '2nd array' }]],
    result = array.reduce(
        (r, a) => r.concat(a.map(({ name, value, where }) => ([name, value, where]))),
        []
    );

console.log(result);```

Title: Javascript convert objects to array

Body:
I have an array of arrays of objects like this:

var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]

And I want to convert it to this:

[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...


问:
How to call python function in jquery in odoo 11
Python code:

```<code>@api.model
def test_method(self):
    a= 10
    b = 20
    c = a+b
    return c
</code>```

jQuery:

```<code>var Model = require('web.Model');
$(document).ready(function() {
  var test_model = new Model("MyClass");
  test_model.call("test_method").then(function(c) {
    console.log("res ult:" + JSON.stringify(result));
  });
});
</code>```

Error:

Missing depends,

The above code will is working in odoo 10 but not in odoo 11. I want to know how to call a python function from JS.

答:
in Odoo 11 you need to use

```<code>var rpc = require('web.rpc');
</code>```

instead of

```<code>var Model = require('web.Model');
</code>```

And later call a method using .query() method as below:

```<code>rpc.query({
            model: 'model.name',
            method: 'method_name',
            args: [{
                'arg1': value1,
                'arg2': value2,
            }]
        }).then(function (returned_value) { // do something }
</code>```

Body:
Python code:

@api.model
def test_method(self):
    a= 10
    b = 20
    c = a+b
    return c

jQuery:

var Model = require('web.Model');
$(document).ready(function() {
  var test_model = new Model("MyClass");
  test_model.call("test_method").then(function(c) {
    console.log("res ult:" + JSON.stringify(result));
  });
});

Error:

Missing depends,

The above code will is working in odoo 10 but not in odoo 11. I want to know how to call a python function from JS.

Body:
in Odoo 11 you need to use

var rpc = require('web.rpc');

instead of

var Model = require('web.Model');

And later call a method using .query() method as below:

rpc.query({
            model: 'model.name',
            method: 'method_name',
            args: [{
                'arg1': value1,
                'arg2': value2,
            }]
        }).then(function (returned_value) { // do something }