text:
Q: UITableView accumulates tens of cells after row insertions/updates from NSFetchedResultsController In our app we have a controller that manages a UITableView (NOT a UITableViewController in this case). This controller is both the table view's delegate and data source. It is also the NSFetchedResultsController's (hereafter FRC) delegate. We register a custom nib with a consistent reuse identifier for our table view cells. After reloading 8 cells several times, we see about 40 UITableViewCells inside the UITableView (UITableViewWrapperView, technically speaking) on the View Debugging -> Capture View Hierarchy screen.
Why might UITableView not be removing cells from its view hierarchy? This unfortunately presents a huge performance issue after a few batches of the aforementioned updates where scrolling on the UITableView lags very noticeably.
Our FRC->UITableView code:
didChangeObject:
        switch type {
        case NSFetchedResultsChangeType.Insert:
            self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
            sectionsToReload.addIndex(newIndexPath!.section)
        case NSFetchedResultsChangeType.Delete:
            self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
            sectionsToReload.addIndex(indexPath!.section)
        case NSFetchedResultsChangeType.Update:
            self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
            sectionsToReload.addIndex(indexPath!.section)
        case NSFetchedResultsChangeType.Move:
            self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
            self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
            sectionsToReload.addIndex(indexPath!.section)
            sectionsToReload.addIndex(newIndexPath!.section)
        }

didChangeSection:
    let indexSet = NSIndexSet(index: sectionIndex)
    switch type {
    case NSFetchedResultsChangeType.Insert:
        self.tableView.insertSections(indexSet, withRowAnimation: UITableViewRowAnimation.Fade)
        self.insertedSections.addIndexes(indexSet)
    case NSFetchedResultsChangeType.Delete:
        self.tableView.deleteSections(indexSet, withRowAnimation: UITableViewRowAnimation.Fade)
        self.deletedSections.addIndexes(indexSet)
    default:
        return
    }

controllerWillChangeContent:
    self.tableView.beginUpdates()
    self.insertedSections = NSMutableIndexSet()
    self.deletedSections = NSMutableIndexSet()
    self.sectionsToReload = NSMutableIndexSet()

controllerDidChangeContent:
    for section in self.insertedSections {
        if self.sectionsToReload.containsIndex(section) {
            self.sectionsToReload.removeIndex(section)
        }
    }
    for section in self.deletedSections {
        if self.sectionsToReload.containsIndex(section) {
            self.sectionsToReload.removeIndex(section)
        }
    }

    if shouldReloadSectionsWhenRowsChange {
        self.tableView.reloadSections(self.sectionsToReload, withRowAnimation: .None)
    }

    self.tableView.endUpdates()

UITableViewDataSource methods
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = self.fetchedResultsController.sections {
        return sections[section].numberOfObjects
    } else {
        return 0
    }
}

public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = self.fetchedResultsController.sections {
        return sections.count
    } else {
        return 0
    }
}

public override func getCount() -> Int {
    if let count = self.fetchedResultsController.fetchedObjects?.count {
        return count
    }
    return 0
}

public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    guard let cell = self.tableView.dequeueReusableCellWithIdentifier(cellNibIdentifier) else {
        Rlog.e(self, "Failed to dequeueReusableCellWithIdentifier:\(cellNibIdentifier)")
        return UITableViewCell()
    }
    self.configureCell(cell, indexPath: indexPath)
    return cell
}


text:
Q: Android Tests Compiling using Maven I have been bashing my head against this for days now so I thought its time to ask.
I have an android project and a android-test project. I can run my tests in eclipse and it all works great.
So now I am moving on to use these tests through maven so I can use them for CI.
Anyway long story short I can't get maven to compile/run them. I have looked at all the examples provided with the android-maven-plugin to no avail.
Main POM.
<groupId>com.xxx.x_android_finder</groupId>
<artifactId>x_Android_Finder</artifactId>
<version>1.0.2</version>
<packaging>apk</packaging>
<name>xxxx</name>

<dependencies>
   <!--    <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.1</version>
          <scope>test</scope>
    </dependency> -->
    <dependency>
        <groupId>com.google.android</groupId>
        <artifactId>android</artifactId>
        <version>4.0.1.2</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
<groupId>com.google.android.maps</groupId>
        <artifactId>maps</artifactId>
        <version>15_r2</version>
        <scope>provided</scope>
    </dependency>

   <dependency>
        <groupId>com.actionbarsherlock</groupId>
        <artifactId>library</artifactId>
        <version>4.1.0</version>
        <type>apklib</type>
        <exclusions>
            <exclusion>
                <groupId>com.google.android</groupId>
                <artifactId>support-v4</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.actionbarsherlock</groupId>
        <artifactId>plugin-maps</artifactId>
        <version>4.1.0</version>
    </dependency>

    <dependency>
        <groupId>net.hockeyapp.android</groupId>
        <artifactId>HockeySDK</artifactId>
        <version>2.0.2</version>
        <type>apklib</type>
    </dependency>

    <dependency>
        <groupId>com.codeslap</groupId>
        <artifactId>android-facebook</artifactId>
        <version>1.6</version>
        <scope>compile</scope>
    </dependency>

     <dependency>
       <groupId>org.twitter4j</groupId>
       <artifactId>twitter4j-core</artifactId>
       <version>[3.0,)</version>
   </dependency>

</dependencies>

<repositories>
    <repository>
        <id>jakewharton</id>
        <url>http://r.jakewharton.com/maven/release/</url>
    </repository>
    <repository>
        <id>codeslap</id>
        <url>http://casidiablo.github.com/codeslap-maven/repository/</url>
    </repository>

</repositories>

<build>

    <plugins>

        <plugin>
            <groupId>com.jayway.maven.plugins.android.generation2</groupId>
            <artifactId>android-maven-plugin</artifactId>
            <version>3.2.0</version>
            <extensions>true</extensions>

            <configuration>
                <!-- replace resources with target specific -->

                <renameManifestPackage>${customerPackage}</renameManifestPackage>
                <resourceOverlayDirectory>${customerResources}</resourceOverlayDirectory>

                 <sign>
                    <debug>false</debug>
                 </sign>
                  <manifest>
                    <versionCodeAutoIncrement>true</versionCodeAutoIncrement>
                  </manifest>
                   <zipalign>
                    <inputApk>${project.build.directory}/${project.build.finalName}.apk</inputApk>
                    <outputApk>${project.build.directory}/x_Android_Finder.apk</outputApk>
                 </zipalign>

               <proguard>
                    <skip>true</skip>
                </proguard>

                <sdk>
                    <!-- platform or api level (api level 4 = platform 1.6)-->
                    <platform>17</platform>
                </sdk>
                <assetsDirectory>${project.basedir}/${customerAssets}</assetsDirectory>
                <resourceDirectory>${project.basedir}/res</resourceDirectory>
            </configuration>

            <executions>
                <execution>
                    <id>manifestUpdate</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>manifest-update</goal>
                    </goals>
                </execution>
                <execution>
                    <id>alignApk</id>
                    <phase>package</phase>
                    <goals>
                        <goal>zipalign</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jarsigner-plugin</artifactId>
            <version>1.2</version>
            <executions>
                <execution>
                    <id>signing</id>
                    <goals>
                        <goal>sign</goal>
                    </goals>
                    <phase>package</phase>

                    <inherited>true</inherited>
                    <configuration>
                        <archiveDirectory></archiveDirectory>
                        <includes>
                            <include>target/*.apk</include>
                        </includes>
                        <keystore>../certificates/xxx.keystore</keystore>
                        <storepass>xxxx</storepass>
                        <keypass>xxxx</keypass>
                        <alias>csl</alias>

                    </configuration>
                </execution>
            </executions>
        </plugin>

        <!-- <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <configuration>
              <skip>true</skip>
            </configuration>
       </plugin> -->

    </plugins>
</build>

Test pom
    <artifactId>x_Android_Finder_Test</artifactId>
    <packaging>apk</packaging>
    <version>1.0.0</version>
    <name>xxxxx</name>

    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android-test</artifactId>
            <version>1.5_r3</version>
          </dependency>

        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>4.0.1.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.android.maps</groupId>
            <artifactId>maps</artifactId>
            <version>15_r2</version>
            <scope>provided</scope>
        </dependency>

       <dependency>
            <groupId>com.actionbarsherlock</groupId>
            <artifactId>library</artifactId>
            <version>4.1.0</version>
            <type>apklib</type>
            <exclusions>
                <exclusion>
                    <groupId>com.google.android</groupId>
                    <artifactId>support-v4</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.actionbarsherlock</groupId>
            <artifactId>plugin-maps</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>com.connectionservices.csl_android_finder</groupId>
            <artifactId>Csl_Android_Finder</artifactId>
            <type>apk</type>
            <version>1.0.2</version>
        </dependency>

        <dependency>
            <groupId>com.connectionservices.csl_android_finder</groupId>
            <artifactId>Csl_Android_Finder</artifactId>
            <scope>provided</scope>
            <type>jar</type>
            <version>1.0.2</version>
        </dependency>

         <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.8.1</version>
              <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.hockeyapp.android</groupId>
            <artifactId>HockeySDK</artifactId>
            <version>2.0.2</version>
            <type>apklib</type>
        </dependency>

        <dependency>
            <groupId>com.codeslap</groupId>
            <artifactId>android-facebook</artifactId>
            <version>1.6</version>
            <scope>compile</scope>
        </dependency>

         <dependency>
           <groupId>org.twitter4j</groupId>
           <artifactId>twitter4j-core</artifactId>
           <version>[3.0,)</version>
       </dependency>

        <dependency>
            <groupId>com.jayway.android.robotium</groupId>
            <artifactId>robotium-solo</artifactId>
            <version>3.6</version>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>oss.sonatype.org-jayway-with-staging</id>
            <url>http://oss.sonatype.org/content/groups/jayway-with-staging/</url>
        </repository>

        <repository>
             <id>jakewharton</id>
            <url>http://r.jakewharton.com/maven/release/</url>
         </repository>

         <repository>
             <id>codeslap</id>
             <url>http://casidiablo.github.com/codeslap-maven/repository/</url>
         </repository>

    </repositories>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>

            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>

                <configuration>
                    <sdk>
                        <platform>15</platform>
                    </sdk>

            <test>

                        <createReport>true</createReport>

                    </test>

                </configuration>
                <extensions>true</extensions>

            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.13</version>

              </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jarsigner-plugin</artifactId>
                <!--   <version>1.2</version> -->
                <executions>
                    <execution>
                        <id>signing</id>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                        <phase>package</phase>

                        <inherited>true</inherited>
                        <configuration>
                            <removeExistingSignatures>true</removeExistingSignatures>

                            <archiveDirectory></archiveDirectory>
                            <includes>
                                <include>target/*.apk</include>
                            </includes>
                            <keystore>../certificates/xxxx.keystore</keystore>
                            <storepass>xxx</storepass>
                            <keypass>xxxx</keypass>
                            <alias>csl</alias>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

the test projects are held under main/java/... in the test project
When I compile i use mvn clean test
the errors its throwing up are
ERROR] /Users/aidenfry/AndroidHSF(trunknew)/x_Android_Finder_Parent/x_Android_Finder_Test/src/main/java/com/xxxxxxx/x_android_finder_test/FinderActivityTest.java:[27,7] cannot access junit.framework.TestCase
[ERROR] class file for junit.framework.TestCase not found
[ERROR] public class FinderActivityTest extends ActivityInstrumentationTestCase2<FinderActivity> {
[ERROR] /Users/aidenfry/AndroidHSF(trunknew)/x_Android_Finder_Parent/x_Android_Finder_Test/src/main/java/com/xxxx/xx_android_finder_test/FinderActivityTest.java:[39,8] cannot find symbol
[ERROR] symbol  : variable super
[ERROR] location: class

I can provide more but they are all similar to this, seems it cant find the Junit lib? But i already have that in the dependancioes.
If anyone can help/hints for me to sort out this mess It would be very much appreciated!

A: In case someone has the same issue, and wants to execute real Android Unit Tests instead of normal JUnit Tests:
You need to uncomment
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
      <!-- scope is compile, not test! -->
      <scope>compile</scope>
</dependency>

the junit dependency and use normal scope (compile), not test!
Hope that helps.

A: Ok, so here is how i did it.
I originally had my test cases in a seperate module / eclipse project. This seemed to be buggering up my stuff.
Moved the class into the main application project under src/main/test this now fixed all my issues thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Collection class of specific type containing basic features Every time i use some class e.g Artikel as follows:
Public Class Artikel
   Property ID As Integer
   Property Nummer As String
   Property Name As String
   Property Position As Integer
End Class

For such classes i would like to have collection class. The features i would like to have is like:
--> Add (passing Artikel object)
--> Remove (passing Artikel object)
--> Sort entire collection (based on Position property desc/asc)
--> Compare two Artikels (pass by Artikels and tell by which property has to be compared)
--> Check whether two artikels equals
--> Every added artikel has to be marked by Key (so maybe dictionary)? <key><Artikel>
--> Remove Artikel (passing by Key index)

Could somone from you there tell me or even better provide example of collection class pass those requirments?
EDIT: Startup:
Artikel's collection:
Option Strict On
Public Class Articles

Public Property collection As Dictionary(Of Integer, Artikel)

Sub New()
    'Initiate new collection
    collection = New Dictionary(Of Integer, Artikel)
End Sub

   'Add new Artikel to collection
    Public Function AddToCollection(ByVal artikel As Artikel) As Boolean
        collection.Add(artikel)
        Return True
    End Function

    'Remove specific Artikel
    Public Sub RemoveFromCollectionByArtikel(artikel As Artikel)
        If Not IsNothing(collection) Then
            collection.Remove(artikel)
        End If
    End Sub

   'Get collection
   Public Function GetCollection() As Dictionary(Of Integer, Artikel)
        Return collection
    End Function

   'Sort collection by property position
   Public Sub SortByPosition()
        collection.Sort()
    End Sub

    'Remove specific sending keys and then reorder them
    Public Sub RemoveAllMarkedAsDeleted(keys As List(Of Integer))
        '-- Check whther anything has been marked as deleted
        If keys.Count > 0 Then
            For Each row In keys
                collection.Remove(row)
            Next
            ReorderKeys()
    End If

    'Reorder all Artikels in collection
    Private Sub ReorderKeys()
        Dim newCollection As New Dictionary(Of Integer, Artikel)
        Dim index As Integer = 0
        For Each collitem In collection
            newCollection.Add(index, collitem.Value)
            index += 1
        Next
        collection.Clear()
        collection = newCollection
    End Sub

End Class

Artikel class (additionally i implemented IComparable to be able to sort)
Option Strict On
     Public Class Artikel
         Implements IComparable(Of Artikel)
           Property ID As Integer
           Property Nummer As String
           Property Name As String
           Property Position As Integer

        Public Function CompareTo(pother As Artikel) As Integer Implements IComparable(Of Artikel).CompareTo    'we can sort because of this
            Return String.Compare(Me.Position, pother.Position)
        End Function
        Public Shared Function FindPredicate(ByVal partikel As Artikel) As Predicate(Of Artikel)
            Return Function(partikel2 As Artikel) partikel.ID = partikel2.ID
        End Function
        Public Shared Function FindPredicateByUserId(ByVal partikel As String) As Predicate(Of Artikel)
            Return Function(partikel2 As Artikel) partikel = partikel2.ID
        End Function
    End Class

A: Create your class
Public Class Artikel
   Property ID As Integer
   Property Nummer As String
   Property Name As String
   Property Position As Integer

   sub new (_ID as integer, _Nummer as string, _Name as string, _Position as integer)
      ID = _ID
      Nummer = _Nummer
      Name = _Name
      Position = _Position
   End Sub
End Class

Create another class which holds a private list and add sub routines to it
 Public Class ArtikelList
      Private _List as new list (of Artikel)

      Public sub remove(Key as integer)
         Dim obj as Artikel = nothing
         for each x as Artikel in _List
            if x.ID = Key then
               obj = x
               exit for
            end if
         Next
         if not isnothing(obj) then
               _List.remove(obj)
          end if
      End sub

      Sub Add(obj as Artikel)
         Dim alreadyDeclared as boolean = falsse

         for each x as Artikel in _List
            if x.ID = obj.id then
               alreadyDeclared = true
               exit for
            end if
         Next
          if not AlreadyDeclared then
               _List.add(obj)
          Else
             'Somehow inform the user of the duplication if need be.
          end if

      End sub
    End Class

Then use your list class.
dim L as new ArtikelList
L.add(new Artikel(1280, "AFKforever!", "Prof.FluffyButton", 96))
L.remove(1280)

I only added one sub routine as an example. I hope it helps but feel free to ask for more example routines.
This can also be done by creating a class which inherits from the list class, exposing all list class functionality but by using this method you are forced to create every subroutine that will be used. This way you only use routines that you created exclusively for the purpose Artikel objects handling.
Check if two Artikels are equal
Public Class Artikel
       Property ID As Integer
       Property Nummer As String
       Property Name As String
       Property Position As Integer

       sub new (_ID as integer, _Nummer as string, _Name as string, _Position as integer)
          ID = _ID
          Nummer = _Nummer
          Name = _Name
          Position = _Position
       End Sub
    End Class

Public Overrides Overloads Function Equals(obj As Object) As Boolean

      If obj Is Nothing OrElse Not Me.GetType() Is obj.GetType() Then
         Return False
      else
        dim _obj as artikel = obj
        if Me.ID = _obj.ID then
           Return true
        else Return False
      End If

   End Function

End Class

Use it like:
If x.equals(y) then
    'they have the same ID
end if

A: Parts of it look good, but I would ultimately do it a bit differently.  First, consider overloads on the item class to make them easier to create and default initialization:
Public Class Article
    Property ID As Integer = -1
    Property Key As String = ""
    Property Name As String = ""
    Property Position As Integer = -1
    Property PubDate As DateTime = DateTime.Minimum

    Public Sub New()

    End Sub
    ' whatever minimum data a new item requires
    Public Sub New(k As String, n As String)
        Key = k
        Name = n
    End Sub
    ' full initialization:
    Public Sub New(k As String, n As String, pos As Int32,
                    pubDt As DateTime)
       ...
   End Sub
End Class

I added some properties for variety, and I suspect "Nummer" might be the "Key" mentioned in the OP, but whatever it is, I would add it to the Article class as that name, if it has some importance.
You might need a simple ctor for serialization (???). Some of these will find and use a Private parameterless constructor, but your code will be forced to use one of the overloads in order to provide some minimum level of data when a new one is created.

You probably do not need IComparable.  That is typically for more complex comparisons, such as multiple or complex properties.  An example is a carton or box:
If (width = Other.Width) AndAlso (height = Other.Height) Then
    Return 0
ElseIf (width = Other.Height) AndAlso (height = Other.Width) Then
    Return 0
End If

Plus more gyrations to work out which is "less" than the other.  One reason you dont need it, is because If Art1.Postion > Art2.Postion is trivial.  The other reason in your case, is because a Dictionary cannot be sorted.
Rather than a Dictionary, an internal List would work better for some of the things you describe but still allow you to have it act like a Dictionary to the extent you need it to.  For this, I might build it using ICollection<T>:
Public Class ArticleCollection
    Implements ICollection(Of Article)

Pressing Enter after that line will add all the required methods including:
Public Sub Add(item As Article) Implements ICollection(Of Article).Add

Public Sub Clear() Implements ICollection(Of Article).Clear

Public Function Contains(item As Article) As Boolean Implements ICollection(Of Article).Contains

Public ReadOnly Property Count As Integer Implements ICollection(Of Article).Count

Public Function Remove(item As Article) As Boolean Implements ICollection(Of Article).Remove

It remains completely up to you how these are implemented. It also doesn't rule out adding methods such as RemoveAt(int32) or RemoveByKey(string) depending on what you need/how it will be used.   One of the benefits to ICollection(Of T) is that it includes IEnumerable which will allow use for each loops (once you write the Enumerator): For Each art In Articles
To emulate a dictionary to allow only one item with a specific property value:
Public Class ArticleCollection
    Implements ICollection(Of Article)

    Private mcol As List(Of Article)
    ...
    Public Sub Add(item As Article) Implements ICollection(Of Article).Add
        ' check for existing key
        If KeyExists(item.Key) = False Then
            mcol.Add(item)
        End If
    End Sub

You can also overload them:
' overload to match Article ctor overload
Public Sub Add(key As String, name As String)
     If KeyExists(key) = False Then
        ' let collection create the new item
        ' with the minimum required info
        mcol.Add(New Article(key, name))
    End If
End Sub

If you add an Item Property, you can index the collection ( Articles(3) ):
Property Item(ndx As Int32) As Article
    Get
        If ndx > 0 AndAlso ndx < mcol.Count Then
            Return mcol(ndx)
        Else
            Return Nothing
        End If
    End Get
    Set(value As Article)
        If ndx > 0 AndAlso ndx < mcol.Count Then
            mcol(ndx) = value
        End If
    End Set
End Property

' overload for item by key:
Public Property Item(key As String) As Article

An Add method and an Item Property will be important if the collection will display in the standard NET CollectionEditor.
There are several ways to implement sorting.  The easiest is to use linq in the code which uses your collection:
Articles = New ArticleCollection
' add Article items
Dim ArticlesByDate = Articles.OrderBy(Function(s) s.PubDate).ToList()

Where PubDate is one of the Article properties I added.  The other way to handle sorting is by the collection class returning a new collection (but it is so simple to do, there is little need for it):
Friend Function GetSortedList(bSortAsc As Boolean) As List(Of Article)
    If bSortAsc Then
        Return mcol.OrderBy(Function(q) q.PubDate).
                ThenBy(Function(j) j.Position).ToList()
    Else
        Return mcol.OrderByDescending(Function(q) q.PubDate).
                ThenByDescending(Function(j) j.Position).ToList()
    End If
End Function

Whether it implements ICollection(Of T), inherits from ICollection(Of T) or does work off a Dictionary depends entirely on what this is, how it is used and whatever rules and restrictions there are (including if it will be serialized and how).  These are not things we know.
MSDN has an article on Guidelines for Collections which is excellent.


text:
Q: RxSwift limited Debounce to fire periodic events using additional time flag I am in need of a debounce functionality in RxSwift which if certain time expires emits the even regardless of debounce condition.
e.g.
SETUP: debounce = 0.2 secs & periodic = 5 secs.
Case 1 (Needed) > If a user continuously pressing a button, i would like to receive an even if he doesn't stops continuous taps but only after a certain interval. This will give throttle like behaviour with periodic limit.
Case 2 (Works) > If user presses button every 0.5 sec, debounce limit won't be an issue and user will get his events every 0.5 secs.
Case 3 (Works) > User doesn't press anything, no event fired.
While debounce provides Case 2 & 3. Achieving case 1 is tricky.

Posting some clarification > My use case is not special panic button clicks. I know that throttle should be enough for it. Use case is more of a continuous stream of data. If data comes continuously in debounce limit (say 200ms), i want to have a throttle behaviour giving response say every 2 seconds but if data is not coming very frequently say every 0.5 secs, i want data to be sent immediately by observable for UI to be more responsive.

A: It sounds to me that you are describing the throttle operator, not the denounce operator.
In general, you should use throttle when dealing with button clicks/triggers and denounce when dealing with data input.


text:
Q: Schema for send image in xmpp i would like to know which is the xmpp schema for send images or data.
And I would like to know if is possible send an image from your iphone inside a xmpp message and how ??
Thanks !!


text:
Q: Symfony2 rendering checkbox choice field unchecked I'm displaying a choice field in Symfony 2.0.4 with multiple checkboxes. Symfony always displays the first checkbox as checked and I would like to disable this behavior. I've tried setting the underlying entity's field to an empty array before building the form but this didn't have any effect. Is this a glitch in the Symfony version or is there a special way of achieving this?
EDIT:
By choice field with multiple checkboxes I mean a choice field having the expanded and multiple options set to true.

A: It seems that this was my stupid mistake. I was overriding the form theme and in the choice_widget_expanded block I was adding the checked flag for the first element of the choice array.

A: You need to add in your form class :
$builder->add('yourField', 'choice', array(
    'choices'     => $choices
    'required'    => false,
    ....
));

You can find more information in the ChoiceField type documentation http://symfony.com/doc/2.0/reference/forms/types/choice.html
Also check that you don't have any JavaScript which is checking the first value.


text:
Q: WPF datagrid inline editing I have starting to work with WPF and C# to help designed a small app for my company.  The goal is to be able to look up a part number, display all possible matches in a grid view and finally be able to update the parts in the grid.  The data is being pull from a single table on a SQL table.
I have pulled most of my code from other examples and gotten it to work. However I am confused on the next steps in order to get editing to work.
Code is as follows:
XML CODE
<Window x:Class="SQLtests.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="387" Width="783">

<Grid>
    <DataGrid Name="Master" Margin="10,130,10,10" CanUserAddRows="True" CanUserDeleteRows="True" IsTabStop="True" IsReadOnly="False" ItemsSource="{Binding}"/>
    <Button x:Name="Search" Content="Search"  Height="19" Margin="140,30,535,311" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top" Click="okSreach"/>
    <TextBox x:Name="PartNumber" HorizontalAlignment="Left" Height="19" Margin="10,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"/>

</Grid>

C# Code
namespace SQLtests
{

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }
    private void okSreach(object sender, RoutedEventArgs e)
    {
       string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
       string CmdString = string.Empty;
        using (SqlConnection con = new SqlConnection(ConString))
        {
            CmdString = "SELECT PartsNumber, NewGMNumber, Interchange1 FROM Rydell.Master WHERE NewGMNumber = " + "'" + PartNumber.Text + "'";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("Master");
            sda.Fill(dt);
            Master.ItemsSource = dt.DefaultView;
        }
    }

}
}

Everything works fine as I am able to search for a part, however I have read some many different sources and ideas that getting inline editing to work is confusing.
I could be over my head too, as I am just starting out, any good books,websites, etc for C# and WPF is welcome

A: I would rather use a ObservableCollection to bind instead of a datatable,
and I found in WPF,
it makes life a lot easier if you use a control like a ListView or even a ListBox,
where you have a lot more freedom to customize the control to your desire.
Be sure to use INotifyPropertyChanged, a basic sample would be like this.....
And what you would like to use with the listview would be a datatemplete or CellTemplte of the gridview.
Here is a example for you http://www.wpf-tutorial.com/datagrid-control/custom-columns/
^-^


text:
Q: How to work around different padding sizes between browsers I consider myself a novice at CSS 3 so i'd appreciate any help you can give.
The situation is that i'm creating a dashboard for our test automation suite.
So far i've created a decent looking template, however the navigation bar has a different padding appearance across browsers. In IE and Chrome it looks fine, however in firefox 28 the padding seems to add an extra pixel to the bottom of the nav bar item.
Here is my CSS:

Here is my HTML:

Bristol Automation

            Global Automation Hub

            UK Automation

             UK QA Home

            Automated Test Finished

            Test Name: Agent_Registration_TestClass

            Result Status: Pass

            Start Time: 12:24

            EndTime: 12:25

            Elapsed Time: 0 Seconds

            Run by: JohnN

            Machine: BRSL1960

Test Results For: Agent_Registration_TestClass

Expand/Collapse All

  Up to Top ^^

TestResults v0.85 written by Bristol Automation Team
 Click here to visit our sharepoint!

I understand that I can use some css to detect if the browser is firefox and change the padding based on that, but that didnt seem to work. From what I can see the following block of code is where the issue is:
    #nav li a {
        padding-left: 10px;
        padding-right: 10px;
        padding-top: 10px;
        padding-bottom: 10px;
        text-decoration: none;
        color: #FFFFFF;
        background-color:#752864;
        font-family: 'Verdana', 'Lucida Grande', Sans-Serif;
    }

Any help would be much appreciated. Cheers.
UPDATE
Here is the JS fiddle http://jsfiddle.net/Vwr3x/

A: You need to add css reset or normalize.css to neutralize browser default styling
reset.css
/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

Normalize.css
Add either of these two at the beginning in your style.css file.

A: You need to use browser specific CSS to get accurate results on all browsers.
I mean not for all but the one you are getting wrong, use mozilla, internet explorer or google chrome specific css.

A: if you want I have a jQuery script to detect all the navigators, then the script add a class to a body with the name of the browser.


text:
Q: Join table very slow how can I fix it? I have problem with my query because of joining a lot of table.   So I would like to find another ways beside this query but the result it the same. My code is bellow :
SELECT
    tblReturn.CountryID,
    tblReturn.ShopLocationId,
    tblReturn.ReturnID,
    tblVoucherDetail.VoucherDetailID,
    tblVoucherDetail.VoucherNo,
    tblVoucherDetail.BarcodeVoucher,
    tblReturn.DateTimeStamp AS DateTimeReturn,
    tblClient.ClientNoString,
    tblSaleDetail.BarCode,
    tblReturnType.Description,
    tblReturn.Reason,
    tblSale.DateTimeStamp AS DateTimeSale,tblReturn.Status
FROM
(
    tblSale
    INNER JOIN
    (
        (
            (
                tblReturn
                INNER JOIN
                (
                     tblVoucherDetail
                     INNER JOIN
                     tblVoucher ON tblVoucherDetail.VoucherID = tblVoucher.VoucherID
                ) ON tblReturn.ReturnID = tblVoucher.ReturnID
            )
            INNER JOIN
                 tblClient
            ON
                 tblVoucherDetail.ClientNo = tblClient.ClientNo
        )
        INNER JOIN
            tblSaleDetail
        ON
            tblReturn.SaleDetailIDOrigin = tblSaleDetail.SaleDetailID)
        ON
            (tblSale.SaleID = tblSaleDetail.SaleID)
        AND
            (tblSale.ShopLocationID = tblSaleDetail.ShopLocationID))
        INNER JOIN
            tblReturnType
        ON
            tblReturn.ReturnTypeID = tblReturnType.ReturnTypeID
        WHERE
            tblReturn.CountryID = 7
        AND
            tblReturn.ShopLocationID = 4
       ORDER BY
            tblVoucherDetail.VoucherDetailID DESC

How can I adjust it?

A: Use explain and indexes. http://dev.mysql.com/doc/refman/5.0/en/explain.html. Using indexes will enable the database to optimize the search

A: While optimizing your query is good (indexes are your friend), there is another approach you might consider with this many joins.  "Denormalize" your database and create a table that has exactly the data you want.  This involves updating your data both in the original table and in the new "report" table you create.  There are obvious disadvantages to this -- (1) more space used, (2) you have to either write code to keep your data in sync, or you have to rebuild your "report" table on a periodic basis, (3) subtle bugs can happen if you data does get out of sync.
However, sometimes denormalizing is the simplest and best solution to nasty join performance problems.


text:
Q: Vue.js pushing object to array changes every element in the array to be identical I am building a Vue.js application that allows a user to make and view a feed of products.
I have a parent element NewFeed which allows a user to have a name for their feed, and then allows a user to push products into this feed.
The child element NewProduct allows the user to input data for the product, then pushes into the parent's products array. I have noticed that every time I push a new product into the array, every element in the array is changed to be the value of the new element.
How do I change this so that the elements remain as they were originally input?
NewFeed (Parent Element):
Vue.component('NewFeed', {
  data: function() {
    return {
      newFeed: {
        name: "",
        products: []
      },
    }
  },
  methods: {
    addProduct: function(p) {
      p.id = this.pushedProducts;
      this.newFeed.products.push(p);
    }
  },
 template: `

      Feed Name:
      <input id='feedNameInput' v-bind:value='newFeed.name' v-on:input='newFeed.name = $event.target.value'/>

      <ViewProduct v-for='product in newFeed.products' :key='product.id'></ViewProduct>
      <NewProduct v-on:pushProduct='addProduct($event)'></NewProduct>
      <button v-on:click='pushNewFeed'>Add Feed</button>

`});

NewProduct (Child Element)
Vue.component('NewProduct', {
  data: function() {
    return {
      newProduct: { id: 0 }
    }
  },
  methods: {
    addProduct: function() {
       this.$emit('pushProduct', this.newProduct);
       this.newProduct.id++;
    }
  },
  template: `

      Product Name:
      <input id='productNameInput' v-bind:value='newProduct.name' v-on:input='newProduct.name = $event.target.value'/>

      Original Price:
      <input id='productOriginalPriceInput' v-bind:value='newProduct.originalPrice' v-on:input='newProduct.originalPrice = $event.target.value'/>

      New Price:
      <input id='productNewPrice' v-bind:value='newProduct.newPrice' v-on:input='newProduct.newPrice = $event.target.value'/>

      Discount Amount:
      <input id='productDiscountAmount' v-bind:value='newProduct.discountAmount' v-on:input='newProduct.discountAmount = $event.target.value'/>

      Upload Image:
      <input type='file' accept='image/*' id='productImage' v-bind:file='newProduct.imageFile' v-on:change='newProduct.imageFile = $event.target.files[0];'/>

      <button v-on:click="addProduct">Add Product</button>

`});

A: This happens because the child component emits the same object reference each time (JavaScript objects are passed by reference).  So all of the emitted objects are the same object.  You have to create a brand new object each time.  Maybe the simplest way to do that is to reset the child object right after you emit:
addProduct: function() {
   this.$emit('pushProduct', this.newProduct);
   const id = this.newProduct.id + 1;
   this.newProduct = { id }
}


text:
Q: Extjs Grid - How to add class name to tr in column CheckboxModel I have a gridpanel and CheckboxModel column
in function
renderer:function(value,metaData,record,rowIndex,colIndex,store,view){
      if (record.data.check ==0) {
         metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
         return '

';
      }else {
         metaData.trCls = Ext.baseCSSPrefix + 'x-grid-row-selected'; // not working
         return '

';
      }
}

how to add class name to tr to make checkbox selected. I try below code but not working
 metaData.trCls = Ext.baseCSSPrefix + 'x-grid-row-selected'; // not working

How to do that thanks
EDIT
here is my example code for my problem http://jsfiddle.net/wj9GM/. How to fix that thanks

A: Ext.onReady(function() {

      // Create a dummy store
    var store = new Ext.data.ArrayStore({
        fields: ['id', 'name', 'check'],
        data: [
           [1, 'profile 1', 1],
           [2, 'profile 2', 1],
           [3, 'profile 3', 0]
        ]
    });

    var selModel = Ext.create('Ext.selection.CheckboxModel', {
        checkOnly: true,
        mode: 'MULTI'
    });

    var grid = new Ext.grid.GridPanel({
        width: 400,
        height: 200,
        store: store,
        loadMask: true,
        selModel: selModel,
        columns: [
            {header: 'Id', sortable: true, dataIndex: 'id' },
            {header: 'Name', sortable: true, dataIndex: 'name'}
        ],
        listeners: {
            'afterlayout': function(){
                var records = this.getView().getRecords(this.getView().getNodes());
                var result = new Array();
                Ext.Array.each(records, function(record, index, records) {
                    if(record.get('check', 1)) {
                        result.push(record);
                    }
                });
                selModel.select(result);
            }
        },
        renderTo: Ext.getBody()
    });
});


text:
Q: What's the matter?
A (1). What's wrong?      A (2). What's the matter?
  B. The internet doesn't work.

In A (1), 'what' is beyond doubt a subject. But in A (2), Which is the subject: 'what' or 'the matter'? Can it be clearly designated? Or ambivalent?

A: If you take 's to be a normal copular, then what is a subject-complement.
e.g.

What is a car?
  What is your name?

Both a car and your name are subjects, similarly to how subject-auxiliary inversion works.
However I would argue that such analysis is incorrect, as "what's the matter?" has become idiomatic and simply means "what's wrong?". So you can, in fact, argue that the matter in that instance can be seen as adjectival.
This is because you can say:

What is [the matter/wrong] is that the house is on fire.

But not

*What is a car is a fridge on wheels.

And thus what is a subject again.


text:
Q: awk process own field value I have a CSV file formatted like this:
Postcode,Count,Total
L1 3RT,20,345.65

I am summing the counts and totals by Postcode using awk, however I'd like to do this for the first portion of a postcode (ie L1, thus combining the values for L1 3RT and L2 4XW). Sample data and existing awk command shown below.
CM1 4QR,979,32950.8
CM1 4QS,2,145.14
CM13 1DL,115,3771

AWK line
awk 'BEGIN { FS = "," } ; {sums[$1] += $2; totals[$1] += $3} END { for (i in sums) printf("%s,%s,%i\n", i, sums[i],totals[i])}' coach.csv

I would like the output to be
CM1,981,33095.94
CM13,115,3771

A: The following works:
awk -F'[ ,]' '
{
  sums[$1] += $3;
  totals[$1] += $4;
}
END {
  for (i in sums)
    printf("%s,%i,%i\n", i, sums[i],totals[i]);
}' coach.csv

It uses two delimiters, the comma and space.  It works for your sample input, but won't for more complex input that has spaces elsewhere.

A: You can use multiple delimiters in awk. Please try this
awk -F'[, ]' '{sums[$1] += $3; totals[$1] += $4} END {for (i in sums) printf("%s,%.2f,%.2f\n", i, sums[i], totals[i])}' coach.csv


text:
Q: Poisson-Nearst-Planck equations with normal distribution as initial condition I am having a hard time trying to think of this model:
Imagine you have a normal distribution of +q charges in 2D
$$\rho(r,t=0)=\rho_0 e^{-\frac{r^2}{\sigma_0^2}} $$
where $\sigma_0$ is the width of the distribution. How does the distribution change over time?
To model this, Nearst-Planck equation can be written as
$$\frac{\partial }{\partial t}\rho(t,r)=D[\nabla^2\rho(r,t)-\beta \nabla\cdot(\textbf{E}(r,t)\rho(r,t))]$$
with D as the diffusion coefficient and $\beta=(kT)^{-1}$ as the reciprocal of the thermodynamic temperature. The $\textbf{E}$ field is due to the charge distribution itself. But
$$\textbf{E}(r,t)=-\nabla  \phi(r,t) $$
so the equation is rewritten as
$$\frac{\partial }{\partial t}\rho(t,r)=D[\nabla^2\rho(r,t)+\beta \nabla\cdot(\nabla  \phi(r,t)\rho(r,t))]$$
Additionally, due to Poisson's equation
$$\nabla^2\phi=-\frac{\rho(r,t)}{\epsilon}$$
It is known that for non-charged-particles ($\phi=0$), the solution for the same initial condition (normal distribution) is:
$$ \rho(r,t)=\frac{\rho_0 \sigma_0^2}{\sigma_0^2+4Dt}e^{-\frac{r^2}{\sigma_0^2+4Dt}}$$
which is just a Gaussian with a width $(\sigma_0^2+4Dt)^{\frac{1}{2}}$.
Is it possible to try to approximate the solution or simulate numerically the distribution over time for charged particles?
Thanks for all the insights!

A: It seems to me that the problem you will run into is not that you have a $\rho^2$ term (easily addressed since $\rho(x_i)\to\rho_i\implies\rho(x_i)^2=\rho_i^2$; consider, for instance, the Burgers' equation), but that you will end up with a term like $\nabla\phi\cdot\nabla\rho$, so the potential will need to be tracked and evolved, which means you have a pair of diffusion problems to solve at each step, which is time-consuming computationally--though this means it should be solvable numerically.
Essentially, your simulation would be something like,

*

*Initialize $\rho(r,\,0)$

*Compute $\phi(r,\,0)$ using the Poisson equation

*Evolve $\rho(r,\,\mathrm{d}t)$ using the Nearst-Planck equation

*Continue from #2 until required $t$ is satisfied.

Presumably you would use escaping boundaries, but whatever boundaries you choose would be applied with each step.
In Cartesian coordinates, the discretization scheme should be pretty straight-forward, e.g., for 1D you'd have,
$$
\frac{\rho_{i}^{n+1}-\rho_{i}^n}{\mathrm{d}t}=D\left[\frac{\rho_{i+1}^n+\rho_{i-1}^n-2\rho_i^n}{\mathrm{d}x^2}-\frac{\beta}{\varepsilon}\left(\rho_i^n\right)^2+\frac{\beta}{4}\frac{\phi_{i+1}-\phi_{i-1}}{\mathrm{d}x}\cdot\frac{\rho_{i+1}^n-\rho_{i-1}^n}{\mathrm{d}x}\right].\tag{1}
$$
Though, if you intend on using the radial form, you may run into the issue of dividing by zero with the diffusion term. This can be mitigated by other means, as I discuss in this post of mine. But I otherwise don't see any issues that could arise in solving the system.
I used Eq (1) with a couple different parameters of $\rho\left(t,\,D,\,\beta\right)$ (though with $\sigma_0=\varepsilon=1$) for $x\in[-5,\,5]$ and ran it from $t=0$ until $t=0.5$ and found the following,

which looks still reasonably Gaussian for the different parameter pairs. It appears that $\beta$ is controls the height of the central peak while $D$ controls the width and heights.
The Python code I used to produce the above can be found in my github page.


text:
Q: Image in center position in determined height I'm trying to position an image in determined height.
Just like this main image:
http://littlelines.com/
I have this:
HTML

CSS
.present100 {
    width: 100%;
    height: 620px;
    background-color: #333;
    position: absolute;
    overflow: hidden;
    top: 0;
    left: 0;
    margin: auto;
}

#imagem {
    position: relative;
    width: 100%;
    min-width: 1300px;
    min-height: 100%;
}

I don't know how to center the image on resize just like the http://littlelines.com/

A: Not sure why you have absolute position on the .present100 element, but you will have to absolutely position the image as well
#imagem {
    position: absolute;
    width: 100%;
    min-width: 1300px;
    min-height: 100%;

    left:50%;
    top:50%;

        -ms-transform: translate(-50%, -50%);
       -moz-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
}

Demo at http://jsfiddle.net/gaby/vMyvc/


text:
Q: vb.net client object model: view content from sharepoint 2010 wikipage On SharePoint 2010 i have many wikipages containing a table. Is it possible to view the content of that page in vb.net using the client object model?
I tried to get the file code using a stream but the text i get is a lot of asp.net code but not the html code/content from that page...
Dim fileAlgemeen As SP.File = Nothing
Dim siteUrl As String = "https://portal.xx.be/sites/kdb"
Dim ctx As New ClientContext(siteUrl)
Dim credentials As NetworkCredential = New NetworkCredential("xx", "xx")
ctx.Credentials = credentials
Dim web As Web = ctx.Web
ctx.Load(web)
ctx.ExecuteQuery()
Dim relativeUrl As String = "/sites/kdb/596/Algemeen.aspx"
Dim file As SP.File = web.GetFileByServerRelativeUrl(relativeUrl)
ctx.Load(file)
ctx.ExecuteQuery()

Dim fileRef = relativeUrl

Dim fileInfo As FileInformation = SP.File.OpenBinaryDirect(ctx, fileRef.ToString())

Using fileInfo.Stream
    Using sr As StreamReader = New StreamReader(fileInfo.Stream)
        Dim line As String = sr.ReadToEnd()
        lbl.Text = line
    End Using
End Using

A: There is no need to read file content since wiki content is stored in associated List Item PublishingPageContent field.
The following example demonstrates how to read and update wiki content using SharePoint CSOM (VB.NET)
Sub Main()

    Const siteUrl As String = "https://contoso.sharepoint.com/kb/"
    Const userName As String = "username@contoso.onmicrosoft.com"
    Const password As String = "password"

    Using ctx = New ClientContext(siteUrl)

        Dim credentials As NetworkCredential = New NetworkCredential(userName, password)
        ctx.Credentials = credentials

        '1. Read Wiki content
        Dim wikiFile = ctx.Web.GetFileByServerRelativeUrl("/kb/Pages/Welcome.aspx")
        Dim wikiItem = wikiFile.ListItemAllFields
        ctx.Load(wikiItem)
        ctx.ExecuteQuery()
        Console.WriteLine(wikiItem("PublishingPageContent"))

        '2. Update wiki content
        wikiItem("PublishingPageContent") = "
Welcome to the SharePoint!
"
        wikiItem.Update()
        ctx.ExecuteQuery()

    End Using

End Sub

Key Points:

*

*Wiki content is stored in List Item PublishingPageContent field

*File.ListItemAllFields property is used to retrieve List Item
associated with File


text:
Q: Is this the best way to use unique_ptr to avoid leaks? I'm a beginner and I am working to understand memory leaks.
Does the code below have any leaks? Does it make sense to use unique_ptr for the vector and map?
My purpose is mostly for performance and minimal tolerance in my code. If this code is wrong, please tell me where I made a mistake.
typedef struct MyStruct
{
    std::string name;
    int age;
} tMyStruct;

typedef std::map<std::unique_ptr<MyStruct>, std::unique_ptr<MyStruct>> den_mp;
typedef std::vector< std::unique_ptr<MyStruct> > den_vec;

den_mp  m_mp;
den_vec m_vec;

void doit(auto& mp)
{
    for (auto it = mp.begin(); it != mp.end(); it++)
    {
        std::cout << it->first->name << std::endl;
    }
}

void doit2(auto& mp)
{
    for (auto it = mp.begin(); it != mp.end(); it++)
    {
        std::cout << it->get()->name << std::endl;
    }
}

void addvec(std::string name, int age)
{
    std::unique_ptr<MyStruct> strt(new MyStruct);
    strt->age = age;
    strt->name = name;
    m_mp.emplace(std::move(strt), std::move(strt));
}

void addvec2(std::string name, int age)
{
    std::unique_ptr<MyStruct> strt(new MyStruct);
    strt->age = age;
    strt->name = name;
    m_vec.emplace_back(std::move(strt));
}

int main()
{
    addvec("ads", 10);
    addvec2("asdfg", 10);

    doit(m_mp);
    doit2(m_vec);

    std::cin.get();
}

A:
Is the codes have any leak?

No, the shown program doesn't have memory leaks as far as I could tell.
However, this is broken:
 m_mp.emplace(std::move(strt), std::move(strt));

If you move from something twice, then the second move will be from an object that has already been moved from. In this case, the unique pointer would be null after being moved from.
You cannot have multiple unique pointers pointing to the same object. That's why it's called "unique".

Does it make sense to use unique_ptr vector and map?'

It can. But it doesn't always make sense. It can be unnecessarily inefficient when storing the object itself as an element would suffice.

A:
Is the codes have any leak?

No.

Does it make sense to use unique_ptr vector and map?

Sure. But you should be aware of what you are doing. Especially using unique_ptr as the key type of a map.

If this codes is wrong pls tell me where I made a mistake?

void addvec(std::string name, int age)
{
        std::unique_ptr<MyStruct> strt(new MyStruct);
        strt->age = age;
        strt->name = name;
        m_mp.emplace(std::move(strt), std::move(strt)); // Undefined Behavior
}

m_mp.emplace(std::move(strt), std::move(strt))

*

*Let's say the first move is called first. It is moved successfully(as key), then the second move would be evaluated to null, as it has been already moved

*According to C++ standard, you cannot be sure which argument is evaluated first. i.e. the second move could be called first. Order of evaluation in C++ function parameters

A: The code is overly elaborate. If you just write the obvious it will work:
std::vector<MyStruct> m_mp;

void addvec2(std::string name, int age) {
    m_mp.emplace_back(name, age);
}

There is no need for pointers here. The best way to avoid leaks is to not make heap allocations.
Of course, if the code in the question was a simplification of a problem that actually required heap allocations, ignore this.


text:
Q: Deleting entries based on date with BeautifulSoup I have a XML file which looks like this:
?xml version="1.0" encoding="UTF-8"?>
  <url>
    <lastmod>2020-02-04T16:21:00+01:00</lastmod>
    <loc>https://www.h.com</loc>
  </url>
  <url>
    <lastmod>2020-01-31T17:17:00+01:00</lastmod>
    <loc>https://www.h.com</loc>
  </url>
  <url>
    <lastmod>2020-01-27T13:53:00+01:00</lastmod>
    <loc>https://www.h.coml</loc>
  </url>

A datetime.date which looks like this:
datetime.date(2020, 02, 01)

Is it possible to use BeautifulSoup to delete/igonre the content of an <url> tag, if the date in the <lastmod> tag is older than the given datetime.date?
With a result like this:
?xml version="1.0" encoding="UTF-8"?>
  <url>
    <lastmod>2020-02-04T16:21:00+01:00</lastmod>
    <loc>https://www.h.com</loc>
  </url>

Can somebody help?

A: Is this all right?
import time
from simplified_scrapy.simplified_doc import SimplifiedDoc
html = '''
<?xml version="1.0" encoding="UTF-8"?>
<url>
  <lastmod>2020-02-04T16:21:00+01:00</lastmod>
  <loc>https://www.h.com</loc>
</url>
<url>
  <lastmod>2020-01-31T17:17:00+01:00</lastmod>
  <loc>https://www.h.com</loc>
</url>
<url>
  <lastmod>2020-01-27T13:53:00+01:00</lastmod>
  <loc>https://www.h.coml</loc>
</url>
'''
doc = SimplifiedDoc(html)
urls = doc.urls
startTime = time.strptime("2020-2-1", "%Y-%m-%d")
removeList=[]
for url in urls:
  lastmod = url.lastmod.html # Get lastmod
  tm = time.strptime(lastmod[0:lastmod.find('+')], "%Y-%m-%dT%H:%M:%S")
  if tm<startTime:
    removeList.append(url)
n = len(removeList)
html = doc.html
while n>0: # Delete data in reverse order
  n-=1
  url = removeList[n]
  html = html[0:url._start]+html[url._end:] # Delete url data
print (html.strip())

Result:
<?xml version="1.0" encoding="UTF-8"?>
<url>
  <lastmod>2020-02-04T16:21:00+01:00</lastmod>
  <loc>https://www.h.com</loc>
</url>

A: If you are using python >=3.7, you can convert time string (for convinence named below as your_date_string)to time in the following way:
datetime.strptime(your_date_string, '%Y-%m-%dT%H:%M:%S%z')

if it's older python version, you need to remove last colon from the timezone
if your_date_string[-3] == ':':
    your_date_string = your_date_string[:-3]+ your_date_string[-2:]


text:
Q: Monitor and Lock clarification I grabbed the concept of synchronization as the following: every object in Java has a monitor and a lock. Lock is an entity which can be acquired or released by a thread, whereas monitor is an instance's mechanism which decides whether or not a thread can get the lock on an object.
I'd like to clarify the following example.
Firstly, I want to create two objects:
  MyClass obj1 = new MyClass();
  MyClass obj2 = new MyClass();

Will each instance has its own monitor and lock? Or a shared one?
If I synchronize on a class:
  synchronized (MyClass.class) {
     ...
  }

How will it behave? Will this synchronization block acquiring of obj1 and obj2 locks? If so, is there any lock hierarchy in Java?
Follow-up: Which is the correct way to say "the object's monitor" or "the object's lock"?

A:
every object in Java has a monitor and a lock.

That doesn't sound right.  Every object has a lock.  Some people call the lock a "monitor".  Monitors are an idea out of the past that never gained much traction, but back when Java was created, the implementers thought that monitors would be the next Big Thing.  Basically, a monitor is an object whose methods are all synchronized.

Will each instance has its own... lock?

Yes.

If I syncronize on a class ... How will it behave?

A class is an object.
There are three distinct objects in your example; obj1, obj2, and MyClass.class.  Each of those objects has its own lock, and their locks do not interact with one another at all.

A:
If I synchronize on a class... How will it behave? Will this synchronization block acquiring of obj1 and obj2 locks?

If you synchronize on MyClass.class it will only sync with other attempts to sync on MyClass.class.  So locking on obj1 or obj2 will have no effect.

If so, is there any lock hierarchy in Java?

Nope, there is no lock hierarchy in Java.

Which is the correct way to say "the object's monitor" or "the object's lock"?

Typically people only refer to "the object's lock" when talking about synchronization.  Monitor's come into play when you start using wait() and notify(), but that is a different topic.


text:
Q: Conditional expectation of integral $$E\Big(\int_0^2 t^2W_t^3 \, dt \mid F_1\Big)=\int_0^1 t^2W_t^3 \, dt +\int_1^2 E(t^2W_t^3 \mid F_1) \, dt=$$

$E(W_t^3\mid F_1)=E((W_t-W_1+W_1)^3\mid F_1)=E((W_t-W_1)^3\mid F_1)+3E((W_t-W_1)^2W_1\mid F_1)+3E((W_t-W_1)W_1^2\mid F_1)+E(W_1^3\mid F_1)=0+3(t-1)W_1+0+W_1^3$

$$=\int_0^1 t^2W_t^3\,dt +\int_1^2 t^23(t-1)W_1\,dt+\int_1^2 t^2 W_1^3\,dt=\int_0^1 t^2W_t^3\,dt+\frac{17}{4}W_1+\frac{7}{3}W_1^3$$
I would like to ask you if thats correct?

A: Note that $$\int_1^2 t^2 \, dt = \frac{7}{3} \neq \frac{1}{3}$$ (last step). Except for that minor mistake your calculations are correct.


text:
Q: Find subsets of a huge list that overlap/intersect with another large list I wrote a Python module to find subsets of a list by checking if the items in the list overlap/intersect with items in another list. The main part of my module looks something like this:
from collections import defaultdict

There are total of 1865390 items in overalllist (items are tuple)
overalllist = [(8361474, 8363645), (8363182, 8363758), …, (14634342, 14634440)]

There are total of 608348 items in mylist
mylist = [(8362677, 8363216), (8414202, 8414313), …, (14634354, 14634397)]

Find subsets of list
def mysubsets(list1, list2):
    sublist = [(x, y) for x, y in list1 if x <= list2[1] and y >= list2[0]]
    return sublist

For my example lists given above, the first item of mylist, (8362677, 8363216), overlaps with the first two items of overalllist, [(8361474, 8363645), (8363182, 8363758)]. So for (8362677, 8363216), the subset of overalllist is [(8361474, 8363645), (8363182, 8363758)], …
Initialize an empty dictionary of list that will be populated with items from mylist as keys and subsets from overalllist as values
mydict = defaultdict(list)

Loop through each item in mylist and find subsets in overalllist and put them into mydict
for item in mylist:
    sublist = mysubsets(overalllist, item)
    mydict.update({item:sublist})

The output looks something like this
>>> mydict
defaultdict(<type 'list'>, {(14634354, 14634397): [(14634342, 14634440)], …, (8362677, 8363216): [(8361474, 8363645), (8363182, 8363758)]})

My script works but is extremely slow (it ran for about 18 hours). I checked the execution time using cProfile and found mysubsets() spent a lot of time:
ncalls tottime percall cumtime percall filename:lineno(function)
608348 1732.827 0.003 1732.827 0.003 mymodule.py:383(mysubsets)
I wonder if there is any most fast and efficient way to achieve my goal. Thank you.

A: Assuming that the intervals in each list have no overlaps among themsevles, first sort each list, and then traverse both lists from beginning to end, in linear time, following this pseudo code:
i1 = 0
i2 = 0
while i1<len(list1) && i2<len(list2):
  if list1[i1] is to the left of list2[i2]:
    i1 += 1
  elif list2[i2] is to the left of list1[i1]:
    i2 += 1
  else // list1[i1] overlaps list2[i2]
    find all intervals from list2[i2:] that overlap with the interval list1[i1]
    i1 += 1

A: def mysubsets(list1, list2):
    len_l2 = len(list2)
    idx = 0
    sublist = []
    for x,y in list1:
        if x<=list2[idx][0]:
            if y>=list2[idx][1]:
                sublist.append((x,y))
        else:
            idx+=1
            if idx>=len_l2:
                break
    return sublist

A: Another approach you can try is a divide-and-conquer one, and this doesn't assume mutually exclusive intervals:
Fix some value X.
Take list1, divide it to three lists: left1, mid1, right1.
  left1 contains all intervals that are left of x.
  right1 contains all intervals that are right of x.
  mid1 contains all intervals that contain x

The value X should be selected such that it roughly puts half of the items in left1 and the other half in right1.
Do the same for list2. Divide it to three lists: left2, mid2, right2.

Now we know that left1 has no overlaps with right2
And left2 has no overlaps with right1
Now, recursively find all overlaps between (left1+mid1) and (left2+mid2)
and all overlaps between (right1+mid1) and (right2+mid2)

The stopping condition for the recursion should be that the size of one of the lists is below some threshold.
This is not an optimal algorithm, and some overlaps here will be found more than once. But for practical purposes should be fast enough.


text:
Q: need help understanding this transformation step in Riccati equation to Lyapunov equation In this note Discrete LQR note, I am not understanding the transition from equation (4) to (5) on page 14.
In particular, I don't get this step:
$$
(A-BK_{s})^{\top}{P_s}(A-BK_{s}) + 2A^{\top}{P_{s}}BK_{s} - K_{s}^{\top}B^{\top}P_{s}BK_{s} + C^{\top}C - K^{\top}(R + B^{\top}PB)K \\
= (A-BK_{s})^{\top}{P_s}(A-BK_{s}) + C^{\top}C + K_{s}^{\top}RK_{s}
$$
What is the trick used here?


text:
Q: Killing the process running on server I wrote a program. It kills the process notepad.exe running on computer by and it looks like that:
    `
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = @"d:\Windows\System32";
process.StartInfo.Arguments = "/c taskkill /IM notepad.exe";
process.Start();
process.Close();`

I placed this code on my web page. The problem is: when I use the Visual Studio Development server it works. When  change to local iis 7.5 it don't. I tried to figure it out, so I even gave the administrator privileges to "DefaultAppPool" or run the whole web page as Administrator (then all the processes as cmd.exe are running as Administrator) but wasn't a solution.


text:
Q: Doctrine: Symfony 2 foreign key null just before flush I am new to Symfony2 and Doctrine, i am stuck a little bit. Error receiving while saving to the database.
An exception occurred while executing 'INSERT INTO tho_provider (provid_name, provid_logo, provid_logo_path, created_time, provider_created_by) VALUES (?, ?, ?, ?, ?)' with params ["test", {}, "qwwwww", "2015-08-11 16:03:15", null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'provider_created_by' cannot be null
I have the form where i am only getting provider name input and logo, rest is i am handling in the controller, Including provider_created_by which gets null just after the flush, before the flush command its showing the value.
public function createAction(Request $request)
{
    $user = $this->getUser();
    $entity = new Provider();
    $entity->setProvidLogoPath("qwwwww");
    $entity->setProviderCreatedBy($user);

    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {

        //$entity->setCreatedBy($user);
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);

        $em->flush();

        return $this->redirect($this->generateUrl('provider_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

I have entities, PROVIDER and USER.
User's can create many provider and providers only belongs to one user. One to many relationship.
    <?php

    namespace AppBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\HttpFoundation\File\File;
    use Vich\UploaderBundle\Mapping\Annotation as Vich;
    /**
     * Provider
     *
     * @ORM\Table(name="tho_provider")
     * @ORM\Entity(repositoryClass="AppBundle\Entity\ProviderRepository")
     * @Vich\Uploadable
     * @ORM\HasLifecycleCallbacks()
     */
    class Provider
    {
        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="providers")
         * @ORM\JoinColumn(name="provider_created_by", referencedColumnName="id")
         */
        protected $users;

        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

        /**
         * @var string
         * @Assert\NotBlank()
         * @ORM\Column(name="provid_name", type="string", length=255)
         */
        private $providName;

        /**
         * NOTE: This is not a mapped field of entity metadata, just a simple property.
         *
         * @Vich\UploadableField(mapping="general_image", fileNameProperty="provid_logo")
         *
         * @var File
         */
        private $imageFile;
        /**
         * @var string
         *
         * @ORM\Column(name="provid_logo", type="string", length=255)
         */
        private $providLogo;

        /**
         * @var string
         *
         * @ORM\Column(name="provid_logo_path", type="string", length=255)
         */
        private $providLogoPath;

        /**
         * @var \DateTime
         * @Assert\Type("\DateTime")
         * @ORM\Column(name="created_time", type="datetime")
         */
        private $createdTime;

        /**
         * @var integer
         *
         * @ORM\Column(name="provider_created_by", type="integer")
         */
        public $providerCreatedBy;

        /**
         * Get id
         *
         * @return integer
         */
        public function getId()
        {
            return $this->id;
        }

        /**
         * Set providName
         *
         * @param string $providName
         * @return Provider
         */
        public function setProvidName($providName)
        {
            $this->providName = $providName;

            return $this;
        }

        /**
         * Get providName
         *
         * @return string
         */
        public function getProvidName()
        {
            return $this->providName;
        }

        /**
         * Set providLogo
         *
         * @param string $providLogo
         * @return Provider
         */
        public function setProvidLogo($providLogo)
        {
            $this->providLogo = $providLogo;

            return $this;
        }

        /**
         * Get providLogo
         *
         * @return string
         */
        public function getProvidLogo()
        {
            return $this->providLogo;
        }

        /**
         * Set providLogoPath
         *
         * @param string $providLogoPath
         * @return Provider
         */
        public function setProvidLogoPath($providLogoPath)
        {
            $this->providLogoPath = $providLogoPath;

            return $this;
        }

        /**
         * Get providLogoPath
         *
         * @return string
         */
        public function getProvidLogoPath()
        {
            return $this->providLogoPath;
        }

        /**
         * Set createdTime
         *
         * @param \DateTime $createdTime
         * @return Provider
         */
        public function setCreatedTime($createdTime)
        {
            $this->createdTime = $createdTime;

            return $this;
        }

        /**
         * Get createdTime
         *
         * @return \DateTime
         */
        public function getCreatedTime()
        {
            return $this->createdTime;
        }

        /**
         * Set users
         *
         * @param \AppBundle\Entity\User $users
         * @return Provider
         */
        public function setUsers(\AppBundle\Entity\User $users = null)
        {
            $this->users = $users;

            return $this;
        }

        /**
         * Get users
         *
         * @return \AppBundle\Entity\User
         */
        public function getUsers()
        {
            return $this->users;
        }

        /**
         * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
         * of 'UploadedFile' is injected into this setter to trigger the  update. If this
         * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
         * must be able to accept an instance of 'File' as the bundle will inject one here
         * during Doctrine hydration.
         *
         * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
         */
        public function setImageFile(File $image = null)
        {
            $this->imageFile = $image;

            if ($image) {
                // It is required that at least one field changes if you are using doctrine
                // otherwise the event listeners won't be called and the file is lost
                $this->updatedAt = new \DateTime('now');
            }
        }

        /**
         * @return File
         */
        public function getImageFile()
        {
            return $this->imageFile;
        }

        /**
         * @ORM\PrePersist
         */
        public function setCreatedTimeValue()
        {
            $this->createdTime = new \DateTime();
        }

        /**
         * Set providerCreatedBy
         *
         * @param integer $providerCreatedBy
         * @return Provider
         */
        public function setProviderCreatedBy($providerCreatedBy)
        {
            $this->providerCreatedBy = $providerCreatedBy;

            return $this;
        }

        /**
         * Get providerCreatedBy
         *
         * @return integer
         */
        public function getProviderCreatedBy()
        {
            return $this->providerCreatedBy;
        }
    }

USER:
    <?php

    namespace AppBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Security\Core\User\AdvancedUserInterface;
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use Doctrine\Common\Collections\ArrayCollection;
    /**
     * User
     *
     * @ORM\Table(name="tho_user")
     * @ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
     * @UniqueEntity(fields="email",message = "This email already exist.")
     * @UniqueEntity(fields = "username",message = "This username already taken")
     */
    class User implements AdvancedUserInterface, \Serializable
    {

        /**
         * @ORM\OneToMany(targetEntity="Provider", mappedBy="user")
         */
        protected $providers;

        public function __construct()
        {
            $this->providers = new ArrayCollection();
        }
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

        /**
         * @var string
         *@Assert\NotBlank(message="Username is required!")
         * @Assert\Length(min=3,minMessage="Minimum 3 characters long.")
         * @ORM\Column(name="username", type="string", length=255)
         */
        protected $username;

        /**
         * @var string
         *
         *
         * @ORM\Column(name="password", type="string", length=255)
         */
        private $password;
        /**
         * @var array
         *
         * @ORM\Column(name="roles",type="json_array")
         */
        private $roles = array();
        /**
         * @var bool
         *
         * @ORM\Column(name="is_active",type="boolean")
         */
        private $isActive = true;

        /**
         * @var string
         *@Assert\NotBlank()
         * @Assert\Email
         * @ORM\Column(name="email",type="string", length=255)
         */
        private $email;

        /**
         * @var string
         *@Assert\NotBlank()
         *
         * @ORM\Column(name="first_name",type="string", length=255)
         */
        private $firstName;

        /**
         * @var string
         *@Assert\NotBlank()
         * @ORM\Column(name="last_name",type="string", length=255)
         */
        private $lastName;

        /**
         * @var string
         *
         * @ORM\Column(name="iata",type="string", length=255)
         */
        private $iata;

        /**
         * @var string
         *
         * @ORM\Column(name="job_title",type="string", length=255)
         */
        private $jobTitle;

        /**
         * @var string
         *
         * @ORM\Column(name="agency_phone",type="string", length=255)
         */
        private $agencyPhone;

        /**
         * @var string
         *
         * @ORM\Column(name="emergency_mobile",type="string", length=255)
         */
        private $emergencyMobile;

        /**
         * Storing password temporarily
         * @Assert\NotBlank()
         * @Assert\Length(min=6,minMessage="Minimum 6 characters long.")
         * @var string
         */
        private $plainPassword;
       /**
         * Get id
         *
        *
         * @return integer
         */

        public function getId()
        {
            return $this->id;
        }

        /**
         * Set username
         *
         * @param string $username
         * @return User
         */
        public function setUsername($username)
        {
            $this->username = $username;

            return $this;
        }

        /**
         * Get username
         *
         * @return string
         */
        public function getUsername()
        {
            return $this->username;
        }

        /**
         * Set password
         *
         * @param string $password
         * @return User
         */
        public function setPassword($password)
        {
            $this->password = $password;

            return $this;
        }

        /**
         * Get password
         *
         * @return string
         */
        public function getPassword()
        {
            return $this->password;
        }

        public function getRoles()
        {
            $roles = $this->roles;
            $roles[] = 'ROLE_ADMIN';
            return array_unique($roles);
        }

        public function setRoles(array $roles)
        {
            $this->roles = $roles;
            return $this;
        }
        public function eraseCredentials()
        {
           $this->setPlainPassword(null);
        }

        public function getSalt()
        {
            return null;
        }

        /**
         * @return boolean
         */
        public function isIsActive()
        {
            return $this->isActive;
        }

        /**
         * @param boolean $isActive
         */
        public function setIsActive($isActive)
        {
            $this->isActive = $isActive;
        }

        /**
         * Checks whether the user's account has expired.
         *
         * Internally, if this method returns false, the authentication system
         * will throw an AccountExpiredException and prevent login.
         *
         * @return bool true if the user's account is non expired, false otherwise
         *
         * @see AccountExpiredException
         */
        public function isAccountNonExpired()
        {
            return true;
        }

        /**
         * Checks whether the user is locked.
         *
         * Internally, if this method returns false, the authentication system
         * will throw a LockedException and prevent login.
         *
         * @return bool true if the user is not locked, false otherwise
         *
         * @see LockedException
         */
        public function isAccountNonLocked()
        {
            return true;
        }

        /**
         * Checks whether the user's credentials (password) has expired.
         *
         * Internally, if this method returns false, the authentication system
         * will throw a CredentialsExpiredException and prevent login.
         *
         * @return bool true if the user's credentials are non expired, false otherwise
         *
         * @see CredentialsExpiredException
         */
        public function isCredentialsNonExpired()
        {
            return true;
        }

        /**
         * Checks whether the user is enabled.
         *
         * Internally, if this method returns false, the authentication system
         * will throw a DisabledException and prevent login.
         *
         * @return bool true if the user is enabled, false otherwise
         *
         * @see DisabledException
         */
        public function isEnabled()
        {
           return true;
        }

        /**
         * Get isActive
         *
         * @return boolean
         */
        public function getIsActive()
        {
            return $this->isActive;
        }

        /**
         * Set email
         *
         * @param string $email
         * @return User
         */
        public function setEmail($email)
        {
            $this->email = $email;

            return $this;
        }

        /**
         * Get email
         *
         * @return string
         */
        public function getEmail()
        {
            return $this->email;
        }

        /**
         * (PHP 5 >= 5.1.0)

         * String representation of object
         * @link http://php.net/manual/en/serializable.serialize.php
         * @return string the string representation of the object or null
         */
        public function serialize()
        {
            return serialize(array(
                $this->id,
                $this->username,
                $this->password
            ));
        }

        /**
         * (PHP 5 >= 5.1.0)

         * Constructs the object
         * @link http://php.net/manual/en/serializable.unserialize.php
         * @param string $serialized

         * The string representation of the object.
         *

         * @return void
         */
        public function unserialize($serialized)
        {
            list(
                $this->id,
                $this->username,
                $this->password
                ) = unserialize($serialized);
        }

        /**
         * @return string
         */
        public function getFirstName()
        {
            return $this->firstName;
        }

        /**
         * @param string $firstName
         */
        public function setFirstName($firstName)
        {
            $this->firstName = $firstName;
        }

        /**
         * @return string
         */
        public function getLastName()
        {
            return $this->lastName;
        }

        /**
         * @param string $lastName
         */
        public function setLastName($lastName)
        {
            $this->lastName = $lastName;
        }

        /**
         * @return string
         */
        public function getIata()
        {
            return $this->iata;
        }

        /**
         * @param string $iata
         */
        public function setIata($iata)
        {
            $this->iata = $iata;
        }

        /**
         * @return string
         */
        public function getJobTitle()
        {
            return $this->jobTitle;
        }

        /**
         * @param string $jobTitle
         */
        public function setJobTitle($jobTitle)
        {
            $this->jobTitle = $jobTitle;
        }

        /**
         * @return string
         */
        public function getAgencyPhone()
        {
            return $this->agencyPhone;
        }

        /**
         * @param string $agencyPhone
         */
        public function setAgencyPhone($agencyPhone)
        {
            $this->agencyPhone = $agencyPhone;
        }

        /**
         * @return string
         */
        public function getEmergencyMobile()
        {
            return $this->emergencyMobile;
        }

        /**
         * @param string $emergencyMobile
         */
        public function setEmergencyMobile($emergencyMobile)
        {
            $this->emergencyMobile = $emergencyMobile;
        }

        /**
         * @return string
         */
        public function getPlainPassword()
        {
            return $this->plainPassword;
        }

        /**
         * @param string $plainPassword
         */
        public function setPlainPassword($plainPassword)
        {
            $this->plainPassword = $plainPassword;
        }

        /**
         * Set provider
         *
         * @param \AppBundle\Entity\Provider $provider
         * @return User
         */
        public function setProvider(\AppBundle\Entity\Provider $provider = null)
        {
            $this->provider = $provider;

            return $this;
        }

        /**
         * Get provider
         *
         * @return \AppBundle\Entity\Provider
         */
        public function getProvider()
        {
            return $this->provider;
        }

        /**
         * Add providers
         *
         * @param \AppBundle\Entity\Provider $providers
         * @return User
         */
        public function addProvider(\AppBundle\Entity\Provider $providers)
        {
            $this->providers[] = $providers;

            return $this;
        }

        /**
         * Remove providers
         *
         * @param \AppBundle\Entity\Provider $providers
         */
        public function removeProvider(\AppBundle\Entity\Provider $providers)
        {
            $this->providers->removeElement($providers);
        }

        /**
         * Get providers
         *
         * @return \Doctrine\Common\Collections\Collection
         */
        public function getProviders()
        {
            return $this->providers;
        }
    }

A: Your metadata is
/**
 * @var integer
 *
 * @ORM\Column(name="provider_created_by", type="integer")
 */
public $providerCreatedBy;

but you are passing an object (probably null):
$user = $this->getUser();
/* ... */
$entity->setProviderCreatedBy($user);

And the setter has no type hint:
public function setProviderCreatedBy($providerCreatedBy)
{
    $this->providerCreatedBy = $providerCreatedBy;

    return $this;
}

You must change your mapping of $providerCreatedBy to ManyToOne with User entity.

A: Check if your user has been logged in, $this->getUser() returns null if user is anonymous, also I think you should change your mapping info for providerCreatedBy field, from column type integer to ManyToOne relationship with User class..


text:
Q: Wilcoxon Test with Random Effect I would like to test if there is a significant difference in the speed of movement between 2 treatments for different females. For each female, I have several sampling points. I have a table with the female's ID (1st column), the speed for the first treatment (2nd column) and the speed for the second treatment (3rd column) (with several sampling points per female).
I was thinking of doing a Wilcoxon test to test if there is a significant difference between the two treatments, but I need to add the random effect of the female's ID.
I was told to apply a mixed model, but the result of the model only gives me if I have a linear relationship between the two, whereas I want to know if the two treatments are significantly different.
Does anyone know how I can get this result?


text:
Q: Diferença de usar ou não o termo function Estou iniciando o estudo com o Vue.js e me deparei com uma situação dentro de uma das opções e imagino que sirva para outras opções que é o uso do termo function, por exemplo:
var vm = new Vue({
  methods : {

    /* assim */

    enviar() {
      // code
    },

    /* ou assim */

    enviar: function() {
      // code
    },

  }
})

E com isso minha dúvida é se tem diferença em cada uma das sintaxes e de navegadores?

A: Segundo a documentação na Mozilla, enviar apesar de ser à forma contraída de enviar: function(), a forma contraída é uma função nomeada, enquanto que a segunda é uma função anonima.

Note : The shorthand syntax uses named function instead of anonymous
  functions (as in …foo: function() {}…). Named functions can be called
  from the function body (this is impossible for anonymous function as
  there is no identifier to refer to). For more details, see function.

Fonte: Method definitions
Porem se você executar o código abaixo, verá que a forma contraída se comporta como uma função anonima, pelo menos é este comportamento que estou tendo ao executar no Opera.

var teste = {
  nomeada: function nomeada(imprimir) {
    return !imprimir ? nomeada(true) : console.log("nomeada");
  },
  curta(imprimir) {
    return !imprimir ? curta(true) : console.log("curta");
  },
  anomina: function(imprimir) {
    return !imprimir ? anomina(true) : console.log("anomina");
  }
}

try {
  teste.nomeada();
} catch (e) {
  console.error(e.message);
}
try {
  teste.curta();
} catch (e) {
  console.error(e.message);
}
try {
  teste.anomina();
} catch (e) {
  console.error(e.message);
}

Um outro ponto curioso, é que na documentação na Mozilla fala que a forma contraída não pode ser utilizada como.

Method definitions are not constructable
All method definitions are not constructors and will throw a TypeError
  if you try to instantiate them.

Fonte: Method definitions
Mas ao executar o código abaixo, obtive um comportamento diferente do apontado. Pelo menos foi o que aconteceu ao executar no Opera.

var teste = {
  nomeada: function nomeada() {
    this.nome = "nomeada";
  },
  curta() {
    this.nome = "curta";
  },
  anomina: function() {
    this.nome = "anomina";
  }
}

try {
  console.log(new teste.nomeada);
} catch (e) {
  console.error(e.message);
}
try {
  console.log(new teste.curta);
} catch (e) {
  console.error(e.message);
}
try {
  console.log(new teste.anomina);
} catch (e) {
  console.error(e.message);
}

Um outro ponto, é quanto a compatibilidade com os browsers, funções curtas podem ser utilizadas apenas em browsers mais recentes/atualizados. Porém, como está a utilizar o VueJS, deve está utilizando o vue-cli, o gulp-babel ou qual quer solução que transpile o seu javaScript ES5 para algo compatível com browser antigos, então isto não chega a ser um problema.


text:
Q: Showing that $\{\sin(nx)\}_{n=1}^\infty$ is a complete orthogonal system in $C([0,2\pi])$ and $L_2[0,\pi]$. Showing that $\{\sin(nx)\}_{n=1}^\infty$ is a complete orthogonal system in $C([0,2\pi])$ and $L_2[0,\pi]$.
So set the inner product for $C([0,2\pi])$ to be $\langle u,v\rangle = \int_0^{2\pi} u(t)v(t) dt$
Now $\langle \sin(nt),\sin(mt)\rangle=\int_0^{2\pi} \sin(nt)\sin(mt)dt$
When $n=m$ we have $\int_0^{2\pi} \sin^2(nt)\, dt = \int_0^{2\pi} \frac12 - \frac{\cos(2t)}{2} dt= \pi + [-\sin(2t)]_0^{2\pi} =\pi$
When $n\ne m$ we get $\int_0^{2\pi} \sin(nt)\sin(mt)dt$
Not sure what to do here, don't know how to evaluate this. How to evalute?

For $L_2[0,\pi]$, I am not sure what inner product to set.
 What to set?

A: $\{ e^{inx} \}_{n=-\infty}^{\infty}$ is a complete orthonormal basis of $L^2[-\pi,\pi]$ with respect to the inner product
$$
                 (f,g) = \frac{1}{2\pi}\int_{-\pi}^{\pi}f(t)\overline{g(t)}dt.
$$
If $f \in L^2[0,\pi]$, then $f$ may uniquely extended to an odd function $\tilde{f}$ on $[-\pi,\pi]$, which means the following converges in $L^2[-\pi,\pi]$ and, hence, also in $L^2[0,\pi]$:
$$
             \tilde{f} = \sum_{n=0}^{\infty}(\tilde{f},e^{int})e^{inx}.
$$
Because $\tilde{f}$ is odd, then $(\tilde{f},e^{int})=0$ for $n=0$, and
\begin{align}
        (\tilde{f},e^{int})
   & = \frac{1}{2\pi}\left[\int_{-\pi}^{0}(-f(-t))e^{-int}dx +\int_{0}^{\pi}f(t)e^{-int}dt\right] \\
   & = \frac{1}{2\pi}\int_{0}^{\pi}f(t)\{e^{-int}-e^{int}\}dt \\
   & = -\frac{i}{\pi}\int_{0}^{\pi}f(t)\sin(nt)dt.
\end{align}
Therefore $(\tilde{f},e^{int})=-(\tilde{f},e^{-int})$ and
\begin{align}
         \tilde{f} & = \sum_{n=1}^{\infty}\{(f,e^{int})e^{int}+(f,e^{-int})e^{-int}\} \\
      & = \sum_{n=1}^{\infty}(f,e^{int})\{e^{int}-e^{-int}\} \\
      & = \sum_{n=1}^{\infty}\left(-\frac{i}{\pi}\int_{0}^{\pi}f(t)\sin(nt)dt\right)2i\sin(nx) \\
      & = \sum_{n=1}^{\infty}\left(\frac{2}{\pi}\int_{0}^{\pi}f(t)\sin(nt)dt\right)\sin(nx)
\end{align}
The orthogonality of the $\sin(nx)$ functions in $L^2[0,\pi]$ follows easily from
$$
       \int_{0}^{\pi}\sin(nx)\sin(mx)dx = \int_{-\pi}^{\pi}\sin(nx)\sin(mx)dx \\
   = -\frac{1}{4}\int_{-\pi}^{\pi}\{e^{inx}-e^{-inx}\}\{e^{imx}-e^{-imx}\}dx.
$$


text:
Q: Creating secondary column with data from existing column I need help creating a secondary column using partial data from my first column in my data frame. I currently have this:
Column 1
300
400
200
100
24
80

I wish to have this:
Column 1   Column 2
300        100
400        24
200        80

Any help would be greatly appreciated.

A:  df
 #   A
 # 1 1
 # 2 2
 # 3 3
 # 4 4
 # 5 5
 # 6 6

 as.data.frame(matrix(df$A, byrow=FALSE, ncol = 2))
 #   V1 V2
 # 1  1  4
 # 2  2  5
 # 3  3  6

OR
 as.data.frame(matrix(df$A, byrow=FALSE, nrow = 3))
 #   V1 V2
 # 1  1  4
 # 2  2  5
 # 3  3  6

Filling ROW WISE
as.data.frame(matrix(df$A, byrow=TRUE, ncol = 2))
#   V1 V2
# 1  1  2
# 2  3  4
# 3  5  6

A: as.data.frame(matrix(dd$Column1, ncol = 2))
#    V1  V2
# 1 300 100
# 2 400  24
# 3 200  80

Assuming your data is something like this:
dd = read.table(text = "Column1
300
400
200
100
24
80", header = T)

A: We can also split the data frame and then cbind.
do.call(cbind,split(dd,rep(1:2,each=3)))
  Column1 Column1
1     300     100
2     400      24
3     200      80


text:
Q: asymptotic for the complex exponential integral Ei(s) Let $\operatorname{Ei}(s)$ denote the complex exponential integral function, which (if I am correct) can be defined for $s \in \mathbb{C}\backslash(-\infty,0]$ by
$$\operatorname{Ei}(s) = \gamma+\log s -\operatorname{Ein}(-s)= \gamma+\log s+\sum_{n = 1}^\infty \frac{s^n}{n!n},$$
where $\operatorname{Ein}(s)$ is the entire function $\sum_{n = 1}^\infty \frac{(-1)^{n+1}s^n}{n!n}$.
Is it true that
$$\operatorname{Ei}(s)\sim \frac{e^s}{s} \ (s \to \infty)$$
on $\{s \in \mathbb{C}: |\operatorname{Arg} s|\leq \frac{\pi}{2}-\epsilon\}$ for every $\epsilon > 0$?  More generally, for any $\epsilon > 0$, can one give an asymptotic expansion of $\operatorname{Ei}(s)$ on that set?  Given computations in Mathematica, it seems unlikely that such an asymptotic relation can be extended to the case where $\epsilon = 0$.  (Mathematica's command for the function is $\tt{ExpIntegralEi[s]}$.)
EDIT: I don't know why, but information on the web about the complex function $\operatorname{Ei}(s)$ is very scarce.  But it's an important function used a lot in analytic number theory, and in particular in the Riemann--von Mangoldt explicit formula for $\pi_0(x)$, since one has $\operatorname{li}(s) = \operatorname{Ei}(\log s)$.  Please, somebody, help!

A: It is known that
$$\tag{1}
E_1 (z) = \int_z^\infty  {\frac{{e^{ - t} }}{t}dt}  \sim \frac{{e^{ - z} }}{z}\left( {1 - \frac{{1!}}{z} + \frac{{2!}}{{z^2 }} - \frac{{3!}}{{z^3 }} +  \cdots } \right)
$$
as $z\to \infty$ in the sector $\left| {\arg z} \right| \le \frac{{3\pi }}{2} - \varepsilon  < \frac{{3\pi }}{2}$ (cf. http://dlmf.nist.gov/6.12.E1). The region of validity is maximal since the rays $\arg z =\pm\frac{{3\pi }}{2}$ are anti-Stokes lines for $E_1 (z)$. Now the function $\operatorname{Ei}(x)$ is defined for positive real $x$ only, and is related to $E_1(z)$ via
$$
\operatorname{Ei}(x) =  - \frac{{E_1 (xe^{\pi i} ) + E_1 (xe^{ - \pi i} )}}{2}.
$$
If you like, you can take $x$ to be complex and by $(1)$, we find the asymptotic series
$$
\operatorname{Ei}(z) \sim \frac{{e^z }}{z}\left( {1 + \frac{{1!}}{z} + \frac{{2!}}{{z^2 }} + \frac{{3!}}{{z^3 }} +  \cdots } \right)
$$
as $z\to \infty$ in the sector $\left| {\arg z} \right| \le \frac{{\pi }}{2} - \varepsilon  < \frac{{\pi }}{2}$, and this region of validity is maximal. To examine what happens on the anti-Stokes line $\arg z =\frac{{\pi }}{2}$ for example, take $z=xe^{\frac{\pi }{2}i}$ with $x>0$ and note that
\begin{align*}
\operatorname{Ei}(xe^{\frac{\pi }{2}i} ) & =   - \frac{{E_1 (xe^{\frac{{3\pi }}{2}i} ) + E_1 (xe^{ - \frac{\pi }{2}i} )}}{2} \\ & =  - \frac{{E_1 (xe^{ - \frac{\pi }{2}i} e^{2\pi i} ) + E_1 (xe^{ - \frac{\pi }{2}i} )}}{2} \\ &=  - E_1 (xe^{ - \frac{\pi }{2}i} ) + \pi i \\ & \sim \pi i + \frac{{e^{ix} }}{{ix}}\left( {1 + \frac{{1!}}{{ix}} + \frac{{2!}}{{(ix)^2 }} + \frac{{3!}}{{(ix)^3 }} +  \cdots } \right)
\end{align*}
as $x\to +\infty$. Here we used http://dlmf.nist.gov/6.4.E2 with $m=1$. Note that the exponential factor is no longer large and hence the previously neglected term $\pi i$ becomes significant.
The complete asymptotic expansion may be written
$$
\operatorname{Ei}(z) \sim \frac{{e^z }}{z}\left( {1 + \frac{{1!}}{z} + \frac{{2!}}{{z^2 }} + \frac{{3!}}{{z^3 }} +  \cdots } \right) + \begin{cases} \quad\, 0, & \text{ if }\; \arg z =0,\\ \;\;\,\pi i, & \text{ if }\; 0<\arg z \leq \frac{\pi}{2}, \\ -\pi i, & \text{ if }\; -\frac{\pi}{2} \leq \arg z <0.\end{cases}
$$