问:
Delphi 7: How to copy non-latin text to clipboard? (convert to Unicode?)
I have code like this to copy some text to clipboard.

```<code>uses Clipbrd;

var
  text: string;
begin
  text := 'Some non-latin text, for example Russian: Привет!'

  Clipboard.AsText := text;
end;
</code>```

Win7-8 OS, Russian locale (and format) set in OS Region settings, Delphi 7.

The problem is that it works only when I switch (shift+alt) to Russian keyboard layout when copying. Otherwise it will be pasted as "Ïðèâåò!" instead of "Привет!".

How can I fix that?

I think that I need somehow convert text to Unicode and call Unicode clipboard copy function from WinAPI? But how to do that?

答:
Thank you very much, by thees means you can also convert Encoding in the clipboard if you catch WM_CLIPBOARDUPDATE message - very usefull with old versions of delphi, e.g. for Russian Language.
Here is a full working code:

(N.B. This buffer listening tecnique will only work for Windows Vista and newer OS, that's why I use dynamic WinAPI linking, see this article -
 http://delphidabbler.com/articles?article=9)

```<code>type
  TAddOrRemoveClipboardFormatListener = function (hWndNewViewer : HWND) : BOOL; stdcall;

var _isClipboardChangeRequired : boolean;
var _addClipboardFormatListener, _removeClipboardFormatListener : TAddOrRemoveClipboardFormatListener;

procedure TDM.DataModuleCreate(Sender: TObject);
begin
<...>
  _addClipboardFormatListener := GetProcAddress(GetModuleHandle('user32.dll'), 'AddClipboardFormatListener');
  _removeClipboardFormatListener := GetProcAddress(GetModuleHandle('user32.dll'), 'RemoveClipboardFormatListener');

  if (Assigned(_addClipboardFormatListener) AND NOT _addClipboardFormatListener(Application.Handle)) then
    begin
      _isClipboardChangeRequired := false;
      ShowMessage('Не удалось установить перехватчик изменения буфера обмена! Кодировка при вставке в контролы может быть неверной!' +
        sLineBreak + 'Код ошибки (' + IntToStr(GetLastError()) + '): ' + SysErrorMessage(GetLastError()));
    //      WriteLog([ssWarn], ClassName, 'Не удалось установить перехватчик изменения буфера обмена! Кодировка при вставке в контролы может быть неверной!' +
    //      sLineBreak + 'Код ошибки (' + IntToStr(GetLastError()) + '): ' + SysErrorMessage(GetLastError()));
    end
    else
        _isClipboardChangeRequired := true;
<...>
end;

procedure TDM.DataModuleDestroy(Sender: TObject);
begin
    if Assigned(_removeClipboardFormatListener) then
    _removeClipboardFormatListener(Application.Handle);
end;

procedure TDM.ApplicationEvents_ClipboardChangeMessage(var Msg: tagMSG; var Handled: Boolean);
const
    // WM_CLIPBOARDUPDATE is not defined in the Messages unit of all supported
  // versions of Delphi, so we defined it here for safety.
  // (взято отсюда: http://delphidabbler.com/articles?article=9)
  WM_CLIPBOARDUPDATE = $031D;
  MAX_CLIPBOARD_OPEN_ATTEMPTS = 3;
var
    textBuf : array[0..512] of WideChar;
  clipHandle : THandle;
  dataPtr: Pointer;
  dataSize : integer;
  str : string;
  attemptCount : integer;
  isClipboardOpened : boolean;
begin
  // если система не поддерживает слежение за буфером обмена, прекращаем дальнейшие попытки это сделать
    if (NOT Assigned(_addClipboardFormatListener)) then
    begin
        ApplicationEvents_ClipboardChange.OnMessage := nil;
      Exit;
    end;
  if (Msg.message = WM_CLIPBOARDUPDATE) AND (Clipboard.HasFormat(CF_UNICODETEXT)) then
    if NOT _isClipboardChangeRequired then
        begin
            _isClipboardChangeRequired := true;
        Exit;
      end
    else
      begin
        attemptCount := 1;
        isClipboardOpened := false;
        repeat
          try
            Clipboard.Open();
            isClipboardOpened := true;
          except
            if (attemptCount >= MAX_CLIPBOARD_OPEN_ATTEMPTS) then
              begin
                OutputDebugString(PChar('Внимание: Нет доступа к буферу обмена - невозможно изменить его кодировку!'));
                Exit;
              end
            else
              inc(attemptCount);
          end;
        until isClipboardOpened;
        clipHandle := Clipboard.GetAsHandle(CF_UNICODETEXT);
        dataPtr := GlobalLock(clipHandle);
        if (dataPtr <> nil) then
          try
            dataSize := GlobalSize(clipHandle);
            ZeroMemory(@textBuf, sizeof(textBuf));
            CopyMemory(@textBuf, dataPtr, dataSize);
            SetString(str, textBuf, dataSize);
            str := Trim(str);
            Clipboard.AsText := str;
            _isClipboardChangeRequired := false;
            OutputDebugString(PChar('Clipboard encoding converted!'));
          finally
            GlobalUnlock(clipHandle);
          end;
        Clipboard.Close();
      end;
end;
</code>```

Body:
I have code like this to copy some text to clipboard.

uses Clipbrd;

var
  text: string;
begin
  text := 'Some non-latin text, for example Russian: Привет!'

  Clipboard.AsText := text;
end;

Win7-8 OS, Russian locale (and format) set in OS Region settings, Delphi 7.

The problem is that it works only when I switch (shift+alt) to Russian keyboard layout when copying. Otherwise it will be pasted as "Ïðèâåò!" instead of "Привет!".

How can I fix that?

I think that I need somehow convert text to Unicode and call Unicode clipboard copy function from WinAPI? But how to do that?

Body:
Thank you very much, by thees means you can also convert Encoding in the clipboard if you catch WM_CLIPBOARDUPDATE message - very usefull with old versions of delphi, e.g. for Russian Language.
Here is a full working code:

(N.B. This buffer listening tecnique will only work for Windows Vista and newer OS, that's why I use dynamic WinAPI linking, see this article -
 http://delphidabbler.com/articles?article=9)

type
  TAddOrRemoveClipboardFormatListener = function (hWndNewViewer : HWND) : BOOL; stdcall;

var _isClipboardChangeRequired : boolean;
var _addClipboardFormatListener, _removeClipboardFormatListener : TAddOrRemoveClipboardFormatListener;

procedure TDM.DataModuleCreate(Sender: TObject);
begin
<...>
  _addClipboardFormatListener := GetProcAddress(GetModuleHandle('user32.dll'), 'AddClipboardFormatListener');
  _removeClipboardFormatListener := GetProcAddress(GetModuleHandle('user32.dll'), 'RemoveClipboardFormatListener');

  if (Assigned(_addClipboardFormatListener) AND NOT _addClipboardFormatListener(Application.Handle)) then
    begin
      _isClipboardChangeRequired := false;
      ShowMessage('Не удалось установить перехватчик изменения буфера обмена! Кодировка при вставке в контролы может быть неверной!' +
        sLineBreak + 'Код ошибки (' + IntToStr(GetLastError()) + '): ' + SysErrorMessage(GetLastError()));
    //      WriteLog([ssWarn], ClassName, 'Не удалось установить перехватчик изменения буфера обмена! Кодировка при вставке в контролы может быть неверной!' +
    //      sLineBreak + 'Код ошибки (' + IntToStr(GetLastError()) + '): ' + SysErrorMessage(GetLastError()));
    end
    else
        _isClipboardChangeRequired := true;
<...>
end;

procedure TDM.DataModuleDestroy(Sender: TObject);
begin
    if Assigned(_removeClipboardFormatListener) then
    _removeClipboardFormatListener(Application.Handle);
end;

procedure TDM.ApplicationEvents_ClipboardChangeMessage(var Msg: tagMSG; var Handled: Boolean);
const
    // WM_CLIPBOARDUPDATE is not defined in the Messages unit of all supported
  // versions of Delphi, so we defined it here for safety.
  // (взято отсюда: http://delphidabbler.com/articles?article=9)
  WM_CLIPBOARDUPDATE = $031D;
  MAX_CLIPBOARD_OPEN_ATTEMPTS = 3;
var
    textBuf : array[0..512] of WideChar;
  clipHandle : THandle;
  dataPtr: Pointer;
  dataSize : integer;
  str : string;
  attemptCount : integer;
  isClipboardOpened : boolean;
begin
  // если система не поддерживает слежение за буфером обмена, прекращаем дальнейшие попытки это сделать
    if (NOT Assigned(_addClipboardFormatListener)) then
    begin
        ApplicationEvents_ClipboardChange.OnMessage := nil;
      Exit;
    end;
  if (Msg.message = WM_CLIPBOARDUPDATE) AND (Clipboard.HasFormat(CF_UNICODETEXT)) then
    if NOT _isClipboardChangeRequired then
        begin
            _isClipboardChangeRequired := true;
        Exit;
      end
    else
      begin
        attemptCount := 1;
        isClipboardOpened := false;
        repeat
          try
            Clipboard.Open();
            isClipboardOpened := true;
          except
            if (attemptCount >= MAX_CLIPBOARD_OPEN_ATTEMPTS) then
              begin
                OutputDebugString(PChar('Внимание: Нет доступа к буферу обмена - невозможно изменить его кодировку!'));
                Exit;
              end
            else
              inc(attemptCount);
          end;
        until isClipboardOpened;
        clipHandle := Clipboard.GetAsHandle(CF_UNICODETEXT);
        dataPtr := GlobalLock(clipHandle);
        if (dataPtr <> nil) then
          try
            dataSize := GlobalSize(clipHandle);
            ZeroMemory(@textBuf, sizeof(textBuf));
            CopyMemory(@textBuf, dataPtr, dataSize);
            SetString(str, textBuf, dataSize);
            str := Trim(str);
            Clipboard.AsText := str;
            _isClipboardChangeRequired := false;
            OutputDebugString(PChar('Clipboard encoding converted!'));
          finally
            GlobalUnlock(clipHandle);
          end;
        Clipboard.Close();
      end;
end;


来源: stackexchange

问:
Why the result not fit when I run group by and order by?
My query like this :

```<code>SELECT *
FROM products_categories
WHERE product_id = 1
ORDER BY updated_at DESC
</code>```

If the query run, the result like this :

I add group by like this :

```<code>SELECT *
FROM products_categories
WHERE product_id = 1
GROUP BY product_id
ORDER BY updated_at DESC
</code>```

The result : display 1 record (id=1)

It does not fit. Should the id shown is id = 3 (latest updated_at)

How can I solve it?

答:
Unfortunately you are trapped by the strange behavior of mysql (some other sql engines like sqlite do the same). Your sql query is not correct according to sql98 and should be yield an error. You can not select fields which are not grouped for or using aggregate function (max/min/avg). Unfortunately mysql wont yield an error but gives back the first value for the ill defined fields.

The group by will merge all your rows with the same product_id into single row. That's why you get 1 (wrong) line back.  I suppose you thought the order by will run first before the group by. This is not the case. The single (grouped by) row will be sorted.

If you want to get the latest updated_at, you should query that:
select max(updated_at) from products_categories WHERE product_id = 1 and then query the row which using this value in an another select. (select * from products_categories where product_id=1 and updated_at = (select max(updated_at) from products_categories where products_id=1)) Of course it may not work as intended if your updated_at value is not unique. Then you will get multiple results.

If you need strictly one answer row you can do
SELECT * FROM products_categories
WHERE product_id = 1  ORDER BY updated_at DESC LIMIT 1;

ContentLicense: CC BY-SA 3.0

Body:
My query like this :

SELECT *
FROM products_categories
WHERE product_id = 1
ORDER BY updated_at DESC

If the query run, the result like this :

I add group by like this :

SELECT *
FROM products_categories
WHERE product_id = 1
GROUP BY product_id
ORDER BY updated_at DESC

The result : display 1 record (id=1)

It does not fit. Should the id shown is id = 3 (latest updated_at)

How can I solve it?


问:
Google Mobile Native Express ads iOS - Issues with [AnyObject]
I'm trying to implement Native Express Ads in my iOS Project, with swift.

First of all I have a class

```<code>class Events {
  var _eventName: String!
  var _realDate: Date!

    var realDate: Date {
        if _realDate == nil {
            _realDate = nil
        }
        return _realDate
    }

    var eventName: String {
        if _eventName == nil {
            _eventName = ""
        }
        return _eventName
    }

//...
}
</code>```

Which class is getting a JSON from internet and it fills out a tableview.
Also i have some functions with this like Searching through the names of the events and also i have a button that filters events by date.
All these are working fine with the code below

```<code>var eventData = [Events]()
var filteredEvents = [Events]()

eventData.sort() { $0.realDate < $1.realDate }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filteredEvents = eventData.filter { events in
            return events.eventName.lowercased().contains(searchText.lowercased())
        }
</code>```

So While i followed the example of the native express ads from here and here

First of all i changed

```<code>var eventData = [Events]()
var filteredEvents = [Events]()
</code>```

to

```<code>var eventData = [AnyObject]()
var filteredEvents = [AnyObject]()
</code>```

So the ads can be appended to the array as i show below in the function addNativeExpressAds()!
I have issues with the functions sort() and the filter.

for the sort() it says Value of type 'AnyObject' has no member 'realDate'

and for filter it says Value of type 'AnyObject' has no member 'eventName'

Update 1.
After some research on google i found out this could be a solution for sort() function

```<code>eventData.sort() { (($0 as! Events).realDate ) < ($1 as! Events).realDate }
</code>```

Although the eventData Array also includes GADNativeExpressAdView since in the example that i have linked above there is this block of code that downloads the express native ads and appends them to the AnyObject Array eventData see below

```<code>func addNativeExpressAds() {
    var index = adInterval
    // Ensure subview layout has been performed before accessing subview sizes.
    nearMeTable.layoutIfNeeded()
    while index < eventData.count {
        let adSize = GADAdSizeFromCGSize(
            CGSize(width: nearMeTable.contentSize.width, height: adViewHeight))
        guard let adView = GADNativeExpressAdView(adSize: adSize) else {
            print("GADNativeExpressAdView failed to initialize at index \(index)")
            return
        }
        adView.adUnitID = adUnitID
        adView.rootViewController = self
        adView.delegate = self

        eventData.insert(adView, at: index) //here it inserts the ads
        adsToLoad.append(adView)
        loadStateForAds[adView] = false

        index += adInterval
    }
}
</code>```

and by this I get the error

```<code>Could not cast value of type 'GADNativeExpressAdView' (0x10046ebd8) to 'Events_Near_Me.Events' (0x10046fb90).
</code>```

So i can't sort the array of any object cause the GADNativeExpressAdView ads inside my array.

Any idea about this one?

答:
First of all in your sort function you force a cast ! to an Event type but your array does not only contain Event object only. So you force the cast and your code fails.

```<code>eventData.sort { (first, second) in
    if let first = first as? Event,
        let second = second as? Event {
        return first.realDate < second.realDate
    }
    if let fist = first as? GADNativeExpressAdView,
        let second = second as? GADNativeExpressAdView {
        return \\ compare?
    }

    return false
}
</code>```

This is a sample code, I haven't tested it to see if it works as expected but it should give you an idea on how to proceed.

P.S. I do not think it is a good practice to mix your data with views. You should keep your array clean of views and have it only contain data.

Body:
I'm trying to implement Native Express Ads in my iOS Project, with swift.

First of all I have a class

class Events {
  var _eventName: String!
  var _realDate: Date!

    var realDate: Date {
        if _realDate == nil {
            _realDate = nil
        }
        return _realDate
    }

    var eventName: String {
        if _eventName == nil {
            _eventName = ""
        }
        return _eventName
    }

//...
}

Which class is getting a JSON from internet and it fills out a tableview.
Also i have some functions with this like Searching through the names of the events and also i have a button that filters events by date.
All these are working fine with the code below

var eventData = [Events]()
var filteredEvents = [Events]()

eventData.sort() { $0.realDate < $1.realDate }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filteredEvents = eventData.filter { events in
            return events.eventName.lowercased().contains(searchText.lowercased())
        }

So While i followed the example of the native express ads from here and here

First of all i changed

var eventData = [Events]()
var filteredEvents = [Events]()

to

var eventData = [AnyObject]()
var filteredEvents = [AnyObject]()

So the ads can be appended to the array as i show below in the function addNativeExpressAds()!
I have issues with the functions sort() and the filter.

for the sort() it says Value of type 'AnyObject' has no member 'realDate'

and for filter it says Value of type 'AnyObject' has no member 'eventName'

Update 1.
After some research on google i found out this could be a solution for sort() function

eventData.sort() { (($0 as! Events).realDate ) < ($1 as! Events).realDate }

Although the eventData Array also includes GADNativeExpressAdView since in the example that i have linked above there is this block of code that downloads the express native ads and appends them to the AnyObject Array eventData see below

func addNativeExpressAds() {
    var index = adInterval
    // Ensure subview layout has been performed before accessing subview sizes.
    nearMeTable.layoutIfNeeded()
    while index < eventData.count {
        let adSize = GADAdSizeFromCGSize(
            CGSize(width: nearMeTable.contentSize.width, height: adViewHeight))
        guard let adView = GADNativeExpressAdView(adSize: adSize) else {
            print("GADNativeExpressAdView failed to initialize at index \(index)")
            return
        }
        adView.adUnitID = adUnitID
        adView.rootViewController = self
        adView.delegate = self

        eventData.insert(adView, at: index) //here it inserts the ads
        adsToLoad.append(adView)
        loadStateForAds[adView] = false

        index += adInterval
    }
}

and by this I get the error

Could not cast value of type 'GADNativeExpressAdView' (0x10046ebd8) to 'Events_Near_Me.Events' (0x10046fb90).

So i can't sort the array of any object cause the GADNativeExpressAdView ads inside my array.

Any idea about this one?

Body:
First of all in your sort function you force a cast ! to an Event type but your array does not only contain Event object only. So you force the cast and your code fails.

eventData.sort { (first, second) in
    if let first = first as? Event,
        let second = second as? Event {
        return first.realDate < second.realDate
    }
    if let fist = first as? GADNativeExpressAdView,
        let second = second as? GADNativeExpressAdView {
        return \\ compare?
    }

    return false
}

This is a sample code, I haven't tested it to see if it works as expected but it should give you an idea on how to proceed.

P.S. I do not think it is a good practice to mix your data with views. You should keep your array clean of views and have it only contain data.


问:
Remove user from a slack team [API]
I need to remove user from slack team (totally), via API using Python. Recently I've found the undocumented methods https://github.com/ErikKalkoken/slackApiDoc
But users.admin.setInactive is not working correctly. It seems that there is no such method, because I get an AttributeError: 'UsersAdmin' object has no attribute 'setInactive'
Is there any way to achieve my goal?

答:
Unfortunately this method is not available for Slack teams that use the free tier, so I can not fully test it. However, I am still getting the error "paid_only" when I call it, which would suggest that the API method itself does exist.

Based on your error it sounds more like in error in the implementation of the access layer to the API (e.g. if you are using 3rd party library it may not include this method).

You can verify by calling the method directly, which should work if you are on a paid tier:

```<code>https://slack.com/api/users.admin.setInactive?token=TOKEN&user=U12345678
</code>```

If that works your issue is in the access layer of your code / the 3rd party library you are using.

Title: Remove user from a slack team [API]

Body:
Unfortunately this method is not available for Slack teams that use the free tier, so I can not fully test it. However, I am still getting the error "paid_only" when I call it, which would suggest that the API method itself does exist.

Based on your error it sounds more like in error in the implementation of the access layer to the API (e.g. if you are using 3rd party library it may not include this method).

You can verify by calling the method directly, which should work if you are on a paid tier:

https://slack.com/api/users.admin.setInactive?token=TOKEN&user=U12345678

If that works your issue is in the access layer of your code / the 3rd party library you are using.


问:
How to split list to lists by condition?
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

```<code>in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]
</code>```

by condition

```<code>If (next - prev) > 4
</code>```

答:
NOTICE: in and next are Python keywords and builtin functions respectively.

The trick is to use zip() function with 2 slices of the same list, but shifted on one item:

```<code>in_list = [1, 2, 3, 9, 10, 11, 100, 200]

parts = [[]]
for prev_item, next_item in zip(in_list[:-1], in_list[1:]):
    top = parts[-1]
    top.append(prev_item)
    if next_item - prev_item > 4:
        parts.append([])
top = parts[-1]
top.append(in_list[-1])
</code>```

The output is:

```<code>[[1, 2, 3], [9, 10, 11], [100], [200]]
</code>```

Body:
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]

by condition

If (next - prev) > 4

Body:
NOTICE: in and next are Python keywords and builtin functions respectively.

The trick is to use zip() function with 2 slices of the same list, but shifted on one item:

in_list = [1, 2, 3, 9, 10, 11, 100, 200]

parts = [[]]
for prev_item, next_item in zip(in_list[:-1], in_list[1:]):
    top = parts[-1]
    top.append(prev_item)
    if next_item - prev_item > 4:
        parts.append([])
top = parts[-1]
top.append(in_list[-1])

The output is:

[[1, 2, 3], [9, 10, 11], [100], [200]]


答:
Assuming that your data.frame is named DF, you can first create a variable that extracts the month and year from the invoice dates:

```<code>invoice.months <- format(as.Date(DF$Invoice.Date), "%m%Y")
</code>```

Then create a unique identifier for each invoice claim, removing the replicate claims within each month:

```<code>unique.id <- unique(paste(DF$Invoice, invoice.months))
</code>```

To get the number of unique invoice claims each month (from the earliest month to the latest month):

```<code>library(lubridate)
month.vector <- format(seq.Date(min(DF$mtime), max(DF$mtime), by="1 month"), "%m%Y")
num.claims.per.month <- sapply(month.vector, function (x) length(grep(x, unique.id)))
</code>```

Title: Aggregate sum without duplicated values of the same month, same reference but different date

Body:
This is my df. As you can see it has unique values since the invoice could be claimed several times in the same month.

        Invoice        mtime            Client.Code. Invoice.Date   Amount
1      20170100000 2017-04-03 13:03:53      1006442   2017-01-23   645.75
6      20170100001 2017-05-04 11:57:06      1004791   2017-01-23   5798.10
15     20170100007 2017-04-03 13:03:53      1004775   2017-01-23   12912.81
21     20170100008 2017-04-03 13:03:53      1004775   2017-01-23   132.37
26     20170100011 2017-04-11 09:59:42      1004689   2017-01-23   13455.10
38     20170100011 2017-04-19 15:59:18      1004689   2017-01-23   13455.10
50     20170100011 2017-05-04 11:57:06      1004689   2017-01-23   13455.10
62     20170100012 2017-04-03 13:03:53      1004775   2017-01-23   15649.38
68     20170100013 2017-04-03 13:03:53      1004849   2017-01-23   6616.40
74     20170100013 2017-04-11 09:59:42      1004849   2017-01-23   6616.40
80     20170100024 2017-04-03 13:03:53      1004962   2017-01-24   3046.59

I would like to know the aggregate amount of the invoices claimed per month (mtime), so if the same invoice has been claimed twice in a month, just sum like one, but if it have been claimed in several months, it should sum one for each month.

I dont know how to do the trick.

Thank you.

Body:
Assuming that your data.frame is named DF, you can first create a variable that extracts the month and year from the invoice dates:

invoice.months <- format(as.Date(DF$Invoice.Date), "%m%Y")

Then create a unique identifier for each invoice claim, removing the replicate claims within each month:

unique.id <- unique(paste(DF$Invoice, invoice.months))

To get the number of unique invoice claims each month (from the earliest month to the latest month):

library(lubridate)
month.vector <- format(seq.Date(min(DF$mtime), max(DF$mtime), by="1 month"), "%m%Y")
num.claims.per.month <- sapply(month.vector, function (x) length(grep(x, unique.id)))


问:
How MongoDb dynamic Child Object access in PHP
How MongoDb dynamic Child Object access in PHP

i have following example code, i need to do same query in php

i will show the SHELL Script to get the result in mongoDB

```<code>db.getCollection('Data').find({'COLLECTION.2017-06-16': {$type:'object'}});
</code>```

How i can able to get result in PHP Collection Query with Array and Objects.

i have tried like this but its not working properly

```<code>$finder = $drum->find({'COLLECTION.2017-06-14': {$type:'object'}});
</code>```

or

```<code>$finder = $drum->find(array('COLLECTION.2017-06-14' => array($type:'object')));
</code>```

Thanks in advance i have attached sample json also.
please ref and give me solution.

```<code> {
  "CODE": "XXXYYY",
  "COLLECTION": {
    "2017-06-16": {
      "TEST": "CLEAR"
    },
    "2017-06-17":{
        "TEST":"PUTPOST"
    }
  },
  "Success": true,
},{
  "CODE": "XXXYYYZZZZ",
  "COLLECTION": {
    "2017-06-16": {
      "TEST": "CLEAR"
    },
    "2017-06-17":{
        "TEST":"PUTPOST"
    }
  },
  "Success": true,
}
</code>```

答:
Your syntax is wrong. In PHP, you can't use the :, but need to use => for key/value combinations.

Instead of array(…) you can use […] for clarity.

You also need to enclose the array keys with '…':

```<code>$drum->find( [ 'COLLECTION.2017-06-14' => [ '$type' => 'object' ] ] );
</code>```

I would also like to point out that it is usually a bad idea to use a value (2017-06-14) as a key. It makes it often harder to query against, and even impossible to find a range of documents that fall for example in a specific month.

Body:
How MongoDb dynamic Child Object access in PHP

i have following example code, i need to do same query in php

i will show the SHELL Script to get the result in mongoDB

db.getCollection('Data').find({'COLLECTION.2017-06-16': {$type:'object'}});

How i can able to get result in PHP Collection Query with Array and Objects.

i have tried like this but its not working properly

$finder = $drum->find({'COLLECTION.2017-06-14': {$type:'object'}});

or

$finder = $drum->find(array('COLLECTION.2017-06-14' => array($type:'object')));

Thanks in advance i have attached sample json also.
please ref and give me solution.

 {
  "CODE": "XXXYYY",
  "COLLECTION": {
    "2017-06-16": {
      "TEST": "CLEAR"
    },
    "2017-06-17":{
        "TEST":"PUTPOST"
    }
  },
  "Success": true,
},{
  "CODE": "XXXYYYZZZZ",
  "COLLECTION": {
    "2017-06-16": {
      "TEST": "CLEAR"
    },
    "2017-06-17":{
        "TEST":"PUTPOST"
    }
  },
  "Success": true,
}

Body:
Your syntax is wrong. In PHP, you can't use the :, but need to use => for key/value combinations.

Instead of array(…) you can use […] for clarity.

You also need to enclose the array keys with '…':

$drum->find( [ 'COLLECTION.2017-06-14' => [ '$type' => 'object' ] ] );

I would also like to point out that it is usually a bad idea to use a value (2017-06-14) as a key. It makes it often harder to query against, and even impossible to find a range of documents that fall for example in a specific month.


问:
List the names of people that have never scored above 3
From a table like this:

```<code>Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1
</code>```

Return the names of people that have never scored above 3

Answer would be:

```<code>Name   |
------ |
Bill   |
</code>```

答:
```<code>SELECT name
FROM table_name
WHERE score < 3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
From a table like this:

Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1

Return the names of people that have never scored above 3

Answer would be:

Name   |
------ |
Bill   |


问:
COM Integration from ALBPM - Cannot find IDispatch for '{00020906-0000-0000-C000-000000000046}'
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

```<code>wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename
</code>```

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

答:
To inspect installed COM Interfaces on your PC i suggest you download oleview.exe which is part of the Windows 2003 resource Kit

I actually have {00020906-0000-0000-C000-000000000046} but also no IDispatch interface and get a "Class not registered" error when trying to create an instance of it. My home PC doesn't have office installed just the Office tools which is most likely the cause.

In the past when automating Office Applications i was always able to talk to a version independent ProgID's such as "Excel.Application". Are you sure your referencing the right COM Objects ? Check it out in oleview or give us some more code to munch on :)

OwnerDisplayName: Daniel M

LastEditorDisplayName: warren

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

OwnerDisplayName: Martijn Laarman


问:
fopen does not return
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

```<code>printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);
</code>```

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik

答: So what? fopen is allowed to block until the file has been opened, or until it has been determined that access is denied. If you have a slow storage device, it is absolutely correct to wait until that becomes available. But that is an operating system issue then, not C's.</p>

Title: fopen does not return

Body:
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik


问:
How to get the total number of positive, neutral and negative tweets in SQL Server?
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

```<code>T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText
</code>```

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

```<code>SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6
</code>```

答:
Why not just use:</p>

```<code>SELECT COUNT(*), SentimentLabel
FROM SentimentLabel
GROUP BY SentimentLabel
</code>```

Body:
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6

Body:
Why not just use:

SELECT COUNT(*), SentimentLabel
FROM SentimentLabel
GROUP BY SentimentLabel


问:
How to use @ syntax in Emmet 2.0?
This worked in in older Emmet of VS Code but not in the newer one. Is there a different syntax for this?

This is its output, same as Intellisense.

答: This feature is not yet implemented in new Emmet</p>

Title: How to use @ syntax in Emmet 2.0?


问:
Exporting DNS zonefile from Amazon Route 53
I would like to export a DNS zonefile from my Amazon Route 53 setup. Is this possible, or can zonefiles only be created manually? (e.g. through http://www.zonefile.org/?lang=en)</p>

答: Exporting and importing is possible with https://github.com/RisingOak/route53-transfer</p>


问:
A more readable way of joining some lists with some lists returned by lapply in R
Say I want to create a list of four lists. The first two are manually defined, the second two are the result of lapply. So to be specific, I have these three items:

```<code>> list("a" = 1)
> list("b" = 1)
> lapply(1:2,FUN=function(i) { list("c"=i) }
</code>```

And I want to combine them so that the output list is:

```<code>[[1]]
[[1]]$a
[1] 1

[[2]]
[[2]]$b
[1] 1

[[3]]
[[3]]$c
[1] 1

[[4]]
[[4]]$c
[1] 2
</code>```

I can achieve it using the following:

```<code>> unlist(recursive=FALSE,
         list(
              list(list("a"=1),list("b"=1)),
              lapply(1:2,FUN = function(i) { list("c"=i) })
              )
         )
</code>```

But all this lists of lists of lists business seems a bit verbose! I know I can of course just write a function to do this, but I'm wondering if there is a cleaner one liner?

答:
When you're objecting to that " lists of lists of lists business seems a bit verbose", are you unhappy that the output of lists is verbose, or the code of lists is verbose?

Which part(s) can be an atomic list, and which parts need to remain a list?  Do either of these address your concern?

```<code>c(
  rep("a", 1),
  rep("b", 1),
  rep("c", 2)
)

rep(
  c("a", "b", "c"),
  c( 1 ,  1 ,  2 )
)
</code>```

Both produce the atomic character vector:

```<code>[1] "a" "b" "c" "c"
</code>```

Body:
Say I want to create a list of four lists. The first two are manually defined, the second two are the result of lapply. So to be specific, I have these three items:

> list("a" = 1)
> list("b" = 1)
> lapply(1:2,FUN=function(i) { list("c"=i) }

And I want to combine them so that the output list is:

[[1]]
[[1]]$a
[1] 1

[[2]]
[[2]]$b
[1] 1

[[3]]
[[3]]$c
[1] 1

[[4]]
[[4]]$c
[1] 2

I can achieve it using the following:

> unlist(recursive=FALSE,
         list(
              list(list("a"=1),list("b"=1)),
              lapply(1:2,FUN = function(i) { list("c"=i) })
              )
         )

But all this lists of lists of lists business seems a bit verbose! I know I can of course just write a function to do this, but I'm wondering if there is a cleaner one liner?

Body:
When you're objecting to that " lists of lists of lists business seems a bit verbose", are you unhappy that the output of lists is verbose, or the code of lists is verbose?

Which part(s) can be an atomic list, and which parts need to remain a list?  Do either of these address your concern?

c(
  rep("a", 1),
  rep("b", 1),
  rep("c", 2)
)

rep(
  c("a", "b", "c"),
  c( 1 ,  1 ,  2 )
)

Both produce the atomic character vector:

[1] "a" "b" "c" "c"


问:
Nested if loop iteration in python
I am fairly new to python and at a beginner stage. I am trying to create a loop which iterates within an internal loop with an conditional statement.Here is what i want to accomplish:

1)Iterates through the locations list that were defined before

2) For each location, iterate through each player in the players dictionary with a second, internal for-loop.

Here is my code :

```<code>locations = ['reddit.com', 'amazon.com', 'twitter.com', 'linkedin.com', 'ebay.com', 'netflix.com', 'google.com', 'stackoverflow.com', 'github.com', 'quora.com']

players = {1: {'player_name': 'cynthia', 'time_played': 30.9, 'player_pokemon': {}, 'gyms_visited': []}, 2: {'player_name': 'teri', 'time_played': 22.2, 'player_pokemon': {}, 'gyms_visited': ['alcatraz', 'pacific_beach']}}

for loc in locations:
   for player in players.keys():
    if player["gyms_visited"] != loc[""]:
        print (loc, player)
</code>```

答:
There are some problems here:

loc is an element of the locations list, so a string, you cannot call [""] on a string; and

player is an element from the key set of the dictionary. So it does not contain a "gyms_visited" list.

You should iterate over the .values() of the dictionary, and omit the [""] acces on the loc:

```<code>for loc in locations:
   for player in players.<b>values()</b>:
    if player["gyms_visited"] != <b>loc</b>: # no [""]
        print (loc, player)</code>```

In case you want to print the player key instead of the dictionary, you can iterate over the .items() of the dictionary:

```<code>for loc in locations:
   for <b>player_id,</b>player in players.<b>items()</b>:
    if player["gyms_visited"] != <b>loc</b>:
        print (loc, player_id)</code>```

Now the gyms_visited of a player is a list. And a list is never equal to a string. So that can never happen. If you look however whether the loc is in the list of gyms_visited, you can use:

```<code>for loc in locations:
   for player_id,player in players.items():
    if loc <b>in</b> player["gyms_visited"]:
        print (loc, player_id)</code>```

Title: Nested if loop iteration in python

Body:
I am fairly new to python and at a beginner stage. I am trying to create a loop which iterates within an internal loop with an conditional statement.Here is what i want to accomplish:

1)Iterates through the locations list that were defined before

2) For each location, iterate through each player in the players dictionary with a second, internal for-loop.

Here is my code :

locations = ['reddit.com', 'amazon.com', 'twitter.com', 'linkedin.com', 'ebay.com', 'netflix.com', 'google.com', 'stackoverflow.com', 'github.com', 'quora.com']

players = {1: {'player_name': 'cynthia', 'time_played': 30.9, 'player_pokemon': {}, 'gyms_visited': []}, 2: {'player_name': 'teri', 'time_played': 22.2, 'player_pokemon': {}, 'gyms_visited': ['alcatraz', 'pacific_beach']}}

for loc in locations:
   for player in players.keys():
    if player["gyms_visited"] != loc[""]:
        print (loc, player)

Body:
There are some problems here:

loc is an element of the locations list, so a string, you cannot call [""] on a string; and

player is an element from the key set of the dictionary. So it does not contain a "gyms_visited" list.

You should iterate over the .values() of the dictionary, and omit the [""] acces on the loc:

for loc in locations:
   for player in players.values():
    if player["gyms_visited"] != loc: # no [""]
        print (loc, player)

In case you want to print the player key instead of the dictionary, you can iterate over the .items() of the dictionary:

for loc in locations:
   for player_id,player in players.items():
    if player["gyms_visited"] != loc:
        print (loc, player_id)

Now the gyms_visited of a player is a list. And a list is never equal to a string. So that can never happen. If you look however whether the loc is in the list of gyms_visited, you can use:

for loc in locations:
   for player_id,player in players.items():
    if loc in player["gyms_visited"]:
        print (loc, player_id)


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
If you have a collection and you kow upfront you're going to systematically pass through all values, use foreach as it is usually easier to work with the "current" instance.

If some condition can make you stop iterating, you can use for or while. They are pretty similar, the big difference being that for takes control of when the current index or value is updated (in the for declaration) as in a while you decide when and where in the while block to update some values that are then checked in the while predicate.

Title: When to use each type of loop?


问:
PolyUtil.containsLocation doesn't work as expected
I've made a simple test:

```<code>LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.659365, 17.656366));
pts.add(new LatLng(52.525305, 19.303601));

LatLngBounds bounds = new LatLngBounds(pts.get(2), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);
</code>```

Here is how it works:

I created a particular point (city), which I want to test if it is inside a polygon,

I declared a polygon as 4 points and bounds as 2 points (northeast
and southwest).

Output is:

```<code>contains1: false
contains2: true
</code>```

Why PolyUtil.containsLocation returns false? What am I missing here? It's a simple thing, you can test these points on google maps.

PolyUtil is a class from android maps utils provided by Google: 'com.google.maps.android:android-maps-utils:0.5'

答:
You should define the vertices of the polygon in correct order. Let's explain with screenshots, because the picture is worth of thousand words. Currently you have the following vertices for polygon

If you try to draw the polygon for the array list from your example you will see the following polygon.

As you can see, indeed the city is outside of the polygon and the PolyUtil gives correct result. In the same time you define bounds correctly with southwest and northeast vertices, so the city is inside the bounds. To fix the issue you should swap points 3 and 4 in your example.

```<code>LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.525305, 19.303601));
pts.add(new LatLng(52.659365, 17.656366));

bounds = new LatLngBounds(pts.get(3), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);
</code>```

You can find sample project that I used to create screenshots at https://github.com/xomena-so/so44523611

I hope this helps!

Body:
I've made a simple test:

LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.659365, 17.656366));
pts.add(new LatLng(52.525305, 19.303601));

LatLngBounds bounds = new LatLngBounds(pts.get(2), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);

Here is how it works:

I created a particular point (city), which I want to test if it is inside a polygon,

I declared a polygon as 4 points and bounds as 2 points (northeast
and southwest).

Output is:

contains1: false
contains2: true

Why PolyUtil.containsLocation returns false? What am I missing here? It's a simple thing, you can test these points on google maps.

PolyUtil is a class from android maps utils provided by Google: 'com.google.maps.android:android-maps-utils:0.5'

Body:
You should define the vertices of the polygon in correct order. Let's explain with screenshots, because the picture is worth of thousand words. Currently you have the following vertices for polygon

If you try to draw the polygon for the array list from your example you will see the following polygon.

As you can see, indeed the city is outside of the polygon and the PolyUtil gives correct result. In the same time you define bounds correctly with southwest and northeast vertices, so the city is inside the bounds. To fix the issue you should swap points 3 and 4 in your example.

LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.525305, 19.303601));
pts.add(new LatLng(52.659365, 17.656366));

bounds = new LatLngBounds(pts.get(3), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);

You can find sample project that I used to create screenshots at https://github.com/xomena-so/so44523611

I hope this helps!


问:
with which programming language social networks like facebook , or forums can be written?
I wanna make a social network with some new ideas . I wonder with which programming languages , social networks , or forums can be written?
thanks .</p>

答: Anything which can be written in one Turing-complete language can also be written in every other Turing-complete language. Since the vast majority of what we think of as "programming languages" are Turing-complete, this means that they can be written in pretty much any programming language.</p>


问:
Hide a container and show another
I have a container and three elements inside it. I need to hide .short-post, show .long-post and modify the parent width.

.container, .short-post, .read-more
{
    display: block;
}

.long-post
{
    display: none;
}

.read-more:active > .short-post
{
    display: none;
}

.read-more:active > .long-post
{
    display: block;
}

.read-more:active > .container
{
    /*Previous width = 623px*/
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="short-post">
    something
    </div>
    <div class="long-post">
    something bigger
    </div>
    <span class="read-more">
    READ MORE
    </span>
</div></code>```

I know I can't use the selector > but I can't find one that fits my code, I'm reading all references here W3Schools CSS Selectors and testing them all. Is there a way to do what I want with CSS? I know that it's possible with JavaScript.

答:
only with css Read more button just refer this

html { background: white }

* {
    margin: 0;
    padding: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}

body {
    max-width: 480px;
    width: 90%;
    margin: 3em auto;
    font-size: 75%;
    line-height: 1.3rem;
    font-family: sans-serif;
    position: relative;
    *zoom: 1;
}

body:before, body:after {
    content: "";
    display: table;
}

body:after { clear: both }

p { margin-bottom: 1.3rem }

.container {
    margin-bottom: 3rem;
    position: relative;
    *zoom: 1;
}

.container:before, .container:after {
    content: "";
    display: table;
}

.container:after { clear: both }

.container figure {
    float: right;
    width: 32.5%;
}

.container .short-post {
    float: left;
    width: 62.5%;
}

.container .long-post {
    display: none;
    visibility: hidden;
}

div {
    -webkit-transition: 1s linear;
    -moz-transition: .125s linear;
    -ms-transition: .125s linear;
    -o-transition: .125s linear;
    transition: 1s linear;
}

input[type=checkbox] {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    width: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
}

[for="read_more"] {
    position: absolute;
    bottom: -3rem;
    left: 0;
    width: 100%;
    text-align: center;
    padding: .65rem;
    box-shadow: inset 1px 1px rgba(0, 0, 0, 0.1), inset -1px -1px rgba(0, 0, 0, 0.1);
}

[for="read_more"]:hover {
    background: rgba(0,0,0,.5);
    color: rgb(255,255,255);
}

[for="read_more"] span:last-of-type {
    display: none;
    visibility: hidden;
}

input[type=checkbox]:checked ~ .short-post, input[type=checkbox]:checked ~ .long-post {
    display: block;
    visibility: visible;
    width: 100%;
}

input[type=checkbox]:checked ~ figure { width: 100% }

input[type=checkbox]:checked ~ [for="read_more"] span:first-of-type {
    display: none;
    visibility: hidden;
}

input[type=checkbox]:checked ~ [for="read_more"] span:last-of-type {
    display: block;
    visibility: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<input type="checkbox" id="read_more" role="button">
    <label for="read_more" onclick=""><span>Read More</span><span>Less</span></label>
    <div class="short-post">
      <p>Owls are a group of birds that belong to the order Strigiformes, constituting 200 extant bird of prey species. Most are solitary and nocturnal, with some exceptions (e.g. the Northern Hawk Owl). </p>
    </div>

<div class="long-post">
    <p>Owls hunt mostly small mammals, insects, and other birds, although a few species specialize in hunting fish. They are found in all regions of the Earth except Antarctica, most of Greenland and some remote islands. Though owls are typically solitary, the literary collective noun for a group of owls is a parliament. Owls are characterized by their small beaks and wide faces, and are divided into two families: the typical owls, Strigidae; and the barn-owls, Tytonidae.</p>
    <p>Owls have large forward-facing eyes and ear-holes; a hawk-like beak; a flat face; and usually a conspicuous circle of feathers, a facial disc, around each eye. The feathers making up this disc can be adjusted in order to sharply focus sounds that come from varying distances onto the owls' asymmetrically placed ear cavities. Most birds of prey sport eyes on the sides of their heads, but the stereoscopic nature of the owl's forward-facing eyes permits the greater sense of depth perception necessary for low-light hunting. Although owls have binocular vision, their large eyes are fixed in their sockets — as are those of other birds — so they must turn their entire head to change views. Owls can rotate their heads and necks as much as 270 degrees in either direction. As owls are farsighted, they are unable to see clearly anything within a few centimeters of their eyes. Caught prey can be felt by owls with the use of filoplumes — like feathers on the beak and feet that act as "feelers". Their far vision, particularly in low light, is exceptionally good.</p>
</div>

</div></code>```

Title: Hide a container and show another

Body:
I have a container and three elements inside it. I need to hide .short-post, show .long-post and modify the parent width.

.container, .short-post, .read-more
{
    display: block;
}

.long-post
{
    display: none;
}

.read-more:active > .short-post
{
    display: none;
}

.read-more:active > .long-post
{
    display: block;
}

.read-more:active > .container
{
    /*Previous width = 623px*/
    width: 100%;
}

    something

    something bigger

    READ MORE

I know I can't use the selector > but I can't find one that fits my code, I'm reading all references here W3Schools CSS Selectors and testing them all. Is there a way to do what I want with CSS? I know that it's possible with JavaScript.

Body:
only with css Read more button just refer this

html { background: white }

* {
    margin: 0;
    padding: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}

body {
    max-width: 480px;
    width: 90%;
    margin: 3em auto;
    font-size: 75%;
    line-height: 1.3rem;
    font-family: sans-serif;
    position: relative;
    *zoom: 1;
}

body:before, body:after {
    content: "";
    display: table;
}

body:after { clear: both }

p { margin-bottom: 1.3rem }

.container {
    margin-bottom: 3rem;
    position: relative;
    *zoom: 1;
}

.container:before, .container:after {
    content: "";
    display: table;
}

.container:after { clear: both }

.container figure {
    float: right;
    width: 32.5%;
}

.container .short-post {
    float: left;
    width: 62.5%;
}

.container .long-post {
    display: none;
    visibility: hidden;
}

div {
    -webkit-transition: 1s linear;
    -moz-transition: .125s linear;
    -ms-transition: .125s linear;
    -o-transition: .125s linear;
    transition: 1s linear;
}

input[type=checkbox] {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    width: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
}

[for="read_more"] {
    position: absolute;
    bottom: -3rem;
    left: 0;
    width: 100%;
    text-align: center;
    padding: .65rem;
    box-shadow: inset 1px 1px rgba(0, 0, 0, 0.1), inset -1px -1px rgba(0, 0, 0, 0.1);
}

[for="read_more"]:hover {
    background: rgba(0,0,0,.5);
    color: rgb(255,255,255);
}

[for="read_more"] span:last-of-type {
    display: none;
    visibility: hidden;
}

input[type=checkbox]:checked ~ .short-post, input[type=checkbox]:checked ~ .long-post {
    display: block;
    visibility: visible;
    width: 100%;
}

input[type=checkbox]:checked ~ figure { width: 100% }

input[type=checkbox]:checked ~ [for="read_more"] span:first-of-type {
    display: none;
    visibility: hidden;
}

input[type=checkbox]:checked ~ [for="read_more"] span:last-of-type {
    display: block;
    visibility: visible;
}

<div class="container">
<input type="checkbox" id="read_more" role="button">
    <label for="read_more" onclick=""><span>Read More</span><span>Less</span></label>
    <div class="short-post">
      <p>Owls are a group of birds that belong to the order Strigiformes, constituting 200 extant bird of prey species. Most are solitary and nocturnal, with some exceptions (e.g. the Northern Hawk Owl). </p>
    </div>

<div class="long-post">
    <p>Owls hunt mostly small mammals, insects, and other birds, although a few species specialize in hunting fish. They are found in all regions of the Earth except Antarctica, most of Greenland and some remote islands. Though owls are typically solitary, the literary collective noun for a group of owls is a parliament. Owls are characterized by their small beaks and wide faces, and are divided into two families: the typical owls, Strigidae; and the barn-owls, Tytonidae.</p>
    <p>Owls have large forward-facing eyes and ear-holes; a hawk-like beak; a flat face; and usually a conspicuous circle of feathers, a facial disc, around each eye. The feathers making up this disc can be adjusted in order to sharply focus sounds that come from varying distances onto the owls' asymmetrically placed ear cavities. Most birds of prey sport eyes on the sides of their heads, but the stereoscopic nature of the owl's forward-facing eyes permits the greater sense of depth perception necessary for low-light hunting. Although owls have binocular vision, their large eyes are fixed in their sockets — as are those of other birds — so they must turn their entire head to change views. Owls can rotate their heads and necks as much as 270 degrees in either direction. As owls are farsighted, they are unable to see clearly anything within a few centimeters of their eyes. Caught prey can be felt by owls with the use of filoplumes — like feathers on the beak and feet that act as "feelers". Their far vision, particularly in low light, is exceptionally good.</p>
</div>

</div>


问:
JavaAgent on Java 9
Prior to java 9, the monitoring JavaAgent were loaded into the JVM by boostrapClassloader so that the monitored applications could access them

With Java 9 modular architecture, only java.base module gets loaded in Bootstrap classloader and so, Java agent can access only classes inside java.base?
It can't access anything outside java.base by default?

What is required to be changed inside javaAgent in order to access other modules like java.sql?

答:
I just validated this for the latest build and when using

```<code>Instrumentation::appendToBootstrapClassLoaderSearch
</code>```

The class is added to the bootstrap loader (null) and loaded into the unnamed module of this loader. This is true for Java 9, ea-176.

Title: JavaAgent on Java 9

Body:
I just validated this for the latest build and when using

Instrumentation::appendToBootstrapClassLoaderSearch

The class is added to the bootstrap loader (null) and loaded into the unnamed module of this loader. This is true for Java 9, ea-176.


问:
CSS 404 Node.JS
I have been trying for a long time to make the CSS file load. I have looked at other stackoverflow  questions and no luck. I have the express.static statements. I have the "standard" file order. It seems that I am doing something very very obvious wrong.</p>

```<code>    <html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <nav>
            <ul>
                <li class="inline"><a class="inline" target="_blank" href="http://instagram.com/blakskyben/?hl=en">My Insta</a></li>
                <li class="inline"><a class="inline" href="/about">About Me</a></li>
                <li class="inline"><a class="inline" href="/">Blogs</a></li>
            </ul>
        </nav>
___________________________________________________________________________
    var express = require("express"),
        app = express(),
        bodyParser = require("body-parser"),
        mongoose = require("mongoose");

    mongoose.connect("mongodb://localhost/blog");

    var blogSchema = new mongoose.Schema({
         title: String,
         content: String
    });

    app.use(express.static("public"));
    app.use(express.static("partials"));

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());

    app.get("/",function(req,res){
        res.redirect("/blogs");
    });

    app.get("/blogs",function(req,res){
        blog.find({},function(err,foundBlogs){
            if(foundBlogs){
                res.render("blogs.ejs",{blogs: foundBlogs});
            } else {
                res.send("Sorry, an error occured retriving the blogs, " + err);
            }
        });
    });

    app.get("/blogs/:id",function(req,res){
        blog.findById(req.params.id,function(err,foundBlog){
            if(foundBlog){
                res.render("show.ejs",{blog: foundBlog});
            } else {
                res.send("Sorry, but there was an error, " + err);
            }
        });
    });

    app.get("/about",function(req,res){
        res.render("about.ejs");
    });

    var blog = mongoose.model("blog",blogSchema);

    //Seed the DB!

    blog.create({
        title: "Camp",
        content: "Blah."
    });

    app.listen(8080);
</code>```

答:
Try adding the css path from application's root direcotry i.e

```<code><link rel="stylesheet" href="/style.css">
</code>```

or if your CSS file is inside a folder, then

```<code><link rel="stylesheet" href="/folderName/style.css">
</code>```

whichever applicable for you.

Title: CSS 404 Node.JS

Body:
I have been trying for a long time to make the CSS file load. I have looked at other stackoverflow  questions and no luck. I have the express.static statements. I have the "standard" file order. It seems that I am doing something very very obvious wrong.

        <link rel="stylesheet" href="style.css">

My Insta

About Me

Blogs

___________________________________________________________________________
    var express = require("express"),
        app = express(),
        bodyParser = require("body-parser"),
        mongoose = require("mongoose");

    mongoose.connect("mongodb://localhost/blog");

    var blogSchema = new mongoose.Schema({
         title: String,
         content: String
    });

    app.use(express.static("public"));
    app.use(express.static("partials"));

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());

    app.get("/",function(req,res){
        res.redirect("/blogs");
    });

    app.get("/blogs",function(req,res){
        blog.find({},function(err,foundBlogs){
            if(foundBlogs){
                res.render("blogs.ejs",{blogs: foundBlogs});
            } else {
                res.send("Sorry, an error occured retriving the blogs, " + err);
            }
        });
    });

    app.get("/blogs/:id",function(req,res){
        blog.findById(req.params.id,function(err,foundBlog){
            if(foundBlog){
                res.render("show.ejs",{blog: foundBlog});
            } else {
                res.send("Sorry, but there was an error, " + err);
            }
        });
    });

    app.get("/about",function(req,res){
        res.render("about.ejs");
    });

    var blog = mongoose.model("blog",blogSchema);

    //Seed the DB!

    blog.create({
        title: "Camp",
        content: "Blah."
    });

    app.listen(8080);

Body:
Try adding the css path from application's root direcotry i.e

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

or if your CSS file is inside a folder, then

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

whichever applicable for you.


问:
Ifelse temperature modelling
I am building a model in R and I have a data frame of daily temperature data in Kelvin (CSV file). I will run the model individually for each station. The literature I am basing the model off of states: when the temperature rises above 285.15, spawning is induced and ER is reduced to 0, meaning my graphical output should fall to zero and start climbing again after the temperature decreases. My question is this: How would I write this command into R? Thus far I have written:

```<code>spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, ER-ER, 0)
</code>```

I have also tried:

```<code>if(temperature > 285.15) {ER-ER}
</code>```

My parameters look like this:

```<code>param <- list(Temperature = Mussel_Daily_Temp$AS_TEMP, etc....)
</code>```

Any help would be most appreciated!

答:
you are on the right path:</p>

```<code>ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)
</code>```

Title: Ifelse temperature modelling

Body:
I am building a model in R and I have a data frame of daily temperature data in Kelvin (CSV file). I will run the model individually for each station. The literature I am basing the model off of states: when the temperature rises above 285.15, spawning is induced and ER is reduced to 0, meaning my graphical output should fall to zero and start climbing again after the temperature decreases. My question is this: How would I write this command into R? Thus far I have written:

spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, ER-ER, 0)

I have also tried:

if(temperature > 285.15) {ER-ER}

My parameters look like this:

param <- list(Temperature = Mussel_Daily_Temp$AS_TEMP, etc....)

Any help would be most appreciated!

Body:
you are on the right path:

ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)


问:
Trying to find column index via range name in VBA
I am currently working on this spreadsheet and am running into massive difficulties. Essentially, I am trying to find the column index number that contains the range name "Average".

So, if "Average" is in column index 22, then 22 will be returned, etc.

```<code>Range("AA1").Select
Selection.Name = "Average"

Dim colNumber As Integer

colNumber = WorksheetFunction.Match("Average", ActiveWorkbook.Sheets(Sheet1).Range("1, Average"), 0)  'Average is a range name

Columns(colNumber).Insert
</code>```

Each time I get different errors for this line, ranging from type mismatch to global_ failure:

colNumber = WorksheetFunction.Match("Average", ActiveWorkbook.Sheets(Sheet1).Range("1, Average"), 0)

I've searched everywhere looking for how to find a column index number based on a range name within a range, and I can't find anything. Any help is hugely appreciated.

Thank you!

答:
You are re-defining the range name by these lines of code:

```<code>Range("AA1").Select
Selection.Name = "Average"
</code>```

In the remaining code you seem to just look for a text string "Average" in cell-content.

To get the column of the top-left corner of a range name named "Average" you would need:

```<code>Dim lCol As Long
lCol = ThisWorkbook.Names("Average").ReferstoRange.Cells(1,1).Column
</code>```

Body:
I am currently working on this spreadsheet and am running into massive difficulties. Essentially, I am trying to find the column index number that contains the range name "Average".

So, if "Average" is in column index 22, then 22 will be returned, etc.

Range("AA1").Select
Selection.Name = "Average"

Dim colNumber As Integer

colNumber = WorksheetFunction.Match("Average", ActiveWorkbook.Sheets(Sheet1).Range("1, Average"), 0)  'Average is a range name

Columns(colNumber).Insert

Each time I get different errors for this line, ranging from type mismatch to global_ failure:

colNumber = WorksheetFunction.Match("Average", ActiveWorkbook.Sheets(Sheet1).Range("1, Average"), 0)

I've searched everywhere looking for how to find a column index number based on a range name within a range, and I can't find anything. Any help is hugely appreciated.

Thank you!

Body:
You are re-defining the range name by these lines of code:

Range("AA1").Select
Selection.Name = "Average"

In the remaining code you seem to just look for a text string "Average" in cell-content.

To get the column of the top-left corner of a range name named "Average" you would need:

Dim lCol As Long
lCol = ThisWorkbook.Names("Average").ReferstoRange.Cells(1,1).Column


问:
redux-thunk dispatch does not work
I have a problem with thunk and async dispatching. So here is my code:

```<code>function fetchProvider() {
  return (dispatch) => {
    graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

class Dashboard extends React.Component {
  componentDidMount() {
    this.props.fetchProvider();
  }

  render() {
    const { provider } = this.props;

    return (
      <div>
        <ul>
          <li>id: {provider.id}</li>
          <li>name: {provider.name}</li>
          <li>description: {provider.description}</li>
        </ul>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  provider: state.provider,
});

const mapDispatchToProps = (dispatch) => ({
  fetchProvider: () => dispatch(fetchProvider()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
</code>```

I don't know why but dispatch inside fetchProvider action creator does not work. graphqlService works well and in moment of dispatching FETCH_PROVIDER action data passed to dispatch is correct but then something goes wrong and reducers doesn't called with this action. What possibly could cause this problem?

答: Finally I found the problem. It was caused by incorrect initialization of react-router-redux middleware. I passed middleware constructor to applyMiddleware instead of constructed middleware.</p>

Title: redux-thunk dispatch does not work

Body:
I have a problem with thunk and async dispatching. So here is my code:

function fetchProvider() {
  return (dispatch) => {
    graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

class Dashboard extends React.Component {
  componentDidMount() {
    this.props.fetchProvider();
  }

  render() {
    const { provider } = this.props;

    return (

id: {provider.id}

name: {provider.name}

description: {provider.description}

    );
  }
}

const mapStateToProps = (state) => ({
  provider: state.provider,
});

const mapDispatchToProps = (dispatch) => ({
  fetchProvider: () => dispatch(fetchProvider()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

I don't know why but dispatch inside fetchProvider action creator does not work. graphqlService works well and in moment of dispatching FETCH_PROVIDER action data passed to dispatch is correct but then something goes wrong and reducers doesn't called with this action. What possibly could cause this problem?


问:
How to override a bundle in OroCrm
I am trying (unsuccessfully) to override a specific class of a bundle.
The class I'd like to override is:

Oro\Bundle\MagentoBundle\Entity\Repository\CustomerRepository

To do so, I created my bundle

```<code>namespace Kiwee\Bundle\MnhBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MnhMagentoBundle extends Bundle {

    public function getParent() {
        return 'OroMagentoBundle';
    }
}
</code>```

And I added the bundles.yml

```<code>bundles:
    - Kiwee\Bundle\MnhBundle\MnhMagentoBundle
</code>```

So far, so good.. the bundle is loaded.
Now, it seems I can't find any working example about how to override the class mentioned above.

I tried creating a file with the same relative path as the class I'd like to override, but it doesn't work.

```<code>namespace Kiwee\Bundle\MnhBundle\Entity\Repository;

use Oro\Bundle\MagentoBundle\Entity\Repository\CustomerRepository as BaseCustomerRepository;

class CustomerRepository extends BaseCustomerRepository
{
    public function calculateLifetimeValue(Customer $customer)
    {
        // [... here is my custom logic for this method ...]

    }
}
</code>```

The first problem I have is that "Customer" is not the same type as in the original class.
The second is that, even fixing it by declaring the full class path, this method is never used while the original is.
Any hint?

Thank you very much

答:
Just override it as a regular doctrine repository.
See this answer https://stackoverflow.com/a/37486268/2119164 it should resolve your issue.</p>

Title: How to override a bundle in OroCrm

Body:
I am trying (unsuccessfully) to override a specific class of a bundle.
The class I'd like to override is:

Oro\Bundle\MagentoBundle\Entity\Repository\CustomerRepository

To do so, I created my bundle

namespace Kiwee\Bundle\MnhBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MnhMagentoBundle extends Bundle {

    public function getParent() {
        return 'OroMagentoBundle';
    }
}

And I added the bundles.yml

bundles:
    - Kiwee\Bundle\MnhBundle\MnhMagentoBundle

So far, so good.. the bundle is loaded.
Now, it seems I can't find any working example about how to override the class mentioned above.

I tried creating a file with the same relative path as the class I'd like to override, but it doesn't work.

namespace Kiwee\Bundle\MnhBundle\Entity\Repository;

use Oro\Bundle\MagentoBundle\Entity\Repository\CustomerRepository as BaseCustomerRepository;

class CustomerRepository extends BaseCustomerRepository
{
    public function calculateLifetimeValue(Customer $customer)
    {
        // [... here is my custom logic for this method ...]

    }
}

The first problem I have is that "Customer" is not the same type as in the original class.
The second is that, even fixing it by declaring the full class path, this method is never used while the original is.
Any hint?

Thank you very much


问:
Java Casting to superclass not change object type?
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

```<code>interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}
</code>```

答:
Though you cast Owl to Nocturnal still the Owl object contains the its methods. And that's why its printing false -

```<code>Nocturnal nocturnal = (Nocturnal) new Owl();
</code>```

The casting here just make the newly created Owl object compatible for Nocturnal references - "nocturnal"

So when you call the method of isBlind() you are actually calling the isBlind() of Owl object which is just referenced by (or stored in) nocturnal of type Nocturnal. Here we say dynamic polymorphic is happen.

Body:
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}

Body:
Though you cast Owl to Nocturnal still the Owl object contains the its methods. And that's why its printing false -

Nocturnal nocturnal = (Nocturnal) new Owl();

The casting here just make the newly created Owl object compatible for Nocturnal references - "nocturnal"

So when you call the method of isBlind() you are actually calling the isBlind() of Owl object which is just referenced by (or stored in) nocturnal of type Nocturnal. Here we say dynamic polymorphic is happen.


问:
Regex to extract specific field with other constraints
I have to create a Regex which extract specific field from large log file. I have created one but its not perfect as different type of occurane present in logs.

I have attached screenshot. There are 2 different type of log entry and I want to extract real="value".

The problem is, multiple "real=value" present in extracted line and I want to get only first occurance. +

My Regex:

```<code>CMS-concurrent-abortable-preclean:\s.*real=(?P<cms_abortable_preclean>\d+\.\d+)\s
</code>```

Screen Shot: Sample data and Regex command

Sample Data:

2017-05-16T13:21:47.420+0200: 5.114: [GC (Allocation Failure)
  2017-05-16T13:21:47.420+0200: 5.114:
  [ParNew2017-05-16T13:21:47.461+0200: 5.155:
  [CMS-concurrent-abortable-preclean: 0.120/0.735 secs] [Times:
  user=1.17 sys=0.12, real=0.73 secs] : 886080K->110720K(996800K),
  0.3158400 secs] 886080K->161751K(6180736K), 0.3168208 secs] [Times: user=0.33 sys=0.10, real=0.32 secs]

1.583: [CMS-concurrent-abortable-preclean: 0.052/0.171 secs] [Times: user=0.20 sys=0.01, real=0.17 secs]  CMS: abort preclean due to time
  8077.162: [CMS-concurrent-abortable-preclean: 4.850/5.566 secs] [Times: user=5.92 sys=0.02, real=5.57 secs]

I want to extract fields in bold.

答:
You could use a regex like this:

```<code>^.*?Times.*?real=(\d+(?:\.\d+))
</code>```

Working demo

The idea is to capture the first real belonging to Times for each line

Body:
I have to create a Regex which extract specific field from large log file. I have created one but its not perfect as different type of occurane present in logs.

I have attached screenshot. There are 2 different type of log entry and I want to extract real="value".

The problem is, multiple "real=value" present in extracted line and I want to get only first occurance. +

My Regex:

CMS-concurrent-abortable-preclean:\s.*real=(?P<cms_abortable_preclean>\d+\.\d+)\s

Screen Shot: Sample data and Regex command

Sample Data:

2017-05-16T13:21:47.420+0200: 5.114: [GC (Allocation Failure)
  2017-05-16T13:21:47.420+0200: 5.114:
  [ParNew2017-05-16T13:21:47.461+0200: 5.155:
  [CMS-concurrent-abortable-preclean: 0.120/0.735 secs] [Times:
  user=1.17 sys=0.12, real=0.73 secs] : 886080K->110720K(996800K),
  0.3158400 secs] 886080K->161751K(6180736K), 0.3168208 secs] [Times: user=0.33 sys=0.10, real=0.32 secs]

1.583: [CMS-concurrent-abortable-preclean: 0.052/0.171 secs] [Times: user=0.20 sys=0.01, real=0.17 secs]  CMS: abort preclean due to time
  8077.162: [CMS-concurrent-abortable-preclean: 4.850/5.566 secs] [Times: user=5.92 sys=0.02, real=5.57 secs]

I want to extract fields in bold.

Body:
You could use a regex like this:

^.*?Times.*?real=(\d+(?:\.\d+))

Working demo

The idea is to capture the first real belonging to Times for each line


问:
Python: split array into variables
I have a function that returns a list. The length of this list is unknown to the caller.

```<code>def get_array():
    ret = [1, 2]
    return ret

var1, var2 = get_array()
</code>```

This sets var1 = 1 and var2 = 2. This works fine with all lists except when the length is less than 2. For example, if the list has length of 1:

```<code> def get_array():
    ret = [1]
    return ret

 var1 = get_array()
</code>```

This sets var1 to [1], but I want var1 to be 1. Is there a cleaner way to unpack this array without having to check its length?

答:
Sure, if the size of the resulting list is known, use the same notation:</p>

```<code>var1, = [1]  # var1 is set to 1
</code>```

Title: Python: split array into variables

Body:
I have a function that returns a list. The length of this list is unknown to the caller.

def get_array():
    ret = [1, 2]
    return ret

var1, var2 = get_array()

This sets var1 = 1 and var2 = 2. This works fine with all lists except when the length is less than 2. For example, if the list has length of 1:

 def get_array():
    ret = [1]
    return ret

 var1 = get_array()

This sets var1 to [1], but I want var1 to be 1. Is there a cleaner way to unpack this array without having to check its length?

Body:
Sure, if the size of the resulting list is known, use the same notation:

var1, = [1]  # var1 is set to 1


问:
Counting the same column with different where conditions
I have a table called employees, whose schema looks like the following:

```<code>mysql> desc employees;
+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no     | int(11)       | NO   | PRI | NULL    |       |
| birth_date | date          | NO   |     | NULL    |       |
| first_name | varchar(14)   | NO   |     | NULL    |       |
| last_name  | varchar(16)   | NO   |     | NULL    |       |
| gender     | enum('M','F') | NO   |     | NULL    |       |
| hire_date  | date          | NO   |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+
</code>```

I just want to query the count of emp_no for Males (where generder = 'M') and females (where generder = 'F').

I want the results like:

```<code>+--------+--------+
| Male   | FeMale |
+--------+--------+
| 300    | 120    |
+--------+--------+
</code>```

Any suggestion on how to do that in a single query?

答:
```<code>SELECT SUM(gender = 'M') AS Male, SUM(gender = 'F') AS Female
FROM employees
</code>```

Body:
I have a table called employees, whose schema looks like the following:

mysql> desc employees;
+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no     | int(11)       | NO   | PRI | NULL    |       |
| birth_date | date          | NO   |     | NULL    |       |
| first_name | varchar(14)   | NO   |     | NULL    |       |
| last_name  | varchar(16)   | NO   |     | NULL    |       |
| gender     | enum('M','F') | NO   |     | NULL    |       |
| hire_date  | date          | NO   |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+

I just want to query the count of emp_no for Males (where generder = 'M') and females (where generder = 'F').

I want the results like:

+--------+--------+
| Male   | FeMale |
+--------+--------+
| 300    | 120    |
+--------+--------+

Any suggestion on how to do that in a single query?


答:
If you're using python3, you can use the splatted unpacking syntax to help you out here:

```<code>In [113]: a,*b = [1]

In [114]: a
Out[114]: 1

In [115]: b
Out[115]: []
</code>```

Basically, this lets you unpack get_array()[1:] into b, which will be empty, if get_array() returns a list of size 1

Title: Python: split array into variables

Body:
If you're using python3, you can use the splatted unpacking syntax to help you out here:

In [113]: a,*b = [1]

In [114]: a
Out[114]: 1

In [115]: b
Out[115]: []

Basically, this lets you unpack get_array()[1:] into b, which will be empty, if get_array() returns a list of size 1


问:
Example of presenceGroup used in apiRTC.init
In the documentation it is indicated that presenceGroup and subscribeToPresenceGroup can be set in the apiRTCinit.  They are json parameters, but what exactly is the format?  What do they each do, they sound redundant, so I am not clear.</p>

答:
Here is a sample of apiRTC.init() :

```<code>//apiRTC init
apiRTC.init({
    apiKey : "myDemoApiKey",
    //apiCCId : "229",
    onReady : sessionReadyHandler,
    userData : {
        "lastName": "lastName",
        "firstName": "firstName"
    },
    presenceGroup : ["agent"],
    subscribeToPresenceGroup : ["visitor", "agent"]
});
</code>```

presenceGroup : define the groups of the user : user will be considered as present in these groups

subscribeToPresenceGroup : define the presence group to which the user has subscribed : user will receive the presence information for these groups.

In our sample : user is connected to group "agent", but will receive presence information for group "visitor" and group "agent"

Body:
Here is a sample of apiRTC.init() :

//apiRTC init
apiRTC.init({
    apiKey : "myDemoApiKey",
    //apiCCId : "229",
    onReady : sessionReadyHandler,
    userData : {
        "lastName": "lastName",
        "firstName": "firstName"
    },
    presenceGroup : ["agent"],
    subscribeToPresenceGroup : ["visitor", "agent"]
});

presenceGroup : define the groups of the user : user will be considered as present in these groups

subscribeToPresenceGroup : define the presence group to which the user has subscribed : user will receive the presence information for these groups.

In our sample : user is connected to group "agent", but will receive presence information for group "visitor" and group "agent"