text:
Q: Swift: 'ViewController.Type' does not have a member named 'URL' I have some code in my viewController
 var URL: NSURL = NSURL(string: "http://someurl.com")!
 var request : NSMutableURLRequest = NSMutableURLRequest(URL:URL)

 request.HTTPMethod = "POST"

 var bodyData = "data=something"

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
        (response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

However I get the error: 'ViewController.Type' does not have a member named 'URL'. If I put the code in the ViewDidLoad it works on app launch.
How do I get the code to run on the click of a button? I tried putting the @IBAction in the ViewDidLoad func but that doesnt work either :/
edit: Full View
 //
 //  ViewController.swift
 //  postPhp
 //
 //  Created by  -  on 01/12/2014.
 //  Copyright (c) 2014 Dannie C. All rights reserved.
 //

 import UIKit

 class ViewController: UIViewController {

 var URL: NSURL = NSURL(string: "http://someurl.com")!
 var request : NSMutableURLRequest = NSMutableURLRequest(URL:URL)

 request.HTTPMethod = "POST"

 var bodyData = "data=something"

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
  {
   (response, data, error) in
   println(NSString(data: data, encoding: NSUTF8StringEncoding))
  }

@IBOutlet var serverLabel: UILabel!

@IBAction func serverButton(sender: AnyObject) {

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

A: None of your code is in a method, wrap it up in a method and call the method when appropriate.


text:
Q: Should I store things in corpses? I was looking for a safe place to store my stuff, but I am nowhere near able to afford a house, and haven't located any of the "safe" locations.
However, I remember killing Alvor in Riverwood a while back, and his corpse is still there. Can I store my items on him without them disappearing?

A: No. Your items will not be safe, eventually, he will despawn.

A: *Although some dead bodies,either having been killed by you or in game event
sometimes stick around for a while you can NOT count on this for safe storage.
the answer is NO you cannot count on this for safe storage.
some bodies that remain in game dead will be looted at random as well, had this happen to myself once when i did what your asking about.
hope this helped

A: According to this Respawn and DeadBody Timers mod on SkyrimNexus:

Vanilla Respawn Timer details
Npcs, Creatures and Items... respawn after 10 Days or 240 Hours..
Areas that are marked cleared on your map respawn after 30 days or 720 hours
Merchants Respawn Items every 24 hours..No Change..
Dead Bodies Remove themselves after X amount of Day
and If More than 15 Dead Bodies are in cell then Remover Features kick in

So, no. It is not safe to store anything in corpses.
I've read that named NPCs do not respawn in Skyrim. So Alvor won't come back (ie. it won't be reset). I wouldn't bet on his corpse staying there forever though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS + Laravel - Turn Chat Feature Into Web Socket I have a chat feature in my app using JSQMessagesViewController (https://github.com/jessesquires/JSQMessagesViewController).
It makes an API call to my server every 5 seconds to get all the chat messages between two users to populate the chat view with those messages. It was suggested I turn that into a socket connection because making an API call every 5 seconds will be hard on the battery and a waste of API calls.
How do I turn my chat feature into a socket connection with my server?
Are there any libraries in Objective-C that will help me accomplish this? And also, I'm pretty sure that I'll have to set this up on the back end too, so are there any resources as to how to set this up on a PHP Laravel backend?

A: You should be able to accomplish this using a couple mature libraries on both the iOS frontend and the PHP backend.
iOS: SocketRocket
https://github.com/square/SocketRocket
PHP:: Ratchet
http://socketo.me
They both support RFC 6455 so should integrate pretty easily.
Since you are using PHP, I'm going to take a stab and guess you are using Apache? If so, here is some more information on setting up websockets to work with Apache which can have issues with connection management: Setting up a websocket on Apache?


text:
Q: Typescript Super Type I am looking for a type which is a the super type of T?
Something like:
foo<T>(obj: Super<T>): T

Lets say T is an object with properties of { username, password }.
Super < T > with properties of { username, password, confirmPassword }.
Example of a function signature:
function excludeKeys<T>(obj: Super<T>, excludeKeys: string[]): T {

    // Exclude key/pairs form original object ...
}

A: You have to specify the parent with T extends U so TypeScript can infer the parent type:
function foo<T extends U, U>(obj: U): T { ... }

Or you could try something like this:
type Super<T> = T extends infer U ? U : object;

function foo<T>(obj: Super<T>): T { ... }


text:
Q: Convert QPair to QVariant I have the following problem: I want to transmitt data via TCP, and wrote a function for that. For maximum reusability the function template is f(QPair<QString, QVariant> data). The first value (aka QString) is used by the receiver as target address, the second contains the data. Now I want to transfer a QPair<int, int>-value, but unfortunately I can not convert a QPair to a QVariant. The optimum would be to be able to transfer a pair of int-values without having to write a new function (or to overload the old one). What is the best alternative for QPair in this case?

A: Note: this answer uses another functions to convert them, something you may consider.
You could use QDataStream to serialize the QPair to QByteArray and then convert it to QVariant, and you can the inverse process to get the QPair from a QVariant.
Example:
//Convert the QPair to QByteArray first and then
//convert it to QVariant
QVariant tovariant(const QPair<int, int> &value)
{
    QByteArray ba;
    QDataStream stream(&ba, QIODevice::WriteOnly);
    stream << value;
    return QVariant(ba);
}

//Convert the QVariant to QByteArray first and then
//convert it to QPair
QPair<int, int> topair(const QVariant &value)
{
    QPair<int, int> pair;
    QByteArray ba = value.toByteArray();
    QDataStream stream(&ba, QIODevice::ReadOnly);
    stream >> pair;
    return pair;
}

A: You have to use the special macro Q_DECLARE_METATYPE() to make custom types available to QVariant system.
Please read the doc carefully to understand how it works.
For QPair though it's quite straightforward:
#include <QPair>
#include <QDebug>

typedef QPair<int,int> MyType;    // typedef for your type
Q_DECLARE_METATYPE(MyType);       // makes your type available to QMetaType system

int main(int argc, char *argv[])
{
    // ...

    MyType pair_in(1,2);
    QVariant variant = QVariant::fromValue(pair_in);
    MyType pair_out = variant.value<MyType>();
    qDebug() << pair_out;

    // ...
}


text:
Q: SQL semantics for "FOR UPDATE" & "JOIN" I'd like to understand the exact semantics of using "FOR UPDATE" in connection with "JOIN". Does it just lock all the rows that were effectively used to build the end result? Does it do something else?
From this topic:
http://postgresql.1045698.n5.nabble.com/Select-For-Update-and-Left-Outer-Join-td4363154.html
I understand there are some important differences between database implementations. However I'm not sure. I'm interested in behaviour of any popular RDBMS out there, however PostgreSQL in particular.

A: You've got it correct. In a "SELECT FOR UPDATE" with a JOIN, any rows that contribute to the returned rows will be locked. You can change this behavior by adding an "OF table_a" to the "FOR UPDATE" so that only the rows from table_a will be locked. You can read more about this in the Postgres docs here:
http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE


text:
Q: Data sorting in query I work with SQL Server 2005. I have a table in which FK: two columns (book number, bookshelf number). A PK = FK + Datetime column. And also I have the column of value. I want to create query, which sort the data as follows.
I have this data set:
BookNumber   BookshelfNumber          DateTime          Value
    0              0             12.01.2012 14:40:42      4
    0              0             12.01.2012 14:45:42      5
    0              0             12.01.2012 14:48:42      9
    0              1             12.01.2012 14:38:42      1
    0              1             12.01.2012 14:42:42      4
    0              1             12.01.2012 14:48:42      1
    1              1             12.01.2012 14:38:42      5
    1              1             12.01.2012 14:48:42      7
    1              1             12.01.2012 14:58:42      4

After query I want this result:
BookNumber   BookshelfNumber          DateTime          Value
    0              0             12.01.2012 14:40:42      4
    0              1             12.01.2012 14:38:42      1
    1              1             12.01.2012 14:38:42      5

A: You can use the ROW_NUMBER function to add a number to your dataset that

*

*restarts numbering by each change in Booknumber & BookshelfNumber (PARTITION BY)

*Numbers the result from oldest to newest datetime (ORDER BY)

SQL Statement
SELECT  *
FROM    (
          SELECT  BookNumber
                  , BookShelfNumber
                  , DateTime
                  , Value
                  , rn = ROW_NUMBER() OVER (PARITION BY BookNumber, BookshelNumber ORDER BY DateTime)
          FROM    Books
        ) b
WHERE   rn = 1


text:
Q: naming and configuring jsfiddle This is going to sound like a really stupid question to whoever knows the answer!
When I create a JSfiddle it appears on my listing page like this
cGzCe Revision 8
Then I title it 'Multi-create nodes ' (extra space since the revision number is added with no space to this phrase) and update again and get this
cGzCe Multi-create nodes Revision 9
I want to alter the text of the cGzCe in the larger font - where can I do that? I forked someone else's fiddle the other day and it had this done, but I couldn't see how the settings differed from one of my fiddles! Help please :-D
...
Also, for a bonus point - does anyone know how to disable the auto-indenting... (or make it work reliably, or lower the indent to two spaces..)
Thanks!

A: Here is what worked for me,
for new fiddle:

*

*In the left panel, under Fiddle Meta, give a name in the "untitled fiddle" input box

*Click save from the top menu to save the fiddle and the given name

for existing fiddle with code name:

*

*Click on the fiddle to open it.

*In the left panel, under Fiddle Meta, give a name in the "untitled fiddle" input box

*Click update and then set as base from the top menu to save the  given name

A: I had trouble replacing the fiddle code number with a fiddle name and description.
Here's how I got the results I wanted:

*

*Clicked on "Base" to get the fiddle URL to show as /xxxxxx/#Base where xxxxxx is the fiddle code.

*Used the Fiddle Options to set the Fiddle Name as "MyFiddleName" and Description

*Clicked "Update"

*Clicked "Set as base"

*Now the dashboard shows "MyFiddleName" with the description and doesn't show the xxxxxx code.

A: While I think this is off-topic for Stack Overflow (and have voted to close as such), the way to have no string of random characters besides the title of the saved Fiddle is, when you start the Fiddle, declare its title; if the title is added after a point at which it's been previously saved then the string of characters will appear, since that's the 'base'/'original' Fiddle, whereas the 'titled' Fiddle is a later revision.


text:
Q: Different between Android onResume(), onStart() and lifecycleScope I have viewmodel call TestViewModel and a method call fetchDataFromDataSource() to call fetch data from the server, I used to call load data on OnResume() until I bump into lifecycleScope
I have tried to read more but didn't really get which is better.
class TestViewModel: Viewmodel() {

    fun fetchDataFromDataSource(){
       ....
    }
}

class TestActivity : AppCompatActivity() {

private val viewModel: TestViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
    ...

    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
        // Is it best to call here
         viewModel.fetchDataFromDataSource()
        }
    }
}

onResume(){
  super.onResume()
  // or is it best to call here
         viewModel.fetchDataFromDataSource()
}

}
where is the best place to call fetchDataFromDataSource(),  is it in onResume() or lifecycleScope and what is the advantage lifecycleScope has over onResume() or onStart()
I know the view has rendered at onResume() so what benefit does lifecycleScope has over android lifecycle (onResume onCreate onStart...)

A: repeatOnLifecycle is similar to calling methods on the respective lifecycle events every time the Activity hits that state but with a quick access to the lifecycleScope which can launch a coroutine.
Example:
override fun onResume(){
    super.onResume()
    viewModel.fetchDataFromDataSource()
}

is equivalent to -
class MainActivity : AppCompatActivity {

  init {
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.RESUMED) {
           viewModel.fetchDataFromDataSource()
      }
    }
  }
}

If you want to load the data from ViewModel every time the user comes to foreground from background, use onStart or repeatOnLifecycle(Lifecycle.State.STARTED).
If you need to load the data everytime the Activity resumes, then use onResume or the lifecycleScope equivalent as shown above but if this is just a one-time op, consider using onCreate.


text:
Q: Is a Beowulf cluster a solution for me? Background
I'm an undergrad working on an scientific experiment.
Till now I was pilot testing our one of the program  on Ubuntu 12.04 and now I need to deploy it.
The PC on which I tested the program has a Q9550 Intel processor.
The program has been written by an alumnus who was working on the experiment few years ago.
What I know
The programs uses lot of computing power.
It uses all the processor cores available to it.
It is written in Python.
What I don't know
I don't know much about coding.
I really don't know much about it's code.
I cannot easily tweak it.
I'm not focusing on it's technical aspects. I'm more interested in it's application
What help I need
The quad core processor is really really insufficient for the actual deployment of the program as it crunches a lot of data. I need to get a lot of processing cores. I do not have a big grant to buy a server with 24-core processors.
However there are many such quad core computers available in our lab all running Ubuntu and some running CentOS. Can I harness their computing power by forming a Beowulf cluster?
I'm really unaware of the code of my program, however as I mentioned earlier, it uses all the available processing cores. Would it be possible to run the program on the cluster?
If that's possible, Can someone guide me about what method of creating a Beowulf cluster would more helpful for my application?


text:
Q: Azure Automation powershell runbook hung up issue I am creating an Azure Automation account having a powershell runbook. The script is simply looping over each VM in a resource group and deleting all files under a particular folder.
$ResourceGroup = '<<myResourceGroup>>'
$TargetDir = '<targetDirectoryPath/.'
$TargetCommand = 'rm -rfv ' + $TargetDir

try
{
    $message = Connect-AzAccount -Identity

    $myAzureVMs = Get-AzVM -ResourceGroupName $ResourceGroup -status | Where-Object {$_.PowerState -eq "VM running" -and $_.StorageProfile.OSDisk.OSType -eq "Linux"}

    if($myAzureVMs.Name.Count -gt 1)
    {
        For($val = 0; $val -le $myAzureVMs.Name.Count-1; $val++)
        {
           # the script hangs here
            $message = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroup -Name $myAzureVMs.Name[$val] -CommandId 'RunShellScript' -ScriptString $TargetCommand
        }
    }

    Write-Output "DONE !!"
}
catch
{
    Write-Error -Message $_.Exception
    throw $_.Exception
}

The script is working fine but the issue is if a VM is not ok or has some connectivity problem then the script hangs just there. No error or exception is thrown. It just keeps waiting and eventually times out after hours.
My question is there any way to check if the VM can be connected or not (or any better solution) and then only the script should execute. I have also tried putting the Invoke-AzVMRunCommand inside a try-catch block to eat up the exception and to move to the next VM but in vain. It's simply hangs on to that VM and no exception thrown.

A: Before collecting the "VM status" or relevant virtual machine details, I would suggest using the
start-AzVM Azure PowerShell command to check whether VM is connected.
The script should then be called based on the connectivity status it returns. You can avoid waiting time by doing so while running the remaining script.
$vmstatus = start-AzVM -Name <VMName> -ResourcegroupName <resourcegroupname>
if($vmstatus.status -eq "succeeded") {
write-host "connected"
}

Output:

Alternatively, check the Test-AzNetworkWatcherConnectivity by enabling Network Watcher in your environment.

A: Solved.
Actually the run command utilizes the VM's agent to execute the task and in some VMs this agent is not properly ready and that's why the hung up. So, added an additional checking to check the VM agent status on each VM before executing the operation and that solved the problem.


text:
Q: Calculate EMVA1288 temporal dark noise Say I have a dark current plot (image mean over shutter time) with an offset (y-intercept) of 4100 and system gain K = 4.23, is the following calculation correct?
Variance of dark signal = sqrt(4100) = 64.
Temporal dark noise = sqrt(64)/K = 1.89 electrons.

A: I'm happy to see that other people are working with EMVA1288 as i'm one of the authors and test equipment manufacturer.
Your calculation is incorrect. The total noise is not the dark temporal noise, you need to get rid of the fixed pattern noise.
In EMVA1288, we do this by accumulating images in large quantities to separate the fixed noise and the temporal noise. This is quite well explained in the standard. If you do not exactly follow the procedures in the standard then you will not be compliant. There are more details to come about this compliance in future versions of the standard.


text:
Q: Why does CSMA/CD require a minimum frame size? I read this somewhere - An Ethernet frame has a minimum size of 64 bytes because anything that is shorter than the 64 byte minimum is interpreted by receiving station as a frame resulting from a collision. This allows the receiving station to inform the transmitting station that a collision has resulted, hence it backs off and begins a re-transmission at an arbitrary time.
I am able to comprehend the overall idea. Could you please explain it ?

A: The minimum frame size on Ethernet is so that by the time the beginning of a frame gets all the way across a maximum-width network, if a collision is detected there on the far side of the network, there's still enough time for the jam signal (collision detection notification) to make it all the way back across the network while the transmitter is still transmitting, so that the transmitter will receive the jam signal and know it got collided with so it will have to retransmit.
Anything below 64 bytes is just considered a runt (a buggy transmission) and ignored. Runts are not collisions and do not trigger retransmissions.
But this is all pretty much moot as nobody runs hubs anymore, since Gigabit Ethernet requires switches. So today's networks are always full duplex and CSMA/CD is a thing of the past.


text:
Q: Unable to parse xml string in Brightscript I am currently trying to create an application for Roku where the user can find and watch some of the most recent recorded church services available from my church's archives. To do this, I access an API containing an XML document with data pertaining to said recordings. The document contains an element called ArrayOfMediaModel which has at least 30 or more elements within it which are called MediaModel nodes. My hope is to parse the information from these nodes in order to create and play video feed for the end user
That being said, I can't seem to parse the information. Every time I try, I get the following error in the command prompt:

Function call operator () attempted on non-function. (runtime error &he0) in pkg:/source/CreateRecentMenu.brs(8)

Here is the code I have for this operation. As you can assume by the title, it is written in Brightscript.
sub CreateRecentMenu()
   screen = CreateObject("roGridScreen")
   port = CreateObject("roMessagePort")
   xml = CreateObject("roXMLElement")
   screen.setMessagePort(port)

   xml = GetXML("[a url exists here which i removed in this post]")
   Parse (xml)

   'more code occurs beyond this, but the function crashes upon the Parse() call

end sub

The GetXML function retrieves data from the XML file specified by the url (which, again, I removed for the sake of posting here) and returns a string. I have tested the result of this and I am confident that it properly returns the string as is intended.
Reading over the documentation of Roku Brightscript, it seems like this should work but it does not. It is also my understanding that, in order to retrieve any meaningful information from the xml document, I have to perform the Parse() function to the xml string. Any help provided is greatly appreciated.

A: No wonder, you are confused what xml exactly is - is it the parsed object or the xml text. Try this:
   xml = CreateObject("roXMLElement")
   xml_str = GetXML("[a url exists here which i removed in this post]")
   xml.parse(xml_str)


text:
Q: Does all the input function use the same buffer? Does all the input functions use the same buffer? I read it in a book   It says that all the input functions use the same buffer in a program.But I made a test, it shows that maybe it's wrong. I want to know that is there any problem in my test?
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE    *fp1;
    FILE    *fp2;
    char    ch;
    char    ch2;
    int d;

    scanf("%d", &d);

    fp1 = fopen("file1.c","r");
    fp2 = fopen("file2.c", "r");

    while((ch = getc(fp1)) != 'r')
        putchar(ch);
    putchar('\n');

    putchar(ch = getc(fp1));
    putchar('\n');

    while((ch2 = getc(fp2)) != 'n')
        putchar(ch2);
    putchar('\n');

    putchar(getc(fp1));
    putchar('\n');

    putchar(ch2 = getc(fp2));
    putchar('\n');

    putchar(getchar());
    putchar('\n');

    return 0;

}

contents of the file1.c is:    the first one
contents of the file2.c is:    the second one
when I entered: 12cd
the output is:
 the fi

 s

 the seco

 t

 d

 c

It seems that file1.c file2.c and stdin use three different buffers, Can you tell me is there any problem of my test? any help will be appreciated.

A: I think the book means that all the functions that reads from standard input have the same buffer.
In your example, you read from different files, every file will have their own stream, so they will have different buffers.
C11 7.21.3 Files

A stream is associated with an external file (which may be a physical device) by opening
  a file, which may involve creating a new file.

Then later the standard keeps talking about how to treat streams with different buffers(full, line, or unbuffered). Apparently buffers are relevant to streams, and streams are to files.
In C++, it's similar.

A: First of all, I will recommend you to use other extension for your text files.
Obviously there is different streams or buffers in which you can read or write. The example that you have been wrote is a good prove of that.
Your program works perfectly fine.


text:
Q: Find the best time to change the other times the least I want to find the best common time to change the other times the least (that the sum of the differences is the lowest possible).
On input, I have the array of times.
On output, there should be the new, common time.
Note that the times can be not ordered and be absolutely different (e.g. 02:00, 02:30 and 03:30)
Example 1
Input: ["01:00", "02:00", "03:00", "04:00", "05:00"]
Output should be 03:00, because it's the best to change 01:00 to 03:00 (2 hours of change), 02:00 to 03:00 (1 hour of change), keep 03:00 the same, 04:00 to 03:00 (1 hour), and 05:00 to 03:00 (2 hours).
Example 2
Input: ["12:00", "13:00", "14:00"]
Output should be 13:00 - change 12:00 to 13:00 (1 hour) and 14:00 to 13:00 (1 hour)
Example 3 (tricky)
Input: ["23:00", "01:00", "02:00"]
Output should be 01:00 - change 23:00 to 01:00 (2 hours) and 02:00 to 01:00 (1 hour) (the tricky thing is 23:00 - the best time is not 13:00)
I tried functions that make the average of times, e.g. https://stackoverflow.com/a/52839039/19022995, but unfortunately it doesn't work
I would be really grateful for tips how to do this
Thank you in advance

A: Lemma: an optimal answer coincides with one of the given times.
To prove it, consider a solution that doesn't coincide with any of the given times. Try to move it a bit forward and then a bit backward. In at least one of the cases, the total difference does not increase. So, continue moving in that direction until you hit one of the given times.

What is left now is to write a function that computes the difference, taking wraparound from 23:59 to 00:00 into account.
After that, try every given time as a candidate answer, calculate the total difference for each, and pick the best one as the final answer.

In pseudocode:
time (h, m) = h * 60 + m

diff (t1, t2) = min (abs (t1 - t2), 60 * 24 - abs (t1 - t2))

t[0..n) = given times

total (x) = sum {diff (x, t[i])} for i in [0..n)

answer = arg min {total (t[i])} for i in [0..n)

A: One approach is to look for the smallest "window" containing all the times. To do this, sort the times (naively) and, consider each time as being the "first". For instance, in your third example, considering 1:00 as the first time would lead to a 22 hour window (because that makes the "last" time 23:00); considering 2:00 as the first time would lead to a 23 hour window; but considering 23:00 as the first time would lead to a 3 hour window. From there, simply calculate relative to that first time, calculating differences mod 24.


text:
Q: FileHelpers import issues Good afternoon, i've been trying to import a field from a txt/csv file and it keeps causing an error in my import. I know why i just can't seem to figure out how to resolve it.
I have a string filed listed below that is causing an error when it runs. The issue is that the accident description is quoted correctly but also contains another set of double quotes. Is there any way for me to strip out quotes from the quoted string ?
"123456","I heard a "pop" in my shoulder","01/01/1900"

This is the FileHelpers class
Namespace xxx
    <DelimitedRecord(","), IgnoreFirst(1)>
    Public Class  yyy

        <FieldQuoted()> _
        Public IDAs String
        <FieldQuoted()> _
        Public AccidentDescr As String
        <FieldQuoted()> <FieldConverter(ConverterKind.Date, "yyyy-MM-dd")> _
        Public DOI As DateTime

any help would be great

A: The trick is to NOT use the FieldQuoted attribute, but instead apply a custom FieldConverter to remove the quotes.
Public Class MyQuotedStringConverter
    Inherits ConverterBase
    Public Overrides Function StringToField(from As String) As Object
        ' StringToField() is used by import. The 'from' parameter will contain all the text between the comma delimiters (including all quotes)

        Dim result As String = from
        ' remove the first and last quotes
        If result IsNot Nothing Then
            If result.StartsWith("""") Then
                result = result.SubString(1)
            End If
            If result.EndsWith("""") Then
                result = result.SubString(0, result.Length - 1)
            End If
        End If
        Return result
    End Function

    Public Overrides Function FieldToString(fieldValue As Object) As String
        ' FieldToString is used by export
        Return fieldValue.ToString()
    End Function
End Class

And change any problem fields to use the converter. For example
<DelimitedRecord(","), IgnoreFirst(1)>
Public Class  yyy

    <FieldConverter(GetType(MyQuotedStringConverter))> _
    Public IDAs String
    <FieldConverter(GetType(MyQuotedStringConverter))> _
    Public AccidentDescr As String
    <FieldQuoted()> <FieldConverter(ConverterKind.Date, "yyyy-MM-dd")> _
    Public DOI As DateTime


text:
Q: Enter the same value into multiple cells in Excel I would like to enter a same value into multiple cells.
What is the quickest way? (I have tried selecting the cells, typing a value, and pressing Enter.)

A: *

*Select the cells.

*Type the value.

*Press Ctrl-Enter instead of Enter.
All selected cells will be filled with the value you typed.


text:
Q: Eofexception in Google app engine / Restlet combination I created a restful web service using a combination of GAE, objectify for persistence at server side and the restlet framework.
I managed to get everything working: putting new objects, getting, getting the whole list, ... My application works perfectly when I am running it locally in Eclipse using the GAE plugin.
However, after deploying my app to the Google App Engine server, I run into EOFException when getting the data. Here is the client-side code I have:
(servername omitted for safety)
ClientResource con = new ClientResource("http://" + servername + "/sidin/event/1003");
con.setRequestEntityBuffering(true);
eventres = con.wrap(IEventResource.class);
ev = eventres.retrieve();
System.out.println("DONE getting event");

This code works fine on the local GAE instance but after deploying this to the server of Google I get the following error:
Unable to convert a [application/json,UTF-8] representation into an object of class be.ehb.iwt.sidin.appengine.core.Event

java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2775)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1909)
at org.restlet.ext.jackson.JacksonRepresentation.getObject(JacksonRepresentation.java:137)
at org.restlet.ext.jackson.JacksonConverter.toObject(JacksonConverter.java:218)
at org.restlet.service.ConverterService.toObject(ConverterService.java:167)
at org.restlet.resource.Resource.toObject(Resource.java:828)
at org.restlet.engine.resource.ClientInvocationHandler.invoke(ClientInvocationHandler.java:240)
at $Proxy7.retrieve(Unknown Source)
at Main.main(Main.java:59)

Any help or ideas are appreciated!


text:
Q: Best Method To Substract DataFrame I Have the two following DataFrame :
d1 = pd.DataFrame({'A':[1,2,3],'B':[10,20,30]})
   A   B
0  1  10
1  2  20
2  3  30

d2 = pd.DataFrame({'A':[1,3,2],'B':[10,20,30]})
   A   B
0  1  10
1  3  20
2  2  30

I would like substract this two DataFrame d1 - d2, expected result :
   A   B
0  1  0
1  3  -10
2  2  10

What is the best method to do that ?
Could someone help me ?

A: Method 1:
Using sort_values and reset_index to allign the index:
d2['B'] = d1['B'] - d2.sort_values('A')['B'].reset_index(drop=True)

Method 2:
Or using numpy.array with to_numpy so we can ignore the miss-allignment in the index after sorting:
d2['B'] = d1['B'] - d2.sort_values('A')['B'].to_numpy()

Method 3:
We can also map the A column of d1 to d2 and this way allign the B columns in both dataframes:
d2['B'] = d2['B'] - d2['A'].map(d1.set_index('A')['B'])

Output
   A   B
0  1   0
1  3 -10
2  2  10

A: We can also use DataFrame.merge:
d2['B']=d2.merge(d1,on='A').diff(-1,axis=1)['B_x']
print(d2)

   A     B
0  1   0.0
1  3 -10.0
2  2  10.0

A: You can set_index of each dataframe to A and then reset_index:
d2['B'] = (d1.set_index('A') - d2.set_index('A')).reset_index(drop=True)

print(d2)

Output:
   A   B
0  1   0
1  3 -10
2  2  10


text:
Q: Cannot install updates Ubuntu 14.04 I get a message which says "Package Managers cannot be resolved" when I attempt to install regular updates.
When I try to install from the Terminal with sudo apt-get update I get the following:
Reading package lists... Done
W: There is no public key available for the following key IDs:
1397BC53640DB551
W: Ignoring Provides line with DepCompareOp for package libreoffice-l10n
W: Ignoring Provides line with DepCompareOp for package libreoffice-l10n
W: Ignoring Provides line with DepCompareOp for package libreoffice-l10n
W: Ignoring Provides line with DepCompareOp for package libreoffice-l10n
W: Ignoring Provides line with DepCompareOp for package libreoffice-l10n
W: Ignoring Provides line with DepCompareOp for package libreoffice-l1

I can't seem to install updates anymore. What is the issue? I am using Ubuntu 14.04.5 LTS.


text:
Q: Accessing presentingViewController while dismissal animation of a Modal View Controller I have a button within the main view controller, that presents modally another view controller. I made a custom animation of main view controller being dimmed while modal vc slides up. But how can I make it go backwards while modal vc slides down (using dismiss)?
Using the tutorial on this site , I created protocols to access the presenting vc, but animation does not happen, it just instantly changes the opacity.
Also, if I put the animation code into the viewWillAppear of the presenting vc, it starts the animation only when the modal vc slides down all the way (disappears). I did not use regular show segue because I don't think that's the best way to get rid of a modal vc. If I am wrong, please correct me
This is the prepareForSegue in the presenting vc
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier{
        switch identifier {
        case "showSettings":
            let tempFrame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
            dimView = UIView(frame: tempFrame)
            dimView.backgroundColor = .black
            dimView.layer.opacity = 0
            self.view.addSubview(dimView)
            UIView.animate(withDuration: 0.5, animations: {
                self.dimView.layer.opacity = 0.4
            })
        default:break
        }
    }
    if let vc = segue.destination as? Dismissable
    {
        vc.dismissalDelegate = self
    }
}

Here is an IBaction, that dismisses the modal vc within itself.
    @IBAction func dismiss() {
    dismissalDelegate?.finishedShowing(viewController: self)
    UIView.animate(withDuration: 1.0, animations:{
        (self.dismissalDelegate as! ViewController).dimView.layer.opacity = 0.3
    })
}

A: This is just an example of how it could be done. Pretty sure it's far from perfect, but should work as a starting point. There is a lot of code there specific to an old project I had, but that can be stripped away.
final class ModalSeguePushStyle : UIStoryboardSegue
{
    override func perform() {
        let sourceVC = self.sourceViewController
        let destinationVC = self.destinationViewController
        var endPosition = destinationVC.view.frame
        var startPostition = destinationVC.view.frame

        startPostition.origin.x = startPostition.width

        if sourceVC.navigationController != nil
        {
            startPostition.origin.y = -44
            endPosition.origin.y = -44
        }

        destinationVC.view.frame = startPostition

        sourceVC.view.addSubview(destinationVC.view)

        UIView.animateWithDuration(0.3, animations: { () -> Void in
            destinationVC.view.frame = endPosition
            }) { (Bool) -> Void in
                self.sourceViewController.presentViewController(self.destinationViewController, animated: false, completion: nil)
        }
    }
}

final class ModalSeguePushStyleUnwind : UIStoryboardSegue
{
    func createMockView(view: UIView) -> UIImageView {
        UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.mainScreen().scale)

        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return UIImageView(image: image)
    }

    override func perform() {
        let sourceVC = self.sourceViewController
        let destinationVC = self.destinationViewController
        var endPosition = sourceVC.view.frame

        endPosition.origin.x += endPosition.width

        var bar:UIImageView?
        let mock = createMockView(destinationVC.view)

        if destinationVC.navigationController != nil
        {
            mock.frame.origin.y = 64
        }

        sourceVC.view.superview!.insertSubview(mock, atIndex: 0)

        if let b = destinationVC.tabBarController?.tabBar
        {
            bar = createMockView(b)
            bar?.frame = b.frame
            sourceVC.view.superview!.insertSubview(bar!, aboveSubview: mock)
        }

        UIView.animateWithDuration(0.3, animations: { () -> Void in
            sourceVC.view.frame = endPosition
            }) { (Bool) -> Void in
                sourceVC.dismissViewControllerAnimated(false, completion: { () -> Void in

                })
        }
    }
}


text:
Q: How to finish activity from ViewModel using Android's architecture components? I try to figure out how to in best way finish an Activity from ViewModel. I found the one way to do this using LiveData object and emitting "signal".
I have a doubt that this solution has a overhead. So is it right solution or I should use more accurate?
So go to example: let's suppose that in an app is an activity MainActivity and view model like below:
 class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val model = ViewModelProviders.of(this).get(MainViewModel::class.java)

        model.shouldCloseLiveData.observe(this, Observer { finish() })

    }
 }

and as a companion to the MainActivity is a MainViewModel like below:
class MainViewModel(app: Application) : AndroidViewModel(app) {

  val shouldCloseLiveData = MutableLiveData<Void>()

  fun someAction(){
    shouldCloseLiveData.postValue(null)
  }

}

A: I share your feelings that this solution does not look tidy for two reasons. First using a MutableLiveData object to signal an event is a workaround. No data is changed. Second exposing LiveData to the outside of the view model violates the principle of encapsulation in general.
I am still surprised about this ugly concept of android. They should provide an option to observe the view model instead of it's internal LiveData objects.
I experimented with WeakReferences to implement the observer pattern. This was unstable. In an unpredictable manner the referent of the WeakReference was lost (null), in wich cases it was not possible to call finish(). This was surprising as I don't think the activity is garbage collected while running.
So this is an partly answer by exclusion. The observer pattern implemented as WeakReference seems to be no alternative to your suggestion.
A wonder if it is legitimate implement the observer pattern by hard references, if I remove the references during onStop(), or onDestroy(). I asked this question here.

A: You can use a Single Event, as you can see the implementation here:
https://gist.github.com/JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af#file-event-kt
So, you don't have change the implementation of your activity
 class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val model = ViewModelProviders.of(this).get(MainViewModel::class.java)

        model.shouldCloseLiveData.observe(this, Observer { finish() })

    }
 }

The View Model will be like
class MainViewModel : ViewModel() {

  private val _shouldCloseLiveData = MutableLiveData<Event<Boolean>>()
  val shouldCloseLiveData: LiveData<Event<Boolean>> = _shouldCloseLiveData

  fun someAction(){
      _shouldCloseLiveData.postValue(Event(true))
  }

}

A: I had a similar problem: I had two activities (A and B) with its view models connected to an object (a table in a database): from an observable of a live data I had to navigate to another activity B (from A to B). The problem was, after invoking the new activity B, the observable in B change the value in the observed object.. activity A was still live,
 its live data call again the navigation code to B.. in an infinite loop.
After some research, I realized running a finish method does not mean the activity is really destroyed.
The solution is, in the observable code, remove from the live data the observables linked to specific activity.
liveData.removeObservers(activity);

I show it in the following snippet code. It's written in Java, but I think you have no problem to read it. With this, I solved my problem.
public class LockActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        mViewModel = ViewModelProviders.of(this).get(ConfigurationViewModel.class);

        LiveData<Configurazione> liveData = mViewModel.getConfiguration();
        liveData.observe(this, config-> {
            // this code will be executed even another activity is in front of
            // screen
            boolean validToken = (config.getToken()!=null);

            if (!tokenValido) {
                intent = LoginActivity.createIntent(this);
            } else {
                intent = MainActivity.createIntent(this);
            }

            // this line remove the observable, so even activity will be destroied with calm, it is not a problem, the code is no more executed
            liveData.removeObservers(this);
        });
    }

    ...
}

I think you can easily adapt to this situation to your code. I hope it helps.

A: I agree that there doesn't seem to be a good solution for this, and your suggestion does work pretty well. But I would suggest the following.
Since you are using Kotlin you could pass a function from your activity to the viewmodel like this:
ViewModel:
class MainViewModel(app: Application) : AndroidViewModel(app) {

    fun someAction(block: () -> Unit) {
        // do stuff
        block()
    }
}

Activity: here the button (and clicklistener) is used as an example but this can be anywhere in the activity's code.
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val model = ViewModelProviders.of(this).get(MainViewModel::class.java)

        myButton.setOnClickListener {
            model.someAction() {
                finish()
            }
        }
    }
}

the block function will essentially act as a callback.

A: one-lined method
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <import type="android.app.Activity" />

        <import type="androidx.databinding.DataBindingUtil" />

        <import type="androidx.databinding.ViewDataBinding" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{(v)->((Activity)(((ViewDataBinding)DataBindingUtil.findBinding(v)).lifecycleOwner)).finish()}"
            android:text="Exit" />
    </LinearLayout>
</layout>

or simplify the layout expression, move code to a helper class
public class DataBindingHelper {
    public static Activity findActivity(View v) {
        final ViewDataBinding binding = DataBindingUtil.findBinding(v);
        return binding != null ? (Activity) binding.getLifecycleOwner() : null;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <import type="com.xxx.settingitemmoretest.DataBindingHelper" />

        <import type="android.app.Activity" />

        <variable
            name="viewModel"
            type="com.xxx.settingitemmoretest.MainActivity.ViewModel" />

    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ToggleButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:checked="@{viewModel.shouldCloseLiveData}"
            android:onCheckedChanged="@{(v, p)-> p ? DataBindingHelper.findActivity(v).finish(): void}"
            android:text="Stub Useless Button"
            android:visibility="gone" />

        <ToggleButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:checked="@{viewModel.shouldCloseLiveData}"
            android:onCheckedChanged="@{(v, p)-> p ? ((Activity)context).finish(): void}"
            android:text="Stub Useless Button"
            android:visibility="gone" />
    </LinearLayout>
</layout>

or use a Binding Adapter
public class ViewGroupBindingAdapter {

    @BindingAdapter({"android:shouldClose"})
    public static void setShouldClose(ViewGroup viewGroup, boolean shouldClose) {
        if(shouldClose){
            final ViewDataBinding binding = DataBindingUtil.getBinding(viewGroup);
            if (binding != null) {
                ((Activity) binding.getLifecycleOwner()).finish();
            }
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="viewModel"
            type="com.xxx.settingitemmoretest.MainActivity.ViewModel" />

    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:shouldClose="@{viewModel.shouldCloseLiveData}"
        tools:context=".MainActivity">
     </LinearLayout>
</layout>


text:
Q: Text Editor java Swing actionListener save file Problem
I am making a text editor in java using Swing. I have a button which saves the file, using this method:
private void save() {
        if (savedAs) {
            try {
                PrintWriter fout = new PrintWriter(savedAsFile);
                fout.print(textArea.getText());
                fout.close();
                this.setTitle("Text Editor - " + fileName);
                saved = true;
            } catch (FileNotFoundException ex) {
                Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

The savedAs boolean is true only when a file is first created, otherwise it just saves it without opening the save as file chooser. When I use the button everything works, however when I call the save() method from the key bindings it saves but due to this method:
private void textAreaKeyTyped(java.awt.event.KeyEvent evt) {
    this.setTitle("Text Editor - *" + fileName);
    saved = false;
}

It adds the asterisk back on to the title. I want it to display it without the asterisk because it has been saved. How can I make sure that the textAreaKeyTyped method does not pick up input while the action listener is calling the save method.
Key bindings actionlistener:
public void initBindings() {
    textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(
            KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_DOWN_MASK), "actionMapKey");
    textArea.getActionMap().put("actionMapKey", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            save();
        }
    });
}

Cause
I think that the text area picks up input caused by the user typing CTRL + S, therefore puts the asterisk in the title.
Thanks!

A: I think you have two choices:

*

*Disregard the (Ctrl+s) key evt in your textAreaKeyTyped method. Maybe also disregard other key combinations that don't necessarily edit the text

*Or set the title (without the asterisk) after you have saved

A: The most robust way would be to keep a String lastSaved object.
When you do save() do:
lastSaved = textArea.getText();

Then in your textAreaKeyTyped() do:
boolean unchanged = textArea.getText.equals(lastSaved);

if (!unchanged) {
   // add *, enable save, etc
} else {
   // remove *, disable save, etc
}

This will have the added benefit that if a user reverses their changes their document will go back to a "not modified" state.
I would actually create a method updateSaveState() containing that code and have both save and the modified callback call updateSaveState(), removing the duplicated code there and putting all the logic for window title etc in one place.
I'd also be tempted to create an isModified() method that returns !textArea.getText.equals(lastSaved) and remove the saved flag completely. Anything that wants to know can just call isModified().
Note that in this case the edit will not be applied yet at the point the keyTyped is received. If you do a SwingUtilities.invokeLater to delay your processing until after the keypress has been processed that should fix this problem.


text:
Q: Mongo repairDatabase procedure I need to run a repairDatabase in mongo in order to reclaim some os disk space. Can anyone provide feedback on the following procedure: let me know if its correct, if I'm missing anything, if the steps are in order, etc.
The setup is a primary/secondary on separate servers. They are both about out of disk space. My plan is to repair the database on each one separately after the other completes. As I am out of disk space, I will be using an external block storage from my cloud provider to use as a repair path. Mongo is currently running via sudo service mongodb start. To complete this it seems that I'll run the following:

*

*On the primary I step down using rs.stepDown()

*I shutdown mongo using rs.shutdownServer() - Is this correct? For the next step it seems that I shouldn't run it if Mongo already has another instance running.

*On the primary I run mongod --config /etc/mongodb.conf --repair --repairpath PATH_TO_BLOCK_STORAGE

*When complete, do I need to copy the data in the repair path over to the original (/var/lib/mongodb)?

*Once back up, I restart Mongo using sudo service mongodb start

*I then wait for the oplogs to catch up and for the mongos to be in sync.

*Once they primary and secondary are in sync I then go onto mongodb-perf-02 and run rs.stepDown() so that mongodb-perf-01 is the primary again.

*Once complete I then repeat this on the secondary.

A: The solution to this issue was as follows:
Starting with the secondary:
Inside of Mongo I ran the following:
db.shutdownServer()
exit

On the command line:
rm -rf /var/lib/mongodb/*
sudo service mongodb start

It then takes a couple of hours to resync. Once resynced I did the following on the primary:
rs.status() //To make sure that the everything was synced
rs.stepDown(9200)
db.shutdownServer()
exit

On the command line I ran:
rm -rf /var/lib/mongodb/*
sudo service mongodb start

Then in Mongo I ran:
rs.status() //To make sure that everything was synced
rs.freeze(0) //To remove the re.stepDown(9200) lock

On the secondary I ran:
rs.stepDown()

Note: If possible, back up all of your data first.


text:
Q: Load objects from file to arrayList I wonder how I should do to read objects from a list if I don't know how many object there are? To save is easier because than I use the number of objects that I have in the ArrayList where I store all objects. Code like this:
// Save all customer object from customerList
for(int j=0; j < customerList.size(); j++) {
    outObjectStream.writeObject(customerList.get(j));
}

My thought was to use something similar to load all objects in the file and add them one after one to the ArrayList after it has been cleared. But as I wrote, it's not possible when I don't know the number of object inside the file. Any ideas how I can solve this in simple way?

A: Your design is flawed: You should be serializing the List to file, not each Customer object. Then you would just deserialize the whole List.
After deserializing you will have a new instance of the list. If you absolutely must load the customers into your list, use customerList.addAll(list);
All of the common Collections are themselves Serializable: Use and trust the JDK API!

A: You should use outObjectStream.writeObject(customerList); and let the ObjectInputStream do the job while reading it back.

A: Use ArrayList.add(). The number of elements is not required to be known beforehand.

A: To read objects from a file into a list you need to read it back in the opposite way you wrote it:
readObject(...)

rather than:
writeObject(...)

However, you really wouldn't normally want to save each object separately. One should either save the whole list at one as one object or ideally save it to a more readable format such as CSV, XML or JSON etc.
Writing and Reading objects gets tricky when you start changing your objects (adding new fields etc.).


text:
Q: bootstrap-sass in Rails 4 not showing the proper glyphicons I installed the bootstrap-sass Gem and tried to use some glyphicons but they're just not showing in the right way. Its looks like the browser is using replacements for the actual glyphicons but it doesn't give me any error message.
For most glyphicons I just get this one:
 and for the pencil for example i get this ✏. It looks like the browser can't find them but my stylesheets are getting loaded properly as far as I can tell. So is there maybe a problem in the gem that I have to fix?
My code looks like this:
application.css.scss
/*
 *= require jquery-ui
 *= require_tree .
 *= require_self
 */

@import "bootstrap-sprockets";
@import 'bootstrap';

application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require bootstrap-sprockets
//= require moment
//= require jquery_nested_form
//= require turbolinks
//= require ckeditor/init
//= require_tree .

index.html.erb
<%= link_to booking_path(booking), :class => 'btn btn-xs', :title => "#{ t('.show', :default => t('helpers.links.show')) }" do %>
    <%= glyph 'info-sign' %>
<%- end -%>

If you need any more information let me know please.
Edit1:
My code creates following html:

A: After specifying the Gem version of the rails-sass.gem and the bootstrap-sass.gem it finally works.
gem 'bootstrap-sass', '~> 3.3.5.1'
gem 'sass-rails', '~> 5.0.1'

A: Following documentation of bootstrap-sass, you have to remove  *= require_self and *= require_tree in you application.css.scss.

Then, remove all the *= require_self and *= require_tree . statements
  from the sass file. Instead, use @import to import Sass files.
Do not use *= require in Sass or your other stylesheets will not be
  able to access the Bootstrap mixins or variables.

So you can use @import
application.css.scss
/*
 *= require jquery-ui
 */

@import "bootstrap-sprockets";
@import 'bootstrap';


text:
Q: Error setting environment variables in python I am trying to use Bloomberg python API. I need to set BLPAPI_ROOT environment variable for this. I added,
export BLPAPI_ROOT="/home/user/Downloads/blpapi_cpp_3.6.3.1"
export PATH=$PATH:$BLPAPI_ROOT

to my .bashrc file and ran source .bashrc.
Now, when I open python shell and do,
print os.environ['BLPAPI_ROOT']

it gives me correct output. But when the same this runs inside the setup.py provided, it throws a
Traceback (most recent call last):
  File "setup.py", line 27, in <module>
    blpapiRoot = os.environ['BLPAPI_ROOT']
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'BLPAPI_ROOT'

What am I missing here ?
System :
Ubuntu 12.04
Python 2.7

A: I would try using it the following way:
import os
try:
    os.environ['BLPAPI_ROOT'] = "/home/user/Downloads/blpapi_cpp_3.6.3.1"
except EnvironmentError:
    sys.exit(1)

A: This is quite old, but for anyone searching, you can get around this by setting sudo to keep the environmental variable BLPAPI_ROOT, a la keep environmental variables using sudo.
sudo visudo

Then add:
Defaults env_keep +="BLPAPI_ROOT"

You can now run:
sudo python setup.py install

and it should work just fine.


text:
Q: Find an equation of the tangent to the curve $y=e^x$ that is parallel to $x-4y=1$ Here is the problem and my attempt at solution.

Did I do this question correctly? It took me a while and I'm unsure about a few of the steps.

A: The solution is correct.
I would not have written dy/dx instead of y' but this is more of a preference.


text:
Q: Samba setup problem After multiple unsuccessful attempts to configure samba shares and installing/uninstalling several times, Samba and system-config-samba will not install correctly. Please see output from installation attempt in terminal. Help appreciated.
> Setting up samba (2:4.6.7+dfsg-1ubuntu3.1) ...
Failed to preset unit: Unit file /etc/systemd/system/samba-ad-dc.service is masked.
/usr/bin/deb-systemd-helper: error: systemctl preset failed on samba-ad-dc.service: No such file or directory
Job for smbd.service failed because the control process exited with error code.
See "systemctl  status smbd.service" and "journalctl  -xe" for details.
invoke-rc.d: initscript smbd, action "start" failed.
● smbd.service - Samba SMB Daemon
   Loaded: loaded (/lib/systemd/system/smbd.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2018-02-11 11:34:46 EST; 3ms ago
     Docs: man:smbd(8)
           man:samba(7)
           man:smb.conf(5)
  Process: 26745 ExecStart=/usr/sbin/smbd $SMBDOPTIONS (code=exited, status=1/FAILURE)
 Main PID: 26745 (code=exited, status=1/FAILURE)

Feb 11 11:34:46 Mycenae systemd[1]: Starting Samba SMB Daemon...
Feb 11 11:34:46 Mycenae systemd[1]: smbd.service: Main process exited, code=exited, status=1/FAILURE
Feb 11 11:34:46 Mycenae systemd[1]: Failed to start Samba SMB Daemon.
Feb 11 11:34:46 Mycenae systemd[1]: smbd.service: Unit entered failed state.
Feb 11 11:34:46 Mycenae systemd[1]: smbd.service: Failed with result 'exit-code'.
dpkg: error processing package samba (--configure):
 subprocess installed post-installation script returned error exit status 1
Processing triggers for hicolor-icon-theme (0.17-1) ...
dpkg: dependency problems prevent configuration of system-config-samba:
 system-config-samba depends on samba; however:
  Package samba is not configured yet.

dpkg: error processing package system-config-samba (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                          Processing triggers for libc-bin (2.26-0ubuntu2.1) ...
Errors were encountered while processing:
 samba
 system-config-samba
E: Sub-process /usr/bin/dpkg returned an error code (1)


text:
Q: How add a wmts layer to leaflet map via geoserver i am working on making a web mapping project using leaflet and geoserver
in addition, i want to load a layer via the wmts where i need to define the url ,tilematrixSet,...
i have tried it with openlayers and it works just like this
        **var projection = ol.proj.get('EPSG:4326');
        var projectionExtent = projection.getExtent();
        var mapExtent = [-180.0,-90.0,180.0,90.0];
        var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570312E-5, 5.364418029785156E-6, 2.682209014892578E-6, 1.341104507446289E-6, 6.705522537231445E-7, 3.3527612686157227E-7];
        var matrixIds = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10', 'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'];
        var layer_wmts=new ol.layer.Tile({
            title:"My layer",
            source: new ol.source.WMTS({
                url: 'http://localhost:8080/geoserver/gwc/service/wmts?',
                layer: 'store_DB:layer',
                matrixSet: 'EPSG:4326',
                format: 'image/png',
                projection: projection,
                tileGrid: new ol.tilegrid.WMTS({
                    origin: ol.extent.getTopLeft(projectionExtent),
                    resolutions: resolutions,
                    matrixIds: matrixIds
                })
            })});**

My question is , how to do the same thing using leaflet


text:
Q: Excel Conditional formatting whole table color code I would like to create a condition for my whole table.
I have three categories (i.e R, G, B).
If the first column (example: A1) is R, the rest of the ROW (ex: B1:E1) should be colored with red. If G, then green, and if B, then Blue.
What I've done so far is I've selected my work area which is B1:E1, then clicked on conditional formatting > new rule > "Use a formula to determine which cell to format" (I'm using excel 2010). Then Typed this at the formula bar =SEARCH("R", $A$1)>0. It does change the color of B1:E1, however, I don't know how to do this for my whole table. If I select my whole table, and A1 is equal to R or G or B, the whole table change its color to whatever the value of A1. I also change my formula to =SEARCH("R", $A$1:$A$120)>0 which is the range of my table, still doesn't work. I've also created 3 conditions for each color with same formula (I just changed the letter R to G and B), still does not work.
Any ideas? Thank you in advance.

A: you were actually pretty close, just change
=SEARCH("R", $A$1)>0

to
=SEARCH("R", $A1)>0

so the conditional formatting rule will always look for "R" in the current row rather than row 1.
You should have this rule apply to the whole range that may be colored (I'm guessing B1:E120)
Also, you can make two rules for your other colors using the same approach.


text:
Q: Regarding empty initialisation of static array of class types When I ran static code analyzer QACPP, I got a warning. According to the QACPP documentation, initializing with {0} only works for built in types. To initialize an array of objects of type A, {} must be used. As below:
int i[5] = {0};  // Only works with built-in types.
A   a[5] = {};   // OK, works with both built-in and class types

Is this a standard C++ rule? According to this, an array of pointers to a class type must also be initialized with {}, right?
Does this statement:
A* ap[5] = {}

initialise the 5 pointers with NULL?
QACPP throws me a warning when I used A* ap[5] = {NULL}, though the code compiles and works perfectly even otherwise.

Additional
I think the warning was more because the array is static.
And here is the explanation I found in the documentation:

There are many problems with the use
  of objects with static storage
  duration, particularly those declared
  outside of functions. If many
  functions can access a static object
  this situation may become difficult to
  maintain. Also, in the case of
  multi-threaded applications it becomes
  necessary to protect with mutex each
  static object that can be accessed
  concurrently. It is therefore a good
  idea to limit the scope of a static
  object as much as possible, so that
  you know where such object is
  accessed.
Namespace or class objects with static
  storage duration will be initialised
  at the start of the program, before
  calling main(), and the order of
  initialisation is unspecified.
  Reliance on the order of
  initialisation may lead to objects
  being used before they are
  initialised. If an exception is thrown
  as a result of initialising a
  non-local object the program will
  immediately terminate.
Block scope objects with static
  storage duration will be initialised
  when the function is first called.
  Therefore, it is best to use the
  singleton pattern instead of namespace
  objects and static data members. This
  entails wrapping the object in a
  function as a local static object, and
  having the function return a reference
  to this object.

A: Yes, it is a standard rule. An array is an aggregate. The rules of initialization are explicitly mentioned in the standard for aggregates.

Does this statement: A* ap[5] = {}
  intialise the 5 pointers with NULL?

Yes

QACPP throws me a warning when I used A* ap[5] = {NULL}

What warning? Maybe the warning is that you initialized only the first element, and the others will stay NULL. Of course, it may be what you need. But then, the compiler is just warning you :)
I think this question and answer will be very interesting. What are Aggregates and PODs and how/why are they special?

A: IMHO, pointers it is built-in types too, so statement A* ap[5] = {NULL} is fine.


text:
Q: case map will not work in spark shell I have a code like this
val pop = sc.textFile("population.csv")
.filter(line => !line.startsWith("Country"))
.map(line => line.split(","))
.map { case Array(CountryName, CountryCode, Year, Value) => (CountryName, CountryCode, Year, Value) }

The file looks like this.
Country Name,Country Code,Year,Value
Arab World,ARB,1960,93485943
Arab World,ARB,1961,96058179
Arab World,ARB,1962,98728995
Arab World,ARB,1963,101496308
Arab World,ARB,1964,104359772
Arab World,ARB,1965,107318159
Arab World,ARB,1966,110379639
Arab World,ARB,1967,113543760
Arab World,ARB,1968,116787194

up until the .map {case}, I can print out by pop.take(10),
And I get Array[Array[String]].
But once the case is added, I'm getting
error: not found: value (all columns)

all columns meaning 4 different errors with CountryName, CountryCode, Year, Value, etc...
Not sure where I'm doing wrong.
The data is clean.

A: You need to use lowercase variable names in pattern matching. I.e:
.map { case Array(countryName, countryCode, year, value) => (countryName, countryCode, year, value) }

In Scala's pattern matching variables that are Capitalized as well as variables enclosed in backticks (`) are taken from outer scope and used as constants. Here is an example to illustrate what I'm saying:
Array("a") match {
  case Array(a) => a
}

Will match array with any string, while:
val A = "a"
Array("a") match {
  case Array(A) =>
}

will match only literal "a". Or, equivalent:
val a = "a"
Array("a") match {
  case Array(`a`) =>
}

will also match only literal "a".


text:
Q: Why is there an error with snapshot.data.length? I am trying to parse data from an API. For that, I am using FutureBuilder to list all the parsed data in a ListView.
I've performed a check for nullity of snapshot.data but I keep on getting this error in the segment snapshot.data.length, it says, The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').
I've a similar error in the snapshot.data[i] section, which says The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Here is my code's section of the same:
 body: Container(
        child: FutureBuilder(
          future: getData('hello'),
          builder: (context, snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("Loading"),
              );
            }else{
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: snapshot.data[i].partOfSpeech,
                    );
                  });
            }
          },
        ),
      ),

Here's getData(String s):
Future<List> getData(String s) async {
  var response = await http
      .get(Uri.https('api.dictionaryapi.dev', 'api/v2/entries/en_US/' + s));
  var jsonData = jsonDecode(response.body)[0];

  List<Data> data = [];

  for (var x in jsonData["meanings"]) {
    String definition = x["definitions"][0]["definition"];
    Data d = Data(x["partOfSpeech"], definition);
    data.add(d);
  }

  return data;
}

A: In continuation to this answer,
I found the solution to my problem. Apparently getData was not returning a List as intended. Instead, it was returning an Object.
Typecasting the Object to List solved the problem.
Here's the corrected code:
body: Container(
        child: FutureBuilder(
          future: getData('hello'),
          builder: (context, snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("Loading"),
              );
            }else{
              //typecasting Object to List
              var data = (snapshot.data as List<Data>).toList();
              return ListView.builder(
                  itemCount: data.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: data[i].partOfSpeech,
                    );
                  });
            }
          },
        ),
      ),

A: if u are using a new version of flutter (2.2.0 or above). first try adding a null check to the target ('!'). because of the null safety feature.
 body: Container(
    child: FutureBuilder(
      future: getData('hello'),
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          return Container(
            child: Text("Loading"),
          );
        }else{
          return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, i) {
                return ListTile(
                  title: snapshot.data[i].partOfSpeech,
                );
              });
        }
      },
    ),
  ),

then try specifying the FutureBuilder type to a List of Data type
 body: Container(
    child: FutureBuilder<List<Data>>(
      future: getData('hello'),
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          return Container(
            child: Text("Loading"),
          );
        }else{
          return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, i) {
                return ListTile(
                  title: snapshot.data[i].partOfSpeech,
                );
              });
        }
      },
    ),
  ),

A: Put 'AsyncSnapshot' before snapshot in the builder parameter.
builder: (context, AsyncSnapshot snapshot)

A: Since you are checking that snapshot.data is not null you can do the following to fix it.
 body: Container(
        child: FutureBuilder(
          future: getData('hello'),
          builder: (context, snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("Loading"),
              );
            } else{
              return ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: snapshot.data[i]!.partOfSpeech,
                    );
                  });
            }
          },
        ),
      ),

A: What you need to look at is the result of getData('hello')
Apparently, it does not return something that has a length property.


text:
Q: Is there a faster lm function I would like to get the slope of a linear regression fit for 1M separate data sets (1M * 50 rows for data.frame, or 1M * 50 for array). Now I am using the lm() function, which takes a very long time (about 10 min).
Is there any faster function for linear regression?

A: lmfit in the package Rfast is even faster than .lm.fit.
The only drawback is that it does not work when the design matrix does not have full rank.

A: speedlm from speedglm should do it as it works on large data sets.

A: Yes there are:

*

*R itself has lm.fit() which is more bare-bones: no formula notation, much simpler result set

*several of our Rcpp-related packages have fastLm() implementations: RcppArmadillo, RcppEigen, RcppGSL.
We have described fastLm() in a number of blog posts and presentations.  If you want it in the fastest way, do not use the formula interface: parsing the formula and preparing the model matrix takes more time than the actual regression.
That said, if you are regressing a single vector on a single vector you can simplify this as no matrix package is needed.

A: Since 3.1.0 there is a .lm.fit() function. This function should be faster than lm() and lm.fit().
It's described and its performance is compared with different lm functions here - https://rpubs.com/maechler/fast_lm.


text:
Q: Hibernate C3P0 not clearing closed connection from pool ISSUE
I am having a problem with Hibernate and C3P0 not closing and discarding a "closed" connection when the connection has been closed by the database itself and has been idle for too long.
I have a daily Quartz job that is supposed to query up some data from an Informix database, process it and persist the results to an Oracle database. The query I am executing takes about 15 minutes to complete since it has to go through about 20+ million records in Informix (it's as optmized as I can make it to be).
However, immediately after the query is done I get the following warnings and errors:
[c3p0] A PooledConnection that has already signalled a Connection error is still in use!
[c3p0] Another error has occurred [ java.sql.SQLRecoverableException: Closed Connection ] which will not be reported to listeners!
java.sql.SQLRecoverableException: Closed Connection
...
org.springframework.orm.jpa.JpaSystemException: java.sql.SQLException: ORA-02396: exceeded maximum idle time, please connect again

I know this error happens because Oracle closed the connection due to IDLE_TIME limit being reached, but what I don't understand is, why isn't C3P0 or Hibernate not clearing this connection from the pool? Also, why is the connection being created even before it's used for the first time in the lifetime of the job?
CONFIG
Some info on my configuration and application

*

*Spring Boot 1.4.2.RELEASE

*Hibernate 5.1.0.Final

*Java 1.7

Here is part of my persistence.xml file with the persistence unit information:
<persistence-unit name="oracle_PU" transaction-type="RESOURCE_LOCAL">
...
    <properties>
        <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
        <property name="javax.persistence.jdbc.url" value="@url@"/>
        <property name="javax.persistence.jdbc.user" value="@username@"/>
        <property name="javax.persistence.jdbc.password" value="@password@"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" />
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
        <property name="hibernate.hbm2ddl.auto" value=""/>
        <property name="hibernate.jdbc.batch_size" value="30" />
        <property name="hibernate.order_inserts" value="true" />
        <property name="hibernate.order_updates" value="true" />
        <property name="hibernate.jdbc.batch_versioned_data" value="true" />
        <property name="current_session_context_class" value="thread" />
        <property name="hibernate.connection.release_mode" value="after_transaction"/>

        <!-- Connection Pooling settings -->
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.max_size" value="20" />
        <property name="hibernate.c3p0.min_size" value="0" />
        <property name="hibernate.c3p0.acquire_increment" value="1" />
        <property name="hibernate.c3p0.idle_test_period" value="30" />
        <property name="hibernate.c3p0.max_statements" value="0" />
        <property name="hibernate.c3p0.timeout" value="120" />
    </properties>
</persistence-unit>

<persistence-unit name="informix_PU" transaction-type="RESOURCE_LOCAL">
...
    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.informix.jdbc.IfxDriver"/>
        <property name="javax.persistence.jdbc.url" value="@informix.url@"/>
        <property name="javax.persistence.jdbc.user" value="@informix.username@"/>
        <property name="javax.persistence.jdbc.password" value="@informix.password@"/>
        <property name="hibernate.show_sql" value="false"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.InformixDialect"/>
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
        <property name="hibernate.jdbc.batch_size" value="30"/>
        <property name="hibernate.order_inserts" value="true"/>
        <property name="hibernate.order_updates" value="true"/>
        <property name="hibernate.jdbc.batch_versioned_data" value="true"/>
    </properties>
</persistence-unit>

This is the database-context.xml where I declare my EntityManager factory beans
<tx:jta-transaction-manager/>

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath:META-INF/persistence.xml</value>
        </list>
    </property>
</bean>

<bean id="entityManagerFactory" primary="true" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaProperties">
        <props>
            <prop key="openjpa.ReadLockLevel">none</prop>
            <prop key="openjpa.Log" >DefaultLevel=INFO, Runtime=TRACE, Tool=INFO, SQL=TRACE</prop>
        </props>
    </property>
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="oracle_PU"/>
</bean>

<bean id="entityManagerFactoryInformix" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaProperties">
        <props>
            <prop key="openjpa.ReadLockLevel">none</prop>
            <prop key="openjpa.Log" >DefaultLevel=INFO, Runtime=TRACE, Tool=INFO, SQL=TRACE</prop>
        </props>
    </property>
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="informix_PU"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

I've even added a c3p0.properties files with the following properties:
c3p0.preferredTestQuery=SELECT 1 FROM dual
c3p0.testConnectionOnCheckin=false
c3p0.testConnectionOnCheckout=true
c3p0.unreturnedConnectionTimeout=180

This is part of my quartz-context.xml file with the Quartz job configuration
<bean id="dataProcessorBean" class="com.my.package.DataProcessor" />

<bean name="jobDataProcessor" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="com.my.package.QuartzDataProcessor" />
    <property name="jobDataMap">
        <map>
            <entry key="dataProcessor" value-ref="dataProcessorBean" />
        </map>
    </property>
    <property name="durability" value="true" />
</bean>

<bean id="cronDataProcessor" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="jobDataProcessor" />
    <property name="cronExpression" value="0 0 4 * * ? " />
</bean>

<bean  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="autoStartup" value="true" />
    <property name="jobDetails">
        <list>
            <ref bean="jobDataProcessor" />
        </list>
    </property>

    <property name="triggers">
        <list>
            <ref bean="cronDataProcessor" />
        </list>
    </property>
</bean>

CLASSES
Here is the Java class the Quartz job calls for processing data
public class QuartzDataProcessor extends QuartzJobBean {

    private DataProcessor dataProcessor;

    @Override
    protected void executeInternal(JobExecutionContext arg0) {
        dataProcessor.execJob();
    }

    public DataProcessor getProcesador() {
        return dataProcessor;
    }

    public void setProcesador(DataProcessor dataProcessor) {
        this.dataProcessor = dataProcessor;
    }
}

public class DataProcessor {
    private static final Logger LOG = LoggerFactory.getLogger(DataProcessor.class);

    @Autowired
    private OracleDao oracleDao;

    @Autowired
    private InformixDao informixDao;

    public void execJob() {
        LOG.info("Starting the job");
        try {
            processData();
        } catch (Exception ex) {
            LOG.error("Something went wrong while executing the job", ex);
        }
        LOG.info("Job finished");
    }

    private void processData() throws Exception {
        long init = System.currentTimeMillis();
        List<String> listData = informixDao.getListData();
        // The exception is thrown before getting to this line
        LOG.info("Informix time: " + (System.currentTimeMillis() - init) + " ms");
        // process the data
        oracleDao.insertProcessedData(listProcessedData);
        LOG.info("Time total: " + (System.currentTimeMillis() - init) + " ms");
    }
}

@Component
@Transactional(noRollbackFor = NoResultException.class)
public class InformixDao {

    private static final Logger LOG = LoggerFactory.getLogger(InformixDao.class);

    @Autowired
    @Qualifier(value = "entityManagerFactoryInformix")
    private EntityManagerFactory emFactoryInformix;

    public List<String> getListData() {
        EntityManager em = emFactoryInformix.createEntityManager();
        try {
            em.clear();
            return em.createQuery("SELECT t FROM InformixTable t", String.class).getResultList();
        } catch (NoResultException ex) {
        } catch (Exception ex) {
            LOG.error("Could not get list of Informix data", ex);
        } finally {
            try {
                em.close();
            } catch (Exception ignored) {
            }
        }
        return null;
    }
}

I've been trying with different C3P0 options and even tried using plain old JdbcTemplate for the long-running Informix query thinking that could be the cause, but the timeout is still thrown regardless. I've also tried using JdbcTemplate for the Oracle transactions and that seems to work, but that would defeat the purpose of using Hibernate and C3P0.
Any help or suggestion is greatly appreciated!


text:
Q: Understanding gradients on Riemannian Manifolds I am trying to understand how the gradients are defined on a Riemannian manifold, at least in a shallow way. The wikipedia definition is as the following:

What I understand from this is, given a manifold $M$ with the metric $g$, the gradient of function $f$on the manifold $M$ is the vector field $(\nabla f)_x$ which produces for every $x \in M$ and $X_x \in T_xM$ a scalar $(\partial_{X}f)(x)$. According to the definition here, $(\partial_{X}f)(x)$ is equal to the directional derivative of $f$ at the direction of $X$, both evaluated at $x$. So, this should be $\nabla f(x)^TX_x$, if I understand correctly. But this understanding seems trivial; then the required $\nabla f$ will be just the evaluation of the function $f$'s gradient at each $x \in M$. And the last definition of $\partial_{X}f$ with the coordinate chart $\phi$ seems to tell something else; so I am confused here. What is the actual, correct interpretation of this definition?

A: I will try to convince you that there is no difference with what happens in "normal" calculus. Let's then start from $\mathbb{R}^n$.
In $\mathbb{R}^n$ you have a natural inner product (the Euclidean product) which is given (in the orthonormal basis $\hat x, \hat y, \hat z$) by
$\left<a,b\right> = a^t b$. This product defines an isomorphism A: $\mathbb{R}^n \rightarrow (\mathbb{R}^n)^*$ such that $A: a\mapsto \langle a,\cdot \rangle$.
To every function $f:\mathbb{R}^n\rightarrow \mathbb{R}$ you can associate its differential $df$, which is the map $df: v\mapsto D_v(f)$ (directional derivative). Using the isomorphism $A$ given by the eucledian product, you can find a vector (called gradient of f, denoted by $\nabla f$), such that $\left<\nabla f , v\right> = df(v) = D_v(f)$. In the orthonormal basis $\hat x, \hat y, \hat z$, this means $(\nabla f)^k = \frac{\partial f}{\partial x^k} $. This last formula is not true, however, in an arbitrary basis.
Note that the differential of f is the more general object, while its gradient exists thanks to the Euclidean scalar product.
On a Riemaniann manifold, the procedure is exactly the same! The differential is the more general object, defined in exactly the same way: $df(v) = v(f)$ (since $v$ is the generalization of a directional derivative!) and so is the gradient: $g(\nabla f, v) = df(v)$.

A: Think of it in terms of properties we want the gradient to have. Properties come first, and formulas are then written out so that they satisfy those properties.
The essential properties of the gradient vector field $\nabla f$ are:

*

*$\nabla f$ is perpendicular to the level sets of $f$

*$|\nabla f|$ is proportional to the rate of increase of $f$

The differential $df$ takes a vector field $X$ and returns a measurement of how quickly $f$ is increasing along the flow line of $X$. If $\nabla f$ has the properties above, then we should be able to obtain this measurement by taking the dot product of $X$ with the gradient field $\nabla f$. So the defining property of the vector field $\nabla f$ is that, for all vector fields $X$, we have:
$$ g(\nabla f, X) = df(X) = \partial_Xf $$

A: The following is another, equivalent, point of view: the idea that a gradient gives you the direction of "steepest ascent".
The gradient applied to a function $f$ at $p$ should produce a tangent vector that in some sense maximizes the local change in $f$ when walking in the direction of the tangent vector. In order for this to make sense, we have to constrain the length of the vector (otherwise the target of this maximization is unbounded). But this is exactly what the Riemannian metric does, which is a way of specifying at each point a scalar product $\langle v,w\rangle_p=g_p(v,w)$ for any two vectors $v,w$ at $p$, in a way that depends smoothly on the point. We may then define a steepest direction of $f$ at $p$ as the unit vector that maximizes the directional derivative of $f$ at $p$
$$sf_p = \arg \max_{\langle v,v\rangle_p=1} vf= \arg \max_{\langle v,v\rangle_p=1} df_p(v), \tag1$$
and then we define the gradient as a scaled version that also takes into account how fast $f$ actually changes in that direction. We therefore multiply $sf_p$ by the directional derivative of $f$ in the direction of $sf_p$:
$$\text{grad} f_p=df_p(sf_p)\;sf_p.$$
It may then be shown that $\text{grad} f_p$ satisfies
$$\langle \text{grad} f_p, v \rangle_p = df_p(v) \tag2$$
for every tangent vector $v$. By the non-degeneracy of the scalar product, this then uniquely defines $\text{grad} f_p$ in terms of the inverse metric tensor. In order to show (2), we may write down a Lagrangian for the constrained optimization problem (1):
$$\mathcal{L}(v)=df_p(v)+\lambda(\langle v,v\rangle_p-1),$$
where $\lambda$ is some Lagrange multiplier. The first variation of this reads
$$\mathcal{L}(v+\delta v)-\mathcal{L}(v)=df_p(\delta v)+2\lambda \langle v,\delta v\rangle_p+\text{higher-order terms} = 0, \quad \forall\delta v,$$
from which we obtain (by setting $v=\delta v=sf_p$) that $-2\lambda=df_p(sf_p)$ and then by plugging this back into the first variation for $v=sf_p$,
$$\langle \text{grad} f_p, \delta v \rangle_p=df_p(sf_p)\langle sf_p, \delta v \rangle_p = df_p(\delta v), \quad \forall\delta v.$$


text:
Q: Angular : How to show md-error which is inside md-input-container from code without considering Validators inside the attached formcontrol? I have an input field
<md-input-container class="margin-top-little">
    <input mdInput placeholder="{{placeholder}}" [(ngModel)]="value" (blur)="onBlur()" name="{{name}}" [formControl]="validator"
    (change)="onChange()" (focus)="onfocus()">
    <md-error *ngIf="validator.hasError('minlength') || validator.hasError('maxlength') ||  validator.hasError('allowed_values') || service_error_type">
        Please enter a valid {{placeholder}}
    </md-error>
    <md-error *ngIf="validator.hasError('required') || service_error_missing">
        {{placeholder}} is required
    </md-error>
</md-input-container>

I want to show the 2nd md-error with the help of an event or any flag but not the value inside the ngModel .
How to do this ?
Main motive is to map field level errors coming from services to the respective fields .

A: The md-error is created and destroyed by the *ngIf structural directive. If you want to show or hide an <md-error></md-error> or any <> </> HTML element, you would want to put your condition in the *ngIF statement (e.g. *ngIf = " event === true ")
<md-error *ngIf="validator.hasError('required') || service_error_missing">
</md-error>

to
<md-error *ngIf="condition">
</md-error>

or more generally:

where condition is a function, variable, or statement which returns (or equates) to either "true" or "false"


text:
Q: JavaScript For Loop continuing beyond condition I have a function that takes an array of coordinates and creates a path for use with Google Maps API. Worked great, but suddenly it seems to have decided to continue looping beyond the condition and I'm not sure what to do or why it's doing it. I've looked at it over and over again and it looks right to me, so Idk...
parseCoordinates = function (
    coordinates) {
    var paths = [];

    for (var i = 0, coordinate = null; coordinate = coordinates[i], i < coordinates.length; i++) {
        console.log(i);

        paths.push(new google.maps.LatLng(coordinate.latitude, coordinate.longitude));
    }

    return paths;
},

In the test case I'm using the coordinates array has seven elements and when I output i to the console it starts from zero and reaches six, but then decides to continue after that which ends up causing null reference errors. Can someone point me to what's happening? Thanks in advance!

A: You set coordinate = coordinates[i] before you check i < coordinates.length.

A: Never mind, got it. Turns out my JSON data was containing two null coordinates objects at the end which is why it was throwing the error trying to loop them. I just need to do a null check before I use the for loop, which is what I was doing everywhere else I was using the for loops which is probably why I wasn't getting errors. Sorry to waste everyone's time.


text:
Q: count days in each month between two dates (both dates available) excluding weekend and PH I would like to calculate the number of days excluding PH and weekends for 2 specific date by month.
Eg,the image shows the result I want.
Result I want
I tried using the formula I found below.
IFERROR(IF($A2>EDATE(C$1,1),0,MAX(,IFERROR(IF(MIN($B2,MIN(EDATE(C$1,1),$B2))=C$1-1,0,MIN($B2,MIN(EDATE(C$1,1),$B2))),"")-MAX($A2,C$1))),0)
Its similar to what I want. However the formula include weekend and PH. And If the start and end date are the same, it will count as zero.
Excel - count days in each month between two dates (both dates available)
Please help..


text:
Q: Cutting edge online WYSIWYG editor wanted What is the most efficient WYSIWYG editor that can be used on a blog?
I'm looking for something like the one in Gmail, but I'm really annoyed that sometimes the cursor gets stuck in some invisible wrapper div tag or after selecting and deleting a part of text the cursor jumps to the end of the whole block.
The ideal editor doesn't have to be backwards compatible and may use emerging technologies. I don't have anything specific in my mind but I've heard about the Bespin project and wondered maybe the canvas tag could be of use. Or perhaps Silverlight or Flash, I don't know.
I'd use this editor to create and maintain fairly simple HTML document structures with hyperlinks, images, headers and lists. The ability to assign CSS classnames to nodes would be a plus. Speed and responsiveness is also a major factor.
Clarification:
I'd love to see an editor which doesn't rely on contentEditable, since as Pekka has mentioned that is the source of the annoyances.

A: Interesting question.
The most evolved HTML-based WYSIWYG editor in my opinion is CKEDitor. It has a clean API, the documentation is not perfect yet but it's getting there, and usability is very nice -  although it sometimes still tends to show the problems you describe, but this is often down to the browser's "editable HTML" engine and something you will come across in every HTML/JS based WYSIWYG component.
Interested to see whether there is something more evolved in the Flash or Silverlight world.

A: Doing a HTML editor using something like Canvas would be far more complex than Bespin. In Bespin the text is always using the same font, there are no html or css rules to respect, it's just text that you can know beforehand how it should be rendered. And you have to keep in mind that doing something like Bespin isn't easy.
In HTML there are images, tables, lists, different font-sizes, floating elements... so doing all the rendering using Canvas would be a huge initial task, and after that you have to add the editing features to select the text, images, ...
Flash does support a limited set of HTML, it's really poor in that aspect so you can't expect a good HTML editor based on that.
With regards to Silverlight, I don't know its current state, but at the very first moment that they release something "usable", you can expect several such editors to popup like there are hundreds of little js editors that just use contentEditable.
The difference between all the js editors that claim to be fast, small or simple and the most widely used like CKEditor and TinyMCE, is that these ones work hard to fix the problems due to each browser and that's why they aren't so small, but on the other hand you have much better control of the output and the behavior while editing. In that aspect these editors are implementing lots of the features by themselves, contentEditable might be used to provide the basic keyboard functionality, but each day more features are implemented in js instead of relying on the native behavior of contentEditable.

A: http://tinymce.moxiecode.com/ I like this editor for simple web apps its pretty familiar to the users as well. TinyMCE is really easy to setup and is pretty fast, even in IE6. You can also set custom classes in a drop down and assign them to text, just like you would bold text which is nice. Very customizable as well.
As far as a Canvas text editor I haven't really seen one besides the Bespin project.

A: I use http://www.wymeditor.org/ for a project. It differs slightly from other alternatives. It does not give you all the font-size, font-color, bold etc. etc. But only lets you build the structural part of a page like: list, em, strong, table, headline etc.
You can of cause extend it with a set of classes. But the idea is that you for example can't change a columns (in a table) width but you can define a class which have the specific width, border etc.
It therefore don't permit the user to do unintended things :) which is both good and bad. Good: The pages conform to a specified style, clean, tight. Bad: If the user wants something unexpected, you have to add a class to do it.
It do rely on the content editable BUT it abstracts the browser away. So the code generated is fully standard and XHTML strict by the way. Take the demonstration to see it :)
I know you're looking for a plugin based editor but this statement:
"I'd use this editor to create and maintain fairly simple HTML document structures with hyperlinks, images, headers and lists. The ability to assign CSS classnames to nodes would be a plus. Speed and responsiveness is also a major factor."
Can Wymeditor easily manage.


text: Q: Is the set of all non-zero real number bounded? Define the set of all non-zero real number as $A = \{a \in \mathbb{R} : a \neq 0\}$. So the obvious gap of the set is the point zero. I am a bit confused by the definition of upper/lower bound, because a tutor of my class said this set $A$ is bounded. Does this count as a lower bound or upper bound?


text:
Q: Filter generates a topology compatible with the vector structure of $X$. Let X be a Haudorff Topological Vector Space.
Define the following relation on the collection of all Cauchy filters on X:
$F ∼_R G$ ⇔ $∀U$ nbhood of the origin in $X, ∃A ∈ F, ∃B ∈ G$ s.t. $A − B ⊂ U$.
We define $\hat{X}$ as the quotient of the set of all c.f. on X w.r.t. the equivalence relation (R).
Hence, an element $\hat{x}$ of $\hat{X}$ is an equivalence class of c.f. on $X$ w.r.t. (R).
Let $U$ be an arbitrary nbhood of the origin in X. Define
$ \hat{U}:= \{ \hat{x} ∈  \hat{X} : U ∈ F  \text{ for some } F ∈  \hat{x}\}$.
and consider the collection
$ \hat{B} := \{ \hat{U}: U \text{ nbhood of the origin in } X \}$.
The filter generated by $ \hat{B} $ fulfills all the properties in this theorem

A filter $F$ of a vector space $X$ over $K$ is the filter of
  neighbourhoods of the origin w.r.t. some topology compatible with the vector
  structure of X if and only if

*

*The origin belongs to every set $U ∈ F$

*$∀U ∈ F, ∃V ∈ F$ s.t. $V + V ⊂ U$

*$∀U ∈ F, ∀λ ∈ K$ with $λ \ne 0$ we have $λU ∈ F$

*$∀U ∈ F$,$U$ is absorbing.

*$∀U ∈ F, ∃V ∈ F$ s.t. $V ⊂ U$ is balanced.

How can I check this?
I try to do this but cant because I am new reader in Topological Vector spaces.
Please help me.