text:
Q: Swift NStatusBarItem, make button support drag&drop I know there are a bunch of questions similar to this, but they are all very outdated, basically I have a statusBarItem and I want to make it responsive to dragging and dropping files, here is some of the code I've tried:
extension NSStatusBarButton {
    open override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
        true
    }

    open override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        print("dragging entered")
        return .copy
    }

    open override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        print("Something was dragged!")
        return true
    }

    open override func draggingEnded(_ sender: NSDraggingInfo) {
        print("Draging ended")
    }
}

class DragAndDropButton: NSStatusBarButton {

    open override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
        true
    }

    open override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        print("dragging entered")
        return .copy
    }

    open override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        print("Something was dragged!")
        return true
    }

    open override func draggingEnded(_ sender: NSDraggingInfo) {
        print("Draging ended")
    }
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    var popover: NSPopover!
    var statusBarItem: NSStatusItem!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
        // Add `@Environment(\.managedObjectContext)` in the views that will need the context.
        let popoverView = PopoverView()

        popover = NSPopover()

        popover.contentSize = NSSize(width: AppConstants.popoverWidth, height: AppConstants.popoverHeight)
        popover.animates = true
        popover.behavior = .transient
        popover.contentViewController = NSHostingController(rootView: popoverView)

        statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))

        let dropSubview = DragAndDropButton()
        dropSubview.registerForDraggedTypes([.png])
        dropSubview.image = NSImage(named: "CognitionSmall")

        statusBarItem.button = drop
//        statusBarItem.view = dropSubview
//        statusBarItem.title = "Test"

        if let button = self.statusBarItem.button {
//            button.view

//            button.registerForDraggedTypes([.multipleTextSelection])
            button.addSubview(dropSubview)
            button.imagePosition = NSControl.ImagePosition.imageLeft
            button.image = NSImage(named: "CognitionSmall")
            button.action = #selector(togglePopover(_:))
//            button.window!.delegate = self
//            button.addSubview(cognitoSubview)
//            button.performDragOperation = #selector(onDrag(_:))
        }
    }

as you can see I've tried to extend and override the default NSStatusBarButton behavior as well as replacing it with my own NSView and adding a subview to the button, but nothing seems to work, does anybody have an idea of how to make this work?

A: This works on my system using CommandLine (haven't tried it in Xcode)
import Cocoa

class CustomView:NSView {

var filePaths : [String] = []

override init(frame frameRect: NSRect) {
 super.init(frame:frameRect)
 self.registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
}

required init?(coder  aDecoder : NSCoder) {
 super.init(coder: aDecoder)
}

override func draw(_ rect: NSRect) {
 super.draw(rect)
 let bkgrnd = NSBezierPath(rect:rect)
 NSColor.red.set()
 bkgrnd.fill()
 NSColor.black.set()
let str = String("DND")
let font = NSFont.init(name: "Menlo", size:14.0)
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let attrText = NSAttributedString(string:str, attributes: [.paragraphStyle: style, .font:font!])
attrText.draw(in: rect)
}

override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
 print("draggingEntered")
 return .copy
}

override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
 print("draggingUpdated")
 return .copy
}

override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let board = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray
var draggedFilePath : String
draggedFilePath = board![0]  as! String
print("draggedFilePath = \(draggedFilePath)")
return true
}

}

// **** main.swift **** //
let app = NSApplication.shared
app.setActivationPolicy(NSApplication.ActivationPolicy.regular)
let statusItem = NSStatusBar.system.statusItem(withLength: 100)
var view : CustomView!
view = CustomView(frame:NSMakeRect(0, 0, 100, 40))
statusItem.button?.addSubview(view)
app.run()

A: Turns out the extension I did to the NSStatusBarButton was fine, with the exception that I did not test it properly, if you declare more registered types it works just fine:
extension NSStatusBarButton {
    open override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
        true
    }

    open override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        print("dragging entered")
        return .copy
    }

    open override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        print("Something was dragged!")
        return true
    }

    open override func draggingEnded(_ sender: NSDraggingInfo) {
        print("Draging ended")
    }
}

... more initialization code

button.registerForDraggedTypes([.fileURL, .multipleTextSelection, .png])

A: @Oscar - I revised your original post and can confirm that the following code will add drag and drop capability to an NSStatusBarButton by using an extension and that it obviates the need for an NSView subview. Thanks.
import Cocoa

extension NSStatusBarButton {
 open override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
 true
}

 open override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
 print("Dragging entered.")
 return .copy
}

 open override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
 print("Something was dragged!")
 return true
}

 open override func draggingEnded(_ sender: NSDraggingInfo) {
 print("Dragging ended.")
}
}

class AppDelegate: NSObject, NSApplicationDelegate {
 var window: NSWindow!
 var statusItem: NSStatusItem!

func applicationDidFinishLaunching(_ aNotification: Notification) {
 statusItem = NSStatusBar.system.statusItem(withLength: 100)
 statusItem.button!.title = "DND Test"
 statusItem.button!.registerForDraggedTypes([.fileURL])
}
}
let appDelegate = AppDelegate()

// **** main.swift **** //
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = appDelegate
app.activate(ignoringOtherApps:true)
app.run()

If the file is saved as statusItem.swift it may be run from Terminal using:
swiftc statusItem.swift -framework Cocoa -o statusItem && ./statusItem


text:
Q: How do cookies work when browsing websites On websites where you have to enter a user name and password, I notice that I can browse the site with one browser and it will know who I am no matter where I go on the site.  But if I open a different browser it doesn't know who I am in that browser unless I log on in that browser.
After I log in to a website, does it store some kind of cookie in my browser, and every time I navigate to a different page on that site, it checks the cookie for my identity?
What would happen if I logged in, and then before browsing to a different page on the site, deleted the cookie?

A: This is more of a "teach a man to fish" answer, so I apologise if it's not what you were after. But if you take my advice you will learn lots, so please trust me :)
There's a number of tools that you can use to track exactly what http traffic is going between your browser and the server. One is called Firebug, a plugin for Firefox. The other kind of tool is called a "web debugging proxy". There's charles, which is very powerful, and fiddler, which is free.

What you want to do with any of these tools is use a website, and then look at the raw request. This shows you exactly what your browser is saying to the server. You'll see the cookies for that server are sent along with every request. What's cool about these tools is that you can edit a request just before it's sent, so you can test how the servers respond...

A:
After I log in to a website, does it store some kind of cookie in my browser, and every time I navigate to a different page on that site, it checks the cookie for my identity?

Yes. The cookie is sent with each HTTP request.

What would happen if I logged in, and then before browsing to a different page on the site, deleted the cookie?

The same as if you were to switch browsers.

A: Every time when you navigate a new page, your browser  sends a request to the server and the server sends back you the response. Your request contains the cookies, which the server can parse and use. You if you delete the cookie, your browser can't send it with the next request.

A:
What would happen if I logged in, and then before browsing to a different page on the site, deleted the cookie?

You would no longer be logged in.

After I log in to a website, does it store some kind of cookie in my browser, and every time I navigate to a different page on that site, it checks the cookie for my identity?

Yes. Most likely, you are dealing with a "session-cookie". These cookies do not store any information themselves, but use a long string to identify yourself to a server. I would suggest doing some research on cookies. As for the (I'm guessing assumed) question of "Why cookies work on different pages?" is because cookies are tied to the domain, and not the exact URI.
Cookies contain names, values, and expirations (along with a few others). The most common you'll see are sessions, which use an identifier to load a session-state from the server containing your information. These are the safest cookies as everything is centralized and not as prone to hijacking. The other kind is a regular cookie, which has a limited size and stores information client-side. Anything that has to do with shopping or anything that tracks users most likely uses sessions, while something like a customizable javascript-y page probably uses a normal cookie. The former tracks information server-side for additional security, while the latter poses no security risk, and leaves the information for the client to manage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counts number of rows with like in SQL Server I have a SQL Server database. I want to count number of rows where the id starts from 1112 .
(id is string and its format in data base is nchar(7))
I have 20 rows that start from 1112 like 1112000, 1112001, 1112002,....
But when I write this query returns 0!.
SELECT COUNT(*) AS num
FROM table
WHERE (id LIKE '1112*')

A: You should use % instead of *.
SELECT        COUNT(*) AS num
FROM           table
WHERE        (id LIKE '1112%')

LIKE (Transact-SQL)

A: try % instead of *
"id LIKE '1112%')


text:
Q: How to pass values to array then loop through a data set I'm trying to build a loop to sum 200 consecutive rows (or a number of rows determined from an input box) from Column E, then move the range down one cell and recalculate (loop) until it has gone through all the used cells in the named worksheet.
the length/size of the Array is static for the purposes of the loop, it is requested from the user via an inputbox and is to remain the same until the loop is completed.
So far I have completed the calculation once using static cell references eg. "E2:E201" shown below:
ClosingPrice200Array = Range("E2:E201").Value

So i know the code can calculate the Sum of the range and divide by a variable.
The problems I'm having include:

*

*I want to sum the next 200 consecutive rows from E3:E202, then E4:E203 etc all the way down to the last used row without naming every change of range.

To do this I have declared row variables, confirmed I have counted the correct number of rows and attempted to pass the first range (E2:E201) to the named array using row variables however I am getting a "Compile error: Can't assign to Array" from my code:
Sub Calculate200DMA()

    Dim Dma200current As Double
    Dim SumLast200Days As Long
    Dim MovingAverageLength As Integer
    MovingAverageLength = Application.InputBox("Input Required", "Moving Average Length", 200, , , , , 1)
    Dim ClosingPrice200Array(MovingAverageLength) as Variant

'can't remember if an array size needs to be a constant but I can create other array variables to cater for that in need, so please advise if I cannot dynamically adjust the Array size each time it runs the macro.
Dim FirstRow As Integer
Dim Lastrow As Integer
Dim CurrentRow As Integer
Dim NumberOfRows As Long

'count number of rows to be used in the For loop
Sheets("Data processing").Select
NumberOfRows = ActiveSheet.UsedRange.Rows.Count

FirstRow = 2
CurrentRow = FirstRow + (MovingAverageLength - 1)
Lastrow = CurrentRow

'this is the row causing the compile error:
ClosingPrice200Array = Sheets("Data processing").Range(Cells(FirstRow, 5), Cells(Lastrow, 5)).Value

'the rest seems to work correctly in terms of calculating the number i want:
SumLast200Days = Excel.WorksheetFunction.Sum(ClosingPrice200Array)
Dma200current = SumLast200Days / MovingAverageLength
Sheets("Data processing").Cells(CurrentRow, 10).Value = Dma200current

'then i want to increment to the For loop but i have not written the start nor end loop yet because not sure exactly how to write (have been googling how to populate the array first)
FirstRow = FirstRow + 1
Lastrow = Lastrow + 1
CurrentRow = CurrentRow + 1

*Also the input box is not appearing to prompt input of the length (number of rows) for the range. This is my code for the input box:
Dim MovingAverageLength As Integer
MovingAverageLength = Application.InputBox("Input Required", "MovingAverageLength", 200, , , , , 1)
Thank you in advance for helping. Could not find exactly something which solved the problem in my google searches (here or elsewhere) so far.
John

A: You need to qualify all your objects to your worksheet when setting the range for your array.
So replace this line:
ClosingPrice200Array = Sheets("Data processing").Range(Cells(FirstRow, 5), Cells(Lastrow, 5)).Value

With
With Worksheets("Data processing")
    ClosingPrice200Array = .Range(.Cells(firstRow, 5), .Cells(lastRow, 5)).Value
End With

Also, ensure that you are declaring your array as type Variant as stated by Tim William's comment.

Editing in response to OP's question:

can you please advise why you used the with instead?

You are never required to use a With...End With statement. This statement simply makes your code more readable and also can save some keystrokes.
If you didn't use the with statement, you would have had to type out your Worksheets("Data processing") three times in that line:

*

*Worksheets("Data processing").Range()

*Worksheets("Data processing").Cells(firstRow, 5)

*Worksheets("Data processing").Cells(lastRow, 5)

This would make it less readable with this being the outcome:
ClosingPrice200Array = Worksheets("Data processing").Range(Worksheets("Data processing").Cells(firstRow, 5), Worksheets("Data processing").Cells(lastRow, 5)).Value

While the above works, it just makes sense not to type out Worksheets("Data processing") three times, but instead use the with statement.
The reason your code wasn't working is that you only qualified your Range() object to the worksheet, but not the Cells() objects within your Range(), which meant you were using the active sheet instead.
You can qualify objects inside a with statement by using placing a period . in front of the child objects.
Here's another example of using a With statement:
With Worksheets("Sheet1")
    .Range("A1") = "Blah"
    .Cells(1, 1) = "Blah"
    .Range("F:F").Clear
End With

If you didn't use the with statement, you would have had to type the worksheet out three times:
Worksheets("Sheet1").Range("A1") = "Blah"
Worksheets("Sheet1").Cells(1, 1) = "Blah"
Worksheets("Sheet1").Range("F:F").Clear

So again, it's optional but useful. You just needed to qualify both of your Cells() objects to the worksheet.

A: you can directly use WorksheetFunction.Average() function and work with ranges:
Option Explicit

Sub Calculate200DMA()
    Dim MovingAverageLength As Long, LastRow As Long
    MovingAverageLength = Application.InputBox("Input Required", "Moving Average Length", 200, , , , , 1)

    Dim FirstRow As Long, CurrentRowOffset As Long, LastRowOffset As Long

    FirstRow = 2
    With Sheets("Data processing")
        LastRow = .Cells(.Rows.Count, 4).End(xlUp).Row
        LastRowOffset = (LastRow - FirstRow + 1) - MovingAverageLength ' set the last offset from first row
        With .Cells(FirstRow, 4).Resize(MovingAverageLength) ' reference the first range to sum
            For CurrentRowOffset = 0 To LastRowOffset
                .Cells(.Rows.Count).Offset(CurrentRowOffset, 6).Value = WorksheetFunction.Average(.Offset(CurrentRowOffset))
            Next
        End With
    End With
End Sub


text:
Q: SSRS slow then Error I Create Chart Report using SSRS report and use this report in MS CRM
My report About Summary in parameter section when run user can choose report display summary per day / month / year or quater
Then report work correctly when a little rows but when I choose display per day and choose date range between 2014-01-01 and 2015-03-23 report run too long and then I get this error
Then I run Query in Sql server management studio It's run 00:00:00 sec and return 1814 rows
Here is my Query
DECLARE @paramSdate AS DATE = (SELECT CAST('2014-01-01' AS DATE))
DECLARE @paramNdate AS DATE = (SELECT CAST('2015-03-23' AS DATE))
DECLARE @sdate AS DATE
    ,@edate AS DATE
SET @sdate = @paramSdate
SET @edate = @paramNdate

CREATE TABLE #tmp (x DATE,link INT)

WHILE @sdate <= @edate
BEGIN
    INSERT INTO #tmp VALUES(@sdate,1)
    SET @sdate = DATEADD(DAY,1,@sdate)
END

SELECT  FORMAT(t.x,'dd/MM/yyyy','TH-th') AS [x]
    ,h.name
    ,ISNULL(cc.cnt,0) AS [cnt]
FROM #tmp t
LEFT JOIN (
    SELECT 2 AS [type] , 'New Visit' AS [name] ,1 AS [link]
    UNION
    SELECT 3 AS [type] , 'Re-Visit' AS [name] ,1 AS [link]
    UNION
    SELECT 4 AS [type] , 'Book' AS [name] ,1 AS [link]
    UNION
    SELECT 5 AS [type] , 'Total' AS [name] , 1 AS [link]
) h ON t.link = h.link
LEFT JOIN (
        SELECT COUNT(*) AS [cnt]
     ,CAST(v.new_contactdate AS DATE) AS [d]
            ,v.new_type
        FROM [SCASSET_MSCRM].[dbo].[new_VisitHistory] v with(nolock)
        WHERE v.new_type IN (2)
        AND v.new_projectid IN ('CB2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D42115AC-633F-E411-80DD-F01FAFE5E7C0'
,'DE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'B92115AC-633F-E411-80DD-F01FAFE5E7C0'
,'032215AC-633F-E411-80DD-F01FAFE5E7C0'
,'EE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EF2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'F02115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D32115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BD2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BA2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D82115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EB2115AC-633F-E411-80DD-F01FAFE5E7C0')
        AND CAST(v.new_contactdate AS DATE) BETWEEN @paramSdate AND @paramNdate
        GROUP BY v.new_type
     ,CAST(v.new_contactdate AS DATE)
        UNION
        SELECT COUNT(*) AS [cnt]
     ,CAST(v.new_contactdate AS DATE) AS [d]
            ,'3' AS [new_type]
        FROM [SCASSET_MSCRM].[dbo].[new_VisitHistory] v with(nolock)
        WHERE v.new_type IN (3,4)
        AND v.new_projectid IN ('CB2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D42115AC-633F-E411-80DD-F01FAFE5E7C0'
,'DE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'B92115AC-633F-E411-80DD-F01FAFE5E7C0'
,'032215AC-633F-E411-80DD-F01FAFE5E7C0'
,'EE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EF2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'F02115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D32115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BD2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BA2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D82115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EB2115AC-633F-E411-80DD-F01FAFE5E7C0')
        AND CAST(v.new_contactdate AS DATE) BETWEEN @paramSdate AND @paramNdate
        GROUP BY v.new_type
     ,CAST(v.new_contactdate AS DATE)
        UNION
        SELECT COUNT(*) AS [cnt]
     ,CAST(s.new_reservationdate AS DATE) AS [d]
            ,'4' AS [new_type]
        FROM [SCAsset_MSCRM].[dbo].[new_salehistory] s with(nolock)
        WHERE s.new_projectId IN ('CB2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D42115AC-633F-E411-80DD-F01FAFE5E7C0'
,'DE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'B92115AC-633F-E411-80DD-F01FAFE5E7C0'
,'032215AC-633F-E411-80DD-F01FAFE5E7C0'
,'EE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EF2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'F02115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D32115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BD2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BA2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D82115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EB2115AC-633F-E411-80DD-F01FAFE5E7C0')
        AND CAST(s.new_reservationdate AS DATE) BETWEEN @paramSdate AND @paramNdate
        GROUP BY
     CAST(s.new_reservationdate AS DATE)
        UNION
        SELECT COUNT(*) AS [cnt]
     ,CAST(v.new_contactdate AS DATE) AS [d]
            ,'5' AS [new_type]
        FROM [SCAsset_MSCRM].[dbo].[new_VisitHistory] v with(nolock)
        WHERE v.new_projectId IN ('CB2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D42115AC-633F-E411-80DD-F01FAFE5E7C0'
,'DE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'B92115AC-633F-E411-80DD-F01FAFE5E7C0'
,'032215AC-633F-E411-80DD-F01FAFE5E7C0'
,'EE2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EF2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'F02115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D32115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BD2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'BA2115AC-633F-E411-80DD-F01FAFE5E7C0'
,'D82115AC-633F-E411-80DD-F01FAFE5E7C0'
,'EB2115AC-633F-E411-80DD-F01FAFE5E7C0')
        AND v.new_type IN (2,3,4)
        AND CAST(v.new_contactdate AS DATE) BETWEEN @paramSdate AND @paramNdate
        GROUP BY
 CAST(v.new_contactdate AS DATE)
) cc ON cc.new_type = h.[type]
 AND CAST(cc.d AS DATE) = CAST(t.x AS DATE)
ORDER BY t.x

OPTION(RECOMPILE)

DROP TABLE #tmp

here is my data set and report design
Thank you.

A: This is probably an issue with too many records and your report and/or database timing out. I believe this to be the case because the report runs when you limit the data set to just a few records.
I would check this resource for more help in fixing this issue.what is the default timeout processing option in SSRS Server


text:
Q: How can I fix this Ruby syntax error concerning the end keyword? This is from a problem on Exercism. Making every solution so far a class method seems like an odd way of going about things but it's not my idea. Anyway here is the code:
class ResistorColorDuo
  @@colors = %w(
    black
    brown
    red
    orange
    yellow
    green
    blue
    violet
    grey
    white)

  def self.value(array)
    @@colors.index array[0] * 10 + @@colors.index array[1]
  end
end

The error message:
Traceback (most recent call last):
    1: from resistor_color_duo_test.rb:2:in `<main>'
resistor_color_duo_test.rb:2:in `require_relative': /home/muhammad/exercism/ruby/resistor-color-duo/resistor_color_duo.rb:15: syntax error, unexpected tIDENTIFIER, expecting keyword_end (SyntaxError)
...0]) * 10 + @@colors.index array[1]

I don't see the problem because the end keywords are all properly balanced. How should I go about fixing this?

A:
I was under the impression that parentheses were optional in this instance.

Yes and no. Parentheses are indeed optional, but that doesn't mean that not using them won't change the behavior of your code, just that you won't get a syntax error.
If Ruby encounters a space immediately after a method, it will parse the rest of the line as its argument(s). So, parentheses are optional if you don't have anything on the line that isn't a part of the method argument. If you do, you have to specify what part of the line constitutes your argument list, by enclosing it in parentheses.
Here's a related potential problem to be aware of. Consider these lines, which differ by only a single space:
f(3+2)+1
f (3+2)+1

The first of these passes 5 to the function f and adds 1 to the result. The second one passes 6 to the function f. For the same reason: if Ruby encounters a space immediately after a method call, the rest of the line is parsed as the argument list.
I borrowed that example from Matz's book, where he eloquently calls this a "pernicious whitespace dependency." You have to be careful with spaces on method call lines.
This is the cause, also, of the error that you're getting. Ruby can't parse your line because you have two method calls in it. So the second one causes the error: Ruby is expecting the end keyword and instead it's encountering another method call.
Adding parentheses to the second one gets rid of the syntax error:
@@colors.index array[0] * 10 + @@colors.index(array[1])

But it probably doesn't give you the result you want. It will parse it like this:
@@colors.index(array[0] * 10 + @@colors.index(array[1]))

So, use parentheses for both of them. I'm not sure what you're trying to do (not sure what you want to multiply by 10), but something like this:
@@colors.index(array[0]) * 10 + @@colors.index(array[1])

In general, I prefer to parenthesize arguments to method calls. Pretty much the only time I don't use them is with puts, print and p (edit: and all those other ones I forgot about that Jörg has added in the comments below).
And be careful not to put a space between the method call and the open paren.

A: An addition to @dinjas answer from the comment section
If you have two arrays:
colors = [1,10]
array = [1]

And do something like in your example:
colors.index array[0] * 10

you will get #=> 1 which the index of the second element of the colors array which is 10. That is because Ruby will first calculate array[0] * 10 (which is 1 * 10 = 10) and then check for  the index of the first element that equals 10 in the colors array.
If you, however, add parenthesis and do this:
 colors.index(array[0]) * 10

you will get #=> 0 because the index of the first element that equals 1 (array[0] = 1) in the colors array is 0 and 0 * 10 = 0.
There was also a similar issue a few days ago, you might want to check it out here.


text:
Q: how to confirm dates are valid in google big query I have a Birthdate field that has YYYY-MM-DD in it.
I'm using the below statement:
select
  farm_fingerprint(cast(P.Key as string)) as person_id
  , EXTRACT(YEAR from P.BirthDate) as year_of_birth
  , EXTRACT(MONTH from P.BirthDate) as month_of_birth
  , EXTRACT(DAY from P.BirthDate) as day_of_birth
  , DATETIME(TIMESTAMP (CONCAT(CAST(P.BirthDate as string), ' 00:00:00')))
  , P.Birthdate
from person P;

my question is about the BirthDate Field.  How do I ensure that this is a valid date prior to conversion?
If the value is bad, EXTRACT() will fail.  Does COALESCE() work on failed functions? if not, how do I compensate and set null?
Thanks

A: We had similar kind of requirement where we filter out invalid records using SAFE_CAST()
select * from invalid_date_fix_test
WHERE
SAFE_CAST(dt_date AS TIMESTAMP) is not null and
timestamp(dt_date) > TIMESTAMP_SUB(TIMESTAMP_TRUNC('2019-03-24 00:37:35', DAY),INTERVAL 3 DAY)

A: Hi faced the data format issue since data was coming from multiple countries and in their local formats mm/dd/yyyy vs dd/mm/yyyy which I dealt with as below. hope it helps or gives a direction.
case when departureDate is null  or departureDate = '' then null
     when cast(substr(departureDate,1,2) as int64) > 12 then
     cast(parse_date('%d/%m/%Y',departureDate) as datetime)
   else cast(parse_date('%m/%d/%Y',departureDate) as datetime) end as departureDate


text:
Q: Using LIMIT 1 in MySQL When is it appropriate to add LIMIT 1 at the end of the query in MySQL. I normally add it in DELETE but I've seen it being used with INSERT a and even UPDATE. Is it an overkill or a good practice?

A:  INSERT INTO .. VALUES () LIMIT 1

Doesn't exist. Hopefully you know how many VALUES() you put in there!
 INSERT INTO .. SELECT ... LIMIT 1

Does exist and is pretty useful, and off topic since the LIMIT is on the SELECT.
 DELETE ... LIMIT 1
 UPDATE ... LIMIT 1

Extremely rarely useful. Either you know your database enough to be certain that your WHERE matches a UNIQUE condition, or you don't, in which case you should spend a little more time looking at your database and learning SQL.
But ...
 UPDATE jobs SET owner=me WHERE owner IS NULL ORDER BY job_submit_time LIMIT 1

Can be extremely useful! This makes a near-lockless job queue, where you can come and take a job from the queue without any waiting, locking, or conflict resolution. Quite excellent.
 DELETE FROM cache ORDER BY last_update_time LIMIT N

Cache takes too much space ? Purge the N oldest rows...

A: Well, if you use EXPLAIN you'll see that it speeds things up, as once it's found one result, it stops.
It's also a failsafe – if you know your insert of update should only ever affect one row, by specifying it, you are guaranteeing that it won't ever go wrong and mess up multiple rows.

A: I can't think of an instance where something that speeds up a query and makes it more secure at the same time could be called overkill.  I'll put my vote in the good practice column.

A:
Extremely rarely useful. Either you know your database enough to be certain > that your WHERE matches a UNIQUE condition, or you don't, in which case you > should spend a little more time looking at your database and learning SQL

There are instances where a limit 1 is REALLY useful.  For example, a table without a unique key.  If we have five of the exact same, then limit one will work.

A: Assume you are writing Forgot Password code (in PHP):
UPDATE
    `users`
SET
    `pass` = PASSWORD('{$new_salted_pass}')
WHERE
    `account_id` = '{$account_id}'
LIMIT 1

If your software is a Software as a Service (SaaS),
and multiple organizations use your software,
and account_id-organization_id fields together are a unique id,
and the account_id is auto-generated in the code like so:
JONES0001
JONES0002
JONES0003
...
and the software engineer forgets to add AND organization_id = '{$organization_id}' to the query's WHERE condition,
and the code passes QA when testing the Forgot Password functionality in QA environment,
and the code is then pushed to production,
then the LIMIT 1 can limit the damage done when two organizations' user's share the same account_id.


text:
Q: git pull terminal allow everyone We have a staging server and at the moment, when I go to the server in the terminal and perform a git pull, everything works fine. When my colleague tries it, he's asked for my password. How can I change this so that everyone is able to perform a pull on that server and not just me?

A: use ssh.

create your very own keypair like this
then add the public key to your bitbucket account
replace your remote link with the respective ssh one
using git pull will now no longer ask for a password

A: try this code by write it in terminal

git config receive.denyCurrentBranch ignore


text:
Q: LINQ to XML - VB.NET to c# have the following in my project, written in VB.NET:
 Dim items = From item In rssFeed.Elements("forecast").Elements("tabular").Elements("time") _
                    Select New WetherItem With {.time=item.Element("windDirection").Attribute("code").Value }

How is this written in C #?
I have tried the following ...
XElement rssFeed = XElement.Load(@"http://www.yr.no/sted/Norge/Rogaland/Karm%C3%B8y/Torvastad/varsel.xml");
var items = from item in rssFeed.Elements("forecast").Elements("tabular").Elements("time")
select new WetherItem { .time=item.Element("windDirection").Attribute("code").Value };

But I get the error message from

rssFeed.Elements("forecast").Elements("tabular").Elements("time")
Error 5   Could not find an implementation of the query pattern for
  source type
  'System.Collections.Generic.IEnumerable'.
  'Select' not found.  Are you missing a reference or a using directive
  for 'System.Linq'?    c:\users\\documents\visual studio
  2012\Projects\Database1\Database1\SqlStoredProcedure1.cs  32  30  Database1

I have reference to System.XML.Linq and System.Data.Linq

A: In the C# code file on top you will see the using statements, in there add:
using System.Linq;
using System.Xml.Linq;

Also remove . from .time in your select statement, if the property name is time

A: Remember to add using statements at the top of the file, and your query in c#:
var items = from item in rssFeed.Elements("forecast".Elements("tablular").Elements("time")
            select new WetherItem {
                           time = item.Element("windDirection").Attribute("code").Value
                       };

A: This is a very unusual problem, that even i faced while working on a app, because neither VS clearly specifies what the problem is nor there are proper ans to this problem. One ans, I think may be is :-
Add another reference to your project :-
using System.Linq; apart from using System.Xml.Linq;
using System.Linq;
using System.Xml.Linq;

The errors might go & the project will build.

For more help reference this article :-
problem with using refrence to System.Xml.Linq


text:
Q: Blackberry vertical scrolling for side by side vertical managers I have to built this UI for Blackberry JRE 4.6 & above.
Please suggest the approach for this UI.

A: I solved the problem, here is the approach,

*

*Take horizontal manager for header
HorizontalFieldManager nonscrollableHFM= new HorizontalFieldManager();

*Take another horizontal manager as a container
HorizontalFieldManager containerHfm = new HorizontalFieldManager();
2.1 Add vertical manager for left section (Non Scrollable)
VerticalFieldManager leftVfm = new VerticalFieldManager();
2.2 Create a custom vertical manager for right section as below
{
   class RightVfm extends VerticalFieldManager {

  RightVfm() {

    super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR | NO_HORIZONTAL_SCROLL
    | NO_HORIZONTAL_SCROLLBAR | USE_ALL_WIDTH);

      }

  protected void sublayout(int width, int height) {

      super.sublayout(width, getPreferredHeight());

      setExtent(width, getPreferredHeight());

  }

  public int getPreferredWidth() {

     return _width;

  }

public void setWidth(int w) {

            _width = w;

        }

public int getPreferredHeight() {

            return _height;

        }

public void setHeight(int h) {

            _height = h;

        }

    private int _width;
    private int _height;

};

}

*

*Adjust the height & width of right verticle manager by calling setHeight & setWidth   methods
I got help from here,
http://www.blackberryforums.com/developer-forum/209190-set-height-verticalfieldmanager.html


text:
Q: Smart Table Client Side Pagination Not Working: Apex I've followed the examples on Smart Table to a 'T'.  I'm unable to get Client Side pagination working.  The data is loading asynchronously, hence the st-safe-src.
The main issue is that the page length is not reducing to the defined length and none of the buttons are displaying.  There are zero errors in the console.
<apex:page standardController="Account" extensions="RegulationOCheckController">

    <apex:stylesheet value="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />

    <apex:includescript value="//code.angularjs.org/1.3.1/angular.js" />
    <apex:includescript value="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js" />
    <apex:includescript value="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js" />
    <apex:includescript value="//cdnjs.cloudflare.com/ajax/libs/angular-smart-table/2.1.8/smart-table.min.js" />

    <apex:pageBlock >

                            Insider Name
                            % Similarity

                                <input st-search="accountName" placeholder="search for insider" class="input-sm form-control" type="search" />

                            {{ row.accountName }}
                            {{ row.similarity }}

    </apex:pageBlock>

</apex:page>

A: Your problem lies inside the DataService factory, you get your data using a deferred constructor instead of utilizing a proper $http call.
You should replace this mess
funcs.regulationOCheck = function(){

            var deferred = $q.defer()

            RegulationOCheckController.compare(
                '{!$CurrentPage.parameters.id}',
                function(result, event){
                    $rootScope.$apply(function(){
                        if(event.statusCode >= 200 || event.statusCode < 300){
                            deferred.resolve(JSON.parse(result))
                        }else{
                            deferred.reject(event)
                        }
                    })
                },
                { escape: false }
            )
            return deferred.promise
        }

With something along the lines of
funcs.regulationOCheck = function(){

            RegulationOCheckController.compare(
                '{!$CurrentPage.parameters.id}',
                function(result, event){
                    $rootScope.$apply(function(){
                        if(event.statusCode >= 200 || event.statusCode < 300){
                            return $q.when(JSON.parse(result))
                        }else{
                            return $q.reject(event)
                        }
                    })
                },
                { escape: false }
            )
        }

or even $http
funcs.regulationOCheck = function() {
    return $http.get("data.json");
}

And avoid using $rootScope.$apply, it will call a digest cycle for all the application and it's totally not necessary for your scenario
Here is a plunker demo


text:
Q: Javascript redirect on prompt input in same window I have been using a javascript prompt to generate reports on a website.  You click on the link, which brings up a javascript prompt.  You type in the code for the report you want and it generates that report.
So, for example, if you wanted report "ABC123", when the prompt appears, you would type ABC123 and it would open "http://example.com/reports/ABC123"
The code for this is below:

function getReport(){
               var reportcode = prompt("Report Code : ", "xxx000");
               window.open("http://example.com/reports/"+reportcode,"_blank");
               return true;
            }

This works perfectly in terms of opening reports to print.  But I have tried to change the code to redirect to a web version of the report that opens in the same window, rather than opening a new window.
I thought that changing "_blank" to "_self" would achieve this.  But if I use "_self" or "_top" or "_parent", rather than opening the report in the same window, it simply reloads the original content of the window.
In other words, if I have the original page of "http://example.com/reports_index", rather than loading "http://exmaple.com/reports/ABC123", it simply reloads "http://example.com/reports_index".
I can't work out why it works for "_blank" but not for "_self"
Any ideas very much appreciated!

A: You can use this for opening in the same window.
window.location.href = "https://example.com/reports/"+reportcode


text:
Q: When you come back / when do you come back / when are you coming back? I'm confused about the right way to ask this question:

When you come back to London?
  When do you come back to London?
  When are you coming back to London?

Which one should I use?

A: If your sentence is in the Future Tense then the correct option is: "When are you coming back to London?"

A: Disclaimer: this answer doesn't address tense correctness.
The first,

When you come back to London

is usually followed by another phrase, such as an action to be performed upon return.

When you come back to London don't forget to visit.

The second,

When do you come back to London?

is suitable if the person is definitely coming back to London, and you want to know exactly when. This is the most certain and direct way to ask.
The third:

When are you coming back to London?

is somewhat less certain (or more polite) than the second, as if the person may not actually come back, but is very close in meaning to the second.
It may come off sounding more like:

Are you coming back to London?

The third could also be used with a sarcastic implication that the person has been gone for a long time or (somewhat jokingly) might not come back.

Are you ever coming back to London?

Context is important.


text:
Q: A combinatorial number theory proof How can I prove the following identity:
$$\sum_{k=1}^{n}{\sigma_{\ 0} (k^2)}  = \sum_{k=1}^{n}{\left\lfloor \frac{n}{k}\right\rfloor \ 2^{\omega(k)}}$$
where $\omega(k)$ is the number of distinct prime divisors of $k$.

A: Here is a very big clue:
$$[k|m]=\left\lfloor\frac{m}{k}\right\rfloor-\left\lfloor\frac{m-1}{k}\right\rfloor=\begin{cases}1 && k|m \\ 0 && \text{otherwise}.\end{cases}$$
Consider induction...

 Applying the forward difference operator to our equation and shifting back,  $$\sigma_0(n^2)=\sum_{d|n}2^{\omega(d)}$$ is what we need to prove first for a workable induction proof on the original claim. This can be done, since both sides are multiplicative functions (note $\omega(ab)=\omega(a)+\omega(b)$ when $a,b$ are coprime), and on prime powers $n=p^r$, $$\sum_{d|n}2^{\omega(d)}=1+\sum_{l=1}^r 2^1=2r+1,$$ which agrees with $\sigma_0(p^{2r})$.

(Wish I could see a more bijective proof though. Drats.)


text:
Q: In RStudio, how to print tibble in quarto/rmarkdown chunk as in console? When editing quarto/rmarkdown documents, I would like RStudio to display inline tibbles the same way as it does in the console, instead of the paginated default printing.
Instead of this:

I would much prefer the output from the console:
# A tibble: 150 × 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1          5.1         3.5          1.4         0.2 setosa
 2          4.9         3            1.4         0.2 setosa
 3          4.7         3.2          1.3         0.2 setosa
 4          4.6         3.1          1.5         0.2 setosa
 5          5           3.6          1.4         0.2 setosa
 6          5.4         3.9          1.7         0.4 setosa
 7          4.6         3.4          1.4         0.3 setosa
 8          5           3.4          1.5         0.2 setosa
 9          4.4         2.9          1.4         0.2 setosa
10          4.9         3.1          1.5         0.1 setosa
# … with 140 more rows
# ℹ Use `print(n = ...)` to see more rows

I have tried setting #| results: asis and changing the df-print option in the yaml, but that only affects the rendered document. I could make RStudio show chunk output in the console instead, but I would prefer if i could keep it inline.

A: I like the answer above, as you have more control over individual chunks. Just to add 2 cents here: in case you want a general solution, you can add it to the head section like this:
---
format: html
editor_options:
  chunk_output_type: console
---

as seen in this answer here in Stackoverflow.

A: This is an addition to @Quinten's answer. I did some digging and found that RStudio overwrites some printing methods by default, which the option paged.print changes. These are: print.data.frame, print.tbl_df, print.paged_df, print.grouped_df, print.rowwise_df, print.tbl_sql, print.data.table, and print.tbl_lazy (source code). There are several ways in which you can pass the option to RStudio: as a chunk option (as in @Quinten's answer), as a knitr chunk option (knitr::opts_chunk$set(paged.print = FALSE)) and as an R option. You could hence apply this to the whole document with:
```{r setup, include=FALSE}
options(paged.print = FALSE)
```

If you want to make this permanent between sessions, you could put it in your .Rprofile with usethis::edit_r_profile().
In case you want to customise the default printing, there are also the pillar_options, which control tibble printing (see ?pillar::pillar_options). For example:
```{r setup, include=FALSE}
options(paged.print = FALSE,
        pillar.print_max = 25,
        pillar.print_min = 25)
```

Or you overwrite the print method again with whatever you like ;)
```{r setup, include=FALSE}
print.tbl_df <- function(x, ...) print(knitr::include_graphics("https://jeroen.github.io/images/frink.png"))
```

Again, you could put all of this in your .Rprofile. However, that would also affect rendered output, which is probably not what you want. Instead, you could only run this in interactive sessions:
if (interactive()) {
  print.data.fram <- print.grouped_df <- print.tbl_df <- function(x, ...) print(knitr::include_graphics("https://jeroen.github.io/images/frink.png"))
}

Use this with caution, because it could really confuse somebody who has this secretly put into their .Rprofile ;)

A: You could use the option paged.print=FALSE in your chunk which will turn of paged tables like this:
---
format: html
---

```{r paged.print=FALSE}
library(tibble)
as_tibble(iris)
```

Which outputs this in chunk:
# A tibble: 150 × 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1          5.1         3.5          1.4         0.2 setosa
 2          4.9         3            1.4         0.2 setosa
 3          4.7         3.2          1.3         0.2 setosa
 4          4.6         3.1          1.5         0.2 setosa
 5          5           3.6          1.4         0.2 setosa
 6          5.4         3.9          1.7         0.4 setosa
 7          4.6         3.4          1.4         0.3 setosa
 8          5           3.4          1.5         0.2 setosa
 9          4.4         2.9          1.4         0.2 setosa
10          4.9         3.1          1.5         0.1 setosa
# … with 140 more rows
# ℹ Use `print(n = ...)` to see more rows

Check this document for more information and options in chunks.


text:
Q: How do I prevent Maven from downloading maven-metadata.xml for an artifact that I already have in my repo? I'm using Maven 3.2.  I have this dependency in my pom.xml file (a WAR project)
            <dependency>
                    <groupId>joda-time</groupId>
                    <artifactId>joda-time</artifactId>
                    <version>1.6.2</version>
                    <scope>provided</scope>
            </dependency>

Whenever I run any phase for my pom (e.g. "mvn install"), the app always attempts to download some metadata about the dependency …
Downloading: http://repo.spring.io/milestone/joda-time/joda-time/maven-metadata.xml

How do I tell Maven to stop doing that?  I already have the artifact cached in my local Maven repo.
Thanks, - Dave

A: Maybe the update policies need to be specified explicitly. See this answer: Why is Maven downloading the maven-metadata.xml every time?
<pluginRepositories>
<pluginRepository>
    <id>central</id>
    <url>http://gotoNexus</url>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>daily</updatePolicy>
    </snapshots>
    <releases>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
    </releases>
</pluginRepository>

A: This means that somewhere in your dependency tree either a SNAPSHOT or a version-range is used (direct or as transitive dependency). For both cases the solution is the same: lock the version to a specific release. Did you lock it as direct dependency or within dependencyManagement?


text:
Q: What is parent frame of R What is parent frame of R. By the way way, what does parent frame mean? I guess it's the defining environment instead of calling environment since R uses lexical scoping, but I am not sure. Thanks.

A: Well, from the ?parent.frame help page

The parent frame of a function evaluation is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current evaluation, nor is it the environment within which the function was defined. sys.parent returns the number of the parent frame if n is 1 (the default), the grandparent if n is 2, and so on

and also

Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. So internal functions (which may or may not set contexts and so may or may not appear on the call stack) may not be counted, and S3 methods can also do surprising things.

So the parent.frame refers to the environment where the function was called from, not where it was defined.
For example
parentls <- function() {
  ls(envir=parent.frame())
}

a<-function() {
    x <- 5
    parentls()
}

b <- function() {
    z <- 10
    parentls()
 }

a()
# [1] "x"
b()
# [1] "z"
parentls()
# [1] "a"        "b"        "parentls"

Here, parentls() does an ls() in the parent.frame. And when run from within a() or b() we only see the variables within those functions. When called by itself, it simply gives you all the variables in your global environment just as if you called ls() by itself.
You can read more about parent frames in the Closure section or Calling Environment section of Hadely's Advanced R.


text:
Q: Concatinating properties in a list of items I am having trouble with a small section of code.
I have a List of a MapItem class with a couple properties, Address and Html, and I need to concatenate the Html properties for each item with an identical Address property
For example:
firstMapItem = new MapItem { Address = "1122 Elm Street",
                             Html="
some html
" };
secondMapItem = new MapItem { Address = "1122 Elm Street",
                              Html="
different html
" };

would become:
firstMapItem.Address == "1122 Elm Street";
firstMapItem.Html == "
some html

different html
";

secondMapItem.Address == "1122 Elm Street";
secondMapItem.Html == "
some html

different html
";

This is what I have tried so far:
            foreach (MapItem item in mapItems)
            {
                var sameAddress = from m in mapItems
                                  where m.Address == item.Address
                                  select m;

                if (sameAddress.Count() > 1)
                {
                    //tried inserting -> item.Html = ""; right here as well
                    foreach (MapItem single in sameAddress)
                    {
                        item.Html += single.Html;
                    }
                }
            }

I am probably making this more complicated than it needs to be.
Thanks in advance.

A: You could group by Address and then concatenate the Html values:
var results = from m in mapItems
              group m by m.Address into ms
              select new MapItem
              {
                  Address = ms.Key,
                  Html = string.Concat(ms.Select(m => m.Html))
              };

A: Use a grouping on the address, then just string.Join the Html of all the items in the group to produce a new MapItem:
var resultList = mapItems.GroupBy(m => m.Address)
                         .Select(g => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) })
                         .ToList();

Edit:
Like the other solutions presented so far above approach will remove duplicates - that doesn't seem to be what you want - below a solution that creates a list that is not deduplicated (so will produce 2 items for the sample input)
var resultList = mapItems.GroupBy(m => m.Address)
                         .Select(g => g.Select( item => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) } ))
                         .SelectMany( x=> x)
                         .ToList();

A: If you group by Address, you'll end up with only one item when you have items with the same Address. If that's OK with, go with Group By. However, if you need all the original items, with the Html concatenated, you should do like that:
var newMapItems = mapItems
    .Select(mi => new MapItem() { Address = mi.Address,
                                  Html = mapItems.Where(mi2 => mi2.Address == mi.Address)
                                                 .Select(mi3 => mi3.Html)
                                                 .Aggregate((acc, html) => acc += html)
                                }
           );

A: You can do this with a GroupBy and Select:
    var result = items
        .GroupBy(m => m.Address, m => m.Html)
        .Select(g => new MapItem() {Address = g.Key, Html = string.Concat(g.Select(h => h))});

A: This code should update your existing objects with appended values.
foreach (MapItem item in mapItems)
            {

                var sameAddress = from m in mapItems
                                  group m by m.Address into ms
                                  select string.Join("", ms.Select(e => e.Html).ToArray());

                foreach (string concatHtml in sameAddress)
                {
                    item.Html = concatHtml;
                }

            }


text:
Q: PyArrow: Writing a parquet file with a particular schema For testing purposes, I am trying to generate a file with dummy data, but with the following schema (schema of the real data):
pa.schema([
  pa.field('field1', pa.int64()),
  pa.field('field2', pa.list_(pa.field('element', pa.int64()))),
  pa.field('field3', pa.list_(pa.field('element', pa.float64()))),
  pa.field('field4', pa.list_(pa.field('element', pa.float64()))),
], )

I have the following code:
import pyarrow as pa
import pyarrow.parquet as pq

loc = "test.parquet"

data = {
        "field1": [0],
        "field2": [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]],
        "field3": [[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9]],
        "field4": [[2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9]]
    }

schema1 = pa.schema([
    pa.field('field1', pa.int64()),
    pa.field('field2', pa.list_(pa.field('element', pa.int64()))),
    pa.field('field3', pa.list_(pa.field('element', pa.float64()))),
    pa.field('field4', pa.list_(pa.field('element', pa.float64()))),
], )

schema2 = pa.schema([
    pa.field('field1', pa.int64()),
    pa.field('field2', pa.list_(pa.int64())),
    pa.field('field3', pa.list_(pa.float64())),
    pa.field('field4', pa.list_(pa.float64())),
], )

writer = pq.ParquetWriter(loc, schema1)
writer.write(pa.table(data))
writer.close()

The dictionary in the code, when converted to a PyArrow table and written to a parquet file, generates a file whose schema matches schema2. Passing schema1 to the writer gives an error. How can I change the dictionary in such a way that its schema matches schema1 when converted to a table?

A: Semantically the schemas are the same, the name of the list item ("element") should not matter. This used to be an issue but has been fixed in pyarrow 11.0.0 (https://issues.apache.org/jira/browse/ARROW-14999)
So you can upgrade to pyarrow and it should work.
Alternatively you can make sure your table has got the correct schema by doing either:
writer.write(pa.table(data, schema=schema1))

Or casting by casting it:
writer.write(pa.table(data).cast(schema1))


text:
Q: Github: find issues where assignee IS NOT a specific user How do I filter the issue list where the assignee IS NOT a specific user? Something like assignee:!userA (although that doesn't work).

A: It looks like you can use the "-" as in -assignee:userA
More info on Filter Qualifiers Based On Exclusion


text:
Q: What's the problem with my regular sentences? import re

demo_str = "descr:          Copper Concentrate Mine"
re.findall(r"(.*?):\s+(.*?)", a, re.I)

output: [('descr', '')]
This result is not what I expected.
What I want is "[('descr', 'Copper Concentrate Mine')]"

A: Remove the last ? from the capturing group to make it greedy (doc):
import re

demo_str = "descr:          Copper Concentrate Mine"
print( re.findall(r"(.*?):\s+(.*)", demo_str, re.I) )

Prints:
[('descr', 'Copper Concentrate Mine')]

A: This expression might also work:
import re

regex = r"([^:]+):\s*(.+)"
test_str = "descr:          Copper Concentrate Mine"
print(re.findall(regex, test_str))

Output
[('descr', 'Copper Concentrate Mine')]

If you wish to explore/simplify/modify the expression, it's been
  explained on the top right panel of
  regex101.com. If you'd like, you
  can also watch in this
  link, how it would match
  against some sample inputs.

A: The reason the second entry is empty is due to the non greedy dot .*? in the second part. It will match as least as possible.
As it is the last part in the expression and there are no boundaries or anchors following, an empty match will satisfy the condition.
Another option for your example data is to use re.split on matching : surrounded by 0+ whitespace chars.
\s*:\s*

Or to match only a colon and 1+ whitespace chars:
:\s+

Regex demo | Python demo
import re

demo_str = "descr:          Copper Concentrate Mine"
print(re.split(r"\s*:\s*", demo_str))

Result
['descr', 'Copper Concentrate Mine']


text:
Q: Compare two Dataframes of sentences and return a third one I want to compare two long Dataframe columns of sentences, and return a third dataframe that looks like this.
a snapshot is shown below.
My first approach was long winded and only worked for single instances, but failed when i applied it to the dataframe. It can be found in a previous question.
The logic is for words in c1 and c2, new value =1, for word in only c1, value set to zero.

sentences = tra_df['Sent1']
context = tra_df['Sent2']

Sent1[0] = "I am completely happy with the plan you have laid out today"
Sent2[0] = 'the plan you have laid out today'
c3 = ['0', '0', '0', '0' , '0', '1', '1', '1', '1', '1', '1']

A: According to my understanding of your question, here is the solution.
def get_common_words(c1, c2):
    res = [0]*len(c1.split())
    for idx, existing_word in enumerate(c1.split()):
        if existing_word in c2.split():
            res[idx] = 1
    return res

get_common_words(c1, c2)

If you want to make it work for a pandas dataframe
def get_common_words_df(row):
   c1 = row['Sent1']
   c2 = row['Sent2']
   return get_common_words(c1, c2)

df['sent3'] = df.apply(get_common_words_df, axis=1)

You can optimize it a lot


text:
Q: foursquare api venues search intent=match not working? I have been using foursquare api venues search with intent=match and it returned reasonable results a few months ago. Now, when I do the same search, results are empty.
E.g.
https://api.foursquare.com/v2/venues/search?ll=51.4914147,-0.1608899%20&client_id=clientId&client_secret=clientSecret&v=20131016&intent=match&query=The%20Five%20Fields
returns an empty venues array, despite of the version parameter being the same as before. It does not return an error, just the empty array (with valid clientId and clientSecret).
It still works with intent=checkin, but the match seems like an obvious choice for me. Any ideas why it doesn't work anymore?

A: intent=match is still working.
E.g.
https://api.foursquare.com/v2/venues/search?ll=51.4914147,-0.1608899&client_id=(YOUR_CLIENT_ID)&client_secret=(YOUR_CLIENT_SECRET)&v=20131016&intent=match&query=John%20Sandoe%20Books
I don't know why, but it does not work "John Sandoe Books" only..


text:
Q: NetSuite searchMoreWithID fails with Invalid SOAP action I'm trying to extend my NetSuite search beyond the 100 item limit.  I'm using SOAP through zeep in a python app but I'm testing in Postman first.  I can successfully get the first page of the search using a CustomRecordSearchAdvanced.  However, when I use the nsid from the response in the follow on searchMoreWithId request I am getting the following error
        <faultcode xmlns:ns1="http://xml.apache.org/axis/">ns1:Client.NoSOAPAction</faultcode>
        <faultstring>Invalid SOAPAction header: Search</faultstring>

The SOAP header is exactly the same in both cases.  The SOAP body for the first search which works is
<soapenv:Body>
    <search xsi:type='platformMsgs:SearchRequest'>
        <searchRecord xsi:type='setupCustom:CustomRecordSearchAdvanced' savedSearchId='1234'/>
    </search>
</soapenv:Body>

The SOAP body for the second search which fails is below.  I copy the searchId exactly from the response of the first search.
<soapenv:Body>
    <searchMoreWithId xsi:type='platformMsgs:SearchMoreWithIdRequest'>
        <searchId xsi:type='xsd:string'>WEBSERVICES_************</searchId>
        <pageIndex xsi:type='xsd:int'>2</pageIndex>
    </searchMoreWithId>
</soapenv:Body>

The WSDL I am using is https://webservices.na1.netsuite.com/wsdl/v2020_1_0/netsuite.wsdl and from what I can tell, this should work although there is no section in the WSDL with SOAP actions.

A: The message inside the SOAP Fault is:

Invalid SOAPAction header: Search

Looking at the WSDL, the header value should be searchMoreWithId not Search.
You can find the value to use for the SOAPAction header inside each <soap:operation> of the WSDL. The name of the operation you are requesting needs to match with an appropriate header. You are making a request to searchMoreWithId with a Search header, and from here your error message. Change the header value to searchMoreWithId and try again.
Note also that the SOAPAction header is a HTTP header, not a SOAP header.


text:
Q: How to shift Black to Color in an Image, Python I have a new backlit led monitor, and I found this black and white image of a storm trooper that looks fantastic on the backlit monitor.  My other monitor, however, is an old "energy star" liquid crystal, and the whites are yellow and the blacks are brown.  The same background looks awful...
So, I was trying to write some code to create a negative of the image, then shift the base grays and blacks to a color.  However, I guess I don't understand enough about color theory.  I tried the following on the negative of the image:
def colorshift_image(hueshift,image_file,output_image_file):
    image = imread(image_file)
    hsv_image = colors.rgb_to_hsv(image)
    hsv_image[:,:,2] += hueshift
    image = colors.hsv_to_rgb(hsv_image)
    imsave(output_image_file,image)

and it doesn't do much of anything, except maybe make the image look worse:
Original:

Negative:

Hue Shift:

Actually, it looks moderately awesome in the lower resolution.   But anyway, I think the gist is that I would like the extreme whites to take on a color--in fact, keeping this last image as a base (because the color palette is good for the LCD, then adding a blur to soften the jarring hue transitions, I think it would work...if only I could move from the grays and whites: shift them to some kind of color...
Is there a way to grab, using PIL/Scipy/etc., the "shiny" bright white parts, and shift it to a red or blue...and the greys to another base color?


text:
Q: C# There Is No Thread? I read a stackoverflow answer here, and in that answer it says There is no Thread in his blog, but the article is complicated that I can't easily understand the core idea, can anyone judge whether There is no Thread is true, if true can help to explain the core idea simpler and easier?

A: He's just saying that while a task is being awaited there is no thread actually waiting for it. That's all.
That's a good thing.


text:
Q: How does VMware configure X11? Autosize Error. Host: VMWare Workstation 12 Player 12.5.5 Windows 10
Guest: Debian 8 Jessie, Awesome WM
I have been trying to track down a configuration bug that suddenly appeared in a VM I use where the autofit feature of vmware-tools stopped working. The resolution is fixed at 800x600 after the autosize stopped working. If I
xrandr --size 1360x768

it will change resolution to the new resolution. The list of resolutions output in xrandr does not include the native resolution of the LCD which is 1600x1200. I have tried many other solutions to similar types of questions on the net but nothing has solved my problem. I removed X11 and reinstalled it, removed open-vm-tools-desktop and reinstalled, same with the VMware provided version of vmware-tools. Finally I have another debian vm which is nearly identical on this host which has xrandr showing a more complete list of resolutions and has the autofit feature working.
I was hoping to get the autofit feature working again without having to do create a new vm.

A: Recently the same happened to me, but I've managed to find a culprit because I use 2 different .vmx files for the same guest (linux is placed on the USB drive) to run it on 2 different computers and fortunately only the 1 file got corrupted. After comparing both files, it turned out, it is only necessary to remove the following lines from the .vmx file and it starts to work again:
svga.guestBackedPrimaryAware = "TRUE"
svga.maxWidth = "1920"
svga.maxHeight = "1080"
svga.autodetect = "TRUE"
svga.vramSize = "134217728"


text:
Q: React on small media query show the native mobile keyboard I am using material ui textfield to search a query and show the list of items below.
My problem is when i have small screen (mobile view) i have the same functionallity as web, and i wanna change it.
For example i dont want to "click" in query text to move on but i want to "click" on search icon mobile keyboard and make the search as the image below

Textfield Component
        <TextField
          autoFocus
          placeholder="Start typing to search"
          fullWidth
          id="fullWidth"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />


text:
Q: socketIO-client python callback not receiving args I send a command to a flask server (files). It responds by emitting a response, as argument, a dict is provided with the requested filenames.
from socketIO_client import SocketIO, LoggingNamespace, BaseNamespace

def on_data_command_response(*args):
    print('on_data_command_response')
    print(len(args))
    print("-----------")

with SocketIO("192.168.1.164", 5000, LoggingNamespace) as socketIO:

    socketIO.on('data command response', on_data_command_response)

    socketIO.emit('data event', {'command': 'files'}, on_data_command_response)
    socketIO.emit('data event', {'command': 'files'}, on_data_command_response)

    socketIO.wait_for_callbacks(seconds=5)

In flask the command is received as:
@socketio.on('data event')
def data_event(json, methods=['GET', 'POST']):
    print('received data command: {}'.format(json))

and a response is sent:
def emit_data_command_response(payload_json):
    socketio.emit('data command response', payload_json, callback=messageReceived)

The question:
It looks like the emit was receive two times. Once with args and once without for each command that I sent.
on_data_command_response
2
-----------
on_data_command_response
0
-----------
on_data_command_response
2
-----------
on_data_command_response
0
-----------

VARIATION 1:
socketIO.on('data command response', on_data_command_response)

socketIO.emit('data event', {'command': 'files'}, on_data_command_response)
socketIO.emit('data event', {'command': 'files'})
socketIO.emit('data event', {'command': 'files'})
socketIO.emit('data event', {'command': 'files'})

returns
on_data_command_response
2
-----------
on_data_command_response
0
-----------
on_data_command_response
2
-----------
on_data_command_response
2
-----------
on_data_command_response
2
-----------

but VARIATION 2 (which I thought looked the most logical):
socketIO.on('data command response', on_data_command_response)
socketIO.emit('data event', {'command': 'files'})

on_data_command_response does not even get called.
I don't understand what I am doing wrong here. Any help to get callback "on_data_command_response" called once with args?

A: The problem is that I confused callback and emit.
--> callback is when a server "returns" an emit command.
--> socketIO.on.... is guiding when a server did an emit.
socketIO.wait(seconds=1) --> waits for callbacks. So, if no callback functions provided, it doesn't do anything.
https://pypi.org/project/socketIO-client/
A client:
import time
from socketIO_client import SocketIO, LoggingNamespace, BaseNamespace

def on_data_command_response(*args):
    if len(args) > 0:
        print(len(args))
        # print('on_data_command_response')
        # for arg in args[0]:
           # print((arg))
    else:
        print("no args received.")
    # return # send acknowledgement

def message_received_by_servercallback(*args):
    print("----all good----")

def on_disconnect():
    print("lode disconnect")

with SocketIO("192.168.1.164", 5000, LoggingNamespace) as socketIO:

    socketIO.on('disconnect', on_disconnect)

    socketIO.on('data command response', on_data_command_response)

    socketIO.emit('backend event', {'command': 'files'}, message_received_by_servercallback)

    socketIO.wait_for_callbacks(seconds=1)

with a server:
@socketio.on('backend event')
def backend_request(json):
    if "command" in json.keys():
        if json["command"] == "files":
            response_json = {}
            response_json["status"] = "download files"

    payload_json = response_json
    socketio.emit('data command response', payload_json, callback=messageReceived)
    return ["received"] # will trigger the callback

performs as expected (client terminal):
2
----all good----
lode disconnect
>>>


text:
Q: HTML JavaScript print from file onto page I have a problem with a little site (it's intended to work as a local site) I try to create.
I want it to print text from local txt file onto the page. I want it to display it like this one,

but I want it to do it from a file, like this one

I tried to merge them together like this

But something is still not working right (after choosing the file to read, it does nothing) and I am not sure what am I doing wrong. I am green in javascript, so I would appreciate any help in that matter.

A: Actually, now that I read that again - the only issue with your example is you were using file[0] instead of file

    <input type="file" id="inputfile" />


text:
Q: R- Following Error: API returned: Request had insufficient authentication scopes I've verified my API in RStudio after hours of trying and now I've reached another error while trying to translate a sentence. Would be grateful for any help!
I'm just trying to translate "hello" to french using googleLanguageR package -
> gl_translate("Hello", "fr")

The result I get is this -
2021-01-21 17:15:36 -- Translating text: 5 characters -
i 2021-01-21 17:15:36 > Request Status Code:  403
Error: API returned: Request had insufficient authentication scopes.

I'm a literal beginner in the field of computing and do not understand what scopes mean here.
Thanks for the help!

A: Scopes are permissions that you give to apps you use to access an API. For example, one App might have permission to read the private messages of a users, whereas another doesn't. It's similar to when an app on your phone asks for permission to use the camera, or access your contacts.
Your app is trying to do something that it doesn't have permission to do. You'll need to add the relevant scopes in whatever setting that it is where you're generating keys etc. Presumably Google Data Studio?

A: Okay, I found an answer.
I needed to download a json version of my key and authorize it using the code -
gl_auth("filename.json")

After doing this, I needed to make sure my API is enabled. Now, it is working perfectly!


text:
Q: Enabling Offline Sync: Sync works, Offline does not I get below error when attempting to be offline, I began with the starter code as instructed by the Docs and I just keep getting the error.
I followed the details here: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-offline-data
Even trying a new download of the starter code doesn't seem to work, for what ever reason the app refuses to acknowledge that it is offline.  My offline data is synced and is available, but as soon as I am without connectivity the app crashes with the following exception:

Message:  The text associated with this error code could not be found.
  The server name or address could not be resolved StackTrace:
  {System.Runtime.InteropServices.COMException (0x80072EE7): The text
  associated with this error code could not be found. The server name or
  address could not be resolved at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at
  System.Net.Http.HttpHandlerToFilter.d__4.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Net.Http.HttpClientHandler.d__86.MoveNext()}

The fact that it is even attempting to resolve is puzzling.  What have I not implemented?
I am at a complete loss as to what is causing this and why after having followed the documentation exactly, it does not work.
Any guidance would be appreciated.


text:
Q: Ammap.js 4 - set map to be half static view globe + set mapObject to be center I'm using Ammap js version 4 to bulid static website.

*

*I want to make the map to be half globe like:

*When user click on specific div I want to center the globe accoring to specific lat/long coors with rotate animation, any ideas?
I've tried the function zoomToMapObject, but it doesn't work corrent and I don't need the zoom feature.
my code:
      am4core.useTheme(am4themes_animated);
      var chart = am4core.create("chartdiv", am4maps.MapChart);
      var interfaceColors = new am4core.InterfaceColorSet();
      chart.seriesContainer.draggable = false;
      chart.seriesContainer.resizable = false;

      chart.homeGeoPoint = {
        latitude: 0,
        longitude: 0
      };
      chart.deltaLongitude = 100;

      var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
      polygonSeries.useGeodata = true;

      polygonSeries.calculateVisualCenter = true;
      polygonSeries.tooltip.background.fillOpacity = 0.2;
      polygonSeries.tooltip.background.cornerRadius = 20;

      var template = polygonSeries.mapPolygons.template;
      template.nonScalingStroke = true;
      template.fill = am4core.color("#D3DDE7");
      template.stroke = am4core.color("#c5cfd8");

      polygonSeries.calculateVisualCenter = true;
      template.propertyFields.id = "id";
      template.tooltipPosition = "fixed";
      template.fillOpacity = 1;
      try {
        chart.geodata = am4geodata_worldLow;
      } catch (e) {
        chart.raiseCriticalError(
          new Error(
            'Map geodata could not be loaded. Please download the latest amcharts geodata and extract its contents into the same directory as your amCharts files.'
          )
        );
      }

      let cities = chart.series.push(new am4maps.MapImageSeries());
      cities.mapImages.template.nonScaling = true;

      let city = cities.mapImages.template.createChild(am4core.Circle);
      city.radius = 10;
      // city.fill = am4core.color("#666EE8");

      function addCity(coords, title, color) {
        let city = cities.mapImages.create();
        city.fill = am4core.color(color);
        city.latitude = coords.latitude;
        city.longitude = coords.longitude;
        city.tooltipText = title;
        return city;
      }

      // Set projection
      chart.projection = new am4maps.projections.Orthographic();
      chart.panBehavior = "rotateLong";

      let paris = addCity(
        { latitude: 48.8567, longitude: 2.351 },
        "Paris",
        "#ff0000"
      );
      let toronto = addCity(
        { latitude: 43.8163, longitude: -79.4287 },
        "Toronto",
        "#ff9d00"
      );
      let la = addCity(
        { latitude: 34.3, longitude: -118.15 },
        "Los Angeles",
        "#b600ff"
      );
      //let havana = addCity({ latitude: 23, longitude: -82 }, "Havana");
      let polygonTemplate = polygonSeries.mapPolygons.template;
      var lineSeries = chart.series.push(new am4maps.MapLineSeries());
      lineSeries.mapLines.template.stroke = am4core.color("#666EE8");
      lineSeries.mapLines.template.strokeWidth = 2;
      lineSeries.data = [
        {
          multiGeoLine: [
            [
              { latitude: paris.latitude, longitude: paris.longitude },
              { latitude: toronto.latitude, longitude: toronto.longitude },
              { latitude: la.latitude, longitude: la.longitude }
            ]
          ]
        }
      ];
      document.getElementsByClassName("option-1")[0].onmouseover = function() {
        chart.zoomLongitude = paris.longitude;
        chart.zoomLatitude = paris.latitude;
      };
      document.getElementsByClassName("option-2")[0].onmouseover = function() {
        chart.zoomLongitude = toronto.longitude;
        chart.zoomLatitude = toronto.latitude;
      };
      document.getElementsByClassName("option-3")[0].onmouseover = function() {
        chart.zoomLongitude = la.longitude;
        chart.zoomLatitude = la.latitude;
      };

A: The map/globe position is controlled by deltaLongitude. You even have that in your code. (related docs about map rotation)
So, if you need to rotate the globe to specific position, you can set deltaLongitude or even animate it. E.g.:
// rotate to Asia instantly
chart.deltaLongitude = -90;

// or animate rotation
animation = chart.animate({
  property: "deltaLongitude",
  to: -90
}, 2000);

Here's a working example:

/**
 * ---------------------------------------
 * This demo was created using amCharts 4.
 *
 * For more information visit:
 * https://www.amcharts.com/
 *
 * Documentation is available at:
 * https://www.amcharts.com/docs/v4/
 * ---------------------------------------
 */

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

var chart = am4core.create("chartdiv", am4maps.MapChart);

// Set map definition
chart.geodata = am4geodata_worldLow;

// Set projection
chart.projection = new am4maps.projections.Orthographic();
chart.panBehavior = "rotateLongLat";
chart.deltaLatitude = -20;
chart.padding(20,20,20,20);

// Create map polygon series
var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());

// Make map load polygon (like country names) data from GeoJSON
polygonSeries.useGeodata = true;

// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#47c78a");
polygonTemplate.stroke = am4core.color("#454a58");
polygonTemplate.strokeWidth = 0.5;

var graticuleSeries = chart.series.push(new am4maps.GraticuleSeries());
graticuleSeries.mapLines.template.line.stroke = am4core.color("#ffffff");
graticuleSeries.mapLines.template.line.strokeOpacity = 0.08;
graticuleSeries.fitExtent = false;

// Water
chart.backgroundSeries.mapPolygons.template.polygon.fill = am4core.color("#454a58");
chart.backgroundSeries.mapPolygons.template.polygon.fillOpacity = 1;

// Create hover state and set alternative fill color
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = chart.colors.getIndex(0).brighten(-0.5);

// Rotation function
var animation;
function rotateTo(delta) {
  if(animation){
    animation.stop();
  }
  animation = chart.animate({
    property: "deltaLongitude",
    to: delta
  }, 2000);
}
#chartdiv {
  width: 100%;
  height: 500px;
}

<input type="button" value="Europe" onclick="rotateTo(0);" />
<input type="button" value="Americas" onclick="rotateTo(90);" />
<input type="button" value="Asia" onclick="rotateTo(-90);" />
<input type="button" value="Australia" onclick="rotateTo(-130);" />


text:
Q: android - первый элемент RecyclerView не нажимается У меня RecylerView, которая должна реагировать на нажатия.
Для простоты задаю два текста в качестве элемента.
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:background="#ABCDEF">

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        android:text="Header"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/textViewContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewHeader"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        android:text="Content" />
</RelativeLayout>

Это адаптер с обработчиком нажатия. Задал обработчик в методе onCreateViewHolder.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private Context context;
    private String[][] dataset;
    private RecyclerView recyclerView;
    private View.OnClickListener onClickListener;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView textViewHeader;
        public TextView textViewContent;

        public ViewHolder(View v) {
            super(v);
            textViewHeader = (TextView) v.findViewById(R.id.textViewHeader);
            textViewContent = (TextView) v.findViewById(R.id.textViewContent);
        }
    }

    public RecyclerAdapter(Context context, String[][] dataset, RecyclerView recyclerView) {
        this.context = context;
        this.dataset = dataset;
        this.recyclerView = recyclerView;
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        v.setOnClickListener(onClickListener);
        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int itemPosition = recyclerView.getChildPosition(v);
                String item = dataset[itemPosition][0];
                Toast.makeText(context, item, Toast.LENGTH_LONG).show();
                String[][] dataset0 = dataset;
                dataset0[itemPosition][0] = dataset0[itemPosition][0] + " (clicked)";
                recyclerView.setAdapter(new RecyclerAdapter(context, dataset0, recyclerView));
            }
        };
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textViewHeader.setText(dataset[position][0]);
        holder.textViewContent.setText(dataset[position][1]);
    }

    @Override
    public int getItemCount() {
        return dataset.length;
    }
}

В активити один RecyclerView
<android.support.v7.widget.RecyclerView
        android:id="@+id/recView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

В коде активити только даю определение списка и задаю адаптер.
    RecyclerView recyclerView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            recyclerView = (RecyclerView) findViewById(R.id.recView);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(new RecyclerAdapter(this, new String[][]{{"A", "B"},
                {"C", "D"}, {"E", "F"}, {"G", "H"}}, recyclerView));
        }

Когда нажимаю на элементы, обработчик не действует на первый элемент. При нажатии на остальные элементы получаю всплывающее сообщение и изменение в тексте. Как это исправить?

A: Это один из тех случаев, когда проще написать правильно, чем разбираться, что не так, потому что вы используете абсолютно неверное решение. Ваш код будет создавать большое количество совершенно ненужных объектов и у меня нет никакого желания профилировать этот код, но есть большая вероятность утечки памяти, не говоря уже о том, что он полностью не соответствует принятым паттернам и архитектуре Android в частности и ООП в целом.
Предлагаю следующий адаптер, который лишен всех проблем адаптера в вашем вопросе:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.Holder> {

    private final Context context;
    private final String[][] dataset;

    RecyclerAdapter(Context context, String[][] dataset) {
        this.context = context;
        this.dataset = dataset;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(final Holder holder, int position) {
        holder.textViewHeader.setText(dataset[position][0]);
        holder.textViewContent.setText(dataset[position][1]);
        holder.item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clicked(holder.getAdapterPosition());
            }
        });

    }

    private void clicked(int position) {
        Toast.makeText(context, dataset[position][0], Toast.LENGTH_LONG).show();
        dataset[position][0] += " (clicked)";
        notifyItemChanged(position);
    }

    @Override
    public int getItemCount() {
        return dataset.length;
    }

    static class Holder extends RecyclerView.ViewHolder {
        final TextView textViewHeader;
        final TextView textViewContent;
        final LinearLayout item;

        Holder(View view) {
            super(view);
            item = (LinearLayout) view.findViewById(R.id.item); //ID корневого лэйаута в айтеме
            textViewHeader = (TextView) view.findViewById(R.id.textViewHeader);
            textViewContent = (TextView) view.findViewById(R.id.textViewContent);
        }
    }
}

Активити:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(new RecyclerAdapter(this, new String[][]{{"A", "B"}, {"C", "D"}, {"E", "F"}, {"G", "H"}}));
    }
}

и немного рефакторинга в разметке, это позволит несколько поберечь ресурсы устройства:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

recycler_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="#ABCDEF"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="18dp"
        tools:text="Header" />

    <TextView
        android:id="@+id/textViewContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        tools:text="Content" />
</LinearLayout>


text:
Q: Python list implementation How are the lists implemented in python? I mean how is it possible to append an element in constant time and also get an item in constant time? Can anyone please tell how to do it in C?

A: A simple implementation is to use a preallocated buffer and a counter for the number of elements.
When the buffer is filled up and you want to append element, then you allocate a bigger buffer (e.g. twice as big) and copy the old one's data into the new one.
Thus the append operation is not strictly O(1), but it's amortized O(1), namely on average it's O(1).


text:
Q: Given a r.v. $X$, can we choose a r.v. $Y$ independent of $X$ and with the same distribution? The question originates in the following problem: Given that $\phi$ is a characteristic function, show that so is $| \phi |^2$.
The solution given by a lecturer was as follows: Suppose $\phi$ is the characteristic function of a random variable $X$. Choose another random variable $Y$ which is independent of $X$ and has the same distribution. Then $| \phi |^2$ is the characteristic function of $X-Y$.
I agree with the last part once $Y$ is chosen, but it does not seem completely obvious to me that you can necessarily choose such a $Y$. $Y$ has to be defined on the same probability space as $X$ in order for $X-Y$ to be defined. So my question is whether it is so that given any random variable $X$ defined on the space $( \Omega, \mathcal{F}, P)$, we may choose another random variable $Y$ defined on $( \Omega, \mathcal{F}, P)$ such that $X$ and $Y$ are independent and have the same distribution? If so, how can we show that?

A: In fact, we are not forced to define $Y$ over the same probability space. Instead, we can define a new probability space $(\Omega', \mathcal{F}', P')$, define $X'$ on $(\Omega', \mathcal{F}', P')$ so that it has the same distribution as $X$ and then define $Y$ on $(\Omega', \mathcal{F}', P')$ so that it is independent of $X'$ and has the same distribution as $X'$.
We end up in the desired situation where we have two independent random variables on the same probability space and with the same distribution described by the characteristic function $\phi$. This enables us to define $X-Y$ as required.
Now, in this particular case, we may choose to define our new probability space as
$$
(\Omega', \mathcal{F}', P')=(\Omega\times\Omega,\mathcal{F}\otimes\mathcal{F}, P\times P)
$$
where $\Omega'=\Omega\times\Omega$ is the Cartesian product, $\mathcal{F'}=\mathcal{F}\otimes\mathcal{F}$ is the product $\sigma$-algebra on $\Omega'$ and $P'=P\times P$ is the$^1$ product measure. Next, for $(\omega_1, \omega_2)\in\Omega'$ we define
$$
X'((\omega_1, \omega_2)) := X(\omega_1)\\
Y((\omega_1, \omega_2)) := X(\omega_2).
$$
These are easily seen to be measurable functions on $\Omega'$. Moreover, by definition of product measure, we have $P'(A\times B)=P(A)P(B)$ for any $A,B\in\mathcal{F}$. This can be used to show that $X'$ and $Y$ are independent. Finally, they both have the same distribution as $X$ and therefore their characteristic function is $\phi$.

$^1$ Product measure is unique here because probability measures are finite.


text:
Q: Getting distinct value of the _id field in mongo db I have a collection which is the result of a map_reduce that looks like this.
[
  {
    _id: { id_field1: 'id_field_value1', ... }
    value: { value_field1: 'value_field_1' }
  },
  ...
]

Now I want to get the distinct values of _id.field1
But
collection.distinct('_id.id_field1')

returns an empty list.
If I do
collection.distinct('value.value_field1')

I get the expected results. (As point out here : MongoDB: How to get distinct list of sub-document field values?)
Is there any reason why I can't distinct values from the id of the document?
EDIT:
mongo 2.5.5
actual document
 db.collection.findOne()

 { _id : { year : 2013, month : 11, date : 2, language : en-US},
   value : { sentence_eval : { Num : 36, PerfectMatch : 33} }
 }
db.collection.distinct('value.sentence_eval.Num)
[36,...]
db.collection.distinct('_id.language')
[]

A: I tried the same query with the same collection that you have and distinct() does return the expected value.  Please see below.
BTW, the value for _id.language has to be enclosed within double-quotes. I hope what you entered is a typo.
> db.bar.findOne()
{
        "_id" : {
                "year" : 2013,
                "month" : 11,
                "date" : 2,
                "language" : "en-US"
        },
        "value" : {
                "sentence_eval" : {
                        "Num" : 36,
                        "PerfectMatch" : 33
                }
        }
}
> db.bar.distinct("value.sentence_eval.Num")
[ 36 ]
> db.bar.distinct("value.sentence_eval.PerfectMatch")
[ 33 ]
> db.bar.distinct("_id.year")
[ 2013 ]
> db.bar.distinct("_id.language")
[ "en-US" ]

A: Version 2.5.5 of mongodb seems to have the bug.
I verify with 2.4.9 and 2.6RC1 and it is now working as intended. So updating mongodb fixed the problem.


text:
Q: certain page of Flask web app goes down after a couple hours I am hosting a Flask app with nginx and uWSGI on a CentOS box. After a few hours, one of my pages goes down with a 500 internal server error Do you see anything jump out at you from my configs below?
My ers_portal_nginx.conf:
server {
    listen      80;
    server_name www.mydomain.com;

    location / { try_files $uri @app; }
    location @app {
        include uwsgi_params;
        uwsgi_pass unix:/home/metheuser/webapps/ers_portal/run_web_uwsgi.sock;
    }
}

My ers_portal_uwsgi.ini:
[uwsgi]
#user info
uid = metheuser
gid = ers_group

#application's base folder
base = /home/metheuser/webapps/ers_portal

#python module to import
app = run_web
module = %(app)

home = %(base)/ers_portal_venv
pythonpath = %(base)

#socket file's location
socket = /home/metheuser/webapps/ers_portal/%n.sock

#permissions for the socket file
chmod-socket    = 666

#uwsgi varible only, does not relate to your flask application
callable = app

#location of log files
logto = /home/metheuser/webapps/ers_portal/logs/%n.log

Relevant parts of my views.py
data_modification_time = None
data = None
def reload_data():
    global data_modification_time, data, sites, column_names
    filename = '/home/metheuser/webapps/ers_portal/app/static/' + ec.dd_filename
    mtime = os.stat(filename).st_mtime
    if data_modification_time != mtime:
        data_modification_time = mtime
        with open(filename) as f:
            data = pickle.load(f)
    return data

@a bunch of authentication stuff...

@app.route('/')
@app.route('/index')
def index():
    return render_template("index.html",
                           title = 'Main',)

@app.route('/login', methods = ['GET', 'POST'])
def login():
    login stuff...

@app.route('/my_table')
@login_required
def my_table():
    print 'trying to access data table...'
    data = reload_data()
    return render_template("my_table.html",
                           title = "Rundata Viewer",
                           sts = sites,
                           cn = column_names,
                           data = data) #  dictionary of data

I installed nginx via yum (yesterday)
I am using uWSGI installed in my venv via pip
I am on CentOS 6
I have everything set up very similar to here, meaning all the configs are in my app folder and  /etc/nginx/nginx.conf is symlinked to.
My uwsgi log shows:
Wed Jun 11 17:20:01 2014 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 287] during GET /whm-server-status (127.0.0.1)
IOError: write error
[pid: 9586|app: 0|req: 135/135] 127.0.0.1 () {24 vars in 292 bytes} [Wed Jun 11 17:20:01 2014] GET /whm-server-status => generated 0 bytes in 3 msecs (HTTP/1.0 404) 2 headers in 0 bytes (0 switches on core 0)

When its working, the print statement in the views "my_table" route prints into the log file. But not once it stops working.
Any ideas?


text:
Q: React Native Flatlist - Run function only when visible I have an array with 500+ id's, each item on this array is going to fetch some data so I'm using Flatlist.
  <FlatList
    viewabilityConfig={viewabilityConfig.current}
    updateCellsBatchingPeriod={400}
    initialNumToRender={10}
    removeClippedSubviews={true}
    data={threads}
    renderItem={({item}) => <SectionThread item={item} />}
  />

The component SectionThread calls an api when mounted
  const getThread = React.useCallback(async () => {
    const o = await fetchThread(props.item);
    setThread(o);   }, []);

  React.useEffect(() => {
    getThread();   }, []);

  return (
    <View>
      {thread.title}
    </View>   );

I need to find a way to only call this api when the item is visible, right now it calls everything at once and my app gets really laggy.
I've tried a bunch of stuff like viewabilityConfig but with no success.
My question is: Is there a way where the item on a flatlist is only mounted when is visible?

A: So it was the first prop on the documentation page, windowSize fixed everything
  <FlatList
    disableVirtualization={true}
    windowSize={2}
    initialNumToRender={25}
    removeClippedSubviews={true}
    data={threads}
    renderItem={({item}) => <SectionThread item={item} />}
    keyExtractor={item => item.id}
    onScrollBeginDrag={handleScroll}
    onMomentumScrollBegin={handleScroll}
  />

windowSize Determines the maximum number of items rendered outside of
  the visible area, in units of visible lengths. So if your list fills
  the screen, then windowSize={21} (the default) will render the visible
  screen area plus up to 10 screens above and 10 below the viewport.
  Reducing this number will reduce memory consumption and may improve
  performance, but will increase the chance that fast scrolling may
  reveal momentary blank areas of unrendered content.

And for some reason the list got all crazy if I don't disable virtualization

disableVirtualization DEPRECATED: Virtualization provides significant
  performance and memory optimizations, but fully unmounts react
  instances that are outside of the render window. You should only need
  to disable this for debugging purposes.