working on it ...

# Explore Public Snippets

Found 5,374
snippets
matching: *links*

####
public
by clsw
*350065*
*0*
*6*
*1*

### Image upload to API, return direct link. (IMGUR)

Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.

public string UploadImage(Image img) { //get a dev key from api.imgur.com, anonymous usage (no user auth) only. string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)"; //define the WebClient we'll use to communicate with Imgur. WebClient w = new WebClient(); //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above. w.Headers.Add("Authorization", "Client-ID " + devkey); System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection(); try { //Converts the image to a byte array so it can be turned into a string for upload. using (MemoryStream stream = new MemoryStream()) { img.Save(stream, ImageFormat.Png); Keys.Add("image", Convert.ToBase64String(stream.ToArray())); } //uploads the string-formatted-image and waits for the response. byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys); dynamic result = Encoding.ASCII.GetString(responseArray); //formats the (long and technical) result into just the direct image link. Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result); string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/"); //returns the online address of the image. return url; } catch (Exception s) { MessageBox.Show(s.Message); return "err"; } }

####
public
by cghersi
*204466*
*0*
*6*
*2*

### Embed a browser into SWT Dialog and manage the firing of popups from links in the displayed page

This is how to manage an embedded browser.
Note: unfortunately this seems not working on some versions of Mac OS X.

try { Browser browser = new Browser(this, SWT.NONE); browser.setJavascriptEnabled(true); browser.setUrl("www.myurl.com"); browser.addOpenWindowListener(new OpenWindowListener() { public void open(WindowEvent event) { log.debug("Opening browser:" + event); new Thread( new Runnable() { public void run() { log.debug("some stuff t do here..."); } }).start(); final Shell shell = new Shell(event.display); shell.setText("My Browser page"); shell.setLayout(new FillLayout()); event.browser = new Browser(shell, SWT.NONE); shell.open(); event.browser.addCloseWindowListener(new CloseWindowListener() { @Override public void close(WindowEvent event) { log.debug("closing"); shell.setVisible(false); } }); } }); } catch (Throwable t) { //on some architecture seems that SWT Browser is not working... log.warn("Cannot display SWT Browser"); }

####
public
by micurs
*2842*
*1*
*7*
*0*

### Find all Internal Links

Regular expression that find all links that start with the sites domain, a slash, relative file path, or a hashtag.
This regex can be used to find all the internal links in a page or section of a page.

var siteURL = "http://" + top.location.host.toString(); var $internalLinks = $("a[href^='" + siteURL + "'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

####
public
by lbottaro
*2743*
*2*
*6*
*1*

### Parsing and finding symbolic links in multiple paths

This bash script will list simbolic links in multiple path (using wildchar * for nested directories), at level 1 from main directory, parsing the result as well.
The script will use awk to parse returned data, getting the 11th data, space separated.

ls -l `find ABC*/code/target-*/TARGET -maxdepth 1 -type l -name "*"` | awk '{print $11}'

####
public
by micurs
*2005*
*2*
*7*
*2*

### CSS rule to remove dotted outline links

This CSS rule removes dotted outline around links.

a { outline: 0; }

####
public
by newjackswing4ever
*2520*
*8*
*5*
*0*

### Find all internal links on a webpage using JQuery snippet in a browser that has Firebug/Console editor

A nifty little script that allows you to find internal links on a webpage - using Firebug or Console tool

var url = window.location.href; var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/); var domain = urlParts[0].split('.'); var brand=''; var mydomain = domain[1] + '.' + domain[2]; var links = []; jQuery('a').each(function() { links.push( this.href ); // output of links: ['http://www.google.com', 'http://www.dictionay.com'] // According to comment // if you need each link separately then // may try like var href = this.href; //if an internal page, if (href.indexOf(mydomain) != -1) { console.log(href); } // });

####
public
by marcospinello
*2796*
*0*
*3*
*0*

### Programmatically handle relative links in Jekyll using Liquid templating syntax

Programmatically handle relative links in Jekyll using Liquid templating syntax:
jekyll_links_liquid_syntax.md

```markdown {% comment %} source: http://stackoverflow.com/questions/4629675/jekyll-markdown-internal-links code snippet author: http://stackoverflow.com/users/399105/bmaupin {% endcomment %} {% for page in site.pages %} {% if page.url == '/path/to/page.html' %} [{{ page.title }}]({{ page.url }}) {% endif %} {% endfor %} ```

####
public
by TSiege
*1540*
*1*
*4*
*0*

### This is my technical interview cheat sheet. Feel free to fork it or do whatever you want with it. PLEASE let me know if there are any errors or if anything crucial is missing. I will add more links soon.

This is my technical interview cheat sheet. Feel free to fork it or do whatever you want with it. PLEASE let me know if there are any errors or if anything crucial is missing. I will add more links soon.:
The Technical Interview Cheat Sheet.md

## Studying for a Tech Interview Sucks, so Here's a Cheat Sheet to Help This list is meant to be a both a quick guide and reference for further research into these topics. It's basically a summary of that comp sci course you never took or forgot about, so there's no way it can cover everything in depth. It also will be available as a [gist](https://gist.github.com/TSiege/cbb0507082bb18ff7e4b) on Github for everyone to edit and add to. ## Data Structure Basics ###**Array** ####Definition: - Stores data elements based on an sequential, most commonly 0 based, index. - Based on [tuples](http://en.wikipedia.org/wiki/Tuple) from set theory. - They are one of the oldest, most commonly used data structures. ####What you need to know: - Optimal for indexing; bad at searching, inserting, and deleting (except at the end). - **Linear arrays**, or one dimensional arrays, are the most basic. - Are static in size, meaning that they are declared with a fixed size. - **Dynamic arrays** are like one dimensional arrays, but have reserved space for additional elements. - If a dynamic array is full, it copies it's contents to a larger array. - **Two dimensional arrays** have x and y indices like a grid or nested arrays. ####Big O efficiency: - Indexing: Linear array: O(1), Dynamic array: O(1) - Search: Linear array: O(n), Dynamic array: O(n) - Optimized Search: Linear array: O(log n), Dynamic array: O(log n) - Insertion: Linear array: n/a Dynamic array: O(n) ###**Linked List** ####Definition: - Stores data with **nodes** that point to other nodes. - Nodes, at its most basic it has one datum and one reference (another node). - A linked list _chains_ nodes together by pointing one node's reference towards another node. ####What you need to know: - Designed to optimize insertion and deletion, slow at indexing and searching. - **Doubly linked list** has nodes that reference the previous node. - **Circularly linked list** is simple linked list whose **tail**, the last node, references the **head**, the first node. - **Stack**, commonly implemented with linked lists but can be made from arrays too. - Stacks are **last in, first out** (LIFO) data structures. - Made with a linked list by having the head be the only place for insertion and removal. - **Queues**, too can be implemented with a linked list or an array. - Queues are a **first in, first out** (FIFO) data structure. - Made with a doubly linked list that only removes from head and adds to tail. ####Big O efficiency: - Indexing: Linked Lists: O(n) - Search: Linked Lists: O(n) - Optimized Search: Linked Lists: O(n) - Insertion: Linked Lists: O(1) ###**Hash Table or Hash Map** ####Definition: - Stores data with key value pairs. - **Hash functions** accept a key and return an output unique only to that specific key. - This is known as **hashing**, which is the concept that an input and an output have a one-to-one correspondence to map information. - Hash functions return a unique address in memory for that data. ####What you need to know: - Designed to optimize searching, insertion, and deletion. - **Hash collisions** are when a hash function returns the same output for two distinct outputs. - All hash functions have this problem. - This is often accommodated for by having the hash tables be very large. - Hashes are important for associative arrays and database indexing. ####Big O efficiency: - Indexing: Hash Tables: O(1) - Search: Hash Tables: O(1) - Insertion: Hash Tables: O(1) ###**Binary Tree** ####Definition: - Is a tree like data structure where every node has at most two children. - There is one left and right child node. ####What you need to know: - Designed to optimize searching and sorting. - A **degenerate tree** is an unbalanced tree, which if entirely one-sided is a essentially a linked list. - They are comparably simple to implement than other data structures. - Used to make **binary search trees**. - A binary tree that uses comparable keys to assign which direction a child is. - Left child has a key smaller than it's parent node. - Right child has a key greater than it's parent node. - There can be no duplicate node. - Because of the above it is more likely to be used as a data structure than a binary tree. ####Big O efficiency: - Indexing: Binary Search Tree: O(log n) - Search: Binary Search Tree: O(log n) - Insertion: Binary Search Tree: O(log n) ## Search Basics ###**Breadth First Search** ####Definition: - An algorithm that searches a tree (or graph) by searching levels of the tree first, starting at the root. - It finds every node on the same level, most often moving left to right. - While doing this it tracks the children nodes of the nodes on the current level. - When finished examining a level it moves to the left most node on the next level. - The bottom-right most node is evaluated last (the node that is deepest and is farthest right of it's level). ####What you need to know: - Optimal for searching a tree that is wider than it is deep. - Uses a queue to store information about the tree while it traverses a tree. - Because it uses a queue it is more memory intensive than **depth first search**. - The queue uses more memory because it needs to stores pointers ####Big O efficiency: - Search: Breadth First Search: O(|E| + |V|) - E is number of edges - V is number of vertices ###**Depth First Search** ####Definition: - An algorithm that searches a tree (or graph) by searching depth of the tree first, starting at the root. - It traverses left down a tree until it cannot go further. - Once it reaches the end of a branch it traverses back up trying the right child of nodes on that branch, and if possible left from the right children. - When finished examining a branch it moves to the node right of the root then tries to go left on all it's children until it reaches the bottom. - The right most node is evaluated last (the node that is right of all it's ancestors). ####What you need to know: - Optimal for searching a tree that is deeper than it is wide. - Uses a stack to push nodes onto. - Because a stack is LIFO it does not need to keep track of the nodes pointers and is therefore less memory intensive than breadth first search. - Once it cannot go further left it begins evaluating the stack. ####Big O efficiency: - Search: Depth First Search: O(|E| + |V|) - E is number of edges - V is number of vertices ####Breadth First Search Vs. Depth First Search - The simple answer to this question is that it depends on the size and shape of the tree. - For wide, shallow trees use Breadth First Search - For deep, narrow trees use Depth First Search ####Nuances: - Because BFS uses queues to store information about the nodes and its children, it could use more memory than is available on your computer. (But you probably won't have to worry about this.) - If using a DFS on a tree that is very deep you might go unnecessarily deep in the search. See [xkcd](http://xkcd.com/761/) for more information. - Breadth First Search tends to be a looping algorithm. - Depth First Search tends to be a recursive algorithm. ## Efficient Sorting Basics ###**Merge Sort** ####Definition: - A comparison based sorting algorithm - Divides entire dataset into groups of at most two. - Compares each number one at a time, moving the smallest number to left of the pair. - Once all pairs sorted it then compares left most elements of the two leftmost pairs creating a sorted group of four with the smallest numbers on the left and the largest ones on the right. - This process is repeated until there is only one set. ####What you need to know: - This is one of the most basic sorting algorithms. - Know that it divides all the data into as small possible sets then compares them. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n log n) - Worst Case Sort: Merge Sort: O(n log n) ###**Quicksort** ####Definition: - A comparison based sorting algorithm - Divides entire dataset in half by selecting the average element and putting all smaller elements to the left of the average. - It repeats this process on the left side until it is comparing only two elements at which point the left side is sorted. - When the left side is finished sorting it performs the same operation on the right side. - Computer architecture favors the quicksort process. ####What you need to know: - While it has the same Big O as (or worse in some cases) many other sorting algorithms it is often faster in practice than many other sorting algorithms, such as merge sort. - Know that it halves the data set by the average continuously until all the information is sorted. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n log n) - Worst Case Sort: Merge Sort: O(n^2) ###**Bubble Sort** ####Definition: - A comparison based sorting algorithm - It iterates left to right comparing every couplet, moving the smaller element to the left. - It repeats this process until it no longer moves and element to the left. ####What you need to know: - While it is very simple to implement, it is the least efficient of these three sorting methods. - Know that it moves one space to the right comparing two elements at a time and moving the smaller on to left. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n^2) - Worst Case Sort: Merge Sort: O(n^2) ####Merge Sort Vs. Quicksort - Quicksort is likely faster in practice. - Merge Sort divides the set into the smallest possible groups immediately then reconstructs the incrementally as it sorts the groupings. - Quicksort continually divides the set by the average, until the set is recursively sorted. ## Basic Types of Algorithms ###**Recursive Algorithms** ####Definition: - An algorithm that calls itself in its definition. - **Recursive case** a conditional statement that is used to trigger the recursion. - **Base case** a conditional statement that is used to break the recursion. ####What you need to know: - **Stack level too deep** and **stack overflow**. - If you've seen either of these from a recursive algorithm, you messed up. - It means that your base case was never triggered because it was faulty or the problem was so massive you ran out of RAM before reaching it. - Knowing whether or not you will reach a base case is integral to correctly using recursion. - Often used in Depth First Search ###**Iterative Algorithms** ####Definition: - An algorithm that is called repeatedly but for a finite number of times, each time being a single iteration. - Often used to move incrementally through a data set. ####What you need to know: - Generally you will see iteration as loops, for, while, and until statements. - Think of iteration as moving one at a time through a set. - Often used to move through an array. ####Recursion Vs. Iteration - The differences between recursion and iteration can be confusing to distinguish since both can be used to implement the other. But know that, - Recursion is, usually, more expressive and easier to implement. - Iteration uses less memory. - **Functional languages** tend to use recursion. (i.e. Haskell) - **Imperative languages** tend to use iteration. (i.e. Ruby) - Check out this [Stack Overflow post](http://stackoverflow.com/questions/19794739/what-is-the-difference-between-iteration-and-recursion) for more info. ####Pseudo Code of Moving Through an Array (this is why iteration is used for this) ``` Recursion | Iteration ----------------------------------|---------------------------------- recursive method (array, n) | iterative method (array) if array[n] is not nil | for n from 0 to size of array print array[n] | print(array[n]) recursive method(array, n+1) | else | exit loop | ``` ###**Greedy Algorithm** ####Definition: - An algorithm that, while executing, selects only the information that meets a certain criteria. - The general five components, taken from [Wikipedia](http://en.wikipedia.org/wiki/Greedy_algorithm#Specifics): - A candidate set, from which a solution is created. - A selection function, which chooses the best candidate to be added to the solution. - A feasibility function, that is used to determine if a candidate can be used to contribute to a solution. - An objective function, which assigns a value to a solution, or a partial solution. - A solution function, which will indicate when we have discovered a complete solution. ####What you need to know: - Used to find the optimal solution for a given problem. - Generally used on sets of data where only a small proportion of the information evaluated meets the desired result. - Often a greedy algorithm can help reduce the Big O of an algorithm. ####Pseudo Code of a Greedy Algorithm to Find Largest Difference of any Two Numbers in an Array. ``` greedy algorithm (array) var largest difference = 0 var new difference = find next difference (array[n], array[n+1]) largest difference = new difference if new difference is > largest difference repeat above two steps until all differences have been found return largest difference ``` This algorithm never needed to compare all the differences to one another, saving it an entire iteration.

####
public
by juntalis
*1343*
*1*
*4*
*0*

### Find hard links for a given filepath

Find hard links for a given filepath:
readlinks.c

/** * @file findlinks.c * @brief Find links */ #include "pch.h" #include "ntfsdefs.h" typedef struct _FILENAME_PART { LPWSTR Data; UCHAR DataLength; struct _FILENAME_PART *Next; struct _FILENAME_PART *Prev; } FILENAME_PART; typedef BOOL(*PROCESSFILERECORD)(IN PFILE_RECORD_HEADER lpFileRecordHeader, IN OPTIONAL LPVOID lpUserData); typedef BOOL(*ENUMATTRIBUTEPROC)(IN PATTRIBUTE lpAttr, IN OPTIONAL LPVOID lpUserData, IN OUT LPBOOL lpbContinue); BOOL ReadFileNamePartsProcessFileRecord(IN PFILE_RECORD_HEADER lpFileRecordHeader, IN OPTIONAL LPVOID lpUserData); FILENAME_PART* AllocateNextPart(FILENAME_PART* lpCurrent) { FILENAME_PART* lpNext = NULL; if(lpNext = (FILENAME_PART*)malloc(sizeof(FILENAME_PART))) { memset((void*)lpNext, 0, sizeof(FILENAME_PART)); lpNext->Prev = lpCurrent; } return (lpCurrent->Next = lpNext); } BOOL CopyFileNamePart(IN OUT FILENAME_PART* lpPart, IN PFILENAME_ATTRIBUTE lpFileName) { BOOL bResult = FALSE; SIZE_T szBuffer = sizeof(WCHAR) * (lpFileName->NameLength + 1); if(lpPart->Data = (LPWSTR)malloc(szBuffer)) { lpPart->DataLength = lpFileName->NameLength; memset((void*)lpPart->Data, 0, szBuffer); wcsncpy(lpPart->Data, (const wchar_t*)lpFileName->Name, lpPart->DataLength); bResult = TRUE; } return bResult; } BOOL EnumRecordAttributes(PFILE_RECORD_HEADER lpFileRecordHeader, IN ENUMATTRIBUTEPROC fnEnumAttrs, IN OPTIONAL LPVOID lpUserData) { BOOL bSuccess = TRUE, bContinue = TRUE; PATTRIBUTE lpAttr = (PATTRIBUTE)((LPBYTE)lpFileRecordHeader + lpFileRecordHeader->AttributesOffset); // Loop through our attributes (unless our handler says to stop) while(bContinue && lpAttr && lpAttr->AttributeType <= AttributeLoggedUtilityStream) { // Process attribute if(!(bSuccess = fnEnumAttrs(lpAttr, lpUserData, &bContinue))) break; // Figure out the current attribute size, then move on to the next. if(lpAttr->Nonresident) { lpAttr = (PATTRIBUTE)Add2Ptr(lpAttr, sizeof(NONRESIDENT_ATTRIBUTE)); } else if(lpAttr->Length && lpAttr->Length < lpFileRecordHeader->BytesInUse) { lpAttr = (PATTRIBUTE)Add2Ptr(lpAttr, lpAttr->Length); } else { lpAttr = NULL; } } return bSuccess; } BOOL ProcessFileRecord(IN HANDLE hVolume, IN LARGE_INTEGER FileReferenceNumber, IN PROCESSFILERECORD fnProcessFileRecord, IN OPTIONAL LPVOID lpUserData) { BOOL bSuccess = FALSE; DWORD dwRead, dwBufferSize = FILE_RECORD_OUTPUT_BUFFER_SIZE; C_ASSERT(sizeof(FileReferenceNumber) == sizeof(NTFS_FILE_RECORD_INPUT_BUFFER)); NTFS_FILE_RECORD_OUTPUT_BUFFER* nrb = (NTFS_FILE_RECORD_OUTPUT_BUFFER*)malloc(dwBufferSize); if(DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD, &FileReferenceNumber, sizeof(FileReferenceNumber), nrb, dwBufferSize, &dwRead, NULL)) { // FSCTL_GET_NTFS_FILE_RECORD retrieves one MFT entry // FILE_RECORD_HEADER is the Base struct for the MFT entry // that we will work from PFILE_RECORD_HEADER lpFileRecordHeader = (PFILE_RECORD_HEADER)nrb->FileRecordBuffer; // Verify that the first four bytes are: FILE if(lpFileRecordHeader->Ntfs.Type == 'ELIF') { bSuccess = fnProcessFileRecord(lpFileRecordHeader, lpUserData); } } return bSuccess; } typedef struct { HANDLE hVolume; FILENAME_PART* Tail; } ReadFileNamePartsData; typedef struct { HANDLE hVolume; USHORT LinkCount; USHORT CurrentLink; ReadFileNamePartsData* LinkData; } ReadHardlinksData; BOOL ReadFileNamePartsEnumAttributes(IN PATTRIBUTE lpAttr, IN OPTIONAL LPVOID lpUserData, IN OUT LPBOOL lpbContinue) { BOOL bSuccess = TRUE; ReadFileNamePartsData* lpData = (ReadFileNamePartsData*)lpUserData; *lpbContinue = TRUE; if(lpAttr->AttributeType == AttributeFileName) { PRESIDENT_ATTRIBUTE lpResident = (PRESIDENT_ATTRIBUTE)lpAttr; PFILENAME_ATTRIBUTE lpFileName = (PFILENAME_ATTRIBUTE)Add2Ptr(lpAttr, lpResident->ValueOffset); if(lpFileName->NameType & WIN32_NAME || lpFileName->NameType == 0) { FILENAME_PART* lpNext; bSuccess = FALSE; if((lpNext = AllocateNextPart(lpData->Tail)) && CopyFileNamePart(lpNext, lpFileName)) { lpData->Tail = lpNext; if(lpFileName->DirectoryFileReferenceNumber == 0x5 || lpFileName->NameType == 3) { bSuccess = TRUE; } else { bSuccess = ProcessFileRecord(lpData->hVolume, *((LARGE_INTEGER*)&lpFileName->DirectoryFileReferenceNumber), ReadFileNamePartsProcessFileRecord, lpUserData); } } *lpbContinue = FALSE; } } return bSuccess; } BOOL ReadFileNamePartsProcessFileRecord(IN PFILE_RECORD_HEADER lpFileRecordHeader, IN OPTIONAL LPVOID lpUserData) { BOOL bSuccess = FALSE; ReadFileNamePartsData* lpData = (ReadFileNamePartsData*)lpUserData; return EnumRecordAttributes(lpFileRecordHeader, ReadFileNamePartsEnumAttributes, lpUserData); } BOOL ReadHardlinksEnumAttributes(IN PATTRIBUTE lpAttr, IN OPTIONAL LPVOID lpUserData, IN OUT LPBOOL lpbContinue) { BOOL bSuccess = TRUE; ReadHardlinksData* lpData = (ReadHardlinksData*)lpUserData; *lpbContinue = TRUE; if(lpAttr->AttributeType == AttributeFileName) { ReadFileNamePartsData* lpReadData; PRESIDENT_ATTRIBUTE lpResident = (PRESIDENT_ATTRIBUTE)lpAttr; PFILENAME_ATTRIBUTE lpFileName = (PFILENAME_ATTRIBUTE)Add2Ptr(lpAttr, lpResident->ValueOffset); if(lpFileName->NameType & WIN32_NAME || lpFileName->NameType == 0) { bSuccess = FALSE; lpReadData = &(lpData->LinkData[lpData->CurrentLink++]); if(lpReadData->Tail = (FILENAME_PART*)malloc(sizeof(FILENAME_PART))) { memset((void*)lpReadData->Tail, 0, sizeof(FILENAME_PART)); if(CopyFileNamePart(lpReadData->Tail, lpFileName)) { lpReadData->hVolume = lpData->hVolume; bSuccess = ProcessFileRecord(lpData->hVolume, *((LARGE_INTEGER*)&lpFileName->DirectoryFileReferenceNumber), ReadFileNamePartsProcessFileRecord, (LPVOID)lpReadData); } } } } return bSuccess; } BOOL ReadHardlinksProcessFileRecord(IN PFILE_RECORD_HEADER lpFileRecordHeader, IN OPTIONAL LPVOID lpUserData) { BOOL bSuccess = FALSE; ReadHardlinksData* lpData = (ReadHardlinksData*)lpUserData; size_t szDataSize = sizeof(ReadFileNamePartsData) * lpFileRecordHeader->LinkCount; lpData->LinkCount = lpFileRecordHeader->LinkCount; if(lpData->LinkData = (ReadFileNamePartsData*)malloc(szDataSize)) { lpData->CurrentLink = 0; memset((void*)lpData->LinkData, 0, szDataSize); if(!(bSuccess = EnumRecordAttributes(lpFileRecordHeader, ReadHardlinksEnumAttributes, lpUserData))) { //free((void*)lpData->LinkData); //lpData->LinkData = NULL; } } return bSuccess; } VOID ReadHardLinks(IN HANDLE hVolume, IN LARGE_INTEGER FileRef) { BOOL bSuccess; ReadHardlinksData rhlData = { hVolume }; if(ProcessFileRecord(hVolume, FileRef, ReadHardlinksProcessFileRecord, (LPVOID)&rhlData)) { USHORT i = 0; for(; i < rhlData.LinkCount; i++) { FILENAME_PART* lpCurrent = rhlData.LinkData[i].Tail; while(lpCurrent->Prev) { FILENAME_PART* lpLast = lpCurrent; wprintf(L"%s\\", lpCurrent->Data); lpCurrent = lpCurrent->Prev; free((void*)lpLast->Data); free((void*)lpLast); if(!lpCurrent->Prev) { wprintf(L"%s\n", lpCurrent->Data); } } free((void*)lpCurrent->Data); free((void*)lpCurrent); } free(rhlData.LinkData); } else { wprintf(L"ReadHardLinks failed!\n"); } } VOID ReadHardLinkParts(IN HANDLE hVolume, IN LARGE_INTEGER FileRef) { DWORD dwRead, dwBufferSize = FILE_RECORD_OUTPUT_BUFFER_SIZE; C_ASSERT(sizeof(FileRef) == sizeof(NTFS_FILE_RECORD_INPUT_BUFFER)); NTFS_FILE_RECORD_OUTPUT_BUFFER* nrb = (NTFS_FILE_RECORD_OUTPUT_BUFFER*)malloc(dwBufferSize); if(DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD, &FileRef, sizeof(FileRef), nrb, dwBufferSize, &dwRead, NULL)) { // FSCTL_GET_NTFS_FILE_RECORD retrieves one MFT entry // FILE_RECORD_HEADER is the Base struct for the MFT entry // that we will work from PFILE_RECORD_HEADER lpFileRecordHeader = (PFILE_RECORD_HEADER)nrb->FileRecordBuffer; if(lpFileRecordHeader->Ntfs.Type == 'ELIF') { PATTRIBUTE lpAttr = (PATTRIBUTE)((LPBYTE)lpFileRecordHeader + lpFileRecordHeader->AttributesOffset); while(lpAttr && lpAttr->AttributeType <= AttributeLoggedUtilityStream) { // Only process $FILE_NAME attributes if(lpAttr->AttributeType == AttributeFileName) { PRESIDENT_ATTRIBUTE lpResident = (PRESIDENT_ATTRIBUTE)lpAttr; PFILENAME_ATTRIBUTE lpFileName = (PFILENAME_ATTRIBUTE)Add2Ptr(lpAttr, lpResident->ValueOffset); if(lpFileName->NameType & WIN32_NAME || lpFileName->NameType == 0) { // Reached the root if(lpFileName->DirectoryFileReferenceNumber == 0x5) { wprintf(L"Hit Root\n"); } lpFileName->Name[lpFileName->NameLength] = L'\0'; wprintf(L"FileName :%s\n", lpFileName->Name) ; } } if(lpAttr->Nonresident) { lpAttr = (PATTRIBUTE)Add2Ptr(lpAttr, sizeof(NONRESIDENT_ATTRIBUTE)); } else if(lpAttr->Length && lpAttr->Length < lpFileRecordHeader->BytesInUse) { lpAttr = (PATTRIBUTE)Add2Ptr(lpAttr, lpAttr->Length); } else { lpAttr = NULL; } } } } free(nrb); } // Open the volume HANDLE OpenVolume(WCHAR wcVolume) { static HANDLE hVolume = NULL; static WCHAR lpsVolumeRoot[] = L"\\\\.\\A:"; // Uppercase volume letters. if(iswlower((wint_t)wcVolume)) { wcVolume = towupper((wint_t)wcVolume); } if(VALID_HANDLE(hVolume)) { if(wcVolume == lpsVolumeRoot[4]) return hVolume; CloseHandle(hVolume); } lpsVolumeRoot[4] = wcVolume; hVolume = CreateFileW(lpsVolumeRoot, GENERIC_READ, FILE_SHARE_READWRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); return VALID_HANDLE(hVolume) ? hVolume : NULL; } HANDLE OpenVolumeOfFilePath(IN LPCWSTR lpsFilePath, OUT WCHAR* lpwcVolume) { HANDLE hVolume = NULL; WCHAR lpVolumePath[MAX_PATH + 1] = W_EMPTY; *lpwcVolume = L'\0'; if(GetVolumePathName(lpsFilePath, lpVolumePath, WLEN(lpVolumePath))) { hVolume = OpenVolume(*lpwcVolume = *lpVolumePath); } return hVolume; } int __cdecl _tmain(int argc, TCHAR* argv[]) { WCHAR wcVolume; LPCWSTR lpFileName; HANDLE hFile, hVolume; LARGE_INTEGER FileRef; BY_HANDLE_FILE_INFORMATION fiItem; DWORD dwFileAttrs, dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; // Check command-line arguments. if(argc == 1) { _tprintf(_T("Usage: %s <filepath>\n"), argv[0]); return 0; } // Determine the flags we'll use for opening our filepath (based on whether or not lpFileName // contains a folder path) lpFileName = (LPCWSTR)argv[1]; dwFileAttrs = GetFileAttributesW(lpFileName); if(HAS_FLAG(dwFileAttrs, INVALID_FILE_ATTRIBUTES)) { FatalError(ERROR_PATH_NOT_FOUND, _T("%s does not exist."), lpFileName); } else if(HAS_FLAG(dwFileAttrs, FILE_ATTRIBUTE_DIRECTORY)) { dwFlagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS; } hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READWRITE, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); CheckStatement(VALID_HANDLE(hFile)); GetFileInformationByHandle(hFile, &fiItem); CloseHandle(hFile); if(!(hVolume = OpenVolumeOfFilePath(lpFileName, &wcVolume))) { FatalApi(CreateFile); } FileRef.LowPart = fiItem.nFileIndexLow; FileRef.HighPart = fiItem.nFileIndexHigh; ReadHardLinks(hVolume, FileRef); CloseHandle(hVolume); return 0; }

####
public
by canering
*841*
*2*
*3*
*0*

### This is my technical interview cheat sheet. Feel free to fork it or do whatever you want with it. PLEASE let me know if there are any errors or if anything crucial is missing. I will add more links soon.

This is my technical interview cheat sheet. Feel free to fork it or do whatever you want with it. PLEASE let me know if there are any errors or if anything crucial is missing. I will add more links soon.:
The Technical Interview Cheat Sheet.md

## Studying for a Tech Interview Sucks, so Here's a Cheat Sheet to Help This list is meant to be a both a quick guide and reference for further research into these topics. It's basically a summary of that comp sci course you never took or forgot about, so there's no way it can cover everything in depth. It also will be available as a [gist](https://gist.github.com/TSiege/cbb0507082bb18ff7e4b) on Github for everyone to edit and add to. ## Data Structure Basics ###**Array** ####Definition: - Stores data elements based on an sequential, most commonly 0 based, index. - Based on [tuples](http://en.wikipedia.org/wiki/Tuple) from set theory. - They are one of the oldest, most commonly used data structures. ####What you need to know: - Optimal for indexing; bad at searching, inserting, and deleting (except at the end). - **Linear arrays**, or one dimensional arrays, are the most basic. - Are static in size, meaning that they are declared with a fixed size. - **Dynamic arrays** are like one dimensional arrays, but have reserved space for additional elements. - If a dynamic array is full, it copies it's contents to a larger array. - **Two dimensional arrays** have x and y indices like a grid or nested arrays. ####Big O efficiency: - Indexing: Linear array: O(1), Dynamic array: O(1) - Search: Linear array: O(n), Dynamic array: O(n) - Optimized Search: Linear array: O(log n), Dynamic array: O(log n) - Insertion: Linear array: n/a Dynamic array: O(n) ###**Linked List** ####Definition: - Stores data with **nodes** that point to other nodes. - Nodes, at its most basic it has one datum and one reference (another node). - A linked list _chains_ nodes together by pointing one node's reference towards another node. ####What you need to know: - Designed to optimize insertion and deletion, slow at indexing and searching. - **Doubly linked list** has nodes that reference the previous node. - **Circularly linked list** is simple linked list whose **tail**, the last node, references the **head**, the first node. - **Stack**, commonly implemented with linked lists but can be made from arrays too. - Stacks are **last in, first out** (LIFO) data structures. - Made with a linked list by having the head be the only place for insertion and removal. - **Queues**, too can be implemented with a linked list or an array. - Queues are a **first in, first out** (FIFO) data structure. - Made with a doubly linked list that only removes from head and adds to tail. ####Big O efficiency: - Indexing: Linked Lists: O(n) - Search: Linked Lists: O(n) - Optimized Search: Linked Lists: O(n) - Insertion: Linked Lists: O(1) ###**Hash Table or Hash Map** ####Definition: - Stores data with key value pairs. - **Hash functions** accept a key and return an output unique only to that specific key. - This is known as **hashing**, which is the concept that an input and an output have a one-to-one correspondence to map information. - Hash functions return a unique address in memory for that data. ####What you need to know: - Designed to optimize searching, insertion, and deletion. - **Hash collisions** are when a hash function returns the same output for two distinct inputs. - All hash functions have this problem. - This is often accommodated for by having the hash tables be very large. - Hashes are important for associative arrays and database indexing. ####Big O efficiency: - Indexing: Hash Tables: O(1) - Search: Hash Tables: O(1) - Insertion: Hash Tables: O(1) ###**Binary Tree** ####Definition: - Is a tree like data structure where every node has at most two children. - There is one left and right child node. ####What you need to know: - Designed to optimize searching and sorting. - A **degenerate tree** is an unbalanced tree, which if entirely one-sided is a essentially a linked list. - They are comparably simple to implement than other data structures. - Used to make **binary search trees**. - A binary tree that uses comparable keys to assign which direction a child is. - Left child has a key smaller than it's parent node. - Right child has a key greater than it's parent node. - There can be no duplicate node. - Because of the above it is more likely to be used as a data structure than a binary tree. ####Big O efficiency: - Indexing: Binary Search Tree: O(log n) - Search: Binary Search Tree: O(log n) - Insertion: Binary Search Tree: O(log n) ## Search Basics ###**Breadth First Search** ####Definition: - An algorithm that searches a tree (or graph) by searching levels of the tree first, starting at the root. - It finds every node on the same level, most often moving left to right. - While doing this it tracks the children nodes of the nodes on the current level. - When finished examining a level it moves to the left most node on the next level. - The bottom-right most node is evaluated last (the node that is deepest and is farthest right of it's level). ####What you need to know: - Optimal for searching a tree that is wider than it is deep. - Uses a queue to store information about the tree while it traverses a tree. - Because it uses a queue it is more memory intensive than **depth first search**. - The queue uses more memory because it needs to stores pointers ####Big O efficiency: - Search: Breadth First Search: O(|E| + |V|) - E is number of edges - V is number of vertices ###**Depth First Search** ####Definition: - An algorithm that searches a tree (or graph) by searching depth of the tree first, starting at the root. - It traverses left down a tree until it cannot go further. - Once it reaches the end of a branch it traverses back up trying the right child of nodes on that branch, and if possible left from the right children. - When finished examining a branch it moves to the node right of the root then tries to go left on all it's children until it reaches the bottom. - The right most node is evaluated last (the node that is right of all it's ancestors). ####What you need to know: - Optimal for searching a tree that is deeper than it is wide. - Uses a stack to push nodes onto. - Because a stack is LIFO it does not need to keep track of the nodes pointers and is therefore less memory intensive than breadth first search. - Once it cannot go further left it begins evaluating the stack. ####Big O efficiency: - Search: Depth First Search: O(|E| + |V|) - E is number of edges - V is number of vertices ####Breadth First Search Vs. Depth First Search - The simple answer to this question is that it depends on the size and shape of the tree. - For wide, shallow trees use Breadth First Search - For deep, narrow trees use Depth First Search ####Nuances: - Because BFS uses queues to store information about the nodes and its children, it could use more memory than is available on your computer. (But you probably won't have to worry about this.) - If using a DFS on a tree that is very deep you might go unnecessarily deep in the search. See [xkcd](http://xkcd.com/761/) for more information. - Breadth First Search tends to be a looping algorithm. - Depth First Search tends to be a recursive algorithm. ## Efficient Sorting Basics ###**Merge Sort** ####Definition: - A comparison based sorting algorithm - Divides entire dataset into groups of at most two. - Compares each number one at a time, moving the smallest number to left of the pair. - Once all pairs sorted it then compares left most elements of the two leftmost pairs creating a sorted group of four with the smallest numbers on the left and the largest ones on the right. - This process is repeated until there is only one set. ####What you need to know: - This is one of the most basic sorting algorithms. - Know that it divides all the data into as small possible sets then compares them. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n log n) - Worst Case Sort: Merge Sort: O(n log n) ###**Quicksort** ####Definition: - A comparison based sorting algorithm - Divides entire dataset in half by selecting the average element and putting all smaller elements to the left of the average. - It repeats this process on the left side until it is comparing only two elements at which point the left side is sorted. - When the left side is finished sorting it performs the same operation on the right side. - Computer architecture favors the quicksort process. ####What you need to know: - While it has the same Big O as (or worse in some cases) many other sorting algorithms it is often faster in practice than many other sorting algorithms, such as merge sort. - Know that it halves the data set by the average continuously until all the information is sorted. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n log n) - Worst Case Sort: Merge Sort: O(n^2) ###**Bubble Sort** ####Definition: - A comparison based sorting algorithm - It iterates left to right comparing every couplet, moving the smaller element to the left. - It repeats this process until it no longer moves and element to the left. ####What you need to know: - While it is very simple to implement, it is the least efficient of these three sorting methods. - Know that it moves one space to the right comparing two elements at a time and moving the smaller on to left. ####Big O efficiency: - Best Case Sort: Merge Sort: O(n) - Average Case Sort: Merge Sort: O(n^2) - Worst Case Sort: Merge Sort: O(n^2) ####Merge Sort Vs. Quicksort - Quicksort is likely faster in practice. - Merge Sort divides the set into the smallest possible groups immediately then reconstructs the incrementally as it sorts the groupings. - Quicksort continually divides the set by the average, until the set is recursively sorted. ## Basic Types of Algorithms ###**Recursive Algorithms** ####Definition: - An algorithm that calls itself in its definition. - **Recursive case** a conditional statement that is used to trigger the recursion. - **Base case** a conditional statement that is used to break the recursion. ####What you need to know: - **Stack level too deep** and **stack overflow**. - If you've seen either of these from a recursive algorithm, you messed up. - It means that your base case was never triggered because it was faulty or the problem was so massive you ran out of RAM before reaching it. - Knowing whether or not you will reach a base case is integral to correctly using recursion. - Often used in Depth First Search ###**Iterative Algorithms** ####Definition: - An algorithm that is called repeatedly but for a finite number of times, each time being a single iteration. - Often used to move incrementally through a data set. ####What you need to know: - Generally you will see iteration as loops, for, while, and until statements. - Think of iteration as moving one at a time through a set. - Often used to move through an array. ####Recursion Vs. Iteration - The differences between recursion and iteration can be confusing to distinguish since both can be used to implement the other. But know that, - Recursion is, usually, more expressive and easier to implement. - Iteration uses less memory. - **Functional languages** tend to use recursion. (i.e. Haskell) - **Imperative languages** tend to use iteration. (i.e. Ruby) - Check out this [Stack Overflow post](http://stackoverflow.com/questions/19794739/what-is-the-difference-between-iteration-and-recursion) for more info. ####Pseudo Code of Moving Through an Array (this is why iteration is used for this) ``` Recursion | Iteration ----------------------------------|---------------------------------- recursive method (array, n) | iterative method (array) if array[n] is not nil | for n from 0 to size of array print array[n] | print(array[n]) recursive method(array, n+1) | else | exit loop | ``` ###**Greedy Algorithm** ####Definition: - An algorithm that, while executing, selects only the information that meets a certain criteria. - The general five components, taken from [Wikipedia](http://en.wikipedia.org/wiki/Greedy_algorithm#Specifics): - A candidate set, from which a solution is created. - A selection function, which chooses the best candidate to be added to the solution. - A feasibility function, that is used to determine if a candidate can be used to contribute to a solution. - An objective function, which assigns a value to a solution, or a partial solution. - A solution function, which will indicate when we have discovered a complete solution. ####What you need to know: - Used to find the optimal solution for a given problem. - Generally used on sets of data where only a small proportion of the information evaluated meets the desired result. - Often a greedy algorithm can help reduce the Big O of an algorithm. ####Pseudo Code of a Greedy Algorithm to Find Largest Difference of any Two Numbers in an Array. ``` greedy algorithm (array) var largest difference = 0 var new difference = find next difference (array[n], array[n+1]) largest difference = new difference if new difference is > largest difference repeat above two steps until all differences have been found return largest difference ``` This algorithm never needed to compare all the differences to one another, saving it an entire iteration.