text:
Q: Extract data into new workbook based on value in excel I want to extract data from one speadsheet to another based on value of a particular cell.
I want to extract data to a new workbook based on Product. For example, Data for all the customer who purchased HDD should be moved to a new workbook and data for all customer who purchased monitor should be moved to another workbook. I 257 different product types, so data needs to be send to 257 different workbooks.
I was just wondering if there is any feature in excel through which we can search for value(Product in this senario) and move it to another worksheet.
Can anyone please help me regarding this?
Thanks in advance.

A: As tkacprow said there is no 'out of the box' tool that wil do this for you in excel. You will ideally need a VBA macro to do this.
I have just uploaded to my website an example tool/workbook which has the required VBA macro built into it. Feel free to utilise and change this to meet you needs http://tomwinslow.co.uk/handy-excel-tools/.
Let me know if this is not exactly what you are looking for and I can try amend it.
Hope this helps.
Below is the code incase you would prefer it, rather than downloading from my site.
Sub splitMasterList()

    Dim MAST As Worksheet
    Set MAST = Sheets("MASTER")

    Dim headerRng As Range
    Dim areaSelectionCount As Long
    Dim areaSelectionIsValid As Boolean
    Dim areaSelectionRow As Long
    Dim splitColRng As Range
    Dim themeExists As Boolean
    Dim themeArray() As String
    ReDim Preserve themeArray(1 To 1)
    Dim lastRow As Long
    Dim lastSheetTabRow As Long
    Dim i As Long
    Dim ii As Long
    Dim theme As String
    Dim doesSheetExist As Boolean
    Dim ws As Worksheet
    Dim sheetTabRowCounter As Long

    'ask the user to highlight the table header
    On Error Resume Next
    Set headerRng = Application.InputBox(prompt:="Please select the headings of all columns that you wish to utilise." & vbNewLine & vbNewLine & "Note: Hold the 'Ctrl' key to select multiple ranges." & vbNewLine & vbNewLine, Default:="", Type:=8)
    On Error GoTo 0
    If headerRng Is Nothing Then
        'notify user that the process cannot continue
'        MsgBox "You must select a range to undertake this process."
        'exit the sub
        Exit Sub
    End If

    'check how many areas were selected and that they all have 1 row and are all on the same line
    areaSelectionCount = headerRng.Areas.Count
    areaSelectionIsValid = True
    areaSelectionRow = 0
    'loop through all areas checking they are a vald header
    i = 1
    For i = 1 To areaSelectionCount
        'check selection area row count
        If headerRng.Areas(i).Rows.Count <> 1 Then
            areaSelectionIsValid = False
        End If
        'check selection area row
        If areaSelectionRow = 0 Then
            'set areaSelectionRow
            areaSelectionRow = headerRng.Areas(i).Row
        Else
            'test areaSelectionRow variable against the row of the area selection
            If areaSelectionRow <> headerRng.Areas(i).Row Then
                areaSelectionIsValid = False
            End If
        End If

    Next i

    'exit if the area selection is not valid (FALSE)
    If areaSelectionIsValid = False Then
        'notify user that the process cannot continue
        MsgBox "You may only select headings from a single row. Please try again."
        'exit the sub
        Exit Sub
    End If

    'ask the user to select the cell heading which they would like to plit their data on
    On Error Resume Next
    Set splitColRng = Application.InputBox("Select a cell from anywhere in the column which you want to use to classify (split) your data.", Default:="", Type:=8)
    On Error GoTo 0
    If splitColRng Is Nothing Then
        'notify user that the process cannot continue
        MsgBox "You must select a cell to undertake this process. Please start again."
        'exit the sub
        Exit Sub
    End If

    On Error GoTo errorHandling

    'turn updating off
    Application.ScreenUpdating = False

    'loop down the master data and
    lastRow = MAST.Cells(MAST.Rows.Count, "C").End(xlUp).Row

    'loop down the items in the table and build an array of all themes (based on the user split cell selection)
    For i = headerRng.Row + 1 To lastRow
        'if the theme is blank then insert place holder
        If MAST.Cells(i, splitColRng.Column).Value = "" Then
            MAST.Cells(i, splitColRng.Column).Value = "Blank / TBC"
        End If
        'get the theme
        theme = MAST.Cells(i, splitColRng.Column).Value
        'check if the theme exists in the array yet
        themeExists = False
        ii = 1
        For ii = 1 To UBound(themeArray)
            If themeArray(ii) = theme Then
                'stop loop and do not add current theme to the array
                themeExists = True
            End If
        Next ii

        If themeExists = False Then
            'add current theme
            themeArray(UBound(themeArray)) = MAST.Cells(i, splitColRng.Column).Value
            ReDim Preserve themeArray(1 To UBound(themeArray) + 1)
        End If

    Next i

    'notify the user how many themes there are going to be
'    MsgBox "The table is about to be split into " & UBound(themeArray) - 1 & " seperate sheets, each containing grouped data based on the column you selected."

    'loop through the theme array and build a :
    '-sheet
    '-table
    '-rows
    'for each theme
    ii = 1
    For ii = 1 To UBound(themeArray) - 1
        'check if sheet exists
        'check if a worksheet by the name of this theme exists and create one if not
        'returns TRUE if the sheet exists in the workbook
        doesSheetExist = False
        For Each ws In Worksheets
          If Left(Replace(Replace(Replace(Replace(Replace(themeArray(ii), ",", ""), "/", ""), "\", ""), "[", ""), "]", ""), 25) = ws.Name Then
            doesSheetExist = True
          End If
        Next ws

        'create sheet if it does not exist
        If doesSheetExist = False Then
            'create sheet after the master sheet
            Worksheets.Add After:=Worksheets(Worksheets.Count)
            Set ws = ActiveSheet
            'max sheet name is 31 characters and cannot contain special characters
            ws.Name = Left(Replace(Replace(Replace(Replace(Replace(themeArray(ii), ",", ""), "/", ""), "\", ""), "[", ""), "]", ""), 25)
        Else
            'do not creat sheet but activate the existing
            Sheets(Left(Replace(Replace(Replace(Replace(Replace(themeArray(ii), ",", ""), "/", ""), "\", ""), "[", ""), "]", ""), 25)).Activate
            Set ws = ActiveSheet
        End If

        'delete any old data out of the sheet
        lastSheetTabRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
        If lastSheetTabRow < 4 Then
            lastSheetTabRow = 4
        End If
        ws.Rows("4:" & lastSheetTabRow).Delete Shift:=xlUp

        'copy table header into each sheet tab
        headerRng.Copy
        ws.Range("B4").Select
        ws.Paste

        'insert title and time stamp details into new sheet
        ws.Range("B2").Value = themeArray(ii)
        ws.Range("B2").Font.Size = 22
        ws.Range("B2").Font.Bold = True
        ws.Range("B1").Font.Size = 8
        ws.Range("C1:D1").Font.Size = 8
        ws.Range("C1:D1").Cells.Merge
        ws.Range("B1").Value = "Timestamp : "
        ws.Range("C1").Value = Now()
        ws.Range("C1").HorizontalAlignment = xlLeft
        ws.Range("E1").Value = "Updates must NOT be done in this worksheet!"
        ws.Range("E1").Font.Color = vbRed

        'loop down the items in the master table and copy them over to the correct sheet tabs based on selected theme/column
        sheetTabRowCounter = 1
        i = headerRng.Row + 1
        For i = headerRng.Row + 1 To lastRow
            'copy item from master into theme tab if matches the theme
            If MAST.Cells(i, splitColRng.Column).Value = themeArray(ii) Then
                'copy row
                MAST.Activate
                headerRng.Offset(i - headerRng.Row, 0).Copy
                'paste row
                ws.Activate
                ws.Cells(sheetTabRowCounter + 4, 2).Select
                ws.Paste
                'add one to the sheet row couter
                sheetTabRowCounter = sheetTabRowCounter + 1
            End If

        Next i

    Next ii

    'format new sheet
    'loop through all theme sheets and size their columns to match tre master sheet
    ii = 1
    For ii = 1 To UBound(themeArray) - 1

        Sheets(Left(Replace(Replace(Replace(Replace(Replace(themeArray(ii), ",", ""), "/", ""), "\", ""), "[", ""), "]", ""), 25)).Activate
        Set ws = ActiveSheet

        'loop through all of the columns on the master table and get their size
        i = headerRng.Column
        For i = headerRng.Column To (headerRng.Column + headerRng.Columns.Count + 1)
            ws.Columns(i).ColumnWidth = MAST.Columns(i).ColumnWidth
        Next i

        'loop down sheet tab and autofit all row heights
        ws.Rows.AutoFit

        ws.Columns("A").ColumnWidth = 2

        ws.Activate

        'hide gridlines
        ActiveWindow.DisplayGridlines = False

        'freeze panes
        ActiveWindow.FreezePanes = False
        ws.Cells(5, 1).Select
        ActiveWindow.FreezePanes = True

        ws.Range("A1").Select

    Next ii

    'loop through all sheets and delete sheets where the timestamp exists but is older than 5 seconds
    For Each ws In Worksheets
        'check if cell contains a date
        If IsDate(ws.Range("C1").Value) = True And ws.Range("B1").Value = "Timestamp : " Then

            'delete when sheet is older than 10 seconds
            If (Now() - ws.Range("C1").Value) < 10 / 86400 Then
                'MsgBox "OK - " & Now() - ws.Range("C1").Value
            Else
                Application.DisplayAlerts = False
                ws.Delete
                Application.DisplayAlerts = True
            End If

        End If

    Next ws

    Application.CutCopyMode = False

    'activate the master sheet
    MAST.Activate
    MAST.Range("A1").Select

    'turn updating back on
    Application.ScreenUpdating = True

    'notify user process is complete
    MsgBox "Done!"

Exit Sub
errorHandling:
    'notify the user of error
    'activate the master sheet
    MAST.Activate
    MAST.Range("A1").Select

    'turn updating back on
    Application.ScreenUpdating = True

    'notify user process is complete
    MsgBox "Something went wrong! Please try again." & vbNewLine & vbNewLine & "Note: This error may be being caused by an invalid heading selection range." & vbNewLine & vbNewLine & "If the problem persists contact Tom Winslow for assistance."

End Sub

A: I do not suspect there is any out of the box "feature" to do this. However I would approach this as folows:

*

*Sort the product by your category (so that all items going into a single workbook are line by line)

*Do a simple VBA loop which: Checks if the product is of a new type. If yes then it should close the last open product workbook, create a new workbook e.g. using the name of the product, and saves the line to that workbook. If not then save the line to the current created and open workbook.

If you have problems with this VBA post it and we will help.


text:
Q: How to create a form for each entry/record in a table in Microsoft Access 2013? I have a table in MS Access 2013 with 217 records in. I would like to create a form for each of these, but is there a way to do this without designing each one manually?
My overall goal is to have a table with a list of sites and in another field what Trust they belong to, and when I click on the name of the Trust I am taken to a form with all the information about that Trust.
Thank you in advance!
Jenna

A: Forms are visual representation of tables. With single forms, each record is displayed on each navigable page. Plus, single forms can have subforms. With continuous forms (multiple item forms) or datasheets, multiple records are displayed on a scrollable page.
You don't need to create a new form for each record but use same form that is filtered to a specific record using the DoCmd.OpenForm method's where argument. In your example, behind the button that opens other form, filter the opening form filtered to that particular trust:
VBA route
DoCmd.OpenForm "OpeningFormName",  acNormal,  , "TrustID=" & Forms!MainFormName!TrustID"

Macro route
Action: OpenForm  (search drop down)
Form Name: OpeningFormName (search drop down)
Filter: [leave blank]
Where Condition =: TrustID=Forms!MainFormName!TrustID
Data Mode: [leave blank]
Window Mode: [leave default of Normal]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't access variables outside loop fetching mysql data in bash I am currently trying to access variables outside of a loop which fetches 2 columns of a MySQL table in Bash:
mysql dbnameplaceholder -N -uusernameplaceholder -ppasswordplaceholder -
h127.0.0.1 -se "SELECT value1,value2 FROM table1 WHERE
value1='placeholdervalue'" | while read -r value1 value2;
do
    var_value1="$value1"
    var_value2="$value2"
done
echo "$var_value1  $var_value2" >> /tmp/script_debug

but the output is empty.
I did read up on the scope of variables here http://mywiki.wooledge.org/BashFAQ/024 and changed my original code to the following:
var_value1="NULL"
var_value1="NULL"
while read -r value1 value2;
do
    var_value1="$value1"
    var_value2="$value2"
done < <(mysql dbnameplaceholder -N -uusernameplaceholder -ppasswordplaceholder -
h127.0.0.1 -se "SELECT value1,value2 FROM table1 WHERE
value1='placeholdervalue'")
echo "$var_value1  $var_value2" >> /tmp/script_debug

but that did not work either.
By the way if i echo inside the loop i get the expected results so there is no MySQL query issue. Im no Bash expert so im kind of lost here.


text:
Q: Pass data from parent swf to child swf I have two swf, A.swf and B.swf: B.swf is a child of A.swf. Each swf has its DocumentClass. Now: I must pass 4 arrays from A.swf to the DocumentClass of B.swf. Which could be the best way? Is a listener in B.swf a good idea? I noticed there's the possibility to send data over the querystring but I would like to avoid this solution, if possible.

A: EventListeners solution
You have some GlobalEventListener ( http://en.wikipedia.org/wiki/Singleton_pattern ) which is used in both A.swf and B.swf.
You have a customEvent which extends Event and has possibility to send arrays.
package com
{
import flash.events.Event;

public class TransferrArray extends Event
{
    public static const TRANSFERRING:String = 'transferring';
    private var _array:Array;

    public function TransferrArray(type:String, array:Array, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type, bubbles, cancelable);

        _array = array;
    }

    public function get array ():Array
    {
        return _array;
    }
}

}
in B.swf somewhere you putting:
GlobalEventListener.addEventListener ( TransferrArray.TRANSFERRING, handleTransfer )
private function handleTransfer ( e : TransferrArray) : void
{
    e.array // <- do what you need with it
}

in A.swf at the point when your Arrays are ready to be transfered:
GlobalEventListener.dispatchEvent ( new TransferrArray ( TransferrArray.TRANSFERRING, [your,arrays,needed,for,b] );

Direct parsing
B.swf need to have ( the main class of B.swf ) some:
public function transferrArrays ( array : Array )

in A.swf after B.swf is loaded  and your arrays are ready to be transfered:
BSWFLoader.content["transferrArrays"] ( [your,arrays,needed,for,b] );

A: I would not advise starting to walk down the path of Singletons.  Sooner or later, you will regret it. (http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/)
Instead, make the base class of your child swf implement an interface that has a variable for the value you want to set on it.  Once the loader dispatches the complete event, cast your swf to that interface and simply set the variable as normal.
Check out the example here http://flexdiary.blogspot.com/2009/01/example-of-casting-contets-of-swfloader.html.  It's a Flex example, but if you click on the thumbnail, then right click on the movie and select "View Source", you will see the source code.  The source of the Flash movie that implements the Blusher interface is in the flashSrc folder.
HTH;
Amy


text:
Q: How to Increase the quality of the Images on Illustrator I work with Adobe Illustrator creative suite 3.
I want to know how can one really Increase the quality of the Image's / graphics?
because the thing Is,whenever I view the Image or the graphic In Illustrator the graphic Is crisp and really sharp (because Illustrator Is a vector based software,I know that) but when I save the Image In a jpeg/gif or a png the quality dramatically decreases.
I want to know Is there a way to preserve the quality of an image after saving the image?
should I save the image In a particular extension? change the color setting?
what should I do.

A: What you're experiencing is the most easily perceived difference between vector and raster images. While the former describes shapes in an abstract way, the latter deal with images as a collection of rectangular dots, called pixels.
You can surely export the images in a larger resolution which raises the quality at the expense of file size. But if you want to retain the quality of the output then you shouldn't use JPEG or PNG but rather a file format capable of representing vector graphics. If it's for printing then PDF is usually a choice most companies can work with. Besides, it's the native format for Illustrator anyway.
Side note: You don't really want to export vector graphics in a file format like JPEG anyway because JPEG is primarily intended for photographic images. A direct consequence is that JPEG performs extraordinarily bad with line drawings, sharp edges and high contrast which is not uncommon with vector graphics. PNG is a much better choice here if you need a raster format and usually even compresses such images better.

A: With version CS5, Illustrator now lets you snap to the pixel grid. If you enable snapping (View > Snap to Pixel) and pixel preview (View > Pixel Preview), your graphics will export nicely as raster images. You can even see the pixel grid automatically when you zoom in really close, just like Photoshop.
You can also use Fireworks, which was essentially designed for this purpose. You can draw more or less the way you would in Illustrator, but everything is rendered as pixels.

A: Well, is correct to preserve the vector resizable capabilities of an illustration, as it is saved in pdf, SVG, EPS & even the native Ai extension, but if you want to reopen it in a pixel program like Photoshop your best option is to create your actual size canvas, then copy your vector art to it and paste in photoshop as "inteligent object, then adjust the final posiion and size, after that you migh raster that, so you've, decided how the image is set up for your purpose.
or either save your illustration to a bitmap image, but use a maximum resolution profile or rather to use 300 dpi (recomended for standard printing).
However its necessary to think about the convenience of getting to pixels or still working in vectors, maybe you only wanted to make a layout or a sample of your vector work, so your best option is to preserve your original vector file and export the sample in a medium resolution pixel image.

A: One thing I have recently found out is that when working with raster images in Illustrator, is that Illustrator scales down these images automaticaly.
You can set a custom resolution for your images by clicking on Object -> rasterize...


text:
Q: uilabel not the same height as uiimage with the same height Im trying to put an image behind a uilabel and need both to be about the same height (the uiimageview a little bigger to surround uilabel) and I have given both the same height in cgrectmake but yet the uiimageview remains smaller than the uilabel even though they are set to the same height.Please help! Code:
UILabel *labelEntry = [[UILabel alloc]init];
labelEntry.numberOfLines = 0;
labelEntry.text = entry;
CGSize expectedLabelSize = [entry sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(300.f, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
CGRect lblFrame =  CGRectMake(13, 30, 320, expectedLabelSize.height);
labelEntry.frame = lblFrame;
labelEntry.lineBreakMode = NSLineBreakByWordWrapping;
labelEntry.font = [UIFont systemFontOfSize: 17.0];
labelEntry.textAlignment = NSTextAlignmentCenter;
labelEntry.backgroundColor = [UIColor clearColor];

UIImageView *backgroundImage = [[UIImageView alloc]initWithFrame:CGRectMake(13, 30, 320, expectedLabelSize.height)];
backgroundImage.image = [UIImage imageNamed:@"postl.png"];
[scrollView addSubview:backgroundImage];

A: From your image(postl.png) what i can notice is, there is shadow effect applied to the image. Try once by setting background color for the imageview & you can see the shadow of applied image. Later you can adjust the frames accordingly

A: What is the size of post1.png? If it is not the same size as your CGRect you will need to stretch it. That would include changing your UIImageView's contentMode and possibly creating a stretchable image.


text:
Q: jQuery Mobile: Hide header/footer on orientation change I need to able to hide the header/footer when the device orientation event is called (I'd also settle for changing their data-position="fixed" attribute to not-fixed)
I've tried:
$(window).bind('orientationchange resize', function(event){

            if(event.orientation == 'portrait') {
                //do something
            }
            if (event.orientation == 'landscape') {
                $.mobile.fixedToolbars.show(false);
            }
    });

I've also used:
$.mobile.fixedToolbars.hide(true);

But neither seems to do the trick. Has this been removed from JQM 1.1?

A: With css media queries it's very simple to hide elements depending on the device orientation:
/* portrait */
@media screen and (orientation:portrait) {
  /* portrait-specific styles */
}

/* landscape */
@media screen and (orientation:landscape) {
  /* landscape-specific styles */
}

here is working example:
http://jsfiddle.net/5TDg9/bwzdr/show/
(be sure to open this link with your mobile device)

EDIT:
I improved the above sample with a javascript-based detection of the orientation (added to the css), theoretically you could pass anything after "case":
$(window).bind( 'orientationchange', function(e){
    var orientation="portrait";
    if(window.orientation == -90 || window.orientation == 90) orientation = "landscape";

    $("#status").html(orientation);

    switch(orientation){
      case 'portrait':
        // alert('portrait');
        $.mobile.fixedToolbars.setTouchToggleEnabled(true);
        break;
      case 'landscape':
        // alert('landscape');
        $.mobile.fixedToolbars.setTouchToggleEnabled(false);
        break;
      default:
        break;
    };
});

Example here

A: In JQM 1.1 the name of the function has been made all lower case.  The previous method is not longer supported.
Show:
$("[data-position='fixed']").fixedtoolbar('show');

Hide:
$("[data-position='fixed']").fixedtoolbar('hide');

More info on the docs.

A: Depending on the name of your footer you could just simply do this in your orientation detect function.
yourfooter.hide();

which is the same as setting that div to style="display:none;"

A: You can use something like :
$(window).bind('orientationchange', function(event) {
    if (event.orientation == 'landscape' ) {
        $.mobile.fixedToolbars.show(false);
    } else {
        $.mobile.fixedToolbars.show(true);
    }
});


text:
Q: Counting of items in list not working as expected I have a list which contains 91 items in it. I currently loop over and write each line to a text file using StreamWriter. I want to divide the list by 3 so after 30 items I want to insert a blank line. So far I have
foreach (var item in textList)
{
   //write to file
   counter++;
   if (counter == totalItems / 3)
   {
      await sw.WriteLineAsync(Environment.NewLine);
   }
}

but it only works for the first 30 items. Please note the list can contain any number of items but this particular one contains 91. However I will always have to divide into 3.

A: You either want to divide a list of 91 items by 3 or after 30 items. You can't have both. If you do it after every 30 items, you would have the 91st item separated from the rest, on its own 'chunk', i,e. 1-30, 31-60, 61-90, 91. If you have 91 items, and want to split by 3, you should do it every 31 items (hence why I am using Math.Ceiling). That way you'd have 1-31, 32-62 and 63-91.
Also, don't use foreach AND a counter; use the for loop instead. And you can use the modulus operator. As so:
int third = Convert.ToInt32(Math.Ceiling(textList.Count / 3.0));
int divider = third - 1;

for (int i = 0; i < textList.Count; i++)
{
    var itemToWrite = textList[i];
    //write to file

    if (i % third == divider) await sw.WriteLineAsync(Environment.NewLine);
}

A: Use modulo. Try like:
 if (counter % (totalItems / 3) == 0)
 {
   ...


text:
Q: How do you create a Listbox on the fly (at runtime) in VB.net? I'm attempting to create a listbox when a button is clicked in Visual Basic 2008. I can't seem to find code that works to do this.
I found a few examples that were very similar and said this would work:
Dim lstOutput As ListBox

lstOutput = Me.Controls.Add("VB.Label", "List1")

Problem is that both of the things inside the parenthesis generate errors:
For the first one:

Value of type 'String' cannot be converted to 'System.Windows.Forms.Control'.

And the second one:

Too many arguments to 'Public Overridable Sub Add(value As System.Windows.Forms.Control)'.

Any ideas?

A: This will add a empty listbox as the last control in the page:
Dim lstOutput As New ListBox With { .Id = "List1" }
Page.Controls.Add(lstOutput)

A: Try this
Dim lstOutput As new ListBox()
Me.Controls.Add(lstOutput)

A: you must use new keyword like this:
Dim lstOutput As New ListBox
Me.Controls.Add(lstOutput)

A: You want this:
Dim lstOutput As New ListBox()
Me.Controls.Add(lstOutut)

Notice the addition of the "New" keyword to actually create your control.

A: Every time you press the button (assuming the code is under the a button) the listbox is added at the top left corner. What if every time you want to add a new listbox it adds on top of the other and you can't see the new list box. How do you dynamically add one listbox next to the other without specifying the coordinates?


text:
Q: Generate upper and lower password case password from hash I am implementing a password generator, which creates passwords based on the service name and a master password. For this the master password and service are hashed. Now I only have lowercase letters and numbers. How could I also include uppercase letters and special symbols?
I found following code, which seems to solve the problem. Should I use it and what exactly does it do?
raw_hexdigest = make_password(plaintext, service)

# Convert the hexdigest into decimal
num = int(raw_hexdigest, 16)

# What base will we convert `num` into?
num_chars = len(alphabet)

# Build up the new password one "digit" at a time,
# up to a certain length
chars = []
while len(chars) < length:
    num, idx = divmod(num, num_chars)
    chars.append(alphabet[idx])

return ''.join(chars)

A: First, note that the hashed password is returned as an integer key.  The password you return is simply that integer expressed in some base, with a given alphabet.  The crux of this is the alphabet you supply.
For base 10, the alphabet is "01234356789"; for hexadecimal, it's "01234356789ABCDEF".  It seems that you have been using base 36: 10 digits and 26 lower-case letters.
To expand this, simply assign alphabet to be the characters you want in your passwords.
in more detail, the loop at the bottom is a digit-by-digit base conversion.  The base is the length of the alphabet.  At each iteration, the loop uses divmod to split the pass-key integer into a "units" value in that base (idx) and the quotient, the rest of the integer.  Then it picks the corresponding character from the alphabet and appends it to a string that eventually becomes the password.
I suggest that you insert a few strategic print statements and watch how this runs ... perhaps in base 10, then 16.  Instead of calling make_password, just set the key to something you recognize well, such as
raw_hexdigest = 1024 + 256 + 4 + 1

From there, watch how this number gets handled in various alphabets you give the routine.


text:
Q: Exercise 3.39 of Fulton & Harris I would like some help with exercise 3.39 from Fulton & Harris' 'Representation Theory A First Course':
Let $V_0$ be a real vector space on which $G$ acts irreducibly, $V=V_0 \otimes \mathbb{C}$ is a complex representation of $G$. Show that if $V$ is not irreducible, then it has two irreducible factors, and they are conjugate complex representations of $G$.
First of all I would like to remark that conjugate complex representations were not covered before in the book, but after a bit of research I believe the statement in the exercise is equivalent to: $V=W \oplus W^*$ for some (complex) irreducible sub-representation $W \subset V$. If I am mistaken please do correct me!
This question was asked here: Question about Real Representations, but the post got bogged down with notations and since it was so old I decided to ask it again here. It was suggested in the comments of that post that we consider a irreducible (proper) sub-representation $W \subset V$, let $V=W \oplus U$, and show that $U=W^*$, but I don't really see how we can go on...
The only way I have learnt to compute the amount of irreducible factors inside a representation $V$ is by computing $(\chi_V,\chi_V)=\frac{1}{|G|} \sum_{g \in G} |\chi_V(g)|^2$, but since we don't have a corresponding formula (not one that I am aware of) in the real case, I'm not sure how we can prove there are 2 irreducible factors in $V$ here. I am also failing to see how the second statement about the relation between the two factors can follow from the first part.
Any help is appreciated!

A: There is actually a much more elementary way to see this. We write elements of $V_0\otimes \mathbb{C}$ as $x+iy$ for $x,y\in V_0$.
Claim: If W is a nonzero submodule of V, then $W\oplus W^* = V$.
Proof: It is trivial that $W+ W^*$ is a submodule of $V$. Now suppose $x+iy\in W$ is nonzero, where $x,y\in V_0$. Note that $x-iy\in W^*$, so $(x+iy)+(x-iy) = 2x\in W+ W^*$. Then if $x\neq 0$, since $V_0$ is irreducible, this implies that $V_0\subseteq W+W^*$ (using the natural embedding of $V_0$ into $V$). Then $iV_0\subseteq W+ W^*$ and therefore $V = W+ W^*$. If instead $x = 0$, then since we assumed $x+iy\neq 0$, we have $y\neq 0$. So then irreducibility gives $iV_0\subseteq W$ and we proceed similarly to above. We are done proving this claim.
Now if we assume that $W$ is a proper nonzero irreducible submodule of $V$, then since we can easily show $W\cap W^*$ is a submodule of $W$, we have either $W\cap W^* = W$ or $W\cap W^* = 0$. The first case would contradict the claim proven above, since we assumed $W$ was a proper submodule of $V$. So $W\cap W^* = 0$ and $V = W\oplus W^*$.

A: In the context of Fulton and Harris' book, here is how I would explain what is going on:
Suppose $V$ is not irreducible as a $\mathbf{C}[G]$-module and let $0 \neq W \neq V$ be a proper non-zero sub-module. By restricting to $\mathbf{R}[G]$ we see that $W$ is a proper non-zero $\mathbf{R}[G]$-submodule of $V_0^{\oplus 2}$ (here we are using the relation between the real numbers and the complex numbers).
If $W_0$ is an irreducible $\mathbf{R}[G]$-submodule of $W$ then by Schur's  lemma, $W_0 \cong V_0$ as $\mathbf{R}[G]$-modules. By comparing dimensions we must have $W=W_0$. We have proved that every proper non-zero $\mathbf{C}[G]$-submodule of $V$ is isomorphic, upon restriction to $\mathbf{R}[G]$, to $V_0$. In particular the dimension of $W$ is half the dimension of $V$.
Now as in the discussion on page 40, a positive definite $G$-invariant inner product on $V_0$ induces a non-degenerate symmetric $\mathbf{C}$-bilinear form $(\cdot,\cdot)$ on $V$. Using what we proved in the previous paragraph there are only two possibilies: $W \cap W^\perp=0$ or $W=W^\perp$ (in the second case, $W$ is "Lagrangian").
In the first case $W \cong W^*$ and $W^\perp \cong (W^\perp)^*$,  while in the second case the pairing induces an isomorphism $W^* \cong W'$ for any $G$-stable complement $W'$ to $W$ in $V$. It remains only to observe that in the first case the characters of $W$ and $W^\perp$ are real, implying that they are both equal to half the character of $V_0$ and hence $W^\perp \cong W \cong W^*$ as desired.


text:
Q: Comparing many Correlations in R I have hundreds of correlations of populations (varying species, locations, etc) over time. How can I statistically analyze all these correlations (for their respective groups)?
I have p-values, CIs, correlation coefficients for each of the 600+ correlations, but how can I compare these within groups (species, location, etc).
I have tried to perform large partial correlations on the data correlating population number (in percent) and year, with species and location (turned into dummy variables) as controlled factors when correlating within Families, and with location (as dummy variable) as a controlled variable when correlating within species but am not sure if that is correct.
Here is some sample data, but this is a more logistic question oppose to actual data issue:
Location    Species                 Year    Section Total   Percent Family
Chiswell A  Black-legged Kittiwake  1976    Central 310 16.78397401 Gull
Chiswell A  Black-legged Kittiwake  1986    Central 982 53.16729832 Gull
Chiswell A  Black-legged Kittiwake  1989    Central 555 30.04872767 Gull
Chiswell B  Common Murre            1976    Central 150 20.6043956  Auk
Chiswell B  Common Murre            1986    Central 385 52.88461538 Auk
Chiswell B  Common Murre            1991    Central 193 26.51098901 Auk
Natoa Is    Black-legged Kittiwake  1976    Central 70  12.77372263 Gull
Natoa Is    Black-legged Kittiwake  1986    Central 168 30.65693431 Gull
Natoa Is    Black-legged Kittiwake  1989    Central 310 56.56934307 Gull
Wooded Is   Black-legged Kittiwake  1972    Central 1560    13.35159192 Gull
Wooded Is   Pelagic Cormorant       1972    Central 144 45.56962025 Cormorant
Wooded Is   Black-legged Kittiwake  1976    Central 2350    20.11297501 Gull
Wooded Is   Glaucous-winged Gull    1976    Central 150 13.83763838 Gull
Wooded Is   Horned Puffin           1976    Central 30  33.33333333 Auk
Wooded Is   Pelagic Cormorant       1976    Central 44  13.92405063 Cormorant
Wooded Is   Pigeon Guillemot        1976    Central 100 37.59398496 Auk
Wooded Is   Red-faced Cormorant     1976    Central 4   66.66666667 Cormorant
Wooded Is   Tufted Puffin           1976    Central 9600    98.21976673 Auk
Wooded Is   Black-legged Kittiwake  2000    Central 5587    47.81752824 Gull
Wooded Is   Glaucous-winged Gull    2000    Central 472 43.54243542 Gull
Wooded Is   Horned Puffin           2000    Central 30  33.33333333 Auk
Wooded Is   Pelagic Cormorant       2000    Central 64  20.25316456 Cormorant
Wooded Is   Pigeon Guillemot        2000    Central 83  31.20300752 Auk
Wooded Is   Red-faced Cormorant     2000    Central 1   16.66666667 Cormorant
Wooded Is   Tufted Puffin           2000    Central 87  0.890116636 Auk
Wooded Is   Black-legged Kittiwake  2001    Central 2187    18.71790483 Gull
Wooded Is   Glaucous-winged Gull    2001    Central 462 42.6199262  Gull
Wooded Is   Horned Puffin           2001    Central 30  33.33333333 Auk
Wooded Is   Pelagic Cormorant       2001    Central 64  20.25316456 Cormorant
Wooded Is   Pigeon Guillemot        2001    Central 83  31.20300752 Auk
Wooded Is   Red-faced Cormorant     2001    Central 1   16.66666667 Cormorant
Wooded Is   Tufted Puffin           2001    Central 87  0.890116636 Auk

Any advice is appreciated, thank you!

A: This is out of the scope of a stack overflow question and should probably be posted in a more statistically oriented forum.
However, I would check out the vegan package and specifically look at Canonical Correspondence analysis or Principal component analysis.  Ordination methods like allow you to reduce the dimensionality and look at the significant/useful correlations among many different grouping variables.
Vegan
Update
With a time series as one of the variables in the model, it would be statistically correct to determine if there are effects related to the repeated collections through time.  A multi-way ANOVA may be more useful in determining correlation between variables than finding groups of points in an ordination method.


text:
Q: Measuring the performance of a clustering algorithm with "true" clusters available Suppose I have observational units $x_1, \dots, x_n$. Each of these units is in a known cluster $C_1, \dots, C_m$, $m < n$. A ML algorithm generates based on a metric new clusters $C^{*}_1, \dots, C^{*}_p$, $p$ not necessarily equal to $m$.
Is there a standard way to measure the performance of the ML algorithm?
Best-case scenario is the following: $m = p$ and for each $C^{*}_i$, there exists some $C_j$ such that $C^{*}_i = C_j$, where equality is defined by having the same observational units.
Edit as clarification: The reason I'm doing this in the first place is because I have $N > n$ units available, with the remaining $N - n$ units not having known clusters. I'd like to see how well the algorithm performs with the $n$ units before I scale it up to the remaining $N-n$ units.

A: A great discussion of clustering in a Bayesian framework appears in:
Hanson, Robin, John Stutz, and Peter Cheeseman. "Bayesian Classification Theory." http://robinhanson.com/ijcai91.pdf

... the AutoClass system searches for the most probable classifications, automatically choosing the number of classes and complexity of class descriptions ...

... evaluation function optimally trades off the complexity of the model with its fit to the data, and is used
to guide an open-ended search for the best classification ...

Note AutoClass does not use "true" clusters, and has a history of illuminating new meaningful classes to subject matter experts. https://ti.arc.nasa.gov/tech/rse/synthesis-projects-applications/autoclass/


text:
Q: Why the header function doesn't work properly? I am working on a project and i want to make a local webpage. It is in PHP made this site. But i have some problems. After you entered you email and password in the login section, the code has to redirect to the main page of the site but it doesn't do that. I mention that each page of the site is organized in a folder. For example, these are some of the folders: Main, Login, Register, etc. I put the code down below to see what is the problem with the redirect function.
Mineral-World/Main/Main.php

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

        <link rel="icon" href="/Mineral-World/Main/More/icon.png" >
        <title>Mineral-World</title>

        Home
        Buy
        Sell
        Information about minerals
        Register
        Login

 Welcome

 What is Mineral-World?

 We are an online market and here you can buy or sell minerals. You will find the best offers!

 Are any taxes to be paid?

 You can sell or buy minerals without any cost, including the registering process.

Mineral-World/Login/sessionLogin.php
<?php

    include("ConnectBD_Login.php");
    session_start();
    if(isset($_POST['email'])&&isset($_POST['password']))
    {
        $email=$_POST['email'];
        $pass=md5($_POST['password']);
        $sel="select user from users where email='$email' and pass='$pass'";
        $que=mysql_query($sel);
        if(mysql_num_rows($que)==1)
        {
            $rez=mysql_fetch_row($que);
            $_SESSION['user']=$rez[0];
            header("Location: D:\EasyPHP-5.3.8.1\www\Mineral-World\Main\Main.php");
            exit();
        }
        else{
            $_SESSION['neconect']="Email or password is incorrect!";
            header();
            exit();
        }
    }else {
        $_SESSION['neconect']="Email or password is incorrect!";
        header();
        exit();
    }
    mysql_close();
?>

A: Your header location must be an url and not the path to a file, try this:
header("Location: ../../Main/Main.php");


text:
Q: C program that reads a file the user inputs and returns the first line #include <stdio.h>
int main (int argc, char **argv)
  {
    FILE* file;
    char scratch[1024];
    char filename[1024] = argv[1];
    file = fopen( filename, "r" );
    if( file != NULL ){
        if( fgets( scratch, 1024, file ) != NULL ){
            fprintf( stdout, "read line: %s", scratch );
        }
        fclose(file);
    return 0;
  }
}

Essentially if the user was to run
./nameOfTheProgram nameOfTheTextFile
it should return the first line of the Text File
I'm getting the following error:
error: invalid initializer
char filename[1024] = argv[1];

A: #include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
     ... your variables
     char *filename;

     if (argc>1)
     {
         filename = argv[1];
     }
     else
     {
         fprintf(stderr, "need a filename\n");
         exit(1);
     }

     ... your code
     return 0;
}


text:
Q: Почему каждый аргумент в maven начинается с -D -DgroupId...
-DartifactId...
-DarchetypeArifactId...
-DinteractiveMode...
...

каждый аргумент начинается с "D", почему?

A: Все предельно просто. -D - Define a system property, а все дальше - это собсвтенно само свойство (пропертис). А так как в большинстве случаев однобуквенные параметры от значения не нужно разделять пробелом, оно так и получается. То есть, на самом деле maven видит так параметры
-D groupId... -D artifactId... -D archetypeArifactId... -D interactiveMode

А у maven есть ещё много-много других параметров.


text:
Q: chmod($file) not working exactly as I want it to I was using the chmod($path, $mode, bool) function, but it wasn't setting permissions correctly, so I am now trying:
$fp = fopen($path, 'w');
fclose($fp);
chmod($path, 0750);  //changed to add the zero
return true;

problem is when I use the first method it creates the path ok... something like this uploads/2013/name/1/file.pdf(correct) but the permissio0ns are incorrect.
when I use the second method it creates a file with no extension: uploads/2013/name/1(incorrect) but the permissions are correct...
Here is my code:
if($_POST["upload"]){

$year = date('Y');

//path to directory
$path = $_SERVER["DOCUMENT_ROOT"] . '/uploads/' . $year . '/' . strtolower(str_replace(' ','',$_POST["username"])) . '/' . $_POST["month"];

//path to file
$target_path = $path . '/' . basename($_FILES['uploadedfile']['name']);

$filename = basename($_FILES['uploadedfile']['name']);

/* $ext = substr($filename, strrpos($filename, '.') + 1); */

if(!is_dir($path) && !file_exists($target_path)) {

    mkdir($path, 0750, true);

    chmod($path, 0750, true);  //changed to add the zero

    if(($_FILES["uploadedfile"]["type"] == "application/pdf") && ($_FILES["uploadedfile"]["size"] < 550000)) {

        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){

            print "
The file " . "" . basename( $_FILES['uploadedfile']['name']) . "" . " has been uploaded
";
        }
    } else {

        print "
Wrong file format
";

    }

} else {

    print "
File already exists!
";

}

}

A: Looks like your running into an issue with umask try doing a:
umask(0)

in the beginning of your script.
The default umask is fetched from your system configuration and is normaly 0022 and this is applied everytime you do a chmod in php so a chmod 0777 with a umask of 0022 turns into a 0755

A: It looks like your script is executed in a webserver context. So it may be that the webserver-user did not have the rights to change the file rights or a system umask is set.
Since php's chmod is only a wrapper for systems chmod you could easily try this command as the executing user.
For example on my system (www-data is the apache user)
$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.10
DISTRIB_CODENAME=quantal
DISTRIB_DESCRIPTION="Ubuntu 12.10"
NAME="Ubuntu"
VERSION="12.10, Quantal Quetzal"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu quantal (12.10)"
VERSION_ID="12.10"
$ sudo su - www-data -s /bin/bash
$ chmod 750 myfile


text:
Q: Operator binding in Python I have a containery object something like this:
class foo(object):
  def __init__(self,value):
    self.value = value
  def __eq__(self,other):
    return self.value == other

Which I can use like this:
>>> var = foo(4)
>>> var == 4
True
>>> var == 3
False
>>> # So far so good
>>> var == foo(4)
True
>>> var == foo(3)
False
>>> # Huh

My question is: what is happening that allows this to magically "just work"? How does Python bind the == operator inside __eq__ so that the value member of both sides is compared?

A: If an __eq__ method returns NotImplemented for a given argument, Python will try the same test in reverse. So x == y will try x.__eq__(y) first, if that returns the NotImplemented singleton, y.__eq__(x) is tried.
This applies to the comparison inside your __eq__ method as well; you are essentially comparing:
self.value == other

which is:
4 == other

which is:
4.__eq__(other)

which returns NotImplemented:
>>> var = foo(4)
>>> (4).__eq__(var)
NotImplemented

So Python tries other.__eq__(4) instead, which returns True.


text:
Q: Get decorated function from within nested decorator I'm trying to get the reference to the originally decorated function from within a decorator. How can this be done?
import inspect
from functools import wraps

def test_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # the closest I could get to getting the original function:
        # it prints the frame from which the function was called.
        current_frame = inspect.currentframe()
        outer_frames = inspect.getouterframes(current_frame)
        print(outer_frames[-1].frame)

        return func(*args, **kwargs)
    return wrapper

@test_decorator
@test_decorator
@test_decorator
def test_func(a, b, c):
    print("func")

test_func(1,2,3)

The 'originally decorated function' in this context would be test_func, since it's the target function we're decorating. I've looked through the inspect module, the closest I could get is by getting the first frame on the stack, but it doesn't help much.
Maybe, there is a solution already in stdlib?

A: This:
https://github.com/micheles/decorator
import inspect
from decorator import decorator

@decorator
def test_decorator(func, *args, **kwargs):
    print(inspect.getfullargspec(func))
    return func(*args, **kwargs)

@test_decorator
@test_decorator
@test_decorator
def test_func(a, b, c):
    print("func")

test_func(1,2,3)

Now from within each test_decorator it prints:
FullArgSpec(args=['a', 'b', 'c'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

Bless this man who wrote the module, the guy is a legend.


text:
Q: Return JSON elements separated by commas in PHP In PHP, how can I return JSON elements values in a string separated by commas?
This is how I'm calling the "list" JSON file in PHP:
$list = file_get_contents('http://example.com/list/json');
$items = json_decode($list, true);

This is the List JSON content (may contain more items, and more columns for each, not only itemID):
{
 "resultCount":3,
 "results": [
{"itemId":1223604159},
{"itemId":1231618623},
{"itemId":1244303880}]
}

So I want this string as response:
1223604159,1231618623,1244303880

Already tried implode without success:
$IdByCommas = implode(',',$items->results->itemId);

A: As every item of $items->results is an array with one key itemId you can't simply implode($items['results']). You have to get every value of itemId.
With php5.5/5.6/7, where you have array_column function, you can:
echo implode(',', array_column($items['results'], 'itemId')));

Otherwise you have to extract every value of itemId:
$ids = [];
foreach ($items['results'] as $item) {
    $ids[] = $item['itemId'];
}
echo implode(',', $ids);

Also, I'm using [] instead of -> because you decoded json to array, not object.


text:
Q: Precompile riot tag which includes ES6 'import' Is there any way to precompile riot.js tag that includes ES6 import syntax like below?
<riot-tag>
  <script>
    import Foo from './foo'
    new Foo();
  </script>
</riot-tag>

I use gulp and gulp-riot to build tags.
gulp.task('tags', () => {
  return gulp.src([`${srcDir}/*`])
    .pipe($.riot({
      type: 'es6'
    }))
    .pipe(gulp.dest(`${destDir}/`));
});

A: You're going to need gulp to transform your ES2015 code into something the riot compiler can understand.
Start by adding an ES2015 compiler to you app:
npm install babel-core babel-preset-es2015 --save-dev

Then add your .babelrc file, to tell babel what presets to use:
{
  "presets": ["es2015"]
}

Then gulp should be able to handle it ok from there:
import gulp from 'gulp';
import riot from 'gulp-riot';

gulp.task('tags', () => {
  return gulp.src([`${srcDir}/*`])
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest(`${destDir}/`));
});

Hope this helps!


text:
Q: Ubuntu 18.04 with NVIDIA Titan V nvidia-396 disables GPU hardware acceleration I upgraded to Ubuntu 18.04 [Bionic Beaver] and installed an NVIDIA Titan V GPU for deep learning. I am using NVIDIA-396 as the driver, I am able to run keras-gpu neural network libraries explicitly using the GPU.
So, the card and the driver do work for deep learning, although I had to disable Secure Boot to make the driver work.
However, my GPU hardware acceleration is disabled and the OpenGL renderer is pointing to llvmpipe.
The output of glxinfo is:

OpenGL vendor string: VMware, Inc.
  OpenGL renderer string: llvmpipe (LLVM 5.0, 256 bits)

nvidia-smi shows the presence of the NVIDIA-TITAN-V GPU.
nvidia-settings shows an error that

NO INFO can be found.

Please, I have been struggling with this issue for the past two days and would really appreciate any help on this.

A: Reverted to nvidia-390 driver using run file from NVIDIA website instead of apt install. Worked! Took some time to get here, but the graphics are truly awesome :)


text:
Q: Cron expression not giving proper date? I want to run a cron job on every day of first week of December.
But my cron job instead runs on second week of December.
Below is the code
import java.text.ParseException;
import java.util.Date;

import org.quartz.CronExpression;

public class CronExpressionTest{

    public static void main(String[] args) throws ParseException {
        String expression = "0 0 0 ? 12 2#1,3#1,4#1,5#1,6#1,7#1,1#1 *";
        CronExpression cronExpression = new CronExpression(expression);
        Date date = cronExpression.getNextValidTimeAfter(new Date());
        System.out.println(date);
    }
}

If you see the calendar below, job should run on 1st December for the first time, but it runs on 7th December.

Edit 1 :
It looks like week in cron starts from first Sunday instead of 1st day of the month.
Edit 2:-
Apparently cron expression "0 0 0 ? 12 2#1,3#1,4#1,5#1,6#1,7#1 *" starts on 1st Dec which is correct but "0 0 0 ? 12 2#1,3#1,4#1,5#1,6#1,7#1,1#1 *" starts on 7th Dec as I added 1#1 (1st sunday of the month).

A: According to the Quartz Javadoc, only one '#' expression is allowed for day-of-week field:

If the '#' character is used, there can only be one expression in the day-of-week field ("3#1,6#3" is not valid, since there are two expressions).

Reference: http://quartz-scheduler.org/api/2.2.1/org/quartz/CronExpression.html


text:
Q: Date Picker is not getting displayed on the first click I am trying to use DatePicker of Jquery UI for Text Field. It is not getting displayed on the first Click but on unfocus and focus it is displaying.
here is sample code with which i am trying.I am confused with why it is not firsttime only.
Html

Text Field:	<input type="text" name="sampleDate" id="sampleDate" onfocus="showDatePicker(this)"/>

JavaScript :
function showDatePicker(element)
{
$(element).datepicker();
}

A: Try this solution updated on
jsfiddle
For this solution assuming each field which is going to display calander having calss "date", there is no need to attach onclick event

    Text Field:

        <input type="text" name="sampleDate" class="date" id="sampleDate" />

attaching event to each input element having class date
$(document).ready(function () {

    $( ".date" ).each(function( index ) {
       $( this ).datepicker();
   });

});

try onclick event
onClick="showDatePicker(this)"

easily solution is to make use of Datepicker

A: Because on first focus the datepicker is not getting defined
This will give an error
Uncaught excpetion: showDatePicker is not defined

A simple solution will be
$(document).ready(function () {
    $('#sampleDate').datepicker();
});

Fiddle


text:
Q: Cmd + PgUp/Down shortcut to navigate through terminal tabs is it possible to make Cmd+Page Up / Page Down shortcut performing switch tab in Terminal?
At the moment I can use Cmd+Shift+[ or Cmd+Shift+] shortcuts to do the thing, but this is horrible for me. I'm using external USB Keyboard and Karabiner, if that may help somehow.

A: Update:
The answer now reassigns Scroll to Top/Bottom to ⌥⌘PageUp and ⌥⌘PageDown.
This leaves Show Previous/Next Tab free to take over ⌘PageUp and ⌘PageDown.

Assuming your OS X runs in English, you can use this one-liner:
defaults write com.apple.Terminal NSUserKeyEquivalents -dict-add 'Scroll to Top' '~@\Uf72c' 'Scroll to Bottom' '~@\Uf72d' 'Show Previous Tab' '@\Uf72c' 'Show Next Tab' '@\Uf72d'

If your OS X runs in a language other than English, modify the command to resemble the exact menu item text for your language.

A: You can use System Preferences > Keyboard > Keyboard Shortcuts > Application Shortcuts to configure custom shortcuts for anything available in the menus of an application.
Just choose the application from the list or Other... to select an application not in the list (or leave it at All Applications for every application), type in the exact menu text and supply a keyboard shortcut.


text:
Q: How many libraries can i have in the same angular workspace? Can I have more than one library in the same angular workspace?
For Example:
lib-shared/
    projects/
          lib1
          lib2
          lib3

I tried to create a second library in my worskspace and import it into my app getting the following errors:
    core.js:4442 ERROR TypeError: Cannot read property 'bindingStartIndex' of null
    at ɵɵelementStart (core.js:14822)
    at LsLibHeadToolbarComponent_Template (template.html:1)
    at executeTemplate (core.js:7457)
    at renderView (core.js:7264)
    at renderComponent (core.js:8520)
    at renderChildComponents (core.js:7138)
    at renderView (core.js:7289)
    at renderComponent (core.js:8520)
    at renderChildComponents (core.js:7138)
    at renderView (core.js:7289)

I noticed a strange thing: in the first library I created (working) in the src folder there are the files:

*

*-public-api.ts

*-test.ts

instead in the second library there are the files:

*

*-projects.ts

*-test.ts

this is my angular.json of workspace:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ls-lib-menu": {
      "projectType": "library",
      "root": "projects/ls-lib-menu",
      "sourceRoot": "projects/ls-lib-menu/src",
      "prefix": "ls-lib-menu",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/ls-lib-menu/tsconfig.lib.json",
            "project": "projects/ls-lib-menu/ng-package.json"
          },
          "configurations": {
            "production": {
              "tsConfig": "projects/ls-lib-menu/tsconfig.lib.prod.json"
            }
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ls-lib-menu/src/test.ts",
            "tsConfig": "projects/ls-lib-menu/tsconfig.spec.json",
            "karmaConfig": "projects/ls-lib-menu/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ls-lib-menu/tsconfig.lib.json",
              "projects/ls-lib-menu/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ls-lib-head-toolbar": {
      "projectType": "library",
      "root": "projects/ls-lib-head-toolbar",
      "sourceRoot": "projects/ls-lib-head-toolbar/src",
      "prefix": "ls-lib-head-toolbar",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/ls-lib-head-toolbar/tsconfig.lib.json",
            "project": "projects/ls-lib-head-toolbar/ng-package.json"
          },
          "configurations": {
            "production": {
              "tsConfig": "projects/ls-lib-head-toolbar/tsconfig.lib.prod.json"
            }
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ls-lib-head-toolbar/src/test.ts",
            "tsConfig": "projects/ls-lib-head-toolbar/tsconfig.spec.json",
            "karmaConfig": "projects/ls-lib-head-toolbar/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ls-lib-head-toolbar/tsconfig.lib.json",
              "projects/ls-lib-head-toolbar/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ls-lib-menu",
  "cli": {
    "analytics": false
  }
}

I imported both libraries into the app.module.ts file:
import { LsLibMenuModule } from '../../../../../ls-lib-shared/projects/ls-lib-menu/src/public-api';
import { LsLibHeadToolbarModule } from '../../../../../ls-lib-shared/projects/ls-lib-head-toolbar/src/projects';

A: Yes, you can have as many as you want. Just make sure you add them to the angular.json, but if you generate the library with the angular-CLI this will be done automatically.
https://angular.io/guide/creating-libraries


text:
Q: How to terminate a thread that is hanging on blocking IO in a platform independent manner? Since non-blocking console IO is not supported in std C++, I am trying to do the console input on a separate thread. I still have the problem of terminating the thread from outside however.
How can I do it without Unix signals?
If I use select() it can signal if something is in the input buffer, but if it is not a whole line (containing a newline), then "cin << myvar" will still block and I cannot test my stop-flag in between.
Any C++11 conformant solution interests me.

A: You can't in general.  Under Posix, you can set the thread up to catch a
specific signal, and use pthread_kill(); after returning from the
signal handler, blocking IO at the system level (i.e. read()) will
return with errno equal EINTR.  Beyond that, you're pretty much at
the mercy of the iostream implementation, which has two choices (the
implementor of iostream, not you):

*

*it can loop back and retry tge read, or

*it can treat it as an error condition, and set failbit.
In the first case, there's not much you can do about it, short of
implementing your own streambuf and using it (which, for console
input, isn't as difficult as it seems).  For the second, you should set
errno to 0 before reading, and check it after a read failure (at the
iostream level); if it is EINTR, you can then take appropriate action,
not forgetting to reset the error (std::ios_base::clear()) if you
intend to reuse the stream.

A: You can use cin.get(), to read a single character, and select in combination to avoid blocking the thread. Also cin.rdbuf()->in_avail() returns the numbers of ready chars in the buffer.

A: In my humble experience, never seen a stable way to cancel a synchronous and/or blocking I/O operation. That is, it can't be done with "cin >>" operator.


text:
Q: Suppressing margin citations in tufte-book I'm writing a book in tufte-book, in which bibliographic citations (\cite{}) are rendered small in the adjacent page margin and alphabetically at normal size in the bibliography.  This is a lovely, elegant and very readable style.
However, the last section of each chapter is on bibliographic and historical discussions in which every paragraph may have 10 or more citations.  This is simply too many to appear in the margins.  Hence I would like to use a traditional (natbib?) or other citation style just for those final chapter sections.  The citation information should appear in the text body as:  "... as has been discussed before (Jones and Smith, 2016)" and the Jones and Smith reference appear with all the entries in the bibliographic listing at the end of the book.
The ideal would be to create a new citation call:
\nomargincite{}

or
\cite2{}

that I would use just in those final chapter sections.
Alternatively, perhaps there is a way to create an environment such as:
\begin{nomargincite}

\end{nomargincite}

which would envelope just the text in those final sections.
I've seen reference to changing citation style throughout a tufte-book, but I need to employ two citation styles.
Minimum working example:
\documentclass[twoside,symmetric]{tufte-book}

\begin{document}

\chapter{My first chapter}

Beginning chapter text\cite{Rodgers:16}

\section{Bibliographic remarks}

As has been discussed by many folk (\cite{JonesSmith:18}).

\bibliography{Art}
\bibliographystyle{plainnat}

\end{document}

A: Here is a cheap solution: Use \citep. The tufte classes redefine \cite to give sidenote citations, but they don't define natbib's commands \citet and \citep.
So \citep works a treat and even gives parentheses if you pass the round option to natbib.
\PassOptionsToPackage{round}{natbib}
\documentclass[twoside,symmetric]{tufte-book}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@book{appleby,
  author    = {Humphrey Appleby},
  title     = {On the Importance of the Civil Service},
  year      = {1980},
  publisher = {Pub},
  address   = {Place},
}
\end{filecontents}

\begin{document}

\chapter{My first chapter}

Beginning chapter text\cite{appleby}

\section{Bibliographic remarks}
As has been discussed by many folk \citep{appleby}.

\bibliography{\jobname}
\bibliographystyle{plainnat}
\end{document}

Note that this only works if you use an natbib-author-year compatible style (as plainnat is one). It does in particular not work with the provided tufte.bst.


text:
Q: df.show() prints empty result while in hdfs it is not empty I have a pyspark application which is submitted to yarn with multiple nodes and it also reads parquet from hdfs
in my code, i have a dataframe which is read directly from hdfs:
df = self.spark.read.schema(self.schema).parquet("hdfs://path/to/file")

when i use df.show(n=2) directly in my code after the above code, it outputs:
+---------+--------------+-------+----+
|aaaaaaaaa|bbbbbbbbbbbbbb|ccccccc|dddd|
+---------+--------------+-------+----+
+---------+--------------+-------+----+

But when i manually go to the hdfs path, data is not empty.
What i have tried?
1- at first i thought that i may have used few cores and memory for my executor and driver, so i doubled them and nothing changed.
2- then i thought that the path may be wrong, so i gave it an wrong hdfs path and it throwed error that this path does not exist
What i am assuming?
1- i think this may have something to do with drivers and executors
2- it may i have something to do with yarn
3- configs provided when using spark-submit
current config:
spark-submit \
    --master yarn \
    --queue my_queue_name \
    --deploy-mode cluster \
    --jars some_jars \
    --conf spark.yarn.dist.files some_files \
    --conf spark.sql.catalogImplementation=in-memory \
    --properties-file some_zip_file \
    --py-files some_py_files \
    main.py

What i am sure
data is not empty. the same hdfs path is provided in another project which is working fine.

A: So the problem was with the jar files i was providing
The hadoop version was 2.7.2 and i changed it to 3.2.0 and it's working fine


text:
Q: How to push a file to GitHub using an Android app (JAVA) So i have a excel file on my GitHub that needs to be updated so i plan to update it using a application
How do I push the updated excel file to GitHub directly from the app using a button
(Java language)
Could someone point me in the right direction
Mostly when i search this question the results are about how to push the code to GitHub

A: If you are using Java you maybe use Gradle(Usually used with android) or Maven as your project builder tool. I just googled quicly "Java git library" for you and JGit came up wich seems to be a fairly simple library to use. Here is a tutotrial on it.
You probably have to initialize the repo as ususal from code or seperately I suggest from code. And you need to implement file handling as well seperatelly from this simple git client implmentation. You might use this other source helpful for that.
But on native android there might be some different library for handling files as well as you should look into intents for passing differernt files or data between applications.
I hope it helps. :)


text:
Q: Identify which input field trigger ng-change? I have 2 input fields and I prefer to have one ng-change function to store their values in the chrome.storage.local when either of these change:
<input type="text" ng-model="mod1" ng-change="inputChange()" ng-model-options="{ debounce: 250 }">
<input type="text" ng-model="mod2" ng-change="inputChange()" ng-model-options="{ debounce: 250 }">

Function in the controller is similar to this:
$scope.mod1 = "";
$scope.mod2 = "";
$scope.inputChange = function(data) {
  chrome.storage.local.set({
    $scope.model.id : data,
  }, function() {
    console.log("success!");
  });
}

Can't figure out how to obtain changed model's id. Other suggestions to persist form data on change?
EDIT
After multiple comments (thank you) I've ended up with the following (jsbin):

var app = angular.module('example', []);

app.controller('example', ["$scope", "$log",
  function($scope, $log) {

    $scope.form = {
      form_fields: ["mod1", "mod2", "mod3"],
      module: {
        "mod1": null,
        "mod2": null,
        "mod3": null,
      },
      error: {
        "mod1": false,
        "mod2": false,
        "mod3": false,
      },
      field_attr: {
        "mod1": {
          type: "text",
          placeh: "Module-1 Input",
        },
        "mod2": {
          type: "password",
          placeh: "Module-2 Input",
        },
        "mod3": {
          type: "text",
          placeh: "Module-3 Input",
        },
      }
    };

    $scope.inputChange = function(modID) {
      $log.warn("Module: " + modID + "; value: " + $scope.form.module[modID]);
    };

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="example" ng-controller="example">
  <div id="form-gen" ng-repeat="field in form.form_fields">
    <input type="{{form.field_attr[field].type}}" id="{{field}}-in" placeholder="{{form.field_attr[field].placeh}}" ng-model="form.module[field]" ng-model-options="{ debounce: 1000 }" ng-change="inputChange(field)">
  </div>
</body>

Is there anything that still can be improved?

A: You can pass $event into your on-change function.
Then in your controller you can do $event.target to find the html element that changed.
<input type="text" ng-model="mod1" ng-change="inputChange($event)" ng-model-options="{ debounce: 250 }">
<input type="text" ng-model="mod2" ng-change="inputChange($event)" ng-model-options="{ debounce: 250 }">

$scope.inputChange = function($event) {
  var changedInput = $event.target;
}

Sorry, this doesn't work for ng-change. ng-change is a directive and not an event handler. If you were to use ng-keypress it would work.
Alternatively you could use a watch for this.
  $scope.$watch('mod1', function(newMod, oldMod){
    if(newMod == oldMod) return;

    console.log('mod1 changed!');
  });

  $scope.$watch('mod2', function(newMod, oldMod){
    if(newMod == oldMod) return;

    console.log('mod2 changed!');
  });

Examples: https://jsbin.com/teparofogi/1/edit?html,js,console,output

A: You can pass this to on-change function and get the changed input element by using the below snippet :
$scope.inputChange = function(e) {
   var changedInput = e.target; //you can access further prop too
}


text:
Q: Receipt Refresh causes Apple Review to Reject App due to iTunes Store Connection Error I'm seeing a very strange thing happening with my application.
To be specific, I am issuing a receipt request in order to download a receipt from Apple when I detect that the application does not contain a receipt file in its bundle.
Sure, calling the receipt refresh API causes the Apple ID login screen to be shown.
I have created "test"/"sandbox" users in iTunes Connect in order to test my application.
When running the application on my device (iPad with WiFi), the app successfully calls the refresh receipt function and then sure enough, the Apple ID login screen pops up. I enter the correct credentials of the test/sandbox user configured in iTunes Connect and everything is fine (i.e., the receipt is downloaded successfully.)
However, if I attempt to use a real Apple ID user, I get "didFailWithError" and the localized error description is: "Cannot connect to iTunes Store", the error code being "16".
This is expected, in my opinion.
Now, the sad part is that when I have submitted my build to Apple Review, they are getting the exact error mentioned above.
They are saying that they are using a sandbox user and thus they have rejected the application as they were unable to continue.
Note: They too have used an iPad with WiFi for testing the application.
I have consistently been able to reproduce this problem only when using real Apple ID user accounts and have never had a problem with sandbox users!
I've read somewhere that one would have to also make sure that the sandbox user is logged out of the "Settings" screen when testing. I've politely asked Apple Review to make sure that they would not be logged into "Settings" when testing.
They have sent me two screenshots: One with the Apple ID login screen that asks for BOTH the Apple ID user and the password (which causes me to think that they indeed were logged out of the "Settings" screen, otherwise they'd already have the Apple ID user pre-populated in the dialog) and one showing the error mentioned in this post.
I have no idea how to proceed now because I simply cannot reproduce this problem. It works perfectly with any sandbox users on my device -- it just doesn't work with real Apple ID users.
Apple Review sent me a screenshot showing the error mentioned in this post, again, an error that I can only reproduce when using a real Apple ID user in what is really a sandbox environment.
I think the only difference may be the fact that my device is running iOS 10.x while their device may be running iOS 12.x but I don't think it should be an issue.
Any thoughts ?
Thanks in advance!
P.S., they are not using an Apple ID sandbox user created by me -- they use their own. I have suggested to send them my sandbox users to test, but they said they could not accept as it would be a breach of privacy.
UPDATE: I have confirmed that the same thing happens on iOS 12.1 so it's not due to an OS difference.

A: It looks like at least in my case, there seems to be a problem with the refresh receipt API itself.
I have confirmed that initiating a purchase request causes the app to download a receipt from Apple with the credentials of the supplied user (sandbox user in our case.)
The review team has confirmed that the purchase request works correctly with their sandbox user, however, the refresh receipt DOES NOT work with that exact same user (it causes a code 16, "Cannot connect to iTunes Store")!
I have also confirmed that a "Restore" request causes the receipt to be downloaded and that it works with the supplied sandbox user.
In conclusion, both "Purchase" and "Request" operations causes the app to download a receipt from Apple and they work correctly for the sandbox user supplied by the Review Team. However, with the exact same user, the receipt refresh request fails!
I can still ask for a receipt refresh because it should work correctly for actual App Store downloads but it clearly did not work for app review.


text:
Q: Pubsub emulator resend the acknowledged messages I created a subscriber client to listen to messages from pubsub emulator. When I published more than 500 messages to pubsub. The subscriber client still received the messages, although those messages are acknowledged already.
I am using python 3.
There are 3 classes:
Class A: the subscriber client to listen to messages from pubsub emulator
Class B: the object for storing message to cloud storage
Class C: the object for extracting and inserting the message into SQL tables
from google.cloud import pubsub_v1
import B
import C

class A(object):
    def receive_messages(self,project_id, subscription_name):

        subscriber = pubsub_v1.SubscriberClient()

        subscription_path = subscriber.subscription_path(
                            project_id, subscription_name)

        def callback(message):
            print('Received message: {}'.format(message))

            B_obj = B()
            storing_status = B_obj.storing_to_cloud_drive()

            if storing_status:
                message.ack()
                print('Message is acked')

                C_obj = C()
                C_obj.extract_and_insert_to_sql_table()

            else:
                message.nack()
                print('Message is nacked')

        subscriber.subscribe(subscription_path, callback=callback)

        print('Listening for messages on {}'.format(subscription_path))
        while True:
            time.sleep(60)


text:
Q: How to get Number of files touched, Number of lines added, Number of lines removed from for commit in repo.iter_commits(branch) using python git? I would like to store the following info per commit like so,
for commit in repo.iter_commits(branch):
    author_name=commit.author.name
    commit_id=commit
    commit_authored_date=datetime.datetime.fromtimestamp(commit.authored_date)
    commit_committed_date=datetime.datetime.fromtimestamp(commit.committed_date)
    num_files_touched=?
    num_lines_added=?
    num_lines_removed=?

how can I do this?

A: for commit in repo.iter_commits(branch):
        author_name=commit.author.name
        commit_id=commit
        commit_authored_date=datetime.datetime.fromtimestamp(commit.authored_date)
        commit_committed_date=datetime.datetime.fromtimestamp(commit.committed_date)
        num_files_touched=commit.stats.total['files']
        num_lines_added=commit.stats.total['insertions']
        num_lines_removed=commit.stats.total['deletions']

This fetches the number of files touched, the number of lines added, and number of lines removed for each commit


text:
Q: In SPSS, how to obtain a single prediction of the dependent variable for each fixed factor, rather than for each random factor combination? I have a number of thing-types X and for each type want to obtain a single estimate of its true value Y.
When I have measured the same thing-type several times in the same session and several times each in sessions on different days, then if I understand correctly the thing-type is a fixed factor and the absolute day is a random factor (in that I could hypothetically keep doing more measurements for different days, each day influencing the results by introducing a different bias).
When using SPSS to try to obtain estimates, I was elated when seeing the options of saving predicted values and confidence intervals to the dataset.
I put in thing-types as Subjects, and in Random Effects added the different random factors as blocks.
However, when I looked at the output spreadsheet, I saw that measurements with all the same factors had the same predicted value, but measurements with the same fixed factor and different random factors had different predicted values.
At the time, I was attempting to use the Mixed Model Generalized Linear option for Analyze.
Searching near-blindly for the way to get what I imagine without knowing the correct terminology has not been going well.
Is there a way to do what I am imagining?  To put in measurements of several things under several conditions, and to get out one estimate for each thing?
Thank you for your time.

A: The MIXED procedure, which fits linear mixed models, will save both predicted values, which include fixed and random effects, and also fixed predicted values, which include only the fixed effects. The GENLINMIXED procedure only saves predicted values, but it is possible to save the model out and then use the Scoring Wizard to score your data, and this produces the fixed predicted values.
When you run the generalized linear mixed model, go to the Model Options tab's Save Fields screen, where you can save predicted values. In the bottom of the screen you can choose to export the model in .xml format. Choose a file location and run the procedure.
Then, in the menus choose Utilities>Scoring Wizard, navigate to the model file you just saved, and select it. If you've saved the predicted values in GENLINMIXED, you'll have to change the name of the variable into which to save the fixed predicted values, as the default is the same "PredictedValue" string. Clicking Done should produce fixed predicted values from the generalized linear mixed model.


text:
Q: Get event on Coming back to current page, Ionic navigation I am showing some list from api in Page-A, from page-A, I navigate to Page-B, and fill some form and submit, after submission I moved back to Page-A. Now I need to refresh the list in Page-A.
How can i know that I have moved back from Page-B -> Page-A.
I am using Ionic-5.
Thanks

A: You can use Ionic Life Cycle Hooks:

ionViewWillEnter Fired when the component routing to is about to animate into view.

ionViewWillLeave Fired when the component routing from is about to animate.

ionViewDidLeave Fired when the component routing to has finished animating.

ionViewDidEnter Fired when the component routing to> has finished animating.

For More Info: Life Cycle Hooks Documentation

A: SERVICE booleanService
comingFromPageB: boolean;

PAGE B
constructor(private booleanService: BooleanService){}

ionViewWillLeave(){
this.booleanService.comingFromPageB = true;
}

PAGE A
constructor(private booleanService: BooleanService){}

ionViewWillEnter(){
  if(this.booleanService.comingFromPageB){
    - Do your stuff here (delete form...)
     - Reset boolean : this.booleanService.comingFromPageB = false
   }
}

A: You can achieve these things by using events and subscribe concept. Like as below
Step 1: Create one service(provider) with apphelper name
Step 2: run this npm i rxjs command
Step 3: import below things in apphelper.service.ts and
    import { Subject, Subscription } from 'rxjs';

    // Events
  subscribe(topic: string, observer: (_: any) => void): Subscription {
    if (!this.channels[topic]) {
      this.channels[topic] = new Subject<any>();
    }
    return this.channels[topic].subscribe(observer);
  }

  publish(topic: string, data?: any): void {
    const subject = this.channels[topic];
    if (!subject) {
      // Or you can create a new subject for future subscribers
      return;
    }
    subject.next(data);
  }

  destroy(topic: string): null {
    const subject = this.channels[topic];
    if (!subject) {
      return;
    }
    subject.complete();
    delete this.channels[topic];
  }

Now import service on page A and page B. After that add click event in back button and fire publish the event as below on page B:
 this.appHelper.publish("RELOAD_DATA");

And on page A subscribe event in the constructor as below:
this.appHelper.subscribe("RELOAD_DATA", (data: any) => {
// call the function as per your requirement
    });


text:
Q: Should the contentView.translatesAutoResizingMaskToConstraints of a UICollectionViewCell subclass be set to `false`? TL;DR
When trying to size UICollectionViewCells via auto layout, you can easily get auto layout warnings with even a simple example.
Should we be setting contentView.translatesAutoResizingMaskToConstraints = false to get rid of them?

I'm trying to create a UICollectionView with self sizing auto layout cells.
In viewDidLoad:
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = CGSize(width: 10, height: 10)
collectionView.collectionViewLayout = layout

My cell is very basic. It's a single blue view with width and height 75 for testing purposes. The constraints are created by pinning the view to the superview on all 4 edges, and giving it a height and width.
class MyCell: UICollectionViewCell {
  override init(frame: CGRect) {
    view = UIView()

    super.init(frame: frame)

    view.backgroundColor = UIColor.blueColor()
    contentView.addSubview(view)

    installConstraints()
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  var view: UIView

  func installConstraints() {
    view.translatesAutoresizingMaskIntoConstraints = false

    var c: NSLayoutConstraint

    // pin all edges
    c = NSLayoutConstraint(item: contentView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
    c.active = true
    c = NSLayoutConstraint(item: contentView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
    c.active = true
    c = NSLayoutConstraint(item: contentView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
    c.active = true
    c = NSLayoutConstraint(item: contentView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
    c.active = true

    // set width and height
    c = NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 75)
    c.active = true
    c = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 75)
    c.active = true
  }
}

When running the code, I get two errors about not being able to simultaneously satisfy constraints:
Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x7fed88c1bac0 h=--& v=--& H:[UIView:0x7fed8a90c2f0(10)]>",
    "<NSLayoutConstraint:0x7fed8ab770b0 H:[UIView:0x7fed8a90bbe0(75)]>",
    "<NSLayoutConstraint:0x7fed8a90d610 UIView:0x7fed8a90c2f0.leading == UIView:0x7fed8a90bbe0.leading>",
    "<NSLayoutConstraint:0x7fed8ab005f0 H:[UIView:0x7fed8a90bbe0]-(0)-|   (Names: '|':UIView:0x7fed8a90c2f0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7fed8ab770b0 H:[UIView:0x7fed8a90bbe0(75)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

(The second error about the vertical constraints is omitted but it's nearly identical.)
These errors make sense. Essentially, the contentView (0x7fed8a90c2f0) has translatesAutoresizingMask = true, thus its bounds set to 10x10 (from the estimated size) creates that NSAutoresizingMaskLayoutConstraint constraint. There's no way the view can be both 10 pixels wide and 75 pixels wide, so it outputs an error.
I tried several different things to resolve this problem, with only 2 of them seeming to work.
Solution 1: Set at least one of the constraints to 999 or less
In this case, if I change the constraint that pins the bottom of the blue view to the bottom of the contentView to 999 priority (and do the same with the trailing constraint), it resolves the problem. Similarly, I could have chosen Top+Leading, or Width+Height so long as I don't have 1000 priorities in every direction. At least one has to "give" for the initial layout.
Although it may sound like this would cause the view to have an incorrect height/width, it actually appears to be the correct size.
Solution 2: Set contentView.translatesAutoresizingMaskIntoConstraints = false
By setting this to false, it essentially gets rid of the NSAutoresizingMaskLayoutConstraint constraint, and we no longer have a conflict. On the other hand, since the contentView is not set up with auto layout to begin with, it's as though no matter how you change its frame, its superview (the cell) is never going to update its size because there is nothing "pushing" back against it.
Nevertheless, this solution somehow magically works. I assume that at some point the cell looks at the contentView's frame and decides "hey you set me to this size, that probably means you want the cell to be this size as well" and takes care of resizing the cell for you.
Which solution should we use?
Are there better solutions to this problem? Which of the above should be used? Are there any downsides to the two solutions mentioned above, or are they essentially the same and it doesn't matter which one you use?

Notes:

*

*The reason it is harder to see in examples such as DGSelfSizingCollectionViewCells is because they are relying on intrinsicContentSize + contentCompressionResistancePriority. If you get rid of my width+height constraints, replace them with 1000 setContentCompressionResistancePriority calls (horizontal+vertical), and use something with an intrinsic size (e.g. a label with text), you will no longer see the auto layout errors. This implies that width@1000 behaves differently than an intrinsicWidth + contentCompressionResistance@1000. Perhaps the time a view gets its intrinsic width is after it's okay to modify the the frame of the content view.

Things that didn't work:

*

*I noticed that when I create cells via a storyboard, I usually never run in to this problem. When I examined the differences in the view of a cell created via a storyboard and one created programmatically, I noticed that the autoresizingMask was RM+BM (36) in the storyboard, but 0 when created via code. I tried manually setting the autoresizingMask of my blue view to 36, but that didn't work. The real reason that the storyboard solution works is that usually the constraints you create are already perfectly set in the storyboard (otherwise you would have storyboard errors that need to be fixing). As part of fixing these errors, you may change the bounds of the cell. Since it calls init?(coder:), the bounds of the cell are already configured correctly. So even though the contentView.autoresizingMask = true, there are no conflicts since it's already defined at the correct size.

*In the linked guide, it links to this post when talking about creating constraints. It mentions that constraints should be created in updateConstraints. However, it sounds like this was Apple's original recommendations and that they are no longer recommending this convention for most of your constraints. Nevertheless, since that article says to create them in updateConstraints I tried to no avail. I got the same results. This is because the frame wasn't updated by the time updateConstraints was called (it was still 10x10).

*I've noticed similar problems when you choose a estimated size that is too small. I've fixed it in the past by increasing the estimated size. In this case I tried 100x100, but it still caused the same errors. This makes sense... a view can't be both 100 wide and 75 wide at the same time. (Note that I consider setting it to 75x75 a non-solution. See below for more info.)

Non-solutions:

*

*Setting the estimated size to 75x75. Although this will resolve the errors for this simple example, it won't resolve the problem for cells that truly are dynamically sized. I want a solution that'll work everywhere.

*Returning the exact dimensions of the cell in collectionView(_:layout:sizeForItemAtIndexPath:) (e.g. by creating a sizing cell). I want a solution that works with my cell directly without needing any bookkeeping or extra calculation.

A: After testing things out, I noticed at least one reason to keep contentView.translatesAutoresizingMaskToConstraints = true.
If you use preferredLayoutAttributesFittingAttributes(_:) to alter the dimensions of a UICollectionViewCell, it works by sizing the contentView to the correct dimension. If you set contentView.translatesAutoresizingMaskToConstraints = false, you'll lose this functionality.
Therefore, I recommend using Solution 1 (altering at least one constraint in each dimension to be non-required). In fact, I created a wrapper for UICollectionViewCell that will handle both the required 999 constraint, and a way to get preferred height or width to function correctly.
By using this wrapper, you won't need to remember the intricacies of getting the contentView in a UICollectionViewCell to behave properly.

class CollectionViewCell<T where T: UIView>: UICollectionViewCell {

  override init(frame: CGRect) {
    preferredHeight = nil
    preferredWidth = nil

    super.init(frame: frame)
  }

  var preferredWidth: CGFloat?
  var preferredHeight: CGFloat?
  private(set) var view: T?

  func initializeView(view: T) {
    assert(self.view == nil)
    self.view = view

    contentView.addSubview(view)

    view.translatesAutoresizingMaskIntoConstraints = false

    var constraint: NSLayoutConstraint

    constraint = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 0)
    constraint.active = true
    constraint = NSLayoutConstraint(item: view, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 0)
    constraint.active = true

    // Priority must be less than 1000 to prevent errors when installing
    // constraints in conjunction with the contentView's autoresizing constraints.
    let NonRequiredPriority: UILayoutPriority = UILayoutPriorityRequired - 1

    constraint = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)
    constraint.priority = NonRequiredPriority
    constraint.active = true
    constraint = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: 0)
    constraint.priority = NonRequiredPriority
    constraint.active = true
  }

  override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let newLayoutAttributes = super.preferredLayoutAttributesFittingAttributes(layoutAttributes)

    if let preferredHeight = preferredHeight {
      newLayoutAttributes.bounds.size.height = preferredHeight
    }
    if let preferredWidth = preferredWidth {
      newLayoutAttributes.bounds.size.width = preferredWidth
    }

    return newLayoutAttributes
  }
}

(Note: the init method is required due to a bug with generic subclasses of UICollectionViewCell.)
To register:
collectionView.registerClass(CollectionViewCell<UIView>.self, forCellWithReuseIdentifier: "Cell")

To use:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell<UILabel>

  if cell.view == nil {
    cell.initializeView(UILabel())
  }

  cell.view!.text = "Content"
  cell.preferredHeight = collectionView.bounds.height

  return cell
}


text:
Q: Coffeescript - Method chaining with function arguments[2] or use functions instead of params I start to learn CoffeeScript recently, and I faced with a problem as this. I want to write javascript :
TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions()).done(
        function(rendered) { // something1
}).fail(function(ex) {
    // something2

});

Which way I can get it? I try rewrite that:
TemplateManager.tmpl @template, @modelJSON(), @templateOptions()
    .done (rendered) ->
       #something1
    .fail (ex) ->
       #something2

and I get:
TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions().done(function(rendered) {

  }).fail(function(ex) {

  }));

A: Add parenthesis for tmpl and done methods
TemplateManager.tmpl( @template, @modelJSON(), @templateOptions() )
   .done( (rendered) ->
        #something1
    )
   .fail (ex) ->
        #something2

The solution isn't elegant, and I think others may give a better way in coffeescript
Updated
Base on comment, removing parenthesis for done. I've updated the code and I think this one is elegant
TemplateManager
   .tmpl(@template, @modelJSON(), @templateOptions())
   .done (rendered) ->
        some
        code
        here

   .fail (ex) ->
        another
        code
        here

A: Instead of making a mess of "I'm not using parentheses because they're optional" and tricky impenetrable indentation, just break things into little pieces, give the pieces names, and put them together simply:
done = (rendered) ->
    # something1
fail = (ex) ->
    # something2
TemplateManager.tmpl(@template, @modelJSON(), @templateOptions())
    .done(done)
    .fail(fail)

I have no idea what "something1" and "something2" are so I can't give them decent sensible names, consider done and fail as proof of concept names.
Just because a function can be anonymous doesn't mean is must be anonymous, just because some parentheses are optional doesn't mean that they must be left out.


text:
Q: Maven Jboss AOP plugin - anybody had success with annotation marked pointcuts? In my jboss-aop.xml, if I mark pointcuts using normal signature, like this:
<bind pointcut="execution(public void org.POJO->noop())">
<Interceptor class="org.SimpleInterceptor"/>
</bind>
aspects compile without a problem, but if I use annotation, like this
<bind pointcut="execution(void *->@org.Trace(..))">
   <interceptor class="org.SimpleInterceptor"/>
</bind>
then there is no aop compile - no error, but the pointcut is not compiled.
So - anybody knows if the maven jboss aop plugin supposed to be able to compile annotation marked pointcuts?

A: After exploration of the jboss aop sdk (where annotation example worked) and hours of trying to bring 2 projects together to find a reason, the offender was missing
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)

on my Trace interface.
In combination with the aop compiler being very picky to almost every aspect of its setup and silently not compiling if anything vital (like goal/compile) is missing, this was a pretty entertaining puzzle!


text:
Q: Splitting one column in a SQL query into multiple columns The idea is this, I have one column that has values that range from 0 to 25,000.
I want to basically have one column that counts the number of values from 0 to 5000, 5000-10000, etc.
Where would I start? And how would I do such a thing?

A: I'm assuming you don't really want the ranges to overlap:
count(case when <column> between     0 and  5000 then 1 else null end) as range0,
count(case when <column> between  5001 and 10000 then 1 else null end) as range1,
...

or maybe you prefer (if you actually meant 0 to 4999, 5000 to 9999, etc):
count(case when <column> / 5000 = 0 then 1 else null end) as range0,
count(case when <column> / 5000 = 1 then 1 else null end) as range1,
count(case when <column> / 5000 = 2 then 1 else null end) as range2,
count(case when <column> / 5000 = 3 then 1 else null end) as range3,
count(case when <column> / 5000 = 4 then 1 else null end) as range4,
count(case when <column> / 5000 = 5 then 1 else null end) as range5

You'd need the last one to actually cover 25,000 or just do >= 4. And note that I assumed integer division.


text:
Q: Initializing values in OleCreatePropertyFrame for web capture pin properties Has anyone been able to fully initialize the values in the OleCreatePropertyFrame() menu when using it to set web capture pin properties?
As long as one does not re "Moniker" the "IBaseFilter *pSrc", the "IAMStreamConfig *pConfig" getFormat() value is maintained (one can release and rebuild the FilterGraph without changing the current configuration).
However, the OleCreatePropertyFrame() menu always seems to display the lowest format height for the current format width, and the maximum frame rate allowed.
This behavior can be seen in AMcap as well as in other small examples.
Has anyone figure how to get OleCreatePropertyFrame() to simply display the exact current format?


text:
Q: Library connection in GCC I have 4 files:

*

*main.cpp

*emcd.h

*EMCB.dll

*EMCB.lib

I want to use the functions that are in the dll.
There is not a lot of code, but it captures the essence.
#pragma comment(lib,"EMCB.lib")

#include "emcb.h"

int main()
{
    EMCBLibInitialize(); //DLL function
}

To compile, I use gcc and do it with the following command

gcc main.cpp -l: EMCB.lib

after which I get an error

/usr/bin/ld: cannot find -l:EMCB.lib
collect2: error: ld returned 1 exit status

A: The preprocessor statement:
#pragma comment(lib,"xxx.lib")

will not be recognized by the GCC compiler. You need to use -l