text:
Q: Problem with pasting table from excel to word I use a macro for over 2 years with no problems. The macro is simple - copy a table from an Excel file and paste it into a Word document. For a few days, I am struggling with a problem - after starting the macro

error 4198 is occurring.

After clicking Debug VBA highlights such part of the code:
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False

When I click Continue, the macro is going to the end with no additional problems until the next iteration.
Here is the entire macro:
Sub Agent_info()

Dim w As MailMerge
Dim a As Integer
Dim NumberOfFiles As Integer
Dim sFileName As String
Dim xlTable As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim komorka As String

Dim my_xl As Excel.Workbook
Dim xlApp As Excel.Application

'NumberOfFiles = 3
NumberOfFiles = InputBox("Ile pism przygotować?", "Pytanie")

On Error GoTo ERR_Handler

    Application.ScreenUpdating = False
    Application.Visible = True

    Set w = ActiveDocument.MailMerge

    w.DataSource.ActiveRecord = wdFirstDataSourceRecord

    Set xlApp = CreateObject("Excel.Application")
    Dim xlPath As String
    xlPath = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\ZAŁĄCZNIKI.xlsx"
    xlApp.Visible = True
    Set my_xl = xlApp.Workbooks.Open(xlPath)
    Worksheets("info").Activate
    Range("A1").Select
    If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania", vbDirectory)) = 0 Then
        MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania"
    End If
    If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO", vbDirectory)) = 0 Then
        MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO"
    End If
    If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma", vbDirectory)) = 0 Then
        MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma"
    End If
    If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe", vbDirectory)) = 0 Then
        MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe"
    End If

    For a = 1 To NumberOfFiles

        On Error Resume Next

        Set xlApp = GetObject("Excel.Application")
        Err.Clear
        If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application")
        If Err.Number = 429 Then
            MsgBox "Microsoft Excel could not be found, aborting."
        End If
        On Error GoTo 0

        komorka = ActiveCell.Address
        Do While ActiveCell.Value <> "Suma"
            ActiveCell.Offset(1, 0).Select
        Loop
        ActiveCell.Offset(0, 1).Select
        Set xlTable = Excel.Range(komorka, ActiveCell)
        xlTable.Copy
        Do While ActiveCell.Value <> "Zaległość"
            ActiveCell.Offset(-1, 0).Select
        Loop
        ActiveCell.Offset(0, 1).Select

        With w
            .Destination = wdSendToNewDocument
            .SuppressBlankLines = True
            With .DataSource
                .FirstRecord = a
                .LastRecord = a
            End With

            .Execute Pause:=False

        End With
        Dim katalog As String
        Dim folder As String
        Dim sciezka1 As String
        Dim sciezka2 As String
        Dim PDF As String
        Dim PDF2 As String
        Dim nazwaPisma As String
        Dim nazwa1 As String
        Dim nazwa2 As String
        katalog = w.DataSource.DataFields("NAZWA_PLIKU").Value
        folder = w.DataSource.DataFields("DATA_DO_PISMA_rrrrmmdd").Value
        'folder = Format(Date, "yyyy-mm-dd")
        If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog, vbDirectory)) = 0 Then
            MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
        End If
        If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder, vbDirectory)) = 0 Then
            MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
        End If
        'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
        'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
        nazwaPisma = " informacja o stanie zaległości z dnia "

        sciezka1 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
        sciezka2 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
        PDF = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
        PDF2 = "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
        ActiveDocument.Parent.ScreenUpdating = False
        ActiveDocument.SaveAs _
            FileName:=sciezka1, _
            FileFormat:=wdFormatXMLDocument, _
            LockComments:=False, _
            Password:="", _
            AddToRecentFiles:=True, _
            WritePassword:="", _
            ReadOnlyRecommended:=False, _
            EmbedTrueTypeFonts:=False, _
            SaveNativePictureFormat:=False, _
            SaveFormsData:=False, _
            SaveAsAOCELetter:=False
        ActiveDocument.Close

        On Error Resume Next
        Set WordApp = GetObject(class:="Word.Application")
        Err.Clear
        If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
        If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        End If
        On Error GoTo 0

        WordApp.Visible = True
        WordApp.Activate
        Set myDoc = WordApp.Documents.Open(sciezka1)
        myDoc.Paragraphs(17).Range.PasteExcelTable _
        LinkedToExcel:=False, _
        WordFormatting:=False, _
        RTF:=False
        'If Err.Number = 4198 Then
            'MsgBox "Microsoft Word could not be found, aborting."
        'End If

        Set WordTable = myDoc.Tables(1)
        WordTable.AutoFitBehavior (wdAutoFitWindow)
        WordTable.Range.ParagraphFormat.SpaceAfter = 0
        Set PasteSheet = Nothing
        Documents(myDoc).SaveAs _
            FileName:=sciezka2, _
            FileFormat:=wdFormatXMLDocument, _
            LockComments:=False, _
            Password:="", _
            AddToRecentFiles:=True, _
            WritePassword:="", _
            ReadOnlyRecommended:=False, _
            EmbedTrueTypeFonts:=False, _
            SaveNativePictureFormat:=False, _
            SaveFormsData:=False, _
            SaveAsAOCELetter:=False

        ActiveDocument.ExportAsFixedFormat _
            OutputFileName:=PDF2, _
            ExportFormat:=wdExportFormatPDF, _
            OpenAfterExport:=False, _
            OptimizeFor:=wdExportOptimizeForPrint, _
            Range:=wdExportAllDocument, _
            From:=1, To:=1, _
            Item:=wdExportDocumentContent, _
            IncludeDocProps:=True, _
            KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, _
            DocStructureTags:=True, _
            BitmapMissingFonts:=True, _
            UseISO19005_1:=False

        ActiveDocument.ExportAsFixedFormat _
            OutputFileName:=PDF, _
            ExportFormat:=wdExportFormatPDF, _
            OpenAfterExport:=False, _
            OptimizeFor:=wdExportOptimizeForPrint, _
            Range:=wdExportAllDocument, _
            From:=1, To:=1, _
            Item:=wdExportDocumentContent, _
            IncludeDocProps:=True, _
            KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, _
            DocStructureTags:=True, _
            BitmapMissingFonts:=True, _
            UseISO19005_1:=False
        Documents(myDoc).Close

        w.DataSource.ActiveRecord = wdNextRecord

    Next

END_Handler:

    Application.Visible = True
    Application.ScreenUpdating = True

    Exit Sub

ERR_Handler:

    MsgBox Err.Description

    Resume END_Handler:
End Sub


text:
Q: How do I load a tab-delimited file of mixed datatype into numpy or pandas? I have a tab delimited dataset that loads into Excel looking something like this in terms of data types, but has dimension 83 x 23275.  As you can see, this dataset is of mixed type, with the 0th row and column of type string.
               "A"         "B"         "C"         "D"
"2000-01-01"  0.469112 -0.282863 -1.509059 -1.135632
"2000-01-02"  1.212112 -0.173215  0.119209 -1.044236
"2000-01-03" -0.861849 -2.104569 -0.494929  1.071804
"2000-01-04"  0.721555 -0.706771 -1.039575  0.271860
"2000-01-05" -0.424972  0.567020  0.276232 -1.087401
"2000-01-06" -0.673690  0.113648 -1.478427  0.524988
"2000-01-07"  0.404705  0.577046 -1.715002 -1.039268
"2000-01-08" -0.370647 -1.157892 -1.344312  0.844885

Using pandas or numpy, how can I load this sort of data and access the numbers associated with their proper labels?  I would even be happy with two vectors of labels (83 and 23275 length for row and column) of datatype string, and then a matrix of float64 (82x23274 for the float data).
I got as far as loading the file into numpy and pandas respectively, but haven't been successful at accessing any of my data.
import numpy as np
import pandas as pd

#numpy
path = "C:/nature13173-s4.txt"
e18 = np.genfromtxt(path, delimiter = '\t')
print(e18.shape)

#pandas
df=pd.read_csv(path, sep='\t',header=None)

A: I cut-n-pasted your sample to a file. That doesn't carry over tabs well, so I'm using the default 'white space' delimiter.
My first try:
e18=np.genfromtxt('stack33662863.txt',names=True)

gave me errors
ValueError: Some errors were detected !
Line #2 (got 5 columns instead of 4)

That's because the 1st line has 4 column headers, but none for the date column.  So I'll have to skip the header line and give my own field names:
In [624]: e18=np.genfromtxt('stack33662863.txt',names=['date','A','B','C','D'],skip_header=1)
In [625]: e18
Out[625]:
array([(nan, 0.469112, -0.282863, -1.509059, -1.135632),
       (nan, 1.212112, -0.173215, 0.119209, -1.044236),
       (nan, -0.861849, -2.104569, -0.494929, 1.071804),
       (nan, 0.721555, -0.706771, -1.039575, 0.27186),
       (nan, -0.424972, 0.56702, 0.276232, -1.087401),
       (nan, -0.67369, 0.113648, -1.478427, 0.524988),
       (nan, 0.404705, 0.577046, -1.715002, -1.039268),
       (nan, -0.370647, -1.157892, -1.344312, 0.844885)],
      dtype=[('date', '<f8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8')])

Almost - except 'date' column is nan.  Let's use dtype=None to tell it to deduce datatype for each column, rather than assume all are float.  An alterantive is to  give a dtype for each column.
In [626]: e18=np.genfromtxt('stack33662863.txt',names=['date','A','B','C','D'],skip_header=1,dtype=None)
In [627]: e18
Out[627]:
array([(b'"2000-01-01"', 0.469112, -0.282863, -1.509059, -1.135632),
       (b'"2000-01-02"', 1.212112, -0.173215, 0.119209, -1.044236),
       (b'"2000-01-03"', -0.861849, -2.104569, -0.494929, 1.071804),
       (b'"2000-01-04"', 0.721555, -0.706771, -1.039575, 0.27186),
       (b'"2000-01-05"', -0.424972, 0.56702, 0.276232, -1.087401),
       (b'"2000-01-06"', -0.67369, 0.113648, -1.478427, 0.524988),
       (b'"2000-01-07"', 0.404705, 0.577046, -1.715002, -1.039268),
       (b'"2000-01-08"', -0.370647, -1.157892, -1.344312, 0.844885)],
      dtype=[('date', 'S12'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8')])

Looks pretty good. Data is all there.
I can access attributes and values with:
In [628]: e18.shape
Out[628]: (8,)
In [629]: e18.dtype
Out[629]: dtype([('date', 'S12'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8')])
In [630]: e18['date']
Out[630]:
array([b'"2000-01-01"', b'"2000-01-02"', b'"2000-01-03"', b'"2000-01-04"',
       b'"2000-01-05"', b'"2000-01-06"', b'"2000-01-07"', b'"2000-01-08"'],
      dtype='|S12')
In [631]: e18['A']
Out[631]:
array([ 0.469112,  1.212112, -0.861849,  0.721555, -0.424972, -0.67369 ,
        0.404705, -0.370647])

Another option is to load the data without names
In [636]: e18=np.genfromtxt('stack33662863.txt',skip_header=1)
In [637]: e18.shape
Out[637]: (8, 5)
In [638]: e18[:3,:]
Out[638]:
array([[      nan,  0.469112, -0.282863, -1.509059, -1.135632],
       [      nan,  1.212112, -0.173215,  0.119209, -1.044236],
       [      nan, -0.861849, -2.104569, -0.494929,  1.071804]])

Now it is all floats, a 2d array, but with nan in the 1st date column.  We can just slice that off, to get a nice 2d array:
In [639]: e18[:,1:]
Out[639]:
array([[ 0.469112, -0.282863, -1.509059, -1.135632],
       [ 1.212112, -0.173215,  0.119209, -1.044236],
       [-0.861849, -2.104569, -0.494929,  1.071804],
       [ 0.721555, -0.706771, -1.039575,  0.27186 ],
       [-0.424972,  0.56702 ,  0.276232, -1.087401],
       [-0.67369 ,  0.113648, -1.478427,  0.524988],
       [ 0.404705,  0.577046, -1.715002, -1.039268],
       [-0.370647, -1.157892, -1.344312,  0.844885]])

I could get the same array with usecols. With many more columns in the real data this might not be as good (but feel free to try it):
e18=np.genfromtxt('stack33662863.txt',skip_header=1,usecols=range(1,5))

You could load the dates separately with:
In [647]: np.genfromtxt('stack33662863.txt',skip_header=1,usecols=0,dtype=None)
Out[647]:
array([b'"2000-01-01"', b'"2000-01-02"', b'"2000-01-03"', b'"2000-01-04"',
       b'"2000-01-05"', b'"2000-01-06"', b'"2000-01-07"', b'"2000-01-08"'],
      dtype='|S12')

Yet another option - define a dtype with all of the numeric columns:
In [654]: dt=np.dtype([('date','S12'),('data','float',(4,))])
In [655]: e18=np.genfromtxt('stack33662863.txt',skip_header=1,dtype=dt)
In [656]: e18['date']
Out[656]:
array([b'"2000-01-01"', b'"2000-01-02"', b'"2000-01-03"', b'"2000-01-04"',
       b'"2000-01-05"', b'"2000-01-06"', b'"2000-01-07"', b'"2000-01-08"'],
      dtype='|S12')

Now you can retrieve the numeric part as 2d array:
In [658]: e18['data']
Out[658]:
array([[ 0.469112, -0.282863, -1.509059, -1.135632],
       [ 1.212112, -0.173215,  0.119209, -1.044236],
       [-0.861849, -2.104569, -0.494929,  1.071804],
       [ 0.721555, -0.706771, -1.039575,  0.27186 ],
       [-0.424972,  0.56702 ,  0.276232, -1.087401],
       [-0.67369 ,  0.113648, -1.478427,  0.524988],
       [ 0.404705,  0.577046, -1.715002, -1.039268],
       [-0.370647, -1.157892, -1.344312,  0.844885]])

A: actually this worked fine with me using pandas , instead use \s+ as your separator rather than tab , it seems to be that tab character is not the separator in your case
In [10]:
pd.read_csv('C:/nature13173-s4.txt' , sep = '\s+')
Out[10]:
               A           B            C          D
2000-01-01  0.469112    -0.282863   -1.509059   -1.135632
2000-01-02  1.212112    -0.173215   0.119209    -1.044236
2000-01-03  -0.861849   -2.104569   -0.494929   1.071804
2000-01-04  0.721555    -0.706771   -1.039575   0.271860
2000-01-05  -0.424972   0.567020    0.276232    -1.087401
2000-01-06  -0.673690   0.113648    -1.478427   0.524988
2000-01-07  0.404705    0.577046    -1.715002   -1.039268
2000-01-08  -0.370647   -1.157892   -1.344312   0.844885

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does it make sense to add a few footprints into the schematic component in Altium? I'm new to Altium. I have a question about libraries in Altium. If I draw a passive component such as a capacitor in the schematic library of Altium, after all packages of capacitors like 0402, 0603, 1206, and so on separately draw their footprint in PCB Library. Is it suitable to add all footprints into a component symbol in the schematic library of Altium?

A: You can do this, and it's fine if you're doing assembly yourself, but it's not the convention within Altium and it makes getting professional assembly done more complicated.
On the upside, it means you can just make one generic resistor and set its value and pick the right footprint each time you want to add it to a design, without needing to worry about any extra work creating new schematic symbols for each manufacturer part.
However, when you export the bill of materials (BoM) and pick and place files for manufacturing, the generic resistor or capacitor that you've chosen will be exported without an associated part number, so it won't match up with the actual parts you need to order and have assembled. You'll have to manually do all the data entry to make sure the right parts get assigned to the right component designators.
What I do is create schematic library entries for each of the manufacturer part numbers you want to use (you can copy-paste the actual symbol graphics and pins) and then assign the correct footprint for that part. That way, when I export the BoM and assembly documents, I know everything is correct. Since I fill out parametric data for my parts, too, I can quickly find real parts that I know will fit my needs.
You can also use the Manufacturer Part Search to pull information from suppliers, including parametric data and stock information, and import a specific part as its own schematic library item.
If you happen to be using JLCPCB for your designs and assemblies, I auto-generated Altium schematic libraries for all their passives, complete with parametrics, so you can save yourself a lot of time and effort there.

A: It's up to you. If you want each  component in the library to represent a specific component with one or two possible part numbers and suppliers then it doesn't make sense to have multiple footprints.
If you just want a generic capacitor symbol and you'll figure out the BOM part number and suppliers some other time, then your method involves less up-front work (and more work later).
Similarly, you can create different symbols for each value (as well as package) of capacitor or resistor or just have a generic 0402 or whatever. At the extreme you can create a 3D STEP model with value markings for (say) each 0603 resistor and tie that to the component package and value.
Some suppliers such as JLC may make a subset of their available components available as an Altium library, which simplifies ordering PCBA from that one supplier.


text:
Q: exporting drupal database from devlopement box to drupal database (new from install ) in cpanel - duplicate data I am new to phpMyAdmin, and cPanel, I have developed a site in my local box, and now I need to transfer the site into cpanel in the server where the site will be there in test mode.
I have installed drupal in cpanel successfully, and now I want to take my drupal database from my local box to the database in Cpanel .
so the export file I generated, includes all the insert statements for some of the tables that already have those data in cpanel, so obviously I get the duplicate primary key error.
how can I import drupal database data (my local box -development) into the new drupal database( set up when installed drupal in cpanel) without dealing with duplicate data which is for the default tables/data
I am using phpMyAdmin in both my local (dev) box and server side
I appreciate any one 's help

A: I would create a new empty DB on the host, import your dev db, then change the db name in the settings.php file to point to the new DB.


text:
Q: Xcode iOS 4.2.1 -> Give Map View the address to show the pin?
Possible Duplicate:
Forward Geocode Example using CLGeocoder

I have a plist full of names and their adrresses. I want my iOS app to show on a map view a pin with the address of the person he has selected. Can I import the address to map view and get a pin? And how?? Thank you.

A: Use the CLGeocoder class to convert addresses into lat/long coordinates:
Forward Geocode Example using CLGeocoder
The more accurate address you have, the better the result should be so with exact addresses you should get very accurate points.

A: Another option is to use Google's geocoding web service, simply pass the address string to this function and you will get an CLLocationCoordinate2D which contains a latitude & longitude.
Right now it grabs the location at the 0th index, which is the closest matching result. Log out the result to see the JSON response from Google.
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=true&address=%@", esc_addr];
    CLLocationCoordinate2D center;

    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result)
    {
        //NSLog(@"LOC RESULT: %@", result);
        NSError *e;
        NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData: [result dataUsingEncoding:NSUTF8StringEncoding]
                                                                   options: NSJSONReadingMutableContainers
                                                                     error: &e];
        NSArray *resultsArray = [resultDict objectForKey:@"results"];

        if(resultsArray.count > 0)
        {
            resultDict = [[resultsArray objectAtIndex:0] objectForKey:@"geometry"];
            resultDict = [resultDict objectForKey:@"location"];
            center.latitude = [[resultDict objectForKey:@"lat"] floatValue];
            center.longitude = [[resultDict objectForKey:@"lng"] floatValue];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Results Found" message:@"No locations were found using, please try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alert show];
        }

        //goes through each result
        /*for(NSDictionary *dict in resultsArray)
        {
            resultDict = [dict objectForKey:@"geometry"];
            resultDict = [resultDict objectForKey:@"location"];
        }*/
    }
    return center;
}

A: This is whats known as Forward Geocoding, and there is no built in API to do this for you. You need to use an external service, which one you use really depends on your app.
I have used Google's service for this. http://code.google.com/apis/maps/documentation/geocoding/
It is a very simple API, but has restrictions based on your app's license. I know there are a couple other services for this, but I'll leave that as an exercise to you.


text:
Q: Efficiently combine two uneven lists into dictionary based on condition I have two lists of tuples and I want to map elements in e to elements in s based on a condition. The condition is that the 1st element of something in e needs to be >= to the 1st element in s and elements 1+2 in e need to be <= to elements 1+2 in s. The 1st number in each s tuple is a start position and the second is the length. I can do it as follows:
e = [('e1',3,3),('e2',6,2),('e3',330,3)]
s = [('s1',0,10),('s2',11,24),('s3',35,35),('s4',320,29)]

for i in e:
    d = {i:j for j in s if i[1]>=j[1] and i[1]+i[2]<=j[1]+j[2]}
    print(d)

Output (what I want):
{('e1', 3, 3): ('s1', 0, 10)}
{('e2', 6, 2): ('s1', 0, 10)}
{('e3', 330, 3): ('s4', 320, 29)}

Is there a more efficient way to get to this result, ideally without the for loop (at least not a double loop)? I've have tried some things with zip as well as something along the lines of
list(map(lambda i,j: {i:j} if i[1]>=j[1] and i[1]+i[2]<=j[1]+j[2] else None, e, s))
but it is not giving me quite what I am looking for.
The elements in s will never overlap. For example, you wouldn't have ('s1',0,10) and ('s2', 5,15). In other words, the range (0, 0+10) will never overlap with (5,5+15) or that of any other tuple. Additionally, all the tuples in e will be unique.

A: The constraint that the tuples in s can't overlap is pretty strong. In particular, it implies that each value in e can only match with at most one value in s (I think the easiest way to show that is to assume two distinct, non-overlapping tuples in s match with a single element in e and derive a contradiction).
Because of that property, any s-tuple s1 matching an e-tuple e1 has the property that among all tuples sx in s with sx[1]<=e1[1], it is the one with the greatest sum(sx[1:]), since if it weren't then the s-tuple with a small enough 1st coordinate and greater sum would also be a match (which we already know is impossible).
That observation lends itself to a fairly simple algorithm where we linearly walk through both e and s (sorted), keeping track of the s-tuple with the biggest sum. If that sum is big enough compared to the e-tuple we're looking at, add the pair to our result set.
def pairs(e, s):
  # Might be able to skip or replace with .sort() depending
  # on the rest of your program
  e = sorted(e, key=lambda t: t[1])
  s = sorted(s, key=lambda t: t[1])

  i, max_seen, max_sum, results = 0, None, None, {}
  for ex in e:
    while i < len(s) and (sx:=s[i])[1] <= ex[1]:
      if not max_seen or sum(sx[1:]) > max_sum:
        max_seen, max_sum = sx, sum(sx[1:])
      i += 1

    if max_seen and max_sum > sum(ex[1:]):
      results[ex] = s[i]

  return results


text:
Q: setOnClickListener for DialogFragment's button? I'm showing a DialogFragment when a user clicks on the Customize button for an item.
btnCustomize.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(View v){
        CustomDialog dialog = new CustomDialog();
        FragmentManager manager = ((Activity) context).getFragmentManager();
        dialog.show(manager,"tag");
        // the line below throws null pointer exception
        Button btnCustomConfirm = v.findViewById(R.id.btnCustomConfirm);
        btnCustomConfirm.setOnClickListener(new View.OnClickListener(){
            @Override public void onClick(View v){
                //
            }
        });
    }
}

In the dialog's xml layout file there is a Button btnCustomConfirm, but the line btnCustomConfirm.setOnClickListener(...) throws nullpointerexception:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

A: Try changing the line to
Button btnCustomConfirm = v.findViewById(R.id.btnCustomConfirm);

Also, I assume that you have a button with id btnCustomConfirm in the dialog's XML layout.


text:
Q: How to display custom fields on WordPress Product I have an online bookstore that is build from WordPress Woocommerce Plugin. But currently I am not able to add custom fields (author etc.) on a product.
How do i make it possible like the one on the photo below? Adding the Author of the books (highlighted in yellow).

This is the website : libroatbp2011.com

A: This depends on where you want to place it. The easiest way is to use the built in Product Attributes of WooCommerce.

This will display on the "Additional Information" tab on the product page.


text:
Q: Modify user attributes in LDAP using JAVA I'm trying to change the attributes of a user in the LDAP server and when I try to change any attribute of a user in LDAP I get a NoPermissionException however if the user is admin them I'm able to change/add the attributes. my goal is to change the password as well.
javax.naming.NoPermissionException: [LDAP: error code 50 - 00002098: SecErr: DSID-03150F93, problem 4003 (INSUFF_ACCESS_RIGHTS), data 0
]; remaining name 'CN=test,CN=Users,DC=myid,DC=com,DC=local'

My Code
ModificationItem[] mods = new ModificationItem[2];
mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                            new BasicAttribute("department"));
mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
                            new BasicAttribute("department", "New Department"));

ldapCtx.modifyAttributes("CN=test,CN=Users,DC=myid,DC=com,DC=local", mods);

Thanks.

A: After a little research I figured it out. You can delegate those permissions to that user by granting them permission in the Active Directory.

*

*In ADUC (Active Directory Users and Computers), right-click on the OU (Organizational Unit) which contains all the users that you want another user to be able to modify their attributes. Choose "Delegate Control".

*Add the user that you would like to give the ability to. Next.

*Choose "Create a custom task to delegate". Next.

*Choose "Only the following objects in the folder" then "User objects" in the list. Next.

*Uncheck General. Only check Property-specific.

*Under Permissions list, check the entries per your requirement such as
Write Department
Write Telephone Number
Write Street Address

*Click Next and Finish.


text:
Q: Is there any alternate way to supply similar functions as COM does? Window's COM allow us to wrap our application function for out-of-process invocation.  If the COM interfaces are well defined and design, it is certainly great to consume the services via scripts and any programming platform that support COM/Automation/Active-X.
I am just wondering if there exist any alternate methods to design of what COM does?  Or something close or similar methodology?
I am using Delphi in Win32 platform.

A: I'm not entirely sure, but it seems that you're talking about an alternate to COM for creating plug-ins for your software?
If so, there are myriad options:

*

*TMS Software's Plugin Framework

*RemObject's Hydra

*Project JEDI's JVCL includes a plugin system

You can also roll your own. I wrote an article many years ago that provides the fundamentals (though the linked source is long since gone to the great bit bucket in the sky).

A: Corba
or
IBM's SOM
I'm sure there are others as well but those are the 2 others i can think of off the top of my head ...

A: If you want a TCP/IP (over the internet or over a LAN) interface for your objects, consider SOAP, and REST.
If you want to write plugins for your delphi app and not use COM/OLE-Automation, consider RemObjects SDK.


text:
Q: How to match the same cards in two arrays I'm creating a snap game were the player has to match two cards. I've created two arrays one for english cards and one for Spanish cards.The pack generates random cards but I can't get the same cards matching, which the player wins 1 point when the cards are correctly matched.
 var cardNamesArray: [String] = ["sad", "sleepy","angry"]
 var cardNamesArray2: [String] = ["triste", "cansado","enfadado"]

    //first card generate random number
    let firstRandomNumber = Int (arc4random_uniform(3))
    let firstCardString:String = self.cardNamesArray[firstRandomNumber]
    self.FirstCardImageView.image = UIImage(named: firstCardString)

    //Second Card generate random number
    let SecondRandomNumber = Int (arc4random_uniform(3))
    let SecondCardString:String = self.cardNamesArray2[SecondRandomNumber]
    self.SecondCardImageView.image = UIImage(named: SecondCardString)

I tried matching "sad" with "triste" but the score remains the same
        if ["sad"] == ["triste"] {

        print("match")

        self.playerScore += 1
        self.playerScoreLabel.text = String(self.playerScore)

    }

A: At least two different ways to do it, depending on how distant you are from the random number generation:
If you still have the random numbers available, you can use:
if firstRandomNumber == secondRandomNumber {
    print("number match")
}

If you don't still have the random numbers available, but just have the strings, you can use indexOf to find the string in the appropriate array:
if cardNamesArray.indexOf(firstCardString) == cardNamesArray2.indexOf(secondCardString) {
    print("index match")
}


text:
Q: Primary key that is unique over 2 columns in SQLAlchemy Using SQLAlchemy I'm a bit confused about composite keys (?), uniqueconstraint, primarykeyconstraint, etc.
How do I create an class that is unique over 2 columns, and refer to that unique combination? Say each User is unique by his combination of name and email:
class User(Base):
    __tablename__ = 'user'
    name = Column(String)
    email = Column(String)

Should I use UniqueConstraint?:
class User(Base):
    __tablename__ = 'user'
    name = Column(String)
    email = Column(String)
    __table_args__ = (UniqueConstraint(name, email), )

But how do I then refer to a specific user from another class?

A: Thanks for the feedback. Turns out adding a primary_key=True to each column automatically creates a composite primary key, meaning the combination must be unique but each column individually doesn't have to be unique. So this suffices:
class User(Base):
    __tablename__ = 'user'
    name = Column(String, primary_key=True)
    email = Column(String, primary_key=True)


text:
Q: OSX application freezes when try to set the value of TextView? I am really new to Objective-C.
First please see the code:
Here it is the property:
@property (atomic) IBOutlet NSTextView *txtResponse;

And here it is the action:
- (IBAction)sendReq:(id)sender {
    @synchronized(self)
    {
        request *req = [[request alloc] init];

        voidCallback callback = ^(NSURLResponse *resp,  NSData *data, NSError *error) {
            NSString *val = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            [self.txtResponse setString:val];
            //NSLog(val);
        };

        [req setUrl:[[NSURL alloc] initWithString:@"http://foo.bar"]];

        [req setCallback:callback];

        [req send];
    }
}

The UI freezes when I try to use [self.txtResponse setString:val];
I also tried the code without @synchronized(self)
Where is the problem?
Thanks in advance!

A: 3rd day that I am working with objective-c and finally found the answer :)
I used the performSelectorOnMainThread and solved the problem
- (IBAction)sendReq:(id)sender {

    request *req = [[request alloc] init];

    voidCallback callback = ^(NSURLResponse *resp,  NSData *data, NSError *error) {
        NSString *val = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        [self performSelectorOnMainThread:@selector(setResponseValue:) withObject:val waitUntilDone:NO];
    };

    [req setUrl:[[NSURL alloc] initWithString:@"http://programming.com"]];

    [req setCallback:callback];

    [req send];
}

- (void)setResponseValue:(NSString *)resp
{
    [self.txtResponse setString:resp];
    //NSLog(resp);
}


text:
Q: Matrix with each cell equal to sum of its adjacent cells Consider a $m \times n$ matrix $M$ such that each cell in $M$ is equal to the sum of its adjacent cells (sharing either an edge or a corner with this cell). What are the values in this matrix.
I am trying to find a non-zero matrix satisfying this condition. Does there exist such a matrix, or if not, is there a proof for it?
I know that when the matrix values are equal to average of surrounding cells, then all values in the matrix are equal. Is there a similar conclusion we can reach to in this case?

A: For sure such matrix could be found for $m \in 2\mathbb{N}+1, n \in 3\mathbb{N}+2$:
$$\left[\begin{matrix}
a&a&0&-a&-a&0&a&a&0&\cdots & 0 & a &a &  0 &-a &-a\\
0&0&0&0&0&0&0&0&0&\cdots&0&0&0&0&0&0\\
-a&-a&0&a&a&0&-a&-a&0&\cdots & 0 & -a &-a &  0 &a &a\\
0&0&0&0&0&0&0&0&0&\cdots&0&0&0&0&0&0\\
\cdots&&&&&&&&&\cdots\\
0&0&0&0&0&0&0&0&0&\cdots&0&0&0&0&0&0\\
a&a&0&-a&-a&0&a&a&0&\cdots & 0 & a &a &  0 &-a &-a\\
\end{matrix}\right]$$
Of course depending on the value of $n$ and $m$ last row and two last columns might be different (last row might start with $-a, -a$ and last columns might start with $a,a$), but general idea is the same.

A: The point of this answer is to show that the only solutions are Jaroslaw Matlak's solution (when $m \equiv 1 \bmod 2$ and $n \equiv 2 \bmod 3$), the transpose of his solution, and linear combinations of the above (when $m \equiv n \equiv 5 \bmod 6$).
Let's first avoid boundary effects by studying the problem on an $M \times N$ torus, so indices wrap around. Let $\phi$ be the linear map from $M \times N$ matrices which replaces each entry of the matrix with the sum of its $8$ neighbors. We want to understand the $1$-eigenspace of $\phi$.
In fact, it is easy to diagonalize $\phi$ completely. For any $0 \leq a < M$ and $0 \leq b < N$, the matrix
$$A_{jk} = \exp\left( (2 \pi i) \left( \tfrac{aj}{M} + \tfrac{bk}{N} \right) \right)$$
is an eigenvector of $\phi$ with eigenvalue $(2 \cos \tfrac{a \pi}{M} + 1)(2 \cos \tfrac{b \pi}{N} + 1)-1$. That's $MN$ eigenvectors in an $MN$ dimensional vector space, and it is easy to show they are linearly independent. So we have found all the eigenvectors.
We want
$$(2 \cos \tfrac{a \pi}{M} + 1)(2 \cos \tfrac{b \pi}{N} + 1)=2 \quad (\ast).$$ I will now show that the only solutions to $(\ast)$ in integers are $(\cos \tfrac{a \pi}{M}, \cos \tfrac{b \pi}{N}) = (1/2,0)$ and $=(0, 1/2)$.
Lemma Let $M > 6$. Then there is some $a$ with $M/4 < a < 3M/4$ and $\mathrm{GCD}(a,M)=1$.
Proof: We break into cases according to $M \bmod 4$. If $M$ is odd, $\tfrac{M-1}{2}$ does the trick. If $M \equiv 2 \bmod 4$, then $\tfrac{M-4}{2}$ works; if $M \equiv 0 \bmod 4$, then $\tfrac{M-2}{2}$ does. $\square$.
Now, suppose we have a solution to $(\ast)$ in lowest terms with $M>6$. The Galois group of $\mathbb{Q}(\cos \pi/M, \cos \pi/N)$ acts transitively on the values $\cos \tfrac{a \pi}{M}$ with $\mathrm{GCD}(a,M)=1$, so we can apply a Galois automorphism to make $a$ be as in the lemma, with $M/4 < a < 3M/4$.
But then $-1 < 2 \cos \tfrac{\pi a}{M} +1 < 0$, which means that $2 \cos \tfrac{\pi b}{N} +1 < -2$, an impossibility. We have a contradiction and deduce that $M \leq 6$; then we just check cases.
Finally, we need go from the torus case back to the rectangle. Given an $m \times n$ solution to the rectangular problem, we can build a $(2m+2) \times (2n+2)$ solution to the torus problem as shown in the example below for $(m,n) = (2,3)$.
$$\begin{bmatrix}  u&v&w\\x&y&z \\ \end{bmatrix} \leadsto
\begin{bmatrix}
0&0&0&0&0&0&0&0 \\
0&u&v&w&0&-w&-v&-u \\
0&x&y&z&0&-z&-y&-x \\
0&0&0&0&0&0&0&0 \\
0&-x&-y&-z&0&z&y&x \\
0&-u&-v&-w&0&w&v&u \\
\end{bmatrix}.$$
So our previous solutions with $(\tfrac{a}{M}, \tfrac{b}{N}) = (\tfrac{1}{4}, \tfrac{1}{6})$ turn into $(\tfrac{a}{2m+2}, \tfrac{b}{2n+2}) = (\tfrac{1}{4}, \tfrac{1}{6})$ etcetera and, after a bit of cleaning up, we see that Jaroslaw Matlak has found them all.


text:
Q: How to partially color section title without changing the displayed title in pdf? Hi I would like to do something like this to my section title

It seems doable but it gives

on the PDF file bookmarks. Is there a way to remedy this? I have set the default color of the section title to be blue, so the code is as follows
Edu\color{black}{cation}

Thanks!

A: You can give an alternative with \texorpdfstring{Edu\color{black}cation}{Education}.
And please notice that \color{black} does not take any additional arguments, if you want that syntax, use \textcolor{black}{bla}


text:
Q: Can "return this" pattern be optimized to no cost performance? return this (or similar construct) allows method chaining. Lack of it is painful, because you have to write such code (C#):
var list = new List<string>();
list.Add("hello");
list.Add("world");

instead of
list.Add("hello").Add("world");

Elixir solves it nicely for function chaining, instead of relying on callee it relies on caller (forgive me my mistakes, I don't know Elixir):
list |> add("hello") |> add("world");

But now I have just read this sentence at wikipedia:

Returning an object of built-in type from a function usually carries
  little to no overhead, since the object typically fits in a CPU
  register.

On one hand callee does not know if the result will be used or not, on the other hand caller cannot stop callee from setting the result value. So I am skeptical about this "little", but "no overhead"?
Thus MY QUESTION for this very particular pattern (i.e return this with method chaining) -- can it be optimized with no overhead? How?
Question by example -- say I will write a framework and sprinkle every possible method with return this just to give ability for method chaining. The question arise -- will user who does not use method chaining will pay the price of lowered performance? How compiler could optimize code that this feature will have zero cost.
Update after first 2 comments -- "cheap"!="free", so maybe another perspective for my question, why the difference "little" vs. "no cost". If it can be guaranteed it is at no cost, we write "no cost", period. So I assume it cannot be guaranteed, thus "little".
Clarification I am not asking how to make another Elixir-like syntax in other language. I am asking how it is possible for compiler to optimize callee-caller interaction on return this + method chaining (or lack of it, when not used).

A: At least in C#, your desired construct is entirely unnecessary.
You can write something like
var mylist = new List<string>(new[] {"Hello", "World"});
...
mylist.AddRange(new[] {"Add", "Some", "More", "Items"});

which is about as concise as you can get, while still being perfectly readable.
If you really want method chaining in a class, even one that you don't have the source for, you can use extension methods.
public static class ListExtender
{
    public static IList<T> ChainedAdd<T>(this IList<T> list, T item)
    {
        list.Add(item);
        return list;
    }
}

then
 mylist.ChainedAdd("x").ChainedAdd("y").ChainedAdd("z");

A:
Returning an object of built-in type from a function usually carries
  little to no overhead, since the object typically fits in a CPU
  register.

The point of this comment from wikipedia isn't that returning the value has no cost. Overhead is additional cost, and the here the cost is in addition to that of the return value mechanism. The article is contrasting additional work required for objects to have be copied when they are returned.

Thus MY QUESTION for this very particular pattern (i.e return this
  with method chaining) -- can it be optimized with no overhead? How?

In general, no. In particular cases (such as where the function can be inlined) it can be.

A:
can it be optimized with no overhead? How?

As Telastyn wrote, one approach is to have a compiler providing two function versions. If I were in the role of a compiler designer, I would handle it this way:

*

*I would build a compiler with inlining support. Such a tool can obviously optimize the return this statement out when it is not used.

*and if this hypothetical compiler decides not to inline a specific function, optimizing out the machine code equivalent of return this is definitely not worth it (if it would be, the compiler would inline).
So this does not lead to "zero overhead" in a pure mathematical sense, but to "zero overhead" for any practical purpose.

A: If the implementation uses a calling convention that uses the same register to pass the this pointer to a function that it does to return a value from the function, then return this is a zero-cost operation (because the return value is already there).

A: A compiler could guarantee that the return this + function chaining pattern has never worse performance than calling multiple methods on the same object, by always rewriting the former pattern into the latter.
But I think it would be a relatively complicated rewrite and I'm not sure it would be worth the effort. Especially since I believe the return this pattern has a potential to be more efficient, because it means that this doesn't have to remembered by both the caller and the callee: the caller can forget the object while the chain is executing.
Note that the compiler is unlikely to recognize this. So, to take advantage of this (theoretical) optimization, instead of writing:

var list = new List<string>();
list.Add("hello").Add("world");
foo(list);

You would write:
foo(new List<string>().Add("hello").Add("world"));

A: First off,
var list = new List<string>();
list.Add("hello");
list.Add("world");

Is just as, if not more readable than
var list = new List<string>().Add("hello").Add("world");

Lines of code is not, in any way a proxy for code's cleanliness or simplicity.

Thus my question for this very particular pattern (i.e "return this" for method chaining) -- can it be optimized with no overhead? How?

So theoretically, sure. This would be similar to tail call optimization, where you wouldn't need to completely unwind the stack frame when moving between functions, you could leave the this argument where it is when you're done (or just peek rather than pop it in a stack based model). The challenge comes that you can only do that if you know the next call will be a chain. Since functions don't really know about their callers, they don't know if they should clean up after themselves or not. You could have some internal flag, which the function could check to know which path to take, but that would be more expensive than just passing in this all the time.
The compiler could also make two versions of the function, and pick the right one at compile time. That would bloat the resultant executable, slow compilation time, but probably shave an instruction or two from actual runtime.

A: Dart has this feature. So you can do
StringList myList = new StringList()
    ..Add("hello")
    ..Add("world");

Here we can treat F(expr..m(...)) as syntax sugar for:
var _generated_temp = expr;
_generated_temp.m(...);
F(_generated_temp);

You can see Dart also allows setting properties to be chained in the same way:
Person myPerson = new Person()
    ..Name = "Jane Doe"
    ..Age  = 31;

C# gives you a subset of these features with initialization syntax. So you can translate the above into
StringList myList = new StringList { "hello", "world" };

Person myPerson = new Person{ Name = "Jane Doe", Age = 31 };

However, this syntax sugar is available only at initialization and not available for arbitrary method calls, so it is strictly less expressive than Dart's version.
So it is possible to offer fluent interfaces as a language feature, which would remove any performance cost. However, the performance cost of a fluid interface is so negligible as to be effectively nil, so one should not argue for it on those bases. (Note that it might be in theory possible for non-virtual methods that just return this to be optimized away. This optimization would not be worth performing.) Rather, the benefit would be the opportunity to use a fluent interface even when it was not designed for.

A: In theory, yes.  C++ has a term for it: copy elision.  The C++ standard allows for copy elision.  The concept you are asking about, in fact, has its own tla: RVO (return-value optimization).
Essentially, the compiler can (but, unfortunately, is not required to) decide on the space where the return value will reside before the function is called.  This avoids pushing the return value on the stack and then copying it to this space.  The compiler can generate the function code in such a way that instead of changing the value to be pushed on the stack it gets written directly to the space where that stack value will get copied after the function returns.
The reason why this cannot be done always (ie, by default) is that the space where the value is to be copied may contain information which is used during the execution of the function.  But there are well-known methods to get around that, too.  For example, copy-on-write is what operating systems do to blocks of memory shared by multiple processes.  Compilers can, in the same way, do copy-on-write of space which is to be populated at the return of a function.


text:
Q: Use more placeholders in WHERE statement after IN statement with arrays I need more placeholders to be added to the following query. Is this possible? I have no idea where to begin and I can not find any options on the Internet.
The query now:
$in2  = str_repeat('?,', count($arrayid) - 1) . '?';
$sql2 = "SELECT COUNT(id) AS totalacc FROM account WHERE id IN ($in2) ";
$stmt2  = $mysqli->prepare($sql2);
$types2 = str_repeat('i', count($arrayid));
$stmt2->bind_param($types2,...$arrayid);
$stmt2->execute();
$stmt2->bind_result($row['totalacc']);
    while($stmt2->fetch()) $totalacc = $row['totalacc'];

The query I am aiming for:
$countname1 = '(Hallo)';
    $countname = trim(filter_var("%{$countname1}%", FILTER_SANITIZE_STRING));
$in2  = str_repeat('?,', count($arrayid) - 1) . '?';
$sql2 = "SELECT COUNT(id) AS totalacc FROM account WHERE id IN ($in2) AND name LIKE ?";
$stmt2  = $mysqli->prepare($sql2);
$types2 = str_repeat('i', count($arrayid));
$stmt2->bind_param($types2,s,...$arrayid,$countname); // Will never work, but how to do this?
$stmt2->execute();
$stmt2->bind_result($row['totalacc']);
    while($stmt2->fetch()) $totalacc = $row['totalacc'];

A: You just need to append the extra values to your array of parameters and string of types. This should work (untested):
$countname1 = '(Hallo)';
$countname = trim(filter_var("%{$countname1}%", FILTER_SANITIZE_STRING));
$in2  = str_repeat('?,', count($arrayid) - 1) . '?';

$sql2 = "SELECT COUNT(id) AS totalacc FROM account WHERE id IN ($in2) AND name LIKE ?";
$stmt2  = $mysqli->prepare($sql2);

$types2 = str_repeat('i', count($arrayid));
$types2 .= "s"; //append "s" to the end of the $types2 string.
$arrayid[] = $countname; //append the value of $countname to the array of parameters

$stmt2->bind_param($types2, ...$arrayid);
$stmt2->execute();
//...etc

A: The easiest solution would be to use PDO instead of mysqli. This would be so much easier.
If you are stuck with mysqli then you can achieve a similar thing by simply ignoring the types and appending your result to the array.
$countname1 = '(Hallo)';
$countname = "%{$countname1}%";
$in2 = str_repeat('?,', count($arrayid) - 1) . '?';
$sql2 = "SELECT COUNT(id) AS totalacc FROM account WHERE id IN ($in2) AND name LIKE ?";
$stmt2 = $mysqli->prepare($sql2);

$arrayid[] = $countname;
$stmt2->bind_param(str_repeat('s', count($arrayid)), ...$arrayid);
$stmt2->execute();
$stmt2->bind_result($totalacc);
$stmt2->fetch();

You could even write a function to abstract from all of this code.


text:
Q: R read.table long string I have a log file (txt) with separations of tab:
T<=>31158[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>http://tieba.baidu.com/p/1576129401[=]A<=>3504a4[=]B<=>540532[=]V<=>8.00.6001.18702   34682   77  2012-05-07_07-52-43
T<=>31200[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>javascript:var c=rich_postor._getData();c.content=我爱你;for(var i=1;i<=999;i++){PostHandler.post(rich_postor._option.url,c,function(I){rich_postor.showAddResult(I)},function(I){});};void 0[=]A<=>3504a4[=]B<=>540532[=]V<=>8.00.6001.18702   34682   77  2012-05-07_07-52-43
T<=>31212[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>http://tieba.baidu.com/p/1576129401   34682   77  2012-05-07_07-52-43

When I imported this file, it returned error:
df <- read.table("2012-05-07.txt", sep="\t", quote="", stringsAsFactors= FALSE)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
line 2 did not have 4 elements

if I added the arg 'fill= TRUE', no error popped but the dataset was wrong:
df <- read.table("2012-05-07.txt", sep="\t", fill= TRUE, quote="", stringsAsFactors=FALSE)
df[2, ]
V1
T<=>31200[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>javascript:var c=rich_postor._getData();c.content=&
  V2 V3 V4

The first cell should be
T<=>31200[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>javascript:var c=rich_postor._getData();c.content=我爱你;for(var i=1;i<=999;i++){PostHandler.post(rich_postor._option.url,c,function(I){rich_postor.showAddResult(I)},function(I){});};void 0[=]A<=>3504a4[=]B<=>540532[=]V<=>8.00.6001.18702

but it is
T<=>31200[=]P<=>iexplore.exe[=]I<=>1096[=]U<=>javascript:var c=rich_postor._getData();c.content=&

it breaks at #, it seems that the string "我爱你" is the Chinese words for 'I love you'. Could anyone tell me how to get all the string in one cell? Thanks a lot!

A: Set the argument comment.char empty:
read.table("file.txt", header= TRUE, quote= "", sep="\t", comment.char= "", stringsAsFactors= FALSE)


text:
Q: roboflow not generating new version Please help me, when I generate a new version of my dataset, roboflow takes a long time with only 14 images and then generates a new empty version with no images.
1
3

A: Can you help me understand your user flow? When Generating a new version of a dataset you should be taken to the "Generating New Version" page where you have the option to add more source images, rebalance train/test/split, preprocess, augment, and generate.
Addressing the images you attached with unused classes 3-7, if the question here is to remove the unwanted classes, you can do this by clicking Add preprocessing step and selecting modify classes to remove or override a name


text:
Q: JavaFX - Access fx:id from nested FXML So, this is my main FXML file, called 'Home.fxml':
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
    <fx:include source="MenuBar.fxml" />

    <fx:include source="PlayerElement.fxml" />
</VBox>

within that file i am including a music player element which has a label with the fx:id 'songTime', when i try to use 'songTime' within the Controller of Home.fxml i get a NullPointerException, because the fx:id from within a nested fxml doesn't seem to be useable. Is there a easy way to achieve this?

A: It is generally bad practice to expose UI controls outside of the controller for the FXML file in which they occur.
You can inject the controller from the included FXML file into the controller for your Home.fxml file:
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
    <fx:include source="MenuBar.fxml" />

    <fx:include fx:id="player" source="PlayerElement.fxml" />
</VBox>

and in the controller for Home.fxml you can do
public class HomeController {

    @FXML
    private PlayerElementController playerController ;

    // ...
}

where PlayerElementController is the controller class for the PlayerElement.fxml file. This is described under "Nested Controllers" in the documentation, but essentially just use a field whose name is the fx:id for the fx:include with "Controller" appended to it, so here fx:id="player" for the include allows you to inject the controller instance for the included FXML file to the field playerController.
Now just define some methods in PlayerElementController for setting the desired text:
public class PlayerElementController {

    @FXML
    private Label songTime ;

    // note: might want to make the parameter a more appropriate type than string,
    // and perform the conversion to a string in this method...
    public void setSongTime(String songTime) {
        this.songTime.setText(songTime);
    }

    // and similarly here for the return type
    public String getSongTime() {
        return songTime.getText();
    }

    // ...
}

Now back in your HomeController all you need do is
playerController.setSongTime(...);

to set the text. If you need other functionality associated with the label, just define the appropriate methods corresponding to the behavior you need.


text:
Q: Python library for downloading L8-9 data from USGS EarthExplorer A couple of years ago I used to work with Landsat-8 data. I was using kapadia/usgs or yannforget/landsatxplore librairies to download data programmatically from USGS EarthExplorer.
Now I need to download this data again, but it seems these libraries are not maintained anymore.
Is there any up-to-date, currently maintained python library for searching and download Landsat-8 and -9 data from USGS EarthExplorer?

A: After some investigation, I recommend the EODAG library.
This library allows to search, aggregate results, and download data not only from USGS, but also from many other data providers, with a unified API regardless of the provider.


text:
Q: How do I set a program to run on startup and how desktop application's login check done I have a small application built using python and tkinter, and I want  that application to run on startup.
Here I have few questions

*

*My question is how do I actually set the app to run at startup.

*My application needs to login, but I don't understand how I can connect, application with database without placing database credentials in user's downloaded application.

A: There are 2 points here:

*

*how to set-up an application to run at start-up?
If what you call startup if the machine startup before any user logs in, then the answer will depend on the OS. You will have rc scripts on Unix (and Unix-like) systems, or services on Windows.

*how can an unattented application connect to the database?
A common way is to have the application run under a dedicated login (user name). Then you configure the database to accept passwordless connections from that specific login on that specific machine (ideally the same one). Of course that login should have the less possible privileges...

A: What platform do you want to do?
On Windows you can set your built (maybe .exe) in Task Scheduler.

press Start logo and Call Task Scheduler

Open it and Create task

and then setup what app do you want to run in Action tab and don't forget to Naming in General tab
On Linux I used to see somepeople follow this step you can follow from this link below :
How to Schedule Tasks on Linux: An Introduction to Crontab Files
Or you can search for Crontab to see how to setup task with Crontab commands


text:
Q: Customize standalone AIR runtime folder package I'm looking to figure out if there is a way to customize the folder structure when packaging an AIR app with the captive runtime?
As it is right now the folder structure is as follows:
Projectname_standalone [parrentfolder]

*

*Adobe AIR [folder]

*META-INF [folder]

*other folders for images and such [folder]

*mimetype [file in Projectname_standalone folder]

*projectname.exe [file in Projectname_standalone folder]

*projectname.swf [file in Projectname_standalone folder]

What i would like to get is something along the lines with this:
Projectname_standalone [parrentfolder]

*

*data [folder]

*
*

*Adobe AIR [subfolder of data]

*
*

*META-INF [subfolder of data]

*
*

*other folders for images and such [subfolder of data]

*
*

*mimetype [file in data folder]

*projectname.exe [file in Projectname_standalone folder]

*projectname.swf [file in Projectname_standalone folder]

Has anyone any experience with this?I'm working in Flashdevelop, but I assume this would also apply to both Flash Pro and Flash Builder and include some modification of the AIR SDK.


text:
Q: Error: Redis connection to 127.0.0.1:6379 failed - connect EMFILE So I created, an realtime application using socket.io, redis and node.js.
The problem is that with 30 users, I'm already reaching the number of connections of the server ( I'm running Ubuntu 14.04.
And I think it has something to do about the way I connect to redis.
So on one page, I have at most 12 channels to subscribe to. On two socket.io connections, one has 6 channels and the other has the other 6 channels.
Before showing my node js code, what I do, is for each channel, I create a new redis client, so let's say that I have an insert and update channel, on the node.js code, so my code wiil be:
var data = io.of('/data');
data.on('connection', function(client) {
    var insert = redis.createClient();
    var update = redis.createClient();

    insert.subscribe('insert');

    insert.on("message", function(channel, message) {
        client.emit('data_insert', message);
    });

    update.subscribe('update');
    update.on("message", function(channel, message) {
        client.emit('data_update', message);
    });
});

I believe that this is the problem, and that why, with 30 users I'm exceeding the limit of connections of the server, since 30 * 12 + 2 * 30 = 420, plus a few others for everything else, and it's easy to reach 1024.
So how can I optimize the code, to reduce the number of connections per client to one or two the max?
Does it help, to have the var insert = redis.createClient(); outside the data.on('connection')??

A: You should not be creating one (or more) redis connections per client - just keep using the same global one.  Further, there's really no reason to create a client for each channel you want to subscribe to.  Just use the channel argument to figure out which thing to do with the data (in this case, you're doing the same thing on each channel, so even less point in having separate ones).
var data = io.of('/data');
var redis = redis.createClient();
redis.subscribe('insert');
redis.subscribe('update');
data.on('connection', function(client) {
    redis.on("message", function(channel, message) {
        if(channel == 'insert')
            client.emit('data_insert', message);
        else if(channel == 'update')
            client.emit('data_update', message);
    });
});

There are probably better ways to do this, but this is a fairly direct translation of your code into something that uses only one redis connection.
Note that redis subcribers can only subscribe - you will need a second client to publish or do any other redis operations.

A: just for your information (I lost this evening with that)
This does not work (it defaults connecting to localhost:6379 whatever you put in the url):
const redisURL = "redis://foo.bar.org:6379"
redis.createClient( redisURL )

but this DOES WORK (it tries to connect too foo.bar.org)
redis.createClient( {url: redisURL} )

A: Use socket.io's namespace. Within each namespace you can also define rooms but namespace should be enough for your needs.


text:
Q: How to make visible Bluetooth connection on a laptop with Windows 8.1? I have a Toshiba laptop, with Windows 8.1 installed on it and I want to transfer a file from my smart phone (Samsung Galaxy Gio) to the aforementioned laptop.
The problem is that, although I opened the Bluetooth adapter, on the laptop, I can't seem to make it visible to the phone. I tinkered into the Control Panel and all that I found was the on/off switch. Once I turned it on, the laptop also looks for devices, but it doesn't find any, although the phone's Bluetooth is on and visibile.
I am sure that the phone is not the problem because I had successfully sent files from it to another laptop using Bluetooth.
What am I missing?

A: In my case, the laptop had two different Bluetooth driver versions for the same device. The second driver was installed without my knowledge. Uninstalling the last driver installed solved the problem.


text:
Q: What is the length of a point on the real number line? Since an interval is made up of an infinite number of points, I am considering the relation of the length of an interval and the length of a point, this lead me to ask what is the length of a point on the real number line ?
The nested interval theorem made me feel the length of a point should be $0$ because of $\lim_{{n\to\infty}}(b_{n}\!-\!a_{n})=0$
While if the length of a point  on the real number line is $0$, then I get a contradiction : Supposing we remove the point $0$ on the real number line, then there is a gap there, and the width of the gap is $0$ since the length of a point  on the real number line is $0$, however I think the width of the gap being $0$ is equivalent to there being no such gap on the real number line, so this leads to a contradiction.
What's wrong here? Does a point on the real number line have a width? If so, what is the length of a point on the real number line? Infinitesimal?

A: Take for example the rational numbers. They can be considered as having infinitely many gaps, because the don't include the irrationals. However, those gaps have no "width", because you can come arbitrarily close to each irrational from above and below with a rational number.
The situation is similar if you remove a single real number from all real numbers.
In other words: There are just to many of them, so you wont notice if a single one is missing ;).

A: Much like many other 'paradoxes' you'll find that carefully formalizing the problem makes it go away. Whatever counter intuitive phenomena persist is not paradoxical, but simply counter intuitive.
So, what do you mean by length of a point? Well, whatever it is it seems reasonable to define it to have the following properties: 1) the length of an interval $[a,b]$ is $b-a$; and 2) if the point $p$ is contained in an interval, than the length of the point is $\le $ the length of the interval. We further assume all lengths are measured by non-negative real numbers, so there are no infinitesimals around at all.
Now, from these it follows that the length of any point is $0$. So, any notion of length of a point conforming to the above must assign length $0$ to each point. That is a theorem.
Consequently, the situation you describe, where removing a point having length $0$ results in a broken line is a correct description. It is not a paradox but rather a counter intuitive situation. Well, what shall we do with it? You can examine our assumptions and change them, or hone your intuition. In this case, I suggest the latter.

A: Strictly speaking the "number line" does not have a "length" automatically associated with it- we have to add that.  Typically, we define the length of the interval [a, b] (or (a, b), (a, b], [a, b)) to be b- a.  Using that definition of length, the length of a single point is 0.

A: Perhaps this helps: When you remove a point from a line, you don't just pick it out with your fingers and throw it away. Instead, you declare that one point not to be a part of the set you are considering. That is, imagine $L$ is a line. Then "$L$ with one point removed" is a new set, $L'$, that contains all of the points of $L$ except for the point being removed. $L'$ is a subset of $L$. So of course the line is now broken into two pieces - to get from one part of $L'$ to another, you have to cross through the removed point.
This is actually the way my high school geometry teacher explained this question to me when I had it a long time ago, and it stuck with me. It doesn't contradict any of the other answers given, I should say, but it may help you think about how to interpret these things.

A:
What's wrong here ?

This is where you go wrong:

I think the width of the gap is $0$ is equivalent to that there is no such gap exists on the real number line

Much like there are objects with length $0$ (namely, single points), there are real gaps of length zero (namely, the absence of a single point).

A: While this is not supposed to be a complete, satisfying answer, I would like to draw your attention to an area where your "paradox" has a straightforward interpretation.
"In probability theory, one says that an event happens almost surely (sometimes abbreviated as a.s.) if it happens with probability one."  Contrary to what one might expect, probability one does not mean that it will surely happen, for the exact reason that you have pointed out: Individual, but non-negligible gaps of "length" (we ususally set "measure") zero.
Think of drawing a real number from $[-1, 1]$. The probability of drawing $0$ is arbitrarily small; there is an infinity number of other numbers to draw instead. So $P(X = 0)$ is actually $0$, as is the length of the interval $[0, 0]$ - but drawing it is still not impossible. By completeness, $P(X \neq 0) = 1$ - this will almost surely happen (yet not surely).

A:
I think the width of the gap is 0 is equivalent to that there is no such gap exists on the real number line, this leads to a contradiction.

You mix up countable and uncountable sets. Uncountable sets do not have this sort of gaps as countable sets have.
You can remove an arbitrary number of points from a line, and it will still be a line. Think of removing all the irritional numbers from $\mathbb{R}$ to have the set of rational numbers $\mathbb{Q}$.

A: The measure of a discrete point is in fact zero ($0$).
For more, see articles: Null set and Lebesgue measure.

A: As others have pointed out, the length of a single point must be zero for any reasonable definition of length.
Notice however, that "length" and "number of points" are very different ways of measuring size.
For a point the first measure gives zero and the second one gives one.
For an open interval the first measure gives the distance between the endpoints and the second one gives infinity.
A single point is negligible in the sense of length but not in the sense of amount.
If you remove a single point from an interval, the total length does not change.
The number of points also stays the same, but only because the interval has infinitely many points to begin with.
These different ways of associating sets with sizes are called measures.
The measure corresponding to length is called the Lebesgue measure, and the one corresponding to number of points is called the counting measure.
These may or may not mean anything to you at this point, but you will encounter them later on if you continue working with real analysis.
I should probably also point out a possible false reasoning, despite being absent in your question:
The interval $[0,1]$ consists of points, so its total length must be the sum of the lengths of its points.
(We can make sense of uncountable sums. Especially if all numbers are zero, this is easy: then the sum is indeed zero.)
But all points have length zero, so the length of $[0,1]$ is zero, too!
This is not a bad argument, but it turns out that lengths — or measures in general — do not have such an additivity property.
However, if you only take a finite or countable union of disjoint sets, the length of the union is the sum of the lengths.
(I'm ignoring technicalities related to measurability as they are beside the point.)
The set $[0,1]$ is uncountable, so this "naive geometric reasoning" fails, and it can be enlightening to figure out why.

A:
Since an interval is made up of an infinite number of points, I am considering the relation of the length of an interval and the length of a point, this lead me to ask what is the length of a point on the real number line ?
The nested interval theorem made me feel the length of a point should be $0$...

I don't think that the nested interval theorem comes into play here, because it does not require length to be defined. Let's define a set $I$ as a set of all intervals in $\Bbb{R}$, length of an interval is a function $L: I \rightarrow \Bbb{R}$, naturally we can say that if $i$ – an interval with endpoints $a, b$ then $L(i) = d(a, b)$, where function $d: \Bbb{R}x\Bbb{R} \rightarrow \Bbb{R}$ is a distance (not necessarily Euclidean). Now we need to extend the definition of length to a point, because so far L defined on the set of subsets of $\Bbb{R}$ we called $I$. Value $L(x), where \space x \in \Bbb{R}$ is undefined. A natural way to extend the definition of length is to view an element $x$ as a single element set $\{x\}$, which in turn can be expressed as an interval $[x, x]$, then $L([x, x]) = d(x, x)$ which is $0$ according to the definition of distance.
Not to confuse with Cardinality of a single element set: $|\{x\}| = 1$.

...however I think the width of the gap being $0$ is equivalent to there being no such gap on the real number line...

I think the closest thing to having no gaps in a metric space is Cauchy Completness. If $\Bbb{R}^x = \Bbb{R} \setminus \{x\},$ then $\Bbb{R}^x$ is not complete, because there is a Cauchy sequence of numbers ${x_n}$ with the following properties: $x_n \in \Bbb{R^x}$ and $\lim_{{n\to\infty}}x_n=x$, but $x \notin \Bbb{R}^x$. Fact that length of a point is $0$ (or more important that distance satisfies the axiom of Identity of indiscernibles) is useful for completion of an uncompleted space.
Note, however, that cardinality is still the same: $|\Bbb{R}^x| = |\Bbb{R}|$

A: Yes your are absolutely correct.I argue that length of a point is infinitesimal,so is breadth of a line segment.An interval(a,b) is a disjoint union of points.If point has a length 0, 0+0+.......infinity =b-a-finite is impossible.So it should be infinitesimal.Same argument holds for breadth of a line segment.A rectangle of sides a and b whose area is ab is formed by placing a line segment of length a arbitrarily close to one another.If the line segment has breadth 0 then 0+0+......=ab-finite is impossible. similarly we can prove that thickness of a plane rectangular area is infinitesimal. My final conclusion is that length,breadth, thickness of a point is infinitesimal.point has no length is wrong.it is arbitrarily small  . I think this proof clarifies your doubt


text:
Q: Problems with ImageMagick 6.8.5 on CentOS 6.3 I installed ImageMagick from source per their instructions since they didn't have a matching version for our OS.
http://www.imagemagick.org/script/install-source.php
However, I ran make check and it passes everything up to tests/validate-stream.tap 1, and then it just stops there. I've left it sitting for half an hour and I have to Ctrl+c to get out. What am I doing wrong? What's the best way to uninstall and which version should I be using for CentOS 6.3?

A: Uninstall
If your build never reached the make install phase, then no files should have been added to the OS. The prefix you used during your configure should specify where files were placed.  If you left it as default, the likely location is /usr/local/bin for ImageMagick binaries.
I recommend using 3rd party RPM repos as a last resort.  If the version included in your OS will work, then use it.
Install
To install a newer version, consider using RPMForge or RPmfind.  This an other 3rd party RPM repositories often provider newer versions than included with the OS.
RPM search sites like rpmfind.net and pbone.net can help you find 3rd party RPMS.
If you cannot find something, then build your own RPMs.
Install recent ImageMagick on CentOS 6.3


text:
Q: Resetting ReplaySubject in RxJS 6 I have a filterable 'activity log' that's currently implemented using a ReplaySubject (since a few components use it and they might subscribe at different times).
When the user changes the filter settings, a new request is made, however the results are appended to the ReplaySubject rather than replacing it.
I was wondering if there is anyway to update the ReplaySubject to only send through the new items using something like a switchMap?
Otherwise, I might need to either use a BehaviorSubject that returns an array of all the activity entries or recreate the ReplaySubject and notify users (probably by using another observable) to unsubscribe and resubscribe to the new observable.

A: Here is a class that is using the resettable factory posted here before, so you can use
const myReplaySubject = new ResettableReplaySubject<myType>()
import { ReplaySubject, Subject, Observable, SchedulerLike } from "rxjs";
import { startWith, switchMap } from "rxjs/operators";

export class ResettableReplaySubject<T> extends ReplaySubject<T> {

reset: () => void;

constructor(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike) {
    super(bufferSize, windowTime, scheduler);
    const resetable = this.resettable(() => new ReplaySubject<T>(bufferSize, windowTime, scheduler));

    Object.keys(resetable.subject).forEach(key => {
        this[key] = resetable.subject[key];
    })

    Object.keys(resetable.observable).forEach(key => {
        this[key] = resetable.observable[key];
    })

    this.reset = resetable.reset;
}

private resettable<T>(factory: () => Subject<T>): {
    observable: Observable<T>,
    reset(): void,
    subject: Subject<T>,
} {
    const resetter = new Subject<any>();
    const source = new Subject<T>();
    let destination = factory();
    let subscription = source.subscribe(destination);
    return {
        observable: resetter.asObservable().pipe(
            startWith(null),
            switchMap(() => destination)
        ) as Observable<T>,
        reset: () => {
            subscription.unsubscribe();
            destination = factory();
            subscription = source.subscribe(destination);
            resetter.next();
        },
        subject: source,
    };
}
}

A: I had kind of same problem: One of my components subscribed to an ReplaySubject of a shared service. Once navigated away and coming back the former values where still delivered to the component.
Just completing the subject was not enough.
The solutions above seemed to complicated for this purpose but I found another real simple solution in just completing the subject and assigning a newly created one in the shared service like so:
constructor() {
    this.selectedFeatures = new ReplaySubject()
    this.selectedFeaturesObservable$ = this.selectedFeatures.asObservable()
}

completeSelectedFeatures() {
    this.selectedFeatures.complete()
    this.selectedFeatures = new ReplaySubject()
    this.selectedFeaturesObservable$ = this.selectedFeatures.asObservable()

}

I also printed the constructor of the shared service to show the types I used.
That way any time I move away from my component I just call that method on my shared service and hence get a new fresh and empty ReplaySubject anytime I navigate back to my component thats consuming the shared services observable.
I call that method inside ngOnDestroy Angular lifecycle hook:
ngOnDestroy() {
    console.log('unsubscribe')
    this.featureSub.unsubscribe()
    this.sharedDataService.completeSelectedFeatures()
}

A: If you want to be able to reset a subject without having its subscribers explicitly unsubscribe and resubscribe, you could do something like this:
import { Observable, Subject } from "rxjs";
import { startWith, switchMap } from "rxjs/operators";

function resettable<T>(factory: () => Subject<T>): {
  observable: Observable<T>,
  reset(): void,
  subject: Subject<T>
} {
  const resetter = new Subject<any>();
  const source = new Subject<T>();
  let destination = factory();
  let subscription = source.subscribe(destination);
  return {
    observable: resetter.asObservable().pipe(
      startWith(null),
      switchMap(() => destination)
    ),
    reset: () => {
      subscription.unsubscribe();
      destination = factory();
      subscription = source.subscribe(destination);
      resetter.next();
    },
    subject: source
  };
}

resettable will return an object containing:

*

*an observable to which subscribers to the re-settable subject should subscribe;

*a subject upon which you'd call next, error or complete; and

*a reset function that will reset the (inner) subject.

You'd use it like this:
import { ReplaySubject } from "rxjs";
const { observable, reset, subject } = resettable(() => new ReplaySubject(3));
observable.subscribe(value => console.log(`a${value}`)); // a1, a2, a3, a4, a5, a6
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
observable.subscribe(value => console.log(`b${value}`)); // b2, b3, b4, b5, b6
reset();
observable.subscribe(value => console.log(`c${value}`)); // c5, c6
subject.next(5);
subject.next(6);

A: The problem becomes easier if you can use the fact that the buffer consumes data from the original source, and that subscribers to buffered data can switch to the original source after receiving all the old values.
Eg.
let data$ = new Subject<any>() // Data source

let buffer$ = new ReplaySubject<any>()
let bs = data$.subscribe(buffer$)  // Buffer subscribes to data

// Observable that returns values until nearest reset
let getRepeater = () => {
   return concat(buffer$.pipe(
      takeUntil(data$), // Switch from buffer to original source when data comes in
    ), data$)
}

To clear, replace the buffer
// Begin Buffer Clear Sequence
bs.unsubscribe()
buffer$.complete()

buffer$ = new ReplaySubject()
bs = data$.subscribe(buffer$)
buffObs.next(buffer$)

To make the code more functional, you can replace the function getRepeater() with a subject that reflects the latest reference
let buffObs = new ReplaySubject<ReplaySubject<any>>(1)
buffObs.next(buffer$)

let repeater$ = concat(buffObs.pipe(
   takeUntil(data$),
   switchMap((e) => e),
), data$)

The following
    let data$ = new Subject<any>()

    let buffer$ = new ReplaySubject<any>()
    let bs = data$.subscribe(buffer$)

    let buffObs = new ReplaySubject<ReplaySubject<any>>(1)
    buffObs.next(buffer$)

    let repeater$ = concat(buffObs.pipe(
      takeUntil(data$),
      switchMap((e) => e),
    ), data$)

    // Begin Test

    data$.next(1)
    data$.next(2)
    data$.next(3)

    console.log('rep1 sub')
    let r1 = repeater$.subscribe((e) => {
      console.log('rep1 ' + e)
    })

    // Begin Buffer Clear Sequence
    bs.unsubscribe()
    buffer$.complete()

    buffer$ = new ReplaySubject()
    bs = data$.subscribe(buffer$)
    buffObs.next(buffer$)
    // End Buffer Clear Sequence

    console.log('rep2 sub')
    let r2 = repeater$.subscribe((e) => {
      console.log('rep2 ' + e)
    })

    data$.next(4)
    data$.next(5)
    data$.next(6)

    r1.unsubscribe()
    r2.unsubscribe()

    data$.next(7)
    data$.next(8)
    data$.next(9)

    console.log('rep3 sub')
    let r3 = repeater$.subscribe((e) => {
      console.log('rep3 ' + e)
    })

Outputs
rep1 sub
rep1 1
rep1 2
rep1 3
rep2 sub
rep1 4
rep2 4
rep1 5
rep2 5
rep1 6
rep2 6
rep3 sub
rep3 4
rep3 5
rep3 6
rep3 7
rep3 8
rep3 9

A: For certain situations (ex. where everything is contained in one class), here's what I believe is a very concise solution, with few moving parts:

*

*new subscribers will get the latest from value$$ unless reset$$ has been called since the last value

*existing subscribers get each new item emitted to value$$
const value$$ = new Subject();
const reset$$ = new Subject();

const value$ = reset$$.pipe(
  // can optionally startWith(null)
  map(() => value$$.pipe(shareReplay(1)), // create a new stream every time reset emits
  shareReplay(1), // this shares the latest cached value stream emitted
  switchAll(), // subscribe to the inner cached value stream
)


text:
Q: Calling class properties from within protocol extension In using protocol extension for default implementation I encounter a problem. I define a protocol with different optional properties and functions to use. In the extension I implement a default function and nil properties. In the implementation I use properties and functions from within the protocol.
On the device it works how I expect. Also on the debugger it gave me the property from the class when I run into breakpoint within the extension implementation.
Can someone help me out why I didn't get the property in the example from the class but the nil property from extension.
Example from playground
import UIKit

protocol Collectable {

    var item: String?  { get }
    func collect()
}

extension Collectable {
    var item: String?  { return nil }
    func collect() {
        if let some = item {
            print("collect \(some)")
        } else {
            print("nothing")
        }
    }
}

class Car: Collectable {
    var item = "letter"
}

let car = Car()
car.collect()

A: In the protocol your item is optional string, while in your class you declared another variable named also item. Your collect function is looking for the optional item, and in the extension you specified that it should return nil.

A: As @SavcaMarin stated in their answer, you have a type conflict between the item property declared in your extension (String?) and the one in your Car (String).
You can see this if you comment the extension.  The compiler will tell you that Car does not conform to Collectable.  If you ask it to create the required stubs it will create func collect and var item: String?.  It then gives an error that item is re-defined.
As Rob and Matt pointed out in comments on the other answer, this seems to be a bug in the Swift compiler. It doesn't indicate the re-definition of item or the non-conformance of your item to the protocol if there is a default implementation that satisfies the protocol conformance (your extension).
The simple fix is to tell Swift that the item in Car is the same as item in Collectable by declaring the type explicitly (String?) rather than relying on type inference (Which gives String):
class Car: Collectable {
    var item:String? = "letter"
}


text:
Q: Autofac - injected instance doesn't work as singleton I register necessary type with Autofac as InstancePerLifetimeScope:
builder.RegisterType<WebSecurityContext>()
                .AsSelf()
                .InstancePerLifetimeScope();

and resolve it through interface:
builder.Register<IApplicationContext>(context =>
            {
                return context.Resolve<WebSecurityContext>();
            })
            .As<IApplicationContext>();

I inject ApplicationContext in my WebAPI controller:
public class MedicalCenterController : BaseApiController
{
    private readonly IApplicationContext applicationContext;

    public MedicalCenterController(IApplicationContext applicationContext)
    {
        this.applicationContext = applicationContext;
    }

ApplicationContext has MedicalCenterId value. This value should change after select of new medical center on UI.
Changing of the MedicalCenterId occurs in the action filter which also contains the necessary context.
public class MedicalCenterAttribute : ActionFilterAttribute
{
    public IApplicationContext ApplicationContext
    {
        get;
        set;
    }

    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        .....
        ApplicationContext.SetMedicalCenterId(medicalCenterId);
    }
}

But after it, ApplicationContext continues to have previous value of MedicalCenterId in MedicalCenterController and another controllers.
Why autofac uses different instances in different classes, though I use InstancePerLifetimeScope object?
Thanks.

A: Do not confuse lifetime scopes with singletons. Instances with lifetime scope will behave similar to singletons, but only within each lifetime scope. Thus, depending services resolved from a lifetime scope will get the same instance, but services resolved in another lifetime scope will get a different instance.
So, with Autofac in ASP.NET, in addition to the global/root lifetime scope shared by the whole application, each request gets a new lifetime scope. Since the application context in your case is registered with lifetime scope, on each request a new application context is created. The changes made to one instance is only seen by services within the same lifetime scope, and will be lost as soon as the request is done.
So, do not confuse lifetime scopes with singletons. A singleton must be registered with SingleInstance, not InstancePerLifetimeScope.
Update: since you are looking for a way to set "medical center id" per user, this is something you should not handle inside Autofac. My advice is to have ApplicationContext load/store that value in some user-specific store. That way, whenever you query MedicalCenterId it will be served per user, independent on how you register ApplicationContext in your container.


text:
Q: How do I get 2560x1440 resolution within VirtualBox on a Mac? I'm trying to get a functional Ubuntu instance running in VirtualBox on my iMac 27".  The iMac has a resolution of 2560x1440, and I'd like to run Ubuntu in full screen at that resolution.
I've installed the Guest Additions that come with VirtualBox (rather than the ones in the archive).  I'm using Ubuntu 11.10 64 bit.
The display currently runs at 1600x1200, and when I run the displays dialog (or xrandr), I get a list of resolutions that are 1600x1200 or smaller, and are all at 4:3 aspect ratio (whereas the iMac monitor is 16:9).
The settings for the virtual machine have video memory set to 128MB.  Whether I run the VM with or without 3D acceleration makes no difference to the available resolutions (although with 3D acceleration enabled, launched windows aren't visible – a different question perhaps).
I have a natty VirtualBox VM that does run at 2560x1440, so I know it's possible.  However, I don't know how to achieve it.
Thanks,
jml

A: Well this is embarrassing.
It turns out that all I needed to do was run in full screen mode and then Ubuntu will figure out the new resolution automatically.  I could have sworn I tried that.  Oh well.
Don't know how to "cancel" this question, I'm afraid.

A: This question has already been answered, however, I'd like to share the following post worked for me, namely commands I used were:
xrandr --newmode "2560x1440_60.00" 311.83  2560 2744 3024 3488  1440 1441 1444 1490  -HSync +Vsync
xrandr --addmode Virtual1 2560x1440_60.00

A: I found increasing the Video Memory to 128MB in the Virtual Machine display settings worked for me.

A: I've never used VB on Mac, but on Windows it might be impossible sometimes to get a high resolution. In general:

*

*3D accelleration (as far as I was interested in it last time) was highly experimental and may not work correctly.

*If acceleration doesn'yt work, operating system (or rather GNOME) might not show options for making the resolution too high (or rather too expensive in the meaning of performance)
These are the limiting factors. However You may (carefully) try to change settings: create xorg.conf.new file and there in the proper section set the resolution.
The second thing might be that Your hardware (monitor) is not recognized by Ubuntu. So looking up xorg.conf.new would give us the hint.

A: this may not be possible as i have found instances of 64 bit OS' under vbox to still be lacking comapred to 32 bit (i'm running 4.1.8) so it may be a current limitation of the 64 bit at this time , but maybe you can manually set the resolution in xrandr
you may want to refer to xrandr --help from a terminal


text:
Q: Confused how to read assembly instruction I have some questions dealing with reading assembly instruction. I know the basic instruction syntax, but it gets confusing when some of the register comes with some address in front of it, or the question uses any of the strange instruction. Is there any easy to understand set of reference to the assembly instructions?
For example, I have a question to read these instruction:
0x401050    <what>:         push   %ebp
0x401051    <what+1>:       mov    %esp,%ebp
0x401053    <what+3>:       sub    $0xc,%esp
0x401056    <what+6>:       mov    0x8(%ebp),%eax
0x401059    <what+9>:       add    $0x4,%eax
0x40105c    <what+12>:      mov    %eax,0xfffffffc(%ebp)
0x40105f    <what+15>:      mov    0x8(%ebp),%eax
0x401062    <what+18>:      imul   0xc(%ebp),%eax
0x401066    <what+22>:      mov    %eax,0xfffffff8(%ebp)
0x401069    <what+25>:      mov    0xc(%ebp),%edx
0x40106c    <what+28>:      mov    0x8(%ebp),%eax
0x40106f    <what+31>:      sub    %edx,%eax
0x401071    <what+33>:      mov    %eax,0xfffffff4(%ebp)
0x401074    <what+36>:      mov    0xfffffff8(%ebp),%eax
0x401077    <what+39>:      add    0xfffffffc(%ebp),%eax
0x40107a    <what+42>:      add    0xfffffff4(%ebp),%eax
0x40107d    <what+45>:      leave
0x40107e    <what+46>:      ret
0x401089    <main>:         push   %ebp
0x40108a    <main+1>:       mov    %esp,%ebp
0x40108c    <main+3>:       sub    $0x18,%esp
0x40108f    <main+6>:       and    $0xfffffff0,%esp
0x401092    <main+9>:       mov    $0x0,%eax
0x401097    <main+14>:      mov    %eax,0xfffffff0(%ebp)
0x40109a    <main+17>:      mov    0xfffffff0(%ebp),%eax
0x40109d    <main+20>:      call   0x401420 <_alloca>
0x4010a2    <main+25>:      call   0x4014b0 <__main>
0x4010a7    <main+30>:      mov    0xc(%ebp),%eax
0x4010aa    <main+33>:      add    $0x4,%eax
0x4010ad    <main+36>:      mov    (%eax),%eax
0x4010af    <main+38>:      mov    %eax,(%esp)
0x4010b2    <main+41>:      call   0x4014d0 <atoi>
0x4010b7    <main+46>:      mov    %eax,0xfffffffc(%ebp)
0x4010ba    <main+49>:      mov    0xc(%ebp),%eax
0x4010bd    <main+52>:      add    $0x8,%eax
0x4010c0    <main+55>:      mov    (%eax),%eax
0x4010c2    <main+57>:      mov    %eax,(%esp)
0x4010c5    <main+60>:      call   0x4014d0 <atoi>
0x4010ca    <main+65>:      mov    %eax,0xfffffff8(%ebp)
0x4010cd    <main+68>:      mov    0xfffffff8(%ebp),%eax
0x4010d0    <main+71>:      inc    %eax
0x4010d1    <main+72>:      mov    %eax,0x4(%esp)
0x4010d5    <main+76>:      mov    0xfffffffc(%ebp),%eax
0x4010d8    <main+79>:      add    $0x2,%eax
0x4010db    <main+82>:      mov    %eax,(%esp)
0x4010de    <main+85>:      call   0x401050 <what>
0x4010e3    <main+90>:      mov    %eax,0xfffffff4(%ebp)
0x4010e6    <main+93>:      mov    0xfffffff4(%ebp),%eax
0x4010e9    <main+96>:      mov    %eax,0x4(%esp)
0x4010ed    <main+100>:     movl   $0x40107f,(%esp)
0x4010f4    <main+107>:     call   0x4014c0 <printf>
0x4010f9    <main+112>:     mov    $0x0,%eax
0x4010fe    <main+117>:     leave
0x4010ff    <main+118>:     ret

The questions are:
This program is invoked from the command line as shown:
./program 5 7
The procedure named what is called from main, with the following argument(s):
1)  6, 8
2)  7, 8
3)  5, 7
4)  7, 5

The procedure named what is called from main, and returns to main with the value:
1)  11
2)  24
3)  42
4)  66

Could anyone guide me how the instructions in this example works? Any suggestion or help would be appreciated. Thanks.

A: You should try and loading that binary into IDA. IDA gives you a better view of the structure and its easier to understand what it is you are trying to ask (aside from reading instructions).
Edit: https://www.hex-rays.com/products/ida/
This is for binaries, if it fits your needs, there is a free version of this software on the above page as well. You can use the demo version to do your work as well. I have used IDA Pro (demo) for viewing and editing iOS App Binaries.
To the comments below, you are the worst thing about Stack Exchange - therefore this is the last time I try to help. Reddit it is.


text:
Q: How do I turn off slow motion in the iPhone simulator? I don't know if it's because I'm using a Mighty Mouse or what, but I keep accidently turning on Slow Motion when using the iPhone simulator. How the heck do I turn it off?

A: I just installed "slowmo", as mentioned above, and it works on the 3.2 simulator. It took me a while to figure out how to enable it. You have to check "simulate hardware keyboard" in the simulator's hardware menu, and then press your Mac's shift key 3 times in rapid succession to toggle it on/off.

A: I think, In iOS 8 and above, it's Cmd+T

A: Updated: version 11.3 (2019 Dec) works fine.
I have iOS Simulator version 8.3 (Xcode 6) and the new shortcut is command ⌘ + T to toggle "Slow Animations"

A: Pre beta 5 it was tripple shift. Apple changed (or broke it) see this question (which doesn't have an answer).

A: I'm not totally sure, but I notice toggeling 'demo mode' in the menu sometimes does the trick, and sometimes does not.  I'm also not totally sure if there actually is a slow motion feature, or if that is a bug in the simulator.

A: You can download "slowmo" from http://mschrag.github.com/ to re-enable the slow motion feature, allowing you to toggle between modes.
I tested it on the iPhone Simulator 3.1 (139.1) and it still works.
Run the slowmo.sh script in the download, then press shift 3 times in quick succession.


text:
Q: DBF file exist while user has been dropped? I am new to Oracle. I have dropped some users from my database using:
DROP USER username cascade;

The issue is that the .dbf file still exists in the $ORACLE_HOME/dbs/oradata/ directory, which is creating disk space issues.
Can I remove the unused file directly or by some other processes? Also the size of the .trc file has increased to 16 GB. How can I clean that up?
I can delete these file directly but not sure that it may cause any start up or configuration issue, which I don't want.
Simply my concern is to get rid of disk space issue from the above unwanted files.

A: Datafiles are allocated to tablespaces, not users. Dropping the users will remove the tables etc. from the tablespace, but the underlying storage is not affected.
Don't delete the dbf files from the filesystem directly, you'll get your database into a mess. To remove them, find which tablespace the files belong to using the following statement:
select tablespace_name
from   dba_data_files
where  file_name = <file name with full path>;

You can then remove the file(s) by dropping the tablespace:
drop tablespace <tablespace_name> including contents and datafiles;

Before doing this you should verify that there aren't any objects still allocated to the tablespace for other users however. You can find this by running:
select * from dba_segments
where  tablespace_name = <tablespace to drop>;

If this returns anything, move the objects to another tablespace if you want to keep them before dropping the tablespace.


text:
Q: Internet Authentication Service (IAS) failure when SQL logging server unavailable We are setting up netlogin on our network switches to authenticate computers prior to letting them on the network. In the process, the switch will send the MAC address of the computer to the RADIUS server (we are using Windows Server 2003 IAS) to determine what VLAN the computer should be in.
In IAS there is an option for logging where you can log all authentication attempts to a central SQL server (we are using MSSQL Server 2005). This works great... until the SQL server is unavailable. According to Microsoft's own documentation:

If the IAS server cannot establish a
connection with SQL Server 2000, the
IAS server stops processing
authentication and accounting requests
and users cannot log on to the network

I couldn't believe what I read, until I tested it. If the logging server is unavailable users cannot log onto the network?!?! Since when is logging a critical function? We have offices in many locations and the SQL server in a central office, so if a link to an outlying office goes down, the users would no longer be able to log onto the network because the SQL server would be unreachable.
Is there any way to log IAS actions without having the whole process fail if the SQL server cannot be reached?

A: If this is going to be a mission critical thing I'd suggest clustering your SQL Server. That particular drawback is specific to IAS so you'd have to take that up with Microsoft. Sorry :-/

A: For security purposes, logging is critical because the first thing hackers will do is disable logging to prevent being busted.  SQL Server's own security auditing can be set up to function this same way - if logging stops working, then the instance stops.  It's hard-core, but the security geeks say that's the way to go.

A: Install a local version of SQL Server on each IAS server. If logging isn't critical for you, that should work. It may mean a beefier solution, but that's the only way of doing this without deploying a separate server (which would be my normal preference) just for the SQL Server in each location. You can then use some sort of process to periodically pull records out of each local SQL Server instance to post to a centralized SQL Server for reporting purposes.